context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, 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. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using Encog.ML.Data; using Encog.ML.Data.Basic; using Encog.ML.SVM; using Encog.ML.SVM.Training; using Encog.ML.Train; using Encog.ML.Train.Strategy; using Encog.Neural.Networks.Training; using Encog.Neural.Networks.Training.Anneal; using Encog.Neural.Networks.Training.Propagation.Back; using Encog.Util; using Encog.Util.Arrayutil; namespace Encog.Examples.SVM_Predict { class SVMPredictSunSpots { public class PredictSunspotSVM { #region sunspot array public static double[] SUNSPOTS = { 0.0262, 0.0575, 0.0837, 0.1203, 0.1883, 0.3033, 0.1517, 0.1046, 0.0523, 0.0418, 0.0157, 0.0000, 0.0000, 0.0105, 0.0575, 0.1412, 0.2458, 0.3295, 0.3138, 0.2040, 0.1464, 0.1360, 0.1151, 0.0575, 0.1098, 0.2092, 0.4079, 0.6381, 0.5387, 0.3818, 0.2458, 0.1831, 0.0575, 0.0262, 0.0837, 0.1778, 0.3661, 0.4236, 0.5805, 0.5282, 0.3818, 0.2092, 0.1046, 0.0837, 0.0262, 0.0575, 0.1151, 0.2092, 0.3138, 0.4231, 0.4362, 0.2495, 0.2500, 0.1606, 0.0638, 0.0502, 0.0534, 0.1700, 0.2489, 0.2824, 0.3290, 0.4493, 0.3201, 0.2359, 0.1904, 0.1093, 0.0596, 0.1977, 0.3651, 0.5549, 0.5272, 0.4268, 0.3478, 0.1820, 0.1600, 0.0366, 0.1036, 0.4838, 0.8075, 0.6585, 0.4435, 0.3562, 0.2014, 0.1192, 0.0534, 0.1260, 0.4336, 0.6904, 0.6846, 0.6177, 0.4702, 0.3483, 0.3138, 0.2453, 0.2144, 0.1114, 0.0837, 0.0335, 0.0214, 0.0356, 0.0758, 0.1778, 0.2354, 0.2254, 0.2484, 0.2207, 0.1470, 0.0528, 0.0424, 0.0131, 0.0000, 0.0073, 0.0262, 0.0638, 0.0727, 0.1851, 0.2395, 0.2150, 0.1574, 0.1250, 0.0816, 0.0345, 0.0209, 0.0094, 0.0445, 0.0868, 0.1898, 0.2594, 0.3358, 0.3504, 0.3708, 0.2500, 0.1438, 0.0445, 0.0690, 0.2976, 0.6354, 0.7233, 0.5397, 0.4482, 0.3379, 0.1919, 0.1266, 0.0560, 0.0785, 0.2097, 0.3216, 0.5152, 0.6522, 0.5036, 0.3483, 0.3373, 0.2829, 0.2040, 0.1077, 0.0350, 0.0225, 0.1187, 0.2866, 0.4906, 0.5010, 0.4038, 0.3091, 0.2301, 0.2458, 0.1595, 0.0853, 0.0382, 0.1966, 0.3870, 0.7270, 0.5816, 0.5314, 0.3462, 0.2338, 0.0889, 0.0591, 0.0649, 0.0178, 0.0314, 0.1689, 0.2840, 0.3122, 0.3332, 0.3321, 0.2730, 0.1328, 0.0685, 0.0356, 0.0330, 0.0371, 0.1862, 0.3818, 0.4451, 0.4079, 0.3347, 0.2186, 0.1370, 0.1396, 0.0633, 0.0497, 0.0141, 0.0262, 0.1276, 0.2197, 0.3321, 0.2814, 0.3243, 0.2537, 0.2296, 0.0973, 0.0298, 0.0188, 0.0073, 0.0502, 0.2479, 0.2986, 0.5434, 0.4215, 0.3326, 0.1966, 0.1365, 0.0743, 0.0303, 0.0873, 0.2317, 0.3342, 0.3609, 0.4069, 0.3394, 0.1867, 0.1109, 0.0581, 0.0298, 0.0455, 0.1888, 0.4168, 0.5983, 0.5732, 0.4644, 0.3546, 0.2484, 0.1600, 0.0853, 0.0502, 0.1736, 0.4843, 0.7929, 0.7128, 0.7045, 0.4388, 0.3630, 0.1647, 0.0727, 0.0230, 0.1987, 0.7411, 0.9947, 0.9665, 0.8316, 0.5873, 0.2819, 0.1961, 0.1459, 0.0534, 0.0790, 0.2458, 0.4906, 0.5539, 0.5518, 0.5465, 0.3483, 0.3603, 0.1987, 0.1804, 0.0811, 0.0659, 0.1428, 0.4838, 0.8127 }; #endregion public static int STARTING_YEAR = 1700; public static int WINDOW_SIZE = 30; public static int TRAIN_START = WINDOW_SIZE; public static int TRAIN_END = 259; public static int EVALUATE_START = 260; public static int EVALUATE_END; /** * This really should be lowered, I am setting it to a level here that will * train in under a minute. */ public static double MAX_ERROR = 0.01; private static double[] normalizedSunspots; private static double[] closedLoopSunspots; public static void normalizeSunspots(double lo, double hi) { NormalizeArray norm = new NormalizeArray(); norm.NormalizedHigh=( hi); norm.NormalizedLow = lo; // create arrays to hold the normalized sunspots normalizedSunspots = norm.Process(SUNSPOTS); closedLoopSunspots = EngineArray.ArrayCopy(normalizedSunspots); } private static SupportVectorMachine networkx = new SupportVectorMachine(); public static IMLDataSet generateTraining() { TemporalWindowArray temp = new TemporalWindowArray(WINDOW_SIZE, 1); temp.Analyze(normalizedSunspots); return temp.Process(normalizedSunspots); } public static SupportVectorMachine createNetwork() { SupportVectorMachine network = new SupportVectorMachine(WINDOW_SIZE,true); return network; } public static void train(SupportVectorMachine network,IMLDataSet training) { SVMTrain train = new SVMTrain(network, training); train.Iteration(); } public static SupportVectorMachine SVMSearch(SupportVectorMachine anetwork, IMLDataSet training) { SVMSearchTrain bestsearch = new SVMSearchTrain(anetwork, training); StopTrainingStrategy stop = new StopTrainingStrategy(0.00000000001, 1); bestsearch.AddStrategy(stop); while (bestsearch.IterationNumber < 30 && !stop.ShouldStop()) { bestsearch.Iteration(); Console.WriteLine("Iteration #" + bestsearch.IterationNumber + " Error :" + bestsearch.Error); } bestsearch.FinishTraining(); return anetwork; } public static void predict(SupportVectorMachine network) { Console.WriteLine(@"Year \t Actual\t Predict\t Closed Loops"); for(int year=EVALUATE_START;year<EVALUATE_END;year++) { // calculate based on actual data var input = new BasicMLData(WINDOW_SIZE); for(int i=0;i<input.Count;i++) { input[i] = normalizedSunspots[(year - WINDOW_SIZE) + i]; //input.setData(i,this.normalizedSunspots[(year-WINDOW_SIZE)+i]); } IMLData output = network.Compute(input); double prediction = output[0]; closedLoopSunspots[year] = prediction; // calculate "closed loop", based on predicted data for (int i = 0; i < input.Count; i++) { input[i] = closedLoopSunspots[(year - WINDOW_SIZE) + i]; //input.setData(i,this.closedLoopSunspots[(year-WINDOW_SIZE)+i]); } output = network.Compute(input); double closedLoopPrediction = output[0]; // display //System.out.println((STARTING_YEAR+year) // +"\t"+f.format(this.normalizedSunspots[year]) // +"\t"+f.format(prediction) // +"\t"+f.format(closedLoopPrediction) Console.WriteLine(((STARTING_YEAR + year) + @"\t " + Format.FormatDouble(SUNSPOTS[year], 4) + @"\t " + Format.FormatDouble(normalizedSunspots[year], 4) + @"\t " + Format.FormatDouble(prediction, 4) + @"\t " + Format.FormatDouble(closedLoopPrediction, 4) )); } } public static void predict(SupportVectorMachine network, SupportVectorMachine network2) { Console.WriteLine(@"Year\tActual\tPredict\tClosed Loops"); for (int year = EVALUATE_START; year < EVALUATE_END; year++) { // calculate based on actual data var input = new BasicMLData(WINDOW_SIZE); for (int i = 0; i < input.Count; i++) { input[i] = normalizedSunspots[(year - WINDOW_SIZE) + i]; //input.setData(i,this.normalizedSunspots[(year-WINDOW_SIZE)+i]); } IMLData output = network.Compute(input); IMLData output2 = network2.Compute(input); double prediction = output[0]; double prediction2 = output2[0]; closedLoopSunspots[year] = prediction; // calculate "closed loop", based on predicted data for (int i = 0; i < input.Count; i++) { input[i] = closedLoopSunspots[(year - WINDOW_SIZE) + i]; //input.setData(i,this.closedLoopSunspots[(year-WINDOW_SIZE)+i]); } output = network.Compute(input); double closedLoopPrediction = output[0]; IMLData output3 = network2.Compute(input); double closedLoopPrediction2 = output[0]; // display //System.out.println((STARTING_YEAR+year) // +"\t"+f.format(this.normalizedSunspots[year]) // +"\t"+f.format(prediction) // +"\t"+f.format(closedLoopPrediction) Console.WriteLine(((STARTING_YEAR + year) + @"\t " + Format.FormatDouble(SUNSPOTS[year], 4) + @"\t " + Format.FormatDouble(normalizedSunspots[year], 4) + @"\t " + Format.FormatDouble(prediction, 4) + @"\t " + Format.FormatDouble(prediction2, 4) + @"\t " + Format.FormatDouble(closedLoopPrediction, 4) + @"\t " + Format.FormatDouble(closedLoopPrediction2, 4) )); } } public static void run() { normalizeSunspots(0.1,0.9); EVALUATE_END = SUNSPOTS.Length - 1; SupportVectorMachine network = createNetwork(); IMLDataSet training = generateTraining(); SupportVectorMachine trained = SVMSearch(network, training); train(trained,training); predict(trained); } #region Direction enum public enum Direction { Up, Down } ; public static Direction DetermineDirection(double d) { return d < 0 ? Direction.Down : Direction.Up; } #endregion } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Dfm { using System; using System.Collections.Immutable; using System.IO; using System.Linq; using Microsoft.DocAsCode.Common; using Microsoft.DocAsCode.MarkdownLite; public class DfmRenderer : HtmlRenderer, IDisposable { private readonly DfmInclusionLoader _inlineInclusionHelper = new DfmInlineInclusionLoader(true); private readonly DfmInclusionLoader _blockInclusionHelper = new DfmInclusionLoader(); private readonly DfmCodeRenderer _codeRenderer = new DfmCodeRenderer(); public ImmutableDictionary<string, string> Tokens { get; set; } public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmXrefInlineToken token, MarkdownInlineContext context) { StringBuffer result = "<xref"; result = AppendAttribute(result, "href", token.Href); result = AppendAttribute(result, "title", token.Title); result = AppendAttribute(result, "data-throw-if-not-resolved", token.ThrowIfNotResolved.ToString()); result = AppendAttribute(result, "data-raw-source", token.SourceInfo.Markdown); result = AppendSourceInfo(result, renderer, token); result += ">"; foreach (var item in token.Content) { result += renderer.Render(item); } result += "</xref>"; return result; } public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmIncludeBlockToken token, MarkdownBlockContext context) { lock (_blockInclusionHelper) { return _blockInclusionHelper.Load(renderer, token.Src, token.SourceInfo, context, (DfmEngine)renderer.Engine); } } public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmIncludeInlineToken token, MarkdownInlineContext context) { lock (_inlineInclusionHelper) { return _inlineInclusionHelper.Load(renderer, token.Src, token.SourceInfo, context, (DfmEngine)renderer.Engine); } } public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmYamlHeaderBlockToken token, MarkdownBlockContext context) { if (string.IsNullOrEmpty(token.Content)) { return StringBuffer.Empty; } var startLine = token.SourceInfo.LineNumber; var endLine = token.SourceInfo.LineNumber + token.SourceInfo.ValidLineCount - 1; var sourceFile = token.SourceInfo.File; StringBuffer result = $"<yamlheader start=\"{startLine}\" end=\"{endLine}\""; if (!string.IsNullOrEmpty(sourceFile)) { sourceFile = StringHelper.HtmlEncode(sourceFile); result += $" sourceFile=\"{sourceFile}\""; } result += ">"; result += StringHelper.HtmlEncode(token.Content); return result + "</yamlheader>"; } public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmSectionBlockSplitToken splitToken, MarkdownBlockContext context) { StringBuffer content = string.Empty; if (!splitToken.Token.SourceInfo.Markdown.EndsWith("\n")) { Logger.LogWarning("The content part of [!div] syntax is suggested to start in a new line.", file: splitToken.Token.SourceInfo.File, line: splitToken.Token.SourceInfo.LineNumber.ToString()); } content += "<div"; content += ((DfmSectionBlockToken)splitToken.Token).Attributes; content = AppendSourceInfo(content, renderer, splitToken.Token); content += ">"; foreach (var item in splitToken.InnerTokens) { content += renderer.Render(item); } content += "</div>\n"; return content; } public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmNoteBlockSplitToken splitToken, IMarkdownContext context) { StringBuffer content = string.Empty; if (!splitToken.Token.SourceInfo.Markdown.EndsWith("\n")) { Logger.LogWarning("The content part of NOTE/WARNING/CAUTION/IMPORTANT/NEXT syntax is suggested to start in a new line.", file: splitToken.Token.SourceInfo.File, line: splitToken.Token.SourceInfo.LineNumber.ToString()); } var noteToken = (DfmNoteBlockToken)splitToken.Token; content += "<div class=\""; content += noteToken.NoteType.ToUpper(); content += "\""; content = AppendSourceInfo(content, renderer, splitToken.Token); content += ">"; if (Tokens != null && Tokens.TryGetValue(noteToken.NoteType.ToLower(), out string heading)) { content += heading; } else { content += "<h5>"; content += noteToken.NoteType.ToUpper(); content += "</h5>"; } foreach (var item in splitToken.InnerTokens) { content += renderer.Render(item); } content += "</div>\n"; return content; } public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmVideoBlockSplitToken splitToken, IMarkdownContext context) { StringBuffer content = string.Empty; var videoToken = splitToken.Token as DfmVideoBlockToken; content += "<div class=\"embeddedvideo\"><iframe src=\""; content += videoToken.Link; content += "\" frameborder=\"0\" allowfullscreen=\"true\""; content = AppendSourceInfo(content, renderer, splitToken.Token); content += "></iframe></div>\n"; return content; } public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmDefaultBlockQuoteBlockSplitToken splitToken, IMarkdownContext context) { StringBuffer content = string.Empty; content += "<blockquote"; content = AppendSourceInfo(content, renderer, splitToken.Token); content += ">"; foreach (var item in splitToken.InnerTokens) { content += renderer.Render(item); } content += "</blockquote>\n"; return content; } public override StringBuffer Render(IMarkdownRenderer renderer, MarkdownBlockquoteBlockToken token, MarkdownBlockContext context) { StringBuffer content = string.Empty; var splitTokens = DfmBlockquoteHelper.SplitBlockquoteTokens(token.Tokens); foreach (var splitToken in splitTokens) { content += renderer.Render(splitToken); } return content; } public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmFencesToken token, IMarkdownContext context) { return _codeRenderer.Render(renderer, token, context); } [Obsolete] public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmFencesBlockToken token, MarkdownBlockContext context) { return Render(renderer, token, (IMarkdownContext)context); } public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmNoteBlockToken token, MarkdownBlockContext context) { return token.Content; } public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmVideoBlockToken token, MarkdownBlockContext context) { return token.SourceInfo.Markdown; } public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmTabGroupBlockToken token, MarkdownBlockContext context) { StringBuffer sb = @"<div class=""tabGroup"" id=""tabgroup_"; var groupId = StringHelper.Escape(token.Id); sb += groupId; sb += "\""; sb = AppendSourceInfo(sb, renderer, token); sb += ">\n"; sb = RenderTabHeaders(renderer, token, sb, groupId); sb = RenderSections(renderer, token, sb, groupId); sb += "</div>\n"; return sb; } private static StringBuffer RenderTabHeaders(IMarkdownRenderer renderer, DfmTabGroupBlockToken token, StringBuffer sb, string groupId) { sb += "<ul role=\"tablist\">\n"; for (int i = 0; i < token.Items.Length; i++) { var item = token.Items[i]; sb += "<li role=\"presentation\""; if (!item.Visible) { sb += " aria-hidden=\"true\" hidden=\"hidden\""; } sb += ">\n"; sb += @"<a href=""#tabpanel_"; sb = AppendGroupId(sb, groupId, item); sb += @""" role=""tab"" aria-controls=""tabpanel_"; sb = AppendGroupId(sb, groupId, item); sb += @""" data-tab="""; sb += item.Id; if (!string.IsNullOrEmpty(item.Condition)) { sb += @""" data-condition="""; sb += item.Condition; } if (i == token.ActiveTabIndex) { sb += "\" tabindex=\"0\" aria-selected=\"true\""; } else { sb += "\" tabindex=\"-1\""; } sb = AppendSourceInfo(sb, renderer, item.Title); sb += ">"; sb += renderer.Render(item.Title); sb += "</a>\n"; sb += "</li>\n"; } sb += "</ul>\n"; return sb; } private static StringBuffer RenderSections(IMarkdownRenderer renderer, DfmTabGroupBlockToken token, StringBuffer sb, string groupId) { for (int i = 0; i < token.Items.Length; i++) { var item = token.Items[i]; sb += @"<section id=""tabpanel_"; sb = AppendGroupId(sb, groupId, item); sb += @""" role=""tabpanel"" data-tab="""; sb += item.Id; if (!string.IsNullOrEmpty(item.Condition)) { sb += @""" data-condition="""; sb += item.Condition; } if (i == token.ActiveTabIndex) { sb += "\">\n"; } else { sb += "\" aria-hidden=\"true\" hidden=\"hidden\">\n"; } sb += renderer.Render(item.Content); sb += "</section>\n"; } return sb; } private static StringBuffer AppendGroupId(StringBuffer sb, string groupId, DfmTabItemBlockToken item) { sb += groupId; sb += "_"; sb += item.Id; if (!string.IsNullOrEmpty(item.Condition)) { sb += "_"; sb += item.Condition; } return sb; } public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmTabTitleBlockToken token, IMarkdownContext context) { var sb = StringBuffer.Empty; foreach (var item in token.Content.Tokens) { sb += renderer.Render(item); } return sb; } public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmTabContentBlockToken token, IMarkdownContext context) { var sb = StringBuffer.Empty; foreach (var item in token.Content) { sb += renderer.Render(item); } return sb; } public void Dispose() { _inlineInclusionHelper.Dispose(); _blockInclusionHelper.Dispose(); } } }
// <copyright file=Triangle.cs // <copyright> // Copyright (c) 2016, University of Stuttgart // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Software), // to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // </copyright> // <license>MIT License</license> // <main contributors> // Markus Funk, Thomas Kosch, Sven Mayer // </main contributors> // <co-contributors> // Paul Brombosch, Mai El-Komy, Juana Heusler, // Matthias Hoppe, Robert Konrad, Alexander Martin // </co-contributors> // <patent information> // We are aware that this software implements patterns and ideas, // which might be protected by patents in your country. // Example patents in Germany are: // Patent reference number: DE 103 20 557.8 // Patent reference number: DE 10 2013 220 107.9 // Please make sure when using this software not to violate any existing patents in your country. // </patent information> // <date> 11/2/2016 12:25:58 PM</date> using HciLab.Utilities.Mathematics.Core; using System; using System.ComponentModel; using System.Runtime.Serialization; using System.Text.RegularExpressions; namespace HciLab.Utilities.Mathematics.Geometry3D { /// <summary> /// Represents a triangle in 3D space. /// </summary> [Serializable] [TypeConverter(typeof(TriangleConverter))] public struct Triangle : ICloneable, ISerializable { #region Private Fields private Vector3 _p0, _p1, _p2; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Triangle"/> class. /// </summary> /// <param name="p0">A <see cref="Vector3"/> instance.</param> /// <param name="p1">A <see cref="Vector3"/> instance.</param> /// <param name="p2">A <see cref="Vector3"/> instance.</param> public Triangle(Vector3 p0, Vector3 p1, Vector3 p2) { _p0 = p0; _p1 = p1; _p2 = p2; } /// <summary> /// Initializes a new instance of the <see cref="Triangle"/> class using a given Triangle. /// </summary> /// <param name="t">A <see cref="Triangle"/> instance.</param> public Triangle(Triangle t) { _p0 = t._p0; _p1 = t._p1; _p2 = t._p2; } /// <summary> /// Initializes a new instance of the <see cref="Triangle"/> class with serialized data. /// </summary> /// <param name="info">The object that holds the serialized object data.</param> /// <param name="context">The contextual information about the source or destination.</param> private Triangle(SerializationInfo info, StreamingContext context) { _p0 = (Vector3)info.GetValue("P0", typeof(Vector3)); _p1 = (Vector3)info.GetValue("P1", typeof(Vector3)); _p2 = (Vector3)info.GetValue("P2", typeof(Vector3)); } #endregion #region ICloneable Members /// <summary> /// Creates an exact copy of this <see cref="Triangle"/> object. /// </summary> /// <returns>The <see cref="Triangle"/> object this method creates, cast as an object.</returns> object ICloneable.Clone() { return new Triangle(this); } /// <summary> /// Creates an exact copy of this <see cref="Triangle"/> object. /// </summary> /// <returns>The <see cref="Triangle"/> object this method creates.</returns> public Triangle Clone() { return new Triangle(this); } #endregion #region ISerializable Members /// <summary> /// Populates a <see cref="SerializationInfo"/> with the data needed to serialize the target object. /// </summary> /// <param name="info">The <see cref="SerializationInfo"/> to populate with data. </param> /// <param name="context">The destination (see <see cref="StreamingContext"/>) for this serialization.</param> //[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter=true)] public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("P0", _p0, typeof(Vector3)); info.AddValue("P1", _p1, typeof(Vector3)); info.AddValue("P2", _p2, typeof(Vector3)); } #endregion #region Public Static Parse Methods /// <summary> /// Converts the specified string to its <see cref="Triangle"/> equivalent. /// </summary> /// <param name="s">A string representation of a <see cref="Triangle"/></param> /// <returns>A <see cref="Triangle"/> that represents the vector specified by the <paramref name="s"/> parameter.</returns> public static Triangle Parse(string s) { Regex r = new Regex(@"Triangle\((?<p1>\([^\)]*\)), (?<p2>\([^\)]*\)), (?<p3>\([^\)]*\))\)", RegexOptions.None); Match m = r.Match(s); if (m.Success) { return new Triangle( Vector3.Parse(m.Result("${p1}")), Vector3.Parse(m.Result("${p2}")), Vector3.Parse(m.Result("${p3}")) ); } else { throw new ParseException("Unsuccessful Match."); } } #endregion #region Overrides /// <summary> /// Get the hashcode for this vector instance. /// </summary> /// <returns>Returns the hash code for this vector instance.</returns> public override int GetHashCode() { return _p0.GetHashCode() ^ _p1.GetHashCode() ^ _p2.GetHashCode(); } /// <summary> /// Returns a value indicating whether this instance is equal to /// the specified object. /// </summary> /// <param name="obj">An object to compare to this instance.</param> /// <returns><see langword="true"/> if <paramref name="obj"/> is a <see cref="Vector3"/> and has the same values as this instance; otherwise, <see langword="false"/>.</returns> public override bool Equals(object obj) { if(obj is Triangle) { Triangle t = (Triangle)obj; return (_p0 == t.Point0) && (_p1 == t.Point1) && (_p2 == t.Point2); } return false; } /// <summary> /// Returns a string representation of this object. /// </summary> /// <returns>A string representation of this object.</returns> public override string ToString() { return string .Format("Triangle({0}, {1}, {2})", _p0, _p1, _p2); } #endregion #region Public Properties /// <summary> /// The first triangle vertex. /// </summary> /// <value>A <see cref="Vector3"/> instance.</value> public Vector3 Point0 { get { return _p0; } set { _p0 = value;} } /// <summary> /// The second triangle vertex. /// </summary> /// <value>A <see cref="Vector3"/> instance.</value> public Vector3 Point1 { get { return _p1; } set { _p1 = value;} } /// <summary> /// The third triangle vertex. /// </summary> /// <value>A <see cref="Vector3"/> instance.</value> public Vector3 Point2 { get { return _p2; } set { _p2 = value;} } /// <summary> /// Computes the normal for this triangle. /// </summary> /// <value>A <see cref="Vector3"/> instance.</value> public Vector3 Normal { get { Vector3 normal = Vector3.CrossProduct(_p1 - _p0, _p2 - _p0); normal.Normalize(); return normal; } } #endregion #region Comparison Operators /// <summary> /// Tests whether two specified triangles are equal. /// </summary> /// <param name="a">The left-hand triangle.</param> /// <param name="b">The right-hand triangle.</param> /// <returns><see langword="true"/> if the two triangles are equal; otherwise, <see langword="false"/>.</returns> public static bool operator==(Triangle a, Triangle b) { return ValueType.Equals(a,b); } /// <summary> /// Tests whether two specified triangles are not equal. /// </summary> /// <param name="a">The left-hand triangle.</param> /// <param name="b">The right-hand triangle.</param> /// <returns><see langword="true"/> if the two triangles are not equal; otherwise, <see langword="false"/>.</returns> public static bool operator!=(Triangle a, Triangle b) { return !ValueType.Equals(a,b); } #endregion #region Array Indexing Operator /// <summary> /// Indexer ( [P0, P1, P2] ). /// </summary> public Vector3 this[int index] { get { switch(index) { case 0 : return _p0; case 1 : return _p1; case 2 : return _p2; default: throw new IndexOutOfRangeException(); } } set { switch(index) { case 0 : _p0 = value; break; case 1 : _p1 = value; break; case 2 : _p2 = value; break; default: throw new IndexOutOfRangeException(); } } } #endregion /// <summary> /// Calculates a point in the triangle from its barycentric coordinates. /// </summary> /// <param name="u">A single-precision floating point coordinate value.</param> /// <param name="v">A single-precision floating point coordinate value.</param> /// <returns>Returns a point inside the trianlge.</returns> public Vector3 FromBarycentric(double u, double v) { return ((1-u-v)*_p0)+(u*_p1)+(v*_p2); } } #region TriangleConverter class /// <summary> /// Converts a <see cref="Triangle"/> to and from string representation. /// </summary> public class TriangleConverter : ExpandableObjectConverter { /// <summary> /// Returns whether this converter can convert an object of the given type to the type of this converter, using the specified context. /// </summary> /// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param> /// <param name="sourceType">A <see cref="Type"/> that represents the type you want to convert from.</param> /// <returns><b>true</b> if this converter can perform the conversion; otherwise, <b>false</b>.</returns> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) return true; return base.CanConvertFrom (context, sourceType); } /// <summary> /// Returns whether this converter can convert the object to the specified type, using the specified context. /// </summary> /// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param> /// <param name="destinationType">A <see cref="Type"/> that represents the type you want to convert to.</param> /// <returns><b>true</b> if this converter can perform the conversion; otherwise, <b>false</b>.</returns> public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(string)) return true; return base.CanConvertTo (context, destinationType); } /// <summary> /// Converts the given value object to the specified type, using the specified context and culture information. /// </summary> /// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param> /// <param name="culture">A <see cref="System.Globalization.CultureInfo"/> object. If a null reference (Nothing in Visual Basic) is passed, the current culture is assumed.</param> /// <param name="value">The <see cref="Object"/> to convert.</param> /// <param name="destinationType">The Type to convert the <paramref name="value"/> parameter to.</param> /// <returns>An <see cref="Object"/> that represents the converted value.</returns> public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if ((destinationType == typeof(string)) && (value is Triangle)) { Triangle r = (Triangle)value; return r.ToString(); } return base.ConvertTo (context, culture, value, destinationType); } /// <summary> /// Converts the given object to the type of this converter, using the specified context and culture information. /// </summary> /// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param> /// <param name="culture">The <see cref="System.Globalization.CultureInfo"/> to use as the current culture. </param> /// <param name="value">The <see cref="Object"/> to convert.</param> /// <returns>An <see cref="Object"/> that represents the converted value.</returns> /// <exception cref="ParseException">Failed parsing from string.</exception> public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { if (value.GetType() == typeof(string)) { return Triangle.Parse((string)value); } return base.ConvertFrom (context, culture, value); } } #endregion }
// 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.Diagnostics; using System.IO; using System.Linq; namespace Microsoft.NodejsTools.Npm.SPI { internal class NodeModules : AbstractNodeModules { private readonly Dictionary<string, ModuleInfo> _allModules; private static readonly string[] _ignoredDirectories = { @"\.bin", @"\.staging" }; public NodeModules(IRootPackage parent, bool showMissingDevOptionalSubPackages, Dictionary<string, ModuleInfo> allModulesToDepth = null, int depth = 0, int maxDepth = 1) { if (depth >= maxDepth) { return; } var modulesBase = Path.Combine(parent.Path, NodejsConstants.NodeModulesFolder); this._allModules = allModulesToDepth ?? new Dictionary<string, ModuleInfo>(); // This is the first time NodeModules is being created. // Iterate through directories to add everything that's known to be top-level. if (depth == 0) { Debug.Assert(this._allModules.Count == 0, "Depth is 0, but top-level modules have already been added."); // Go through every directory in node_modules, and see if it's required as a top-level dependency foreach (var topLevelDependency in GetTopLevelPackageDirectories(modulesBase)) { var moduleDir = topLevelDependency.Key; var packageJson = topLevelDependency.Value; if (packageJson.RequiredBy.Any()) { // All dependencies in npm v3 will have at least one element present in _requiredBy. // _requiredBy dependencies that begin with hash characters represent top-level dependencies foreach (var requiredBy in packageJson.RequiredBy) { if (requiredBy.StartsWith("#", StringComparison.Ordinal) || requiredBy == "/") { AddTopLevelModule(parent, showMissingDevOptionalSubPackages, moduleDir, depth, maxDepth); break; } } } else { // This dependency is a top-level dependency not added by npm v3 AddTopLevelModule(parent, showMissingDevOptionalSubPackages, moduleDir, depth, maxDepth); } } } if (modulesBase.Length < NativeMethods.MAX_FOLDER_PATH && parent.HasPackageJson) { // Iterate through all dependencies in the root package.json // Otherwise, only iterate through "dependencies" because iterating through optional, bundle, etc. dependencies // becomes unmanageable when they are already installed at the root of the project, and the performance impact // typically isn't worth the value add. var dependencies = depth == 0 ? parent.PackageJson.AllDependencies : parent.PackageJson.Dependencies; foreach (var dependency in dependencies) { var moduleDir = modulesBase; // try to find folder by recursing up tree do { moduleDir = Path.Combine(moduleDir, dependency.Name); if (AddModuleIfNotExists(parent, moduleDir, showMissingDevOptionalSubPackages, depth, maxDepth, dependency)) { break; } var parentNodeModulesIndex = moduleDir.LastIndexOf(NodejsConstants.NodeModulesFolder, Math.Max(0, moduleDir.Length - NodejsConstants.NodeModulesFolder.Length - dependency.Name.Length - 1), StringComparison.Ordinal); moduleDir = moduleDir.Substring(0, parentNodeModulesIndex + NodejsConstants.NodeModulesFolder.Length); } while (moduleDir.Contains(NodejsConstants.NodeModulesFolder)); } } this._packagesSorted.Sort(new PackageComparer()); } private void AddTopLevelModule(IRootPackage parent, bool showMissingDevOptionalSubPackages, string moduleDir, int depth, int maxDepth) { Debug.Assert(depth == 0, "Depth should be 0 when adding a top level dependency"); AddModuleIfNotExists(parent, moduleDir, showMissingDevOptionalSubPackages, depth, maxDepth); } private bool AddModuleIfNotExists(IRootPackage parent, string moduleDir, bool showMissingDevOptionalSubPackages, int depth, int maxDepth, IDependency dependency = null) { depth++; ModuleInfo moduleInfo; this._allModules.TryGetValue(moduleDir, out moduleInfo); if (moduleInfo != null) { // Update module information if the module already exists. if (moduleInfo.Depth > depth) { moduleInfo.Depth = depth; } if (dependency != null) { var existingPackage = this[dependency.Name] as Package; if (existingPackage != null) { existingPackage.RequestedVersionRange = dependency.VersionRangeText; } } } else if (Directory.Exists(moduleDir) || depth == 1) { // Top-level modules are always added so we can include missing modules. moduleInfo = new ModuleInfo(depth); this._allModules.Add(moduleDir, moduleInfo); } else { // The module directory wasn't found. return false; } IPackage package = moduleInfo.Package; if (package == null || depth == 1 || !moduleInfo.RequiredBy.Contains(parent.Path)) { // Create a dummy value for the current package to prevent infinite loops moduleInfo.Package = new PackageProxy(); moduleInfo.RequiredBy.Add(parent.Path); var pkg = new Package(parent, moduleDir, showMissingDevOptionalSubPackages, this._allModules, depth, maxDepth); if (dependency != null) { pkg.RequestedVersionRange = dependency.VersionRangeText; } package = moduleInfo.Package = pkg; } if (parent as IPackage == null || !package.IsMissing || showMissingDevOptionalSubPackages) { AddModule(package); } return true; } public override int GetDepth(string filepath) { var lastNodeModules = filepath.LastIndexOf(NodejsConstants.NodeModulesFolder + "\\", StringComparison.Ordinal); var directoryToSearch = filepath.IndexOf("\\", lastNodeModules + NodejsConstants.NodeModulesFolder.Length + 1, StringComparison.Ordinal); var directorySubString = directoryToSearch == -1 ? filepath : filepath.Substring(0, directoryToSearch); ModuleInfo value = null; this._allModules.TryGetValue(directorySubString, out value); var depth = value != null ? value.Depth : 0; Debug.WriteLine("Module Depth: {0} [{1}]", filepath, depth); return depth; } private static IEnumerable<KeyValuePair<string, IPackageJson>> GetTopLevelPackageDirectories(string modulesBase) { var topLevelDirectories = Enumerable.Empty<string>(); if (Directory.Exists(modulesBase)) { try { topLevelDirectories = Directory.EnumerateDirectories(modulesBase); } catch (IOException) { // We want to handle DirectoryNotFound, DriveNotFound, PathTooLong } catch (UnauthorizedAccessException) { } } // Go through every directory in node_modules, and see if it's required as a top-level dependency foreach (var moduleDir in topLevelDirectories) { if (moduleDir.Length < NativeMethods.MAX_FOLDER_PATH && !_ignoredDirectories.Any(toIgnore => moduleDir.EndsWith(toIgnore, StringComparison.Ordinal))) { IPackageJson json = null; try { json = PackageJsonFactory.Create(new DirectoryPackageJsonSource(moduleDir)); } catch (PackageJsonException) { // Fail gracefully if there was an error parsing the package.json Debug.Fail("Failed to parse package.json in {0}", moduleDir); } if (json != null) { yield return new KeyValuePair<string, IPackageJson>(moduleDir, json); } } } } } internal class ModuleInfo { public int Depth { get; set; } public IPackage Package { get; set; } public IList<string> RequiredBy { get; set; } internal ModuleInfo(int depth) { this.Depth = depth; this.RequiredBy = new List<string>(); } } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010-2013 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion -- License Terms -- using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace MsgPack { internal static class ReflectionAbstractions { public static readonly char TypeDelimiter = '.'; public static readonly Type[] EmptyTypes = new Type[ 0 ]; public static bool GetIsValueType( this Type source ) { #if NETFX_CORE return source.GetTypeInfo().IsValueType; #else return source.IsValueType; #endif } public static bool GetIsEnum( this Type source ) { #if NETFX_CORE return source.GetTypeInfo().IsEnum; #else return source.IsEnum; #endif } public static bool GetIsInterface( this Type source ) { #if NETFX_CORE return source.GetTypeInfo().IsInterface; #else return source.IsInterface; #endif } public static bool GetIsAbstract( this Type source ) { #if NETFX_CORE return source.GetTypeInfo().IsAbstract; #else return source.IsAbstract; #endif } public static bool GetIsGenericType( this Type source ) { #if NETFX_CORE return source.GetTypeInfo().IsGenericType; #else return source.IsGenericType; #endif } public static bool GetIsGenericTypeDefinition( this Type source ) { #if NETFX_CORE return source.GetTypeInfo().IsGenericTypeDefinition; #else return source.IsGenericTypeDefinition; #endif } public static bool GetContainsGenericParameters( this Type source ) { #if NETFX_CORE return source.GetTypeInfo().ContainsGenericParameters; #else return source.ContainsGenericParameters; #endif } public static Assembly GetAssembly( this Type source ) { #if NETFX_CORE return source.GetTypeInfo().Assembly; #else return source.Assembly; #endif } public static bool GetIsPublic( this Type source ) { #if NETFX_CORE return source.GetTypeInfo().IsPublic; #else return source.IsPublic; #endif } public static Type GetBaseType( this Type source ) { #if NETFX_CORE return source.GetTypeInfo().BaseType; #else return source.BaseType; #endif } public static Type[] GetGenericTypeParameters( this Type source ) { #if NETFX_CORE return source.GetTypeInfo().GenericTypeParameters; #else return source.GetGenericArguments().Where( t => t.IsGenericParameter ).ToArray(); #endif } #if NETFX_CORE public static MethodInfo GetMethod( this Type source, string name ) { return source.GetRuntimeMethods().SingleOrDefault( m => m.Name == name ); } public static MethodInfo GetMethod( this Type source, string name, Type[] parameters ) { return source.GetRuntimeMethod( name, parameters ); } public static IEnumerable<MethodInfo> GetMethods( this Type source ) { return source.GetRuntimeMethods(); } public static PropertyInfo GetProperty( this Type source, string name ) { return source.GetRuntimeProperty( name ); } public static ConstructorInfo GetConstructor( this Type source, Type[] parameteres ) { return source.GetTypeInfo().DeclaredConstructors.SingleOrDefault( c => c.GetParameters().Select( p => p.ParameterType ).SequenceEqual( parameteres ) ); } public static IEnumerable<ConstructorInfo> GetConstructors( this Type source ) { return source.GetTypeInfo().DeclaredConstructors; } public static Type[] GetGenericArguments( this Type source ) { return source.GenericTypeArguments; } public static bool IsAssignableFrom( this Type source, Type target ) { return source.GetTypeInfo().IsAssignableFrom( target.GetTypeInfo() ); } public static IEnumerable<Type> GetInterfaces( this Type source ) { return source.GetTypeInfo().ImplementedInterfaces; } public static MethodInfo GetSetMethod( this PropertyInfo source ) { return source.SetMethod; } public static IEnumerable<Type> FindInterfaces( this Type source, Func<Type, object, bool> filter, object filterCriteria ) { return source.GetTypeInfo().ImplementedInterfaces.Where( t => filter( t, filterCriteria ) ); } public static InterfaceMapping GetInterfaceMap( this Type source, Type interfaceType ) { return source.GetTypeInfo().GetRuntimeInterfaceMap( interfaceType ); } public static bool IsDefined( this Type source, Type attributeType ) { return source.GetTypeInfo().IsDefined( attributeType ); } #else public static bool IsDefined( this MemberInfo source, Type attributeType ) { return Attribute.IsDefined( source, attributeType ); } public static T GetCustomAttribute<T>( this MemberInfo source ) where T : Attribute { return Attribute.GetCustomAttribute( source, typeof( T ) ) as T; } #endif } }
/*********************************************************************************************************************** * TorrentDotNET - A BitTorrent library based on the .NET platform * * Copyright (C) 2004, Peter Ward * * * * This library is free software; you can redistribute it and/or modify it under the terms of the * * GNU Lesser General Public License as published by the Free Software Foundation; * * either version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License along with this library; * * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * ***********************************************************************************************************************/ using System.Collections; using Net = System.Net; using Sockets = System.Net.Sockets; using IO = System.IO; using Threading = System.Threading; namespace BitTorrent { public delegate void PeerDisconnectedCallback(Peer peer); public delegate void PeerStatusChangeCallback(Peer peer, bool newStatus); public delegate void PeerBitfieldChangeCallback(Peer peer, int pieceId); public delegate void PeerPieceCallback(Peer peer, int pieceId, int begin, int length, byte[] data); public class Peer { private bool amiChoking = true, amiInterested = false, heisChoking = true, heisInterested = false; private bool connected = true; private MetainfoFile infofile; private DownloadFile downloadFile; private Sockets.Socket socket; private Sockets.NetworkStream netStream; private PeerInformation peerInformation; private PeerProtocol peerProtocol = new PeerProtocol(); private byte[] data = new byte[ Config.MaxRequestSize ]; private PWLib.Platform.CircularBuffer buffer = new PWLib.Platform.CircularBuffer( Config.MaxRequestSize / 2 ); private BitField piecesDownloaded; private ArrayList messageQueue = new ArrayList(); private volatile bool asyncInProgress = false; private int numBytesDownloaded = 0, numBytesUploaded = 0; // internal Piece PieceDownloading = null; public Throttle UpThrottle { get { return peerProtocol.UpThrottle; } } public Throttle DownThrottle { get { return peerProtocol.DownThrottle; } } public bool IsSeed { get { return this.piecesDownloaded.AllTrue; } } internal Sockets.Socket Socket { get { return this.socket; } } #region Events public event PeerStatusChangeCallback IAmChokingChange, IAmInterestedChange, HeIsChokingChange, HeIsInterestedChange; public event PeerBitfieldChangeCallback BitfieldChange; public event PeerPieceCallback PieceRequest, PieceCancel, PieceIncoming; public event PeerDisconnectedCallback Disconnected; #endregion #region Properties public int BytesDownloaded { get { return this.numBytesDownloaded; } } public int BytesUploaded { get { return this.numBytesUploaded; } } /// <summary> /// Downloaded:Uploaded ratio. Higher ratio than 1.0 means we've downloaded more than we've uploaded /// </summary> public float Ratio { get { if (this.numBytesUploaded == 0) return 0.0f; else return (float)this.numBytesDownloaded / (float)this.numBytesUploaded; } } public bool Connected { get { return this.connected; } } public PeerInformation Information { get { return this.peerInformation; } } public BitField BitField { get { return this.piecesDownloaded; } } public bool AmIChoking { get { return this.amiChoking; } set { if (this.amiChoking != value) { this.amiChoking = value; if (this.IAmChokingChange != null) this.IAmChokingChange(this, this.amiChoking); this.SendChokeMessage(this.amiChoking); } } } public bool AmIInterested { get { return amiInterested; } set { if (this.amiInterested != value) { this.amiInterested = value; if (this.IAmInterestedChange != null) this.IAmInterestedChange(this, this.amiInterested); this.SendInterestedMessage(this.amiInterested); } } } public bool HeIsChoking { get { return heisChoking; } } public bool HeIsInterested { get { return heisInterested; } } #endregion public Peer(MetainfoFile infofile, DownloadFile downloadFile, Sockets.Socket socket, Sockets.NetworkStream netStream, PeerInformation peerInformation) { this.infofile = infofile; this.downloadFile = downloadFile; this.socket = socket; this.netStream = netStream; this.peerInformation = peerInformation; this.piecesDownloaded = new BitField(this.infofile.PieceCount); this.peerProtocol.UpThrottle.Start(); this.peerProtocol.DownThrottle.Start(); } public void Disconnect() { try { try { if (this.socket.Connected) this.netStream.Close(); this.netStream = null; } catch (System.Exception) {} if (this.connected) { if (this.Disconnected != null) this.Disconnected(this); } this.socket = null; this.connected = false; this.peerProtocol.UpThrottle.Stop(); this.peerProtocol.DownThrottle.Stop(); // Config.LogDebugMessage("Peer disconnected: " + this.ToString() + " Stack: " + System.Environment.StackTrace); } catch ( System.Exception e ) { Config.LogException( e ); } } #region Receiving messages public int ReadData(byte[] data) { try { int totalRead = 0; do { int bytesRead = this.socket.Receive( data, 0, data.Length, Sockets.SocketFlags.None ); totalRead += bytesRead; this.peerProtocol.DownThrottle.AddData( bytesRead ); if ( bytesRead > 0 ) { this.buffer.Write( data, 0, bytesRead ); } else { this.Disconnect(); } } while ( this.socket != null && this.socket.Connected && this.socket.Available > 0 ); this.ProcessAnyMessages(); return totalRead; } catch (System.Exception e) { Config.LogException(e); this.Disconnect(); } return 0; } private void ProcessAnyMessages() { try { IO.Stream reader = this.buffer.Reader; while ( this.buffer.DataAvailable >= 5 ) { int length; PeerMessage message; peerProtocol.ReadMessageHeader( reader, out length, out message ); if ( length > 0 ) { if ( length - 1 > buffer.DataAvailable ) { reader.Seek( -5, IO.SeekOrigin.Current ); break; } else { length--; // Config.LogDebugMessage("Message received: " + message.ToString() + " from " + this.ToString()); switch ( message ) { case PeerMessage.Bitfield: { this.piecesDownloaded = peerProtocol.ReadBitfieldMessage( reader, length ); this.piecesDownloaded.SetLength( this.infofile.PieceCount ); if ( this.BitfieldChange != null ) this.BitfieldChange( this, -1 ); } break; case PeerMessage.Choke: this.heisChoking = true; if ( this.HeIsChokingChange != null ) this.HeIsChokingChange( this, this.heisChoking ); break; case PeerMessage.Unchoke: this.heisChoking = false; if ( this.HeIsChokingChange != null ) this.HeIsChokingChange( this, this.heisChoking ); break; case PeerMessage.Interested: this.heisInterested = true; if ( this.HeIsInterestedChange != null ) this.HeIsInterestedChange( this, this.heisInterested ); break; case PeerMessage.Uninterested: this.heisInterested = false; if ( this.HeIsInterestedChange != null ) this.HeIsInterestedChange( this, this.heisInterested ); break; case PeerMessage.Have: { // update piecesdownloaded int pieceId = peerProtocol.ReadHaveMessage( reader ); this.piecesDownloaded.Set( pieceId, true ); if ( this.BitfieldChange != null ) this.BitfieldChange( this, pieceId ); } break; case PeerMessage.Request: { int index, begin, pieceLength; peerProtocol.ReadRequestMessage( reader, out index, out begin, out pieceLength ); if ( this.PieceRequest != null ) this.PieceRequest( this, index, begin, pieceLength, null ); } break; case PeerMessage.Cancel: { int index, begin, pieceLength; peerProtocol.ReadCancelMessage( reader, out index, out begin, out pieceLength ); if ( this.PieceCancel != null ) this.PieceCancel( this, index, begin, pieceLength, null ); } break; case PeerMessage.Piece: { int index, begin, pieceLength; peerProtocol.ReadPieceMessageHeader( reader, length, out index, out begin, out pieceLength ); this.numBytesDownloaded += pieceLength; byte[] data = new byte[ pieceLength ]; reader.Read( data, 0, data.Length ); if ( this.PieceIncoming != null ) this.PieceIncoming( this, index, begin, pieceLength, data ); } break; default: // received an unknown message - something has gone wrong. Disconnect the peer this.Disconnect(); break; } } } } } catch (System.Exception e) { Config.LogException(e); this.Disconnect(); } } #endregion #region Sending messages public void SendInterestedMessage(bool interested) { try { if ( socket.Connected ) { if ( !asyncInProgress ) peerProtocol.SendInterestedMessage( this.netStream, interested ); else this.messageQueue.Add( new object[] { PeerMessage.Interested, interested } ); } } catch (System.Exception e) { Config.LogException(e); this.Disconnect(); } } public void SendChokeMessage(bool choked) { try { if ( socket.Connected ) { if ( !asyncInProgress ) peerProtocol.SendChokeMessage( this.netStream, choked ); else this.messageQueue.Add( new object[] { PeerMessage.Choke, choked } ); } } catch (System.Exception e) { Config.LogException(e); this.Disconnect(); } } public void SendHaveMessage(int pieceId) { try { if ( socket.Connected ) { if ( !this.asyncInProgress ) peerProtocol.SendHaveMessage( this.netStream, pieceId ); else this.messageQueue.Add( new object[] { PeerMessage.Have, pieceId } ); } } catch (System.Exception e) { Config.LogException(e); this.Disconnect(); } } public void SendPieceRequest(int pieceId, int begin, int length) { try { if ( socket.Connected ) { if ( !this.asyncInProgress ) peerProtocol.SendPieceRequest( this.netStream, pieceId, begin, length ); else this.messageQueue.Add( new object[] { PeerMessage.Request, pieceId, begin, length } ); } } catch (System.Exception e) { Config.LogException(e); this.Disconnect(); } } public void SendPieceCancel(int pieceId, int begin, int length) { try { if ( socket.Connected ) { if ( !this.asyncInProgress ) peerProtocol.SendPieceCancel( this.netStream, pieceId, begin, length ); else this.messageQueue.Add( new object[] { PeerMessage.Cancel, pieceId, begin, length } ); } } catch (System.Exception e) { Config.LogException(e); this.Disconnect(); } } public void SendPiece(int pieceId, int begin, int length, IO.Stream istream, PeerPieceCallback pieceSentCallback) { try { if ( socket.Connected ) { this.asyncInProgress = true; peerProtocol.SendPiece( this.netStream, pieceId, begin, length, istream, new PeerFinishedPieceTransfer( OnWriteFinished ), (object)( new object[] { pieceId, begin, length, pieceSentCallback } ) ); this.numBytesUploaded += length; } } catch (System.Exception e) { Config.LogException(e); this.Disconnect(); } } private void OnWriteFinished(object state, bool success) { try { this.asyncInProgress = false; if (this.netStream == null || !success) { this.Disconnect(); return; } int pieceId = (int)((object[])state)[0]; int begin = (int)((object[])state)[1]; int length = (int)((object[])state)[2]; PeerPieceCallback pieceSentCallback = (PeerPieceCallback)((object[])state)[3]; pieceSentCallback(this, pieceId, begin, length, null); // flush message queue foreach (object[] objs in this.messageQueue) { PeerMessage message = (PeerMessage)objs[0]; switch (message) { case PeerMessage.Request: this.SendPieceRequest((int)objs[1], (int)objs[2], (int)objs[3]); break; case PeerMessage.Cancel: this.SendPieceCancel((int)objs[1], (int)objs[2], (int)objs[3]); break; case PeerMessage.Choke: this.SendChokeMessage((bool)objs[1]); break; case PeerMessage.Interested: this.SendInterestedMessage((bool)objs[2]); break; case PeerMessage.Have: this.SendHaveMessage((int)objs[1]); break; } } this.messageQueue.Clear(); } catch (System.Exception e) { Config.LogException(e); this.Disconnect(); } } #endregion public override string ToString() { return this.peerInformation.IP + ":" + this.peerInformation.Port; } public override int GetHashCode() { return this.peerInformation.ID.GetHashCode() ; } public override bool Equals(object obj) { if (obj is Peer) { Peer peer = (Peer)obj; return peer.peerInformation.Equals(this.peerInformation); } else return false; } } }
namespace AngleSharp.Css { using System; using System.Runtime.InteropServices; /// <summary> /// A priority object for comparing priorities. /// </summary> [StructLayout(LayoutKind.Explicit, Pack = 1, CharSet = CharSet.Unicode)] public readonly struct Priority : IEquatable<Priority>, IComparable<Priority> { #region Fields [FieldOffset(0)] private readonly Byte _tags; [FieldOffset(1)] private readonly Byte _classes; [FieldOffset(2)] private readonly Byte _ids; [FieldOffset(3)] private readonly Byte _inlines; [FieldOffset(0)] private readonly UInt32 _priority; #endregion #region Default /// <summary> /// Gets the lowest (zero) priority. /// </summary> public static readonly Priority Zero = new Priority(0u); /// <summary> /// Gets the priority for having a single tag. /// </summary> public static readonly Priority OneTag = new Priority(0, 0, 0, 1); /// <summary> /// Gets the priority for having a single class. /// </summary> public static readonly Priority OneClass = new Priority(0, 0, 1, 0); /// <summary> /// Gets the priority for having a single Id. /// </summary> public static readonly Priority OneId = new Priority(0, 1, 0, 0); /// <summary> /// Gets the priority for having an inline element. /// </summary> public static readonly Priority Inline = new Priority(1, 0, 0, 0); #endregion #region ctor /// <summary> /// Creates a new priority with the given hashcode. /// </summary> /// <param name="priority">The hashcode to use.</param> public Priority(UInt32 priority) { _inlines = _ids = _classes = _tags = 0; _priority = priority; } /// <summary> /// Creates a new priority with the given values. /// </summary> /// <param name="inlines">The number of inlines.</param> /// <param name="ids">The number of ids.</param> /// <param name="classes">The number of classes.</param> /// <param name="tags">The number of tags.</param> public Priority(Byte inlines, Byte ids, Byte classes, Byte tags) { _priority = 0; _inlines = inlines; _ids = ids; _classes = classes; _tags = tags; } #endregion #region Properties /// <summary> /// Gets the number of tags for this priority. /// </summary> public Byte Tags => _tags; /// <summary> /// Gets the number of classes for this priority. /// </summary> public Byte Classes => _classes; /// <summary> /// Gets the number of ids for this priority. /// </summary> public Byte Ids => _ids; /// <summary> /// Gets the number of inlines for this priority. /// </summary> public Byte Inlines => _inlines; #endregion #region Operators /// <summary> /// Adds the two given priorities. /// </summary> /// <param name="a">The first priority.</param> /// <param name="b">The second priority.</param> /// <returns>The result of adding the two priorities.</returns> public static Priority operator +(Priority a, Priority b) => new Priority(a._priority + b._priority); #endregion #region Equality /// <summary> /// Compares two priorities and returns a boolean indicating if the two do match. /// </summary> /// <param name="a">The first priority to use.</param> /// <param name="b">The second priority to use.</param> /// <returns>True if both priorities are equal, otherwise false.</returns> public static Boolean operator ==(Priority a, Priority b) => a._priority == b._priority; /// <summary> /// Compares two priorities and returns a boolean indicating if the first one is greater. /// </summary> /// <param name="a">The first priority to use.</param> /// <param name="b">The second priority to use.</param> /// <returns>True if the first priority is higher, otherwise false.</returns> public static Boolean operator >(Priority a, Priority b) => a._priority > b._priority; /// <summary> /// Compares two priorities and returns a boolean indicating if the first one is greater or equal. /// </summary> /// <param name="a">The first priority to use.</param> /// <param name="b">The second priority to use.</param> /// <returns>True if the first priority is higher or equal, otherwise false.</returns> public static Boolean operator >=(Priority a, Priority b) => a._priority >= b._priority; /// <summary> /// Compares two priorities and returns a boolean indicating if the second one is greater. /// </summary> /// <param name="a">The first priority to use.</param> /// <param name="b">The second priority to use.</param> /// <returns>True if the second priority is higher, otherwise false.</returns> public static Boolean operator <(Priority a, Priority b) => a._priority < b._priority; /// <summary> /// Compares two priorities and returns a boolean indicating if the second one is greater or equal. /// </summary> /// <param name="a">The first priority to use.</param> /// <param name="b">The second priority to use.</param> /// <returns>True if the second priority is higher or equal, otherwise false.</returns> public static Boolean operator <=(Priority a, Priority b) => a._priority <= b._priority; /// <summary> /// Compares two priorities and returns a boolean indicating if the two do not match. /// </summary> /// <param name="a">The first priority to use.</param> /// <param name="b">The second color to use.</param> /// <returns>True if both priorities are not equal, otherwise false.</returns> public static Boolean operator !=(Priority a, Priority b) => a._priority != b._priority; /// <summary> /// Checks two priorities for equality. /// </summary> /// <param name="other">The other priority.</param> /// <returns>True if both priorities or equal, otherwise false.</returns> public Boolean Equals(Priority other) => _priority == other._priority; /// <summary> /// Tests if another object is equal to this object. /// </summary> /// <param name="obj">The object to test with.</param> /// <returns>True if the two objects are equal, otherwise false.</returns> public override Boolean Equals(Object? obj) => obj is Priority other && Equals(other); /// <summary> /// Returns a hash code that defines the current priority. /// </summary> /// <returns>The integer value of the hashcode.</returns> public override Int32 GetHashCode() => (Int32)_priority; /// <summary> /// Compares the current priority with another priority. /// </summary> /// <param name="other">The priority to compare to.</param> /// <returns>A value greater than 1 if the current priority is larger.</returns> public Int32 CompareTo(Priority other) => this == other ? 0 : (this > other ? 1 : -1); #endregion #region String Representation /// <summary> /// Returns a string representing the priority. /// </summary> /// <returns>The string representation.</returns> public override String ToString() => $"({_inlines}, {_ids}, {_classes}, {_tags})"; #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Text; namespace System.IO { /// <summary>Contains internal path helpers that are shared between many projects.</summary> internal static partial class PathInternal { /// <summary> /// Returns true if the path starts in a directory separator. /// </summary> internal static bool StartsWithDirectorySeparator(ReadOnlySpan<char> path) => path.Length > 0 && IsDirectorySeparator(path[0]); #if MS_IO_REDIST internal static string EnsureTrailingSeparator(string path) => EndsInDirectorySeparator(path) ? path : path + DirectorySeparatorCharAsString; internal static bool EndsInDirectorySeparator(string path) => !string.IsNullOrEmpty(path) && IsDirectorySeparator(path[path.Length - 1]); #else internal static string EnsureTrailingSeparator(string path) => Path.EndsInDirectorySeparator(path.AsSpan()) ? path : path + DirectorySeparatorCharAsString; #endif internal static bool IsRoot(ReadOnlySpan<char> path) => path.Length == GetRootLength(path); /// <summary> /// Get the common path length from the start of the string. /// </summary> internal static int GetCommonPathLength(string first, string second, bool ignoreCase) { int commonChars = EqualStartingCharacterCount(first, second, ignoreCase: ignoreCase); // If nothing matches if (commonChars == 0) return commonChars; // Or we're a full string and equal length or match to a separator if (commonChars == first.Length && (commonChars == second.Length || IsDirectorySeparator(second[commonChars]))) return commonChars; if (commonChars == second.Length && IsDirectorySeparator(first[commonChars])) return commonChars; // It's possible we matched somewhere in the middle of a segment e.g. C:\Foodie and C:\Foobar. while (commonChars > 0 && !IsDirectorySeparator(first[commonChars - 1])) commonChars--; return commonChars; } /// <summary> /// Gets the count of common characters from the left optionally ignoring case /// </summary> internal static unsafe int EqualStartingCharacterCount(string first, string second, bool ignoreCase) { if (string.IsNullOrEmpty(first) || string.IsNullOrEmpty(second)) return 0; int commonChars = 0; fixed (char* f = first) fixed (char* s = second) { char* l = f; char* r = s; char* leftEnd = l + first.Length; char* rightEnd = r + second.Length; while (l != leftEnd && r != rightEnd && (*l == *r || (ignoreCase && char.ToUpperInvariant(*l) == char.ToUpperInvariant(*r)))) { commonChars++; l++; r++; } } return commonChars; } /// <summary> /// Returns true if the two paths have the same root /// </summary> internal static bool AreRootsEqual(string first, string second, StringComparison comparisonType) { int firstRootLength = GetRootLength(first.AsSpan()); int secondRootLength = GetRootLength(second.AsSpan()); return firstRootLength == secondRootLength && string.Compare( strA: first, indexA: 0, strB: second, indexB: 0, length: firstRootLength, comparisonType: comparisonType) == 0; } /// <summary> /// Try to remove relative segments from the given path (without combining with a root). /// </summary> /// <param name="path">Input path</param> /// <param name="rootLength">The length of the root of the given path</param> internal static string RemoveRelativeSegments(string path, int rootLength) { var sb = new ValueStringBuilder(stackalloc char[260 /* PathInternal.MaxShortPath */]); if (RemoveRelativeSegments(path.AsSpan(), rootLength, ref sb)) { path = sb.ToString(); } sb.Dispose(); return path; } /// <summary> /// Try to remove relative segments from the given path (without combining with a root). /// </summary> /// <param name="path">Input path</param> /// <param name="rootLength">The length of the root of the given path</param> /// <param name="sb">String builder that will store the result</param> /// <returns>"true" if the path was modified</returns> internal static bool RemoveRelativeSegments(ReadOnlySpan<char> path, int rootLength, ref ValueStringBuilder sb) { Debug.Assert(rootLength > 0); bool flippedSeparator = false; int skip = rootLength; // We treat "\.." , "\." and "\\" as a relative segment. We want to collapse the first separator past the root presuming // the root actually ends in a separator. Otherwise the first segment for RemoveRelativeSegments // in cases like "\\?\C:\.\" and "\\?\C:\..\", the first segment after the root will be ".\" and "..\" which is not considered as a relative segment and hence not be removed. if (PathInternal.IsDirectorySeparator(path[skip - 1])) skip--; // Remove "//", "/./", and "/../" from the path by copying each character to the output, // except the ones we're removing, such that the builder contains the normalized path // at the end. if (skip > 0) { sb.Append(path.Slice(0, skip)); } for (int i = skip; i < path.Length; i++) { char c = path[i]; if (PathInternal.IsDirectorySeparator(c) && i + 1 < path.Length) { // Skip this character if it's a directory separator and if the next character is, too, // e.g. "parent//child" => "parent/child" if (PathInternal.IsDirectorySeparator(path[i + 1])) { continue; } // Skip this character and the next if it's referring to the current directory, // e.g. "parent/./child" => "parent/child" if ((i + 2 == path.Length || PathInternal.IsDirectorySeparator(path[i + 2])) && path[i + 1] == '.') { i++; continue; } // Skip this character and the next two if it's referring to the parent directory, // e.g. "parent/child/../grandchild" => "parent/grandchild" if (i + 2 < path.Length && (i + 3 == path.Length || PathInternal.IsDirectorySeparator(path[i + 3])) && path[i + 1] == '.' && path[i + 2] == '.') { // Unwind back to the last slash (and if there isn't one, clear out everything). int s; for (s = sb.Length - 1; s >= skip; s--) { if (PathInternal.IsDirectorySeparator(sb[s])) { sb.Length = (i + 3 >= path.Length && s == skip) ? s + 1 : s; // to avoid removing the complete "\tmp\" segment in cases like \\?\C:\tmp\..\, C:\tmp\.. break; } } if (s < skip) { sb.Length = skip; } i += 2; continue; } } // Normalize the directory separator if needed if (c != PathInternal.DirectorySeparatorChar && c == PathInternal.AltDirectorySeparatorChar) { c = PathInternal.DirectorySeparatorChar; flippedSeparator = true; } sb.Append(c); } // If we haven't changed the source path, return the original if (!flippedSeparator && sb.Length == path.Length) { return false; } // We may have eaten the trailing separator from the root when we started and not replaced it if (skip != rootLength && sb.Length < rootLength) { sb.Append(path[rootLength - 1]); } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Diagnostics; using Microsoft.Win32.SafeHandles; namespace System.Net.WebSockets { internal static class WebSocketProtocolComponent { private static readonly string s_dummyWebsocketKeyBase64 = Convert.ToBase64String(new byte[16]); private static readonly SafeLibraryHandle s_webSocketDllHandle; private static readonly string s_supportedVersion; private static readonly Interop.WebSocket.HttpHeader[] s_initialClientRequestHeaders = new Interop.WebSocket.HttpHeader[] { new Interop.WebSocket.HttpHeader() { Name = HttpKnownHeaderNames.Connection, NameLength = (uint)HttpKnownHeaderNames.Connection.Length, Value = HttpKnownHeaderNames.Upgrade, ValueLength = (uint)HttpKnownHeaderNames.Upgrade.Length }, new Interop.WebSocket.HttpHeader() { Name = HttpKnownHeaderNames.Upgrade, NameLength = (uint)HttpKnownHeaderNames.Upgrade.Length, Value = HttpWebSocket.WebSocketUpgradeToken, ValueLength = (uint)HttpWebSocket.WebSocketUpgradeToken.Length } }; private static readonly Interop.WebSocket.HttpHeader[] s_ServerFakeRequestHeaders; internal enum Action { NoAction = 0, SendToNetwork = 1, IndicateSendComplete = 2, ReceiveFromNetwork = 3, IndicateReceiveComplete = 4, } internal enum BufferType : uint { None = 0x00000000, UTF8Message = 0x80000000, UTF8Fragment = 0x80000001, BinaryMessage = 0x80000002, BinaryFragment = 0x80000003, Close = 0x80000004, PingPong = 0x80000005, UnsolicitedPong = 0x80000006 } internal enum PropertyType { ReceiveBufferSize = 0, SendBufferSize = 1, DisableMasking = 2, AllocatedBuffer = 3, DisableUtf8Verification = 4, KeepAliveInterval = 5, } internal enum ActionQueue { Send = 1, Receive = 2, } #pragma warning disable CA1810 // explicit static cctor static WebSocketProtocolComponent() { s_webSocketDllHandle = Interop.Kernel32.LoadLibraryExW(Interop.Libraries.WebSocket, IntPtr.Zero, 0); if (!s_webSocketDllHandle.IsInvalid) { s_supportedVersion = GetSupportedVersion(); s_ServerFakeRequestHeaders = new Interop.WebSocket.HttpHeader[] { new Interop.WebSocket.HttpHeader() { Name = HttpKnownHeaderNames.Connection, NameLength = (uint)HttpKnownHeaderNames.Connection.Length, Value = HttpKnownHeaderNames.Upgrade, ValueLength = (uint)HttpKnownHeaderNames.Upgrade.Length }, new Interop.WebSocket.HttpHeader() { Name = HttpKnownHeaderNames.Upgrade, NameLength = (uint)HttpKnownHeaderNames.Upgrade.Length, Value = HttpWebSocket.WebSocketUpgradeToken, ValueLength = (uint)HttpWebSocket.WebSocketUpgradeToken.Length }, new Interop.WebSocket.HttpHeader() { Name = HttpKnownHeaderNames.Host, NameLength = (uint)HttpKnownHeaderNames.Host.Length, Value = string.Empty, ValueLength = 0 }, new Interop.WebSocket.HttpHeader() { Name = HttpKnownHeaderNames.SecWebSocketVersion, NameLength = (uint)HttpKnownHeaderNames.SecWebSocketVersion.Length, Value = s_supportedVersion, ValueLength = (uint)s_supportedVersion.Length }, new Interop.WebSocket.HttpHeader() { Name = HttpKnownHeaderNames.SecWebSocketKey, NameLength = (uint)HttpKnownHeaderNames.SecWebSocketKey.Length, Value = s_dummyWebsocketKeyBase64, ValueLength = (uint)s_dummyWebsocketKeyBase64.Length } }; } } #pragma warning restore CA1810 internal static string SupportedVersion { get { if (s_webSocketDllHandle.IsInvalid) { HttpWebSocket.ThrowPlatformNotSupportedException_WSPC(); } return s_supportedVersion; } } internal static bool IsSupported { get { return !s_webSocketDllHandle.IsInvalid; } } internal static string GetSupportedVersion() { if (s_webSocketDllHandle.IsInvalid) { HttpWebSocket.ThrowPlatformNotSupportedException_WSPC(); } SafeWebSocketHandle webSocketHandle = null; try { int errorCode = Interop.WebSocket.WebSocketCreateClientHandle(null, 0, out webSocketHandle); ThrowOnError(errorCode); if (webSocketHandle == null || webSocketHandle.IsInvalid) { HttpWebSocket.ThrowPlatformNotSupportedException_WSPC(); } IntPtr additionalHeadersPtr; uint additionalHeaderCount; errorCode = Interop.WebSocket.WebSocketBeginClientHandshake(webSocketHandle, IntPtr.Zero, 0, IntPtr.Zero, 0, s_initialClientRequestHeaders, (uint)s_initialClientRequestHeaders.Length, out additionalHeadersPtr, out additionalHeaderCount); ThrowOnError(errorCode); Interop.WebSocket.HttpHeader[] additionalHeaders = MarshalHttpHeaders(additionalHeadersPtr, (int)additionalHeaderCount); string version = null; foreach (Interop.WebSocket.HttpHeader header in additionalHeaders) { if (string.Equals(header.Name, HttpKnownHeaderNames.SecWebSocketVersion, StringComparison.OrdinalIgnoreCase)) { version = header.Value; break; } } Debug.Assert(version != null, "'version' MUST NOT be NULL."); return version; } finally { if (webSocketHandle != null) { webSocketHandle.Dispose(); } } } internal static void WebSocketCreateServerHandle(Interop.WebSocket.Property[] properties, int propertyCount, out SafeWebSocketHandle webSocketHandle) { Debug.Assert(propertyCount >= 0, "'propertyCount' MUST NOT be negative."); Debug.Assert((properties == null && propertyCount == 0) || (properties != null && propertyCount == properties.Length), "'propertyCount' MUST MATCH 'properties.Length'."); if (s_webSocketDllHandle.IsInvalid) { HttpWebSocket.ThrowPlatformNotSupportedException_WSPC(); } int errorCode = Interop.WebSocket.WebSocketCreateServerHandle(properties, (uint)propertyCount, out webSocketHandle); ThrowOnError(errorCode); if (webSocketHandle == null || webSocketHandle.IsInvalid) { HttpWebSocket.ThrowPlatformNotSupportedException_WSPC(); } IntPtr responseHeadersPtr; uint responseHeaderCount; // Currently the WSPC doesn't allow to initiate a data session // without also being involved in the http handshake // There is no information whatsoever, which is needed by the // WSPC for parsing WebSocket frames from the HTTP handshake // In the managed implementation the HTTP header handling // will be done using the managed HTTP stack and we will // just fake an HTTP handshake for the WSPC calling // WebSocketBeginServerHandshake and WebSocketEndServerHandshake // with statically defined dummy headers. errorCode = Interop.WebSocket.WebSocketBeginServerHandshake(webSocketHandle, IntPtr.Zero, IntPtr.Zero, 0, s_ServerFakeRequestHeaders, (uint)s_ServerFakeRequestHeaders.Length, out responseHeadersPtr, out responseHeaderCount); ThrowOnError(errorCode); Interop.WebSocket.HttpHeader[] responseHeaders = MarshalHttpHeaders(responseHeadersPtr, (int)responseHeaderCount); errorCode = Interop.WebSocket.WebSocketEndServerHandshake(webSocketHandle); ThrowOnError(errorCode); Debug.Assert(webSocketHandle != null, "'webSocketHandle' MUST NOT be NULL at this point."); } internal static void WebSocketAbortHandle(SafeHandle webSocketHandle) { Debug.Assert(webSocketHandle != null && !webSocketHandle.IsInvalid, "'webSocketHandle' MUST NOT be NULL or INVALID."); Interop.WebSocket.WebSocketAbortHandle(webSocketHandle); DrainActionQueue(webSocketHandle, ActionQueue.Send); DrainActionQueue(webSocketHandle, ActionQueue.Receive); } internal static void WebSocketDeleteHandle(IntPtr webSocketPtr) { Debug.Assert(webSocketPtr != IntPtr.Zero, "'webSocketPtr' MUST NOT be IntPtr.Zero."); Interop.WebSocket.WebSocketDeleteHandle(webSocketPtr); } internal static void WebSocketSend(WebSocketBase webSocket, BufferType bufferType, Interop.WebSocket.Buffer buffer) { Debug.Assert(webSocket != null, "'webSocket' MUST NOT be NULL or INVALID."); Debug.Assert(webSocket.SessionHandle != null && !webSocket.SessionHandle.IsInvalid, "'webSocket.SessionHandle' MUST NOT be NULL or INVALID."); ThrowIfSessionHandleClosed(webSocket); int errorCode; try { errorCode = Interop.WebSocket.WebSocketSend_Raw(webSocket.SessionHandle, bufferType, ref buffer, IntPtr.Zero); } catch (ObjectDisposedException innerException) { throw ConvertObjectDisposedException(webSocket, innerException); } ThrowOnError(errorCode); } internal static void WebSocketSendWithoutBody(WebSocketBase webSocket, BufferType bufferType) { Debug.Assert(webSocket != null, "'webSocket' MUST NOT be NULL or INVALID."); Debug.Assert(webSocket.SessionHandle != null && !webSocket.SessionHandle.IsInvalid, "'webSocket.SessionHandle' MUST NOT be NULL or INVALID."); ThrowIfSessionHandleClosed(webSocket); int errorCode; try { errorCode = Interop.WebSocket.WebSocketSendWithoutBody_Raw(webSocket.SessionHandle, bufferType, IntPtr.Zero, IntPtr.Zero); } catch (ObjectDisposedException innerException) { throw ConvertObjectDisposedException(webSocket, innerException); } ThrowOnError(errorCode); } internal static void WebSocketReceive(WebSocketBase webSocket) { Debug.Assert(webSocket != null, "'webSocket' MUST NOT be NULL or INVALID."); Debug.Assert(webSocket.SessionHandle != null && !webSocket.SessionHandle.IsInvalid, "'webSocket.SessionHandle' MUST NOT be NULL or INVALID."); ThrowIfSessionHandleClosed(webSocket); int errorCode; try { errorCode = Interop.WebSocket.WebSocketReceive(webSocket.SessionHandle, IntPtr.Zero, IntPtr.Zero); } catch (ObjectDisposedException innerException) { throw ConvertObjectDisposedException(webSocket, innerException); } ThrowOnError(errorCode); } internal static void WebSocketGetAction(WebSocketBase webSocket, ActionQueue actionQueue, Interop.WebSocket.Buffer[] dataBuffers, ref uint dataBufferCount, out Action action, out BufferType bufferType, out IntPtr actionContext) { Debug.Assert(webSocket != null, "'webSocket' MUST NOT be NULL or INVALID."); Debug.Assert(webSocket.SessionHandle != null && !webSocket.SessionHandle.IsInvalid, "'webSocket.SessionHandle' MUST NOT be NULL or INVALID."); Debug.Assert(dataBufferCount >= 0, "'dataBufferCount' MUST NOT be negative."); Debug.Assert((dataBuffers == null && dataBufferCount == 0) || (dataBuffers != null && dataBufferCount == dataBuffers.Length), "'dataBufferCount' MUST MATCH 'dataBuffers.Length'."); action = Action.NoAction; bufferType = BufferType.None; actionContext = IntPtr.Zero; IntPtr dummy; ThrowIfSessionHandleClosed(webSocket); int errorCode; try { errorCode = Interop.WebSocket.WebSocketGetAction(webSocket.SessionHandle, actionQueue, dataBuffers, ref dataBufferCount, out action, out bufferType, out dummy, out actionContext); } catch (ObjectDisposedException innerException) { throw ConvertObjectDisposedException(webSocket, innerException); } ThrowOnError(errorCode); webSocket.ValidateNativeBuffers(action, bufferType, dataBuffers, dataBufferCount); Debug.Assert(dataBufferCount >= 0); Debug.Assert((dataBufferCount == 0 && dataBuffers == null) || (dataBufferCount <= dataBuffers.Length)); } internal static void WebSocketCompleteAction(WebSocketBase webSocket, IntPtr actionContext, int bytesTransferred) { Debug.Assert(webSocket != null, "'webSocket' MUST NOT be NULL or INVALID."); Debug.Assert(webSocket.SessionHandle != null && !webSocket.SessionHandle.IsInvalid, "'webSocket.SessionHandle' MUST NOT be NULL or INVALID."); Debug.Assert(actionContext != IntPtr.Zero, "'actionContext' MUST NOT be IntPtr.Zero."); Debug.Assert(bytesTransferred >= 0, "'bytesTransferred' MUST NOT be negative."); if (webSocket.SessionHandle.IsClosed) { return; } try { Interop.WebSocket.WebSocketCompleteAction(webSocket.SessionHandle, actionContext, (uint)bytesTransferred); } catch (ObjectDisposedException) { } } private static void DrainActionQueue(SafeHandle webSocketHandle, ActionQueue actionQueue) { Debug.Assert(webSocketHandle != null && !webSocketHandle.IsInvalid, "'webSocketHandle' MUST NOT be NULL or INVALID."); IntPtr actionContext; IntPtr dummy; Action action; BufferType bufferType; while (true) { Interop.WebSocket.Buffer[] dataBuffers = new Interop.WebSocket.Buffer[1]; uint dataBufferCount = 1; int errorCode = Interop.WebSocket.WebSocketGetAction(webSocketHandle, actionQueue, dataBuffers, ref dataBufferCount, out action, out bufferType, out dummy, out actionContext); if (!Succeeded(errorCode)) { Debug.Assert(errorCode == 0, "'errorCode' MUST be 0."); return; } if (action == Action.NoAction) { return; } Interop.WebSocket.WebSocketCompleteAction(webSocketHandle, actionContext, 0); } } private static void MarshalAndVerifyHttpHeader(IntPtr httpHeaderPtr, ref Interop.WebSocket.HttpHeader httpHeader) { Debug.Assert(httpHeaderPtr != IntPtr.Zero, "'currentHttpHeaderPtr' MUST NOT be IntPtr.Zero."); IntPtr httpHeaderNamePtr = Marshal.ReadIntPtr(httpHeaderPtr); IntPtr lengthPtr = IntPtr.Add(httpHeaderPtr, IntPtr.Size); int length = Marshal.ReadInt32(lengthPtr); Debug.Assert(length >= 0, "'length' MUST NOT be negative."); if (httpHeaderNamePtr != IntPtr.Zero) { httpHeader.Name = Marshal.PtrToStringAnsi(httpHeaderNamePtr, length); } if ((httpHeader.Name == null && length != 0) || (httpHeader.Name != null && length != httpHeader.Name.Length)) { Debug.Fail("The length of 'httpHeader.Name' MUST MATCH 'length'."); throw new AccessViolationException(); } // structure of Interop.WebSocket.HttpHeader: // Name = string* // NameLength = uint* // Value = string* // ValueLength = uint* // NOTE - All fields in the object are pointers to the actual value, hence the use of // n * IntPtr.Size to get to the correct place in the object. int valueOffset = 2 * IntPtr.Size; int lengthOffset = 3 * IntPtr.Size; IntPtr httpHeaderValuePtr = Marshal.ReadIntPtr(IntPtr.Add(httpHeaderPtr, valueOffset)); lengthPtr = IntPtr.Add(httpHeaderPtr, lengthOffset); length = Marshal.ReadInt32(lengthPtr); httpHeader.Value = Marshal.PtrToStringAnsi(httpHeaderValuePtr, (int)length); if ((httpHeader.Value == null && length != 0) || (httpHeader.Value != null && length != httpHeader.Value.Length)) { Debug.Fail("The length of 'httpHeader.Value' MUST MATCH 'length'."); throw new AccessViolationException(); } } private static Interop.WebSocket.HttpHeader[] MarshalHttpHeaders(IntPtr nativeHeadersPtr, int nativeHeaderCount) { Debug.Assert(nativeHeaderCount >= 0, "'nativeHeaderCount' MUST NOT be negative."); Debug.Assert(nativeHeadersPtr != IntPtr.Zero || nativeHeaderCount == 0, "'nativeHeaderCount' MUST be 0."); Interop.WebSocket.HttpHeader[] httpHeaders = new Interop.WebSocket.HttpHeader[nativeHeaderCount]; // structure of Interop.WebSocket.HttpHeader: // Name = string* // NameLength = uint* // Value = string* // ValueLength = uint* // NOTE - All fields in the object are pointers to the actual value, hence the use of // 4 * IntPtr.Size to get to the next header. int httpHeaderStructSize = 4 * IntPtr.Size; for (int i = 0; i < nativeHeaderCount; i++) { int offset = httpHeaderStructSize * i; IntPtr currentHttpHeaderPtr = IntPtr.Add(nativeHeadersPtr, offset); MarshalAndVerifyHttpHeader(currentHttpHeaderPtr, ref httpHeaders[i]); } Debug.Assert(httpHeaders != null); Debug.Assert(httpHeaders.Length == nativeHeaderCount); return httpHeaders; } public static bool Succeeded(int hr) { return (hr >= 0); } private static void ThrowOnError(int errorCode) { if (Succeeded(errorCode)) { return; } throw new WebSocketException(errorCode); } private static void ThrowIfSessionHandleClosed(WebSocketBase webSocket) { if (webSocket.SessionHandle.IsClosed) { throw new WebSocketException(WebSocketError.InvalidState, SR.Format(SR.net_WebSockets_InvalidState_ClosedOrAborted, webSocket.GetType().FullName, webSocket.State)); } } private static WebSocketException ConvertObjectDisposedException(WebSocketBase webSocket, ObjectDisposedException innerException) { return new WebSocketException(WebSocketError.InvalidState, SR.Format(SR.net_WebSockets_InvalidState_ClosedOrAborted, webSocket.GetType().FullName, webSocket.State), innerException); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic.Utils; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading; using AstUtils = System.Linq.Expressions.Utils; namespace System.Linq.Expressions.Interpreter { #if FEATURE_MAKE_RUN_METHODS internal static partial class DelegateHelpers { private const int MaximumArity = 17; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] internal static Type MakeDelegate(Type[] types) { Debug.Assert(types != null && types.Length > 0); // Can only used predefined delegates if we have no byref types and // the arity is small enough to fit in Func<...> or Action<...> if (types.Length > MaximumArity || types.Any(t => t.IsByRef)) { throw Assert.Unreachable; } Type returnType = types[types.Length - 1]; if (returnType == typeof(void)) { Array.Resize(ref types, types.Length - 1); switch (types.Length) { case 0: return typeof(Action); case 1: return typeof(Action<>).MakeGenericType(types); case 2: return typeof(Action<,>).MakeGenericType(types); case 3: return typeof(Action<,,>).MakeGenericType(types); case 4: return typeof(Action<,,,>).MakeGenericType(types); case 5: return typeof(Action<,,,,>).MakeGenericType(types); case 6: return typeof(Action<,,,,,>).MakeGenericType(types); case 7: return typeof(Action<,,,,,,>).MakeGenericType(types); case 8: return typeof(Action<,,,,,,,>).MakeGenericType(types); case 9: return typeof(Action<,,,,,,,,>).MakeGenericType(types); case 10: return typeof(Action<,,,,,,,,,>).MakeGenericType(types); case 11: return typeof(Action<,,,,,,,,,,>).MakeGenericType(types); case 12: return typeof(Action<,,,,,,,,,,,>).MakeGenericType(types); case 13: return typeof(Action<,,,,,,,,,,,,>).MakeGenericType(types); case 14: return typeof(Action<,,,,,,,,,,,,,>).MakeGenericType(types); case 15: return typeof(Action<,,,,,,,,,,,,,,>).MakeGenericType(types); case 16: return typeof(Action<,,,,,,,,,,,,,,,>).MakeGenericType(types); } } else { switch (types.Length) { case 1: return typeof(Func<>).MakeGenericType(types); case 2: return typeof(Func<,>).MakeGenericType(types); case 3: return typeof(Func<,,>).MakeGenericType(types); case 4: return typeof(Func<,,,>).MakeGenericType(types); case 5: return typeof(Func<,,,,>).MakeGenericType(types); case 6: return typeof(Func<,,,,,>).MakeGenericType(types); case 7: return typeof(Func<,,,,,,>).MakeGenericType(types); case 8: return typeof(Func<,,,,,,,>).MakeGenericType(types); case 9: return typeof(Func<,,,,,,,,>).MakeGenericType(types); case 10: return typeof(Func<,,,,,,,,,>).MakeGenericType(types); case 11: return typeof(Func<,,,,,,,,,,>).MakeGenericType(types); case 12: return typeof(Func<,,,,,,,,,,,>).MakeGenericType(types); case 13: return typeof(Func<,,,,,,,,,,,,>).MakeGenericType(types); case 14: return typeof(Func<,,,,,,,,,,,,,>).MakeGenericType(types); case 15: return typeof(Func<,,,,,,,,,,,,,,>).MakeGenericType(types); case 16: return typeof(Func<,,,,,,,,,,,,,,,>).MakeGenericType(types); case 17: return typeof(Func<,,,,,,,,,,,,,,,,>).MakeGenericType(types); } } throw Assert.Unreachable; } } #endif internal class ScriptingRuntimeHelpers { public static object Int32ToObject(int i) { switch (i) { case -1: return Int32_m; case 0: return Int32_0; case 1: return Int32_1; case 2: return Int32_2; } return i; } private static readonly object Int32_m = -1; private static readonly object Int32_0 = 0; private static readonly object Int32_1 = 1; private static readonly object Int32_2 = 2; public static object BooleanToObject(bool b) { return b ? True : False; } internal static readonly object True = true; internal static readonly object False = false; internal static object GetPrimitiveDefaultValue(Type type) { object result; switch (System.Dynamic.Utils.TypeExtensions.GetTypeCode(type)) { case TypeCode.Boolean: result = ScriptingRuntimeHelpers.False; break; case TypeCode.SByte: result = default(SByte); break; case TypeCode.Byte: result = default(Byte); break; case TypeCode.Char: result = default(Char); break; case TypeCode.Int16: result = default(Int16); break; case TypeCode.Int32: result = ScriptingRuntimeHelpers.Int32_0; break; case TypeCode.Int64: result = default(Int64); break; case TypeCode.UInt16: result = default(UInt16); break; case TypeCode.UInt32: result = default(UInt32); break; case TypeCode.UInt64: result = default(UInt64); break; case TypeCode.Single: return default(Single); case TypeCode.Double: return default(Double); // case TypeCode.DBNull: // return default(DBNull); case TypeCode.DateTime: return default(DateTime); case TypeCode.Decimal: return default(Decimal); default: return null; } if (type.GetTypeInfo().IsEnum) { result = Enum.ToObject(type, result); } return result; } } /// <summary> /// Wraps all arguments passed to a dynamic site with more arguments than can be accepted by a Func/Action delegate. /// The binder generating a rule for such a site should unwrap the arguments first and then perform a binding to them. /// </summary> internal sealed class ArgumentArray { private readonly object[] _arguments; // the index of the first item _arguments that represents an argument: private readonly int _first; // the number of items in _arguments that represent the arguments: private readonly int _count; internal ArgumentArray(object[] arguments, int first, int count) { _arguments = arguments; _first = first; _count = count; } public int Count { get { return _count; } } public object GetArgument(int index) { return _arguments[_first + index]; } public static object GetArg(ArgumentArray array, int index) { return array._arguments[array._first + index]; } } internal static class ExceptionHelpers { private const string prevStackTraces = "PreviousStackTraces"; /// <summary> /// Updates an exception before it's getting re-thrown so /// we can present a reasonable stack trace to the user. /// </summary> public static Exception UpdateForRethrow(Exception rethrow) { #if FEATURE_STACK_TRACES List<StackTrace> prev; // we don't have any dynamic stack trace data, capture the data we can // from the raw exception object. StackTrace st = new StackTrace(rethrow, true); if (!TryGetAssociatedStackTraces(rethrow, out prev)) { prev = new List<StackTrace>(); AssociateStackTraces(rethrow, prev); } prev.Add(st); #endif // FEATURE_STACK_TRACES return rethrow; } #if FEATURE_STACK_TRACES /// <summary> /// Returns all the stack traces associates with an exception /// </summary> public static IList<StackTrace> GetExceptionStackTraces(Exception rethrow) { List<StackTrace> result; return TryGetAssociatedStackTraces(rethrow, out result) ? result : null; } private static void AssociateStackTraces(Exception e, List<StackTrace> traces) { e.Data[prevStackTraces] = traces; } private static bool TryGetAssociatedStackTraces(Exception e, out List<StackTrace> traces) { traces = e.Data[prevStackTraces] as List<StackTrace>; return traces != null; } #endif // FEATURE_STACK_TRACES } /// <summary> /// A hybrid dictionary which compares based upon object identity. /// </summary> internal class HybridReferenceDictionary<TKey, TValue> where TKey : class { private KeyValuePair<TKey, TValue>[] _keysAndValues; private Dictionary<TKey, TValue> _dict; private int _count; private const int _arraySize = 10; public HybridReferenceDictionary() { } public HybridReferenceDictionary(int initialCapicity) { if (initialCapicity > _arraySize) { _dict = new Dictionary<TKey, TValue>(initialCapicity); } else { _keysAndValues = new KeyValuePair<TKey, TValue>[initialCapicity]; } } public bool TryGetValue(TKey key, out TValue value) { Debug.Assert(key != null); if (_dict != null) { return _dict.TryGetValue(key, out value); } else if (_keysAndValues != null) { for (int i = 0; i < _keysAndValues.Length; i++) { if (_keysAndValues[i].Key == key) { value = _keysAndValues[i].Value; return true; } } } value = default(TValue); return false; } public bool Remove(TKey key) { Debug.Assert(key != null); if (_dict != null) { return _dict.Remove(key); } else if (_keysAndValues != null) { for (int i = 0; i < _keysAndValues.Length; i++) { if (_keysAndValues[i].Key == key) { _keysAndValues[i] = new KeyValuePair<TKey, TValue>(); _count--; return true; } } } return false; } public bool ContainsKey(TKey key) { Debug.Assert(key != null); if (_dict != null) { return _dict.ContainsKey(key); } else if (_keysAndValues != null) { for (int i = 0; i < _keysAndValues.Length; i++) { if (_keysAndValues[i].Key == key) { return true; } } } return false; } public int Count { get { if (_dict != null) { return _dict.Count; } return _count; } } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { if (_dict != null) { return _dict.GetEnumerator(); } return GetEnumeratorWorker(); } private IEnumerator<KeyValuePair<TKey, TValue>> GetEnumeratorWorker() { if (_keysAndValues != null) { for (int i = 0; i < _keysAndValues.Length; i++) { if (_keysAndValues[i].Key != null) { yield return _keysAndValues[i]; } } } } public TValue this[TKey key] { get { Debug.Assert(key != null); TValue res; if (TryGetValue(key, out res)) { return res; } throw new KeyNotFoundException(); } set { Debug.Assert(key != null); if (_dict != null) { _dict[key] = value; } else { int index; if (_keysAndValues != null) { index = -1; for (int i = 0; i < _keysAndValues.Length; i++) { if (_keysAndValues[i].Key == key) { _keysAndValues[i] = new KeyValuePair<TKey, TValue>(key, value); return; } else if (_keysAndValues[i].Key == null) { index = i; } } } else { _keysAndValues = new KeyValuePair<TKey, TValue>[_arraySize]; index = 0; } if (index != -1) { _count++; _keysAndValues[index] = new KeyValuePair<TKey, TValue>(key, value); } else { _dict = new Dictionary<TKey, TValue>(); for (int i = 0; i < _keysAndValues.Length; i++) { _dict[_keysAndValues[i].Key] = _keysAndValues[i].Value; } _keysAndValues = null; _dict[key] = value; } } } } } internal static class Assert { internal static Exception Unreachable { get { Debug.Assert(false, "Unreachable"); return new InvalidOperationException("Code supposed to be unreachable"); } } [Conditional("DEBUG")] public static void NotNull(object var) { Debug.Assert(var != null); } [Conditional("DEBUG")] public static void NotNull(object var1, object var2) { Debug.Assert(var1 != null && var2 != null); } [Conditional("DEBUG")] public static void NotNull(object var1, object var2, object var3) { Debug.Assert(var1 != null && var2 != null && var3 != null); } [Conditional("DEBUG")] public static void NotNullItems<T>(IEnumerable<T> items) where T : class { Debug.Assert(items != null); foreach (object item in items) { Debug.Assert(item != null); } } [Conditional("DEBUG")] public static void NotEmpty(string str) { Debug.Assert(!String.IsNullOrEmpty(str)); } } [Flags] internal enum ExpressionAccess { None = 0, Read = 1, Write = 2, ReadWrite = Read | Write, } }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // 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 Xamarin.Forms; using Newtonsoft.Json; using Sensus.UI.UiProperties; namespace Sensus.UI.Inputs { public class SliderInput : Input { public const string EFFECT_RESOLUTION_EFFECT_NAME = "SliderInputEffect"; public const string EFFECT_RESOLUTION_NAME = EFFECT_RESOLUTION_GROUP_NAME + "." + EFFECT_RESOLUTION_EFFECT_NAME; private string _tipText; private double _minimum; private double _maximum; private double _increment; private string _leftLabel; private string _rightLabel; private bool _displaySliderValue; private bool _displayMinMax; private Slider _slider; private double _incrementalValue; private bool _incrementalValueHasChanged; private Label _sliderLabel; [EntryStringUiProperty("Tip Text:", true, 9)] public string TipText { get { return _tipText; } set { _tipText = value?.Trim(); } } [EntryDoubleUiProperty(null, true, 10)] public double Minimum { get { return _minimum; } set { _minimum = value; } } [EntryDoubleUiProperty(null, true, 11)] public double Maximum { get { return _maximum; } set { _maximum = value; } } [EntryDoubleUiProperty(null, true, 12)] public double Increment { get { return _increment; } set { _increment = value; } } [EntryStringUiProperty("Left Label:", true, 13)] public string LeftLabel { get { return _leftLabel; } set { _leftLabel = value; } } [EntryStringUiProperty("Right Label:", true, 14)] public string RightLabel { get { return _rightLabel; } set { _rightLabel = value; } } [OnOffUiProperty("Display Slider Value:", true, 15)] public bool DisplaySliderValue { get { return _displaySliderValue; } set { _displaySliderValue = value; } } [OnOffUiProperty("Display Min and Max:", true, 16)] public bool DisplayMinMax { get { return _displayMinMax; } set { _displayMinMax = value; } } public override object Value { get { // the slider can be untouched but still have a value associated with it (i.e., the position of the slider). if the slider // is not a required input, then this value would be returned, which is not what we want since the user never interacted with the // input. so, additionally keep track of whether the value has actually changed, indicating that the user has touched the control. return _slider == null || !_incrementalValueHasChanged ? null : (object)_incrementalValue; } } [JsonIgnore] public override bool Enabled { get { return _slider.IsEnabled; } set { _slider.IsEnabled = value; } } public override string DefaultName { get { return "Slider"; } } public SliderInput() { Construct(1, 10); } public SliderInput(string labelText, double minimum, double maximum) : base(labelText) { Construct(minimum, maximum); } public SliderInput(string name, string labelText, double minimum, double maximum) : base(name, labelText) { Construct(minimum, maximum); } private void Construct(double minimum, double maximum) { _tipText = "Please tap the range below to select a value"; _minimum = minimum; _maximum = maximum; _increment = (_maximum - _minimum + 1) / 10; _leftLabel = _rightLabel = null; _displaySliderValue = true; _displayMinMax = true; } public override View GetView(int index) { if (base.GetView(index) == null) { _slider = new Slider { HorizontalOptions = LayoutOptions.FillAndExpand, // need to set the min and max to extremes to allow them to be reset below to arbitrary values Minimum = double.MinValue, Maximum = double.MaxValue // set the style ID on the view so that we can retrieve it when unit testing #if UNIT_TESTING , StyleId = Name #endif }; _incrementalValueHasChanged = false; _sliderLabel = CreateLabel(index); if (!string.IsNullOrWhiteSpace(_tipText)) { _sliderLabel.Text += " (" + _tipText + ")"; } _slider.Minimum = _minimum; _slider.Maximum = _maximum; _slider.ValueChanged += (sender, e) => { double newIncrementalValue = GetIncrementalValue(e.NewValue); if (newIncrementalValue != _incrementalValue) { _incrementalValue = newIncrementalValue; _incrementalValueHasChanged = true; _sliderLabel.Text = _displaySliderValue ? GetLabelText(index) + " " + _incrementalValue : GetLabelText(index); Complete = Value != null; } }; // we use the effects framework to hide the slider's initial position from the user, in order to avoid biasing the user away from or toward the initial position. _slider.Effects.Add(Effect.Resolve(EFFECT_RESOLUTION_NAME)); base.SetView(new StackLayout { Orientation = StackOrientation.Vertical, VerticalOptions = LayoutOptions.Start, Children = { _sliderLabel, new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { new Label { Text = _displayMinMax ? _slider.Minimum.ToString() : " ", // we used to set the label invisible, but this doesn't leave enough vertical space above/below the slider. adding a blank space does the trick. FontSize = 20, HorizontalOptions = LayoutOptions.Fill }, _slider, new Label { Text = _displayMinMax ? _slider.Maximum.ToString() : " ", // we used to set the label invisible, but this doesn't leave enough vertical space above/below the slider. adding a blank space does the trick. FontSize = 20, HorizontalOptions = LayoutOptions.Fill } } }, new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { new Label { Text = _leftLabel, FontSize = 15, HorizontalOptions = LayoutOptions.FillAndExpand }, new Label { Text = _rightLabel, FontSize = 15, HorizontalOptions = LayoutOptions.End } }, IsVisible = (!string.IsNullOrWhiteSpace(_leftLabel) || !string.IsNullOrWhiteSpace(_rightLabel)) } } }); } else { if (Enabled) { // if the view was already initialized and is enabled, just update the label since the index might have changed. string tipText = _incrementalValueHasChanged ? "" : " " + _tipText; _sliderLabel.Text = GetLabelText(index) + (_displaySliderValue && _incrementalValueHasChanged ? " " + _incrementalValue.ToString() : "") + tipText; } else { // if the view was already initialized but is not enabled and has never been interacted with, there should be no tip text since the user can't do anything with the slider. if (!_incrementalValueHasChanged) { _slider.Value = _minimum; _sliderLabel.Text = GetLabelText(index) + " No value selected."; } } } return base.GetView(index); } private double GetIncrementalValue(double value) { return Math.Round(value / _increment) * _increment; } public override string ToString() { return base.ToString() + " -- " + _minimum + " to " + _maximum; } } }
// // - ProviderRegistrationContext.cs - // // Copyright 2013 Carbonfrost Systems, Inc. (http://carbonfrost.com) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Carbonfrost.Commons.ComponentModel; namespace Carbonfrost.Commons.Shared.Runtime { public class ProviderRegistrationContext { readonly List<ProviderValueSource> result = new List<ProviderValueSource>(); readonly List<Type> roots = new List<Type>(); public Assembly Assembly { get; private set; } internal ProviderRegistrationContext(Assembly assembly) { this.Assembly = assembly; } // TODO Validate root providers // TODO Custom client implementations could register providers and root providers out of order (uncommon) internal IEnumerable<Type> EnumerateRoots() { return roots; } public void DefineRootProvider(Type providerType) { if (providerType == null) throw new ArgumentNullException("providerType"); roots.Add(providerType); } public void DefineProvider(QualifiedName name, Type providerType, Type providerInstanceType, object metadata = null) { if (providerType == null) throw new ArgumentNullException("providerType"); if (providerInstanceType == null) throw new ArgumentNullException("providerInstanceType"); if (providerInstanceType.IsAbstract || !providerType.IsAssignableFrom(providerInstanceType)) throw RuntimeFailure.InvalidProviderInstanceType("providerInstanceType"); var qn = GetName(name, providerInstanceType, providerInstanceType.Name); var tr = new ProviderType(providerInstanceType, providerType, qn); tr.Metadata = ProviderMetadataWrapper.Create(metadata); tr.Metadata.Source = tr; result.Add(tr); } public void DefineProvider(QualifiedName name, Type providerType, FieldInfo field, object metadata = null) { if (providerType == null) throw new ArgumentNullException("providerType"); if (field == null) throw new ArgumentNullException("field"); if (!field.IsStatic || !providerType.IsAssignableFrom(field.FieldType)) { throw RuntimeFailure.InvalidProviderFieldOrMethod("field"); } var qn = GetName(name, field.DeclaringType, field.Name); var fieldResult = new ProviderField(field, providerType, qn); fieldResult.Metadata = ProviderMetadataWrapper.Create(metadata); fieldResult.Metadata.Source = fieldResult; result.Add(fieldResult); } public void DefineProvider(QualifiedName name, Type providerType, MethodInfo factoryMethod, object metadata = null) { if (providerType == null) throw new ArgumentNullException("providerType"); if (factoryMethod == null) throw new ArgumentNullException("factoryMethod"); if (!factoryMethod.IsStatic || !providerType.IsAssignableFrom(factoryMethod.ReturnType)) { throw RuntimeFailure.InvalidProviderFieldOrMethod("factoryMethod"); } var qn = GetName(name, factoryMethod.DeclaringType, factoryMethod.Name); var methodResult = new ProviderMethod(factoryMethod, providerType, name); methodResult.Metadata = ProviderMetadataWrapper.Create(metadata); methodResult.Metadata.Source = methodResult; result.Add(methodResult); } static QualifiedName GetName(QualifiedName userName, Type declaringType, string memberName) { return userName ?? Adaptable.GetQualifiedName(declaringType) .ChangeLocalName(Utility.Camel(memberName)); } internal IEnumerable<ProviderValueSource> EnumerateValueSources() { return result; } sealed class ProviderField : ProviderValueSource { private readonly FieldInfo field; public ProviderField(FieldInfo field, Type providerType, QualifiedName key) : base(providerType, key) { this.field = field; } public override MemberInfo Member { get { return this.field; } } public override Type ValueType { get { return GetValue().GetType(); } } public override object GetValue() { return field.GetValue(null); } public override bool IsValue(object instance) { return field.IsInitOnly && object.ReferenceEquals(instance, GetValue()); } public override object Activate(IEnumerable<KeyValuePair<string, object>> arguments, IPopulateComponentCallback callback, IServiceProvider services) { object result = GetValue(); Activation.Initialize(result, arguments, callback, services); return result; } } sealed class ProviderMethod : ProviderValueSource { private readonly MethodInfo method; private ActivationHelper helper; public ProviderMethod(MethodInfo method, Type providerType, QualifiedName key) : base(providerType, key) { this.method = method; } public override MemberInfo Member { get { return this.method; } } public override Type ValueType { get { return method.ReturnType; } } public override bool IsValue(object instance) { // Non-singletons return false; } public override object GetValue() { return Activate(null, null, null); } public override object Activate(IEnumerable<KeyValuePair<string, object>> arguments, IPopulateComponentCallback callback, IServiceProvider services) { if (helper == null) helper = new ActivationHelper(method); var instance = helper.CreateInstance(method.ReturnType, arguments, callback, services); return instance; } sealed class ActivationHelper : DefaultActivationFactory { // We have a method, so we can't use pure Activation private readonly MethodInfo method; public ActivationHelper(MethodInfo method) { this.method = method; } protected override MethodBase GetActivationConstructor(Type type) { return method; } } } sealed class ProviderType : ProviderValueSource { private readonly Type type; public ProviderType(Type type, Type providerType, QualifiedName key) : base(providerType, key) { this.type = type; } public override Type ValueType { get { return type; } } public override MemberInfo Member { get { return this.type; } } public override Assembly Assembly { get { return this.type.Assembly; } } public override bool IsValue(object instance) { return ValueType == instance.GetType(); } public override object GetValue() { return Activation.CreateInstance(type); } public override object Activate(IEnumerable<KeyValuePair<string, object>> arguments, IPopulateComponentCallback callback, IServiceProvider services) { return Activation.CreateInstance(type, arguments, callback, services); } } } }
// // $Id: seems.cs 11022 2017-07-03 17:43:28Z chambm $ // // // Original author: Matt Chambers <matt.chambers .@. vanderbilt.edu> // // Copyright 2009 Vanderbilt University - Nashville, TN 37232 // // 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.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Diagnostics; using System.Threading; using System.IO; using System.Collections.Specialized; using System.Xml; using System.Text.RegularExpressions; using pwiz.CLI; using pwiz.CLI.msdata; using JWC; using Microsoft.Win32; using DigitalRune.Windows.Docking; using SpyTools; using CommandLine.Utility; namespace seems { public partial class seemsForm : Form { public static string Version = "0.5"; public static string LastModified = "2/10/2009"; private bool isLoaded = false; private OpenDataSourceDialog browseToFileDialog; private MruStripMenu recentFilesMenu; private string seemsRegistryLocation = "Software\\SeeMS"; private RegistryKey seemsRegistryKey; private Manager manager; public Manager Manager { get { return manager; } } public DockPanel DockPanel { get { return dockPanel; } } public GraphForm CurrentGraphForm { get { return Manager.CurrentGraphForm; } } public ToolStrip ToolStrip1 { get { return toolStrip1; } } public StatusStrip StatusStrip1 { get { return statusStrip1; } } public ToolStripStatusLabel StatusLabel { get { return toolStripStatusLabel1; } } public ToolStripProgressBar StatusProgressBar { get { return toolStripProgressBar1; } } public ToolStripButton DataProcessingButton { get { return dataProcessingButton; } } public ToolStripButton AnnotationButton { get { return annotationButton; } } public seemsForm() { InitializeComponent(); ToolStripManager.RenderMode = ToolStripManagerRenderMode.Professional; this.Load += seems_Load; this.Resize += seems_Resize; this.LocationChanged += seems_LocationChanged; seemsRegistryKey = Registry.CurrentUser.OpenSubKey( seemsRegistryLocation ); if( seemsRegistryKey != null ) seemsRegistryKey.Close(); recentFilesMenu = new MruStripMenu( recentFilesFileMenuItem, new MruStripMenu.ClickedHandler( recentFilesFileMenuItem_Click ), seemsRegistryLocation + "\\Recent File List", true ); browseToFileDialog = new OpenDataSourceDialog(); browseToFileDialog.InitialDirectory = "C:\\"; DockPanelManager.RenderMode = DockPanelRenderMode.VisualStyles; manager = new Manager(dockPanel); Manager.GraphFormGotFocus += new GraphFormGotFocusHandler(Manager_GraphFormGotFocus); Manager.LoadDataSourceProgress += new LoadDataSourceProgressEventHandler(Manager_LoadDataSourceProgress); } void Manager_GraphFormGotFocus (Manager sender, GraphForm graphForm) { if (graphForm.FocusedPane != null && graphForm.FocusedItem.Tag is MassSpectrum) { AnnotationButton.Enabled = true; DataProcessingButton.Enabled = true; } else { AnnotationButton.Enabled = false; DataProcessingButton.Enabled = false; } } private void seems_Load( object sender, EventArgs e ) { this.StartPosition = FormStartPosition.Manual; this.Location = Properties.Settings.Default.MainFormLocation; this.Size = Properties.Settings.Default.MainFormSize; this.WindowState = Properties.Settings.Default.MainFormWindowState; isLoaded = true; } private void seems_LocationChanged( object sender, EventArgs e ) { if( isLoaded && this.WindowState == FormWindowState.Normal ) Properties.Settings.Default.MainFormLocation = this.Location; } private void seems_FormClosing( object sender, FormClosingEventArgs e ) { Properties.Settings.Default.MainFormLocation = this.Location; Properties.Settings.Default.MainFormSize = this.Size; Properties.Settings.Default.MainFormWindowState = this.WindowState; Properties.Settings.Default.Save(); Environment.Exit(0); /*foreach( DataSourceMap.MapPair sourceItr in dataSources ) if( sourceItr.Value != null && sourceItr.Value.first != null && sourceItr.Value.first.MSDataFile != null ) sourceItr.Value.first.MSDataFile.Dispose();*/ } public void setFileControls( bool enabled ) { // this is no longer relevant i think } public void setScanControls( bool enabled ) { // if on MS1, enable mass fingerprint // if on MS2+, enable fragmentation // if on MS that is centroided in the file, disable peak processing // if on SRM, disable annotation } private void openFile( string filepath ) { // update recent files list recentFilesMenu.AddFile( filepath, Path.GetFileName( filepath ) ); recentFilesMenu.SaveToRegistry(); Manager.OpenFile(filepath); } private delegate void ParseArgsCallback (string[] args); public void ParseArgs (string[] args) { if (InvokeRequired) { ParseArgsCallback d = new ParseArgsCallback(ParseArgs); Invoke(d, new object[] { args }); return; } try { Arguments argParser = new Arguments(args); if (argParser["help"] != null || argParser["h"] != null || argParser["?"] != null) { Console.WriteLine("TODO"); Close(); return; } BringToFront(); Focus(); Activate(); Show(); Application.DoEvents(); string datasource = null; foreach (string arg in args) if (!arg.StartsWith("--index") && !arg.StartsWith("--id") && !arg.StartsWith("--annotation")) { datasource = arg; break; } IAnnotation annotation = null; if (argParser["annotation"] != null) annotation = AnnotationFactory.ParseArgument(argParser["annotation"]); if (datasource != null) { if (argParser["index"] != null) { Manager.OpenFile(datasource, Convert.ToInt32(argParser["index"]), annotation); } else if (argParser["id"] != null) { Manager.OpenFile(datasource, argParser["id"], annotation); } else Manager.OpenFile(datasource); } } catch (Exception ex) { string message = ex.Message; if (ex.InnerException != null) message += "\n\nAdditional information: " + ex.InnerException.Message; MessageBox.Show(message, "Error parsing command line arguments", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0, false); } } public void Manager_LoadDataSourceProgress (Manager sender, string status, int percentage, CancelEventArgs e) { if (toolStrip1.InvokeRequired) { LoadDataSourceProgressEventHandler d = new LoadDataSourceProgressEventHandler(Manager_LoadDataSourceProgress); Invoke(d, new object[] { sender, status, percentage, e }); } else { if (toolStrip1.IsDisposed) { e.Cancel = true; return; } if (status.Length > 0) { toolStripStatusLabel1.Text = status; toolStripStatusLabel1.Visible = true; } else toolStripStatusLabel1.Visible = false; switch (percentage) { case 100: toolStripProgressBar1.Visible = false; break; default: toolStripProgressBar1.Visible = true; toolStripProgressBar1.Minimum = 0; toolStripProgressBar1.Maximum = 100; toolStripProgressBar1.Value = percentage; break; } toolStrip1.Refresh(); } } private void openFile_Click( object sender, EventArgs e ) { if( browseToFileDialog.ShowDialog() == DialogResult.OK ) { foreach( string dataSource in browseToFileDialog.DataSources ) openFile( dataSource ); } } private void cascadeWindowMenuItem_Click( object sender, EventArgs e ) { LayoutMdi( MdiLayout.Cascade ); } private void tileHorizontalWindowMenuItem_Click( object sender, EventArgs e ) { LayoutMdi( MdiLayout.TileHorizontal ); } private void tileVerticalWindowMenuItem_Click( object sender, EventArgs e ) { LayoutMdi( MdiLayout.TileVertical ); } private void arrangeIconsWindowMenuItem_Click( object sender, EventArgs e ) { LayoutMdi( MdiLayout.ArrangeIcons ); } private void closeAllWindowMenuItem_Click( object sender, EventArgs e ) { foreach( Form f in MdiChildren ) f.Close(); } private void recentFilesFileMenuItem_Click( int index, string filepath ) { openFile( filepath ); } private void exitFileMenuItem_Click( object sender, EventArgs e ) { Application.Exit(); } private void aboutHelpMenuItem_Click( object sender, EventArgs e ) { AboutForm form = new AboutForm(); form.ShowDialog(); } // workaround for MDI Window list bug private void windowToolStripMenuItem_DropDownOpening( object sender, EventArgs e ) { if( ActiveMdiChild != null ) { Form activeMdiChild = ActiveMdiChild; ActivateMdiChild( null ); ActivateMdiChild( activeMdiChild ); } } private void toolStripPanel1_Layout( object sender, LayoutEventArgs e ) { dockPanel.Location = new Point(0, toolStripPanel1.Height); dockPanel.Height = ClientSize.Height - toolStripPanel2.Height - toolStripPanel1.Height; dockPanel.Width = ClientSize.Width; } private void toolStripPanel2_Layout( object sender, LayoutEventArgs e ) { dockPanel.Location = new Point(0, toolStripPanel1.Height); dockPanel.Height = ClientSize.Height - toolStripPanel2.Height - toolStripPanel1.Height; dockPanel.Width = ClientSize.Width; } private void seems_ResizeBegin( object sender, EventArgs e ) { if (CurrentGraphForm != null && CurrentGraphForm.WindowState == FormWindowState.Maximized) { CurrentGraphForm.SuspendLayout(); CurrentGraphForm.ZedGraphControl.Visible = false; } } private void seems_Resize( object sender, EventArgs e ) { dockPanel.Location = new Point(0, toolStripPanel1.Height); dockPanel.Height = ClientSize.Height - toolStripPanel2.Height - toolStripPanel1.Height; dockPanel.Width = ClientSize.Width; } private void seems_ResizeEnd( object sender, EventArgs e ) { if( isLoaded && this.WindowState != FormWindowState.Minimized ) { if( this.WindowState == FormWindowState.Normal ) Properties.Settings.Default.MainFormSize = this.Size; Properties.Settings.Default.MainFormWindowState = this.WindowState; } if (CurrentGraphForm != null && CurrentGraphForm.WindowState == FormWindowState.Maximized) { CurrentGraphForm.ResumeLayout(); CurrentGraphForm.ZedGraphControl.Visible = true; CurrentGraphForm.Refresh(); } } private void dataProcessingButton_Click( object sender, EventArgs e ) { Manager.ShowDataProcessing(); } private void previewAsMzMLToolStripMenuItem_Click( object sender, EventArgs e ) { Manager.ShowCurrentSourceAsMzML(); } private void annotationButton_Click( object sender, EventArgs e ) { Manager.ShowAnnotationForm(); } private void eventLogToolStripMenuItem_Click( object sender, EventArgs e ) { //eventLog.Show(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void RoundToNearestIntegerSingle() { var test = new SimpleUnaryOpTest__RoundToNearestIntegerSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.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 (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.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 (Avx.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 (Avx.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 (Avx.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__RoundToNearestIntegerSingle { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (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<Single, 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 Vector256<Single> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__RoundToNearestIntegerSingle testClass) { var result = Avx.RoundToNearestInteger(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__RoundToNearestIntegerSingle testClass) { fixed (Vector256<Single>* pFld1 = &_fld1) { var result = Avx.RoundToNearestInteger( Avx.LoadVector256((Single*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector256<Single> _clsVar1; private Vector256<Single> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__RoundToNearestIntegerSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); } public SimpleUnaryOpTest__RoundToNearestIntegerSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx.RoundToNearestInteger( Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx.RoundToNearestInteger( Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx.RoundToNearestInteger( Avx.LoadAlignedVector256((Single*)(_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(Avx).GetMethod(nameof(Avx.RoundToNearestInteger), new Type[] { typeof(Vector256<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx).GetMethod(nameof(Avx.RoundToNearestInteger), new Type[] { typeof(Vector256<Single>) }) .Invoke(null, new object[] { Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx).GetMethod(nameof(Avx.RoundToNearestInteger), new Type[] { typeof(Vector256<Single>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx.RoundToNearestInteger( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Single>* pClsVar1 = &_clsVar1) { var result = Avx.RoundToNearestInteger( Avx.LoadVector256((Single*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr); var result = Avx.RoundToNearestInteger(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)); var result = Avx.RoundToNearestInteger(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)); var result = Avx.RoundToNearestInteger(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__RoundToNearestIntegerSingle(); var result = Avx.RoundToNearestInteger(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__RoundToNearestIntegerSingle(); fixed (Vector256<Single>* pFld1 = &test._fld1) { var result = Avx.RoundToNearestInteger( Avx.LoadVector256((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx.RoundToNearestInteger(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Single>* pFld1 = &_fld1) { var result = Avx.RoundToNearestInteger( Avx.LoadVector256((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx.RoundToNearestInteger(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 = Avx.RoundToNearestInteger( Avx.LoadVector256((Single*)(&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(Vector256<Single> op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(MathF.Round(firstOp[0], MidpointRounding.AwayFromZero))) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(MathF.Round(firstOp[i], MidpointRounding.AwayFromZero))) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.RoundToNearestInteger)}<Single>(Vector256<Single>): {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.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace SouthwindRepository { /// <summary> /// Strongly-typed collection for the Supplier class. /// </summary> [Serializable] public partial class SupplierCollection : RepositoryList<Supplier, SupplierCollection> { public SupplierCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>SupplierCollection</returns> public SupplierCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { Supplier o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the suppliers table. /// </summary> [Serializable] public partial class Supplier : RepositoryRecord<Supplier>, IRecordBase { #region .ctors and Default Settings public Supplier() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public Supplier(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("suppliers", TableType.Table, DataService.GetInstance("SouthwindRepository")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @""; //columns TableSchema.TableColumn colvarSupplierID = new TableSchema.TableColumn(schema); colvarSupplierID.ColumnName = "SupplierID"; colvarSupplierID.DataType = DbType.Int32; colvarSupplierID.MaxLength = 10; colvarSupplierID.AutoIncrement = true; colvarSupplierID.IsNullable = false; colvarSupplierID.IsPrimaryKey = true; colvarSupplierID.IsForeignKey = false; colvarSupplierID.IsReadOnly = false; colvarSupplierID.DefaultSetting = @""; colvarSupplierID.ForeignKeyTableName = ""; schema.Columns.Add(colvarSupplierID); TableSchema.TableColumn colvarCompanyName = new TableSchema.TableColumn(schema); colvarCompanyName.ColumnName = "CompanyName"; colvarCompanyName.DataType = DbType.String; colvarCompanyName.MaxLength = 40; colvarCompanyName.AutoIncrement = false; colvarCompanyName.IsNullable = false; colvarCompanyName.IsPrimaryKey = false; colvarCompanyName.IsForeignKey = true; colvarCompanyName.IsReadOnly = false; colvarCompanyName.DefaultSetting = @""; colvarCompanyName.ForeignKeyTableName = ""; schema.Columns.Add(colvarCompanyName); TableSchema.TableColumn colvarContactName = new TableSchema.TableColumn(schema); colvarContactName.ColumnName = "ContactName"; colvarContactName.DataType = DbType.String; colvarContactName.MaxLength = 30; colvarContactName.AutoIncrement = false; colvarContactName.IsNullable = true; colvarContactName.IsPrimaryKey = false; colvarContactName.IsForeignKey = false; colvarContactName.IsReadOnly = false; colvarContactName.DefaultSetting = @""; colvarContactName.ForeignKeyTableName = ""; schema.Columns.Add(colvarContactName); TableSchema.TableColumn colvarContactTitle = new TableSchema.TableColumn(schema); colvarContactTitle.ColumnName = "ContactTitle"; colvarContactTitle.DataType = DbType.String; colvarContactTitle.MaxLength = 30; colvarContactTitle.AutoIncrement = false; colvarContactTitle.IsNullable = true; colvarContactTitle.IsPrimaryKey = false; colvarContactTitle.IsForeignKey = false; colvarContactTitle.IsReadOnly = false; colvarContactTitle.DefaultSetting = @""; colvarContactTitle.ForeignKeyTableName = ""; schema.Columns.Add(colvarContactTitle); TableSchema.TableColumn colvarAddress = new TableSchema.TableColumn(schema); colvarAddress.ColumnName = "Address"; colvarAddress.DataType = DbType.String; colvarAddress.MaxLength = 60; colvarAddress.AutoIncrement = false; colvarAddress.IsNullable = true; colvarAddress.IsPrimaryKey = false; colvarAddress.IsForeignKey = false; colvarAddress.IsReadOnly = false; colvarAddress.DefaultSetting = @""; colvarAddress.ForeignKeyTableName = ""; schema.Columns.Add(colvarAddress); TableSchema.TableColumn colvarCity = new TableSchema.TableColumn(schema); colvarCity.ColumnName = "City"; colvarCity.DataType = DbType.String; colvarCity.MaxLength = 15; colvarCity.AutoIncrement = false; colvarCity.IsNullable = true; colvarCity.IsPrimaryKey = false; colvarCity.IsForeignKey = false; colvarCity.IsReadOnly = false; colvarCity.DefaultSetting = @""; colvarCity.ForeignKeyTableName = ""; schema.Columns.Add(colvarCity); TableSchema.TableColumn colvarRegion = new TableSchema.TableColumn(schema); colvarRegion.ColumnName = "Region"; colvarRegion.DataType = DbType.String; colvarRegion.MaxLength = 15; colvarRegion.AutoIncrement = false; colvarRegion.IsNullable = true; colvarRegion.IsPrimaryKey = false; colvarRegion.IsForeignKey = false; colvarRegion.IsReadOnly = false; colvarRegion.DefaultSetting = @""; colvarRegion.ForeignKeyTableName = ""; schema.Columns.Add(colvarRegion); TableSchema.TableColumn colvarPostalCode = new TableSchema.TableColumn(schema); colvarPostalCode.ColumnName = "PostalCode"; colvarPostalCode.DataType = DbType.String; colvarPostalCode.MaxLength = 10; colvarPostalCode.AutoIncrement = false; colvarPostalCode.IsNullable = true; colvarPostalCode.IsPrimaryKey = false; colvarPostalCode.IsForeignKey = true; colvarPostalCode.IsReadOnly = false; colvarPostalCode.DefaultSetting = @""; colvarPostalCode.ForeignKeyTableName = ""; schema.Columns.Add(colvarPostalCode); TableSchema.TableColumn colvarCountry = new TableSchema.TableColumn(schema); colvarCountry.ColumnName = "Country"; colvarCountry.DataType = DbType.String; colvarCountry.MaxLength = 15; colvarCountry.AutoIncrement = false; colvarCountry.IsNullable = true; colvarCountry.IsPrimaryKey = false; colvarCountry.IsForeignKey = false; colvarCountry.IsReadOnly = false; colvarCountry.DefaultSetting = @""; colvarCountry.ForeignKeyTableName = ""; schema.Columns.Add(colvarCountry); TableSchema.TableColumn colvarPhone = new TableSchema.TableColumn(schema); colvarPhone.ColumnName = "Phone"; colvarPhone.DataType = DbType.String; colvarPhone.MaxLength = 24; colvarPhone.AutoIncrement = false; colvarPhone.IsNullable = true; colvarPhone.IsPrimaryKey = false; colvarPhone.IsForeignKey = false; colvarPhone.IsReadOnly = false; colvarPhone.DefaultSetting = @""; colvarPhone.ForeignKeyTableName = ""; schema.Columns.Add(colvarPhone); TableSchema.TableColumn colvarFax = new TableSchema.TableColumn(schema); colvarFax.ColumnName = "Fax"; colvarFax.DataType = DbType.String; colvarFax.MaxLength = 24; colvarFax.AutoIncrement = false; colvarFax.IsNullable = true; colvarFax.IsPrimaryKey = false; colvarFax.IsForeignKey = false; colvarFax.IsReadOnly = false; colvarFax.DefaultSetting = @""; colvarFax.ForeignKeyTableName = ""; schema.Columns.Add(colvarFax); TableSchema.TableColumn colvarHomePage = new TableSchema.TableColumn(schema); colvarHomePage.ColumnName = "HomePage"; colvarHomePage.DataType = DbType.String; colvarHomePage.MaxLength = 0; colvarHomePage.AutoIncrement = false; colvarHomePage.IsNullable = true; colvarHomePage.IsPrimaryKey = false; colvarHomePage.IsForeignKey = false; colvarHomePage.IsReadOnly = false; colvarHomePage.DefaultSetting = @""; colvarHomePage.ForeignKeyTableName = ""; schema.Columns.Add(colvarHomePage); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["SouthwindRepository"].AddSchema("suppliers",schema); } } #endregion #region Props [XmlAttribute("SupplierID")] [Bindable(true)] public int SupplierID { get { return GetColumnValue<int>(Columns.SupplierID); } set { SetColumnValue(Columns.SupplierID, value); } } [XmlAttribute("CompanyName")] [Bindable(true)] public string CompanyName { get { return GetColumnValue<string>(Columns.CompanyName); } set { SetColumnValue(Columns.CompanyName, value); } } [XmlAttribute("ContactName")] [Bindable(true)] public string ContactName { get { return GetColumnValue<string>(Columns.ContactName); } set { SetColumnValue(Columns.ContactName, value); } } [XmlAttribute("ContactTitle")] [Bindable(true)] public string ContactTitle { get { return GetColumnValue<string>(Columns.ContactTitle); } set { SetColumnValue(Columns.ContactTitle, value); } } [XmlAttribute("Address")] [Bindable(true)] public string Address { get { return GetColumnValue<string>(Columns.Address); } set { SetColumnValue(Columns.Address, value); } } [XmlAttribute("City")] [Bindable(true)] public string City { get { return GetColumnValue<string>(Columns.City); } set { SetColumnValue(Columns.City, value); } } [XmlAttribute("Region")] [Bindable(true)] public string Region { get { return GetColumnValue<string>(Columns.Region); } set { SetColumnValue(Columns.Region, value); } } [XmlAttribute("PostalCode")] [Bindable(true)] public string PostalCode { get { return GetColumnValue<string>(Columns.PostalCode); } set { SetColumnValue(Columns.PostalCode, value); } } [XmlAttribute("Country")] [Bindable(true)] public string Country { get { return GetColumnValue<string>(Columns.Country); } set { SetColumnValue(Columns.Country, value); } } [XmlAttribute("Phone")] [Bindable(true)] public string Phone { get { return GetColumnValue<string>(Columns.Phone); } set { SetColumnValue(Columns.Phone, value); } } [XmlAttribute("Fax")] [Bindable(true)] public string Fax { get { return GetColumnValue<string>(Columns.Fax); } set { SetColumnValue(Columns.Fax, value); } } [XmlAttribute("HomePage")] [Bindable(true)] public string HomePage { get { return GetColumnValue<string>(Columns.HomePage); } set { SetColumnValue(Columns.HomePage, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region Typed Columns public static TableSchema.TableColumn SupplierIDColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn CompanyNameColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn ContactNameColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn ContactTitleColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn AddressColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn CityColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn RegionColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn PostalCodeColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn CountryColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn PhoneColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn FaxColumn { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn HomePageColumn { get { return Schema.Columns[11]; } } #endregion #region Columns Struct public struct Columns { public static string SupplierID = @"SupplierID"; public static string CompanyName = @"CompanyName"; public static string ContactName = @"ContactName"; public static string ContactTitle = @"ContactTitle"; public static string Address = @"Address"; public static string City = @"City"; public static string Region = @"Region"; public static string PostalCode = @"PostalCode"; public static string Country = @"Country"; public static string Phone = @"Phone"; public static string Fax = @"Fax"; public static string HomePage = @"HomePage"; } #endregion #region Update PK Collections #endregion #region Deep Save #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 FSharpWebSite.Areas.HelpPage.ModelDescriptions; using FSharpWebSite.Areas.HelpPage.Models; namespace FSharpWebSite.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. // Licensed under the MIT License. using Newtonsoft.Json; using System.Windows.Forms; using MigAz.Azure.Models; using System.Collections.Generic; using System.IO; using System; using System.Threading.Tasks; using MigAz.Azure.Asm; using MigAz.Azure.Arm; using MigAz.Azure; using MigAz.Azure.Core.Interface; using MigAz.Azure.Core; namespace MigAz.Providers { class UISaveSelectionProvider : ISaveSelectionProvider { string filePath; List<SaveSelection> saveSelections; public UISaveSelectionProvider() { string filedir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\MigAz"; if (!Directory.Exists(filedir)) { Directory.CreateDirectory(filedir); } filePath = filedir + "\\MigAz-SaveSelection.json"; } public async Task Save(Guid subscriptionId, List<TreeNode> selectedNodes) { string jsontext = String.Empty; try { StreamReader saveSelectionReader = new StreamReader(filePath); jsontext = saveSelectionReader.ReadToEnd(); saveSelectionReader.Close(); saveSelections = JsonConvert.DeserializeObject<List<SaveSelection>>(jsontext); // If save selection for this subscription alredy exists, remove it if (saveSelections.Exists(x => x.SubscriptionId == subscriptionId)) { saveSelections.Remove(saveSelections.Find(x => x.SubscriptionId == subscriptionId)); } } catch { // If file does not exist, or invalid, starts a new object saveSelections = new List<SaveSelection>(); } SaveSelection saveSelection = new SaveSelection(); saveSelection.SubscriptionId = subscriptionId; saveSelection.VirtualNetworks = new List<SaveSelectionVirtualNetwork>(); saveSelection.StorageAccounts = new List<SaveSelectioStorageAccount>(); saveSelection.VirtualMachines = new List<SaveSelectionVirtualMachine>(); if (selectedNodes != null) { foreach (TreeNode treeNode in selectedNodes) { if (treeNode.Tag != null) { Type tagType = treeNode.Tag.GetType(); if (tagType == typeof(Azure.Asm.VirtualNetwork)) { Azure.Asm.VirtualNetwork asmVirtualNetwork = (Azure.Asm.VirtualNetwork)treeNode.Tag; SaveSelectionVirtualNetwork saveSelectionVirtualNetwork = new SaveSelectionVirtualNetwork(); saveSelectionVirtualNetwork.VirtualNetworkName = asmVirtualNetwork.Name; saveSelection.VirtualNetworks.Add(saveSelectionVirtualNetwork); } else if (tagType == typeof(Azure.MigrationTarget.StorageAccount)) { Azure.MigrationTarget.StorageAccount storageAccount = (Azure.MigrationTarget.StorageAccount)treeNode.Tag; SaveSelectioStorageAccount saveSelectionStorageAccount = new SaveSelectioStorageAccount(); saveSelectionStorageAccount.StorageAccountName = storageAccount.SourceAccount.Name; saveSelectionStorageAccount.TargetStorageAccountName = storageAccount.TargetName; saveSelection.StorageAccounts.Add(saveSelectionStorageAccount); } else if (tagType == typeof(Azure.MigrationTarget.VirtualMachine)) { Azure.MigrationTarget.VirtualMachine virtualMachine = (Azure.MigrationTarget.VirtualMachine)treeNode.Tag; if (virtualMachine.Source.GetType() == typeof(Azure.Asm.VirtualMachine)) { Azure.Asm.VirtualMachine asmVirtualMachine = (Azure.Asm.VirtualMachine)virtualMachine.Source; SaveSelectionVirtualMachine saveSelectionVirtualMachine = new SaveSelectionVirtualMachine(); saveSelectionVirtualMachine.CloudService = asmVirtualMachine.CloudServiceName; saveSelectionVirtualMachine.VirtualMachine = asmVirtualMachine.RoleName; // todo now asap //if (virtualMachine.TargetVirtualNetwork != null) // saveSelectionVirtualMachine.TargetVirtualNetwork = virtualMachine.TargetVirtualNetwork.Id; //if (virtualMachine.TargetSubnet != null) // saveSelectionVirtualMachine.TargetSubnet = virtualMachine.TargetSubnet.Id; ////Add OS Disk Target Storage Account //if (asmVirtualMachine.OSVirtualHardDisk.TargetStorageAccount != null) // saveSelectionVirtualMachine.TargetDiskStorageAccounts.Add(asmVirtualMachine.OSVirtualHardDisk.DiskName, asmVirtualMachine.OSVirtualHardDisk.TargetStorageAccount.ToString()); //// Add OS Disk Target Storage Account //foreach (Azure.Asm.Disk asmDataDisk in asmVirtualMachine.DataDisks) //{ // if (asmDataDisk.TargetStorageAccount != null) // saveSelectionVirtualMachine.TargetDiskStorageAccounts.Add(asmDataDisk.DiskName, asmDataDisk.TargetStorageAccount.ToString()); //} saveSelection.VirtualMachines.Add(saveSelectionVirtualMachine); } } } } } saveSelections.Add(saveSelection); // save blob copy details file jsontext = JsonConvert.SerializeObject(saveSelections, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore }); StreamWriter saveSelectionWriter = new StreamWriter(filePath); saveSelectionWriter.Write(jsontext); saveSelectionWriter.Close(); } public async Task Read(Guid subscriptionId, AzureRetriever sourceAzureRetreiver, AzureRetriever targetAzureRetreiver, TreeView treeView, TargetSettings targetSettings) { try { StreamReader saveSelectionReader = new StreamReader(filePath); string jsontext = saveSelectionReader.ReadToEnd(); saveSelectionReader.Close(); saveSelections = JsonConvert.DeserializeObject<List<SaveSelection>>(jsontext); } catch { // If file does not exist, or invalid, starts a new object saveSelections = new List<SaveSelection>(); } if (saveSelections.Exists(x => x.SubscriptionId == subscriptionId)) { SaveSelection saveSelection = saveSelections.Find(x => x.SubscriptionId == subscriptionId); foreach (SaveSelectionVirtualNetwork saveSelectionVirtualNetwork in saveSelection.VirtualNetworks) { foreach (TreeNode treeNode in treeView.Nodes.Find(saveSelectionVirtualNetwork.VirtualNetworkName, true)) { if (treeNode.Tag.GetType() == typeof(Azure.Asm.VirtualNetwork)) { Azure.Asm.VirtualNetwork asmVirtualNetwork = (Azure.Asm.VirtualNetwork)treeNode.Tag; treeNode.Checked = true; } } } foreach (SaveSelectioStorageAccount saveSelectionStorageAccount in saveSelection.StorageAccounts) { foreach (TreeNode treeNode in treeView.Nodes.Find(saveSelectionStorageAccount.StorageAccountName, true)) { if (treeNode.Tag.GetType() == typeof(Azure.Asm.StorageAccount)) { Azure.MigrationTarget.StorageAccount storageAccount = (Azure.MigrationTarget.StorageAccount)treeNode.Tag; if (saveSelectionStorageAccount.TargetStorageAccountName.Length > 0) // We aren't going to reload a blank name, should it occur, as a name is required storageAccount.SetTargetName(saveSelectionStorageAccount.TargetStorageAccountName, targetSettings); treeNode.Checked = true; } } } foreach (SaveSelectionVirtualMachine saveSelectionVirtualMachine in saveSelection.VirtualMachines) { foreach (TreeNode virtualMachineNode in treeView.Nodes.Find(saveSelectionVirtualMachine.VirtualMachine, true)) { if (virtualMachineNode.Tag != null) { if (virtualMachineNode.Tag.GetType() == typeof(Azure.Asm.VirtualMachine)) { Azure.Asm.VirtualMachine asmVirtualMachine = (Azure.Asm.VirtualMachine)virtualMachineNode.Tag; if (asmVirtualMachine.CloudServiceName == saveSelectionVirtualMachine.CloudService && asmVirtualMachine.RoleName == saveSelectionVirtualMachine.VirtualMachine) { // todo now asap //asmVirtualMachine.TargetVirtualNetwork = SeekVirtualNetwork(saveSelectionVirtualMachine.TargetVirtualNetwork, await sourceAzureRetreiver.GetAzureAsmVirtualNetworks(), await targetAzureRetreiver.GetAzureARMVirtualNetworks()); //asmVirtualMachine.TargetSubnet = SeekSubnet(saveSelectionVirtualMachine.TargetSubnet, asmVirtualMachine.TargetVirtualNetwork); //if (saveSelectionVirtualMachine.TargetDiskStorageAccounts.ContainsKey(asmVirtualMachine.OSVirtualHardDisk.DiskName)) // asmVirtualMachine.OSVirtualHardDisk.TargetStorageAccount = SeekStorageAccount(saveSelectionVirtualMachine.TargetDiskStorageAccounts[asmVirtualMachine.OSVirtualHardDisk.DiskName].ToString(), await sourceAzureRetreiver.GetAzureAsmStorageAccounts(), await targetAzureRetreiver.GetAzureARMStorageAccounts()); //foreach (Azure.Asm.Disk asmDataDisk in asmVirtualMachine.DataDisks) //{ // if (saveSelectionVirtualMachine.TargetDiskStorageAccounts.ContainsKey(asmDataDisk.DiskName)) // asmDataDisk.TargetStorageAccount = SeekStorageAccount(saveSelectionVirtualMachine.TargetDiskStorageAccounts[asmDataDisk.DiskName].ToString(), await sourceAzureRetreiver.GetAzureAsmStorageAccounts(), await targetAzureRetreiver.GetAzureARMStorageAccounts()); //} virtualMachineNode.Checked = true; } } } } } } } //private IVirtualNetwork SeekVirtualNetwork(string id, List<Azure.Asm.VirtualNetwork> asmVirtualNetworks, List<Azure.Arm.VirtualNetwork> armVirtualNetworks) //{ // if (asmVirtualNetworks != null) // { // foreach (Azure.Asm.VirtualNetwork asmVirtualNetwork in asmVirtualNetworks) // { // if (asmVirtualNetwork.Id == id) // return asmVirtualNetwork; // } // } // if (armVirtualNetworks != null) // { // foreach (Azure.Arm.VirtualNetwork armVirtualNetwork in armVirtualNetworks) // { // if (armVirtualNetwork.Id == id) // return armVirtualNetwork; // } // } // return null; //} //private ISubnet SeekSubnet(string id, IVirtualNetwork virtualNetwork) //{ // if (virtualNetwork != null) // { // foreach (ISubnet subnet in virtualNetwork.Subnets) // { // if (subnet.Id == id) // return subnet; // } // } // return null; //} private IStorageTarget SeekStorageAccount(string id, List<Azure.Asm.StorageAccount> asmStorageAccounts, List<Azure.Arm.StorageAccount> armStorageAccounts) { if (asmStorageAccounts != null) { foreach (Azure.Asm.StorageAccount asmStorageAccount in asmStorageAccounts) { if (asmStorageAccount.Id == id) return null; // todo asap asmStorageAccount; } } if (armStorageAccounts != null) { foreach (Azure.Arm.StorageAccount armStorageAccount in armStorageAccounts) { if (armStorageAccount.Id == id) return null; // todo asap armStorageAccount; } } return null; } } }
//------------------------------------------------------------------------------ // <copyright file="WorkerRequest.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /*++ Copyright (c) 1999 Microsoft Corporation Module Name : HttpWorkerRequest.cs Abstract: This module defines the base worker class used by ASP.NET Managed code for request processing. --*/ namespace System.Web { using System; using System.Collections; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Security.Principal; using System.Text; using System.Threading; using System.Web.Management; // for webevent tracing using System.Web.Util; // // **************************************************************************** // /// <devdoc> /// <para>This abstract class defines the base worker methods and enumerations used by ASP.NET managed code for request processing.</para> /// </devdoc> [ComVisible(false)] public abstract class HttpWorkerRequest { private DateTime _startTime; private volatile bool _isInReadEntitySync; //it is up to the derived classes to implement a real id #pragma warning disable 0649 private Guid _traceId; #pragma warning restore 0649 protected HttpWorkerRequest() { _startTime = DateTime.UtcNow; } // ************************************************************************ // // Indexed Headers. All headers that are defined by HTTP/1.1. These // values are used as offsets into arrays and as token values. // // IMPORTANT : Notice request + response values overlap. Make sure you // know which type of header array you are indexing. // // // general-headers [section 4.5] // /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderCacheControl = 0; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderConnection = 1; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderDate = 2; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderKeepAlive = 3; // not in rfc /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderPragma = 4; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderTrailer = 5; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderTransferEncoding = 6; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderUpgrade = 7; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderVia = 8; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderWarning = 9; // // entity-headers [section 7.1] // /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderAllow = 10; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderContentLength = 11; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderContentType = 12; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderContentEncoding = 13; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderContentLanguage = 14; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderContentLocation = 15; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderContentMd5 = 16; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderContentRange = 17; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderExpires = 18; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderLastModified = 19; // // request-headers [section 5.3] // /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderAccept = 20; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderAcceptCharset = 21; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderAcceptEncoding = 22; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderAcceptLanguage = 23; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderAuthorization = 24; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderCookie = 25; // not in rfc /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderExpect = 26; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderFrom = 27; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderHost = 28; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderIfMatch = 29; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderIfModifiedSince = 30; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderIfNoneMatch = 31; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderIfRange = 32; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderIfUnmodifiedSince = 33; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderMaxForwards = 34; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderProxyAuthorization = 35; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderReferer = 36; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderRange = 37; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderTe = 38; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderUserAgent = 39; // // Request headers end here // /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int RequestHeaderMaximum = 40; // // response-headers [section 6.2] // /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderAcceptRanges = 20; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderAge = 21; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderEtag = 22; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderLocation = 23; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderProxyAuthenticate = 24; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderRetryAfter = 25; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderServer = 26; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderSetCookie = 27; // not in rfc /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderVary = 28; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int HeaderWwwAuthenticate = 29; // // Response headers end here // /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const int ResponseHeaderMaximum = 30; // ************************************************************************ // // Request reasons // /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> /// <internalonly/> public const int ReasonResponseCacheMiss = 0; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> /// <internalonly/> public const int ReasonFileHandleCacheMiss = 1; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> /// <internalonly/> public const int ReasonCachePolicy = 2; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> /// <internalonly/> public const int ReasonCacheSecurity = 3; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> /// <internalonly/> public const int ReasonClientDisconnect = 4; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> /// <internalonly/> public const int ReasonDefault = ReasonResponseCacheMiss; // ************************************************************************ // // Access to request related members // // required members /// <devdoc> /// <para> Returns the virtual path to the requested Uri, including PathInfo.</para> /// </devdoc> public abstract String GetUriPath(); // "/foo/page.aspx/tail" /// <devdoc> /// <para>Provides Access to the specified member of the request header.</para> /// </devdoc> public abstract String GetQueryString(); // "param=bar" /// <devdoc> /// <para>Gets the URI requsted by the client, which will include PathInfo and QueryString if it exists. /// This value is unaffected by any URL rewriting or routing that may occur on the server.</para> /// </devdoc> public abstract String GetRawUrl(); // "/foo/page.aspx/tail?param=bar" /// <devdoc> /// <para>Provides Access to the specified member of the request header.</para> /// </devdoc> public abstract String GetHttpVerbName(); // "GET" /// <devdoc> /// <para>Provides Access to the specified member of the request header.</para> /// </devdoc> public abstract String GetHttpVersion(); // "HTTP/1.1" /// <devdoc> /// <para>Provides Access to the specified member of the request header.</para> /// </devdoc> public abstract String GetRemoteAddress(); // client's ip address /// <devdoc> /// <para>Provides Access to the specified member of the request header.</para> /// </devdoc> public abstract int GetRemotePort(); // client's port /// <devdoc> /// <para>Provides Access to the specified member of the request header.</para> /// </devdoc> public abstract String GetLocalAddress(); // server's ip address /// <devdoc> /// <para>Provides Access to the specified member of the request header.</para> /// </devdoc> public abstract int GetLocalPort(); // server's port internal virtual String GetLocalPortAsString() { return GetLocalPort().ToString(NumberFormatInfo.InvariantInfo); } /* * Internal property to determine if request is local */ internal bool IsLocal() { String remoteAddress = GetRemoteAddress(); // if unknown, assume not local if (String.IsNullOrEmpty(remoteAddress)) return false; // check if localhost if (remoteAddress == "127.0.0.1" || remoteAddress == "::1") return true; // compare with local address if (remoteAddress == GetLocalAddress()) return true; return false; } // Attempt to derive RawUrl from the "CACHE_URL" server variable. internal static String GetRawUrlHelper(String cacheUrl) { // cacheUrl has format "[http|https]://[server]:[port][uri]", including query string and path-info, if they exist. if (cacheUrl != null) { // the URI begins at the 3rd slash int count = 0; for(int index = 0; index < cacheUrl.Length; index++) { if (cacheUrl[index] == '/') { if (++count == 3) { return cacheUrl.Substring(index); } } } } // someone must have modified CACHE_URL, it is not valid throw new HttpException(SR.GetString(SR.Cache_url_invalid)); } // Mark a blocking call // It allows RequestTimeoutManager to eventualy to close the connection and unblock the caller // and handle request timeout properly (if in cancelable state) internal bool IsInReadEntitySync { get { return _isInReadEntitySync; } set { _isInReadEntitySync = value; } } // optional members with defaults supplied /// <devdoc> /// <para>When overriden in a derived class, returns the response query string as an array of bytes.</para> /// </devdoc> public virtual byte[] GetQueryStringRawBytes() { // access to raw qs for i18n return null; } /// <devdoc> /// <para>When overriden in a derived class, returns the client computer's name.</para> /// </devdoc> public virtual String GetRemoteName() { // client's name return GetRemoteAddress(); } /// <devdoc> /// <para>When overriden in a derived class, returns the name of the local server.</para> /// </devdoc> public virtual String GetServerName() { // server's name return GetLocalAddress(); } /// <devdoc> /// <para>When overriden in a derived class, returns the ID of the current connection.</para> /// </devdoc> /// <internalonly/> public virtual long GetConnectionID() { // connection id return 0; } /// <devdoc> /// <para>When overriden in a derived class, returns the context ID of the current connection.</para> /// </devdoc> /// <internalonly/> public virtual long GetUrlContextID() { // UL APPID return 0; } /// <devdoc> /// <para>When overriden in a derived class, returns the application pool ID for the current URL.</para> /// </devdoc> /// <internalonly/> public virtual String GetAppPoolID() { // UL Application pool id return null; } /// <devdoc> /// <para>When overriden in a derived class, returns the reason for the request.</para> /// </devdoc> /// <internalonly/> public virtual int GetRequestReason() { // constants Reason... above return ReasonDefault; } /// <devdoc> /// <para>When overriden in a derived class, returns the client's impersonation token.</para> /// </devdoc> public virtual IntPtr GetUserToken() { // impersonation token return IntPtr.Zero; } // Gets LOGON_USER as WindowsIdentity internal WindowsIdentity GetLogonUserIdentity() { IntPtr token = GetUserToken(); if (token != IntPtr.Zero) { String logonUser = GetServerVariable("LOGON_USER"); String authType = GetServerVariable("AUTH_TYPE"); bool isAuthenticated = (!string.IsNullOrEmpty(logonUser) || (!string.IsNullOrEmpty(authType) && !StringUtil.EqualsIgnoreCase(authType, "basic"))); return CreateWindowsIdentityWithAssert(token, ((authType == null) ? "" : authType), WindowsAccountType.Normal, isAuthenticated); } return null; // invalid token } [PermissionSet(SecurityAction.Assert, Unrestricted = true)] private static WindowsIdentity CreateWindowsIdentityWithAssert(IntPtr token, string authType, WindowsAccountType accountType, bool isAuthenticated) { return new WindowsIdentity(token, authType, accountType, isAuthenticated); } /// <internalonly/> public virtual IntPtr GetVirtualPathToken() { // impersonation token return IntPtr.Zero; } /// <devdoc> /// <para>When overriden in a derived class, returns a value indicating whether the connection is secure (using SSL).</para> /// </devdoc> public virtual bool IsSecure() { // is over ssl? return false; } /// <devdoc> /// <para>When overriden in a derived class, returns the HTTP protocol (HTTP or HTTPS).</para> /// </devdoc> public virtual String GetProtocol() { return IsSecure() ? "https" : "http"; } /// <devdoc> /// <para>When overriden in a derived class, returns the virtual path to the requested Uri, without PathInfo.</para> /// </devdoc> public virtual String GetFilePath() { // "/foo/page.aspx" return GetUriPath(); } internal VirtualPath GetFilePathObject() { // Don't allow malformed paths for security reasons return VirtualPath.Create(GetFilePath(), VirtualPathOptions.AllowAbsolutePath | VirtualPathOptions.AllowNull); } /// <devdoc> /// <para>When overriden in a derived class, returns the translated file path to the requested Uri (from virtual path to /// UNC path, ie "/foo/page.aspx" to "c:\dir\page.aspx") </para> /// </devdoc> public virtual String GetFilePathTranslated() { // "c:\dir\page.aspx" return null; } /// <devdoc> /// <para>When overriden in a derived class, returns additional /// path information for a resource with a URL extension. i.e. for the URL /// /virdir/page.html/tail, the PathInfo value is /tail. </para> /// </devdoc> public virtual String GetPathInfo() { // "/tail" return String.Empty; } /// <devdoc> /// <para>When overriden in a derived class, returns the virtual path to the /// currently executing server application.</para> /// </devdoc> public virtual String GetAppPath() { // "/foo" return null; } /// <devdoc> /// <para>When overriden in a derived class, returns the UNC-translated path to /// the currently executing server application.</para> /// </devdoc> public virtual String GetAppPathTranslated() { // "c:\dir" return null; } // // Virtual methods to read the incoming request // public virtual int GetPreloadedEntityBodyLength() { byte[] bytes = GetPreloadedEntityBody(); return (bytes != null) ? bytes.Length : 0; } public virtual int GetPreloadedEntityBody(byte[] buffer, int offset) { int l = 0; byte[] bytes = GetPreloadedEntityBody(); if (bytes != null) { l = bytes.Length; Buffer.BlockCopy(bytes, 0, buffer, offset, l); } return l; } public virtual byte[] GetPreloadedEntityBody() { return null; } public virtual bool IsEntireEntityBodyIsPreloaded() { return false; } public virtual int GetTotalEntityBodyLength() { int l = 0; String contentLength = GetKnownRequestHeader(HeaderContentLength); if (contentLength != null) { try { l = Int32.Parse(contentLength, CultureInfo.InvariantCulture); } catch { } } return l; } public virtual int ReadEntityBody(byte[] buffer, int size) { return 0; } public virtual int ReadEntityBody(byte[] buffer, int offset, int size) { byte[] temp = new byte[size]; int l = ReadEntityBody(temp, size); if (l > 0) { Buffer.BlockCopy(temp, 0, buffer, offset, l); } return l; } // Returns true if async flush is supported; otherwise false. public virtual bool SupportsAsyncFlush { get { return false; } } // Sends the currently buffered response to the client asynchronously. To support this, // the worker request buffers the status, headers, and resonse body until an asynchronous // flush operation is initiated. public virtual IAsyncResult BeginFlush(AsyncCallback callback, Object state) { throw new NotSupportedException(); } // Finish an asynchronous flush. public virtual void EndFlush(IAsyncResult asyncResult) { throw new NotSupportedException(); } public virtual bool SupportsAsyncRead { get { return false; } } // Begin an asynchronous read of the request entity body. To read the entire entity, invoke // repeatedly until total bytes read is equal to Request.ContentLength or EndRead indicates // that zero bytes were read. If Request.ContentLength is zero and the request is chunked, // then invoke repeatedly until EndRead indicates that zero bytes were read. // // If an error occurs and the client is no longer connected, no exception will be thrown for // compatibility with the synchronous read method (ReadEntityBody). Instead, EndRead will // report that zero bytes were read. // // This implements Stream.BeginRead, and as such, should throw // exceptions as described on MSDN when errors occur. public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { throw new NotSupportedException(); } // Finish an asynchronous read. When this returns zero there is no more to be read. If Request.ContentLength is non-zero, // do not read more bytes then specified by ContentLength, or an error will occur. // This implements Stream.EndRead on HttpBufferlessInputStream, and as such, should throw // exceptions as described on MSDN when errors occur. public virtual int EndRead(IAsyncResult asyncResult) { throw new NotSupportedException(); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public virtual String GetKnownRequestHeader(int index) { return null; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public virtual String GetUnknownRequestHeader(String name) { return null; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [CLSCompliant(false)] public virtual String[][] GetUnknownRequestHeaders() { return null; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public virtual String GetServerVariable(String name) { return null; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> /// <internalonly/> public virtual long GetBytesRead() { return 0; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> /// <internalonly/> internal virtual DateTime GetStartTime() { return _startTime; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> /// <internalonly/> internal virtual void ResetStartTime() { _startTime = DateTime.UtcNow; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public virtual String MapPath(String virtualPath) { return null; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public virtual String MachineConfigPath { get { return null; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public virtual String RootWebConfigPath { get { return null; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public virtual String MachineInstallDirectory { get { return null; } } // IntegratedTraceType in EtwTrace.cs internal virtual void RaiseTraceEvent(IntegratedTraceType traceType, string eventData) { // do nothing } internal virtual void RaiseTraceEvent(WebBaseEvent webEvent) { // do nothing } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public virtual Guid RequestTraceIdentifier { get { return _traceId; } } // // Abstract methods to write the response // /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public abstract void SendStatus(int statusCode, String statusDescription); // for IIS 7, use both the status and substatus // this cannot be abstract internal virtual void SendStatus(int statusCode, int subStatusCode, String statusDescription) { SendStatus(statusCode, statusDescription); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public abstract void SendKnownResponseHeader(int index, String value); /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public abstract void SendUnknownResponseHeader(String name, String value); // headers encoding controled via HttpResponse.HeaderEncoding internal virtual void SetHeaderEncoding(Encoding encoding) { } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public abstract void SendResponseFromMemory(byte[] data, int length); /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public virtual void SendResponseFromMemory(IntPtr data, int length) { if (length > 0) { InternalSecurityPermissions.UnmanagedCode.Demand(); // derived classes could have an efficient implementation byte[] bytes = new byte[length]; Misc.CopyMemory(data, 0, bytes, 0, length); SendResponseFromMemory(bytes, length); } } [SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)] internal virtual void SendResponseFromMemory(IntPtr data, int length, bool isBufferFromUnmanagedPool) { // default implementation SendResponseFromMemory(data, length); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public abstract void SendResponseFromFile(String filename, long offset, long length); /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public abstract void SendResponseFromFile(IntPtr handle, long offset, long length); internal virtual void TransmitFile(String filename, long length, bool isImpersonating) { TransmitFile(filename, 0, length, isImpersonating); } internal virtual void TransmitFile(String filename, long offset, long length, bool isImpersonating) { // default implementation SendResponseFromFile(filename, offset, length); } // VSWhidbey 555203: support 64-bit file sizes for TransmitFile on IIS6 internal virtual bool SupportsLongTransmitFile { get { return false; } } // WOS 1555777: kernel cache support // If the worker request can kernel cache the response, it returns the // kernel cache key; otherwise null. The kernel cache key is used to invalidate // the entry if a dependency changes or the item is flushed from the managed // cache for any reason. internal virtual string SetupKernelCaching(int secondsToLive, string originalCacheUrl, bool enableKernelCacheForVaryByStar) { return null; } // WOS 1555777: kernel cache support internal virtual void DisableKernelCache() { return; } // DevDiv 255268: IIS user-mode cache support internal virtual void DisableUserCache() { return; } internal virtual bool TrySkipIisCustomErrors { get { return false; } set { } } // Execute Url internal virtual bool SupportsExecuteUrl { get { return false; } } internal virtual IAsyncResult BeginExecuteUrl( String url, String method, String headers, bool sendHeaders, bool addUserIndo, IntPtr token, String name, String authType, byte[] entity, AsyncCallback cb, Object state) { throw new NotSupportedException(SR.GetString(SR.ExecuteUrl_not_supported)); } internal virtual void EndExecuteUrl(IAsyncResult result) { } internal virtual void UpdateInitialCounters() { } internal virtual void UpdateResponseCounters(bool finalFlush, int bytesOut) { } internal virtual void UpdateRequestCounters(int bytesIn) { } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public abstract void FlushResponse(bool finalFlush); /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public abstract void EndOfRequest(); // // Virtual helper methods // /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [SuppressMessage("Microsoft.Design","CA1034:NestedTypesShouldNotBeVisible", Scope = "type", Target = "System.Web.HttpWorkerRequest+EndOfSendNotification", Justification = "Already shipped. Cannot move as would be a breaking change.")] public delegate void EndOfSendNotification(HttpWorkerRequest wr, Object extraData); /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public virtual void SetEndOfSendNotification(EndOfSendNotification callback, Object extraData) { // firing the callback helps with buffer recycling } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public virtual void SendCalculatedContentLength(int contentLength) { // oportunity to add Content-Length header if not added by user } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public virtual void SendCalculatedContentLength(long contentLength) { // default implementation is to call the int32 version SendCalculatedContentLength(Convert.ToInt32(contentLength)); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public virtual bool HeadersSent() { return true; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public virtual bool IsClientConnected() { return true; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public virtual void CloseConnection() { } /// <devdoc> /// <para>Defines the base worker class used by ASP.NET Managed code for request /// processing.</para> /// </devdoc> /// <internalonly/> public virtual byte [] GetClientCertificate() { return new byte[0]; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> /// <internalonly/> public virtual DateTime GetClientCertificateValidFrom() { return DateTime.Now; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> /// <internalonly/> public virtual DateTime GetClientCertificateValidUntil() { return DateTime.Now; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> /// <internalonly/> public virtual byte [] GetClientCertificateBinaryIssuer() { return new byte[0]; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> /// <internalonly/> public virtual int GetClientCertificateEncoding() { return 0; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> /// <internalonly/> public virtual byte[] GetClientCertificatePublicKey() { return new byte[0]; } // ************************************************************************ // // criteria to find out if there is posted data // /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool HasEntityBody() { // // content length != 0 -> assume has content // String contentLength = GetKnownRequestHeader(HeaderContentLength); if (contentLength != null && !contentLength.Equals("0")) return true; // // any content encoding -> assume has content // if (GetKnownRequestHeader(HeaderTransferEncoding) != null) return true; // // preloaded -> has it // if (GetPreloadedEntityBody() != null) return true; // // no posted data but everything preloaded -> no content // if (IsEntireEntityBodyIsPreloaded()) return false; return false; } // ************************************************************************ // // Default values for Http status description strings // /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static String GetStatusDescription(int code) { if (code >= 100 && code < 600) { int i = code / 100; int j = code % 100; if (j < s_HTTPStatusDescriptions[i].Length) return s_HTTPStatusDescriptions[i][j]; } return String.Empty; } // Tables of status strings (first index is code/100, 2nd code%100) private static readonly String[][] s_HTTPStatusDescriptions = new String[][] { null, new String[] { /* 100 */"Continue", /* 101 */ "Switching Protocols", /* 102 */ "Processing" }, new String[] { /* 200 */"OK", /* 201 */ "Created", /* 202 */ "Accepted", /* 203 */ "Non-Authoritative Information", /* 204 */ "No Content", /* 205 */ "Reset Content", /* 206 */ "Partial Content", /* 207 */ "Multi-Status" }, new String[] { /* 300 */"Multiple Choices", /* 301 */ "Moved Permanently", /* 302 */ "Found", /* 303 */ "See Other", /* 304 */ "Not Modified", /* 305 */ "Use Proxy", /* 306 */ String.Empty, /* 307 */ "Temporary Redirect" }, new String[] { /* 400 */"Bad Request", /* 401 */ "Unauthorized", /* 402 */ "Payment Required", /* 403 */ "Forbidden", /* 404 */ "Not Found", /* 405 */ "Method Not Allowed", /* 406 */ "Not Acceptable", /* 407 */ "Proxy Authentication Required", /* 408 */ "Request Timeout", /* 409 */ "Conflict", /* 410 */ "Gone", /* 411 */ "Length Required", /* 412 */ "Precondition Failed", /* 413 */ "Request Entity Too Large", /* 414 */ "Request-Uri Too Long", /* 415 */ "Unsupported Media Type", /* 416 */ "Requested Range Not Satisfiable", /* 417 */ "Expectation Failed", /* 418 */ String.Empty, /* 419 */ String.Empty, /* 420 */ String.Empty, /* 421 */ String.Empty, /* 422 */ "Unprocessable Entity", /* 423 */ "Locked", /* 424 */ "Failed Dependency" }, new String[] { /* 500 */"Internal Server Error", /* 501 */ "Not Implemented", /* 502 */ "Bad Gateway", /* 503 */ "Service Unavailable", /* 504 */ "Gateway Timeout", /* 505 */ "Http Version Not Supported", /* 506 */ String.Empty, /* 507 */ "Insufficient Storage" } }; // ************************************************************************ // // Header index to string conversions // /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static int GetKnownRequestHeaderIndex(String header) { Object intObj = s_requestHeadersLoookupTable[header]; if (intObj != null) return(Int32)intObj; else return -1; } // ************************************************************************ /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static String GetKnownRequestHeaderName(int index) { return s_requestHeaderNames[index]; } internal static String GetServerVariableNameFromKnownRequestHeaderIndex(int index) { return s_serverVarFromRequestHeaderNames[index]; } // ************************************************************************ /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static int GetKnownResponseHeaderIndex(String header) { Object intObj = s_responseHeadersLoookupTable[header]; if (intObj != null) return(Int32)intObj; else return -1; } // ************************************************************************ /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static String GetKnownResponseHeaderName(int index) { return s_responseHeaderNames[index]; } // ************************************************************************ // // Implemenation -- lookup tables for header names // static private String[] s_serverVarFromRequestHeaderNames = new String[RequestHeaderMaximum]; static private String[] s_requestHeaderNames = new String[RequestHeaderMaximum]; static private String[] s_responseHeaderNames = new String[ResponseHeaderMaximum]; static private Hashtable s_requestHeadersLoookupTable = new Hashtable(StringComparer.OrdinalIgnoreCase); static private Hashtable s_responseHeadersLoookupTable = new Hashtable(StringComparer.OrdinalIgnoreCase); // ************************************************************************ static private void DefineHeader(bool isRequest, bool isResponse, int index, String headerName, String serverVarName) { Debug.Assert(serverVarName == null || serverVarName == "HTTP_" + headerName.ToUpper(CultureInfo.InvariantCulture).Replace('-', '_')); Int32 i32 = new Int32(); if (isRequest) { i32 = index; s_serverVarFromRequestHeaderNames[index] = serverVarName; s_requestHeaderNames[index] = headerName; s_requestHeadersLoookupTable.Add(headerName, i32); } if (isResponse) { i32 = index; s_responseHeaderNames[index] = headerName; s_responseHeadersLoookupTable.Add(headerName, i32); } } // ************************************************************************ static HttpWorkerRequest() { // // common headers // DefineHeader(true, true, HeaderCacheControl, "Cache-Control", "HTTP_CACHE_CONTROL"); DefineHeader(true, true, HeaderConnection, "Connection", "HTTP_CONNECTION"); DefineHeader(true, true, HeaderDate, "Date", "HTTP_DATE"); DefineHeader(true, true, HeaderKeepAlive, "Keep-Alive", "HTTP_KEEP_ALIVE"); DefineHeader(true, true, HeaderPragma, "Pragma", "HTTP_PRAGMA"); DefineHeader(true, true, HeaderTrailer, "Trailer", "HTTP_TRAILER"); DefineHeader(true, true, HeaderTransferEncoding, "Transfer-Encoding", "HTTP_TRANSFER_ENCODING"); DefineHeader(true, true, HeaderUpgrade, "Upgrade", "HTTP_UPGRADE"); DefineHeader(true, true, HeaderVia, "Via", "HTTP_VIA"); DefineHeader(true, true, HeaderWarning, "Warning", "HTTP_WARNING"); DefineHeader(true, true, HeaderAllow, "Allow", "HTTP_ALLOW"); DefineHeader(true, true, HeaderContentLength, "Content-Length", "HTTP_CONTENT_LENGTH"); DefineHeader(true, true, HeaderContentType, "Content-Type", "HTTP_CONTENT_TYPE"); DefineHeader(true, true, HeaderContentEncoding, "Content-Encoding", "HTTP_CONTENT_ENCODING"); DefineHeader(true, true, HeaderContentLanguage, "Content-Language", "HTTP_CONTENT_LANGUAGE"); DefineHeader(true, true, HeaderContentLocation, "Content-Location", "HTTP_CONTENT_LOCATION"); DefineHeader(true, true, HeaderContentMd5, "Content-MD5", "HTTP_CONTENT_MD5"); DefineHeader(true, true, HeaderContentRange, "Content-Range", "HTTP_CONTENT_RANGE"); DefineHeader(true, true, HeaderExpires, "Expires", "HTTP_EXPIRES"); DefineHeader(true, true, HeaderLastModified, "Last-Modified", "HTTP_LAST_MODIFIED"); // // request only headers // DefineHeader(true, false, HeaderAccept, "Accept", "HTTP_ACCEPT"); DefineHeader(true, false, HeaderAcceptCharset, "Accept-Charset", "HTTP_ACCEPT_CHARSET"); DefineHeader(true, false, HeaderAcceptEncoding, "Accept-Encoding", "HTTP_ACCEPT_ENCODING"); DefineHeader(true, false, HeaderAcceptLanguage, "Accept-Language", "HTTP_ACCEPT_LANGUAGE"); DefineHeader(true, false, HeaderAuthorization, "Authorization", "HTTP_AUTHORIZATION"); DefineHeader(true, false, HeaderCookie, "Cookie", "HTTP_COOKIE"); DefineHeader(true, false, HeaderExpect, "Expect", "HTTP_EXPECT"); DefineHeader(true, false, HeaderFrom, "From", "HTTP_FROM"); DefineHeader(true, false, HeaderHost, "Host", "HTTP_HOST"); DefineHeader(true, false, HeaderIfMatch, "If-Match", "HTTP_IF_MATCH"); DefineHeader(true, false, HeaderIfModifiedSince, "If-Modified-Since", "HTTP_IF_MODIFIED_SINCE"); DefineHeader(true, false, HeaderIfNoneMatch, "If-None-Match", "HTTP_IF_NONE_MATCH"); DefineHeader(true, false, HeaderIfRange, "If-Range", "HTTP_IF_RANGE"); DefineHeader(true, false, HeaderIfUnmodifiedSince, "If-Unmodified-Since", "HTTP_IF_UNMODIFIED_SINCE"); DefineHeader(true, false, HeaderMaxForwards, "Max-Forwards", "HTTP_MAX_FORWARDS"); DefineHeader(true, false, HeaderProxyAuthorization, "Proxy-Authorization", "HTTP_PROXY_AUTHORIZATION"); DefineHeader(true, false, HeaderReferer, "Referer", "HTTP_REFERER"); DefineHeader(true, false, HeaderRange, "Range", "HTTP_RANGE"); DefineHeader(true, false, HeaderTe, "TE", "HTTP_TE"); DefineHeader(true, false, HeaderUserAgent, "User-Agent", "HTTP_USER_AGENT"); // // response only headers // DefineHeader(false, true, HeaderAcceptRanges, "Accept-Ranges", null); DefineHeader(false, true, HeaderAge, "Age", null); DefineHeader(false, true, HeaderEtag, "ETag", null); DefineHeader(false, true, HeaderLocation, "Location", null); DefineHeader(false, true, HeaderProxyAuthenticate, "Proxy-Authenticate", null); DefineHeader(false, true, HeaderRetryAfter, "Retry-After", null); DefineHeader(false, true, HeaderServer, "Server", null); DefineHeader(false, true, HeaderSetCookie, "Set-Cookie", null); DefineHeader(false, true, HeaderVary, "Vary", null); DefineHeader(false, true, HeaderWwwAuthenticate, "WWW-Authenticate", null); } } }
using System; using System.Diagnostics; using System.IO; using System.Threading; using Orleans.Runtime.Configuration; namespace Orleans.Runtime.Host { /// <summary> /// Utility class for initializing an Orleans client running inside Azure. /// </summary> public static class AzureClient { private static readonly IServiceRuntimeWrapper serviceRuntimeWrapper = new ServiceRuntimeWrapper(); /// <summary>Number of retry attempts to make when searching for gateway silos to connect to.</summary> public static readonly int MaxRetries = AzureConstants.MAX_RETRIES; // 120 x 5s = Total: 10 minutes /// <summary>Amount of time to pause before each retry attempt.</summary> public static readonly TimeSpan StartupRetryPause = AzureConstants.STARTUP_TIME_PAUSE; // 5 seconds /// <summary> /// Whether the Orleans Azure client runtime has already been initialized /// </summary> /// <returns><c>true</c> if client runtime is already initialized</returns> public static bool IsInitialized { get { return GrainClient.IsInitialized; } } /// <summary> /// Initialise the Orleans client runtime in this Azure process /// </summary> public static void Initialize() { InitializeImpl_FromFile(null); } /// <summary> /// Initialise the Orleans client runtime in this Azure process /// </summary> /// <param name="orleansClientConfigFile">Location of the Orleans client config file to use for base config settings</param> /// <remarks>Any silo gateway address specified in the config file is ignored, and gateway endpoint info is read from the silo instance table in Azure storage instead.</remarks> public static void Initialize(FileInfo orleansClientConfigFile) { InitializeImpl_FromFile(orleansClientConfigFile); } /// <summary> /// Initialise the Orleans client runtime in this Azure process /// </summary> /// <param name="clientConfigFilePath">Location of the Orleans client config file to use for base config settings</param> /// <remarks>Any silo gateway address specified in the config file is ignored, and gateway endpoint info is read from the silo instance table in Azure storage instead.</remarks> public static void Initialize(string clientConfigFilePath) { InitializeImpl_FromFile(new FileInfo(clientConfigFilePath)); } /// <summary> /// Initializes the Orleans client runtime in this Azure process from the provided client configuration object. /// If the configuration object is null, the initialization fails. /// </summary> /// <param name="config">A ClientConfiguration object.</param> public static void Initialize(ClientConfiguration config) { InitializeImpl_FromConfig(config); } /// <summary> /// Uninitializes the Orleans client runtime in this Azure process. /// </summary> public static void Uninitialize() { if (!GrainClient.IsInitialized) return; Trace.TraceInformation("Uninitializing connection to Orleans gateway silo."); GrainClient.Uninitialize(); } /// <summary> /// Returns default client configuration object for passing to AzureClient. /// </summary> /// <returns></returns> public static ClientConfiguration DefaultConfiguration() { var config = new ClientConfiguration { GatewayProvider = ClientConfiguration.GatewayProviderType.AzureTable, DeploymentId = GetDeploymentId(), DataConnectionString = GetDataConnectionString(), }; return config; } #region Internal implementation of client initialization processing private static void InitializeImpl_FromFile(FileInfo configFile) { if (GrainClient.IsInitialized) { Trace.TraceInformation("Connection to Orleans gateway silo already initialized."); return; } ClientConfiguration config; try { if (configFile == null) { Trace.TraceInformation("Looking for standard Orleans client config file"); config = ClientConfiguration.StandardLoad(); } else { var configFileLocation = configFile.FullName; Trace.TraceInformation("Loading Orleans client config file {0}", configFileLocation); config = ClientConfiguration.LoadFromFile(configFileLocation); } } catch (Exception ex) { var msg = String.Format("Error loading Orleans client configuration file {0} {1} -- unable to continue. {2}", configFile, ex.Message, LogFormatter.PrintException(ex)); Trace.TraceError(msg); throw new AggregateException(msg, ex); } Trace.TraceInformation("Overriding Orleans client config from Azure runtime environment."); try { config.DeploymentId = GetDeploymentId(); config.DataConnectionString = GetDataConnectionString(); config.GatewayProvider = ClientConfiguration.GatewayProviderType.AzureTable; } catch (Exception ex) { var msg = string.Format("ERROR: No AzureClient role setting value '{0}' specified for this role -- unable to continue", AzureConstants.DataConnectionConfigurationSettingName); Trace.TraceError(msg); throw new AggregateException(msg, ex); } InitializeImpl_FromConfig(config); } internal static string GetDeploymentId() { return GrainClient.TestOnlyNoConnect ? "FakeDeploymentId" : serviceRuntimeWrapper.DeploymentId; } internal static string GetDataConnectionString() { return GrainClient.TestOnlyNoConnect ? "FakeConnectionString" : serviceRuntimeWrapper.GetConfigurationSettingValue(AzureConstants.DataConnectionConfigurationSettingName); } private static void InitializeImpl_FromConfig(ClientConfiguration config) { if (GrainClient.IsInitialized) { Trace.TraceInformation("Connection to Orleans gateway silo already initialized."); return; } //// Find endpoint info for the gateway to this Orleans silo cluster //Trace.WriteLine("Searching for Orleans gateway silo via Orleans instance table..."); var deploymentId = config.DeploymentId; var connectionString = config.DataConnectionString; if (String.IsNullOrEmpty(deploymentId)) throw new ArgumentException("Cannot connect to Azure silos with null deploymentId", "config.DeploymentId"); if (String.IsNullOrEmpty(connectionString)) throw new ArgumentException("Cannot connect to Azure silos with null connectionString", "config.DataConnectionString"); bool initSucceeded = false; Exception lastException = null; for (int i = 0; i < MaxRetries; i++) { try { // Initialize will throw if cannot find Gateways GrainClient.Initialize(config); initSucceeded = true; break; } catch (Exception exc) { lastException = exc; Trace.TraceError("Client.Initialize failed with exc -- {0}. Will try again", exc.Message); } // Pause to let Primary silo start up and register Trace.TraceInformation("Pausing {0} awaiting silo and gateways registration for Deployment={1}", StartupRetryPause, deploymentId); Thread.Sleep(StartupRetryPause); } if (initSucceeded) return; OrleansException err; err = lastException != null ? new OrleansException(String.Format("Could not Initialize Client for DeploymentId={0}. Last exception={1}", deploymentId, lastException.Message), lastException) : new OrleansException(String.Format("Could not Initialize Client for DeploymentId={0}.", deploymentId)); Trace.TraceError("Error starting Orleans Azure client application -- {0} -- bailing. {1}", err.Message, LogFormatter.PrintException(err)); throw err; } #endregion } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// SMC Transfer Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class SMC_TFRDataSet : EduHubDataSet<SMC_TFR> { /// <inheritdoc /> public override string Name { get { return "SMC_TFR"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal SMC_TFRDataSet(EduHubContext Context) : base(Context) { Index_ORIG_SCHOOL = new Lazy<Dictionary<string, IReadOnlyList<SMC_TFR>>>(() => this.ToGroupedDictionary(i => i.ORIG_SCHOOL)); Index_TID = new Lazy<Dictionary<int, SMC_TFR>>(() => this.ToDictionary(i => i.TID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="SMC_TFR" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="SMC_TFR" /> fields for each CSV column header</returns> internal override Action<SMC_TFR, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<SMC_TFR, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "TID": mapper[i] = (e, v) => e.TID = int.Parse(v); break; case "ORIG_SCHOOL": mapper[i] = (e, v) => e.ORIG_SCHOOL = v; break; case "SMC_TRANS_ID": mapper[i] = (e, v) => e.SMC_TRANS_ID = v; break; case "SMCKEY": mapper[i] = (e, v) => e.SMCKEY = v == null ? (int?)null : int.Parse(v); break; case "STUDENT": mapper[i] = (e, v) => e.STUDENT = v; break; case "CONDITION_EXISTS": mapper[i] = (e, v) => e.CONDITION_EXISTS = v; break; case "STUDENT_NEW": mapper[i] = (e, v) => e.STUDENT_NEW = v; break; case "MED_CONDITION": mapper[i] = (e, v) => e.MED_CONDITION = v; break; case "MED_CONDITION_NEW": mapper[i] = (e, v) => e.MED_CONDITION_NEW = v; break; case "MED_CONDITION_ACT": mapper[i] = (e, v) => e.MED_CONDITION_ACT = v; break; case "SYMPTOMS": mapper[i] = (e, v) => e.SYMPTOMS = v; break; case "SMC_COMMENT": mapper[i] = (e, v) => e.SMC_COMMENT = v; break; case "REGULAR_MEDICATION": mapper[i] = (e, v) => e.REGULAR_MEDICATION = v; break; case "REGULAR_POISON_RATING": mapper[i] = (e, v) => e.REGULAR_POISON_RATING = v; break; case "REGULAR_DOSAGE": mapper[i] = (e, v) => e.REGULAR_DOSAGE = v; break; case "REGULAR_FREQUENCY": mapper[i] = (e, v) => e.REGULAR_FREQUENCY = v; break; case "REGULAR_DOSAGE_TIME": mapper[i] = (e, v) => e.REGULAR_DOSAGE_TIME = v; break; case "REGULAR_MEDICATION_LOCAT": mapper[i] = (e, v) => e.REGULAR_MEDICATION_LOCAT = v; break; case "REGULAR_ADMIN_BY": mapper[i] = (e, v) => e.REGULAR_ADMIN_BY = v; break; case "REMINDER": mapper[i] = (e, v) => e.REMINDER = v; break; case "INFORM_DOCTOR": mapper[i] = (e, v) => e.INFORM_DOCTOR = v; break; case "INFORM_EMERG_CONTACT": mapper[i] = (e, v) => e.INFORM_EMERG_CONTACT = v; break; case "ADMINISTER_MEDICATION": mapper[i] = (e, v) => e.ADMINISTER_MEDICATION = v; break; case "OTHER_MEDICAL_ACTION": mapper[i] = (e, v) => e.OTHER_MEDICAL_ACTION = v; break; case "SMC_ACTION": mapper[i] = (e, v) => e.SMC_ACTION = v; break; case "AD_HOC_MEDICATION": mapper[i] = (e, v) => e.AD_HOC_MEDICATION = v; break; case "AD_HOC_POISON_RATING": mapper[i] = (e, v) => e.AD_HOC_POISON_RATING = v; break; case "AD_HOC_DOSAGE": mapper[i] = (e, v) => e.AD_HOC_DOSAGE = v; break; case "AD_HOC_FREQUENCY": mapper[i] = (e, v) => e.AD_HOC_FREQUENCY = v; break; case "AD_HOC_MEDICATION_LOCAT": mapper[i] = (e, v) => e.AD_HOC_MEDICATION_LOCAT = v; break; case "AD_HOC_ADMIN_BY": mapper[i] = (e, v) => e.AD_HOC_ADMIN_BY = v; break; case "HOME_MEDICATION": mapper[i] = (e, v) => e.HOME_MEDICATION = v; break; case "ASTHMA_WHEEZE": mapper[i] = (e, v) => e.ASTHMA_WHEEZE = v; break; case "ASTHMA_COUGH": mapper[i] = (e, v) => e.ASTHMA_COUGH = v; break; case "ASTHMA_DIFFBRE": mapper[i] = (e, v) => e.ASTHMA_DIFFBRE = v; break; case "ASTHMA_TGTCHES": mapper[i] = (e, v) => e.ASTHMA_TGTCHES = v; break; case "ASTHMA_SYMTEXE": mapper[i] = (e, v) => e.ASTHMA_SYMTEXE = v; break; case "ASTHMA_MGT_PLAN": mapper[i] = (e, v) => e.ASTHMA_MGT_PLAN = v; break; case "DISABILITY_ADJUSTMENT": mapper[i] = (e, v) => e.DISABILITY_ADJUSTMENT = v; break; case "ST_TRANS_ID": mapper[i] = (e, v) => e.ST_TRANS_ID = v; break; case "KCM_TRANS_ID": mapper[i] = (e, v) => e.KCM_TRANS_ID = v; break; case "IMP_STATUS": mapper[i] = (e, v) => e.IMP_STATUS = v; break; case "IMP_DATE": mapper[i] = (e, v) => e.IMP_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="SMC_TFR" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="SMC_TFR" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="SMC_TFR" /> entities</param> /// <returns>A merged <see cref="IEnumerable{SMC_TFR}"/> of entities</returns> internal override IEnumerable<SMC_TFR> ApplyDeltaEntities(IEnumerable<SMC_TFR> Entities, List<SMC_TFR> DeltaEntities) { HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.ORIG_SCHOOL; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_TID.Remove(entity.TID); if (entity.ORIG_SCHOOL.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<string, IReadOnlyList<SMC_TFR>>> Index_ORIG_SCHOOL; private Lazy<Dictionary<int, SMC_TFR>> Index_TID; #endregion #region Index Methods /// <summary> /// Find SMC_TFR by ORIG_SCHOOL field /// </summary> /// <param name="ORIG_SCHOOL">ORIG_SCHOOL value used to find SMC_TFR</param> /// <returns>List of related SMC_TFR entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SMC_TFR> FindByORIG_SCHOOL(string ORIG_SCHOOL) { return Index_ORIG_SCHOOL.Value[ORIG_SCHOOL]; } /// <summary> /// Attempt to find SMC_TFR by ORIG_SCHOOL field /// </summary> /// <param name="ORIG_SCHOOL">ORIG_SCHOOL value used to find SMC_TFR</param> /// <param name="Value">List of related SMC_TFR entities</param> /// <returns>True if the list of related SMC_TFR entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByORIG_SCHOOL(string ORIG_SCHOOL, out IReadOnlyList<SMC_TFR> Value) { return Index_ORIG_SCHOOL.Value.TryGetValue(ORIG_SCHOOL, out Value); } /// <summary> /// Attempt to find SMC_TFR by ORIG_SCHOOL field /// </summary> /// <param name="ORIG_SCHOOL">ORIG_SCHOOL value used to find SMC_TFR</param> /// <returns>List of related SMC_TFR entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SMC_TFR> TryFindByORIG_SCHOOL(string ORIG_SCHOOL) { IReadOnlyList<SMC_TFR> value; if (Index_ORIG_SCHOOL.Value.TryGetValue(ORIG_SCHOOL, out value)) { return value; } else { return null; } } /// <summary> /// Find SMC_TFR by TID field /// </summary> /// <param name="TID">TID value used to find SMC_TFR</param> /// <returns>Related SMC_TFR entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SMC_TFR FindByTID(int TID) { return Index_TID.Value[TID]; } /// <summary> /// Attempt to find SMC_TFR by TID field /// </summary> /// <param name="TID">TID value used to find SMC_TFR</param> /// <param name="Value">Related SMC_TFR entity</param> /// <returns>True if the related SMC_TFR entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTID(int TID, out SMC_TFR Value) { return Index_TID.Value.TryGetValue(TID, out Value); } /// <summary> /// Attempt to find SMC_TFR by TID field /// </summary> /// <param name="TID">TID value used to find SMC_TFR</param> /// <returns>Related SMC_TFR entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SMC_TFR TryFindByTID(int TID) { SMC_TFR value; if (Index_TID.Value.TryGetValue(TID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a SMC_TFR table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SMC_TFR]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[SMC_TFR]( [TID] int IDENTITY NOT NULL, [ORIG_SCHOOL] varchar(8) NOT NULL, [SMC_TRANS_ID] varchar(30) NULL, [SMCKEY] int NULL, [STUDENT] varchar(10) NULL, [CONDITION_EXISTS] varchar(1) NULL, [STUDENT_NEW] varchar(10) NULL, [MED_CONDITION] varchar(10) NULL, [MED_CONDITION_NEW] varchar(10) NULL, [MED_CONDITION_ACT] varchar(1) NULL, [SYMPTOMS] varchar(MAX) NULL, [SMC_COMMENT] varchar(MAX) NULL, [REGULAR_MEDICATION] varchar(60) NULL, [REGULAR_POISON_RATING] varchar(2) NULL, [REGULAR_DOSAGE] varchar(30) NULL, [REGULAR_FREQUENCY] varchar(15) NULL, [REGULAR_DOSAGE_TIME] varchar(15) NULL, [REGULAR_MEDICATION_LOCAT] varchar(30) NULL, [REGULAR_ADMIN_BY] varchar(7) NULL, [REMINDER] varchar(1) NULL, [INFORM_DOCTOR] varchar(1) NULL, [INFORM_EMERG_CONTACT] varchar(1) NULL, [ADMINISTER_MEDICATION] varchar(1) NULL, [OTHER_MEDICAL_ACTION] varchar(1) NULL, [SMC_ACTION] varchar(MAX) NULL, [AD_HOC_MEDICATION] varchar(60) NULL, [AD_HOC_POISON_RATING] varchar(2) NULL, [AD_HOC_DOSAGE] varchar(30) NULL, [AD_HOC_FREQUENCY] varchar(15) NULL, [AD_HOC_MEDICATION_LOCAT] varchar(30) NULL, [AD_HOC_ADMIN_BY] varchar(7) NULL, [HOME_MEDICATION] varchar(60) NULL, [ASTHMA_WHEEZE] varchar(1) NULL, [ASTHMA_COUGH] varchar(1) NULL, [ASTHMA_DIFFBRE] varchar(1) NULL, [ASTHMA_TGTCHES] varchar(1) NULL, [ASTHMA_SYMTEXE] varchar(1) NULL, [ASTHMA_MGT_PLAN] varchar(MAX) NULL, [DISABILITY_ADJUSTMENT] varchar(MAX) NULL, [ST_TRANS_ID] varchar(30) NULL, [KCM_TRANS_ID] varchar(30) NULL, [IMP_STATUS] varchar(15) NULL, [IMP_DATE] datetime NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [SMC_TFR_Index_TID] PRIMARY KEY NONCLUSTERED ( [TID] ASC ) ); CREATE CLUSTERED INDEX [SMC_TFR_Index_ORIG_SCHOOL] ON [dbo].[SMC_TFR] ( [ORIG_SCHOOL] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SMC_TFR]') AND name = N'SMC_TFR_Index_TID') ALTER INDEX [SMC_TFR_Index_TID] ON [dbo].[SMC_TFR] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SMC_TFR]') AND name = N'SMC_TFR_Index_TID') ALTER INDEX [SMC_TFR_Index_TID] ON [dbo].[SMC_TFR] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SMC_TFR"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="SMC_TFR"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SMC_TFR> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_TID = new List<int>(); foreach (var entity in Entities) { Index_TID.Add(entity.TID); } builder.AppendLine("DELETE [dbo].[SMC_TFR] WHERE"); // Index_TID builder.Append("[TID] IN ("); for (int index = 0; index < Index_TID.Count; index++) { if (index != 0) builder.Append(", "); // TID var parameterTID = $"@p{parameterIndex++}"; builder.Append(parameterTID); command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the SMC_TFR data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SMC_TFR data set</returns> public override EduHubDataSetDataReader<SMC_TFR> GetDataSetDataReader() { return new SMC_TFRDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the SMC_TFR data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SMC_TFR data set</returns> public override EduHubDataSetDataReader<SMC_TFR> GetDataSetDataReader(List<SMC_TFR> Entities) { return new SMC_TFRDataReader(new EduHubDataSetLoadedReader<SMC_TFR>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class SMC_TFRDataReader : EduHubDataSetDataReader<SMC_TFR> { public SMC_TFRDataReader(IEduHubDataSetReader<SMC_TFR> Reader) : base (Reader) { } public override int FieldCount { get { return 46; } } public override object GetValue(int i) { switch (i) { case 0: // TID return Current.TID; case 1: // ORIG_SCHOOL return Current.ORIG_SCHOOL; case 2: // SMC_TRANS_ID return Current.SMC_TRANS_ID; case 3: // SMCKEY return Current.SMCKEY; case 4: // STUDENT return Current.STUDENT; case 5: // CONDITION_EXISTS return Current.CONDITION_EXISTS; case 6: // STUDENT_NEW return Current.STUDENT_NEW; case 7: // MED_CONDITION return Current.MED_CONDITION; case 8: // MED_CONDITION_NEW return Current.MED_CONDITION_NEW; case 9: // MED_CONDITION_ACT return Current.MED_CONDITION_ACT; case 10: // SYMPTOMS return Current.SYMPTOMS; case 11: // SMC_COMMENT return Current.SMC_COMMENT; case 12: // REGULAR_MEDICATION return Current.REGULAR_MEDICATION; case 13: // REGULAR_POISON_RATING return Current.REGULAR_POISON_RATING; case 14: // REGULAR_DOSAGE return Current.REGULAR_DOSAGE; case 15: // REGULAR_FREQUENCY return Current.REGULAR_FREQUENCY; case 16: // REGULAR_DOSAGE_TIME return Current.REGULAR_DOSAGE_TIME; case 17: // REGULAR_MEDICATION_LOCAT return Current.REGULAR_MEDICATION_LOCAT; case 18: // REGULAR_ADMIN_BY return Current.REGULAR_ADMIN_BY; case 19: // REMINDER return Current.REMINDER; case 20: // INFORM_DOCTOR return Current.INFORM_DOCTOR; case 21: // INFORM_EMERG_CONTACT return Current.INFORM_EMERG_CONTACT; case 22: // ADMINISTER_MEDICATION return Current.ADMINISTER_MEDICATION; case 23: // OTHER_MEDICAL_ACTION return Current.OTHER_MEDICAL_ACTION; case 24: // SMC_ACTION return Current.SMC_ACTION; case 25: // AD_HOC_MEDICATION return Current.AD_HOC_MEDICATION; case 26: // AD_HOC_POISON_RATING return Current.AD_HOC_POISON_RATING; case 27: // AD_HOC_DOSAGE return Current.AD_HOC_DOSAGE; case 28: // AD_HOC_FREQUENCY return Current.AD_HOC_FREQUENCY; case 29: // AD_HOC_MEDICATION_LOCAT return Current.AD_HOC_MEDICATION_LOCAT; case 30: // AD_HOC_ADMIN_BY return Current.AD_HOC_ADMIN_BY; case 31: // HOME_MEDICATION return Current.HOME_MEDICATION; case 32: // ASTHMA_WHEEZE return Current.ASTHMA_WHEEZE; case 33: // ASTHMA_COUGH return Current.ASTHMA_COUGH; case 34: // ASTHMA_DIFFBRE return Current.ASTHMA_DIFFBRE; case 35: // ASTHMA_TGTCHES return Current.ASTHMA_TGTCHES; case 36: // ASTHMA_SYMTEXE return Current.ASTHMA_SYMTEXE; case 37: // ASTHMA_MGT_PLAN return Current.ASTHMA_MGT_PLAN; case 38: // DISABILITY_ADJUSTMENT return Current.DISABILITY_ADJUSTMENT; case 39: // ST_TRANS_ID return Current.ST_TRANS_ID; case 40: // KCM_TRANS_ID return Current.KCM_TRANS_ID; case 41: // IMP_STATUS return Current.IMP_STATUS; case 42: // IMP_DATE return Current.IMP_DATE; case 43: // LW_DATE return Current.LW_DATE; case 44: // LW_TIME return Current.LW_TIME; case 45: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 2: // SMC_TRANS_ID return Current.SMC_TRANS_ID == null; case 3: // SMCKEY return Current.SMCKEY == null; case 4: // STUDENT return Current.STUDENT == null; case 5: // CONDITION_EXISTS return Current.CONDITION_EXISTS == null; case 6: // STUDENT_NEW return Current.STUDENT_NEW == null; case 7: // MED_CONDITION return Current.MED_CONDITION == null; case 8: // MED_CONDITION_NEW return Current.MED_CONDITION_NEW == null; case 9: // MED_CONDITION_ACT return Current.MED_CONDITION_ACT == null; case 10: // SYMPTOMS return Current.SYMPTOMS == null; case 11: // SMC_COMMENT return Current.SMC_COMMENT == null; case 12: // REGULAR_MEDICATION return Current.REGULAR_MEDICATION == null; case 13: // REGULAR_POISON_RATING return Current.REGULAR_POISON_RATING == null; case 14: // REGULAR_DOSAGE return Current.REGULAR_DOSAGE == null; case 15: // REGULAR_FREQUENCY return Current.REGULAR_FREQUENCY == null; case 16: // REGULAR_DOSAGE_TIME return Current.REGULAR_DOSAGE_TIME == null; case 17: // REGULAR_MEDICATION_LOCAT return Current.REGULAR_MEDICATION_LOCAT == null; case 18: // REGULAR_ADMIN_BY return Current.REGULAR_ADMIN_BY == null; case 19: // REMINDER return Current.REMINDER == null; case 20: // INFORM_DOCTOR return Current.INFORM_DOCTOR == null; case 21: // INFORM_EMERG_CONTACT return Current.INFORM_EMERG_CONTACT == null; case 22: // ADMINISTER_MEDICATION return Current.ADMINISTER_MEDICATION == null; case 23: // OTHER_MEDICAL_ACTION return Current.OTHER_MEDICAL_ACTION == null; case 24: // SMC_ACTION return Current.SMC_ACTION == null; case 25: // AD_HOC_MEDICATION return Current.AD_HOC_MEDICATION == null; case 26: // AD_HOC_POISON_RATING return Current.AD_HOC_POISON_RATING == null; case 27: // AD_HOC_DOSAGE return Current.AD_HOC_DOSAGE == null; case 28: // AD_HOC_FREQUENCY return Current.AD_HOC_FREQUENCY == null; case 29: // AD_HOC_MEDICATION_LOCAT return Current.AD_HOC_MEDICATION_LOCAT == null; case 30: // AD_HOC_ADMIN_BY return Current.AD_HOC_ADMIN_BY == null; case 31: // HOME_MEDICATION return Current.HOME_MEDICATION == null; case 32: // ASTHMA_WHEEZE return Current.ASTHMA_WHEEZE == null; case 33: // ASTHMA_COUGH return Current.ASTHMA_COUGH == null; case 34: // ASTHMA_DIFFBRE return Current.ASTHMA_DIFFBRE == null; case 35: // ASTHMA_TGTCHES return Current.ASTHMA_TGTCHES == null; case 36: // ASTHMA_SYMTEXE return Current.ASTHMA_SYMTEXE == null; case 37: // ASTHMA_MGT_PLAN return Current.ASTHMA_MGT_PLAN == null; case 38: // DISABILITY_ADJUSTMENT return Current.DISABILITY_ADJUSTMENT == null; case 39: // ST_TRANS_ID return Current.ST_TRANS_ID == null; case 40: // KCM_TRANS_ID return Current.KCM_TRANS_ID == null; case 41: // IMP_STATUS return Current.IMP_STATUS == null; case 42: // IMP_DATE return Current.IMP_DATE == null; case 43: // LW_DATE return Current.LW_DATE == null; case 44: // LW_TIME return Current.LW_TIME == null; case 45: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // TID return "TID"; case 1: // ORIG_SCHOOL return "ORIG_SCHOOL"; case 2: // SMC_TRANS_ID return "SMC_TRANS_ID"; case 3: // SMCKEY return "SMCKEY"; case 4: // STUDENT return "STUDENT"; case 5: // CONDITION_EXISTS return "CONDITION_EXISTS"; case 6: // STUDENT_NEW return "STUDENT_NEW"; case 7: // MED_CONDITION return "MED_CONDITION"; case 8: // MED_CONDITION_NEW return "MED_CONDITION_NEW"; case 9: // MED_CONDITION_ACT return "MED_CONDITION_ACT"; case 10: // SYMPTOMS return "SYMPTOMS"; case 11: // SMC_COMMENT return "SMC_COMMENT"; case 12: // REGULAR_MEDICATION return "REGULAR_MEDICATION"; case 13: // REGULAR_POISON_RATING return "REGULAR_POISON_RATING"; case 14: // REGULAR_DOSAGE return "REGULAR_DOSAGE"; case 15: // REGULAR_FREQUENCY return "REGULAR_FREQUENCY"; case 16: // REGULAR_DOSAGE_TIME return "REGULAR_DOSAGE_TIME"; case 17: // REGULAR_MEDICATION_LOCAT return "REGULAR_MEDICATION_LOCAT"; case 18: // REGULAR_ADMIN_BY return "REGULAR_ADMIN_BY"; case 19: // REMINDER return "REMINDER"; case 20: // INFORM_DOCTOR return "INFORM_DOCTOR"; case 21: // INFORM_EMERG_CONTACT return "INFORM_EMERG_CONTACT"; case 22: // ADMINISTER_MEDICATION return "ADMINISTER_MEDICATION"; case 23: // OTHER_MEDICAL_ACTION return "OTHER_MEDICAL_ACTION"; case 24: // SMC_ACTION return "SMC_ACTION"; case 25: // AD_HOC_MEDICATION return "AD_HOC_MEDICATION"; case 26: // AD_HOC_POISON_RATING return "AD_HOC_POISON_RATING"; case 27: // AD_HOC_DOSAGE return "AD_HOC_DOSAGE"; case 28: // AD_HOC_FREQUENCY return "AD_HOC_FREQUENCY"; case 29: // AD_HOC_MEDICATION_LOCAT return "AD_HOC_MEDICATION_LOCAT"; case 30: // AD_HOC_ADMIN_BY return "AD_HOC_ADMIN_BY"; case 31: // HOME_MEDICATION return "HOME_MEDICATION"; case 32: // ASTHMA_WHEEZE return "ASTHMA_WHEEZE"; case 33: // ASTHMA_COUGH return "ASTHMA_COUGH"; case 34: // ASTHMA_DIFFBRE return "ASTHMA_DIFFBRE"; case 35: // ASTHMA_TGTCHES return "ASTHMA_TGTCHES"; case 36: // ASTHMA_SYMTEXE return "ASTHMA_SYMTEXE"; case 37: // ASTHMA_MGT_PLAN return "ASTHMA_MGT_PLAN"; case 38: // DISABILITY_ADJUSTMENT return "DISABILITY_ADJUSTMENT"; case 39: // ST_TRANS_ID return "ST_TRANS_ID"; case 40: // KCM_TRANS_ID return "KCM_TRANS_ID"; case 41: // IMP_STATUS return "IMP_STATUS"; case 42: // IMP_DATE return "IMP_DATE"; case 43: // LW_DATE return "LW_DATE"; case 44: // LW_TIME return "LW_TIME"; case 45: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "TID": return 0; case "ORIG_SCHOOL": return 1; case "SMC_TRANS_ID": return 2; case "SMCKEY": return 3; case "STUDENT": return 4; case "CONDITION_EXISTS": return 5; case "STUDENT_NEW": return 6; case "MED_CONDITION": return 7; case "MED_CONDITION_NEW": return 8; case "MED_CONDITION_ACT": return 9; case "SYMPTOMS": return 10; case "SMC_COMMENT": return 11; case "REGULAR_MEDICATION": return 12; case "REGULAR_POISON_RATING": return 13; case "REGULAR_DOSAGE": return 14; case "REGULAR_FREQUENCY": return 15; case "REGULAR_DOSAGE_TIME": return 16; case "REGULAR_MEDICATION_LOCAT": return 17; case "REGULAR_ADMIN_BY": return 18; case "REMINDER": return 19; case "INFORM_DOCTOR": return 20; case "INFORM_EMERG_CONTACT": return 21; case "ADMINISTER_MEDICATION": return 22; case "OTHER_MEDICAL_ACTION": return 23; case "SMC_ACTION": return 24; case "AD_HOC_MEDICATION": return 25; case "AD_HOC_POISON_RATING": return 26; case "AD_HOC_DOSAGE": return 27; case "AD_HOC_FREQUENCY": return 28; case "AD_HOC_MEDICATION_LOCAT": return 29; case "AD_HOC_ADMIN_BY": return 30; case "HOME_MEDICATION": return 31; case "ASTHMA_WHEEZE": return 32; case "ASTHMA_COUGH": return 33; case "ASTHMA_DIFFBRE": return 34; case "ASTHMA_TGTCHES": return 35; case "ASTHMA_SYMTEXE": return 36; case "ASTHMA_MGT_PLAN": return 37; case "DISABILITY_ADJUSTMENT": return 38; case "ST_TRANS_ID": return 39; case "KCM_TRANS_ID": return 40; case "IMP_STATUS": return 41; case "IMP_DATE": return 42; case "LW_DATE": return 43; case "LW_TIME": return 44; case "LW_USER": return 45; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
using DevExpress.Internal; using DevExpress.Mvvm.DataAnnotations; using DevExpress.Mvvm.Native; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Windows.Input; using System.Threading.Tasks; using System.Runtime.InteropServices; namespace DevExpress.Mvvm.Native { public static class ViewModelSourceHelper { public static Type GetProxyType(Type type) { return DevExpress.Mvvm.POCO.ViewModelSource.GetPOCOType(type); } public static object Create(Type type) { return DevExpress.Mvvm.POCO.ViewModelSource.Create(type); } public static bool IsPOCOViewModelType(Type type) { return DevExpress.Mvvm.POCO.ViewModelSource.IsPOCOViewModelType(type); } public static ConstructorInfo FindConstructorWithAllOptionalParameters(Type type) { return DevExpress.Mvvm.POCO.ViewModelSource.FindConstructorWithAllOptionalParameters(type); } } } namespace DevExpress.Mvvm.POCO { public interface IPOCOViewModel { void RaisePropertyChanged(string propertyName); } public class ViewModelSource { #region error messages internal const string Error_ObjectDoesntImplementIPOCOViewModel = "Object doesn't implement IPOCOViewModel."; internal const string Error_CommandNotFound = "Command not found: {0}."; internal const string Error_CommandNotAsync = "Command is not async"; const string Error_ConstructorNotFound = "Constructor not found."; const string Error_TypeHasNoCtors = "Type has no accessible constructors: {0}."; const string Error_SealedClass = "Cannot create dynamic class for the sealed class: {0}."; const string Error_InternalClass = "Cannot create dynamic class for the internal class: {0}."; const string Error_TypeImplementsIPOCOViewModel = "Type cannot implement IPOCOViewModel: {0}."; const string Error_RaisePropertyChangedMethodNotFound = "Class already supports INotifyPropertyChanged, but RaisePropertyChanged(string) method not found: {0}."; const string Error_PropertyIsNotVirual = "Cannot make non-virtual property bindable: {0}."; const string Error_PropertyHasInternalSetter = "Cannot make property with internal setter bindable: {0}."; const string Error_PropertyHasNoSetter = "Cannot make property without setter bindable: {0}."; const string Error_PropertyHasNoGetter = "Cannot make property without public getter bindable: {0}."; const string Error_PropertyIsFinal = "Cannot override final property: {0}."; const string Error_MoreThanOnePropertyChangedMethod = "More than one property changed method: {0}."; const string Error_PropertyChangedMethodShouldBePublicOrProtected = "Property changed method should be public or protected: {0}."; const string Error_PropertyChangedCantHaveMoreThanOneParameter = "Property changed method cannot have more than one parameter: {0}."; const string Error_PropertyChangedCantHaveReturnType = "Property changed method cannot have return type: {0}."; const string Error_PropertyChangedMethodArgumentTypeShouldMatchPropertyType = "Property changed method argument type should match property type: {0}."; const string Error_PropertyChangedMethodNotFound = "Property changed method not found: {0}."; const string Error_MemberWithSameCommandNameAlreadyExists = "Member with the same command name already exists: {0}."; const string Error_PropertyTypeShouldBeServiceType = "Service properties should have an interface type: {0}."; const string Error_CantAccessProperty = "Cannot access property: {0}."; const string Error_PropertyIsNotVirtual = "Property is not virtual: {0}."; const string Error_PropertyHasSetter = "Property with setter cannot be Service Property: {0}."; const string Error_ConstructorExpressionCanReferOnlyToItsArguments = "Constructor expression can refer only to its arguments."; const string Error_ConstructorExpressionCanOnlyBeOfNewExpressionType = "Constructor expression can only be of NewExpression type."; const string Error_IDataErrorInfoAlreadyImplemented = "The IDataErrorInfo interface is already implemented."; #endregion static readonly Dictionary<Type, ICustomAttributeBuilderProvider> attributeBuilderProviders = new Dictionary<Type, ICustomAttributeBuilderProvider>(); static ViewModelSource() { RegisterAttributeBuilderProvider(new DisplayAttributeBuilderProvider()); #if !SILVERLIGHT RegisterAttributeBuilderProvider(new DisplayNameAttributeBuilderProvider()); RegisterAttributeBuilderProvider(new ScaffoldColumnAttributeBuilderProvider()); #endif } static void RegisterAttributeBuilderProvider(ICustomAttributeBuilderProvider provider) { attributeBuilderProviders[provider.AttributeType] = provider; } static readonly Dictionary<Type, Type> types = new Dictionary<Type, Type>(); static readonly Dictionary<Assembly, ModuleBuilder> builders = new Dictionary<Assembly, ModuleBuilder>(); static readonly Dictionary<Type, object> Factories = new Dictionary<Type, object>(); public static T Create<T>() where T : class, new() { return Factory(() => new T())(); } public static T Create<T>(Expression<Func<T>> constructorExpression) where T : class { ValidateCtorExpression(constructorExpression, false); var actualAxpression = GetCtorExpression(constructorExpression, typeof(T), false); return Expression.Lambda<Func<T>>(actualAxpression).Compile()(); } #region GetFactory public static Func<TResult> Factory<TResult>(Expression<Func<TResult>> constructorExpression) where TResult : class { return GetFactoryCore(constructorExpression, typeof(TResult)); } public static Func<T1, TResult> Factory<T1, TResult>(Expression<Func<T1, TResult>> constructorExpression) where TResult : class { return GetFactoryCore(constructorExpression, typeof(TResult)); } public static Func<T1, T2, TResult> Factory<T1, T2, TResult>(Expression<Func<T1, T2, TResult>> constructorExpression) where TResult : class { return GetFactoryCore(constructorExpression, typeof(TResult)); } public static Func<T1, T2, T3, TResult> Factory<T1, T2, T3, TResult>(Expression<Func<T1, T2, T3, TResult>> constructorExpression) where TResult : class { return GetFactoryCore(constructorExpression, typeof(TResult)); } public static Func<T1, T2, T3, T4, TResult> Factory<T1, T2, T3, T4, TResult>(Expression<Func<T1, T2, T3, T4, TResult>> constructorExpression) where TResult : class { return GetFactoryCore(constructorExpression, typeof(TResult)); } public static Func<T1, T2, T3, T4, T5, TResult> Factory<T1, T2, T3, T4, T5, TResult>(Expression<Func<T1, T2, T3, T4, T5, TResult>> constructorExpression) where TResult : class { return GetFactoryCore(constructorExpression, typeof(TResult)); } public static Func<T1, T2, T3, T4, T5, T6, TResult> Factory<T1, T2, T3, T4, T5, T6, TResult>(Expression<Func<T1, T2, T3, T4, T5, T6, TResult>> constructorExpression) where TResult : class { return GetFactoryCore(constructorExpression, typeof(TResult)); } public static Func<T1, T2, T3, T4, T5, T6, T7, TResult> Factory<T1, T2, T3, T4, T5, T6, T7, TResult>(Expression<Func<T1, T2, T3, T4, T5, T6, T7, TResult>> constructorExpression) where TResult : class { return GetFactoryCore(constructorExpression, typeof(TResult)); } public static Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult> Factory<T1, T2, T3, T4, T5, T6, T7, T8, TResult>(Expression<Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult>> constructorExpression) where TResult : class { return GetFactoryCore(constructorExpression, typeof(TResult)); } public static Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult> Factory<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>(Expression<Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>> constructorExpression) where TResult : class { return GetFactoryCore(constructorExpression, typeof(TResult)); } public static Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult> Factory<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult>(Expression<Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult>> constructorExpression) where TResult : class { return GetFactoryCore(constructorExpression, typeof(TResult)); } #endregion #region helpers static TDelegate GetFactoryCore<TDelegate>(Expression<TDelegate> constructorExpression, Type resultType) { ValidateCtorExpression(constructorExpression, true); return GetFactoryCore<TDelegate>(() => CreateFactory(constructorExpression, resultType)); } internal static TDelegate GetFactoryCore<TDelegate>(Func<TDelegate> createFactoryDelegate) { return (TDelegate)Factories.GetOrAdd(typeof(TDelegate), () => createFactoryDelegate()); } static TDelegate CreateFactory<TDelegate>(Expression<TDelegate> constructorExpression, Type resultType) { var actualAxpression = GetCtorExpression(constructorExpression, resultType, true); return Expression.Lambda<TDelegate>(actualAxpression, constructorExpression.Parameters).Compile(); } static void ValidateCtorExpression(LambdaExpression constructorExpression, bool useOnlyParameters) { NewExpression newExpression = constructorExpression.Body as NewExpression; if(newExpression != null) { if(useOnlyParameters) { foreach(var item in newExpression.Arguments) { if(!(item is ParameterExpression)) throw new ViewModelSourceException(Error_ConstructorExpressionCanReferOnlyToItsArguments); } } return; } if(!useOnlyParameters) { MemberInitExpression memberInitExpression = constructorExpression.Body as MemberInitExpression; if(memberInitExpression != null) { return; } } throw new ViewModelSourceException(Error_ConstructorExpressionCanOnlyBeOfNewExpressionType); } static Expression GetCtorExpression(LambdaExpression constructorExpression, Type resultType, bool useOnlyParameters) { Type type = GetPOCOType(resultType); NewExpression newExpression = constructorExpression.Body as NewExpression; if(newExpression != null) { return GetNewExpression(type, newExpression); } MemberInitExpression memberInitExpression = constructorExpression.Body as MemberInitExpression; if(memberInitExpression != null) { return Expression.MemberInit(GetNewExpression(type, memberInitExpression.NewExpression), memberInitExpression.Bindings); } throw new ArgumentException("constructorExpression"); } static NewExpression GetNewExpression(Type type, NewExpression newExpression) { var actualCtor = GetConstructor(type, newExpression.Constructor.GetParameters().Select(x => x.ParameterType).ToArray()); return Expression.New(actualCtor, newExpression.Arguments); } internal static object Create(Type type) { Type pocoType = GetPOCOType(type); var defaultCtor = pocoType.GetConstructor(new Type[0]); if(defaultCtor != null) return defaultCtor.Invoke(null); defaultCtor = FindConstructorWithAllOptionalParameters(type); if(defaultCtor != null) return pocoType.GetConstructor(defaultCtor.GetParameters().Select(x => x.ParameterType).ToArray()).Invoke(defaultCtor.GetParameters().Select(x => x.DefaultValue).ToArray()); return Activator.CreateInstance(GetPOCOType(type)); } internal static ConstructorInfo FindConstructorWithAllOptionalParameters(Type type) { return type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) .FirstOrDefault(x => (x.Attributes.HasFlag(MethodAttributes.Public) || x.Attributes.HasFlag(MethodAttributes.Family)) && x.GetParameters().All(y => y.IsOptional)); } public static Type GetPOCOType(Type type) { return types.GetOrAdd(type, () => CreateType(type)); } internal static ConstructorInfo GetConstructor(Type proxyType, Type[] argsTypes) { var ctor = proxyType.GetConstructor(argsTypes ?? Type.EmptyTypes); if(ctor == null) throw new ViewModelSourceException(Error_ConstructorNotFound); return ctor; } static bool CanAccessFromDescendant(MethodBase method) { return method.IsPublic || method.IsFamily || method.IsFamilyOrAssembly; } internal static bool IsPOCOViewModelType(Type type) { try { if(!CheckType(type, false)) return false; if(type.GetCustomAttributes(typeof(POCOViewModelAttribute), true).Any()) return true; if(GetCommandMethods(type).Any() && !type.GetProperties().Where(x => typeof(ICommand).IsAssignableFrom(x.PropertyType)).Any()) return true; if(GetBindableProperties(type).Any() && !typeof(INotifyPropertyChanged).IsAssignableFrom(type)) return true; return false; } catch { return false; } } #endregion static Type CreateType(Type type) { CheckType(type, true); ModuleBuilder moduleBuilder = GetModuleBuilder(type.Assembly); TypeBuilder typeBuilder = CreateTypeBuilder(moduleBuilder, type); BuildConstructors(type, typeBuilder); var raisePropertyChangedMethod = ImplementINotifyPropertyChanged(type, typeBuilder); ImplementIPOCOViewModel(typeBuilder, raisePropertyChangedMethod); BuildBindableProperties(type, typeBuilder, raisePropertyChangedMethod); BuildCommands(type, typeBuilder); ImplementISupportServices(type, typeBuilder); ImplementISupportParentViewModel(type, typeBuilder); BuildServiceProperties(type, typeBuilder); ImplementIDataErrorInfo(type, typeBuilder); return typeBuilder.CreateType(); } static MethodBuilder BuildExplicitStringGetterOverride(TypeBuilder typeBuilder, string propertyName, MethodInfo methodToCall, Type interfaceType, Type argument = null) { MethodAttributes methodAttributes = MethodAttributes.Private | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.SpecialName; var method = typeBuilder.DefineMethod(interfaceType.FullName + ".get_" + propertyName, methodAttributes, typeof(string), argument != null ? new[] { argument } : Type.EmptyTypes); ILGenerator gen = method.GetILGenerator(); if(methodToCall != null) { gen.Emit(OpCodes.Ldarg_0); if(argument != null) gen.Emit(OpCodes.Ldarg_1); gen.Emit(OpCodes.Call, methodToCall); } else { gen.Emit(OpCodes.Ldsfld, typeof(string).GetField("Empty")); } gen.Emit(OpCodes.Ret); typeBuilder.DefineMethodOverride(method, interfaceType.GetProperty(propertyName).GetGetMethod()); return method; } static bool ShouldImplementIDataErrorInfo(Type type) { var pocoViewModelAttr = (POCOViewModelAttribute)type.GetCustomAttributes(typeof(POCOViewModelAttribute), false).FirstOrDefault(); bool implement = pocoViewModelAttr == null ? false : pocoViewModelAttr.ImplementIDataErrorInfo; if(type.GetInterfaces().Contains(typeof(IDataErrorInfo)) && implement) throw new ViewModelSourceException(Error_IDataErrorInfoAlreadyImplemented); return implement; } static void ImplementIDataErrorInfo(Type type, TypeBuilder typeBuilder) { if(!ShouldImplementIDataErrorInfo(type)) return; var errorGetter = BuildExplicitStringGetterOverride(typeBuilder, "Error", null, typeof(IDataErrorInfo)); var errorProperty = typeBuilder.DefineProperty("Error", PropertyAttributes.None, typeof(string), new Type[0]); errorProperty.SetGetMethod(errorGetter); var indexerGetterImpl = typeof(IDataErrorInfoHelper).GetMethod("GetErrorText", BindingFlags.Public | BindingFlags.Static); var indexerGetter = BuildExplicitStringGetterOverride(typeBuilder, "Item", indexerGetterImpl, typeof(IDataErrorInfo), typeof(string)); var indexer = typeBuilder.DefineProperty("Item", PropertyAttributes.None, typeof(string), new[] { typeof(string) }); indexer.SetGetMethod(indexerGetter); ConstructorInfo ciDefaultMemberAttribute = typeof(DefaultMemberAttribute).GetConstructor(new Type[] { typeof(string) }); CustomAttributeBuilder abDefaultMemberAttribute = new CustomAttributeBuilder(ciDefaultMemberAttribute, new object[] { "Item" }); typeBuilder.SetCustomAttribute(abDefaultMemberAttribute); } private static bool CheckType(Type type, bool @throw) { if(!type.IsPublic && !type.IsNestedPublic) return ReturnFalseOrThrow(@throw, Error_InternalClass, type); if(type.IsSealed) return ReturnFalseOrThrow(@throw, Error_SealedClass, type); if(typeof(IPOCOViewModel).IsAssignableFrom(type)) return ReturnFalseOrThrow(@throw, Error_TypeImplementsIPOCOViewModel, type); return true; } static ModuleBuilder GetModuleBuilder(Assembly assembly) { return builders.GetOrAdd(assembly, () => CreateBuilder()); } static ModuleBuilder CreateBuilder() { var assemblyName = new AssemblyName(); assemblyName.Name = AssemblyInfo.SRAssemblyXpfMvvm + ".DynamicTypes." + Guid.NewGuid().ToString(); var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); return assemblyBuilder.DefineDynamicModule(assemblyName.Name, false); } #region constructors static void BuildConstructors(Type type, TypeBuilder typeBuilder) { var ctors = type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Where(x => CanAccessFromDescendant(x)).ToArray(); if(!ctors.Any()) { throw new ViewModelSourceException(string.Format(Error_TypeHasNoCtors, type.Name)); } foreach(ConstructorInfo constructor in ctors) { BuildConstructor(typeBuilder, constructor); } } static ConstructorBuilder BuildConstructor(TypeBuilder type, ConstructorInfo baseConstructor) { MethodAttributes methodAttributes = MethodAttributes.Public; var parameters = baseConstructor.GetParameters(); ConstructorBuilder method = type.DefineConstructor(methodAttributes, CallingConventions.Standard, parameters.Select(x => x.ParameterType).ToArray()); ILGenerator gen = method.GetILGenerator(); gen.Emit(OpCodes.Ldarg_0); for(int i = 0; i < parameters.Length; i++) { gen.Emit(OpCodes.Ldarg_S, i + 1); } gen.Emit(OpCodes.Call, baseConstructor); gen.Emit(OpCodes.Ret); return method; } #endregion #region bindable properties static void BuildBindableProperties(Type type, TypeBuilder typeBuilder, MethodInfo raisePropertyChangedMethod) { foreach(var propertyInfo in GetBindableProperties(type)) { var getter = BuildBindablePropertyGetter(typeBuilder, propertyInfo.GetGetMethod()); typeBuilder.DefineMethodOverride(getter, propertyInfo.GetGetMethod()); MethodInfo propertyChangedMethod = GetPropertyChangedMethod(type, propertyInfo, "Changed", x => x.OnPropertyChangedMethodName, x => x.OnPropertyChangedMethod); MethodInfo propertyChangingMethod = GetPropertyChangedMethod(type, propertyInfo, "Changing", x => x.OnPropertyChangingMethodName, x => x.OnPropertyChangingMethod); var setter = BuildBindablePropertySetter(typeBuilder, raisePropertyChangedMethod, propertyInfo, propertyChangedMethod, propertyChangingMethod); typeBuilder.DefineMethodOverride(setter, propertyInfo.GetSetMethod(true)); var newProperty = typeBuilder.DefineProperty(propertyInfo.Name, PropertyAttributes.None, propertyInfo.PropertyType, new Type[0]); newProperty.SetGetMethod(getter); newProperty.SetSetMethod(setter); } } static IEnumerable<PropertyInfo> GetBindableProperties(Type type) { return type.GetProperties().Where(x => IsBindableProperty(x)); } static bool IsBindableProperty(PropertyInfo propertyInfo) { var bindable = GetBindablePropertyAttribute(propertyInfo); if(bindable != null && !bindable.IsBindable) return false; var getMethod = propertyInfo.GetGetMethod(); var setMethod = propertyInfo.GetSetMethod(true); if(getMethod == null) return ReturnFalseOrThrow(bindable, Error_PropertyHasNoGetter, propertyInfo); if(!getMethod.IsVirtual) return ReturnFalseOrThrow(bindable, Error_PropertyIsNotVirual, propertyInfo); if(getMethod.IsFinal) return ReturnFalseOrThrow(bindable, Error_PropertyIsFinal, propertyInfo); if(setMethod == null) return ReturnFalseOrThrow(bindable, Error_PropertyHasNoSetter, propertyInfo); if(setMethod.IsAssembly) return ReturnFalseOrThrow(bindable, Error_PropertyHasInternalSetter, propertyInfo); if(!(IsAutoImplemented(propertyInfo))) return bindable != null && bindable.IsBindable; return true; } static BindablePropertyAttribute GetBindablePropertyAttribute(PropertyInfo propertyInfo) { return GetAttribute<BindablePropertyAttribute>(propertyInfo); } static MethodInfo GetPropertyChangedMethod(Type type, PropertyInfo propertyInfo, string methodNameSuffix, Func<BindablePropertyAttribute, string> getMethodName, Func<BindablePropertyAttribute, MethodInfo> getMethod) { var bindable = GetBindablePropertyAttribute(propertyInfo); if(bindable != null && getMethod(bindable) != null) { CheckOnChangedMethod(getMethod(bindable), propertyInfo.PropertyType); return getMethod(bindable); } bool hasCustomPropertyChangedMethodName = bindable != null && !string.IsNullOrEmpty(getMethodName(bindable)); if(!hasCustomPropertyChangedMethodName && !(IsAutoImplemented(propertyInfo))) return null; string onChangedMethodName = hasCustomPropertyChangedMethodName ? getMethodName(bindable) : "On" + propertyInfo.Name + methodNameSuffix; MethodInfo[] changedMethods = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance) .Where(x => x.Name == onChangedMethodName).ToArray(); if(changedMethods.Length > 1) throw new ViewModelSourceException(string.Format(Error_MoreThanOnePropertyChangedMethod, propertyInfo.Name)); if(hasCustomPropertyChangedMethodName && !changedMethods.Any()) throw new ViewModelSourceException(string.Format(Error_PropertyChangedMethodNotFound, onChangedMethodName)); changedMethods.FirstOrDefault().Do(x => CheckOnChangedMethod(x, propertyInfo.PropertyType)); return changedMethods.FirstOrDefault(); } static void CheckOnChangedMethod(MethodInfo method, Type propertyType) { if(!CanAccessFromDescendant(method)) { throw new ViewModelSourceException(string.Format(Error_PropertyChangedMethodShouldBePublicOrProtected, method.Name)); } if(method.GetParameters().Length >= 2) { throw new ViewModelSourceException(string.Format(Error_PropertyChangedCantHaveMoreThanOneParameter, method.Name)); } if(method.GetParameters().Length == 1 && method.GetParameters()[0].ParameterType != propertyType) { throw new ViewModelSourceException(string.Format(Error_PropertyChangedMethodArgumentTypeShouldMatchPropertyType, method.Name)); } if(method.ReturnType != typeof(void)) { throw new ViewModelSourceException(string.Format(Error_PropertyChangedCantHaveReturnType, method.Name)); } } static bool IsAutoImplemented(PropertyInfo property) { if(property.GetGetMethod().GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).Any()) return true; if(property.GetSetMethod(true).GetParameters().Single().Name != "AutoPropertyValue") return false; FieldInfo field = property.DeclaringType.GetField("_" + property.Name, BindingFlags.Instance | BindingFlags.NonPublic); return field != null && field.FieldType == property.PropertyType && field.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).Any(); } static MethodBuilder BuildBindablePropertyGetter(TypeBuilder type, MethodInfo originalGetter) { MethodAttributes methodAttributes = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig; MethodBuilder method = type.DefineMethod(originalGetter.Name, methodAttributes); method.SetReturnType(originalGetter.ReturnType); ILGenerator gen = method.GetILGenerator(); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Call, originalGetter); gen.Emit(OpCodes.Ret); return method; } static MethodBuilder BuildBindablePropertySetter(TypeBuilder type, MethodInfo raisePropertyChangedMethod, PropertyInfo property, MethodInfo propertyChangedMethod, MethodInfo propertyChangingMethod) { var setMethod = property.GetSetMethod(true); MethodAttributes methodAttributes = (setMethod.IsPublic ? MethodAttributes.Public : MethodAttributes.Family) | MethodAttributes.Virtual | MethodAttributes.HideBySig; MethodBuilder method = type.DefineMethod(setMethod.Name, methodAttributes); Expression<Action> equalsExpression = () => object.Equals(null, null); method.SetReturnType(typeof(void)); method.SetParameters(property.PropertyType); bool shouldBoxValues = property.PropertyType.IsValueType; ParameterBuilder value = method.DefineParameter(1, ParameterAttributes.None, "value"); ILGenerator gen = method.GetILGenerator(); gen.DeclareLocal(property.PropertyType); Label returnLabel = gen.DefineLabel(); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Call, property.GetGetMethod()); gen.Emit(OpCodes.Stloc_0); gen.Emit(OpCodes.Ldloc_0); if(shouldBoxValues) gen.Emit(OpCodes.Box, property.PropertyType); gen.Emit(OpCodes.Ldarg_1); if(shouldBoxValues) gen.Emit(OpCodes.Box, property.PropertyType); gen.Emit(OpCodes.Call, ExpressionHelper.GetMethod(equalsExpression)); gen.Emit(OpCodes.Brtrue_S, returnLabel); if(propertyChangingMethod != null) { gen.Emit(OpCodes.Ldarg_0); if(propertyChangingMethod.GetParameters().Length == 1) gen.Emit(OpCodes.Ldarg_1); gen.Emit(OpCodes.Call, propertyChangingMethod); } gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldarg_1); gen.Emit(OpCodes.Call, setMethod); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldstr, property.Name); gen.Emit(OpCodes.Call, raisePropertyChangedMethod); if(propertyChangedMethod != null) { gen.Emit(OpCodes.Ldarg_0); if(propertyChangedMethod.GetParameters().Length == 1) gen.Emit(OpCodes.Ldloc_0); gen.Emit(OpCodes.Call, propertyChangedMethod); } gen.MarkLabel(returnLabel); gen.Emit(OpCodes.Ret); return method; } #endregion #region INotifyPropertyChanged implementation static MethodBuilder BuildGetPropertyChangedHelperMethod(TypeBuilder type) { FieldBuilder propertyChangedHelperField = type.DefineField("propertyChangedHelper", typeof(PropertyChangedHelper), FieldAttributes.Private); MethodAttributes methodAttributes = MethodAttributes.Private | MethodAttributes.HideBySig; MethodBuilder method = type.DefineMethod("GetHelper", methodAttributes); Expression<Func<PropertyChangedHelper>> createHelperExpression = () => new PropertyChangedHelper(); ConstructorInfo helperCtor = ExpressionHelper.GetConstructor(createHelperExpression); method.SetReturnType(typeof(PropertyChangedHelper)); ILGenerator gen = method.GetILGenerator(); gen.DeclareLocal(typeof(PropertyChangedHelper)); Label returnLabel = gen.DefineLabel(); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldfld, propertyChangedHelperField); gen.Emit(OpCodes.Dup); gen.Emit(OpCodes.Brtrue_S, returnLabel); gen.Emit(OpCodes.Pop); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Newobj, helperCtor); gen.Emit(OpCodes.Dup); gen.Emit(OpCodes.Stloc_0); gen.Emit(OpCodes.Stfld, propertyChangedHelperField); gen.Emit(OpCodes.Ldloc_0); gen.MarkLabel(returnLabel); gen.Emit(OpCodes.Ret); return method; } static MethodBuilder BuildRaisePropertyChangedMethod(TypeBuilder type, MethodInfo getHelperMethod) { MethodAttributes methodAttributes = MethodAttributes.Family | MethodAttributes.HideBySig; MethodBuilder method = type.DefineMethod("RaisePropertyChanged", methodAttributes); Expression<Action> onPropertyChangedExpression = () => new PropertyChangedHelper().OnPropertyChanged(null, null); method.SetReturnType(typeof(void)); method.SetParameters(typeof(String)); ParameterBuilder propertyName = method.DefineParameter(1, ParameterAttributes.None, "propertyName"); ILGenerator gen = method.GetILGenerator(); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Call, getHelperMethod); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldarg_1); gen.Emit(OpCodes.Callvirt, ExpressionHelper.GetMethod(onPropertyChangedExpression)); gen.Emit(OpCodes.Ret); return method; } static MethodInfo ImplementINotifyPropertyChanged(Type baseType, TypeBuilder typeBuilder) { MethodInfo raisePropertyChangedMethod; if(typeof(INotifyPropertyChanged).IsAssignableFrom(baseType)) { raisePropertyChangedMethod = baseType.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public) .FirstOrDefault(x => { var parameters = x.GetParameters(); return x.Name == "RaisePropertyChanged" && CanAccessFromDescendant(x) && parameters.Length == 1 && parameters[0].ParameterType == typeof(string) && !parameters[0].IsOut && !parameters[0].ParameterType.IsByRef; }); if(raisePropertyChangedMethod == null) throw new ViewModelSourceException(string.Format(Error_RaisePropertyChangedMethodNotFound, baseType.Name)); } else { var getHelperMethod = BuildGetPropertyChangedHelperMethod(typeBuilder); raisePropertyChangedMethod = BuildRaisePropertyChangedMethod(typeBuilder, getHelperMethod); var addHandler = BuildAddRemovePropertyChangedHandler(typeBuilder, getHelperMethod, "add", () => new PropertyChangedHelper().AddHandler(null)); typeBuilder.DefineMethodOverride(addHandler, typeof(INotifyPropertyChanged).GetMethod("add_PropertyChanged")); var removeHandler = BuildAddRemovePropertyChangedHandler(typeBuilder, getHelperMethod, "remove", () => new PropertyChangedHelper().RemoveHandler(null)); typeBuilder.DefineMethodOverride(removeHandler, typeof(INotifyPropertyChanged).GetMethod("remove_PropertyChanged")); } return raisePropertyChangedMethod; } static MethodBuilder BuildAddRemovePropertyChangedHandler(TypeBuilder type, MethodInfo getHelperMethod, string methodName, Expression<Action> addRemoveHandlerExpression) { MethodAttributes methodAttributes = MethodAttributes.Private | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.HideBySig | MethodAttributes.NewSlot; MethodBuilder method = type.DefineMethod(typeof(INotifyPropertyChanged).FullName + "." + methodName + "_PropertyChanged", methodAttributes); method.SetReturnType(typeof(void)); method.SetParameters(typeof(PropertyChangedEventHandler)); ParameterBuilder value = method.DefineParameter(1, ParameterAttributes.None, "value"); ILGenerator gen = method.GetILGenerator(); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Call, getHelperMethod); gen.Emit(OpCodes.Ldarg_1); gen.Emit(OpCodes.Callvirt, ExpressionHelper.GetMethod(addRemoveHandlerExpression)); gen.Emit(OpCodes.Ret); return method; } #endregion #region IPOCOViewModel implementation static void ImplementIPOCOViewModel(TypeBuilder typeBuilder, MethodInfo raisePropertyChangedMethod) { var raisePropertyChangedMethodImplementation = BuildIPOCOViewModel_RaisePropertyChangedMethod(typeBuilder, raisePropertyChangedMethod); IPOCOViewModel pocoViewModel = null; Expression<Action> raisePropertyChangedExpression = () => pocoViewModel.RaisePropertyChanged(null); typeBuilder.DefineMethodOverride(raisePropertyChangedMethodImplementation, ExpressionHelper.GetMethod(raisePropertyChangedExpression)); } static MethodBuilder BuildIPOCOViewModel_RaisePropertyChangedMethod(TypeBuilder type, MethodInfo raisePropertyChangedMethod) { MethodAttributes methodAttributes = MethodAttributes.Private | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.HideBySig | MethodAttributes.NewSlot; MethodBuilder method = type.DefineMethod("DevExpress.Mvvm.Native.IPOCOViewModel.RaisePropertyChanged", methodAttributes); method.SetReturnType(typeof(void)); method.SetParameters(typeof(String)); ParameterBuilder propertyName = method.DefineParameter(1, ParameterAttributes.None, "propertyName"); ILGenerator gen = method.GetILGenerator(); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldarg_1); gen.Emit(OpCodes.Call, raisePropertyChangedMethod); gen.Emit(OpCodes.Ret); return method; } #endregion static TypeBuilder CreateTypeBuilder(ModuleBuilder module, Type baseType) { List<Type> interfaces = new List<Type>(new[] { typeof(INotifyPropertyChanged), typeof(IPOCOViewModel), typeof(ISupportServices), typeof(ISupportParentViewModel) }); if(ShouldImplementIDataErrorInfo(baseType)) { interfaces.Add(typeof(IDataErrorInfo)); } string typeName = baseType.Name + "_" + Guid.NewGuid().ToString().Replace('-', '_'); return module.DefineType(typeName, TypeAttributes.Public, baseType, interfaces.ToArray()); } static T GetAttribute<T>(MemberInfo member) where T : Attribute { return MetadataHelper.GetAttribute<T>(member); } static bool ReturnFalseOrThrow(Attribute attribute, string text, PropertyInfo property) { if(attribute != null) throw new ViewModelSourceException(string.Format(text, property.Name)); return false; } static bool ReturnFalseOrThrow(bool @throw, string text, Type type) { if(@throw) throw new ViewModelSourceException(string.Format(text, type.Name)); return false; } #region commands static void BuildCommands(Type type, TypeBuilder typeBuilder) { MethodInfo[] methods = GetCommandMethods(type).ToArray(); foreach(var commandMethod in methods) { CommandAttribute attribute = ViewModelBase.GetAttribute<CommandAttribute>(commandMethod); bool isAsyncCommand = commandMethod.ReturnType == typeof(Task); string commandName = GetCommandName(commandMethod); if(type.GetMember(commandName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public).Any() || methods.Any(x => GetCommandName(x) == commandName && x != commandMethod)) throw new ViewModelSourceException(string.Format(Error_MemberWithSameCommandNameAlreadyExists, commandName)); MethodInfo canExecuteMethod = GetCanExecuteMethod(type, commandMethod); bool? useCommandManager = attribute != null ? attribute.GetUseCommandManager() : null; var getMethod = BuildGetCommandMethod(typeBuilder, commandMethod, canExecuteMethod, commandName, useCommandManager, isAsyncCommand); PropertyBuilder commandProperty = typeBuilder.DefineProperty(commandName, PropertyAttributes.None, getMethod.ReturnType, null); commandProperty.SetGetMethod(getMethod); BuildCommandPropertyAttributes(commandProperty, commandMethod); } } static IEnumerable<MethodInfo> GetCommandMethods(Type type) { return type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic).Where(x => IsCommandMethod(type, x)); } static bool IsCommandMethod(Type type, MethodInfo method) { ParameterInfo[] parameters = method.GetParameters(); CommandAttribute attribute = ViewModelBase.GetAttribute<CommandAttribute>(method); if(attribute != null && !attribute.IsCommand) return false; if(attribute == null) { if(!method.IsPublic) return false; } else { if(!CanAccessFromDescendant(method)) throw new ViewModelSourceException(string.Format(ViewModelBase.Error_MethodShouldBePublic, method.Name)); } string commandName = GetCommandName(method); if(method.IsSpecialName || method.DeclaringType == typeof(object) || type.GetProperty(commandName) != null) return false; if((method.ReturnType != typeof(void) && method.ReturnType != typeof(Task)) && attribute == null) return false; if(!ViewModelBase.ValidateCommandMethodParameters(method, x => new ViewModelSourceException(x))) return false; return true; } internal static string GetCommandName(MethodInfo method) { CommandAttribute commandAttribute = ViewModelBase.GetAttribute<CommandAttribute>(method); return (commandAttribute != null && !string.IsNullOrEmpty(commandAttribute.Name)) ? commandAttribute.Name : ViewModelBase.GetCommandName(method); } static MethodInfo GetCanExecuteMethod(Type type, MethodInfo method) { return ViewModelBase.GetCanExecuteMethod(type, method, ViewModelBase.GetAttribute<CommandAttribute>(method), x => new ViewModelSourceException(x), CanAccessFromDescendant); } static MethodBuilder BuildGetCommandMethod(TypeBuilder type, MethodInfo commandMethod, MethodInfo canExecuteMethod, string commandName, bool? useCommandManager, bool isAsyncCommand) { bool hasParameter = commandMethod.GetParameters().Length == 1; bool isCommandMethodReturnTypeVoid = commandMethod.ReturnType == typeof(void); Type commandMethodReturnType = commandMethod.ReturnType; Type parameterType = hasParameter ? commandMethod.GetParameters()[0].ParameterType : null; Type commandPropertyType = isAsyncCommand ? hasParameter ? typeof(AsyncCommand<>).MakeGenericType(parameterType) : typeof(AsyncCommand) : hasParameter ? typeof(DelegateCommand<>).MakeGenericType(parameterType) : typeof(ICommand); var commandField = type.DefineField("_" + commandName, commandPropertyType, FieldAttributes.Private); MethodAttributes methodAttributes = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig; MethodBuilder method = type.DefineMethod("get_" + commandName, methodAttributes); ConstructorInfo actionConstructor = (hasParameter ? (isCommandMethodReturnTypeVoid ? typeof(Action<>).MakeGenericType(parameterType) : typeof(Func<,>).MakeGenericType(parameterType, commandMethodReturnType)) : (isCommandMethodReturnTypeVoid ? typeof(Action) : typeof(Func<>).MakeGenericType(commandMethodReturnType))) .GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, new Type[] { typeof(Object), typeof(IntPtr) }, null); ConstructorInfo funcConstructor = (hasParameter ? typeof(Func<,>).MakeGenericType(parameterType, typeof(bool)) : typeof(Func<bool>)).GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, new Type[] { typeof(Object), typeof(IntPtr) }, null); MethodInfo createCommandMethod; if(isAsyncCommand) createCommandMethod = hasParameter ? AsyncCommandFactory.GetGenericMethodWithResult(parameterType, commandMethodReturnType, useCommandManager != null) : AsyncCommandFactory.GetSimpleMethodWithResult(commandMethodReturnType, useCommandManager != null); else createCommandMethod = hasParameter ? (isCommandMethodReturnTypeVoid ? DelegateCommandFactory.GetGenericMethodWithoutResult(parameterType, useCommandManager != null) : DelegateCommandFactory.GetGenericMethodWithResult(parameterType, commandMethodReturnType, useCommandManager != null)) : (isCommandMethodReturnTypeVoid ? DelegateCommandFactory.GetSimpleMethodWithoutResult(useCommandManager != null) : DelegateCommandFactory.GetSimpleMethodWithResult(commandMethodReturnType, useCommandManager != null)); method.SetReturnType(commandPropertyType); ILGenerator gen = method.GetILGenerator(); gen.DeclareLocal(commandPropertyType); Label returnLabel = gen.DefineLabel(); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldfld, commandField); gen.Emit(OpCodes.Dup); gen.Emit(OpCodes.Brtrue_S, returnLabel); gen.Emit(OpCodes.Pop); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldftn, commandMethod); gen.Emit(OpCodes.Newobj, actionConstructor); if(canExecuteMethod != null) { gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldftn, canExecuteMethod); gen.Emit(OpCodes.Newobj, funcConstructor); } else { gen.Emit(OpCodes.Ldnull); } if(isAsyncCommand) { AsyncCommandAttribute attribute = ViewModelBase.GetAttribute<AsyncCommandAttribute>(commandMethod); bool allowMultipleExecution=attribute != null ? attribute.AllowMultipleExecution : false; gen.Emit(allowMultipleExecution ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); } if(useCommandManager != null) gen.Emit(useCommandManager.Value ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); gen.Emit(OpCodes.Call, createCommandMethod); gen.Emit(OpCodes.Dup); gen.Emit(OpCodes.Stloc_0); gen.Emit(OpCodes.Stfld, commandField); gen.Emit(OpCodes.Ldloc_0); gen.MarkLabel(returnLabel); gen.Emit(OpCodes.Ret); return method; } static void BuildCommandPropertyAttributes(PropertyBuilder commandProperty, MethodInfo commandMethod) { foreach(Attribute attribute in MetadataHelper.GetAllAttributes(commandMethod)) { ICustomAttributeBuilderProvider provider; if(attributeBuilderProviders.TryGetValue(attribute.GetType(), out provider)) commandProperty.SetCustomAttribute(provider.CreateAttributeBuilder(attribute)); } } #endregion #region services static void ImplementISupportServices(Type type, TypeBuilder typeBuilder) { if(typeof(ISupportServices).IsAssignableFrom(type)) return; Expression<Func<ISupportServices, IServiceContainer>> getServiceContainerExpression = x => x.ServiceContainer; var getter = ExpressionHelper.GetArgumentPropertyStrict(getServiceContainerExpression).GetGetMethod(); FieldBuilder serviceContainerField = typeBuilder.DefineField("serviceContainer", typeof(IServiceContainer), FieldAttributes.Private); var getServiceContainerMethod = BuildGetServiceContainerMethod(typeBuilder, serviceContainerField, getter.Name); typeBuilder.DefineMethodOverride(getServiceContainerMethod, getter); } static MethodBuilder BuildGetServiceContainerMethod(TypeBuilder type, FieldInfo serviceContainerField, string getServiceContainerMethodName) { MethodAttributes methodAttributes = MethodAttributes.Private | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.HideBySig | MethodAttributes.NewSlot; MethodBuilder method = type.DefineMethod(typeof(ISupportServices).FullName + "." + getServiceContainerMethodName, methodAttributes); Expression<Func<ServiceContainer>> serviceContainerCtorExpression = () => new ServiceContainer(null); method.SetReturnType(typeof(IServiceContainer)); ILGenerator gen = method.GetILGenerator(); gen.DeclareLocal(typeof(IServiceContainer)); Label returnLabel = gen.DefineLabel(); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldfld, serviceContainerField); gen.Emit(OpCodes.Dup); gen.Emit(OpCodes.Brtrue_S, returnLabel); gen.Emit(OpCodes.Pop); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Newobj, ExpressionHelper.GetConstructor(serviceContainerCtorExpression)); gen.Emit(OpCodes.Dup); gen.Emit(OpCodes.Stloc_0); gen.Emit(OpCodes.Stfld, serviceContainerField); gen.Emit(OpCodes.Ldloc_0); gen.MarkLabel(returnLabel); gen.Emit(OpCodes.Ret); return method; } static void BuildServiceProperties(Type type, TypeBuilder typeBuilder) { var serviceProperties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(x => IsServiceProperty(x)).ToArray(); foreach(var propertyInfo in serviceProperties) { ServicePropertyAttribute attribute = GetAttribute<ServicePropertyAttribute>(propertyInfo); bool required = DataAnnotationsAttributeHelper.HasRequiredAttribute(propertyInfo); var getter = BuildGetServicePropertyMethod(typeBuilder, propertyInfo, attribute.With(x => x.Key), attribute.Return(x => x.SearchMode, () => default(ServiceSearchMode)), required); typeBuilder.DefineMethodOverride(getter, propertyInfo.GetGetMethod(true)); var newProperty = typeBuilder.DefineProperty(propertyInfo.Name, PropertyAttributes.None, propertyInfo.PropertyType, Type.EmptyTypes); newProperty.SetGetMethod(getter); } } static bool IsServiceProperty(PropertyInfo property) { ServicePropertyAttribute attribute = GetAttribute<ServicePropertyAttribute>(property); if(attribute != null && !attribute.IsServiceProperty) return false; if(!property.PropertyType.Name.EndsWith("Service") && attribute == null) return false; if(!property.PropertyType.IsInterface) return ReturnFalseOrThrow(attribute, Error_PropertyTypeShouldBeServiceType, property); var getter = property.GetGetMethod(true); if(!CanAccessFromDescendant(getter)) return ReturnFalseOrThrow(attribute, Error_CantAccessProperty, property); if(!getter.IsVirtual) return ReturnFalseOrThrow(attribute, Error_PropertyIsNotVirtual, property); if(getter.IsFinal) return ReturnFalseOrThrow(attribute, Error_PropertyIsFinal, property); if(property.GetSetMethod(true) != null) return ReturnFalseOrThrow(attribute, Error_PropertyHasSetter, property); return true; } static MethodBuilder BuildGetServicePropertyMethod(TypeBuilder type, PropertyInfo property, string serviceName, ServiceSearchMode searchMode, bool required) { var getMethod = property.GetGetMethod(true); MethodAttributes methodAttributes = (getMethod.IsPublic ? MethodAttributes.Public : MethodAttributes.Family) | MethodAttributes.Virtual | MethodAttributes.HideBySig; MethodBuilder method = type.DefineMethod(getMethod.Name, methodAttributes); method.SetReturnType(property.PropertyType); ILGenerator gen = method.GetILGenerator(); if(required) EmitGetRequiredServicePropertyMethod(property.PropertyType, serviceName, searchMode, gen); else EmitGetOptionalServicePropertyMethod(property.PropertyType, serviceName, searchMode, gen); return method; } static void EmitGetOptionalServicePropertyMethod(Type serviceType, string serviceName, ServiceSearchMode searchMode, ILGenerator gen) { Expression<Func<ISupportServices, IServiceContainer>> serviceContainerPropertyExpression = x => x.ServiceContainer; Type[] getServiceMethodParams = string.IsNullOrEmpty(serviceName) ? new Type[] { typeof(ServiceSearchMode) } : new Type[] { typeof(string), typeof(ServiceSearchMode) }; MethodInfo getServiceMethod = typeof(IServiceContainer).GetMethod("GetService", BindingFlags.Instance | BindingFlags.Public, null, getServiceMethodParams, null).MakeGenericMethod(serviceType); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Callvirt, ExpressionHelper.GetArgumentPropertyStrict(serviceContainerPropertyExpression).GetGetMethod()); if(!string.IsNullOrEmpty(serviceName)) gen.Emit(OpCodes.Ldstr, serviceName); gen.Emit(OpCodes.Ldc_I4_S, (int)searchMode); gen.Emit(OpCodes.Callvirt, getServiceMethod); gen.Emit(OpCodes.Ret); } static void EmitGetRequiredServicePropertyMethod(Type serviceType, string serviceName, ServiceSearchMode searchMode, ILGenerator gen) { Expression<Func<ISupportServices, IServiceContainer>> serviceContainerPropertyExpression = x => x.ServiceContainer; Type[] getServiceMethodParams = string.IsNullOrEmpty(serviceName) ? new Type[] { typeof(IServiceContainer), typeof(ServiceSearchMode) } : new Type[] { typeof(IServiceContainer), typeof(string), typeof(ServiceSearchMode) }; MethodInfo getServiceMethod = typeof(ServiceContainerExtensions).GetMethod("GetRequiredService", BindingFlags.Static | BindingFlags.Public, null, getServiceMethodParams, null).MakeGenericMethod(serviceType); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Callvirt, ExpressionHelper.GetArgumentPropertyStrict(serviceContainerPropertyExpression).GetGetMethod()); if(!string.IsNullOrEmpty(serviceName)) gen.Emit(OpCodes.Ldstr, serviceName); gen.Emit(OpCodes.Ldc_I4_S, (int)searchMode); gen.Emit(OpCodes.Call, getServiceMethod); gen.Emit(OpCodes.Ret); } #endregion #region ISupportParentViewModel static void ImplementISupportParentViewModel(Type type, TypeBuilder typeBuilder) { if(typeof(ISupportParentViewModel).IsAssignableFrom(type)) return; Expression<Func<ISupportParentViewModel, object>> parentViewModelPropertyExpression = x => x.ParentViewModel; var getter = ExpressionHelper.GetArgumentPropertyStrict(parentViewModelPropertyExpression).GetGetMethod(); var setter = ExpressionHelper.GetArgumentPropertyStrict(parentViewModelPropertyExpression).GetSetMethod(); FieldBuilder parentViewModelField = typeBuilder.DefineField("parentViewModel", typeof(object), FieldAttributes.Private); var getMethod = BuildGetParentViewModelMethod(typeBuilder, parentViewModelField, getter.Name); var setMethod = BuildSetParentViewModelMethod(typeBuilder, parentViewModelField, setter.Name); typeBuilder.DefineMethodOverride(getMethod, getter); typeBuilder.DefineMethodOverride(setMethod, setter); } static MethodBuilder BuildSetParentViewModelMethod(TypeBuilder type, FieldBuilder parentViewModelField, string setterName) { System.Reflection.MethodAttributes methodAttributes = MethodAttributes.Private | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.HideBySig | MethodAttributes.NewSlot; MethodBuilder method = type.DefineMethod(typeof(ISupportParentViewModel).FullName + "." + setterName, methodAttributes); method.SetReturnType(typeof(void)); method.SetParameters(typeof(object)); ParameterBuilder value = method.DefineParameter(1, ParameterAttributes.None, "value"); ILGenerator gen = method.GetILGenerator(); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldarg_1); gen.Emit(OpCodes.Stfld, parentViewModelField); gen.Emit(OpCodes.Ret); return method; } static MethodBuilder BuildGetParentViewModelMethod(TypeBuilder type, FieldBuilder parentViewModelField, string getterName) { System.Reflection.MethodAttributes methodAttributes = MethodAttributes.Private | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.HideBySig | MethodAttributes.NewSlot; MethodBuilder method = type.DefineMethod(typeof(ISupportParentViewModel).FullName + "." + getterName, methodAttributes); method.SetReturnType(typeof(object)); ILGenerator gen = method.GetILGenerator(); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldfld, parentViewModelField); gen.Emit(OpCodes.Ret); return method; } #endregion } #if !SILVERLIGHT [Serializable] #endif public class ViewModelSourceException : Exception { public ViewModelSourceException() { } public ViewModelSourceException(string message) : base(message) { } } #pragma warning disable 612,618 public static class POCOViewModelExtensions { public static bool IsInDesignMode(this object viewModel) { return ViewModelBase.IsInDesignMode; } public static void RaisePropertiesChanged(this object viewModel) { IPOCOViewModel pocoViewModel = GetPOCOViewModel(viewModel); pocoViewModel.RaisePropertyChanged(string.Empty); } public static void RaisePropertyChanged<T, TProperty>(this T viewModel, Expression<Func<T, TProperty>> propertyExpression) { IPOCOViewModel pocoViewModel = GetPOCOViewModel(viewModel); pocoViewModel.RaisePropertyChanged(BindableBase.GetPropertyNameFast(propertyExpression)); } public static IDelegateCommand GetCommand<T>(this T viewModel, Expression<Action<T>> methodExpression) { return GetCommandCore(viewModel, methodExpression); } public static T SetParentViewModel<T>(this T viewModel, object parentViewModel) { ((ISupportParentViewModel)viewModel).ParentViewModel = parentViewModel; return viewModel; } public static T GetParentViewModel<T>(this object viewModel) where T : class { return (T)((ISupportParentViewModel)viewModel).ParentViewModel; } public static IAsyncCommand GetAsyncCommand<T>(this T viewModel, Expression<Func<T, Task>> methodExpression) { return GetAsyncCommandCore(viewModel, methodExpression); } public static void RaiseCanExecuteChanged<T>(this T viewModel, Expression<Action<T>> methodExpression) { RaiseCanExecuteChangedCore(viewModel, methodExpression); } #if !SILVERLIGHT public static void UpdateFunctionBinding<T>(this T viewModel, Expression<Action<T>> methodExpression) { UpdateFunctionBehaviorCore(viewModel, methodExpression); } public static void UpdateMethodToCommandCanExecute<T>(this T viewModel, Expression<Action<T>> methodExpression) { UpdateFunctionBehaviorCore(viewModel, methodExpression); } static void UpdateFunctionBehaviorCore<T>(this T viewModel, Expression<Action<T>> methodExpression) { string methodName = ExpressionHelper.GetMethod(methodExpression).Name; GetPOCOViewModel(viewModel).RaisePropertyChanged(methodName); } #endif #region GetService methods public static TService GetService<TService>(this object viewModel) where TService : class { return GetServiceContainer(viewModel).GetService<TService>(); } public static TService GetService<TService>(this object viewModel, string key) where TService : class { return GetServiceContainer(viewModel).GetService<TService>(key); } public static TService GetRequiredService<TService>(this object viewModel) where TService : class { return ServiceContainerExtensions.GetRequiredService<TService>(GetServiceContainer(viewModel)); } public static TService GetRequiredService<TService>(this object viewModel, string key) where TService : class { return ServiceContainerExtensions.GetRequiredService<TService>(GetServiceContainer(viewModel), key); } static IServiceContainer GetServiceContainer(object viewModel) { GetPOCOViewModel(viewModel); return ((ISupportServices)viewModel).ServiceContainer; } #endregion [Obsolete("Use the GetAsyncCommand method instead.")] [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public static bool GetShouldCancel<T>(this T viewModel, Expression<Func<T, Task>> methodExpression) { return GetAsyncCommand(viewModel, methodExpression).ShouldCancel; } [Obsolete("Use the GetAsyncCommand method instead.")] [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public static bool GetIsExecuting<T>(this T viewModel, Expression<Func<T, Task>> methodExpression) { return GetAsyncCommand(viewModel, methodExpression).IsExecuting; } internal static void RaiseCanExecuteChangedCore(object viewModel, LambdaExpression methodExpression) { IDelegateCommand command = GetCommandCore(viewModel, methodExpression); command.RaiseCanExecuteChanged(); } static IAsyncCommand GetAsyncCommandCore(object viewModel, LambdaExpression methodExpression) { GetPOCOViewModel(viewModel); ICommand command = GetCommandCore(viewModel, methodExpression); if(!(command is IAsyncCommand)) throw new ViewModelSourceException(ViewModelSource.Error_CommandNotAsync); return (IAsyncCommand)command; } static IDelegateCommand GetCommandCore(object viewModel, LambdaExpression methodExpression) { GetPOCOViewModel(viewModel); MethodInfo method = ExpressionHelper.GetMethod(methodExpression); string commandName = ViewModelSource.GetCommandName(method); PropertyInfo property = viewModel.GetType().GetProperty(commandName); if(property == null) throw new ViewModelSourceException(string.Format(ViewModelSource.Error_CommandNotFound, commandName)); return property.GetValue(viewModel, null) as IDelegateCommand; } static IPOCOViewModel GetPOCOViewModel<T>(T viewModel) { IPOCOViewModel pocoViewModel = viewModel as IPOCOViewModel; if(pocoViewModel == null) throw new ViewModelSourceException(ViewModelSource.Error_ObjectDoesntImplementIPOCOViewModel); return pocoViewModel; } } #pragma warning restore 612,618 #region ViewModelSource<T> public static class ViewModelSource<T> { static TDelegate GetFactoryByTypes<TDelegate>(Func<Type[]> getTypesDelegate) { return ViewModelSource.GetFactoryCore<TDelegate>(() => { Type[] types = getTypesDelegate(); var ctor = ViewModelSource.GetConstructor(ViewModelSource.GetPOCOType(typeof(T)), types); ParameterExpression[] parameters = types.Select(x => Expression.Parameter(x)).ToArray(); return Expression.Lambda<TDelegate>(Expression.New(ctor, parameters), parameters).Compile(); }); } public static T Create() { return GetFactoryByTypes<Func<T>>(() => Type.EmptyTypes)(); } public static T Create<T1>(T1 param1) { return GetFactoryByTypes<Func<T1, T>>(() => new[] { typeof(T1) }) (param1); } public static T Create<T1, T2>(T1 param1, T2 param2) { return GetFactoryByTypes<Func<T1, T2, T>>(() => new[] { typeof(T1), typeof(T2) }) (param1, param2); } public static T Create<T1, T2, T3>(T1 param1, T2 param2, T3 param3) { return GetFactoryByTypes<Func<T1, T2, T3, T>>(() => new[] { typeof(T1), typeof(T2), typeof(T3) }) (param1, param2, param3); } public static T Create<T1, T2, T3, T4>(T1 param1, T2 param2, T3 param3, T4 param4) { return GetFactoryByTypes<Func<T1, T2, T3, T4, T>>(() => new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4) }) (param1, param2, param3, param4); } public static T Create<T1, T2, T3, T4, T5>(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5) { return GetFactoryByTypes<Func<T1, T2, T3, T4, T5, T>>(() => new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5) }) (param1, param2, param3, param4, param5); } public static T Create<T1, T2, T3, T4, T5, T6>(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6) { return GetFactoryByTypes<Func<T1, T2, T3, T4, T5, T6, T>>(() => new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6) }) (param1, param2, param3, param4, param5, param6); } public static T Create<T1, T2, T3, T4, T5, T6, T7>(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7) { return GetFactoryByTypes<Func<T1, T2, T3, T4, T5, T6, T7, T>>(() => new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7) }) (param1, param2, param3, param4, param5, param6, param7); } public static T Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7, T8 param8) { return GetFactoryByTypes<Func<T1, T2, T3, T4, T5, T6, T7, T8, T>>(() => new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8) }) (param1, param2, param3, param4, param5, param6, param7, param8); } public static T Create<T1, T2, T3, T4, T5, T6, T7, T8, T9>(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7, T8 param8, T9 param9) { return GetFactoryByTypes<Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T>>(() => new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8), typeof(T9) }) (param1, param2, param3, param4, param5, param6, param7, param8, param9); } public static T Create<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7, T8 param8, T9 param9, T10 param10) { return GetFactoryByTypes<Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T>>(() => new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8), typeof(T9), typeof(T10) }) (param1, param2, param3, param4, param5, param6, param7, param8, param9, param10); } } #endregion }
using System; using System.Collections.Generic; using UnityEngine; using JuloUtil; using JuloGame; namespace TurtleIsland { public class TurtleIslandGame : Game<TurtleIslandObject, Options>, Behav { public Environment env; public Level level; public TeamManager teamManager; public Controller activeController = null; // State management private enum State { WAIT, APPLY_DAMAGE, DEAD, PREPARE, PLAY, OVER, CELEBRATE, REPLAY } private StateMachine<State> machine; private TTPlayStatus playStatus; public Character currentCharacter = null; // TODO make private private Team currentTeam = null; private Team leftTeam; private Team rightTeam; private List<Character> damagedCharacters; private List<Character> deadCharacters; private TurtleIslandStatus oldStatus; private TurtleIslandStatus gameStatus; public TurtleIslandGame(Environment env, Level level, int numCharacters) : base(env.options) { this.env = env; this.level = level; env.hk.replayManager.clear(); this.machine = new StateMachine<State>(State.WAIT); damagedCharacters = new List<Character>(); deadCharacters = new List<Character>(); this.teamManager = new TeamManager(2, numCharacters); // TODO detect teams from characters leftTeam = new Team(TurtleIsland.LeftTeamId, TurtleIsland.LeftTeamName, options.leftColor, options.leftController); rightTeam = new Team(TurtleIsland.RightTeamId, TurtleIsland.RightTeamName, options.rightColor, options.rightController); this.teamManager.addTeam(leftTeam); this.teamManager.addTeam(rightTeam); leftTeam.setWeapon(0, options.initialWeaponValue); rightTeam.setWeapon(0, options.initialWeaponValue); updateWeaponInfo(); this.teamManager.startsTeam(JuloMath.randomBool() ? TurtleIsland.LeftTeamId : TurtleIsland.RightTeamId); options.leftController.initialize(this, options.difficulty); options.rightController.initialize(this, options.difficulty); hideControls(); } public void addCharacter(Character c) { c.activate(); addObject(c); teamManager.addCharacter(c); c.init(this); } public Color getColorForTeam(int teamId) { if(teamId == TurtleIsland.LeftTeamId) { return options.leftColor; } else if(teamId == TurtleIsland.RightTeamId) { return options.rightColor; } else { throw new ApplicationException("Invalid team"); } } public override void onInit() { //Debug.Log("Initting"); } public override void onStep() { if(machine.state == State.WAIT) { if(!allIsQuiet()) { machine.trigger(State.WAIT); // resets wait counter } else if(machine.isOver(options.waitTime)) { this.oldStatus = this.gameStatus; this.gameStatus = teamManager.getStatus(); if(env.hk.replayManager.isRecording()) { env.hk.replayManager.stop(); } if(env.hk.replayManager.hasRecord()) { if(isReplayable()) { triggerReplay(); } else { triggerApply(); env.hk.replayManager.clear(); } } else { triggerApply(); } } } else if(machine.state == State.APPLY_DAMAGE) { if(machine.isOver(options.applyDamageTime)) { List<Character> reallyDeadCharacters = new List<Character>(); foreach(Character c in deadCharacters) { if(c.isActive() && !c.sinked) { c.dead(); reallyDeadCharacters.Add(c); } } if(reallyDeadCharacters.Count > 0) { env.focusAny(reallyDeadCharacters); machine.trigger(State.DEAD); } else { endOfTurn(); } deadCharacters.Clear(); } } else if(machine.state == State.PREPARE) { if(machine.triggerIfEllapsed(State.PLAY, options.prepareTime)) { currentCharacter.play(activeController); playStatus = TTPlayStatus.PREPARE; } } else if(machine.state == State.DEAD) { if(machine.isOver(options.deathTime)) { endOfTurn(); } } else if(machine.state == State.PLAY) { if(!currentCharacter.isAlive()) { endTurn(); } else if(playStatus == TTPlayStatus.PREPARE) { float remaining = getRemainingTime(); //if(machine.isOver(options.playTime) || currentCharacter.isLocked()) { if(remaining <= 0f || currentCharacter.isLocked()) { endTurn(); showMainTime(0f); } else { showMainTime(remaining); } } else if(playStatus == TTPlayStatus.CHARGE) { if(machine.isOver(options.maximumChargeTime)) { activeController.dischargeForced(); discharge(); } } else if(playStatus == TTPlayStatus.DONE) { if(machine.isOver(options.postTime)) { endTurn(); } } else { throw new ApplicationException("Unknown state"); } } else if(machine.state == State.OVER) { if(machine.triggerIfEllapsed(State.CELEBRATE, options.overTime)) { Team winner = teamManager.getSomeReadyTeam(); if(winner != null) { //if(env.hk.soundsControl.isOn()) env.hk.soundsPlayer.playClip(options.winClip, 1f); foreach(Character c in winner) { if(c.isReady()) { c.celebrate(); } } env.hk.teamDisplays[winner.id].trigger("Win"); } else { //if(env.hk.soundsControl.isOn()) env.hk.soundsPlayer.playClip(options.drawClip, 1f); } } } else if(machine.state == State.CELEBRATE) { if(machine.ellapsed() >= options.celebrateTime) { // TODO restart(); } } else if(machine.state == State.REPLAY) { if(!env.hk.replayManager.isReplaying()) { triggerApply(); env.hk.replayManager.clear(); } } else { Debug.LogWarning("Unknown state: " + machine.state); } } public override void onDeactivate(TurtleIslandObject obj) { obj.kill(); } public override bool isOver() { return machine.state == State.CELEBRATE; } public float getRemainingTime() { return options.playTime - machine.ellapsed(); } public void walk(float axis) { if(machine.state != State.PLAY || playStatus == TTPlayStatus.CHARGE) throw new ApplicationException("Invalid call of walk()"); if(currentCharacter.isGrounded()) { currentCharacter.walk(axis * options.walkSpeed); } } public void moveTarget(float axis) { if(machine.state != State.PLAY || (playStatus != TTPlayStatus.PREPARE && playStatus != TTPlayStatus.CHARGE)) throw new ApplicationException("Invalid call of moveTarget()"); currentCharacter.moveTarget(axis * options.targetSpeed); } public bool isUnderWater(TurtleIslandObject obj) { Vector2 pos = (Vector2) obj.transform.position; Vector2 waterLeft = level.waterLeft.transform.position; Vector2 waterRight = level.waterRight.transform.position; return (pos.x <= waterLeft.x && pos.y <= waterLeft.y) || (pos.x >= waterRight.x && pos.y <= waterRight.y); } public void sink(TurtleIslandObject obj) { //if(env.hk.soundsControl.isOn()) env.hk.soundsPlayer.playClip(options.sinkClip, 1f); Rigidbody2D b = obj.rb; b.drag = 10; b.angularDrag = 10; } public void passTurn() { if(machine.state != State.PLAY || playStatus != TTPlayStatus.PREPARE) throw new ApplicationException("Invalid call of passTurn()"); endTurn(); } public void charge() { if(machine.state != State.PLAY || playStatus != TTPlayStatus.PREPARE) throw new ApplicationException("Invalid call of charge()"); machine.trigger(State.PLAY); // resets machine counter playStatus = TTPlayStatus.CHARGE; currentCharacter.charge(); } public void discharge() { if(machine.state != State.PLAY || playStatus != TTPlayStatus.CHARGE) throw new ApplicationException("Invalid call of discharge()"); float chargeTime = machine.ellapsed(); AudioClip shotClip = chargeTime < options.shotClipThreshold ? options.shot1Clip : options.shot2Clip; //if(env.hk.soundsControl.isOn()) env.hk.soundsPlayer.playClip(shotClip, 1f); machine.trigger(State.PLAY); // resets machine counter playStatus = TTPlayStatus.DONE; currentCharacter.discharge(); Weapon w = env.addNewWeapon( this, currentTeam.weaponIndex, currentTeam.weaponValue, currentCharacter.shotPoint.position, JuloMath.unitVector(currentCharacter.getTargetWorldAngle()), chargeTime ); env.focusObject(w); //hideTurnControls(); if(options.showReplay) { env.hk.replayManager.record(); } } public void setWeaponValue(int value) { if(activeController != null) { currentTeam.weaponValue = value; updateWeaponInfo(); } else { Debug.Log("Invalid call of setWeaponValue"); } } public void incrementWeaponValue() { if(activeController != null && currentTeam.weaponValue < 5) { currentTeam.weaponValue++; updateWeaponInfo(); //} else { // Debug.Log("Invalid call of setWeaponValue"); } } public void decrementWeaponValue() { if(activeController != null && currentTeam.weaponValue > 1) { currentTeam.weaponValue--; updateWeaponInfo(); //} else { // Debug.Log("Invalid call of setWeaponValue"); } } public void nextWeapon() { if(activeController != null) { currentTeam.setWeapon( (currentTeam.weaponIndex + 1) % env.weapons.Length, options.initialWeaponValue ); updateWeaponInfo(); } else { Debug.Log("Invalid call of nextWeapon"); } } public List<Character> getRivals() { return teamManager.getReadyRivals(currentCharacter); } public void addForce(ForceWeighting weighting, float forceScale, float damageScale) { //if(env.hk.soundsControl.isOn()) env.hk.soundsPlayer.playClip(options.explosionClip, 1f); float maxMagnitude = 0; Character maxMagnitudeChar = null; foreach(Character c in teamManager.allActiveCharacters()) { Vector2 f = weighting.weight(c); float magnitude = f.magnitude; if(magnitude > 0f) { c.rb.AddForce(f * forceScale); } if(c.isAlive()) { float fDamage = magnitude * damageScale; int damage = (int)(Mathf.Round(fDamage)); if(damage > 0) { damagedCharacters.Add(c); if(c.hit(damage)) { deadCharacters.Add(c); } } if(magnitude > maxMagnitude) { maxMagnitude = magnitude; maxMagnitudeChar = c; } } } if(maxMagnitudeChar != null) { env.focusObject(maxMagnitudeChar); } } private bool allIsQuiet() { foreach(TurtleIslandObject obj in objects) { if(!obj.isIdle()) { return false; } } return true; } private bool isReplayable() { return gameStatus.readyChars != oldStatus.readyChars; //return gameStatus.isOver(); } private void endOfTurn() { if(gameStatus.isOver()) { triggerGameOver(); } else { triggerNextTurn(); } } private void triggerReplay() { machine.trigger(State.REPLAY); env.hk.replayManager.showReplay(); } private void triggerApply() { List<Character> reallyDamagedCharacters = new List<Character>(); foreach(Character c in damagedCharacters) { if(c.isActive() && !c.sinked) { c.applyDamage(); reallyDamagedCharacters.Add(c); } } if(reallyDamagedCharacters.Count > 0) { //env.focusAny(reallyDamagedCharacters); machine.trigger(State.APPLY_DAMAGE); } else { endOfTurn(); } damagedCharacters.Clear(); } private void triggerGameOver() { machine.trigger(State.OVER); Team winner = teamManager.getSomeReadyTeam(); if(winner != null) { env.focusObject(teamManager.getLastCharacterOf(winner)); } } private void triggerNextTurn() { machine.trigger(State.PREPARE); currentCharacter = teamManager.nextCharacter(); currentTeam = teamManager.currentTeam(); activeController = currentTeam.controller; env.focusObject(currentCharacter); showTurnControls(); } private void endTurn() { playStatus = TTPlayStatus.OVER; machine.trigger(State.WAIT); currentCharacter.stop(); hideTurnControls(); activeController = null; } private void hideControls() { env.hk.mainTimeDisplay.trigger("Off"); env.hk.teamDisplays[TurtleIsland.LeftTeamId].trigger("Off"); env.hk.teamDisplays[TurtleIsland.RightTeamId].trigger("Off"); } private void showTurnControls() { showMainTime(options.playTime); env.hk.mainTimeDisplay.trigger("Show"); env.hk.teamDisplays[currentTeam.id].trigger("Play"); } private void showMainTime(float remaining) { env.hk.mainTimeDisplay.showFloat(remaining, JuloMath.TruncateMethod.CEIL, 0); } private void hideTurnControls() { env.hk.mainTimeDisplay.trigger("Hide"); env.hk.teamDisplays[currentTeam.id].trigger("Stop"); } private void updateWeaponInfo() { env.hk.teamDisplays[TurtleIsland.LeftTeamId].setWeapon(env.weapons[leftTeam.weaponIndex], leftTeam.weaponValue); env.hk.teamDisplays[TurtleIsland.RightTeamId].setWeapon(env.weapons[rightTeam.weaponIndex], rightTeam.weaponValue); } public void start(InputManager inputManager) {} public void update() {} } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.IO; using DiscUtils.Streams; using Buffer=DiscUtils.Streams.Buffer; namespace DiscUtils.Ext { internal class ExtentsFileBuffer : Buffer { private readonly Context _context; private readonly Inode _inode; public ExtentsFileBuffer(Context context, Inode inode) { _context = context; _inode = inode; } public override bool CanRead { get { return true; } } public override bool CanWrite { get { return false; } } public override long Capacity { get { return _inode.FileSize; } } public override int Read(long pos, byte[] buffer, int offset, int count) { if (pos > _inode.FileSize) { return 0; } long blockSize = _context.SuperBlock.BlockSize; int totalRead = 0; int totalBytesRemaining = (int)Math.Min(count, _inode.FileSize - pos); ExtentBlock extents = _inode.Extents; while (totalBytesRemaining > 0) { uint logicalBlock = (uint)((pos + totalRead) / blockSize); int blockOffset = (int)(pos + totalRead - logicalBlock * blockSize); int numRead = 0; Extent extent = FindExtent(extents, logicalBlock); if (extent == null) { throw new IOException("Unable to find extent for block " + logicalBlock); } if (extent.FirstLogicalBlock > logicalBlock) { numRead = (int) Math.Min(totalBytesRemaining, (extent.FirstLogicalBlock - logicalBlock) * blockSize - blockOffset); Array.Clear(buffer, offset + totalRead, numRead); } else { long physicalBlock = logicalBlock - extent.FirstLogicalBlock + (long)extent.FirstPhysicalBlock; int toRead = (int) Math.Min(totalBytesRemaining, (extent.NumBlocks - (logicalBlock - extent.FirstLogicalBlock)) * blockSize - blockOffset); _context.RawStream.Position = physicalBlock * blockSize + blockOffset; numRead = _context.RawStream.Read(buffer, offset + totalRead, toRead); } totalBytesRemaining -= numRead; totalRead += numRead; } return totalRead; } public override void Write(long pos, byte[] buffer, int offset, int count) { throw new NotImplementedException(); } public override void SetCapacity(long value) { throw new NotImplementedException(); } public override IEnumerable<StreamExtent> GetExtentsInRange(long start, long count) { return StreamExtent.Intersect( new[] { new StreamExtent(0, Capacity) }, new StreamExtent(start, count)); } private Extent FindExtent(ExtentBlock node, uint logicalBlock) { if (node.Index != null) { ExtentIndex idxEntry = null; if (node.Index.Length == 0) { return null; } if (node.Index[0].FirstLogicalBlock >= logicalBlock) { idxEntry = node.Index[0]; } else { for (int i = 0; i < node.Index.Length; ++i) { if (node.Index[i].FirstLogicalBlock > logicalBlock) { idxEntry = node.Index[i - 1]; break; } } } if (idxEntry == null) { idxEntry = node.Index[node.Index.Length - 1]; } ExtentBlock subBlock = LoadExtentBlock(idxEntry); return FindExtent(subBlock, logicalBlock); } if (node.Extents != null) { Extent entry = null; if (node.Extents.Length == 0) { return null; } if (node.Extents[0].FirstLogicalBlock >= logicalBlock) { return node.Extents[0]; } for (int i = 0; i < node.Extents.Length; ++i) { if (node.Extents[i].FirstLogicalBlock > logicalBlock) { entry = node.Extents[i - 1]; break; } } if (entry == null) { entry = node.Extents[node.Extents.Length - 1]; } return entry; } return null; } private ExtentBlock LoadExtentBlock(ExtentIndex idxEntry) { uint blockSize = _context.SuperBlock.BlockSize; _context.RawStream.Position = idxEntry.LeafPhysicalBlock * blockSize; byte[] buffer = StreamUtilities.ReadExact(_context.RawStream, (int)blockSize); ExtentBlock subBlock = EndianUtilities.ToStruct<ExtentBlock>(buffer, 0); return subBlock; } } }
// *********************************************************************** // Copyright (c) 2014 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** #if PARALLEL using System.Threading; using NUnit.TestUtilities; namespace NUnit.Framework.Internal.Execution { public class WorkItemQueueTests { private WorkItemQueue _queue; [SetUp] public void CreateQueue() { #if APARTMENT_STATE _queue = new WorkItemQueue("TestQ", true, ApartmentState.MTA); #else _queue = new WorkItemQueue("TestQ", true); #endif } [Test] public void InitialState() { Assert.That(_queue.Name, Is.EqualTo("TestQ")); Assert.That(_queue.IsEmpty, "Queue is not empty"); Assert.That(_queue.State, Is.EqualTo(WorkItemQueueState.Paused)); } [Test] public void StartQueue() { _queue.Start(); Assert.That(_queue.State, Is.EqualTo(WorkItemQueueState.Running)); } [Test] public void StopQueue_NoWorkers() { _queue.Start(); _queue.Stop(); Assert.That(_queue.State, Is.EqualTo(WorkItemQueueState.Stopped)); } [Test] public void StopQueue_WithWorkers() { var workers = new TestWorker[] { new TestWorker(_queue, "1"), new TestWorker(_queue, "2"), new TestWorker(_queue, "3") }; foreach (var worker in workers) { worker.Start(); Assert.That(worker.IsAlive, "Worker thread {0} did not start", worker.Name); } _queue.Start(); _queue.Stop(); Assert.That(_queue.State, Is.EqualTo(WorkItemQueueState.Stopped)); int iters = 10; int alive = workers.Length; while (iters-- > 0 && alive > 0) { Thread.Sleep(60); // Allow time for workers to stop alive = 0; foreach (var worker in workers) if (worker.IsAlive) alive++; } if (alive > 0) foreach (var worker in workers) Assert.False(worker.IsAlive, "Worker thread {0} did not stop", worker.Name); } [Test] public void PauseQueue() { _queue.Start(); _queue.Pause(); Assert.That(_queue.State, Is.EqualTo(WorkItemQueueState.Paused)); } [Test] public void EnqueueBeforeDequeue() { string[] names = new[] { "Test1", "Test2", "Test3" }; EnqueueWorkItems(names); _queue.Start(); VerifyQueueContents(names); } [Test] public void DequeueBeforeEnqueue() { _queue.Start(); var names = new string[] { "Test1", "Test2", "Test3" }; new Thread(new ThreadStart(() => { Thread.Sleep(10); EnqueueWorkItems(names); })).Start(); VerifyQueueContents(names); } [Test] public void EnqueueAndDequeueWhilePaused() { string[] names = new[] { "Test1", "Test2", "Test3" }; EnqueueWorkItems(names); new Thread(new ThreadStart(() => { Thread.Sleep(10); _queue.Start(); })).Start(); VerifyQueueContents(names); } const int HIGH_PRIORITY = 0; const int NORMAL_PRIORITY = 1; [Test] public void PriorityIsHonored() { EnqueueWorkItem("Test1", NORMAL_PRIORITY); EnqueueWorkItem("Test2", HIGH_PRIORITY); EnqueueWorkItem("Test3", NORMAL_PRIORITY); _queue.Start(); VerifyQueueContents("Test2", "Test1", "Test3"); } [Test] public void OneTimeTearDownGetsPriority() { var testFixture = new TestFixture(new TypeWrapper(typeof(MyFixture))); var fixtureItem = WorkItemBuilder.CreateWorkItem(testFixture, TestFilter.Empty) as CompositeWorkItem; var tearDown = new CompositeWorkItem.OneTimeTearDownWorkItem(fixtureItem); EnqueueWorkItem("Test1"); _queue.Enqueue(tearDown); EnqueueWorkItem("Test2"); _queue.Start(); VerifyQueueContents("WorkItemQueueTests+MyFixture", "Test1", "Test2"); } private void EnqueueWorkItems(params string[] names) { foreach (string name in names) EnqueueWorkItem(name); } private void EnqueueWorkItem(string name) { _queue.Enqueue(Fakes.GetWorkItem(this, name)); } private void EnqueueWorkItem(string name, int priority) { _queue.Enqueue(Fakes.GetWorkItem(this, name), priority); } private void VerifyQueueContents(params string[] names) { foreach (string name in names) Assert.That(_queue.Dequeue().Test.Name, Is.EqualTo(name)); } private void Test1() { } private void Test2() { } private void Test3() { } private class MyFixture { } } } #endif
// // MailboxAddress.cs // // Author: Jeffrey Stedfast <[email protected]> // // Copyright (c) 2013-2015 Xamarin Inc. (www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.Text; using System.Collections.Generic; #if PORTABLE using Encoding = Portable.Text.Encoding; #endif #if ENABLE_SNM using System.Net.Mail; #endif using MimeKit.Utils; namespace MimeKit { /// <summary> /// A mailbox address, as specified by rfc822. /// </summary> /// <remarks> /// Represents a mailbox address (commonly referred to as an email address) /// for a single recipient. /// </remarks> public class MailboxAddress : InternetAddress { string address; /// <summary> /// Initializes a new instance of the <see cref="MimeKit.MailboxAddress"/> class. /// </summary> /// <remarks> /// Creates a new <see cref="MailboxAddress"/> with the specified name, address and route. The /// specified text encoding is used when encoding the name according to the rules of rfc2047. /// </remarks> /// <param name="encoding">The character encoding to be used for encoding the name.</param> /// <param name="name">The name of the mailbox.</param> /// <param name="route">The route of the mailbox.</param> /// <param name="address">The address of the mailbox.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="encoding"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="route"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="address"/> is <c>null</c>.</para> /// </exception> public MailboxAddress (Encoding encoding, string name, IEnumerable<string> route, string address) : base (encoding, name) { if (address == null) throw new ArgumentNullException ("address"); Route = new DomainList (route); Route.Changed += RouteChanged; Address = address; } /// <summary> /// Initializes a new instance of the <see cref="MimeKit.MailboxAddress"/> class. /// </summary> /// <remarks> /// Creates a new <see cref="MailboxAddress"/> with the specified name, address and route. /// </remarks> /// <param name="name">The name of the mailbox.</param> /// <param name="route">The route of the mailbox.</param> /// <param name="address">The address of the mailbox.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="route"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="address"/> is <c>null</c>.</para> /// </exception> public MailboxAddress (string name, IEnumerable<string> route, string address) : this (Encoding.UTF8, name, route, address) { } /// <summary> /// Initializes a new instance of the <see cref="MimeKit.MailboxAddress"/> class. /// </summary> /// <remarks> /// Creates a new <see cref="MailboxAddress"/> with the specified name and address. The /// specified text encoding is used when encoding the name according to the rules of rfc2047. /// </remarks> /// <param name="encoding">The character encoding to be used for encoding the name.</param> /// <param name="name">The name of the mailbox.</param> /// <param name="address">The address of the mailbox.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="encoding"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="address"/> is <c>null</c>.</para> /// </exception> public MailboxAddress (Encoding encoding, string name, string address) : base (encoding, name) { Route = new DomainList (); Route.Changed += RouteChanged; this.address = address; } /// <summary> /// Initializes a new instance of the <see cref="MimeKit.MailboxAddress"/> class. /// </summary> /// <remarks> /// Creates a new <see cref="MailboxAddress"/> with the specified name and address. /// </remarks> /// <param name="name">The name of the mailbox.</param> /// <param name="address">The address of the mailbox.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="address"/> is <c>null</c>. /// </exception> public MailboxAddress (string name, string address) : this (Encoding.UTF8, name, address) { } /// <summary> /// Gets the mailbox route. /// </summary> /// <remarks> /// A route is convention that is rarely seen in modern email systems, but is supported /// for compatibility with email archives. /// </remarks> /// <value>The mailbox route.</value> public DomainList Route { get; private set; } /// <summary> /// Gets or sets the mailbox address. /// </summary> /// <remarks> /// Represents the actual email address and is in the form of <c>"[email protected]"</c>. /// </remarks> /// <value>The mailbox address.</value> /// <exception cref="System.ArgumentNullException"> /// <paramref name="value"/> is <c>null</c>. /// </exception> public string Address { get { return address; } set { if (value == null) throw new ArgumentNullException ("value"); if (value == address) return; address = value; OnChanged (); } } /// <summary> /// Gets whether or not the address is an international address. /// </summary> /// <remarks> /// <para>International addresses are addresses that contain international /// characters in either their local-parts or their domains.</para> /// <para>For more information, see http://tools.ietf.org/html/rfc6532#section-3.2</para> /// </remarks> /// <value><c>true</c> if th address is an international address; otherwise, <c>false</c>.</value> public bool IsInternational { get { if (address == null) return false; for (int i = 0; i < address.Length; i++) { if (address[i] > 127) return true; } foreach (var domain in Route) { for (int i = 0; i < domain.Length; i++) { if (domain[i] > 127) return true; } } return false; } } internal override void Encode (FormatOptions options, StringBuilder builder, ref int lineLength) { if (builder == null) throw new ArgumentNullException ("builder"); if (lineLength < 0) throw new ArgumentOutOfRangeException ("lineLength"); string route = Route.ToString (); if (!string.IsNullOrEmpty (route)) route += ":"; if (!string.IsNullOrEmpty (Name)) { string name; if (!options.International) { var encoded = Rfc2047.EncodePhrase (options, Encoding, Name); name = Encoding.ASCII.GetString (encoded, 0, encoded.Length); } else { name = EncodeInternationalizedPhrase (Name); } if (lineLength + name.Length > options.MaxLineLength) { if (name.Length > options.MaxLineLength) { // we need to break up the name... builder.AppendFolded (options, name, ref lineLength); } else { // the name itself is short enough to fit on a single line, // but only if we write it on a line by itself if (lineLength > 1) { builder.LineWrap (options); lineLength = 1; } lineLength += name.Length; builder.Append (name); } } else { // we can safely fit the name on this line... lineLength += name.Length; builder.Append (name); } if ((lineLength + route.Length + Address.Length + 3) > options.MaxLineLength) { builder.Append (options.NewLine); builder.Append ("\t<"); lineLength = 2; } else { builder.Append (" <"); lineLength += 2; } lineLength += route.Length; builder.Append (route); lineLength += Address.Length + 1; builder.Append (Address); builder.Append ('>'); } else if (!string.IsNullOrEmpty (route)) { if ((lineLength + route.Length + Address.Length + 2) > options.MaxLineLength) { builder.Append (options.NewLine); builder.Append ("\t<"); lineLength = 2; } else { builder.Append ('<'); lineLength++; } lineLength += route.Length; builder.Append (route); lineLength += Address.Length + 1; builder.Append (Address); builder.Append ('>'); } else { if ((lineLength + Address.Length) > options.MaxLineLength) { builder.LineWrap (options); lineLength = 1; } lineLength += Address.Length; builder.Append (Address); } } /// <summary> /// Returns a string representation of the <see cref="MailboxAddress"/>, /// optionally encoding it for transport. /// </summary> /// <remarks> /// Returns a string containing the formatted mailbox address. If the <paramref name="encode"/> /// parameter is <c>true</c>, then the mailbox name will be encoded according to the rules defined /// in rfc2047, otherwise the name will not be encoded at all and will therefor only be suitable /// for display purposes. /// </remarks> /// <returns>A string representing the <see cref="MailboxAddress"/>.</returns> /// <param name="encode">If set to <c>true</c>, the <see cref="MailboxAddress"/> will be encoded.</param> public override string ToString (bool encode) { if (encode) { var builder = new StringBuilder (); int lineLength = 0; Encode (FormatOptions.GetDefault (), builder, ref lineLength); return builder.ToString (); } string route = Route.ToString (); if (!string.IsNullOrEmpty (route)) route += ":"; if (!string.IsNullOrEmpty (Name)) return MimeUtils.Quote (Name) + " <" + route + Address + ">"; if (!string.IsNullOrEmpty (route)) return "<" + route + Address + ">"; return Address; } #region IEquatable implementation /// <summary> /// Determines whether the specified <see cref="MimeKit.MailboxAddress"/> is equal to the current <see cref="MimeKit.MailboxAddress"/>. /// </summary> /// <remarks> /// Compares two mailbox addresses to determine if they are identical or not. /// </remarks> /// <param name="other">The <see cref="MimeKit.MailboxAddress"/> to compare with the current <see cref="MimeKit.MailboxAddress"/>.</param> /// <returns><c>true</c> if the specified <see cref="MimeKit.MailboxAddress"/> is equal to the current /// <see cref="MimeKit.MailboxAddress"/>; otherwise, <c>false</c>.</returns> public override bool Equals (InternetAddress other) { var mailbox = other as MailboxAddress; if (mailbox == null) return false; return Name == mailbox.Name && Address == mailbox.Address; } #endregion void RouteChanged (object sender, EventArgs e) { OnChanged (); } /// <summary> /// Tries to parse the given input buffer into a new <see cref="MimeKit.MailboxAddress"/> instance. /// </summary> /// <remarks> /// Parses a single <see cref="MailboxAddress"/>. If the the address is not a mailbox address or /// there is more than a single mailbox address, then parsing will fail. /// </remarks> /// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="options">The parser options to use.</param> /// <param name="buffer">The input buffer.</param> /// <param name="startIndex">The starting index of the input buffer.</param> /// <param name="length">The number of bytes in the input buffer to parse.</param> /// <param name="mailbox">The parsed mailbox address.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="options"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="buffer"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="startIndex"/> and <paramref name="length"/> do not specify /// a valid range in the byte array. /// </exception> public static bool TryParse (ParserOptions options, byte[] buffer, int startIndex, int length, out MailboxAddress mailbox) { InternetAddress address; if (!InternetAddress.TryParse (options, buffer, startIndex, length, out address)) { mailbox = null; return false; } mailbox = address as MailboxAddress; return mailbox != null; } /// <summary> /// Tries to parse the given input buffer into a new <see cref="MimeKit.MailboxAddress"/> instance. /// </summary> /// <remarks> /// Parses a single <see cref="MailboxAddress"/>. If the the address is not a mailbox address or /// there is more than a single mailbox address, then parsing will fail. /// </remarks> /// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="buffer">The input buffer.</param> /// <param name="startIndex">The starting index of the input buffer.</param> /// <param name="length">The number of bytes in the input buffer to parse.</param> /// <param name="mailbox">The parsed mailbox address.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="buffer"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="startIndex"/> and <paramref name="length"/> do not specify /// a valid range in the byte array. /// </exception> public static bool TryParse (byte[] buffer, int startIndex, int length, out MailboxAddress mailbox) { return TryParse (ParserOptions.Default, buffer, startIndex, length, out mailbox); } /// <summary> /// Tries to parse the given input buffer into a new <see cref="MimeKit.MailboxAddress"/> instance. /// </summary> /// <remarks> /// Parses a single <see cref="MailboxAddress"/>. If the the address is not a mailbox address or /// there is more than a single mailbox address, then parsing will fail. /// </remarks> /// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="options">The parser options to use.</param> /// <param name="buffer">The input buffer.</param> /// <param name="startIndex">The starting index of the input buffer.</param> /// <param name="mailbox">The parsed mailbox address.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="options"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="buffer"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="startIndex"/> is out of range. /// </exception> public static bool TryParse (ParserOptions options, byte[] buffer, int startIndex, out MailboxAddress mailbox) { InternetAddress address; if (!InternetAddress.TryParse (options, buffer, startIndex, out address)) { mailbox = null; return false; } mailbox = address as MailboxAddress; return mailbox != null; } /// <summary> /// Tries to parse the given input buffer into a new <see cref="MimeKit.MailboxAddress"/> instance. /// </summary> /// <remarks> /// Parses a single <see cref="MailboxAddress"/>. If the the address is not a mailbox address or /// there is more than a single mailbox address, then parsing will fail. /// </remarks> /// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="buffer">The input buffer.</param> /// <param name="startIndex">The starting index of the input buffer.</param> /// <param name="mailbox">The parsed mailbox address.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="buffer"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="startIndex"/> is out of range. /// </exception> public static bool TryParse (byte[] buffer, int startIndex, out MailboxAddress mailbox) { return TryParse (ParserOptions.Default, buffer, startIndex, out mailbox); } /// <summary> /// Tries to parse the given input buffer into a new <see cref="MimeKit.MailboxAddress"/> instance. /// </summary> /// <remarks> /// Parses a single <see cref="MailboxAddress"/>. If the the address is not a mailbox address or /// there is more than a single mailbox address, then parsing will fail. /// </remarks> /// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="options">The parser options to use.</param> /// <param name="buffer">The input buffer.</param> /// <param name="mailbox">The parsed mailbox address.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="options"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="buffer"/> is <c>null</c>.</para> /// </exception> public static bool TryParse (ParserOptions options, byte[] buffer, out MailboxAddress mailbox) { InternetAddress address; if (!InternetAddress.TryParse (options, buffer, out address)) { mailbox = null; return false; } mailbox = address as MailboxAddress; return mailbox != null; } /// <summary> /// Tries to parse the given input buffer into a new <see cref="MimeKit.MailboxAddress"/> instance. /// </summary> /// <remarks> /// Parses a single <see cref="MailboxAddress"/>. If the the address is not a mailbox address or /// there is more than a single mailbox address, then parsing will fail. /// </remarks> /// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="buffer">The input buffer.</param> /// <param name="mailbox">The parsed mailbox address.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="buffer"/> is <c>null</c>. /// </exception> public static bool TryParse (byte[] buffer, out MailboxAddress mailbox) { return TryParse (ParserOptions.Default, buffer, out mailbox); } /// <summary> /// Tries to parse the given text into a new <see cref="MimeKit.MailboxAddress"/> instance. /// </summary> /// <remarks> /// Parses a single <see cref="MailboxAddress"/>. If the the address is not a mailbox address or /// there is more than a single mailbox address, then parsing will fail. /// </remarks> /// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="options">The parser options to use.</param> /// <param name="text">The text.</param> /// <param name="mailbox">The parsed mailbox address.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="text"/> is <c>null</c>. /// </exception> public static bool TryParse (ParserOptions options, string text, out MailboxAddress mailbox) { InternetAddress address; if (!InternetAddress.TryParse (options, text, out address)) { mailbox = null; return false; } mailbox = address as MailboxAddress; return mailbox != null; } /// <summary> /// Tries to parse the given text into a new <see cref="MimeKit.MailboxAddress"/> instance. /// </summary> /// <remarks> /// Parses a single <see cref="MailboxAddress"/>. If the the address is not a mailbox address or /// there is more than a single mailbox address, then parsing will fail. /// </remarks> /// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="text">The text.</param> /// <param name="mailbox">The parsed mailbox address.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="text"/> is <c>null</c>. /// </exception> public static bool TryParse (string text, out MailboxAddress mailbox) { return TryParse (ParserOptions.Default, text, out mailbox); } #if ENABLE_SNM /// <summary> /// Explicit cast to convert a <see cref="MailboxAddress"/> to a /// <see cref="System.Net.Mail.MailAddress"/>. /// </summary> /// <remarks> /// Casts a <see cref="MailboxAddress"/> to a <see cref="System.Net.Mail.MailAddress"/> /// in cases where you might want to make use of the System.Net.Mail APIs. /// </remarks> /// <returns>The equivalent <see cref="System.Net.Mail.MailAddress"/>.</returns> /// <param name="mailbox">The mailbox.</param> public static explicit operator MailAddress (MailboxAddress mailbox) { return mailbox != null ? new MailAddress (mailbox.Address, mailbox.Name, mailbox.Encoding) : null; } /// <summary> /// Explicit cast to convert a <see cref="System.Net.Mail.MailAddress"/> /// to a <see cref="MailboxAddress"/>. /// </summary> /// <remarks> /// Casts a <see cref="System.Net.Mail.MailAddress"/> to a <see cref="MailboxAddress"/> /// in cases where you might want to make use of the the superior MimeKit APIs. /// </remarks> /// <returns>The equivalent <see cref="MailboxAddress"/>.</returns> /// <param name="address">The mail address.</param> public static explicit operator MailboxAddress (MailAddress address) { return address != null ? new MailboxAddress (address.DisplayName, address.Address) : null; } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // using System; public struct VT { public byte[,] byte2darr; public byte[, ,] byte3darr; public byte[,] byte2darr_b; public byte[, ,] byte3darr_b; } public class CL { public byte[,] byte2darr = { { 0, 1 }, { 0, 0 } }; public byte[, ,] byte3darr = { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } }; public byte[,] byte2darr_b = { { 0, 49 }, { 0, 0 } }; public byte[, ,] byte3darr_b = { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } }; } public class byteMDArrTest { static byte[,] byte2darr = { { 0, 1 }, { 0, 0 } }; static byte[, ,] byte3darr = { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } }; static byte[,] byte2darr_b = { { 0, 49 }, { 0, 0 } }; static byte[, ,] byte3darr_b = { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } }; static byte[][,] ja1 = new byte[2][,]; static byte[][, ,] ja2 = new byte[2][, ,]; static byte[][,] ja1_b = new byte[2][,]; static byte[][, ,] ja2_b = new byte[2][, ,]; public static int Main() { bool pass = true; VT vt1; vt1.byte2darr = new byte[,] { { 0, 1 }, { 0, 0 } }; vt1.byte3darr = new byte[,,] { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } }; vt1.byte2darr_b = new byte[,] { { 0, 49 }, { 0, 0 } }; vt1.byte3darr_b = new byte[,,] { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } }; CL cl1 = new CL(); ja1[0] = new byte[,] { { 0, 1 }, { 0, 0 } }; ja2[1] = new byte[,,] { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } }; ja1_b[0] = new byte[,] { { 0, 49 }, { 0, 0 } }; ja2_b[1] = new byte[,,] { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } }; byte result = 1; // 2D if (result != byte2darr[0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("2darr[0, 1] is: {0}", byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != vt1.byte2darr[0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("vt1.byte2darr[0, 1] is: {0}", vt1.byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != cl1.byte2darr[0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("cl1.byte2darr[0, 1] is: {0}", cl1.byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != ja1[0][0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (result != byte3darr[1, 0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("byte3darr[1,0,1] is: {0}", byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != vt1.byte3darr[1, 0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("vt1.byte3darr[1,0,1] is: {0}", vt1.byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != cl1.byte3darr[1, 0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("cl1.byte3darr[1,0,1] is: {0}", cl1.byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != ja2[1][1, 0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //ByteToBool tests bool Bool_result = true; // 2D if (Bool_result != Convert.ToBoolean(byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("2darr[0, 1] is: {0}", byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(vt1.byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("vt1.byte2darr[0, 1] is: {0}", vt1.byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(cl1.byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("cl1.byte2darr[0, 1] is: {0}", cl1.byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Bool_result != Convert.ToBoolean(byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("byte3darr[1,0,1] is: {0}", byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(vt1.byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("vt1.byte3darr[1,0,1] is: {0}", vt1.byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(cl1.byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("cl1.byte3darr[1,0,1] is: {0}", cl1.byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //ByteToDecimal tests decimal Decimal_result = 1; // 2D if (Decimal_result != Convert.ToDecimal(byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("2darr[0, 1] is: {0}", byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(vt1.byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("vt1.byte2darr[0, 1] is: {0}", vt1.byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(cl1.byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("cl1.byte2darr[0, 1] is: {0}", cl1.byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Decimal_result != Convert.ToDecimal(byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("byte3darr[1,0,1] is: {0}", byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(vt1.byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("vt1.byte3darr[1,0,1] is: {0}", vt1.byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(cl1.byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("cl1.byte3darr[1,0,1] is: {0}", cl1.byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //ByteToDouble double Double_result = 1; // 2D if (Double_result != Convert.ToDouble(byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("2darr[0, 1] is: {0}", byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(vt1.byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("vt1.byte2darr[0, 1] is: {0}", vt1.byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(cl1.byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("cl1.byte2darr[0, 1] is: {0}", cl1.byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Double_result != Convert.ToDouble(byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("byte3darr[1,0,1] is: {0}", byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(vt1.byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("vt1.byte3darr[1,0,1] is: {0}", vt1.byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(cl1.byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("cl1.byte3darr[1,0,1] is: {0}", cl1.byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //ByteToSingle tests Single Single_result = 1; // 2D if (Single_result != Convert.ToSingle(byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("2darr[0, 1] is: {0}", byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(vt1.byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("vt1.byte2darr[0, 1] is: {0}", vt1.byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(cl1.byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("cl1.byte2darr[0, 1] is: {0}", cl1.byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Single_result != Convert.ToSingle(byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("byte3darr[1,0,1] is: {0}", byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(vt1.byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("vt1.byte3darr[1,0,1] is: {0}", vt1.byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(cl1.byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("cl1.byte3darr[1,0,1] is: {0}", cl1.byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //ByteToInt32 tests int Int32_result = 1; // 2D if (Int32_result != Convert.ToInt32(byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("2darr[0, 1] is: {0}", byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(vt1.byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("vt1.byte2darr[0, 1] is: {0}", vt1.byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(cl1.byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("cl1.byte2darr[0, 1] is: {0}", cl1.byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Int32_result != Convert.ToInt32(byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("byte3darr[1,0,1] is: {0}", byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(vt1.byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("vt1.byte3darr[1,0,1] is: {0}", vt1.byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(cl1.byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("cl1.byte3darr[1,0,1] is: {0}", cl1.byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //ByteToInt64 tests long Int64_result = 1; // 2D if (Int64_result != Convert.ToInt64(byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("2darr[0, 1] is: {0}", byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int64_result != Convert.ToInt64(vt1.byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("vt1.byte2darr[0, 1] is: {0}", vt1.byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int64_result != Convert.ToInt64(cl1.byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("cl1.byte2darr[0, 1] is: {0}", cl1.byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int64_result != Convert.ToInt64(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Int64_result != Convert.ToInt64(byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("byte3darr[1,0,1] is: {0}", byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int64_result != Convert.ToInt64(vt1.byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("vt1.byte3darr[1,0,1] is: {0}", vt1.byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int64_result != Convert.ToInt64(cl1.byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("cl1.byte3darr[1,0,1] is: {0}", cl1.byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int64_result != Convert.ToInt64(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //ByteToSByte tests sbyte SByte_result = 1; // 2D if (SByte_result != Convert.ToSByte(byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("2darr[0, 1] is: {0}", byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(vt1.byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("vt1.byte2darr[0, 1] is: {0}", vt1.byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(cl1.byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("cl1.byte2darr[0, 1] is: {0}", cl1.byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (SByte_result != Convert.ToSByte(byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("byte3darr[1,0,1] is: {0}", byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(vt1.byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("vt1.byte3darr[1,0,1] is: {0}", vt1.byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(cl1.byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("cl1.byte3darr[1,0,1] is: {0}", cl1.byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //ByteToInt16 tests short Int16_result = 1; // 2D if (Int16_result != Convert.ToInt16(byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("2darr[0, 1] is: {0}", byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(vt1.byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("vt1.byte2darr[0, 1] is: {0}", vt1.byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(cl1.byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("cl1.byte2darr[0, 1] is: {0}", cl1.byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Int16_result != Convert.ToInt16(byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("byte3darr[1,0,1] is: {0}", byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(vt1.byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("vt1.byte3darr[1,0,1] is: {0}", vt1.byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(cl1.byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("cl1.byte3darr[1,0,1] is: {0}", cl1.byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //ByteToUInt32 uint UInt32_result = 1; // 2D if (UInt32_result != Convert.ToUInt32(byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("2darr[0, 1] is: {0}", byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(vt1.byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("vt1.byte2darr[0, 1] is: {0}", vt1.byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(cl1.byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("cl1.byte2darr[0, 1] is: {0}", cl1.byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (UInt32_result != Convert.ToUInt32(byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("byte3darr[1,0,1] is: {0}", byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(vt1.byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("vt1.byte3darr[1,0,1] is: {0}", vt1.byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(cl1.byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("cl1.byte3darr[1,0,1] is: {0}", cl1.byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //ByteToUInt64 ulong UInt64_result = 1; // 2D if (UInt64_result != Convert.ToUInt64(byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("2darr[0, 1] is: {0}", byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(vt1.byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("vt1.byte2darr[0, 1] is: {0}", vt1.byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(cl1.byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("cl1.byte2darr[0, 1] is: {0}", cl1.byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (UInt64_result != Convert.ToUInt64(byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("byte3darr[1,0,1] is: {0}", byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(vt1.byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("vt1.byte3darr[1,0,1] is: {0}", vt1.byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(cl1.byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("cl1.byte3darr[1,0,1] is: {0}", cl1.byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //ByteToUInt16 tests short UInt16_result = 1; // 2D if (UInt16_result != Convert.ToUInt16(byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("2darr[0, 1] is: {0}", byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(vt1.byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("vt1.byte2darr[0, 1] is: {0}", vt1.byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(cl1.byte2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("cl1.byte2darr[0, 1] is: {0}", cl1.byte2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (UInt16_result != Convert.ToUInt16(byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("byte3darr[1,0,1] is: {0}", byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(vt1.byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("vt1.byte3darr[1,0,1] is: {0}", vt1.byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(cl1.byte3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("cl1.byte3darr[1,0,1] is: {0}", cl1.byte3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //ByteToChar tests char Char_result = '1'; // 2D if (Char_result != Convert.ToChar(byte2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("2darr[0, 1] is: {0}", byte2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(vt1.byte2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("vt1.byte2darr_b[0, 1] is: {0}", vt1.byte2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(cl1.byte2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("cl1.byte2darr_b[0, 1] is: {0}", cl1.byte2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(ja1_b[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Char_result != Convert.ToChar(byte3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("byte3darr_b[1,0,1] is: {0}", byte3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(vt1.byte3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("vt1.byte3darr_b[1,0,1] is: {0}", vt1.byte3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(cl1.byte3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("cl1.byte3darr_b[1,0,1] is: {0}", cl1.byte3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(ja2_b[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (!pass) { Console.WriteLine("FAILED"); return 1; } else { Console.WriteLine("PASSED"); return 100; } } };
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils.Iscsi { using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Threading; internal enum SessionType { [ProtocolKeyValue("Discovery")] Discovery = 0, [ProtocolKeyValue("Normal")] Normal = 1 } /// <summary> /// Represents a connection to a particular Target. /// </summary> public sealed class Session : IDisposable { private static int s_nextInitiatorSessionId = new Random().Next(); private IList<TargetAddress> _addresses; private string _userName; private string _password; private Connection _currentConnection; private ushort _targetSessionId; // a.k.a. TSIH private uint _commandSequenceNumber; private uint _nextInitiaterTaskTag; private ushort _nextConnectionId; private uint _initiatorSessionId; /// <summary> /// The set of all 'parameters' we've negotiated. /// </summary> private Dictionary<string, string> _negotiatedParameters; internal Session(SessionType type, string targetName, params TargetAddress[] addresses) : this(type, targetName, null, null, addresses) { } internal Session(SessionType type, string targetName, string userName, string password, IList<TargetAddress> addresses) { _initiatorSessionId = (uint)Interlocked.Increment(ref s_nextInitiatorSessionId); _addresses = addresses; _userName = userName; _password = password; SessionType = type; TargetName = targetName; _commandSequenceNumber = 1; _nextInitiaterTaskTag = 1; // Default negotiated values... MaxConnections = 1; InitialR2T = true; ImmediateData = true; MaxBurstLength = 262144; FirstBurstLength = 65536; DefaultTime2Wait = 0; DefaultTime2Retain = 60; MaxOutstandingR2T = 1; DataPDUInOrder = true; DataSequenceInOrder = true; _negotiatedParameters = new Dictionary<string, string>(); if (string.IsNullOrEmpty(userName)) { _currentConnection = new Connection(this, _addresses[0], new Authenticator[] { new NullAuthenticator() }); } else { _currentConnection = new Connection(this, _addresses[0], new Authenticator[] { new NullAuthenticator(), new ChapAuthenticator(_userName, _password) }); } } #region Protocol Features /// <summary> /// Gets the name of the iSCSI target this session is connected to. /// </summary> [ProtocolKey("TargetName", null, KeyUsagePhase.SecurityNegotiation, KeySender.Initiator, KeyType.Declarative, UsedForDiscovery = true)] public string TargetName { get; internal set; } /// <summary> /// Gets the name of the iSCSI initiator seen by the target for this session. /// </summary> [ProtocolKey("InitiatorName", null, KeyUsagePhase.SecurityNegotiation, KeySender.Initiator, KeyType.Declarative, UsedForDiscovery = true)] public string InitiatorName { get { return "iqn.2008-2010-04.discutils.codeplex.com"; } } /// <summary> /// Gets the friendly name of the iSCSI target this session is connected to. /// </summary> [ProtocolKey("TargetAlias", "", KeyUsagePhase.All, KeySender.Target, KeyType.Declarative)] public string TargetAlias { get; internal set; } [ProtocolKey("SessionType", null, KeyUsagePhase.SecurityNegotiation, KeySender.Initiator, KeyType.Declarative, UsedForDiscovery = true)] internal SessionType SessionType { get; set; } [ProtocolKey("MaxConnections", "1", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)] internal int MaxConnections { get; set; } [ProtocolKey("InitiatorAlias", "", KeyUsagePhase.All, KeySender.Initiator, KeyType.Declarative)] internal string InitiatorAlias { get; set; } [ProtocolKey("TargetPortalGroupTag", null, KeyUsagePhase.SecurityNegotiation, KeySender.Target, KeyType.Declarative)] internal int TargetPortalGroupTag { get; set; } [ProtocolKey("InitialR2T", "Yes", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)] internal bool InitialR2T { get; set; } [ProtocolKey("ImmediateData", "Yes", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)] internal bool ImmediateData { get; set; } [ProtocolKey("MaxBurstLength", "262144", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)] internal int MaxBurstLength { get; set; } [ProtocolKey("FirstBurstLength", "65536", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)] internal int FirstBurstLength { get; set; } [ProtocolKey("DefaultTime2Wait", "2", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)] internal int DefaultTime2Wait { get; set; } [ProtocolKey("DefaultTime2Retain", "20", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)] internal int DefaultTime2Retain { get; set; } [ProtocolKey("MaxOutstandingR2T", "1", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)] internal int MaxOutstandingR2T { get; set; } [ProtocolKey("DataPDUInOrder", "Yes", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)] internal bool DataPDUInOrder { get; set; } [ProtocolKey("DataSequenceInOrder", "Yes", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)] internal bool DataSequenceInOrder { get; set; } [ProtocolKey("ErrorRecoveryLevel", "0", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)] internal int ErrorRecoveryLevel { get; set; } #endregion internal Connection ActiveConnection { get { return _currentConnection; } } internal uint InitiatorSessionId { get { return _initiatorSessionId; } } internal ushort TargetSessionId { get { return _targetSessionId; } set { _targetSessionId = value; } } internal uint CommandSequenceNumber { get { return _commandSequenceNumber; } } internal uint CurrentTaskTag { get { return _nextInitiaterTaskTag; } } /// <summary> /// Disposes of this instance, closing the session with the Target. /// </summary> public void Dispose() { if (_currentConnection != null) { _currentConnection.Close(LogoutReason.CloseSession); } _currentConnection = null; } /// <summary> /// Enumerates all of the Targets. /// </summary> /// <returns>The list of Targets</returns> /// <remarks>In practice, for an established session, this just returns details of /// the connected Target.</remarks> public TargetInfo[] EnumerateTargets() { return _currentConnection.EnumerateTargets(); } /// <summary> /// Gets information about the LUNs available from the Target. /// </summary> /// <returns>The LUNs available</returns> public LunInfo[] GetLuns() { ScsiReportLunsCommand cmd = new ScsiReportLunsCommand(ScsiReportLunsCommand.InitialResponseSize); ScsiReportLunsResponse resp = Send<ScsiReportLunsResponse>(cmd, null, 0, 0, ScsiReportLunsCommand.InitialResponseSize); if (resp.Truncated) { cmd = new ScsiReportLunsCommand(resp.NeededDataLength); resp = Send<ScsiReportLunsResponse>(cmd, null, 0, 0, (int)resp.NeededDataLength); } if (resp.Truncated) { throw new InvalidProtocolException("Truncated response"); } LunInfo[] result = new LunInfo[resp.Luns.Count]; for (int i = 0; i < resp.Luns.Count; ++i) { result[i] = GetInfo((long)resp.Luns[i]); } return result; } /// <summary> /// Gets all the block-device LUNs available from the Target. /// </summary> /// <returns>The block-device LUNs</returns> public long[] GetBlockDeviceLuns() { List<long> luns = new List<long>(); foreach (var info in GetLuns()) { if (info.DeviceType == LunClass.BlockStorage) { luns.Add(info.Lun); } } return luns.ToArray(); } /// <summary> /// Gets information about a particular LUN. /// </summary> /// <param name="lun">The LUN to query</param> /// <returns>Information about the LUN.</returns> public LunInfo GetInfo(long lun) { ScsiInquiryCommand cmd = new ScsiInquiryCommand((ulong)lun, ScsiInquiryCommand.InitialResponseDataLength); ScsiInquiryStandardResponse resp = Send<ScsiInquiryStandardResponse>(cmd, null, 0, 0, ScsiInquiryCommand.InitialResponseDataLength); TargetInfo targetInfo = new TargetInfo(TargetName, new List<TargetAddress>(_addresses).ToArray()); return new LunInfo(targetInfo, lun, resp.DeviceType, resp.Removable, resp.VendorId, resp.ProductId, resp.ProductRevision); } /// <summary> /// Gets the capacity of a particular LUN. /// </summary> /// <param name="lun">The LUN to query</param> /// <returns>The LUN's capacity</returns> public LunCapacity GetCapacity(long lun) { ScsiReadCapacityCommand cmd = new ScsiReadCapacityCommand((ulong)lun); ScsiReadCapacityResponse resp = Send<ScsiReadCapacityResponse>(cmd, null, 0, 0, ScsiReadCapacityCommand.ResponseDataLength); if (resp.Truncated) { throw new InvalidProtocolException("Truncated response"); } return new LunCapacity(resp.NumLogicalBlocks, (int)resp.LogicalBlockSize); } /// <summary> /// Provides read-write access to a LUN as a VirtualDisk. /// </summary> /// <param name="lun">The LUN to access</param> /// <returns>The new VirtualDisk instance</returns> public Disk OpenDisk(long lun) { return OpenDisk(lun, FileAccess.ReadWrite); } /// <summary> /// Provides access to a LUN as a VirtualDisk. /// </summary> /// <param name="lun">The LUN to access</param> /// <param name="access">The type of access desired</param> /// <returns>The new VirtualDisk instance</returns> public Disk OpenDisk(long lun, FileAccess access) { return new Disk(this, lun, access); } /// <summary> /// Reads some data from a LUN. /// </summary> /// <param name="lun">The LUN to read from</param> /// <param name="startBlock">The first block to read</param> /// <param name="blockCount">The number of blocks to read</param> /// <param name="buffer">The buffer to fill</param> /// <param name="offset">The offset of the first byte to fill</param> /// <returns>The number of bytes read</returns> public int Read(long lun, long startBlock, short blockCount, byte[] buffer, int offset) { ScsiReadCommand cmd = new ScsiReadCommand((ulong)lun, (uint)startBlock, (ushort)blockCount); return Send(cmd, null, 0, 0, buffer, offset, buffer.Length - offset); } /// <summary> /// Writes some data to a LUN. /// </summary> /// <param name="lun">The LUN to write to</param> /// <param name="startBlock">The first block to write</param> /// <param name="blockCount">The number of blocks to write</param> /// <param name="blockSize">The size of each block (must match the actual LUN geometry)</param> /// <param name="buffer">The data to write</param> /// <param name="offset">The offset of the first byte to write in buffer</param> public void Write(long lun, long startBlock, short blockCount, int blockSize, byte[] buffer, int offset) { ScsiWriteCommand cmd = new ScsiWriteCommand((ulong)lun, (uint)startBlock, (ushort)blockCount); Send(cmd, buffer, offset, blockCount * blockSize, null, 0, 0); } /// <summary> /// Performs a raw SCSI command. /// </summary> /// <param name="lun">The target LUN for the command</param> /// <param name="command">The command (a SCSI Command Descriptor Block, aka CDB)</param> /// <param name="outBuffer">Buffer of data to send with the command (or <c>null</c>)</param> /// <param name="outBufferOffset">Offset of first byte of data to send with the command</param> /// <param name="outBufferLength">Amount of data to send with the command</param> /// <param name="inBuffer">Buffer to receive data from the command (or <c>null</c>)</param> /// <param name="inBufferOffset">Offset of the first byte position to fill with received data</param> /// <param name="inBufferLength">The expected amount of data to receive</param> /// <returns>The number of bytes of data received</returns> /// <remarks> /// <para>This method permits the caller to send raw SCSI commands to a LUN.</para> /// <para>The command .</para> /// </remarks> public int RawCommand(long lun, byte[] command, byte[] outBuffer, int outBufferOffset, int outBufferLength, byte[] inBuffer, int inBufferOffset, int inBufferLength) { if (outBuffer == null && outBufferLength != 0) { throw new ArgumentException("outBufferLength must be 0 if outBuffer null", "outBufferLength"); } if (inBuffer == null && inBufferLength != 0) { throw new ArgumentException("inBufferLength must be 0 if inBuffer null", "inBufferLength"); } ScsiRawCommand cmd = new ScsiRawCommand((ulong)lun, command, 0, command.Length); return Send(cmd, outBuffer, outBufferOffset, outBufferLength, inBuffer, inBufferOffset, inBufferLength); } internal uint NextCommandSequenceNumber() { return ++_commandSequenceNumber; } internal uint NextTaskTag() { return ++_nextInitiaterTaskTag; } internal ushort NextConnectionId() { return ++_nextConnectionId; } internal void GetParametersToNegotiate(TextBuffer parameters, KeyUsagePhase phase) { PropertyInfo[] properties = GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (var propInfo in properties) { ProtocolKeyAttribute attr = (ProtocolKeyAttribute)Attribute.GetCustomAttribute(propInfo, typeof(ProtocolKeyAttribute)); if (attr != null) { object value = propInfo.GetGetMethod(true).Invoke(this, null); if (attr.ShouldTransmit(value, propInfo.PropertyType, phase, SessionType == SessionType.Discovery)) { parameters.Add(attr.Name, ProtocolKeyAttribute.GetValueAsString(value, propInfo.PropertyType)); _negotiatedParameters.Add(attr.Name, string.Empty); } } } } internal void ConsumeParameters(TextBuffer inParameters, TextBuffer outParameters) { PropertyInfo[] properties = GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (var propInfo in properties) { ProtocolKeyAttribute attr = (ProtocolKeyAttribute)Attribute.GetCustomAttribute(propInfo, typeof(ProtocolKeyAttribute)); if (attr != null) { if (inParameters[attr.Name] != null) { object value = ProtocolKeyAttribute.GetValueAsObject(inParameters[attr.Name], propInfo.PropertyType); propInfo.GetSetMethod(true).Invoke(this, new object[] { value }); inParameters.Remove(attr.Name); if (attr.Type == KeyType.Negotiated && !_negotiatedParameters.ContainsKey(attr.Name)) { value = propInfo.GetGetMethod(true).Invoke(this, null); outParameters.Add(attr.Name, ProtocolKeyAttribute.GetValueAsString(value, propInfo.PropertyType)); _negotiatedParameters.Add(attr.Name, string.Empty); } } } } } #region Scsi Bus /// <summary> /// Sends an SCSI command (aka task) to a LUN via the connected target. /// </summary> /// <param name="cmd">The command to send</param> /// <param name="outBuffer">The data to send with the command</param> /// <param name="outBufferOffset">The offset of the first byte to send</param> /// <param name="outBufferCount">The number of bytes to send, if any</param> /// <param name="inBuffer">The buffer to fill with returned data</param> /// <param name="inBufferOffset">The first byte to fill with returned data</param> /// <param name="inBufferMax">The maximum amount of data to receive</param> /// <returns>The number of bytes received</returns> private int Send(ScsiCommand cmd, byte[] outBuffer, int outBufferOffset, int outBufferCount, byte[] inBuffer, int inBufferOffset, int inBufferMax) { return _currentConnection.Send(cmd, outBuffer, outBufferOffset, outBufferCount, inBuffer, inBufferOffset, inBufferMax); } private T Send<T>(ScsiCommand cmd, byte[] buffer, int offset, int count, int expected) where T : ScsiResponse, new() { return _currentConnection.Send<T>(cmd, buffer, offset, count, expected); } #endregion } }
using System; using System.Text; using System.Collections; using System.Text.RegularExpressions; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace NoraGrace.Engine { public class ChessPGNHeaders : Dictionary<string,string> { public ChessPGNHeaders(): base(StringComparer.InvariantCultureIgnoreCase) { } public static bool TryParse(string headerLine, out KeyValuePair<string,string> header) { string pattern = @"\[(?<key>[\w]+)\s+\""(?<value>[\S\s]+)\""\]"; Regex regex = new Regex(pattern); MatchCollection matches = regex.Matches(headerLine); if (matches.Count != 1) { header = new KeyValuePair<string, string>(); return false; //throw new ArgumentException("not a valid pgn header: " + headerline); } System.Text.RegularExpressions.Match match = matches[0]; header = new KeyValuePair<string, string>(match.Groups["key"].Value, match.Groups["value"].Value); return true; } public static KeyValuePair<string, string> Parse(string headerLine) { KeyValuePair<string, string> retval; if (TryParse(headerLine, out retval)) { return retval; } else { throw new ArgumentException("not a valid pgn header: " + headerLine, "headerLine"); } } } public class PGN { private readonly List<Move> _moves = new List<Move>(); private GameResult? _result; private GameResultReason _resultReason; private readonly Dictionary<string, string> _headers = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); private readonly Dictionary<int, string> _comments = new Dictionary<int,string>(); public PGN(IEnumerable<KeyValuePair<string, string>> headers, IEnumerable<Move> moves, GameResult? result, IEnumerable<KeyValuePair<int, string>> comments, GameResultReason reason) { if (_headers != null) { foreach (var header in headers) { _headers.Add(header.Key, header.Value); } } _moves.AddRange(moves); _result = result; if (comments != null) { foreach (var comment in comments) { _comments.Add(comment.Key, comment.Value); } } _resultReason = reason; } public PGN(IEnumerable<KeyValuePair<string, string>> headers, Board board) { if (_headers != null) { foreach (var header in headers) { _headers.Add(header.Key, header.Value); } } _moves.AddRange(board.HistoryMoves); _result = null; _resultReason = GameResultReason.NotDecided; } //public ChessPGN(ChessGame game) //{ // _headers = new ChessPGNHeaders(); // _headers.Add(new ChessPGNHeader("White", game.PlayerWhite.Name)); // _headers.Add(new ChessPGNHeader("Black", game.PlayerBlack.Name)); // _headers.Add(new ChessPGNHeader("Date", DateTime.Now.ToShortDateString())); // //_headers.Add(new ChessPGNHeader("TotalNodes", ChessSearch.CountTotalAINodes.ToString())); // //_headers.Add(new ChessPGNHeader("TotalEvals", ChessEval.TotalAIEvals.ToString())); // //_headers.Add(new ChessPGNHeader("TotalAITime", ChessSearch.CountTotalAITime.ToString())); // //double nodesPerSec = ChessSearch.CountTotalAINodes / ChessSearch.CountTotalAITime.TotalSeconds; // //_headers.Add(new ChessPGNHeader("Nodes/Sec", nodesPerSec.ToString())); // _moves = new ReadOnlyCollection<ChessMove>(game.MoveHistory()); // _result = game.Result; // _resultReason = game.ResultReason; // _comments = new List<ChessPGNComment>(); //} public Dictionary<string, string> Headers { get { return _headers; } } public List<Move> Moves { get { return _moves; } } //public List<string> HeaderKeys //{ // get // { // List<string> retval = new List<string>(); // foreach (var header in _headers) // { // retval.Add(header.Key); // } // return retval; // } //} //public string HeaderValue(string key) //{ // ChessPGNHeader h = null; // foreach(var h1 in _headers) // { // if (h1.Key.ToLower() == key.ToLower()) { h = h1; } // } // if (h == null) // { // return ""; // } // else // { // return h.Value; // } //} public string StartingPosition { get { if (Headers.ContainsKey("FEN")) { return Headers["FEN"]; } else { return FEN.FENStart; } } } public GameResult? Result { get { return _result; } } public GameResultReason ResultReason { get { return _resultReason; } } public string White { get { return this.Headers["White"]; } } public string Black { get { return this.Headers["Black"]; } } public int? WhiteElo { get { int retval; if (int.TryParse(this.Headers["WhiteElo"], out retval)) { return retval; } else { return null; } } } public int? BlackElo { get { int retval; if (int.TryParse(this.Headers["BlackElo"], out retval)) { return retval; } else { return null; } } } public DateTime? Date { get { DateTime ret; if (DateTime.TryParse(this.Headers["Date"], out ret)) { return ret; } else if (DateTime.TryParse(this.Headers["EventDate"], out ret)) { return ret; } else { return null; } } } public string Site { get { return this.Headers["Site"]; } } public string EventName { get { return this.Headers["Event"]; } } public Dictionary<int, string> Comments { get { return _comments; } } //public ChessPGNComment CommentForPly(int iPly) //{ // foreach (ChessPGNComment comment in this._comments) // { // if (comment.MoveNum == iPly) // { // return comment; // } // } // return null; //} public override string ToString() { StringBuilder sb = new StringBuilder(); System.IO.StringWriter writer = new System.IO.StringWriter(sb); Write(writer); return sb.ToString(); } public void Write(System.IO.TextWriter writer, int MaxLineLen = 90) { Board board = new Board(this.StartingPosition); StringBuilder sbMoves = new StringBuilder(); StringBuilder sbHeaders = new StringBuilder(); ////result //string sResult = "*"; //switch (_result) //{ // case ChessResult.WhiteWins: sResult = "1-0"; break; // case ChessResult.BlackWins: sResult = "0-1"; break; // case ChessResult.Draw: sResult = "1/2-1/2"; break; // case null: sResult = "*"; break; //} //headers foreach (var header in _headers) { sbHeaders.AppendLine(string.Format(@"[{0} ""{1}""]", header.Key, header.Value));// header.ToString() + Environment.NewLine); } if (!_headers.ContainsKey("Result")) { //sbHeaders.Append(new ChessPGNHeader("Result", sResult).ToString() + Environment.NewLine); sbHeaders.Append(string.Format(@"[Result ""{0}""]", _headers["Result"]) + Environment.NewLine); } sbHeaders.Append(Environment.NewLine); ////write any comments before moves //ChessPGNComment comment = this.CommentForPly(0); //if (comment != null) //{ // sbMoves.Append("{"); // sbMoves.Append(comment.Text); // sbMoves.Append("} "); //} //moves int imove = 1; bool iswhite = true; foreach (Move move in _moves) { if (iswhite) { int ifullmove = (imove / 2) + 1; sbMoves.Append(ifullmove.ToString() + ". "); } sbMoves.Append(move.Description(board) + " "); board.MoveApply(move); if (Comments.ContainsKey(imove - 1)) { string comment = this.Comments[imove - 1]; sbMoves.Append("{"); sbMoves.Append(comment); sbMoves.Append("} "); } iswhite = !iswhite; imove++; } //result if (_result == GameResult.WhiteWins) { sbMoves.Append("1-0 "); } else if (_result == GameResult.BlackWins) { sbMoves.Append("0-1 "); } else if (_result == GameResult.Draw) { sbMoves.Append("1/2-1/2 "); } else if (_result == null) { sbMoves.Append("* "); } //reformat move section to break into lines. string[] movewords = sbMoves.ToString().Split(' '); sbMoves = new StringBuilder(); string currline = ""; foreach (string word in movewords) { if (currline == "") { currline += word; } else if (currline.Length + word.Length > MaxLineLen) { sbMoves.Append(currline + Environment.NewLine); currline = word; } else { currline += " " + word; } } sbMoves.Append(currline + Environment.NewLine); //return result writer.Write(sbHeaders.ToString()); writer.Write(sbMoves.ToString()); writer.WriteLine(); //return sbHeaders.ToString() + sbMoves.ToString(); } public static IEnumerable<PGN> AllGames(System.IO.StreamReader reader) { while (true) { PGN pgn = NextGame(reader); if (pgn == null) { break; } yield return pgn; } } public static IEnumerable<PGN> AllGames(System.IO.FileInfo file) { using (var reader = new System.IO.StreamReader(file.FullName)) { while (true) { PGN pgn = NextGame(reader); if (pgn == null) { break; } yield return pgn; } } } public static PGN NextGame(string PGNString) { System.IO.MemoryStream memory = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(PGNString)); System.IO.StreamReader reader = new System.IO.StreamReader(memory); return NextGame(reader); } public static PGN NextGame(System.IO.StreamReader reader) { ChessPGNHeaders headers = new ChessPGNHeaders(); Dictionary<int, string> comments = new Dictionary<int, string>(); List<Move> moves = new List<Move>(); GameResult? result = null; GameResultReason reason = GameResultReason.NotDecided; Board board = new Board(); int headerlevel = 0; int commentlevel = 0; bool processtok = false; bool gamedone = false; string token = ""; string line; while (!gamedone || commentlevel != 0) { line = reader.ReadLine(); if (line == null) { break; } line += " "; char[] cArray = line.ToCharArray(); foreach (char c in cArray) { if (c == '[') { //begin new header headerlevel++; } else if (c == ']' && headerlevel > 0) { //end header headerlevel--; if (headerlevel == 0) { var header = ChessPGNHeaders.Parse("[" + token + "]"); headers.Add(header.Key, header.Value); if (header.Key.ToUpper() == "FEN") { board = new Board(header.Value); } token = ""; } } else if (headerlevel != 0) { //in header token += c.ToString(); } else if (c == '(' || c == '{') { //begin comment commentlevel++; } else if (c == ')' || c == '}') { //end comment; commentlevel--; if (commentlevel == 0) { //comments.Add(new ChessPGNComment(moves.Count, token)); if (comments.ContainsKey(moves.Count - 1)) { token = comments[moves.Count - 1] + " " + token; comments.Remove(moves.Count - 1); } comments.Add(moves.Count - 1, token); } token = ""; } else if (commentlevel != 0) { token += c; //in comments don't do anything } else if (c == '.') { //a '.' means that we encountered a move number toss this away. token = ""; } else if (c == ' ') { processtok = true; } else { token += c; } // if (processtok && token == "") { processtok = false; } else if (processtok) { processtok = false; bool OkToProcessResults = (headers.Count > 0 || moves.Count > 0); //must have some moves or headers before processing results //otherwise you MAY pick up a result on a new line after previous game if (token.Trim() == "1/2-1/2") { if (OkToProcessResults) { result = GameResult.Draw; if (board.IsDrawByStalemate()) { reason = GameResultReason.Stalemate; } else if (board.IsDrawByRepetition()) { reason = GameResultReason.Repetition; } else if (board.IsDrawBy50MoveRule()) { reason = GameResultReason.FiftyMoveRule; } else { reason = GameResultReason.MutualAgreement; } gamedone = true; } } else if (token.Trim() == "1-0") { if (OkToProcessResults) { result = GameResult.WhiteWins; if (board.IsMate()) { reason = GameResultReason.Checkmate; } else { reason = GameResultReason.Resign; } gamedone = true; } } else if (token.Trim() == "0-1") { if (OkToProcessResults) { result = GameResult.BlackWins; if (board.IsMate()) { reason = GameResultReason.Checkmate; } else { reason = GameResultReason.Resign; } gamedone = true; } } else if (token.Trim() == "*") { if (OkToProcessResults) { result = null; gamedone = true; } } else { Move move = MoveUtil.Parse(board, token); board.MoveApply(move); moves.Add(move); //check for mate. if (board.IsMate()) { if (board.WhosTurn == Player.White) { result = GameResult.BlackWins; reason = GameResultReason.Checkmate; } else { result = GameResult.WhiteWins; reason = GameResultReason.Checkmate; } gamedone = true; } } token = ""; } } } if (moves.Count > 0 || headers.Count > 0) { return new PGN(headers, moves, result, comments, reason); } else { return null; } } } public static class ExtensionsChessPGN { public static string Summary(this IEnumerable<PGN> PGNs) { StringBuilder sb = new StringBuilder(); foreach (var winnerGroup in PGNs.GroupBy(pgn => new { Winner = pgn.Result == GameResult.WhiteWins ? pgn.White : pgn.Result == GameResult.BlackWins ? pgn.Black : "Draw" })) { sb.AppendLine(string.Format("{0,-20} Wins:{1,-4} AvgLen:{2,-5}", winnerGroup.Key.Winner, winnerGroup.Count(), winnerGroup.Average(pgn => pgn.Moves.Count()))); foreach (var reasongroup in winnerGroup.GroupBy(pgn => pgn.ResultReason)) { sb.AppendLine(string.Format("\t{0,-20} Wins:{1,-4} AvgLen:{2,-5}", reasongroup.Key, reasongroup.Count(), reasongroup.Average(pgn => pgn.Moves.Count()))); foreach (var gameLenGroup in reasongroup.GroupBy(pgn => (pgn.Moves.Count / 10) * 10).OrderBy(pgn => pgn.Key)) { sb.AppendLine(string.Format("\t\t {0}-{1} Wins:{2,-4} Min:{3} Max:{4}", gameLenGroup.Key, gameLenGroup.Key + 9, gameLenGroup.Count(), gameLenGroup.Min(pgn => pgn.Moves.Count()), gameLenGroup.Max(pgn => pgn.Moves.Count()))); } } } return sb.ToString(); } public static void ResultsForPlayer(this IEnumerable<PGN> PGNs, string playerName, out int wins, out int losses, out int draws) { wins=0; losses=0; draws=0; foreach (PGN pgn in PGNs) { if (playerName == pgn.White) { if (pgn.Result == GameResult.WhiteWins) { wins++; } else if (pgn.Result == GameResult.BlackWins) { losses++; } else if (pgn.Result == GameResult.Draw) { draws++; } } else if (playerName == pgn.Black) { if (pgn.Result == GameResult.WhiteWins) { losses++; } else if (pgn.Result == GameResult.BlackWins) { wins++; } else if (pgn.Result == GameResult.Draw) { draws++; } } } } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using ASC.Common.Data; using ASC.Common.Data.Sql; using ASC.Common.Data.Sql.Expressions; using ASC.Core; using ASC.Core.Tenants; using ASC.Files.Core; using ASC.Files.Core.Security; using ASC.Security.Cryptography; using ASC.Web.Files.Classes; using Dropbox.Api.Files; namespace ASC.Files.Thirdparty.Dropbox { internal abstract class DropboxDaoBase { protected readonly DropboxDaoSelector DropboxDaoSelector; public int TenantID { get; private set; } public DropboxProviderInfo DropboxProviderInfo { get; private set; } public string PathPrefix { get; private set; } protected DropboxDaoBase(DropboxDaoSelector.DropboxInfo dropboxInfo, DropboxDaoSelector dropboxDaoSelector) { DropboxProviderInfo = dropboxInfo.DropboxProviderInfo; PathPrefix = dropboxInfo.PathPrefix; DropboxDaoSelector = dropboxDaoSelector; TenantID = CoreContext.TenantManager.GetCurrentTenant().TenantId; } public void Dispose() { DropboxProviderInfo.Dispose(); } protected IDbManager GetDb() { return DbManager.FromHttpContext(FileConstant.DatabaseId); } protected object MappingID(object id, bool saveIfNotExist = false) { if (id == null) return null; int n; var isNumeric = int.TryParse(id.ToString(), out n); if (isNumeric) return n; object result; using (var db = GetDb()) { if (id.ToString().StartsWith("dropbox")) { result = Regex.Replace(BitConverter.ToString(Hasher.Hash(id.ToString(), HashAlg.MD5)), "-", "").ToLower(); } else { result = db.ExecuteScalar<String>(Query("files_thirdparty_id_mapping") .Select("id") .Where(Exp.Eq("hash_id", id))); } if (saveIfNotExist) { db.ExecuteNonQuery(Insert("files_thirdparty_id_mapping") .InColumnValue("id", id) .InColumnValue("hash_id", result)); } } return result; } protected SqlQuery Query(string table) { return new SqlQuery(table).Where(GetTenantColumnName(table), TenantID); } protected SqlDelete Delete(string table) { return new SqlDelete(table).Where(GetTenantColumnName(table), TenantID); } protected SqlInsert Insert(string table) { return new SqlInsert(table, true).InColumns(GetTenantColumnName(table)).Values(TenantID); } private static string GetTenantColumnName(string table) { const string tenant = "tenant_id"; if (!table.Contains(" ")) return tenant; return table.Substring(table.IndexOf(" ", StringComparison.InvariantCulture)).Trim() + "." + tenant; } protected static string GetParentFolderPath(Metadata dropboxItem) { if (dropboxItem == null || IsRoot(dropboxItem.AsFolder)) return null; var pathLength = dropboxItem.PathDisplay.Length - dropboxItem.Name.Length; return dropboxItem.PathDisplay.Substring(0, pathLength > 1 ? pathLength - 1 : 0); } protected static string MakeDropboxPath(object entryId) { return Convert.ToString(entryId, CultureInfo.InvariantCulture); } protected string MakeDropboxPath(Metadata dropboxItem) { string path = null; if (dropboxItem != null) { path = dropboxItem.PathDisplay; } return path; } protected string MakeId(Metadata dropboxItem) { return MakeId(MakeDropboxPath(dropboxItem)); } protected string MakeId(string path = null) { return string.Format("{0}{1}", PathPrefix, string.IsNullOrEmpty(path) || path == "/" ? "" : ("-" + path.Replace('/', '|'))); } protected String MakeFolderTitle(FolderMetadata dropboxFolder) { if (dropboxFolder == null || IsRoot(dropboxFolder)) { return DropboxProviderInfo.CustomerTitle; } return Global.ReplaceInvalidCharsAndTruncate(dropboxFolder.Name); } protected String MakeFileTitle(FileMetadata dropboxFile) { if (dropboxFile == null || string.IsNullOrEmpty(dropboxFile.Name)) { return DropboxProviderInfo.ProviderKey; } return Global.ReplaceInvalidCharsAndTruncate(dropboxFile.Name); } protected Folder ToFolder(FolderMetadata dropboxFolder) { if (dropboxFolder == null) return null; if (dropboxFolder is ErrorFolder) { //Return error entry return ToErrorFolder(dropboxFolder as ErrorFolder); } var isRoot = IsRoot(dropboxFolder); var folder = new Folder { ID = MakeId(dropboxFolder), ParentFolderID = isRoot ? null : MakeId(GetParentFolderPath(dropboxFolder)), CreateBy = DropboxProviderInfo.Owner, CreateOn = isRoot ? DropboxProviderInfo.CreateOn : default(DateTime), FolderType = FolderType.DEFAULT, ModifiedBy = DropboxProviderInfo.Owner, ModifiedOn = isRoot ? DropboxProviderInfo.CreateOn : default(DateTime), ProviderId = DropboxProviderInfo.ID, ProviderKey = DropboxProviderInfo.ProviderKey, RootFolderCreator = DropboxProviderInfo.Owner, RootFolderId = MakeId(), RootFolderType = DropboxProviderInfo.RootFolderType, Shareable = false, Title = MakeFolderTitle(dropboxFolder), TotalFiles = 0, TotalSubFolders = 0, }; if (folder.CreateOn != DateTime.MinValue && folder.CreateOn.Kind == DateTimeKind.Utc) folder.CreateOn = TenantUtil.DateTimeFromUtc(folder.CreateOn); if (folder.ModifiedOn != DateTime.MinValue && folder.ModifiedOn.Kind == DateTimeKind.Utc) folder.ModifiedOn = TenantUtil.DateTimeFromUtc(folder.ModifiedOn); return folder; } protected static bool IsRoot(FolderMetadata dropboxFolder) { return dropboxFolder != null && dropboxFolder.Id == "/"; } private File ToErrorFile(ErrorFile dropboxFile) { if (dropboxFile == null) return null; return new File { ID = MakeId(dropboxFile.ErrorId), CreateBy = DropboxProviderInfo.Owner, CreateOn = TenantUtil.DateTimeNow(), ModifiedBy = DropboxProviderInfo.Owner, ModifiedOn = TenantUtil.DateTimeNow(), ProviderId = DropboxProviderInfo.ID, ProviderKey = DropboxProviderInfo.ProviderKey, RootFolderCreator = DropboxProviderInfo.Owner, RootFolderId = MakeId(), RootFolderType = DropboxProviderInfo.RootFolderType, Title = MakeFileTitle(dropboxFile), Error = dropboxFile.Error }; } private Folder ToErrorFolder(ErrorFolder dropboxFolder) { if (dropboxFolder == null) return null; return new Folder { ID = MakeId(dropboxFolder.ErrorId), ParentFolderID = null, CreateBy = DropboxProviderInfo.Owner, CreateOn = TenantUtil.DateTimeNow(), FolderType = FolderType.DEFAULT, ModifiedBy = DropboxProviderInfo.Owner, ModifiedOn = TenantUtil.DateTimeNow(), ProviderId = DropboxProviderInfo.ID, ProviderKey = DropboxProviderInfo.ProviderKey, RootFolderCreator = DropboxProviderInfo.Owner, RootFolderId = MakeId(), RootFolderType = DropboxProviderInfo.RootFolderType, Shareable = false, Title = MakeFolderTitle(dropboxFolder), TotalFiles = 0, TotalSubFolders = 0, Error = dropboxFolder.Error }; } public File ToFile(FileMetadata dropboxFile) { if (dropboxFile == null) return null; if (dropboxFile is ErrorFile) { //Return error entry return ToErrorFile(dropboxFile as ErrorFile); } return new File { ID = MakeId(dropboxFile), Access = FileShare.None, ContentLength = (long)dropboxFile.Size, CreateBy = DropboxProviderInfo.Owner, CreateOn = TenantUtil.DateTimeFromUtc(dropboxFile.ServerModified), FileStatus = FileStatus.None, FolderID = MakeId(GetParentFolderPath(dropboxFile)), ModifiedBy = DropboxProviderInfo.Owner, ModifiedOn = TenantUtil.DateTimeFromUtc(dropboxFile.ServerModified), NativeAccessor = dropboxFile, ProviderId = DropboxProviderInfo.ID, ProviderKey = DropboxProviderInfo.ProviderKey, Title = MakeFileTitle(dropboxFile), RootFolderId = MakeId(), RootFolderType = DropboxProviderInfo.RootFolderType, RootFolderCreator = DropboxProviderInfo.Owner, Shared = false, Version = 1 }; } public Folder GetRootFolder(object folderId) { return ToFolder(GetDropboxFolder(string.Empty)); } protected FolderMetadata GetDropboxFolder(object folderId) { var dropboxFolderPath = MakeDropboxPath(folderId); try { var folder = DropboxProviderInfo.GetDropboxFolder(dropboxFolderPath); return folder; } catch (Exception ex) { return new ErrorFolder(ex, dropboxFolderPath); } } protected FileMetadata GetDropboxFile(object fileId) { var dropboxFilePath = MakeDropboxPath(fileId); try { var file = DropboxProviderInfo.GetDropboxFile(dropboxFilePath); return file; } catch (Exception ex) { return new ErrorFile(ex, dropboxFilePath); } } protected IEnumerable<string> GetChildren(object folderId) { return GetDropboxItems(folderId).Select(MakeId); } protected List<Metadata> GetDropboxItems(object parentId, bool? folder = null) { var dropboxFolderPath = MakeDropboxPath(parentId); var items = DropboxProviderInfo.GetDropboxItems(dropboxFolderPath); if (folder.HasValue) { if (folder.Value) { return items.Where(i => i.AsFolder != null).ToList(); } return items.Where(i => i.AsFile != null).ToList(); } return items; } protected sealed class ErrorFolder : FolderMetadata { public string Error { get; set; } public string ErrorId { get; private set; } public ErrorFolder(Exception e, object id) { ErrorId = id.ToString(); if (e != null) { Error = e.Message; } } } protected sealed class ErrorFile : FileMetadata { public string Error { get; set; } public string ErrorId { get; private set; } public ErrorFile(Exception e, object id) { ErrorId = id.ToString(); if (e != null) { Error = e.Message; } } } protected String GetAvailableTitle(String requestTitle, string parentFolderPath, Func<string, string, bool> isExist) { if (!isExist(requestTitle, parentFolderPath)) return requestTitle; var re = new Regex(@"( \(((?<index>[0-9])+)\)(\.[^\.]*)?)$"); var match = re.Match(requestTitle); if (!match.Success) { var insertIndex = requestTitle.Length; if (requestTitle.LastIndexOf(".", StringComparison.InvariantCulture) != -1) { insertIndex = requestTitle.LastIndexOf(".", StringComparison.InvariantCulture); } requestTitle = requestTitle.Insert(insertIndex, " (1)"); } while (isExist(requestTitle, parentFolderPath)) { requestTitle = re.Replace(requestTitle, MatchEvaluator); } return requestTitle; } private static String MatchEvaluator(Match match) { var index = Convert.ToInt32(match.Groups[2].Value); var staticText = match.Value.Substring(String.Format(" ({0})", index).Length); return String.Format(" ({0}){1}", index + 1, staticText); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; namespace OpenSim.Framework { /// <summary> /// Represent generic cache to store key/value pairs (elements) limited by time, size and count of elements. /// </summary> /// <typeparam name="TKey"> /// The type of keys in the cache. /// </typeparam> /// <typeparam name="TValue"> /// The type of values in the cache. /// </typeparam> /// <remarks> /// <para> /// Cache store limitations: /// </para> /// <list type="table"> /// <listheader> /// <term>Limitation</term> /// <description>Description</description> /// </listheader> /// <item> /// <term>Time</term> /// <description> /// Element that is not accessed through <see cref="TryGetValue"/> or <see cref="Set"/> in last <see cref="ExpirationTime"/> are /// removed from the cache automatically. Depending on implementation of the cache some of elements may stay longer in cache. /// <see cref="IsTimeLimited"/> returns <see langword="true"/>, if cache is limited by time. /// </description> /// </item> /// <item> /// <term>Count</term> /// <description> /// When adding an new element to cache that already have <see cref="MaxCount"/> of elements, cache will remove less recently /// used element(s) from the cache, until element fits to cache. /// <see cref="IsCountLimited"/> returns <see langword="true"/>, if cache is limiting element count. /// </description> /// </item> /// <item> /// <term>Size</term> /// <description> /// <description> /// When adding an new element to cache that already have <see cref="MaxSize"/> of elements, cache will remove less recently /// used element(s) from the cache, until element fits to cache. /// <see cref="IsSizeLimited"/> returns <see langword="true"/>, if cache is limiting total size of elements. /// Normally size is bytes used by element in the cache. But it can be any other suitable unit of measure. /// </description> /// </description> /// </item> /// </list> /// </remarks> public interface ICnmCache<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>> { /// <summary> /// Gets current count of elements stored to <see cref="ICnmCache{TKey,TValue}"/>. /// </summary> /// <remarks> /// <para> /// When adding an new element to <see cref="ICnmCache{TKey,TValue}"/> that is limiting element count, /// <see cref="ICnmCache{TKey,TValue}"/> will remove less recently used elements until it can fit an new element. /// </para> /// </remarks> /// <seealso cref="MaxCount"/> /// <seealso cref="IsCountLimited"/> /// <seealso cref="IsSizeLimited"/> /// <seealso cref="IsTimeLimited"/> int Count { get; } /// <summary> /// Gets or sets elements expiration time. /// </summary> /// <value> /// Elements expiration time. /// </value> /// <remarks> /// <para> /// When element has been stored in <see cref="ICnmCache{TKey,TValue}"/> longer than <see cref="ExpirationTime"/> /// and it is not accessed through <see cref="TryGetValue"/> method or element's value is /// not replaced by <see cref="Set"/> method, then it is automatically removed from the /// <see cref="ICnmCache{TKey,TValue}"/>. /// </para> /// <para> /// It is possible that <see cref="ICnmCache{TKey,TValue}"/> implementation removes element before it's expiration time, /// because total size or count of elements stored to cache is larger than <see cref="MaxSize"/> or <see cref="MaxCount"/>. /// </para> /// <para> /// It is also possible that element stays in cache longer than <see cref="ExpirationTime"/>. /// </para> /// <para> /// Calling <see cref="PurgeExpired"/> try to remove all elements that are expired. /// </para> /// <para> /// To disable time limit in cache, set <see cref="ExpirationTime"/> to <see cref="DateTime.MaxValue"/>. /// </para> /// </remarks> /// <seealso cref="IsTimeLimited"/> /// <seealso cref="IsCountLimited"/> /// <seealso cref="IsSizeLimited"/> /// <seealso cref="PurgeExpired"/> /// <seealso cref="Count"/> /// <seealso cref="MaxCount"/> /// <seealso cref="MaxSize"/> /// <seealso cref="Size"/> TimeSpan ExpirationTime { get; set; } /// <summary> /// Gets a value indicating whether <see cref="ICnmCache{TKey,TValue}"/> is limiting count of elements. /// </summary> /// <value> /// <see langword="true"/> if the <see cref="ICnmCache{TKey,TValue}"/> count of elements is limited; /// otherwise, <see langword="false"/>. /// </value> /// <remarks> /// <para> /// When adding an new element to <see cref="ICnmCache{TKey,TValue}"/> that is limiting element count, /// <see cref="ICnmCache{TKey,TValue}"/> will remove less recently used elements until it can fit an new element. /// </para> /// </remarks> /// <seealso cref="Count"/> /// <seealso cref="MaxCount"/> /// <seealso cref="IsSizeLimited"/> /// <seealso cref="IsTimeLimited"/> bool IsCountLimited { get; } /// <summary> /// Gets a value indicating whether <see cref="ICnmCache{TKey,TValue}"/> is limiting size of elements. /// </summary> /// <value> /// <see langword="true"/> if the <see cref="ICnmCache{TKey,TValue}"/> total size of elements is limited; /// otherwise, <see langword="false"/>. /// </value> /// <remarks> /// <para> /// When adding an new element to <see cref="ICnmCache{TKey,TValue}"/> that is limiting total size of elements, /// <see cref="ICnmCache{TKey,TValue}"/> will remove less recently used elements until it can fit an new element. /// </para> /// </remarks> /// <seealso cref="MaxElementSize"/> /// <seealso cref="Size"/> /// <seealso cref="MaxSize"/> /// <seealso cref="IsCountLimited"/> /// <seealso cref="IsTimeLimited"/> bool IsSizeLimited { get; } /// <summary> /// Gets a value indicating whether or not access to the <see cref="ICnmCache{TKey,TValue}"/> is synchronized (thread safe). /// </summary> /// <value> /// <see langword="true"/> if access to the <see cref="ICnmCache{TKey,TValue}"/> is synchronized (thread safe); /// otherwise, <see langword="false"/>. /// </value> /// <remarks> /// <para> /// To get synchronized (thread safe) access to <see cref="ICnmCache{TKey,TValue}"/> object, use /// <see cref="CnmSynchronizedCache{TKey,TValue}.Synchronized"/> in <see cref="CnmSynchronizedCache{TKey,TValue}"/> class /// to retrieve synchronized wrapper for <see cref="ICnmCache{TKey,TValue}"/> object. /// </para> /// </remarks> /// <seealso cref="SyncRoot"/> /// <seealso cref="CnmSynchronizedCache{TKey,TValue}"/> bool IsSynchronized { get; } /// <summary> /// Gets a value indicating whether elements stored to <see cref="ICnmCache{TKey,TValue}"/> have limited inactivity time. /// </summary> /// <value> /// <see langword="true"/> if the <see cref="ICnmCache{TKey,TValue}"/> has a fixed total size of elements; /// otherwise, <see langword="false"/>. /// </value> /// <remarks> /// If <see cref="ICnmCache{TKey,TValue}"/> have limited inactivity time and element is not accessed through <see cref="Set"/> /// or <see cref="TryGetValue"/> methods in <see cref="ExpirationTime"/> , then element is automatically removed from /// the cache. Depending on implementation of the <see cref="ICnmCache{TKey,TValue}"/>, some of the elements may /// stay longer in cache. /// </remarks> /// <seealso cref="ExpirationTime"/> /// <seealso cref="PurgeExpired"/> /// <seealso cref="IsCountLimited"/> /// <seealso cref="IsSizeLimited"/> bool IsTimeLimited { get; } /// <summary> /// Gets or sets maximal allowed count of elements that can be stored to <see cref="ICnmCache{TKey,TValue}"/>. /// </summary> /// <value> /// <see cref="int.MaxValue"/>, if <see cref="ICnmCache{TKey,TValue}"/> is not limited by count of elements; /// otherwise maximal allowed count of elements. /// </value> /// <remarks> /// <para> /// When adding an new element to <see cref="ICnmCache{TKey,TValue}"/> that is limiting element count, /// <see cref="ICnmCache{TKey,TValue}"/> will remove less recently used elements until it can fit an new element. /// </para> /// </remarks> int MaxCount { get; set; } /// <summary> /// <para>Gets maximal allowed element size.</para> /// </summary> /// <value> /// Maximal allowed element size. /// </value> /// <remarks> /// <para> /// If element's size is larger than <see cref="MaxElementSize"/>, then element is /// not added to the <see cref="ICnmCache{TKey,TValue}"/>. /// </para> /// </remarks> /// <seealso cref="Set"/> /// <seealso cref="IsSizeLimited"/> /// <seealso cref="Size"/> /// <seealso cref="MaxSize"/> long MaxElementSize { get; } /// <summary> /// Gets or sets maximal allowed total size for elements stored to <see cref="ICnmCache{TKey,TValue}"/>. /// </summary> /// <value> /// Maximal allowed total size for elements stored to <see cref="ICnmCache{TKey,TValue}"/>. /// </value> /// <remarks> /// <para> /// Normally size is total bytes used by elements in the cache. But it can be any other suitable unit of measure. /// </para> /// <para> /// When adding an new element to <see cref="ICnmCache{TKey,TValue}"/> that is limiting total size of elements, /// <see cref="ICnmCache{TKey,TValue}"/> will remove less recently used elements until it can fit an new element. /// </para> /// </remarks> /// <exception cref="ArgumentOutOfRangeException">value is less than 0.</exception> /// <seealso cref="MaxElementSize"/> /// <seealso cref="IsSizeLimited"/> /// <seealso cref="Size"/> long MaxSize { get; set; } /// <summary> /// Gets total size of elements stored to <see cref="ICnmCache{TKey,TValue}"/>. /// </summary> /// <value> /// Total size of elements stored to <see cref="ICnmCache{TKey,TValue}"/>. /// </value> /// <remarks> /// <para> /// Normally bytes, but can be any suitable unit of measure. /// </para> /// <para> /// Element's size is given when element is added or replaced by <see cref="Set"/> method. /// </para> /// <para> /// When adding an new element to <see cref="ICnmCache{TKey,TValue}"/> that is limiting total size of elements, /// <see cref="ICnmCache{TKey,TValue}"/> will remove less recently used elements until it can fit an new element. /// </para> /// </remarks> /// <seealso cref="MaxElementSize"/> /// <seealso cref="IsSizeLimited"/> /// <seealso cref="MaxSize"/> /// <seealso cref="IsCountLimited"/> /// <seealso cref="ExpirationTime"/> long Size { get; } /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="ICnmCache{TKey,TValue}"/>. /// </summary> /// <value> /// An object that can be used to synchronize access to the <see cref="ICnmCache{TKey,TValue}"/>. /// </value> /// <remarks> /// <para> /// To get synchronized (thread safe) access to <see cref="ICnmCache{TKey,TValue}"/>, use <see cref="CnmSynchronizedCache{TKey,TValue}"/> /// method <see cref="CnmSynchronizedCache{TKey,TValue}.Synchronized"/> to retrieve synchronized wrapper interface to /// <see cref="ICnmCache{TKey,TValue}"/>. /// </para> /// </remarks> /// <seealso cref="IsSynchronized"/> /// <seealso cref="CnmSynchronizedCache{TKey,TValue}"/> object SyncRoot { get; } /// <summary> /// Removes all elements from the <see cref="ICnmCache{TKey,TValue}"/>. /// </summary> /// <seealso cref="Set"/> /// <seealso cref="Remove"/> /// <seealso cref="RemoveRange"/> /// <seealso cref="TryGetValue"/> /// <seealso cref="PurgeExpired"/> void Clear(); /// <summary> /// Purge expired elements from the <see cref="ICnmCache{TKey,TValue}"/>. /// </summary> /// <remarks> /// <para> /// Element becomes expired when last access time to it has been longer time than <see cref="ExpirationTime"/>. /// </para> /// <para> /// Depending on <see cref="ICnmCache{TKey,TValue}"/> implementation, some of expired elements /// may stay longer than <see cref="ExpirationTime"/> in the cache. /// </para> /// </remarks> /// <seealso cref="IsTimeLimited"/> /// <seealso cref="ExpirationTime"/> /// <seealso cref="Set"/> /// <seealso cref="Remove"/> /// <seealso cref="RemoveRange"/> /// <seealso cref="TryGetValue"/> /// <seealso cref="Clear"/> void PurgeExpired(); /// <summary> /// Removes element associated with <paramref name="key"/> from the <see cref="ICnmCache{TKey,TValue}"/>. /// </summary> /// <param name="key"> /// The key that is associated with element to remove from the <see cref="ICnmCache{TKey,TValue}"/>. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="key"/> is <see langword="null"/>. /// </exception> /// <seealso cref="Set"/> /// <seealso cref="RemoveRange"/> /// <seealso cref="TryGetValue"/> /// <seealso cref="Clear"/> /// <seealso cref="PurgeExpired"/> void Remove(TKey key); /// <summary> /// Removes elements that are associated with one of <paramref name="keys"/> from the <see cref="ICnmCache{TKey,TValue}"/>. /// </summary> /// <param name="keys"> /// The keys that are associated with elements to remove from the <see cref="ICnmCache{TKey,TValue}"/>. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="keys"/> is <see langword="null"/>. /// </exception> /// <seealso cref="Set"/> /// <seealso cref="Remove"/> /// <seealso cref="TryGetValue"/> /// <seealso cref="Clear"/> /// <seealso cref="PurgeExpired"/> void RemoveRange(IEnumerable<TKey> keys); /// <summary> /// Add or replace an element with the provided <paramref name="key"/>, <paramref name="value"/> and <paramref name="size"/> to /// <see cref="ICnmCache{TKey,TValue}"/>. /// </summary> /// <param name="key"> /// The object used as the key of the element. Can't be <see langword="null"/> reference. /// </param> /// <param name="value"> /// The object used as the value of the element to add or replace. <see langword="null"/> is allowed. /// </param> /// <param name="size"> /// The element's size. Normally bytes, but can be any suitable unit of measure. /// </param> /// <returns> /// <see langword="true"/> if element has been added successfully to the <see cref="ICnmCache{TKey,TValue}"/>; /// otherwise <see langword="false"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="key"/>is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The element's <paramref name="size"/> is less than 0. /// </exception> /// <remarks> /// <para> /// If element's <paramref name="size"/> is larger than <see cref="MaxElementSize"/>, then element is /// not added to the <see cref="ICnmCache{TKey,TValue}"/>, however - possible older element is /// removed from the <see cref="ICnmCache{TKey,TValue}"/>. /// </para> /// <para> /// When adding an new element to <see cref="ICnmCache{TKey,TValue}"/> that is limiting total size of elements, /// <see cref="ICnmCache{TKey,TValue}"/>will remove less recently used elements until it can fit an new element. /// </para> /// <para> /// When adding an new element to <see cref="ICnmCache{TKey,TValue}"/> that is limiting element count, /// <see cref="ICnmCache{TKey,TValue}"/>will remove less recently used elements until it can fit an new element. /// </para> /// </remarks> /// <seealso cref="IsSizeLimited"/> /// <seealso cref="IsCountLimited"/> /// <seealso cref="Remove"/> /// <seealso cref="RemoveRange"/> /// <seealso cref="TryGetValue"/> /// <seealso cref="Clear"/> /// <seealso cref="PurgeExpired"/> bool Set(TKey key, TValue value, long size); /// <summary> /// Gets the <paramref name="value"/> associated with the specified <paramref name="key"/>. /// </summary> /// <returns> /// <see langword="true"/>if the <see cref="ICnmCache{TKey,TValue}"/> contains an element with /// the specified key; otherwise, <see langword="false"/>. /// </returns> /// <param name="key"> /// The key whose <paramref name="value"/> to get. /// </param> /// <param name="value"> /// When this method returns, the value associated with the specified <paramref name="key"/>, /// if the <paramref name="key"/> is found; otherwise, the /// default value for the type of the <paramref name="value"/> parameter. This parameter is passed uninitialized. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="key"/>is <see langword="null"/>. /// </exception> /// <seealso cref="Set"/> /// <seealso cref="Remove"/> /// <seealso cref="RemoveRange"/> /// <seealso cref="Clear"/> /// <seealso cref="PurgeExpired"/> bool TryGetValue(TKey key, out TValue value); } }
// Copyright (C) 2014 dot42 // // Original filename: Java.Nio.Channels.Spi.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Java.Nio.Channels.Spi { /// <summary> /// <para><c> SelectorProvider </c> is an abstract base class that declares methods for providing instances of DatagramChannel, Pipe, java.nio.channels.Selector , ServerSocketChannel, and SocketChannel. All the methods of this class are thread-safe.</para><para>A provider instance can be retrieved through a system property or the configuration file in a jar file; if no provider is available that way then the system default provider is returned. </para> /// </summary> /// <java-name> /// java/nio/channels/spi/SelectorProvider /// </java-name> [Dot42.DexImport("java/nio/channels/spi/SelectorProvider", AccessFlags = 1057)] public abstract partial class SelectorProvider /* scope: __dot42__ */ { /// <summary> /// <para>Constructs a new <c> SelectorProvider </c> . </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 4)] protected internal SelectorProvider() /* MethodBuilder.Create */ { } /// <summary> /// <para>Gets a provider instance by executing the following steps when called for the first time: <ul><li><para>if the system property "java.nio.channels.spi.SelectorProvider" is set, the value of this property is the class name of the provider returned; </para></li><li><para>if there is a provider-configuration file named "java.nio.channels.spi.SelectorProvider" in META-INF/services of a jar file valid in the system class loader, the first class name is the provider's class name; </para></li><li><para>otherwise, a system default provider will be returned. </para></li></ul></para><para></para> /// </summary> /// <returns> /// <para>the provider. </para> /// </returns> /// <java-name> /// provider /// </java-name> [Dot42.DexImport("provider", "()Ljava/nio/channels/spi/SelectorProvider;", AccessFlags = 41)] public static global::Java.Nio.Channels.Spi.SelectorProvider Provider() /* MethodBuilder.Create */ { return default(global::Java.Nio.Channels.Spi.SelectorProvider); } /// <summary> /// <para>Creates a new open <c> DatagramChannel </c> .</para><para></para> /// </summary> /// <returns> /// <para>the new channel. </para> /// </returns> /// <java-name> /// openDatagramChannel /// </java-name> [Dot42.DexImport("openDatagramChannel", "()Ljava/nio/channels/DatagramChannel;", AccessFlags = 1025)] public abstract global::Java.Nio.Channels.DatagramChannel OpenDatagramChannel() /* MethodBuilder.Create */ ; /// <summary> /// <para>Creates a new <c> Pipe </c> .</para><para></para> /// </summary> /// <returns> /// <para>the new pipe. </para> /// </returns> /// <java-name> /// openPipe /// </java-name> [Dot42.DexImport("openPipe", "()Ljava/nio/channels/Pipe;", AccessFlags = 1025)] public abstract global::Java.Nio.Channels.Pipe OpenPipe() /* MethodBuilder.Create */ ; /// <summary> /// <para>Creates a new selector.</para><para></para> /// </summary> /// <returns> /// <para>the new selector. </para> /// </returns> /// <java-name> /// openSelector /// </java-name> [Dot42.DexImport("openSelector", "()Ljava/nio/channels/spi/AbstractSelector;", AccessFlags = 1025)] public abstract global::Java.Nio.Channels.Spi.AbstractSelector OpenSelector() /* MethodBuilder.Create */ ; /// <summary> /// <para>Creates a new open <c> ServerSocketChannel </c> .</para><para></para> /// </summary> /// <returns> /// <para>the new channel. </para> /// </returns> /// <java-name> /// openServerSocketChannel /// </java-name> [Dot42.DexImport("openServerSocketChannel", "()Ljava/nio/channels/ServerSocketChannel;", AccessFlags = 1025)] public abstract global::Java.Nio.Channels.ServerSocketChannel OpenServerSocketChannel() /* MethodBuilder.Create */ ; /// <summary> /// <para>Create a new open <c> SocketChannel </c> .</para><para></para> /// </summary> /// <returns> /// <para>the new channel. </para> /// </returns> /// <java-name> /// openSocketChannel /// </java-name> [Dot42.DexImport("openSocketChannel", "()Ljava/nio/channels/SocketChannel;", AccessFlags = 1025)] public abstract global::Java.Nio.Channels.SocketChannel OpenSocketChannel() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the channel inherited from the process that created this VM. On Android, this method always returns null because stdin and stdout are never connected to a socket.</para><para></para> /// </summary> /// <returns> /// <para>the channel. </para> /// </returns> /// <java-name> /// inheritedChannel /// </java-name> [Dot42.DexImport("inheritedChannel", "()Ljava/nio/channels/Channel;", AccessFlags = 1)] public virtual global::Java.Nio.Channels.IChannel InheritedChannel() /* MethodBuilder.Create */ { return default(global::Java.Nio.Channels.IChannel); } } /// <summary> /// <para><c> AbstractSelector </c> is the base implementation class for selectors. It realizes the interruption of selection by <c> begin </c> and <c> end </c> . It also holds the cancellation and the deletion of the key set. </para> /// </summary> /// <java-name> /// java/nio/channels/spi/AbstractSelector /// </java-name> [Dot42.DexImport("java/nio/channels/spi/AbstractSelector", AccessFlags = 1057)] public abstract partial class AbstractSelector : global::Java.Nio.Channels.Selector /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Ljava/nio/channels/spi/SelectorProvider;)V", AccessFlags = 4)] protected internal AbstractSelector(global::Java.Nio.Channels.Spi.SelectorProvider selectorProvider) /* MethodBuilder.Create */ { } /// <summary> /// <para>Closes this selector. This method does nothing if this selector is already closed. The actual closing must be implemented by subclasses in <c> implCloseSelector() </c> . </para> /// </summary> /// <java-name> /// close /// </java-name> [Dot42.DexImport("close", "()V", AccessFlags = 17)] public override void Close() /* MethodBuilder.Create */ { } /// <summary> /// <para>Implements the closing of this channel. </para> /// </summary> /// <java-name> /// implCloseSelector /// </java-name> [Dot42.DexImport("implCloseSelector", "()V", AccessFlags = 1028)] protected internal abstract void ImplCloseSelector() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns true if this selector is open. </para> /// </summary> /// <java-name> /// isOpen /// </java-name> [Dot42.DexImport("isOpen", "()Z", AccessFlags = 17)] public override bool IsOpen() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Returns this selector's provider. </para> /// </summary> /// <java-name> /// provider /// </java-name> [Dot42.DexImport("provider", "()Ljava/nio/channels/spi/SelectorProvider;", AccessFlags = 17)] public override global::Java.Nio.Channels.Spi.SelectorProvider Provider() /* MethodBuilder.Create */ { return default(global::Java.Nio.Channels.Spi.SelectorProvider); } /// <summary> /// <para>Returns this channel's set of canceled selection keys. </para> /// </summary> /// <java-name> /// cancelledKeys /// </java-name> [Dot42.DexImport("cancelledKeys", "()Ljava/util/Set;", AccessFlags = 20, Signature = "()Ljava/util/Set<Ljava/nio/channels/SelectionKey;>;")] protected internal global::Java.Util.ISet<global::Java.Nio.Channels.SelectionKey> CancelledKeys() /* MethodBuilder.Create */ { return default(global::Java.Util.ISet<global::Java.Nio.Channels.SelectionKey>); } /// <summary> /// <para>Registers <c> channel </c> with this selector.</para><para></para> /// </summary> /// <returns> /// <para>the key related to the channel and this selector. </para> /// </returns> /// <java-name> /// register /// </java-name> [Dot42.DexImport("register", "(Ljava/nio/channels/spi/AbstractSelectableChannel;ILjava/lang/Object;)Ljava/nio/c" + "hannels/SelectionKey;", AccessFlags = 1028)] protected internal abstract global::Java.Nio.Channels.SelectionKey Register(global::Java.Nio.Channels.Spi.AbstractSelectableChannel channel, int operations, object attachment) /* MethodBuilder.Create */ ; /// <summary> /// <para>Deletes the key from the channel's key set. </para> /// </summary> /// <java-name> /// deregister /// </java-name> [Dot42.DexImport("deregister", "(Ljava/nio/channels/spi/AbstractSelectionKey;)V", AccessFlags = 20)] protected internal void Deregister(global::Java.Nio.Channels.Spi.AbstractSelectionKey key) /* MethodBuilder.Create */ { } /// <summary> /// <para>Indicates the beginning of a code section that includes an I/O operation that is potentially blocking. After this operation, the application should invoke the corresponding <c> end(boolean) </c> method. </para> /// </summary> /// <java-name> /// begin /// </java-name> [Dot42.DexImport("begin", "()V", AccessFlags = 20)] protected internal void Begin() /* MethodBuilder.Create */ { } /// <summary> /// <para>Indicates the end of a code section that has been started with <c> begin() </c> and that includes a potentially blocking I/O operation. </para> /// </summary> /// <java-name> /// end /// </java-name> [Dot42.DexImport("end", "()V", AccessFlags = 20)] protected internal void End() /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal AbstractSelector() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para><c> AbstractInterruptibleChannel </c> is the root class for interruptible channels. </para><para>The basic usage pattern for an interruptible channel is to invoke <c> begin() </c> before any I/O operation that potentially blocks indefinitely, then <c> end(boolean) </c> after completing the operation. The argument to the <c> end </c> method should indicate if the I/O operation has actually completed so that any change may be visible to the invoker. </para> /// </summary> /// <java-name> /// java/nio/channels/spi/AbstractInterruptibleChannel /// </java-name> [Dot42.DexImport("java/nio/channels/spi/AbstractInterruptibleChannel", AccessFlags = 1057)] public abstract partial class AbstractInterruptibleChannel : global::Java.Nio.Channels.IChannel, global::Java.Nio.Channels.IInterruptibleChannel /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 4)] protected internal AbstractInterruptibleChannel() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns true if this channel is open. </para> /// </summary> /// <java-name> /// isOpen /// </java-name> [Dot42.DexImport("isOpen", "()Z", AccessFlags = 49)] public bool IsOpen() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Closes an open channel. If the channel is already closed then this method has no effect, otherwise it closes the receiver via the <c> implCloseChannel </c> method. </para><para>If an attempt is made to perform an operation on a closed channel then a java.nio.channels.ClosedChannelException is thrown. </para><para>If multiple threads attempt to simultaneously close a channel, then only one thread will run the closure code and the others will be blocked until the first one completes.</para><para><para>java.nio.channels.Channel::close() </para></para> /// </summary> /// <java-name> /// close /// </java-name> [Dot42.DexImport("close", "()V", AccessFlags = 17)] public void Close() /* MethodBuilder.Create */ { } /// <summary> /// <para>Indicates the beginning of a code section that includes an I/O operation that is potentially blocking. After this operation, the application should invoke the corresponding <c> end(boolean) </c> method. </para> /// </summary> /// <java-name> /// begin /// </java-name> [Dot42.DexImport("begin", "()V", AccessFlags = 20)] protected internal void Begin() /* MethodBuilder.Create */ { } /// <summary> /// <para>Indicates the end of a code section that has been started with <c> begin() </c> and that includes a potentially blocking I/O operation.</para><para></para> /// </summary> /// <java-name> /// end /// </java-name> [Dot42.DexImport("end", "(Z)V", AccessFlags = 20)] protected internal void End(bool success) /* MethodBuilder.Create */ { } /// <summary> /// <para>Implements the channel closing behavior. </para><para>Closes the channel with a guarantee that the channel is not currently closed through another invocation of <c> close() </c> and that the method is thread-safe. </para><para>Any outstanding threads blocked on I/O operations on this channel must be released with either a normal return code, or by throwing an <c> AsynchronousCloseException </c> .</para><para></para> /// </summary> /// <java-name> /// implCloseChannel /// </java-name> [Dot42.DexImport("implCloseChannel", "()V", AccessFlags = 1028)] protected internal abstract void ImplCloseChannel() /* MethodBuilder.Create */ ; } /// <summary> /// <para><c> AbstractSelectionKey </c> is the base implementation class for selection keys. It implements validation and cancellation methods. </para> /// </summary> /// <java-name> /// java/nio/channels/spi/AbstractSelectionKey /// </java-name> [Dot42.DexImport("java/nio/channels/spi/AbstractSelectionKey", AccessFlags = 1057)] public abstract partial class AbstractSelectionKey : global::Java.Nio.Channels.SelectionKey /* scope: __dot42__ */ { /// <summary> /// <para>Constructs a new <c> AbstractSelectionKey </c> . </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 4)] protected internal AbstractSelectionKey() /* MethodBuilder.Create */ { } /// <summary> /// <para>Indicates whether this key is valid. A key is valid as long as it has not been canceled.</para><para></para> /// </summary> /// <returns> /// <para><c> true </c> if this key has not been canceled, <c> false </c> otherwise. </para> /// </returns> /// <java-name> /// isValid /// </java-name> [Dot42.DexImport("isValid", "()Z", AccessFlags = 17)] public override bool IsValid() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Cancels this key. </para><para>A key that has been canceled is no longer valid. Calling this method on an already canceled key does nothing. </para> /// </summary> /// <java-name> /// cancel /// </java-name> [Dot42.DexImport("cancel", "()V", AccessFlags = 17)] public override void Cancel() /* MethodBuilder.Create */ { } } /// <summary> /// <para><c> AbstractSelectableChannel </c> is the base implementation class for selectable channels. It declares methods for registering, unregistering and closing selectable channels. It is thread-safe. </para> /// </summary> /// <java-name> /// java/nio/channels/spi/AbstractSelectableChannel /// </java-name> [Dot42.DexImport("java/nio/channels/spi/AbstractSelectableChannel", AccessFlags = 1057)] public abstract partial class AbstractSelectableChannel : global::Java.Nio.Channels.SelectableChannel /* scope: __dot42__ */ { /// <summary> /// <para>Constructs a new <c> AbstractSelectableChannel </c> .</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/nio/channels/spi/SelectorProvider;)V", AccessFlags = 4)] protected internal AbstractSelectableChannel(global::Java.Nio.Channels.Spi.SelectorProvider selectorProvider) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the selector provider that has created this channel.</para><para><para>java.nio.channels.SelectableChannel::provider() </para></para> /// </summary> /// <returns> /// <para>this channel's selector provider. </para> /// </returns> /// <java-name> /// provider /// </java-name> [Dot42.DexImport("provider", "()Ljava/nio/channels/spi/SelectorProvider;", AccessFlags = 17)] public override global::Java.Nio.Channels.Spi.SelectorProvider Provider() /* MethodBuilder.Create */ { return default(global::Java.Nio.Channels.Spi.SelectorProvider); } /// <summary> /// <para>Indicates whether this channel is registered with one or more selectors.</para><para></para> /// </summary> /// <returns> /// <para><c> true </c> if this channel is registered with a selector, <c> false </c> otherwise. </para> /// </returns> /// <java-name> /// isRegistered /// </java-name> [Dot42.DexImport("isRegistered", "()Z", AccessFlags = 49)] public override bool IsRegistered() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Gets this channel's selection key for the specified selector.</para><para></para> /// </summary> /// <returns> /// <para>the selection key for the channel or <c> null </c> if this channel has not been registered with <c> selector </c> . </para> /// </returns> /// <java-name> /// keyFor /// </java-name> [Dot42.DexImport("keyFor", "(Ljava/nio/channels/Selector;)Ljava/nio/channels/SelectionKey;", AccessFlags = 49)] public override global::Java.Nio.Channels.SelectionKey KeyFor(global::Java.Nio.Channels.Selector selector) /* MethodBuilder.Create */ { return default(global::Java.Nio.Channels.SelectionKey); } /// <summary> /// <para>Registers this channel with the specified selector for the specified interest set. If the channel is already registered with the selector, the interest set is updated to <c> interestSet </c> and the corresponding selection key is returned. If the channel is not yet registered, this method calls the <c> register </c> method of <c> selector </c> and adds the selection key to this channel's key set.</para><para></para> /// </summary> /// <returns> /// <para>the selection key for this registration. </para> /// </returns> /// <java-name> /// register /// </java-name> [Dot42.DexImport("register", "(Ljava/nio/channels/Selector;ILjava/lang/Object;)Ljava/nio/channels/SelectionKey;" + "", AccessFlags = 17)] public override global::Java.Nio.Channels.SelectionKey Register(global::Java.Nio.Channels.Selector selector, int interestSet, object attachment) /* MethodBuilder.Create */ { return default(global::Java.Nio.Channels.SelectionKey); } /// <summary> /// <para>Implements the channel closing behavior. Calls <c> implCloseSelectableChannel() </c> first, then loops through the list of selection keys and cancels them, which unregisters this channel from all selectors it is registered with.</para><para></para> /// </summary> /// <java-name> /// implCloseChannel /// </java-name> [Dot42.DexImport("implCloseChannel", "()V", AccessFlags = 52)] protected internal override void ImplCloseChannel() /* MethodBuilder.Create */ { } /// <summary> /// <para>Implements the closing function of the SelectableChannel. This method is called from <c> implCloseChannel() </c> .</para><para></para> /// </summary> /// <java-name> /// implCloseSelectableChannel /// </java-name> [Dot42.DexImport("implCloseSelectableChannel", "()V", AccessFlags = 1028)] protected internal abstract void ImplCloseSelectableChannel() /* MethodBuilder.Create */ ; /// <summary> /// <para>Indicates whether this channel is in blocking mode.</para><para></para> /// </summary> /// <returns> /// <para><c> true </c> if this channel is blocking, <c> false </c> otherwise. </para> /// </returns> /// <java-name> /// isBlocking /// </java-name> [Dot42.DexImport("isBlocking", "()Z", AccessFlags = 17)] public override bool IsBlocking() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Gets the object used for the synchronization of <c> register </c> and <c> configureBlocking </c> .</para><para></para> /// </summary> /// <returns> /// <para>the synchronization object. </para> /// </returns> /// <java-name> /// blockingLock /// </java-name> [Dot42.DexImport("blockingLock", "()Ljava/lang/Object;", AccessFlags = 17)] public override object BlockingLock() /* MethodBuilder.Create */ { return default(object); } /// <summary> /// <para>Sets the blocking mode of this channel. A call to this method blocks if other calls to this method or to <c> register </c> are executing. The actual setting of the mode is done by calling <c> implConfigureBlocking(boolean) </c> .</para><para><para>java.nio.channels.SelectableChannel::configureBlocking(boolean) </para></para> /// </summary> /// <returns> /// <para>this channel. </para> /// </returns> /// <java-name> /// configureBlocking /// </java-name> [Dot42.DexImport("configureBlocking", "(Z)Ljava/nio/channels/SelectableChannel;", AccessFlags = 17)] public override global::Java.Nio.Channels.SelectableChannel ConfigureBlocking(bool blockingMode) /* MethodBuilder.Create */ { return default(global::Java.Nio.Channels.SelectableChannel); } /// <summary> /// <para>Implements the configuration of blocking/non-blocking mode.</para><para></para> /// </summary> /// <java-name> /// implConfigureBlocking /// </java-name> [Dot42.DexImport("implConfigureBlocking", "(Z)V", AccessFlags = 1028)] protected internal abstract void ImplConfigureBlocking(bool blocking) /* MethodBuilder.Create */ ; [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal AbstractSelectableChannel() /* TypeBuilder.AddDefaultConstructor */ { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Orleans; using Orleans.Messaging; using Orleans.Runtime; using Orleans.TestingHost.Utils; using TestExtensions; using Xunit; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.Internal; namespace UnitTests.MembershipTests { internal static class SiloInstanceTableTestConstants { internal static readonly TimeSpan Timeout = TimeSpan.FromMinutes(1); internal static readonly bool DeleteEntriesAfterTest = true; // false; // Set to false for Debug mode internal static readonly string INSTANCE_STATUS_CREATED = SiloStatus.Created.ToString(); //"Created"; internal static readonly string INSTANCE_STATUS_ACTIVE = SiloStatus.Active.ToString(); //"Active"; internal static readonly string INSTANCE_STATUS_DEAD = SiloStatus.Dead.ToString(); //"Dead"; } [Collection(TestEnvironmentFixture.DefaultCollection)] public abstract class MembershipTableTestsBase : IDisposable, IClassFixture<ConnectionStringFixture> { private readonly TestEnvironmentFixture environment; private static readonly string hostName = Dns.GetHostName(); private readonly ILogger logger; private readonly IMembershipTable membershipTable; private readonly IGatewayListProvider gatewayListProvider; protected readonly string clusterId; protected readonly string connectionString; protected ILoggerFactory loggerFactory; protected IOptions<SiloOptions> siloOptions; protected IOptions<ClusterOptions> clusterOptions; protected const string testDatabaseName = "OrleansMembershipTest";//for relational storage protected readonly IOptions<GatewayOptions> gatewayOptions; protected MembershipTableTestsBase(ConnectionStringFixture fixture, TestEnvironmentFixture environment, LoggerFilterOptions filters) { this.environment = environment; loggerFactory = TestingUtils.CreateDefaultLoggerFactory($"{this.GetType()}.log", filters); logger = loggerFactory.CreateLogger(this.GetType().FullName); this.clusterId = "test-" + Guid.NewGuid(); logger.Info("ClusterId={0}", this.clusterId); fixture.InitializeConnectionStringAccessor(GetConnectionString); this.connectionString = fixture.ConnectionString; this.clusterOptions = Options.Create(new ClusterOptions { ClusterId = this.clusterId }); var adoVariant = GetAdoInvariant(); membershipTable = CreateMembershipTable(logger); membershipTable.InitializeMembershipTable(true).WithTimeout(TimeSpan.FromMinutes(1)).Wait(); this.gatewayOptions = Options.Create(new GatewayOptions()); gatewayListProvider = CreateGatewayListProvider(logger); gatewayListProvider.InitializeGatewayListProvider().WithTimeout(TimeSpan.FromMinutes(1)).Wait(); } public IGrainFactory GrainFactory => this.environment.GrainFactory; public IGrainReferenceConverter GrainReferenceConverter => this.environment.Services.GetRequiredService<IGrainReferenceConverter>(); public IServiceProvider Services => this.environment.Services; public void Dispose() { if (membershipTable != null && SiloInstanceTableTestConstants.DeleteEntriesAfterTest) { membershipTable.DeleteMembershipTableEntries(this.clusterId).Wait(); } this.loggerFactory.Dispose(); } protected abstract IGatewayListProvider CreateGatewayListProvider(ILogger logger); protected abstract IMembershipTable CreateMembershipTable(ILogger logger); protected abstract Task<string> GetConnectionString(); protected virtual string GetAdoInvariant() { return null; } protected async Task MembershipTable_GetGateways() { var membershipEntries = Enumerable.Range(0, 10).Select(i => CreateMembershipEntryForTest()).ToArray(); membershipEntries[3].Status = SiloStatus.Active; membershipEntries[3].ProxyPort = 0; membershipEntries[5].Status = SiloStatus.Active; membershipEntries[9].Status = SiloStatus.Active; var data = await membershipTable.ReadAll(); Assert.NotNull(data); Assert.Equal(0, data.Members.Count); var version = data.Version; foreach (var membershipEntry in membershipEntries) { Assert.True(await membershipTable.InsertRow(membershipEntry, version)); version = (await membershipTable.ReadRow(membershipEntry.SiloAddress)).Version; } var gateways = await gatewayListProvider.GetGateways(); var entries = new List<string>(gateways.Select(g => g.ToString())); // only members with a non-zero Gateway port Assert.DoesNotContain(membershipEntries[3].SiloAddress.ToGatewayUri().ToString(), entries); // only Active members Assert.Contains(membershipEntries[5].SiloAddress.ToGatewayUri().ToString(), entries); Assert.Contains(membershipEntries[9].SiloAddress.ToGatewayUri().ToString(), entries); Assert.Equal(2, entries.Count); } protected async Task MembershipTable_ReadAll_EmptyTable() { var data = await membershipTable.ReadAll(); Assert.NotNull(data); logger.Info("Membership.ReadAll returned VableVersion={0} Data={1}", data.Version, data); Assert.Equal(0, data.Members.Count); Assert.NotNull(data.Version.VersionEtag); Assert.Equal(0, data.Version.Version); } protected async Task MembershipTable_InsertRow(bool extendedProtocol = true) { var membershipEntry = CreateMembershipEntryForTest(); var data = await membershipTable.ReadAll(); Assert.NotNull(data); Assert.Equal(0, data.Members.Count); TableVersion nextTableVersion = data.Version.Next(); bool ok = await membershipTable.InsertRow(membershipEntry, nextTableVersion); Assert.True(ok, "InsertRow failed"); data = await membershipTable.ReadAll(); if (extendedProtocol) Assert.Equal(1, data.Version.Version); Assert.Equal(1, data.Members.Count); } protected async Task MembershipTable_ReadRow_Insert_Read(bool extendedProtocol = true) { MembershipTableData data = await membershipTable.ReadAll(); logger.Info("Membership.ReadAll returned VableVersion={0} Data={1}", data.Version, data); Assert.Equal(0, data.Members.Count); TableVersion newTableVersion = data.Version.Next(); MembershipEntry newEntry = CreateMembershipEntryForTest(); bool ok = await membershipTable.InsertRow(newEntry, newTableVersion); Assert.True(ok, "InsertRow failed"); ok = await membershipTable.InsertRow(newEntry, newTableVersion); Assert.False(ok, "InsertRow should have failed - same entry, old table version"); if (extendedProtocol) { ok = await membershipTable.InsertRow(CreateMembershipEntryForTest(), newTableVersion); Assert.False(ok, "InsertRow should have failed - new entry, old table version"); } data = await membershipTable.ReadAll(); if (extendedProtocol) Assert.Equal(1, data.Version.Version); TableVersion nextTableVersion = data.Version.Next(); ok = await membershipTable.InsertRow(newEntry, nextTableVersion); Assert.False(ok, "InsertRow should have failed - duplicate entry"); data = await membershipTable.ReadAll(); Assert.Equal(1, data.Members.Count); data = await membershipTable.ReadRow(newEntry.SiloAddress); if (extendedProtocol) Assert.Equal(newTableVersion.Version, data.Version.Version); logger.Info("Membership.ReadRow returned VableVersion={0} Data={1}", data.Version, data); Assert.Equal(1, data.Members.Count); Assert.NotNull(data.Version.VersionEtag); if (extendedProtocol) { Assert.NotEqual(newTableVersion.VersionEtag, data.Version.VersionEtag); Assert.Equal(newTableVersion.Version, data.Version.Version); } var membershipEntry = data.Members[0].Item1; string eTag = data.Members[0].Item2; logger.Info("Membership.ReadRow returned MembershipEntry ETag={0} Entry={1}", eTag, membershipEntry); Assert.NotNull(eTag); Assert.NotNull(membershipEntry); } protected async Task MembershipTable_ReadAll_Insert_ReadAll(bool extendedProtocol = true) { MembershipTableData data = await membershipTable.ReadAll(); logger.Info("Membership.ReadAll returned VableVersion={0} Data={1}", data.Version, data); Assert.Equal(0, data.Members.Count); TableVersion newTableVersion = data.Version.Next(); MembershipEntry newEntry = CreateMembershipEntryForTest(); bool ok = await membershipTable.InsertRow(newEntry, newTableVersion); Assert.True(ok, "InsertRow failed"); data = await membershipTable.ReadAll(); logger.Info("Membership.ReadAll returned VableVersion={0} Data={1}", data.Version, data); Assert.Equal(1, data.Members.Count); Assert.NotNull(data.Version.VersionEtag); if (extendedProtocol) { Assert.NotEqual(newTableVersion.VersionEtag, data.Version.VersionEtag); Assert.Equal(newTableVersion.Version, data.Version.Version); } var membershipEntry = data.Members[0].Item1; string eTag = data.Members[0].Item2; logger.Info("Membership.ReadAll returned MembershipEntry ETag={0} Entry={1}", eTag, membershipEntry); Assert.NotNull(eTag); Assert.NotNull(membershipEntry); } protected async Task MembershipTable_UpdateRow(bool extendedProtocol = true) { var tableData = await membershipTable.ReadAll(); Assert.NotNull(tableData.Version); Assert.Equal(0, tableData.Version.Version); Assert.Equal(0, tableData.Members.Count); for (int i = 1; i < 10; i++) { var siloEntry = CreateMembershipEntryForTest(); siloEntry.SuspectTimes = new List<Tuple<SiloAddress, DateTime>> { new Tuple<SiloAddress, DateTime>(CreateSiloAddressForTest(), GetUtcNowWithSecondsResolution().AddSeconds(1)), new Tuple<SiloAddress, DateTime>(CreateSiloAddressForTest(), GetUtcNowWithSecondsResolution().AddSeconds(2)) }; TableVersion tableVersion = tableData.Version.Next(); logger.Info("Calling InsertRow with Entry = {0} TableVersion = {1}", siloEntry, tableVersion); bool ok = await membershipTable.InsertRow(siloEntry, tableVersion); Assert.True(ok, "InsertRow failed"); tableData = await membershipTable.ReadAll(); var etagBefore = tableData.Get(siloEntry.SiloAddress).Item2; Assert.NotNull(etagBefore); if (extendedProtocol) { logger.Info("Calling UpdateRow with Entry = {0} correct eTag = {1} old version={2}", siloEntry, etagBefore, tableVersion != null ? tableVersion.ToString() : "null"); ok = await membershipTable.UpdateRow(siloEntry, etagBefore, tableVersion); Assert.False(ok, $"row update should have failed - Table Data = {tableData}"); tableData = await membershipTable.ReadAll(); } tableVersion = tableData.Version.Next(); logger.Info("Calling UpdateRow with Entry = {0} correct eTag = {1} correct version={2}", siloEntry, etagBefore, tableVersion != null ? tableVersion.ToString() : "null"); ok = await membershipTable.UpdateRow(siloEntry, etagBefore, tableVersion); Assert.True(ok, $"UpdateRow failed - Table Data = {tableData}"); logger.Info("Calling UpdateRow with Entry = {0} old eTag = {1} old version={2}", siloEntry, etagBefore, tableVersion != null ? tableVersion.ToString() : "null"); ok = await membershipTable.UpdateRow(siloEntry, etagBefore, tableVersion); Assert.False(ok, $"row update should have failed - Table Data = {tableData}"); tableData = await membershipTable.ReadAll(); var tuple = tableData.Get(siloEntry.SiloAddress); Assert.Equal(tuple.Item1.ToFullString(true), siloEntry.ToFullString(true)); var etagAfter = tuple.Item2; if (extendedProtocol) { logger.Info("Calling UpdateRow with Entry = {0} correct eTag = {1} old version={2}", siloEntry, etagAfter, tableVersion != null ? tableVersion.ToString() : "null"); ok = await membershipTable.UpdateRow(siloEntry, etagAfter, tableVersion); Assert.False(ok, $"row update should have failed - Table Data = {tableData}"); } tableData = await membershipTable.ReadAll(); etagBefore = etagAfter; etagAfter = tableData.Get(siloEntry.SiloAddress).Item2; Assert.Equal(etagBefore, etagAfter); Assert.NotNull(tableData.Version); if (extendedProtocol) Assert.Equal(tableVersion.Version, tableData.Version.Version); Assert.Equal(i, tableData.Members.Count); } } protected async Task MembershipTable_UpdateRowInParallel(bool extendedProtocol = true) { var tableData = await membershipTable.ReadAll(); var data = CreateMembershipEntryForTest(); TableVersion newTableVer = tableData.Version.Next(); var insertions = Task.WhenAll(Enumerable.Range(1, 20).Select(async i => { try { return await membershipTable.InsertRow(data, newTableVer); } catch { return false; } })); Assert.True((await insertions).Single(x => x), "InsertRow failed"); await Task.WhenAll(Enumerable.Range(1, 19).Select(async i => { bool done; do { var updatedTableData = await membershipTable.ReadAll(); var updatedRow = updatedTableData.Get(data.SiloAddress); TableVersion tableVersion = updatedTableData.Version.Next(); await Task.Delay(10); try { done = await membershipTable.UpdateRow(updatedRow.Item1, updatedRow.Item2, tableVersion); } catch { done = false; } } while (!done); })).WithTimeout(TimeSpan.FromSeconds(30)); tableData = await membershipTable.ReadAll(); Assert.NotNull(tableData.Version); if (extendedProtocol) Assert.Equal(20, tableData.Version.Version); Assert.Equal(1, tableData.Members.Count); } protected async Task MembershipTable_UpdateIAmAlive(bool extendedProtocol = true) { MembershipTableData tableData = await membershipTable.ReadAll(); TableVersion newTableVersion = tableData.Version.Next(); MembershipEntry newEntry = CreateMembershipEntryForTest(); bool ok = await membershipTable.InsertRow(newEntry, newTableVersion); Assert.True(ok); var amAliveTime = DateTime.UtcNow; // This mimics the arguments MembershipOracle.OnIAmAliveUpdateInTableTimer passes in var entry = new MembershipEntry { SiloAddress = newEntry.SiloAddress, IAmAliveTime = amAliveTime }; await membershipTable.UpdateIAmAlive(entry); tableData = await membershipTable.ReadAll(); Tuple<MembershipEntry, string> member = tableData.Members.First(); // compare that the value is close to what we passed in, but not exactly, as the underlying store can set its own precision settings // (ie: in SQL Server this is defined as datetime2(3), so we don't expect precision to account for less than 0.001s values) Assert.True((amAliveTime - member.Item1.IAmAliveTime).Duration() < TimeSpan.FromMilliseconds(50), (amAliveTime - member.Item1.IAmAliveTime).Duration().ToString()); } protected async Task MembershipTable_CleanupDefunctSiloEntries(bool extendedProtocol = true) { MembershipTableData data = await membershipTable.ReadAll(); logger.Info("Membership.ReadAll returned VableVersion={0} Data={1}", data.Version, data); Assert.Equal(0, data.Members.Count); TableVersion newTableVersion = data.Version.Next(); MembershipEntry oldEntry = CreateMembershipEntryForTest(); oldEntry.IAmAliveTime = oldEntry.IAmAliveTime.AddDays(-10); oldEntry.StartTime = oldEntry.StartTime.AddDays(-10); bool ok = await membershipTable.InsertRow(oldEntry, newTableVersion); Assert.True(ok, "InsertRow failed"); newTableVersion = newTableVersion.Next(); MembershipEntry newEntry = CreateMembershipEntryForTest(); ok = await membershipTable.InsertRow(newEntry, newTableVersion); Assert.True(ok, "InsertRow failed"); data = await membershipTable.ReadAll(); logger.Info("Membership.ReadAll returned VableVersion={0} Data={1}", data.Version, data); Assert.Equal(2, data.Members.Count); await membershipTable.CleanupDefunctSiloEntries(oldEntry.IAmAliveTime.AddDays(3)); data = await membershipTable.ReadAll(); logger.Info("Membership.ReadAll returned VableVersion={0} Data={1}", data.Version, data); Assert.Equal(1, data.Members.Count); } private static int generation; // Utility methods private static MembershipEntry CreateMembershipEntryForTest() { SiloAddress siloAddress = CreateSiloAddressForTest(); var membershipEntry = new MembershipEntry { SiloAddress = siloAddress, HostName = hostName, SiloName = "TestSiloName", Status = SiloStatus.Joining, ProxyPort = siloAddress.Endpoint.Port, StartTime = GetUtcNowWithSecondsResolution(), IAmAliveTime = GetUtcNowWithSecondsResolution() }; return membershipEntry; } private static DateTime GetUtcNowWithSecondsResolution() { var now = DateTime.UtcNow; return new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, DateTimeKind.Utc); } private static SiloAddress CreateSiloAddressForTest() { var siloAddress = SiloAddressUtils.NewLocalSiloAddress(Interlocked.Increment(ref generation)); siloAddress.Endpoint.Port = 12345; return siloAddress; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Security.Principal; using System.Text; using Htc.Vita.Core.Log; namespace Htc.Vita.Core.Runtime { public static partial class ProcessManager { internal static class Windows { internal static List<WindowsProcessInfo> GetPlatformProcesses(string serverName) { var machineName = serverName; if (string.IsNullOrWhiteSpace(machineName)) { machineName = Environment.MachineName; } var result = new List<WindowsProcessInfo>(); using (var serverHandle = Interop.Windows.WTSOpenServerW(machineName)) { if (serverHandle == null || serverHandle.IsInvalid) { return result; } try { var processInfoPtr = IntPtr.Zero; var processCount = 0U; var success = Interop.Windows.WTSEnumerateProcessesW( serverHandle, 0, 1, ref processInfoPtr, ref processCount ); var dataSize = Marshal.SizeOf(typeof(Interop.Windows.WindowsTerminalServiceProcessInfo)); var currentProcessInfoPtr = processInfoPtr; if (success) { for (var processIndex = 0; processIndex < processCount; processIndex++) { var processInfo = (Interop.Windows.WindowsTerminalServiceProcessInfo)Marshal.PtrToStructure( currentProcessInfoPtr, typeof(Interop.Windows.WindowsTerminalServiceProcessInfo) ); currentProcessInfoPtr += dataSize; var userSid = string.Empty; success = Interop.Windows.ConvertSidToStringSidW(processInfo.pUserSid, ref userSid); if (!success) { userSid = string.Empty; } var windowsProcessInfo = new WindowsProcessInfo { Id = (int)processInfo.processId, Name = processInfo.pProcessName, SessionId = (int)processInfo.sessionId, UserSid = userSid }; result.Add(windowsProcessInfo); } Interop.Windows.WTSFreeMemory(processInfoPtr); } } catch (Exception e) { Logger.GetInstance(typeof(Windows)).Error("Can not get Windows process list: " + e.Message); } return result; } } internal static string GetPlatformProcessPathById(int processId) { try { using (var clientProcess = Process.GetProcessById(processId)) { try { return clientProcess.MainModule?.FileName; } catch (Win32Exception) { using (var processHandle = new Interop.Windows.SafeProcessHandle(clientProcess, false)) { var bufferSize = 256; while (true) { var fullPath = new StringBuilder(bufferSize); var success = Interop.Windows.QueryFullProcessImageNameW( processHandle, 0, fullPath, ref bufferSize ); if (success) { return fullPath.ToString(0, bufferSize); } var win32Error = Marshal.GetLastWin32Error(); if (win32Error != (int) Interop.Windows.Error.InsufficientBuffer) { Logger.GetInstance(typeof(Windows)).Error($"Can not get Windows process path from Process by id: {processId}, error code: {win32Error}"); break; } if (bufferSize > 1024 * 30) { Logger.GetInstance(typeof(Windows)).Error($"Can not get Windows process path under length of {bufferSize}"); break; } bufferSize *= 2; } return null; } } } } catch (ArgumentException) { // skip } catch (Win32Exception) { using (var processHandle = Interop.Windows.OpenProcess(Interop.Windows.ProcessAccessRights.QueryLimitedInformation, false, (uint) processId)) { var bufferSize = 256; while (true) { var fullPath = new StringBuilder(bufferSize); var success = Interop.Windows.QueryFullProcessImageNameW( processHandle, 0, fullPath, ref bufferSize ); if (success) { return fullPath.ToString(0, bufferSize); } var win32Error = Marshal.GetLastWin32Error(); if (win32Error == (int)Interop.Windows.Error.InvalidHandle) { Logger.GetInstance(typeof(Windows)).Debug($"Can not get Windows process path with valid handle by id: {processId}"); break; } if (win32Error != (int)Interop.Windows.Error.InsufficientBuffer) { Logger.GetInstance(typeof(Windows)).Error($"Can not get Windows process path from process handle by id: {processId}, error code: {win32Error}"); break; } if (bufferSize > 1024 * 30) { Logger.GetInstance(typeof(Windows)).Error($"Can not get Windows process path under length of {bufferSize}"); break; } bufferSize *= 2; } return null; } } return null; } internal static bool IsCurrentUserProcessInPlatform(Process process) { var tokenInformation = IntPtr.Zero; try { string currentUserSid; #pragma warning disable CA1416 using (var windowsIdentity = WindowsIdentity.GetCurrent()) { currentUserSid = windowsIdentity.User?.ToString() ?? string.Empty; } #pragma warning restore CA1416 if (string.IsNullOrWhiteSpace(currentUserSid)) { Logger.GetInstance(typeof(Windows)).Error("Can not get current user sid"); return false; } using (var processHandle = new Interop.Windows.SafeProcessHandle(process, false)) { Interop.Windows.SafeTokenHandle tokenHandle; var success = Interop.Windows.OpenProcessToken( processHandle, Interop.Windows.TokenAccessRights.Query | Interop.Windows.TokenAccessRights.Duplicate, out tokenHandle ); if (!success) { Logger.GetInstance(typeof(Windows)).Error($"Can not open process token. error code: {Marshal.GetLastWin32Error()}"); } var tokenInformationSize = 0U; success = Interop.Windows.GetTokenInformation( tokenHandle, Interop.Windows.TokenInformationClass.User, tokenInformation, tokenInformationSize, out tokenInformationSize ); if (!success) { var win32Error = Marshal.GetLastWin32Error(); if (win32Error != (int) Interop.Windows.Error.InsufficientBuffer) { Logger.GetInstance(typeof(Windows)).Error($"Can not get process token information size. error code: {win32Error}"); return false; } } tokenInformation = Marshal.AllocHGlobal((int) tokenInformationSize); success = Interop.Windows.GetTokenInformation( tokenHandle, Interop.Windows.TokenInformationClass.User, tokenInformation, tokenInformationSize, out tokenInformationSize ); if (!success) { Logger.GetInstance(typeof(Windows)).Error($"Can not get process token information. error code: {Marshal.GetLastWin32Error()}"); return false; } var tokenUser = (Interop.Windows.TokenUser) Marshal.PtrToStructure( tokenInformation, typeof(Interop.Windows.TokenUser) ); var processUserSid = string.Empty; success = Interop.Windows.ConvertSidToStringSidW(tokenUser.User.Sid, ref processUserSid); if (!success) { Logger.GetInstance(typeof(Windows)).Error($"Can not convert sid to string sid, error code: {Marshal.GetLastWin32Error()}"); return false; } if (currentUserSid.Equals(processUserSid)) { return true; } Logger.GetInstance(typeof(Windows)).Debug($"Process user SID: [{processUserSid}] is different from current user SID: [{currentUserSid}]"); return false; } } catch (Exception e) { Logger.GetInstance(typeof(Windows)).Error($"Can not check if process is running under current user. {e.Message}"); } finally { if (tokenInformation != IntPtr.Zero) { Marshal.FreeHGlobal(tokenInformation); } } return false; } internal static bool IsElevatedProcessInPlatform(Process process) { var tokenInformation = IntPtr.Zero; try { using (var processHandle = new Interop.Windows.SafeProcessHandle(process, false)) { Interop.Windows.SafeTokenHandle tokenHandle; var success = Interop.Windows.OpenProcessToken( processHandle, Interop.Windows.TokenAccessRights.Query, out tokenHandle ); if (!success) { Logger.GetInstance(typeof(Windows)).Error($"Can not open process token. error code: {Marshal.GetLastWin32Error()}"); } var tokenInformationSize = 0U; success = Interop.Windows.GetTokenInformation( tokenHandle, Interop.Windows.TokenInformationClass.Elevation, tokenInformation, tokenInformationSize, out tokenInformationSize ); if (!success) { var win32Error = Marshal.GetLastWin32Error(); if (win32Error != (int)Interop.Windows.Error.BadLength && win32Error != (int)Interop.Windows.Error.InsufficientBuffer) { Logger.GetInstance(typeof(Windows)).Error($"Can not get process token information size. error code: {win32Error}."); return false; } } tokenInformation = Marshal.AllocHGlobal((int)tokenInformationSize); success = Interop.Windows.GetTokenInformation( tokenHandle, Interop.Windows.TokenInformationClass.Elevation, tokenInformation, tokenInformationSize, out tokenInformationSize ); if (!success) { Logger.GetInstance(typeof(Windows)).Error($"Can not get process token information. error code: {Marshal.GetLastWin32Error()}"); return false; } var tokenElevation = (Interop.Windows.TokenElevation)Marshal.PtrToStructure( tokenInformation, typeof(Interop.Windows.TokenElevation) ); return tokenElevation.TokenIsElevated != 0; } } catch (Exception e) { Logger.GetInstance(typeof(Windows)).Error($"Can not check if process is elevated. {e.Message}"); } finally { if (tokenInformation != IntPtr.Zero) { Marshal.FreeHGlobal(tokenInformation); } } return false; } internal static bool KillPlatformProcessById(int processId) { return KillPlatformProcessById(processId, null); } internal static bool KillPlatformProcessById(int processId, string serverName) { var machineName = serverName; if (string.IsNullOrWhiteSpace(machineName)) { machineName = Environment.MachineName; } var result = false; using (var serverHandle = Interop.Windows.WTSOpenServerW(machineName)) { if (serverHandle == null || serverHandle.IsInvalid) { return false; } try { result = Interop.Windows.WTSTerminateProcess( serverHandle, (uint)processId, 0 ); } catch (Exception e) { Logger.GetInstance(typeof(Windows)).Error("Can not kill Windows process by id: " + processId + ", " + e.Message); } return result; } } internal static ProcessInfo LaunchProcessAsShellUserInPlatform( string fileName, string arguments) { if (!IsElevatedProcess(Process.GetCurrentProcess())) { Logger.GetInstance(typeof(Windows)).Error("This API should be invoked by elevated user process"); return null; } var shellWindowHandle = Interop.Windows.GetShellWindow(); if (shellWindowHandle == IntPtr.Zero) { Logger.GetInstance(typeof(Windows)).Error($"Can not get shell window handle, error code: {Marshal.GetLastWin32Error()}"); return null; } try { var shellWindowProcessId = 0U; Interop.Windows.GetWindowThreadProcessId( shellWindowHandle, ref shellWindowProcessId ); if (shellWindowProcessId == 0) { Logger.GetInstance(typeof(Windows)).Error($"Can not get shell window process id, error code: {Marshal.GetLastWin32Error()}"); return null; } using (var shellWindowProcess = Process.GetProcessById((int) shellWindowProcessId)) { using (var processHandle = new Interop.Windows.SafeProcessHandle(shellWindowProcess, false)) { Interop.Windows.SafeTokenHandle tokenHandle; var success = Interop.Windows.OpenProcessToken( processHandle, Interop.Windows.TokenAccessRights.Duplicate, out tokenHandle ); if (!success) { Logger.GetInstance(typeof(Windows)).Error($"Can not open process token. error code: {Marshal.GetLastWin32Error()}"); return null; } Interop.Windows.SafeTokenHandle newTokenHandle; var securityAttributes = new Interop.Windows.SecurityAttributes(); securityAttributes.nLength = Marshal.SizeOf(securityAttributes); var tokenAccess = Interop.Windows.TokenAccessRights.AdjustDefault | Interop.Windows.TokenAccessRights.AssignPrimary | Interop.Windows.TokenAccessRights.AdjustSessionId | Interop.Windows.TokenAccessRights.Duplicate | Interop.Windows.TokenAccessRights.Query; success = Interop.Windows.DuplicateTokenEx( tokenHandle, tokenAccess, securityAttributes, Interop.Windows.SecurityImpersonationLevel.SecurityImpersonation, Interop.Windows.TokenType.TokenPrimary, out newTokenHandle ); if (!success) { Logger.GetInstance(typeof(Windows)).Error($"Can not duplicate token, error code: {Marshal.GetLastWin32Error()}"); return null; } var commandLine = $"\"{fileName}\" {arguments}"; var startupInfo = new Interop.Windows.StartupInfo(); startupInfo.cb = Marshal.SizeOf(startupInfo); Interop.Windows.ProcessInformation processInformation; success = Interop.Windows.CreateProcessWithTokenW( newTokenHandle, Interop.Windows.LogonFlag.None, fileName, commandLine, Interop.Windows.ProcessCreationFlags.CreateUnicodeEnvironment, IntPtr.Zero, Path.GetDirectoryName(fileName), ref startupInfo, out processInformation ); if (!success) { Logger.GetInstance(typeof(Windows)).Error($"Can not create process as shell user, error code: {Marshal.GetLastWin32Error()}"); return null; } var processId = processInformation.dwProcessID; var processPath = GetPlatformProcessPathById(processId); string processName; using (var process = Process.GetProcessById(processId)) { processName = process.ProcessName; } return new ProcessInfo { Id = processId, Name = processName, Path = processPath }; } } } catch (Exception e) { Logger.GetInstance(typeof(Windows)).Error($"Can not launch process as user: {e}"); } finally { if (shellWindowHandle != IntPtr.Zero) { Interop.Windows.CloseHandle(shellWindowHandle); } } return null; } internal static ProcessInfo LaunchProcessAsUserInPlatform( string fileName, string arguments) { var machineName = Environment.MachineName; using (var serverHandle = Interop.Windows.WTSOpenServerW(machineName)) { if (serverHandle == null || serverHandle.IsInvalid) { return null; } var sessionInfoPtr = IntPtr.Zero; try { var sessionCount = 0U; var success = Interop.Windows.WTSEnumerateSessionsW( serverHandle, 0, 1, ref sessionInfoPtr, ref sessionCount ); if (!success) { Logger.GetInstance(typeof(Windows)).Error($"Can not enumerate WTS session, error code: {Marshal.GetLastWin32Error()}"); return null; } if (sessionCount <= 0U) { Logger.GetInstance(typeof(Windows)).Error("Can not find available WTS session"); return null; } var currentSessionInfoPtr = sessionInfoPtr; var dataSize = Marshal.SizeOf(typeof(Interop.Windows.WindowsTerminalServiceSessionInfo)); for (var sessionIndex = 0U; sessionIndex < sessionCount; sessionIndex++) { var sessionInfo = (Interop.Windows.WindowsTerminalServiceSessionInfo)Marshal.PtrToStructure( currentSessionInfoPtr, typeof(Interop.Windows.WindowsTerminalServiceSessionInfo) ); currentSessionInfoPtr += dataSize; if (sessionInfo.state != Interop.Windows.WindowsTerminalServiceConnectState.Active) { continue; } Interop.Windows.SafeTokenHandle tokenHandle; success = Interop.Windows.WTSQueryUserToken( sessionInfo.sessionId, out tokenHandle ); if (!success) { Logger.GetInstance(typeof(Windows)).Error($"Can not query user token, error code: {Marshal.GetLastWin32Error()}"); continue; } Interop.Windows.SafeTokenHandle newTokenHandle; var securityAttributes = new Interop.Windows.SecurityAttributes(); securityAttributes.nLength = Marshal.SizeOf(securityAttributes); success = Interop.Windows.DuplicateTokenEx( tokenHandle, Interop.Windows.TokenAccessRights.AllAccess, securityAttributes, Interop.Windows.SecurityImpersonationLevel.SecurityImpersonation, Interop.Windows.TokenType.TokenPrimary, out newTokenHandle ); if (!success) { Logger.GetInstance(typeof(Windows)).Error($"Can not duplicate token, error code: {Marshal.GetLastWin32Error()}"); continue; } var tokenInformation = IntPtr.Zero; var tokenInformationSize = 0U; success = Interop.Windows.GetTokenInformation( newTokenHandle, Interop.Windows.TokenInformationClass.LinkedToken, tokenInformation, tokenInformationSize, out tokenInformationSize ); if (!success) { var lastWin32Error = Marshal.GetLastWin32Error(); if (lastWin32Error == (int)Interop.Windows.Error.NoSuchLogonSession) { Logger.GetInstance(typeof(Windows)).Info($"UAC has been disabled, error code: {lastWin32Error}"); } else if (lastWin32Error != (int) Interop.Windows.Error.BadLength) { Logger.GetInstance(typeof(Windows)).Error($"Can not get token information, error code: {lastWin32Error}"); } success = Interop.Windows.GetTokenInformation( newTokenHandle, Interop.Windows.TokenInformationClass.LinkedToken, tokenInformation, tokenInformationSize, out tokenInformationSize ); if (!success) { lastWin32Error = Marshal.GetLastWin32Error(); Logger.GetInstance(typeof(Windows)).Error($"Can not get token information again, error code: {lastWin32Error}"); } } IntPtr environmentPtr; success = Interop.Windows.CreateEnvironmentBlock( out environmentPtr, newTokenHandle, false ); if (!success) { Logger.GetInstance(typeof(Windows)).Error($"Can not create environment block, error code: {Marshal.GetLastWin32Error()}"); } var commandLine = $"\"{fileName}\" {arguments}"; var startupInfo = new Interop.Windows.StartupInfo(); startupInfo.cb = Marshal.SizeOf(startupInfo); Interop.Windows.ProcessInformation processInformation; success = Interop.Windows.CreateProcessAsUserW( newTokenHandle, null, commandLine, securityAttributes, securityAttributes, false, Interop.Windows.ProcessCreationFlags.CreateUnicodeEnvironment | Interop.Windows.ProcessCreationFlags.CreateNoWindow, environmentPtr, null, ref startupInfo, out processInformation ); Interop.Windows.DestroyEnvironmentBlock(environmentPtr); if (!success) { Logger.GetInstance(typeof(Windows)).Error($"Can not create process as user, error code: {Marshal.GetLastWin32Error()}"); continue; } var processId = processInformation.dwProcessID; var processPath = GetPlatformProcessPathById(processId); string processName; using (var process = Process.GetProcessById(processId)) { processName = process.ProcessName; } return new ProcessInfo { Id = processId, Name = processName, Path = processPath }; } } catch (Exception e) { Logger.GetInstance(typeof(Windows)).Error($"Can not launch process as user: {e}"); } finally { if (sessionInfoPtr != IntPtr.Zero) { Interop.Windows.WTSFreeMemory(sessionInfoPtr); } } } return null; } } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Common.Authentication.Models; using Microsoft.Azure.Commands.Management.Storage.Models; using Microsoft.Azure.Management.Storage; using Microsoft.Azure.Management.Storage.Models; using Microsoft.WindowsAzure.Commands.Common.Storage; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Auth; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Management.Automation; using System.Text; using System.Xml; using System.Xml.Linq; using System.Xml.Serialization; namespace Microsoft.Azure.Commands.Compute.Common { public static class DiagnosticsHelper { private static string EncodedXmlCfg = "xmlCfg"; private static string WadCfg = "WadCfg"; private static string WadCfgBlob = "WadCfgBlob"; private static string StorageAccount = "storageAccount"; private static string Path = "path"; private static string ExpandResourceDirectory = "expandResourceDirectory"; private static string LocalResourceDirectory = "localResourceDirectory"; private static string StorageAccountNameTag = "storageAccountName"; private static string StorageAccountKeyTag = "storageAccountKey"; private static string StorageAccountEndPointTag = "storageAccountEndPoint"; public static string XmlNamespace = "http://schemas.microsoft.com/ServiceHosting/2010/10/DiagnosticsConfiguration"; public static string DiagnosticsConfigurationElemStr = "DiagnosticsConfiguration"; public static string DiagnosticMonitorConfigurationElemStr = "DiagnosticMonitorConfiguration"; public static string PublicConfigElemStr = "PublicConfig"; public static string PrivateConfigElemStr = "PrivateConfig"; public static string StorageAccountElemStr = "StorageAccount"; public static string PrivConfNameAttr = "name"; public static string PrivConfKeyAttr = "key"; public static string PrivConfEndpointAttr = "endpoint"; public static string MetricsElemStr = "Metrics"; public static string MetricsResourceIdAttr = "resourceId"; public static string EventHubElemStr = "EventHub"; public static string EventHubUrlAttr = "Url"; public static string EventHubSharedAccessKeyNameAttr = "SharedAccessKeyName"; public static string EventHubSharedAccessKeyAttr = "SharedAccessKey"; public enum ConfigFileType { Unknown, Json, Xml } public static ConfigFileType GetConfigFileType(string configurationPath) { if (!string.IsNullOrEmpty(configurationPath)) { try { XmlDocument doc = new XmlDocument(); doc.Load(configurationPath); return ConfigFileType.Xml; } catch (XmlException) { } try { JsonConvert.DeserializeObject(File.ReadAllText(configurationPath)); return ConfigFileType.Json; } catch (JsonReaderException) { } } return ConfigFileType.Unknown; } public static Hashtable GetPublicDiagnosticsConfigurationFromFile(string configurationPath, string storageAccountName, string resourceId, Cmdlet cmdlet) { switch (GetConfigFileType(configurationPath)) { case ConfigFileType.Xml: return GetPublicConfigFromXmlFile(configurationPath, storageAccountName, resourceId, cmdlet); case ConfigFileType.Json: return GetPublicConfigFromJsonFile(configurationPath, storageAccountName, resourceId, cmdlet); default: throw new ArgumentException(Properties.Resources.DiagnosticsExtensionInvalidConfigFileFormat); } } private static Hashtable GetPublicConfigFromXmlFile(string configurationPath, string storageAccountName, string resourceId, Cmdlet cmdlet) { var doc = XDocument.Load(configurationPath); var wadCfgElement = doc.Descendants().FirstOrDefault(d => d.Name.LocalName == WadCfg); var wadCfgBlobElement = doc.Descendants().FirstOrDefault(d => d.Name.LocalName == WadCfgBlob); if (wadCfgElement == null && wadCfgBlobElement == null) { throw new ArgumentException(Properties.Resources.DiagnosticsExtensionIaaSConfigElementNotDefinedInXml); } if (wadCfgElement != null) { AutoFillMetricsConfig(wadCfgElement, resourceId, cmdlet); } string originalConfiguration = wadCfgElement != null ? wadCfgElement.ToString() : wadCfgBlobElement.ToString(); string encodedConfiguration = Convert.ToBase64String(Encoding.UTF8.GetBytes(wadCfgElement.ToString().ToCharArray())); // Now extract the local resource directory element var node = doc.Descendants().FirstOrDefault(e => e.Name.LocalName == "LocalResourceDirectory"); string localDirectory = (node != null && node.Attribute(Path) != null) ? node.Attribute(Path).Value : null; string localDirectoryExpand = (node != null && node.Attribute("expandEnvironment") != null) ? node.Attribute("expandEnvironment").Value : null; if (localDirectoryExpand == "0") { localDirectoryExpand = "false"; } if (localDirectoryExpand == "1") { localDirectoryExpand = "true"; } var hashTable = new Hashtable(); hashTable.Add(EncodedXmlCfg, encodedConfiguration); hashTable.Add(StorageAccount, storageAccountName); if (!string.IsNullOrEmpty(localDirectory)) { var localDirectoryHashTable = new Hashtable(); localDirectoryHashTable.Add(Path, localDirectory); localDirectoryHashTable.Add(ExpandResourceDirectory, localDirectoryExpand); hashTable.Add(LocalResourceDirectory, localDirectoryHashTable); } return hashTable; } private static void AutoFillMetricsConfig(XElement wadCfgElement, string resourceId, Cmdlet cmdlet) { if (string.IsNullOrEmpty(resourceId)) { return; } var configurationElem = wadCfgElement.Elements().FirstOrDefault(d => d.Name.LocalName == DiagnosticMonitorConfigurationElemStr); if (configurationElem == null) { throw new ArgumentException(Properties.Resources.DiagnosticsExtensionDiagnosticMonitorConfigurationElementNotDefined); } var metricsElement = configurationElem.Elements().FirstOrDefault(d => d.Name.LocalName == MetricsElemStr); if (metricsElement == null) { XNamespace ns = XmlNamespace; metricsElement = new XElement(ns + MetricsElemStr, new XAttribute(MetricsResourceIdAttr, resourceId)); configurationElem.Add(metricsElement); } else { var resourceIdAttr = metricsElement.Attribute(MetricsResourceIdAttr); if (resourceIdAttr != null && !resourceIdAttr.Value.Equals(resourceId)) { cmdlet.WriteWarning(Properties.Resources.DiagnosticsExtensionMetricsResourceIdNotMatch); } metricsElement.SetAttributeValue(MetricsResourceIdAttr, resourceId); } } private static Hashtable GetPublicConfigFromJsonFile(string configurationPath, string storageAccountName, string resourceId, Cmdlet cmdlet) { var publicConfig = GetPublicConfigJObjectFromJsonFile(configurationPath); var properties = publicConfig.Properties().Select(p => p.Name); var wadCfgProperty = properties.FirstOrDefault(p => p.Equals(WadCfg, StringComparison.OrdinalIgnoreCase)); var wadCfgBlobProperty = properties.FirstOrDefault(p => p.Equals(WadCfgBlob, StringComparison.OrdinalIgnoreCase)); var xmlCfgProperty = properties.FirstOrDefault(p => p.Equals(EncodedXmlCfg, StringComparison.OrdinalIgnoreCase)); var hashTable = new Hashtable(); hashTable.Add(StorageAccount, storageAccountName); if (wadCfgProperty != null && publicConfig[wadCfgProperty] is JObject) { var wadCfgObject = (JObject)publicConfig[wadCfgProperty]; AutoFillMetricsConfig(wadCfgObject, resourceId, cmdlet); hashTable.Add(wadCfgProperty, wadCfgObject); } else if (wadCfgBlobProperty != null) { hashTable.Add(wadCfgBlobProperty, publicConfig[wadCfgBlobProperty]); } else if (xmlCfgProperty != null) { hashTable.Add(xmlCfgProperty, publicConfig[xmlCfgProperty]); } else { throw new ArgumentException(Properties.Resources.DiagnosticsExtensionIaaSConfigElementNotDefinedInJson); } return hashTable; } private static void AutoFillMetricsConfig(JObject wadCfgObject, string resourceId, Cmdlet cmdlet) { if (string.IsNullOrEmpty(resourceId)) { return; } var configObject = wadCfgObject[DiagnosticMonitorConfigurationElemStr] as JObject; if (configObject == null) { throw new ArgumentException(Properties.Resources.DiagnosticsExtensionDiagnosticMonitorConfigurationElementNotDefined); } var metricsObject = configObject[MetricsElemStr] as JObject; if (metricsObject == null) { configObject.Add(new JProperty(MetricsElemStr, new JObject( new JProperty(MetricsResourceIdAttr, resourceId)))); } else { var resourceIdValue = metricsObject[MetricsResourceIdAttr] as JValue; if (resourceIdValue != null && !resourceIdValue.Value.Equals(resourceId)) { cmdlet.WriteWarning(Properties.Resources.DiagnosticsExtensionMetricsResourceIdNotMatch); } metricsObject[MetricsResourceIdAttr] = resourceId; } } public static Hashtable GetPrivateDiagnosticsConfiguration(string configurationPath, string storageAccountName, string storageKey, string endpoint) { var privateConfig = new Hashtable(); var configFileType = GetConfigFileType(configurationPath); if (configFileType == ConfigFileType.Xml) { var doc = XDocument.Load(configurationPath); var privateConfigElement = doc.Descendants().FirstOrDefault(d => d.Name.LocalName == PrivateConfigElemStr); if (privateConfigElement != null) { // Unfortunately, there is no easy way to convert the xml config to json config without involving a schema file. // We take the schema file generated by the .xsd file, and let the serializer doing the conversion work for us. // NOTE: this file need to be updated whenever the private schema is changed. XmlSerializer serializer = new XmlSerializer(typeof(Cis.Monitoring.Wad.PrivateConfigConverter.PrivateConfig)); using (StringReader sr = new StringReader(privateConfigElement.ToString())) { var config = (Cis.Monitoring.Wad.PrivateConfigConverter.PrivateConfig)serializer.Deserialize(sr); // Set the StorageAccount element as null, so it won't appear after serialize to json config.StorageAccount = null; var privateConfigInJson = JsonConvert.SerializeObject(config, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); privateConfig = JsonConvert.DeserializeObject<Hashtable>(privateConfigInJson); } } } else if (configFileType == ConfigFileType.Json) { // Find the PrivateConfig var jsonConfig = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(configurationPath)); var hasPrivateConfig = jsonConfig.Properties().Any(p => p.Name.Equals(PrivateConfigElemStr)); if (hasPrivateConfig) { privateConfig = JsonConvert.DeserializeObject<Hashtable>(jsonConfig[PrivateConfigElemStr].ToString()); } } privateConfig[StorageAccountNameTag] = storageAccountName; privateConfig[StorageAccountKeyTag] = storageKey; privateConfig[StorageAccountEndPointTag] = endpoint; return privateConfig; } private static void AddEventHubPrivateConfig(Hashtable privateConfig, string configurationPath) { var eventHubUrl = GetConfigValueFromPrivateConfig(configurationPath, EventHubElemStr, EventHubUrlAttr); var eventHubSharedAccessKeyName = GetConfigValueFromPrivateConfig(configurationPath, EventHubElemStr, EventHubSharedAccessKeyNameAttr); var eventHubSharedAccessKey = GetConfigValueFromPrivateConfig(configurationPath, EventHubElemStr, EventHubSharedAccessKeyAttr); if (!string.IsNullOrEmpty(eventHubUrl) || !string.IsNullOrEmpty(eventHubSharedAccessKeyName) || !string.IsNullOrEmpty(eventHubSharedAccessKey)) { var eventHubConfig = new Hashtable(); eventHubConfig.Add(EventHubUrlAttr, eventHubUrl); eventHubConfig.Add(EventHubSharedAccessKeyNameAttr, eventHubSharedAccessKeyName); eventHubConfig.Add(EventHubSharedAccessKeyAttr, eventHubSharedAccessKey); privateConfig.Add(EventHubElemStr, eventHubConfig); } } private static XElement GetPublicConfigXElementFromXmlFile(string configurationPath) { XElement publicConfig = null; if (!string.IsNullOrEmpty(configurationPath)) { var xmlConfig = XElement.Load(configurationPath); if (xmlConfig.Name.LocalName == PublicConfigElemStr) { // The passed in config file is public config publicConfig = xmlConfig; } else if (xmlConfig.Name.LocalName == DiagnosticsConfigurationElemStr) { // The passed in config file is .wadcfgx file publicConfig = xmlConfig.Elements().FirstOrDefault(ele => ele.Name.LocalName == PublicConfigElemStr); } } return publicConfig; } private static JObject GetPublicConfigJObjectFromJsonFile(string configurationPath) { var config = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(configurationPath)); var properties = config.Properties().Select(p => p.Name); // If the json config has the public config as a property, we extract it. Otherwise, the root object is the public config. var publicConfigProperty = properties.FirstOrDefault(p => p.Equals(PublicConfigElemStr, StringComparison.OrdinalIgnoreCase)); var publicConfig = publicConfigProperty == null ? config : config[publicConfigProperty] as JObject; return publicConfig; } /// <summary> /// Get the private config value for a specific attribute. /// The private config looks like this: /// XML: /// <PrivateConfig xmlns="namespace"> /// <StorageAccount name = "name" key="key" endpoint="endpoint" /> /// <EventHub Url = "url" SharedAccessKeyName="sasKeyName" SharedAccessKey="sasKey"/> /// </PrivateConfig> /// /// JSON: /// "PrivateConfig":{ /// "storageAccountName":"name", /// "storageAccountKey":"key", /// "storageAccountEndPoint":"endpoint", /// "EventHub":{ /// "Url":"url", /// "SharedAccessKeyName":"sasKeyName", /// "SharedAccessKey":"sasKey" /// } /// } /// </summary> /// <param name="configurationPath">The path to the configuration file</param> /// <param name="elementName">The element name of the private config. e.g., StorageAccount, EventHub</param> /// <param name="attributeName">The attribute name of the element</param> /// <returns></returns> public static string GetConfigValueFromPrivateConfig(string configurationPath, string elementName, string attributeName) { string value = string.Empty; var configFileType = GetConfigFileType(configurationPath); if (configFileType == ConfigFileType.Xml) { var xmlConfig = XElement.Load(configurationPath); if (xmlConfig.Name.LocalName == DiagnosticsConfigurationElemStr) { var privateConfigElem = xmlConfig.Elements().FirstOrDefault(ele => ele.Name.LocalName == PrivateConfigElemStr); var configElem = privateConfigElem == null ? null : privateConfigElem.Elements().FirstOrDefault(ele => ele.Name.LocalName == elementName); var attribute = configElem == null ? null : configElem.Attributes().FirstOrDefault(a => string.Equals(a.Name.LocalName, attributeName)); value = attribute == null ? null : attribute.Value; } } else if (configFileType == ConfigFileType.Json) { // Find the PrivateConfig var jsonConfig = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(configurationPath)); var properties = jsonConfig.Properties().Select(p => p.Name); var privateConfigProperty = properties.FirstOrDefault(p => p.Equals(PrivateConfigElemStr)); if (privateConfigProperty == null) { return value; } var privateConfig = jsonConfig[privateConfigProperty] as JObject; // Find the target config object corresponding to elementName JObject targetConfig = null; if (elementName == StorageAccountElemStr) { // Special handling as private storage config is flattened targetConfig = privateConfig; var attributeNameMapping = new Dictionary<string, string>() { { PrivConfNameAttr, "storageAccountName" }, { PrivConfKeyAttr, "storageAccountKey" }, { PrivConfEndpointAttr, "storageAccountEndPoint" } }; attributeName = attributeNameMapping.FirstOrDefault(m => m.Key == attributeName).Value; } else { properties = privateConfig.Properties().Select(p => p.Name); var configProperty = properties.FirstOrDefault(p => p.Equals(elementName)); targetConfig = configProperty == null ? null : privateConfig[configProperty] as JObject; } if (targetConfig == null || attributeName == null) { return value; } // Find the config value corresponding to attributeName properties = targetConfig.Properties().Select(p => p.Name); var attributeProperty = properties.FirstOrDefault(p => p.Equals(attributeName)); value = attributeProperty == null ? null : targetConfig[attributeProperty].Value<string>(); } return value; } /// <summary> /// Initialize the storage account name if it's not specified. /// It can be defined in multiple places, we only take the one with higher precedence. And the precedence is: /// 1. The one get from StorageContext parameter /// 2. The one parsed from the diagnostics configuration file /// </summary> public static string InitializeStorageAccountName(AzureStorageContext storageContext = null, string configurationPath = null) { string storageAccountName = null; var configFileType = GetConfigFileType(configurationPath); if (storageContext != null) { storageAccountName = storageContext.StorageAccountName; } else if (configFileType == ConfigFileType.Xml) { var publicConfig = GetPublicConfigXElementFromXmlFile(configurationPath); var storageNode = publicConfig == null ? null : publicConfig.Elements().FirstOrDefault(ele => ele.Name.LocalName == StorageAccountElemStr); storageAccountName = storageNode == null ? null : storageNode.Value; } else if (configFileType == ConfigFileType.Json) { var publicConfig = GetPublicConfigJObjectFromJsonFile(configurationPath); var properties = publicConfig.Properties().Select(p => p.Name); var storageAccountProperty = properties.FirstOrDefault(p => p.Equals(StorageAccount, StringComparison.OrdinalIgnoreCase)); storageAccountName = storageAccountProperty == null ? null : publicConfig[storageAccountProperty].Value<string>(); } return storageAccountName; } /// <summary> /// Initialize the storage account key if it's not specified. /// It can be defined in multiple places, we only take the one with higher precedence. And the precedence is: /// 1. The one we try to resolve within current subscription /// 2. The one defined in PrivateConfig in the configuration file /// </summary> public static string InitializeStorageAccountKey(IStorageManagementClient storageClient, string storageAccountName = null, string configurationPath = null) { string storageAccountKey = null; StorageAccount storageAccount = null; if (TryGetStorageAccount(storageClient, storageAccountName, out storageAccount)) { // Help user retrieve the storage account key var credentials = StorageUtilities.GenerateStorageCredentials(new ARMStorageProvider(storageClient), ARMStorageService.ParseResourceGroupFromId(storageAccount.Id), storageAccount.Name); storageAccountKey = credentials.ExportBase64EncodedKey(); } else { // Use the one defined in PrivateConfig storageAccountKey = GetConfigValueFromPrivateConfig(configurationPath, StorageAccountElemStr, PrivConfKeyAttr); } return storageAccountKey; } /// <summary> /// Initialize the storage account endpoint if it's not specified. /// We can get the value from multiple places, we only take the one with higher precedence. And the precedence is: /// 1. The one get from StorageContext parameter /// 2. The one get from the storage account /// 3. The one get from PrivateConfig element in config file /// 4. The one get from current Azure Environment /// </summary> public static string InitializeStorageAccountEndpoint(string storageAccountName, string storageAccountKey, IStorageManagementClient storageClient, AzureStorageContext storageContext = null, string configurationPath = null, AzureContext defaultContext = null) { string storageAccountEndpoint = null; StorageAccount storageAccount = null; if (storageContext != null) { // Get value from StorageContext storageAccountEndpoint = GetEndpointFromStorageContext(storageContext); } else if (TryGetStorageAccount(storageClient, storageAccountName, out storageAccount)) { // Get value from StorageAccount var endpoints = storageAccount.PrimaryEndpoints; var context = CreateStorageContext(new Uri(endpoints.Blob), new Uri(endpoints.Queue), new Uri(endpoints.Table), new Uri(endpoints.File), storageAccountName, storageAccountKey); storageAccountEndpoint = GetEndpointFromStorageContext(context); } else if (!string.IsNullOrEmpty( storageAccountEndpoint = GetConfigValueFromPrivateConfig(configurationPath, StorageAccountElemStr, PrivConfEndpointAttr))) { // We can get the value from PrivateConfig } else if (defaultContext != null && defaultContext.Environment != null) { // Get value from default azure environment. Default to use https Uri blobEndpoint = defaultContext.Environment.GetStorageBlobEndpoint(storageAccountName); Uri queueEndpoint = defaultContext.Environment.GetStorageQueueEndpoint(storageAccountName); Uri tableEndpoint = defaultContext.Environment.GetStorageTableEndpoint(storageAccountName); Uri fileEndpoint = defaultContext.Environment.GetStorageFileEndpoint(storageAccountName); var context = CreateStorageContext(blobEndpoint, queueEndpoint, tableEndpoint, fileEndpoint, storageAccountName, storageAccountKey); storageAccountEndpoint = GetEndpointFromStorageContext(context); } return storageAccountEndpoint; } private static bool TryGetStorageAccount(IStorageManagementClient storageClient, string storageAccountName, out StorageAccount storageAccount) { try { var storageAccounts = storageClient.StorageAccounts.List(); storageAccount = storageAccounts == null ? null : storageAccounts.FirstOrDefault(account => account.Name.Equals(storageAccountName)); } catch { storageAccount = null; } return storageAccount != null; } private static AzureStorageContext CreateStorageContext(Uri blobEndpoint, Uri queueEndpoint, Uri tableEndpoint, Uri fileEndpoint, string storageAccountName, string storageAccountKey) { var credentials = new StorageCredentials(storageAccountName, storageAccountKey); var cloudStorageAccount = new CloudStorageAccount(credentials, blobEndpoint, queueEndpoint, tableEndpoint, fileEndpoint); return new AzureStorageContext(cloudStorageAccount); } private static string GetEndpointFromStorageContext(AzureStorageContext context) { var scheme = context.BlobEndPoint.StartsWith("https://", StringComparison.OrdinalIgnoreCase) ? "https://" : "http://"; return scheme + context.EndPointSuffix; } } }
namespace IDT4.Engine.CM { internal partial class CollisionModelManager { /* =============================================================================== Collision detection for translational motion =============================================================================== */ /* ================ idCollisionModelManagerLocal::TranslateEdgeThroughEdge calculates fraction of the translation completed at which the edges collide ================ */ ID_INLINE int idCollisionModelManagerLocal::TranslateEdgeThroughEdge( idVec3 &cross, idPluecker &l1, idPluecker &l2, float *fraction ) { float d, t; /* a = start of line b = end of line dir = movement direction l1 = pluecker coordinate for line l2 = pluecker coordinate for edge we might collide with a+dir = start of line after movement b+dir = end of line after movement t = scale factor solve pluecker inner product for t of line (a+t*dir : b+t*dir) and line l2 v[0] = (a[0]+t*dir[0]) * (b[1]+t*dir[1]) - (b[0]+t*dir[0]) * (a[1]+t*dir[1]); v[1] = (a[0]+t*dir[0]) * (b[2]+t*dir[2]) - (b[0]+t*dir[0]) * (a[2]+t*dir[2]); v[2] = (a[0]+t*dir[0]) - (b[0]+t*dir[0]); v[3] = (a[1]+t*dir[1]) * (b[2]+t*dir[2]) - (b[1]+t*dir[1]) * (a[2]+t*dir[2]); v[4] = (a[2]+t*dir[2]) - (b[2]+t*dir[2]); v[5] = (b[1]+t*dir[1]) - (a[1]+t*dir[1]); l2[0] * v[4] + l2[1] * v[5] + l2[2] * v[3] + l2[4] * v[0] + l2[5] * v[1] + l2[3] * v[2] = 0; solve t v[0] = (a[0]+t*dir[0]) * (b[1]+t*dir[1]) - (b[0]+t*dir[0]) * (a[1]+t*dir[1]); v[0] = (a[0]*b[1]) + a[0]*t*dir[1] + b[1]*t*dir[0] + (t*t*dir[0]*dir[1]) - ((b[0]*a[1]) + b[0]*t*dir[1] + a[1]*t*dir[0] + (t*t*dir[0]*dir[1])); v[0] = a[0]*b[1] + a[0]*t*dir[1] + b[1]*t*dir[0] - b[0]*a[1] - b[0]*t*dir[1] - a[1]*t*dir[0]; v[1] = (a[0]+t*dir[0]) * (b[2]+t*dir[2]) - (b[0]+t*dir[0]) * (a[2]+t*dir[2]); v[1] = (a[0]*b[2]) + a[0]*t*dir[2] + b[2]*t*dir[0] + (t*t*dir[0]*dir[2]) - ((b[0]*a[2]) + b[0]*t*dir[2] + a[2]*t*dir[0] + (t*t*dir[0]*dir[2])); v[1] = a[0]*b[2] + a[0]*t*dir[2] + b[2]*t*dir[0] - b[0]*a[2] - b[0]*t*dir[2] - a[2]*t*dir[0]; v[2] = (a[0]+t*dir[0]) - (b[0]+t*dir[0]); v[2] = a[0] - b[0]; v[3] = (a[1]+t*dir[1]) * (b[2]+t*dir[2]) - (b[1]+t*dir[1]) * (a[2]+t*dir[2]); v[3] = (a[1]*b[2]) + a[1]*t*dir[2] + b[2]*t*dir[1] + (t*t*dir[1]*dir[2]) - ((b[1]*a[2]) + b[1]*t*dir[2] + a[2]*t*dir[1] + (t*t*dir[1]*dir[2])); v[3] = a[1]*b[2] + a[1]*t*dir[2] + b[2]*t*dir[1] - b[1]*a[2] - b[1]*t*dir[2] - a[2]*t*dir[1]; v[4] = (a[2]+t*dir[2]) - (b[2]+t*dir[2]); v[4] = a[2] - b[2]; v[5] = (b[1]+t*dir[1]) - (a[1]+t*dir[1]); v[5] = b[1] - a[1]; v[0] = a[0]*b[1] + a[0]*t*dir[1] + b[1]*t*dir[0] - b[0]*a[1] - b[0]*t*dir[1] - a[1]*t*dir[0]; v[1] = a[0]*b[2] + a[0]*t*dir[2] + b[2]*t*dir[0] - b[0]*a[2] - b[0]*t*dir[2] - a[2]*t*dir[0]; v[2] = a[0] - b[0]; v[3] = a[1]*b[2] + a[1]*t*dir[2] + b[2]*t*dir[1] - b[1]*a[2] - b[1]*t*dir[2] - a[2]*t*dir[1]; v[4] = a[2] - b[2]; v[5] = b[1] - a[1]; v[0] = (a[0]*dir[1] + b[1]*dir[0] - b[0]*dir[1] - a[1]*dir[0]) * t + a[0]*b[1] - b[0]*a[1]; v[1] = (a[0]*dir[2] + b[2]*dir[0] - b[0]*dir[2] - a[2]*dir[0]) * t + a[0]*b[2] - b[0]*a[2]; v[2] = a[0] - b[0]; v[3] = (a[1]*dir[2] + b[2]*dir[1] - b[1]*dir[2] - a[2]*dir[1]) * t + a[1]*b[2] - b[1]*a[2]; v[4] = a[2] - b[2]; v[5] = b[1] - a[1]; l2[4] * (a[0]*dir[1] + b[1]*dir[0] - b[0]*dir[1] - a[1]*dir[0]) * t + l2[4] * (a[0]*b[1] - b[0]*a[1]) + l2[5] * (a[0]*dir[2] + b[2]*dir[0] - b[0]*dir[2] - a[2]*dir[0]) * t + l2[5] * (a[0]*b[2] - b[0]*a[2]) + l2[3] * (a[0] - b[0]) + l2[2] * (a[1]*dir[2] + b[2]*dir[1] - b[1]*dir[2] - a[2]*dir[1]) * t + l2[2] * (a[1]*b[2] - b[1]*a[2]) + l2[0] * (a[2] - b[2]) + l2[1] * (b[1] - a[1]) = 0 t = (- l2[4] * (a[0]*b[1] - b[0]*a[1]) - l2[5] * (a[0]*b[2] - b[0]*a[2]) - l2[3] * (a[0] - b[0]) - l2[2] * (a[1]*b[2] - b[1]*a[2]) - l2[0] * (a[2] - b[2]) - l2[1] * (b[1] - a[1])) / (l2[4] * (a[0]*dir[1] + b[1]*dir[0] - b[0]*dir[1] - a[1]*dir[0]) + l2[5] * (a[0]*dir[2] + b[2]*dir[0] - b[0]*dir[2] - a[2]*dir[0]) + l2[2] * (a[1]*dir[2] + b[2]*dir[1] - b[1]*dir[2] - a[2]*dir[1])); d = l2[4] * (a[0]*dir[1] + b[1]*dir[0] - b[0]*dir[1] - a[1]*dir[0]) + l2[5] * (a[0]*dir[2] + b[2]*dir[0] - b[0]*dir[2] - a[2]*dir[0]) + l2[2] * (a[1]*dir[2] + b[2]*dir[1] - b[1]*dir[2] - a[2]*dir[1]); t = - ( l2[4] * (a[0]*b[1] - b[0]*a[1]) + l2[5] * (a[0]*b[2] - b[0]*a[2]) + l2[3] * (a[0] - b[0]) + l2[2] * (a[1]*b[2] - b[1]*a[2]) + l2[0] * (a[2] - b[2]) + l2[1] * (b[1] - a[1])); t /= d; MrE pats Pluecker on the head.. good monkey edgeDir = a - b; d = l2[4] * (edgeDir[0]*dir[1] - edgeDir[1]*dir[0]) + l2[5] * (edgeDir[0]*dir[2] - edgeDir[2]*dir[0]) + l2[2] * (edgeDir[1]*dir[2] - edgeDir[2]*dir[1]); */ d = l2[4] * cross[0] + l2[5] * cross[1] + l2[2] * cross[2]; if ( d == 0.0f ) { *fraction = 1.0f; // no collision ever return false; } t = -l1.PermutedInnerProduct( l2 ); // if the lines cross each other to begin with if ( t == 0.0f ) { *fraction = 0.0f; return true; } // fraction of movement at the time the lines cross each other *fraction = t / d; return true; } /* ================ CM_AddContact ================ */ ID_INLINE void CM_AddContact( cm_traceWork_t *tw ) { if ( tw->numContacts >= tw->maxContacts ) { return; } // copy contact information from trace_t tw->contacts[tw->numContacts] = tw->trace.c; tw->numContacts++; // set fraction back to 1 to find all other contacts tw->trace.fraction = 1.0f; } /* ================ CM_SetVertexSidedness stores for the given model vertex at which side of one of the trm edges it passes ================ */ ID_INLINE void CM_SetVertexSidedness( cm_vertex_t *v, const idPluecker &vpl, const idPluecker &epl, const int bitNum ) { if ( !(v->sideSet & (1<<bitNum)) ) { float fl; fl = vpl.PermutedInnerProduct( epl ); v->side = (v->side & ~(1<<bitNum)) | (FLOATSIGNBITSET(fl) << bitNum); v->sideSet |= (1 << bitNum); } } /* ================ CM_SetEdgeSidedness stores for the given model edge at which side one of the trm vertices ================ */ ID_INLINE void CM_SetEdgeSidedness( cm_edge_t *edge, const idPluecker &vpl, const idPluecker &epl, const int bitNum ) { if ( !(edge->sideSet & (1<<bitNum)) ) { float fl; fl = vpl.PermutedInnerProduct( epl ); edge->side = (edge->side & ~(1<<bitNum)) | (FLOATSIGNBITSET(fl) << bitNum); edge->sideSet |= (1 << bitNum); } } /* ================ idCollisionModelManagerLocal::TranslateTrmEdgeThroughPolygon ================ */ void idCollisionModelManagerLocal::TranslateTrmEdgeThroughPolygon( cm_traceWork_t *tw, cm_polygon_t *poly, cm_trmEdge_t *trmEdge ) { int i, edgeNum; float f1, f2, dist, d1, d2; idVec3 start, end, normal; cm_edge_t *edge; cm_vertex_t *v1, *v2; idPluecker *pl, epsPl; // check edges for a collision for ( i = 0; i < poly->numEdges; i++) { edgeNum = poly->edges[i]; edge = tw->model->edges + abs(edgeNum); // if this edge is already checked if ( edge->checkcount == idCollisionModelManagerLocal::checkCount ) { continue; } // can never collide with internal edges if ( edge->internal ) { continue; } pl = &tw->polygonEdgePlueckerCache[i]; // get the sides at which the trm edge vertices pass the polygon edge CM_SetEdgeSidedness( edge, *pl, tw->vertices[trmEdge->vertexNum[0]].pl, trmEdge->vertexNum[0] ); CM_SetEdgeSidedness( edge, *pl, tw->vertices[trmEdge->vertexNum[1]].pl, trmEdge->vertexNum[1] ); // if the trm edge start and end vertex do not pass the polygon edge at different sides if ( !(((edge->side >> trmEdge->vertexNum[0]) ^ (edge->side >> trmEdge->vertexNum[1])) & 1) ) { continue; } // get the sides at which the polygon edge vertices pass the trm edge v1 = tw->model->vertices + edge->vertexNum[INTSIGNBITSET(edgeNum)]; CM_SetVertexSidedness( v1, tw->polygonVertexPlueckerCache[i], trmEdge->pl, trmEdge->bitNum ); v2 = tw->model->vertices + edge->vertexNum[INTSIGNBITNOTSET(edgeNum)]; CM_SetVertexSidedness( v2, tw->polygonVertexPlueckerCache[i+1], trmEdge->pl, trmEdge->bitNum ); // if the polygon edge start and end vertex do not pass the trm edge at different sides if ( !((v1->side ^ v2->side) & (1<<trmEdge->bitNum)) ) { continue; } // if there is no possible collision between the trm edge and the polygon edge if ( !idCollisionModelManagerLocal::TranslateEdgeThroughEdge( trmEdge->cross, trmEdge->pl, *pl, &f1 ) ) { continue; } // if moving away from edge if ( f1 < 0.0f ) { continue; } // pluecker coordinate for epsilon expanded edge epsPl.FromLine( tw->model->vertices[edge->vertexNum[0]].p + edge->normal * CM_CLIP_EPSILON, tw->model->vertices[edge->vertexNum[1]].p + edge->normal * CM_CLIP_EPSILON ); // calculate collision fraction with epsilon expanded edge if ( !idCollisionModelManagerLocal::TranslateEdgeThroughEdge( trmEdge->cross, trmEdge->pl, epsPl, &f2 ) ) { continue; } // if no collision with epsilon edge or moving away from edge if ( f2 > 1.0f || f1 < f2 ) { continue; } if ( f2 < 0.0f ) { f2 = 0.0f; } if ( f2 < tw->trace.fraction ) { tw->trace.fraction = f2; // create plane with normal vector orthogonal to both the polygon edge and the trm edge start = tw->model->vertices[edge->vertexNum[0]].p; end = tw->model->vertices[edge->vertexNum[1]].p; tw->trace.c.normal = ( end - start ).Cross( trmEdge->end - trmEdge->start ); // FIXME: do this normalize when we know the first collision tw->trace.c.normal.Normalize(); tw->trace.c.dist = tw->trace.c.normal * start; // make sure the collision plane faces the trace model if ( tw->trace.c.normal * trmEdge->start - tw->trace.c.dist < 0.0f ) { tw->trace.c.normal = -tw->trace.c.normal; tw->trace.c.dist = -tw->trace.c.dist; } tw->trace.c.contents = poly->contents; tw->trace.c.material = poly->material; tw->trace.c.type = CONTACT_EDGE; tw->trace.c.modelFeature = edgeNum; tw->trace.c.trmFeature = trmEdge - tw->edges; // calculate collision point normal[0] = trmEdge->cross[2]; normal[1] = -trmEdge->cross[1]; normal[2] = trmEdge->cross[0]; dist = normal * trmEdge->start; d1 = normal * start - dist; d2 = normal * end - dist; f1 = d1 / ( d1 - d2 ); //assert( f1 >= 0.0f && f1 <= 1.0f ); tw->trace.c.point = start + f1 * ( end - start ); // if retrieving contacts if ( tw->getContacts ) { CM_AddContact( tw ); } } } } /* ================ CM_TranslationPlaneFraction ================ */ #if 0 float CM_TranslationPlaneFraction( idPlane &plane, idVec3 &start, idVec3 &end ) { float d1, d2; d2 = plane.Distance( end ); // if the end point is closer to the plane than an epsilon we still take it for a collision if ( d2 >= CM_CLIP_EPSILON ) { return 1.0f; } d1 = plane.Distance( start ); // if completely behind the polygon if ( d1 <= 0.0f ) { return 1.0f; } // leaves polygon if ( d1 <= d2 ) { return 1.0f; } return (d1-CM_CLIP_EPSILON) / (d1-d2); } #else float CM_TranslationPlaneFraction( idPlane &plane, idVec3 &start, idVec3 &end ) { float d1, d2, d2eps; d2 = plane.Distance( end ); // if the end point is closer to the plane than an epsilon we still take it for a collision // if ( d2 >= CM_CLIP_EPSILON ) { d2eps = d2 - CM_CLIP_EPSILON; if ( FLOATSIGNBITNOTSET(d2eps) ) { return 1.0f; } d1 = plane.Distance( start ); // if completely behind the polygon if ( FLOATSIGNBITSET(d1) ) { return 1.0f; } // if going towards the front of the plane and // the start and end point are not at equal distance from the plane // if ( d1 > d2 ) d2 = d1 - d2; if ( d2 <= 0.0f ) { return 1.0f; } return (d1-CM_CLIP_EPSILON) / d2; } #endif /* ================ idCollisionModelManagerLocal::TranslateTrmVertexThroughPolygon ================ */ void idCollisionModelManagerLocal::TranslateTrmVertexThroughPolygon( cm_traceWork_t *tw, cm_polygon_t *poly, cm_trmVertex_t *v, int bitNum ) { int i, edgeNum; float f; cm_edge_t *edge; f = CM_TranslationPlaneFraction( poly->plane, v->p, v->endp ); if ( f < tw->trace.fraction ) { for ( i = 0; i < poly->numEdges; i++ ) { edgeNum = poly->edges[i]; edge = tw->model->edges + abs(edgeNum); CM_SetEdgeSidedness( edge, tw->polygonEdgePlueckerCache[i], v->pl, bitNum ); if ( INTSIGNBITSET(edgeNum) ^ ((edge->side >> bitNum) & 1) ) { return; } } if ( f < 0.0f ) { f = 0.0f; } tw->trace.fraction = f; // collision plane is the polygon plane tw->trace.c.normal = poly->plane.Normal(); tw->trace.c.dist = poly->plane.Dist(); tw->trace.c.contents = poly->contents; tw->trace.c.material = poly->material; tw->trace.c.type = CONTACT_TRMVERTEX; tw->trace.c.modelFeature = *reinterpret_cast<int *>(&poly); tw->trace.c.trmFeature = v - tw->vertices; tw->trace.c.point = v->p + tw->trace.fraction * ( v->endp - v->p ); // if retrieving contacts if ( tw->getContacts ) { CM_AddContact( tw ); // no need to store the trm vertex more than once as a contact v->used = false; } } } /* ================ idCollisionModelManagerLocal::TranslatePointThroughPolygon ================ */ void idCollisionModelManagerLocal::TranslatePointThroughPolygon( cm_traceWork_t *tw, cm_polygon_t *poly, cm_trmVertex_t *v ) { int i, edgeNum; float f; cm_edge_t *edge; idPluecker pl; f = CM_TranslationPlaneFraction( poly->plane, v->p, v->endp ); if ( f < tw->trace.fraction ) { for ( i = 0; i < poly->numEdges; i++ ) { edgeNum = poly->edges[i]; edge = tw->model->edges + abs(edgeNum); // if we didn't yet calculate the sidedness for this edge if ( edge->checkcount != idCollisionModelManagerLocal::checkCount ) { float fl; edge->checkcount = idCollisionModelManagerLocal::checkCount; pl.FromLine(tw->model->vertices[edge->vertexNum[0]].p, tw->model->vertices[edge->vertexNum[1]].p); fl = v->pl.PermutedInnerProduct( pl ); edge->side = FLOATSIGNBITSET(fl); } // if the point passes the edge at the wrong side //if ( (edgeNum > 0) == edge->side ) { if ( INTSIGNBITSET(edgeNum) ^ edge->side ) { return; } } if ( f < 0.0f ) { f = 0.0f; } tw->trace.fraction = f; // collision plane is the polygon plane tw->trace.c.normal = poly->plane.Normal(); tw->trace.c.dist = poly->plane.Dist(); tw->trace.c.contents = poly->contents; tw->trace.c.material = poly->material; tw->trace.c.type = CONTACT_TRMVERTEX; tw->trace.c.modelFeature = *reinterpret_cast<int *>(&poly); tw->trace.c.trmFeature = v - tw->vertices; tw->trace.c.point = v->p + tw->trace.fraction * ( v->endp - v->p ); // if retrieving contacts if ( tw->getContacts ) { CM_AddContact( tw ); // no need to store the trm vertex more than once as a contact v->used = false; } } } /* ================ idCollisionModelManagerLocal::TranslateVertexThroughTrmPolygon ================ */ void idCollisionModelManagerLocal::TranslateVertexThroughTrmPolygon( cm_traceWork_t *tw, cm_trmPolygon_t *trmpoly, cm_polygon_t *poly, cm_vertex_t *v, idVec3 &endp, idPluecker &pl ) { int i, edgeNum; float f; cm_trmEdge_t *edge; f = CM_TranslationPlaneFraction( trmpoly->plane, v->p, endp ); if ( f < tw->trace.fraction ) { for ( i = 0; i < trmpoly->numEdges; i++ ) { edgeNum = trmpoly->edges[i]; edge = tw->edges + abs(edgeNum); CM_SetVertexSidedness( v, pl, edge->pl, edge->bitNum ); if ( INTSIGNBITSET(edgeNum) ^ ((v->side >> edge->bitNum) & 1) ) { return; } } if ( f < 0.0f ) { f = 0.0f; } tw->trace.fraction = f; // collision plane is the inverse trm polygon plane tw->trace.c.normal = -trmpoly->plane.Normal(); tw->trace.c.dist = -trmpoly->plane.Dist(); tw->trace.c.contents = poly->contents; tw->trace.c.material = poly->material; tw->trace.c.type = CONTACT_MODELVERTEX; tw->trace.c.modelFeature = v - tw->model->vertices; tw->trace.c.trmFeature = trmpoly - tw->polys; tw->trace.c.point = v->p + tw->trace.fraction * ( endp - v->p ); // if retrieving contacts if ( tw->getContacts ) { CM_AddContact( tw ); } } } /* ================ idCollisionModelManagerLocal::TranslateTrmThroughPolygon returns true if the polygon blocks the complete translation ================ */ bool idCollisionModelManagerLocal::TranslateTrmThroughPolygon( cm_traceWork_t *tw, cm_polygon_t *p ) { int i, j, k, edgeNum; float fraction, d; idVec3 endp; idPluecker *pl; cm_trmVertex_t *bv; cm_trmEdge_t *be; cm_trmPolygon_t *bp; cm_vertex_t *v; cm_edge_t *e; // if already checked this polygon if ( p->checkcount == idCollisionModelManagerLocal::checkCount ) { return false; } p->checkcount = idCollisionModelManagerLocal::checkCount; // if this polygon does not have the right contents behind it if ( !(p->contents & tw->contents) ) { return false; } // if the the trace bounds do not intersect the polygon bounds if ( !tw->bounds.IntersectsBounds( p->bounds ) ) { return false; } // only collide with the polygon if approaching at the front if ( ( p->plane.Normal() * tw->dir ) > 0.0f ) { return false; } // if the polygon is too far from the first heart plane d = p->bounds.PlaneDistance( tw->heartPlane1 ); if ( idMath::Fabs(d) > tw->maxDistFromHeartPlane1 ) { return false; } // if the polygon is too far from the second heart plane d = p->bounds.PlaneDistance( tw->heartPlane2 ); if ( idMath::Fabs(d) > tw->maxDistFromHeartPlane2 ) { return false; } fraction = tw->trace.fraction; // fast point trace if ( tw->pointTrace ) { idCollisionModelManagerLocal::TranslatePointThroughPolygon( tw, p, &tw->vertices[0] ); } else { // trace bounds should cross polygon plane switch ( tw->bounds.PlaneSide( p->plane ) ) { case PLANESIDE_CROSS: break; case PLANESIDE_FRONT: if ( tw->model->isConvex ) { tw->quickExit = true; return true; } default: return false; } // calculate pluecker coordinates for the polygon edges and polygon vertices for ( i = 0; i < p->numEdges; i++ ) { edgeNum = p->edges[i]; e = tw->model->edges + abs(edgeNum); // reset sidedness cache if this is the first time we encounter this edge during this trace if ( e->checkcount != idCollisionModelManagerLocal::checkCount ) { e->sideSet = 0; } // pluecker coordinate for edge tw->polygonEdgePlueckerCache[i].FromLine( tw->model->vertices[e->vertexNum[0]].p, tw->model->vertices[e->vertexNum[1]].p ); v = &tw->model->vertices[e->vertexNum[INTSIGNBITSET(edgeNum)]]; // reset sidedness cache if this is the first time we encounter this vertex during this trace if ( v->checkcount != idCollisionModelManagerLocal::checkCount ) { v->sideSet = 0; } // pluecker coordinate for vertex movement vector tw->polygonVertexPlueckerCache[i].FromRay( v->p, -tw->dir ); } // copy first to last so we can easily cycle through for the edges tw->polygonVertexPlueckerCache[p->numEdges] = tw->polygonVertexPlueckerCache[0]; // trace trm vertices through polygon for ( i = 0; i < tw->numVerts; i++ ) { bv = tw->vertices + i; if ( bv->used ) { idCollisionModelManagerLocal::TranslateTrmVertexThroughPolygon( tw, p, bv, i ); } } // trace trm edges through polygon for ( i = 1; i <= tw->numEdges; i++ ) { be = tw->edges + i; if ( be->used ) { idCollisionModelManagerLocal::TranslateTrmEdgeThroughPolygon( tw, p, be); } } // trace all polygon vertices through the trm for ( i = 0; i < p->numEdges; i++ ) { edgeNum = p->edges[i]; e = tw->model->edges + abs(edgeNum); if ( e->checkcount == idCollisionModelManagerLocal::checkCount ) { continue; } // set edge check count e->checkcount = idCollisionModelManagerLocal::checkCount; // can never collide with internal edges if ( e->internal ) { continue; } // got to check both vertices because we skip internal edges for ( k = 0; k < 2; k++ ) { v = tw->model->vertices + e->vertexNum[k ^ INTSIGNBITSET(edgeNum)]; // if this vertex is already checked if ( v->checkcount == idCollisionModelManagerLocal::checkCount ) { continue; } // set vertex check count v->checkcount = idCollisionModelManagerLocal::checkCount; // if the vertex is outside the trace bounds if ( !tw->bounds.ContainsPoint( v->p ) ) { continue; } // vertex end point after movement endp = v->p - tw->dir; // pluecker coordinate for vertex movement vector pl = &tw->polygonVertexPlueckerCache[i+k]; for ( j = 0; j < tw->numPolys; j++ ) { bp = tw->polys + j; if ( bp->used ) { idCollisionModelManagerLocal::TranslateVertexThroughTrmPolygon( tw, bp, p, v, endp, *pl ); } } } } } // if there was a collision with this polygon and we are not retrieving contacts if ( tw->trace.fraction < fraction && !tw->getContacts ) { fraction = tw->trace.fraction; endp = tw->start + fraction * tw->dir; // decrease bounds for ( i = 0; i < 3; i++ ) { if ( tw->start[i] < endp[i] ) { tw->bounds[0][i] = tw->start[i] + tw->size[0][i] - CM_BOX_EPSILON; tw->bounds[1][i] = endp[i] + tw->size[1][i] + CM_BOX_EPSILON; } else { tw->bounds[0][i] = endp[i] + tw->size[0][i] - CM_BOX_EPSILON; tw->bounds[1][i] = tw->start[i] + tw->size[1][i] + CM_BOX_EPSILON; } } } return ( tw->trace.fraction == 0.0f ); } /* ================ idCollisionModelManagerLocal::SetupTrm ================ */ void idCollisionModelManagerLocal::SetupTrm( cm_traceWork_t *tw, const idTraceModel *trm ) { int i, j; // vertices tw->numVerts = trm->numVerts; for ( i = 0; i < trm->numVerts; i++ ) { tw->vertices[i].p = trm->verts[i]; tw->vertices[i].used = false; } // edges tw->numEdges = trm->numEdges; for ( i = 1; i <= trm->numEdges; i++ ) { tw->edges[i].vertexNum[0] = trm->edges[i].v[0]; tw->edges[i].vertexNum[1] = trm->edges[i].v[1]; tw->edges[i].used = false; } // polygons tw->numPolys = trm->numPolys; for ( i = 0; i < trm->numPolys; i++ ) { tw->polys[i].numEdges = trm->polys[i].numEdges; for ( j = 0; j < trm->polys[i].numEdges; j++ ) { tw->polys[i].edges[j] = trm->polys[i].edges[j]; } tw->polys[i].plane.SetNormal( trm->polys[i].normal ); tw->polys[i].used = false; } // is the trace model convex or not tw->isConvex = trm->isConvex; } /* ================ idCollisionModelManagerLocal::SetupTranslationHeartPlanes ================ */ void idCollisionModelManagerLocal::SetupTranslationHeartPlanes( cm_traceWork_t *tw ) { idVec3 dir, normal1, normal2; // calculate trace heart planes dir = tw->dir; dir.Normalize(); dir.NormalVectors( normal1, normal2 ); tw->heartPlane1.SetNormal( normal1 ); tw->heartPlane1.FitThroughPoint( tw->start ); tw->heartPlane2.SetNormal( normal2 ); tw->heartPlane2.FitThroughPoint( tw->start ); } /* ================ idCollisionModelManagerLocal::Translation ================ */ #ifdef _DEBUG static int entered = 0; #endif void idCollisionModelManagerLocal::Translation( trace_t *results, const idVec3 &start, const idVec3 &end, const idTraceModel *trm, const idMat3 &trmAxis, int contentMask, CmHandle model, const idVec3 &modelOrigin, const idMat3 &modelAxis ) { int i, j; float dist; bool model_rotated, trm_rotated; idVec3 dir1, dir2, dir; idMat3 invModelAxis, tmpAxis; cm_trmPolygon_t *poly; cm_trmEdge_t *edge; cm_trmVertex_t *vert; ALIGN16( static cm_traceWork_t tw ); assert( ((byte *)&start) < ((byte *)results) || ((byte *)&start) >= (((byte *)results) + sizeof( trace_t )) ); assert( ((byte *)&end) < ((byte *)results) || ((byte *)&end) >= (((byte *)results) + sizeof( trace_t )) ); assert( ((byte *)&trmAxis) < ((byte *)results) || ((byte *)&trmAxis) >= (((byte *)results) + sizeof( trace_t )) ); memset( results, 0, sizeof( *results ) ); if ( model < 0 || model > MAX_SUBMODELS || model > idCollisionModelManagerLocal::maxModels ) { common->Printf("idCollisionModelManagerLocal::Translation: invalid model handle\n"); return; } if ( !idCollisionModelManagerLocal::models[model] ) { common->Printf("idCollisionModelManagerLocal::Translation: invalid model\n"); return; } // if case special position test if ( start[0] == end[0] && start[1] == end[1] && start[2] == end[2] ) { idCollisionModelManagerLocal::ContentsTrm( results, start, trm, trmAxis, contentMask, model, modelOrigin, modelAxis ); return; } #ifdef _DEBUG bool startsolid = false; // test whether or not stuck to begin with if ( cm_debugCollision.GetBool() ) { if ( !entered && !idCollisionModelManagerLocal::getContacts ) { entered = 1; // if already messed up to begin with if ( idCollisionModelManagerLocal::Contents( start, trm, trmAxis, -1, model, modelOrigin, modelAxis ) & contentMask ) { startsolid = true; } entered = 0; } } #endif idCollisionModelManagerLocal::checkCount++; tw.trace.fraction = 1.0f; tw.trace.c.contents = 0; tw.trace.c.type = CONTACT_NONE; tw.contents = contentMask; tw.isConvex = true; tw.rotation = false; tw.positionTest = false; tw.quickExit = false; tw.getContacts = idCollisionModelManagerLocal::getContacts; tw.contacts = idCollisionModelManagerLocal::contacts; tw.maxContacts = idCollisionModelManagerLocal::maxContacts; tw.numContacts = 0; tw.model = idCollisionModelManagerLocal::models[model]; tw.start = start - modelOrigin; tw.end = end - modelOrigin; tw.dir = end - start; model_rotated = modelAxis.IsRotated(); if ( model_rotated ) { invModelAxis = modelAxis.Transpose(); } // if optimized point trace if ( !trm || ( trm->bounds[1][0] - trm->bounds[0][0] <= 0.0f && trm->bounds[1][1] - trm->bounds[0][1] <= 0.0f && trm->bounds[1][2] - trm->bounds[0][2] <= 0.0f ) ) { if ( model_rotated ) { // rotate trace instead of model tw.start *= invModelAxis; tw.end *= invModelAxis; tw.dir *= invModelAxis; } // trace bounds for ( i = 0; i < 3; i++ ) { if ( tw.start[i] < tw.end[i] ) { tw.bounds[0][i] = tw.start[i] - CM_BOX_EPSILON; tw.bounds[1][i] = tw.end[i] + CM_BOX_EPSILON; } else { tw.bounds[0][i] = tw.end[i] - CM_BOX_EPSILON; tw.bounds[1][i] = tw.start[i] + CM_BOX_EPSILON; } } tw.extents[0] = tw.extents[1] = tw.extents[2] = CM_BOX_EPSILON; tw.size.Zero(); // setup trace heart planes idCollisionModelManagerLocal::SetupTranslationHeartPlanes( &tw ); tw.maxDistFromHeartPlane1 = CM_BOX_EPSILON; tw.maxDistFromHeartPlane2 = CM_BOX_EPSILON; // collision with single point tw.numVerts = 1; tw.vertices[0].p = tw.start; tw.vertices[0].endp = tw.vertices[0].p + tw.dir; tw.vertices[0].pl.FromRay( tw.vertices[0].p, tw.dir ); tw.numEdges = tw.numPolys = 0; tw.pointTrace = true; // trace through the model idCollisionModelManagerLocal::TraceThroughModel( &tw ); // store results *results = tw.trace; results->endpos = start + results->fraction * (end - start); results->endAxis = mat3_identity; if ( results->fraction < 1.0f ) { // rotate trace plane normal if there was a collision with a rotated model if ( model_rotated ) { results->c.normal *= modelAxis; results->c.point *= modelAxis; } results->c.point += modelOrigin; results->c.dist += modelOrigin * results->c.normal; } idCollisionModelManagerLocal::numContacts = tw.numContacts; return; } // the trace fraction is too inaccurate to describe translations over huge distances if ( tw.dir.LengthSqr() > Square( CM_MAX_TRACE_DIST ) ) { results->fraction = 0.0f; results->endpos = start; results->endAxis = trmAxis; results->c.normal = vec3_origin; results->c.material = NULL; results->c.point = start; if ( session->rw ) { session->rw->DebugArrow( colorRed, start, end, 1 ); } common->Printf( "idCollisionModelManagerLocal::Translation: huge translation\n" ); return; } tw.pointTrace = false; tw.size.Clear(); // setup trm structure idCollisionModelManagerLocal::SetupTrm( &tw, trm ); trm_rotated = trmAxis.IsRotated(); // calculate vertex positions if ( trm_rotated ) { for ( i = 0; i < tw.numVerts; i++ ) { // rotate trm around the start position tw.vertices[i].p *= trmAxis; } } for ( i = 0; i < tw.numVerts; i++ ) { // set trm at start position tw.vertices[i].p += tw.start; } if ( model_rotated ) { for ( i = 0; i < tw.numVerts; i++ ) { // rotate trm around model instead of rotating the model tw.vertices[i].p *= invModelAxis; } } // add offset to start point if ( trm_rotated ) { dir = trm->offset * trmAxis; tw.start += dir; tw.end += dir; } else { tw.start += trm->offset; tw.end += trm->offset; } if ( model_rotated ) { // rotate trace instead of model tw.start *= invModelAxis; tw.end *= invModelAxis; tw.dir *= invModelAxis; } // rotate trm polygon planes if ( trm_rotated & model_rotated ) { tmpAxis = trmAxis * invModelAxis; for ( poly = tw.polys, i = 0; i < tw.numPolys; i++, poly++ ) { poly->plane *= tmpAxis; } } else if ( trm_rotated ) { for ( poly = tw.polys, i = 0; i < tw.numPolys; i++, poly++ ) { poly->plane *= trmAxis; } } else if ( model_rotated ) { for ( poly = tw.polys, i = 0; i < tw.numPolys; i++, poly++ ) { poly->plane *= invModelAxis; } } // setup trm polygons for ( poly = tw.polys, i = 0; i < tw.numPolys; i++, poly++ ) { // if the trm poly plane is facing in the movement direction dist = poly->plane.Normal() * tw.dir; if ( dist > 0.0f || ( !trm->isConvex && dist == 0.0f ) ) { // this trm poly and it's edges and vertices need to be used for collision poly->used = true; for ( j = 0; j < poly->numEdges; j++ ) { edge = &tw.edges[abs( poly->edges[j] )]; edge->used = true; tw.vertices[edge->vertexNum[0]].used = true; tw.vertices[edge->vertexNum[1]].used = true; } } } // setup trm vertices for ( vert = tw.vertices, i = 0; i < tw.numVerts; i++, vert++ ) { if ( !vert->used ) { continue; } // get axial trm size after rotations tw.size.AddPoint( vert->p - tw.start ); // calculate the end position of each vertex for a full trace vert->endp = vert->p + tw.dir; // pluecker coordinate for vertex movement line vert->pl.FromRay( vert->p, tw.dir ); } // setup trm edges for ( edge = tw.edges + 1, i = 1; i <= tw.numEdges; i++, edge++ ) { if ( !edge->used ) { continue; } // edge start, end and pluecker coordinate edge->start = tw.vertices[edge->vertexNum[0]].p; edge->end = tw.vertices[edge->vertexNum[1]].p; edge->pl.FromLine( edge->start, edge->end ); // calculate normal of plane through movement plane created by the edge dir = edge->start - edge->end; edge->cross[0] = dir[0] * tw.dir[1] - dir[1] * tw.dir[0]; edge->cross[1] = dir[0] * tw.dir[2] - dir[2] * tw.dir[0]; edge->cross[2] = dir[1] * tw.dir[2] - dir[2] * tw.dir[1]; // bit for vertex sidedness bit cache edge->bitNum = i; } // set trm plane distances for ( poly = tw.polys, i = 0; i < tw.numPolys; i++, poly++ ) { if ( poly->used ) { poly->plane.FitThroughPoint( tw.edges[abs(poly->edges[0])].start ); } } // bounds for full trace, a little bit larger for epsilons for ( i = 0; i < 3; i++ ) { if ( tw.start[i] < tw.end[i] ) { tw.bounds[0][i] = tw.start[i] + tw.size[0][i] - CM_BOX_EPSILON; tw.bounds[1][i] = tw.end[i] + tw.size[1][i] + CM_BOX_EPSILON; } else { tw.bounds[0][i] = tw.end[i] + tw.size[0][i] - CM_BOX_EPSILON; tw.bounds[1][i] = tw.start[i] + tw.size[1][i] + CM_BOX_EPSILON; } if ( idMath::Fabs( tw.size[0][i] ) > idMath::Fabs( tw.size[1][i] ) ) { tw.extents[i] = idMath::Fabs( tw.size[0][i] ) + CM_BOX_EPSILON; } else { tw.extents[i] = idMath::Fabs( tw.size[1][i] ) + CM_BOX_EPSILON; } } // setup trace heart planes idCollisionModelManagerLocal::SetupTranslationHeartPlanes( &tw ); tw.maxDistFromHeartPlane1 = 0; tw.maxDistFromHeartPlane2 = 0; // calculate maximum trm vertex distance from both heart planes for ( vert = tw.vertices, i = 0; i < tw.numVerts; i++, vert++ ) { if ( !vert->used ) { continue; } dist = idMath::Fabs( tw.heartPlane1.Distance( vert->p ) ); if ( dist > tw.maxDistFromHeartPlane1 ) { tw.maxDistFromHeartPlane1 = dist; } dist = idMath::Fabs( tw.heartPlane2.Distance( vert->p ) ); if ( dist > tw.maxDistFromHeartPlane2 ) { tw.maxDistFromHeartPlane2 = dist; } } // for epsilons tw.maxDistFromHeartPlane1 += CM_BOX_EPSILON; tw.maxDistFromHeartPlane2 += CM_BOX_EPSILON; // trace through the model idCollisionModelManagerLocal::TraceThroughModel( &tw ); // if we're getting contacts if ( tw.getContacts ) { // move all contacts to world space if ( model_rotated ) { for ( i = 0; i < tw.numContacts; i++ ) { tw.contacts[i].normal *= modelAxis; tw.contacts[i].point *= modelAxis; } } if ( modelOrigin != vec3_origin ) { for ( i = 0; i < tw.numContacts; i++ ) { tw.contacts[i].point += modelOrigin; tw.contacts[i].dist += modelOrigin * tw.contacts[i].normal; } } idCollisionModelManagerLocal::numContacts = tw.numContacts; } else { // store results *results = tw.trace; results->endpos = start + results->fraction * ( end - start ); results->endAxis = trmAxis; if ( results->fraction < 1.0f ) { // if the fraction is tiny the actual movement could end up zero if ( results->fraction > 0.0f && results->endpos.Compare( start ) ) { results->fraction = 0.0f; } // rotate trace plane normal if there was a collision with a rotated model if ( model_rotated ) { results->c.normal *= modelAxis; results->c.point *= modelAxis; } results->c.point += modelOrigin; results->c.dist += modelOrigin * results->c.normal; } } #ifdef _DEBUG // test for missed collisions if ( cm_debugCollision.GetBool() ) { if ( !entered && !idCollisionModelManagerLocal::getContacts ) { entered = 1; // if the trm is stuck in the model if ( idCollisionModelManagerLocal::Contents( results->endpos, trm, trmAxis, -1, model, modelOrigin, modelAxis ) & contentMask ) { trace_t tr; // test where the trm is stuck in the model idCollisionModelManagerLocal::Contents( results->endpos, trm, trmAxis, -1, model, modelOrigin, modelAxis ); // re-run collision detection to find out where it failed idCollisionModelManagerLocal::Translation( &tr, start, end, trm, trmAxis, contentMask, model, modelOrigin, modelAxis ); } entered = 0; } } #endif } } }
// // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR // PURPOSE. IT CAN BE DISTRIBUTED FREE OF CHARGE AS LONG AS THIS HEADER // REMAINS UNCHANGED. // // Email: [email protected] // // Copyright (C) 2002-2003 Idael Cardoso. // // LAME ( LAME Ain't an Mp3 Encoder ) // You must call the fucntion "beVersion" to obtain information like version // numbers (both of the DLL and encoding engine), release date and URL for // lame_enc's homepage. All this information should be made available to the // user of your product through a dialog box or something similar. // You must see all information about LAME project and legal license infos at // http://www.mp3dev.org/ The official LAME site // // // About Thomson and/or Fraunhofer patents: // Any use of this product does not convey a license under the relevant // intellectual property of Thomson and/or Fraunhofer Gesellschaft nor imply // any right to use this product in any finished end user or ready-to-use final // product. An independent license for such use is required. // For details, please visit http://www.mp3licensing.com. // using System; using System.Runtime.InteropServices; using System.Runtime.Serialization; using WaveLib; namespace Yeti.Lame { public enum VBRMETHOD : int { VBR_METHOD_NONE = -1, VBR_METHOD_DEFAULT = 0, VBR_METHOD_OLD = 1, VBR_METHOD_NEW = 2, VBR_METHOD_MTRH = 3, VBR_METHOD_ABR = 4 } /* MPEG modes */ public enum MpegMode : uint { STEREO = 0, JOINT_STEREO, DUAL_CHANNEL, /* LAME doesn't supports this! */ MONO, NOT_SET, MAX_INDICATOR /* Don't use this! It's used for sanity checks. */ } public enum LAME_QUALITY_PRESET : int { LQP_NOPRESET =-1, // QUALITY PRESETS LQP_NORMAL_QUALITY = 0, LQP_LOW_QUALITY = 1, LQP_HIGH_QUALITY = 2, LQP_VOICE_QUALITY = 3, LQP_R3MIX = 4, LQP_VERYHIGH_QUALITY = 5, LQP_STANDARD = 6, LQP_FAST_STANDARD = 7, LQP_EXTREME = 8, LQP_FAST_EXTREME = 9, LQP_INSANE = 10, LQP_ABR = 11, LQP_CBR = 12, LQP_MEDIUM = 13, LQP_FAST_MEDIUM = 14, // NEW PRESET VALUES LQP_PHONE =1000, LQP_SW =2000, LQP_AM =3000, LQP_FM =4000, LQP_VOICE =5000, LQP_RADIO =6000, LQP_TAPE =7000, LQP_HIFI =8000, LQP_CD =9000, LQP_STUDIO =10000 } [StructLayout(LayoutKind.Sequential), Serializable] public struct MP3 //BE_CONFIG_MP3 { public uint dwSampleRate; // 48000, 44100 and 32000 allowed public byte byMode; // BE_MP3_MODE_STEREO, BE_MP3_MODE_DUALCHANNEL, BE_MP3_MODE_MONO public ushort wBitrate; // 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256 and 320 allowed public int bPrivate; public int bCRC; public int bCopyright; public int bOriginal; } [StructLayout(LayoutKind.Sequential, Size=327), Serializable] public struct LHV1 // BE_CONFIG_LAME LAME header version 1 { public const uint MPEG1 = 1; public const uint MPEG2 = 0; // STRUCTURE INFORMATION public uint dwStructVersion; public uint dwStructSize; // BASIC ENCODER SETTINGS public uint dwSampleRate; // SAMPLERATE OF INPUT FILE public uint dwReSampleRate; // DOWNSAMPLERATE, 0=ENCODER DECIDES public MpegMode nMode; // STEREO, MONO public uint dwBitrate; // CBR bitrate, VBR min bitrate public uint dwMaxBitrate; // CBR ignored, VBR Max bitrate public LAME_QUALITY_PRESET nPreset; // Quality preset public uint dwMpegVersion; // MPEG-1 OR MPEG-2 public uint dwPsyModel; // FUTURE USE, SET TO 0 public uint dwEmphasis; // FUTURE USE, SET TO 0 // BIT STREAM SETTINGS public int bPrivate; // Set Private Bit (TRUE/FALSE) public int bCRC; // Insert CRC (TRUE/FALSE) public int bCopyright; // Set Copyright Bit (TRUE/FALSE) public int bOriginal; // Set Original Bit (TRUE/FALSE) // VBR STUFF public int bWriteVBRHeader; // WRITE XING VBR HEADER (TRUE/FALSE) public int bEnableVBR; // USE VBR ENCODING (TRUE/FALSE) public int nVBRQuality; // VBR QUALITY 0..9 public uint dwVbrAbr_bps; // Use ABR in stead of nVBRQuality public VBRMETHOD nVbrMethod; public int bNoRes; // Disable Bit resorvoir (TRUE/FALSE) // MISC SETTINGS public int bStrictIso; // Use strict ISO encoding rules (TRUE/FALSE) public ushort nQuality; // Quality Setting, HIGH BYTE should be NOT LOW byte, otherwhise quality=5 // FUTURE USE, SET TO 0, align strucutre to 331 bytes //[ MarshalAs( UnmanagedType.ByValArray, SizeConst=255-4*4-2 )] //public byte[] btReserved;//[255-4*sizeof(DWORD) - sizeof( WORD )]; public LHV1(WaveFormat format, uint MpeBitRate) { if ( format.wFormatTag != (short)WaveFormats.Pcm ) { throw new ArgumentOutOfRangeException("format", "Only PCM format supported"); } if ( format.wBitsPerSample != 16) { throw new ArgumentOutOfRangeException("format", "Only 16 bits samples supported"); } dwStructVersion = 1; dwStructSize = (uint)Marshal.SizeOf(typeof(BE_CONFIG)); switch (format.nSamplesPerSec) { case 16000 : case 22050 : case 24000 : dwMpegVersion = MPEG2; break; case 32000 : case 44100 : case 48000 : dwMpegVersion = MPEG1; break; default : throw new ArgumentOutOfRangeException("format", "Unsupported sample rate"); } dwSampleRate = (uint)format.nSamplesPerSec; // INPUT FREQUENCY dwReSampleRate = 0; // DON'T RESAMPLE switch (format.nChannels) { case 1 : nMode = MpegMode.MONO; break; case 2 : nMode = MpegMode.STEREO; break; default: throw new ArgumentOutOfRangeException("format", "Invalid number of channels"); } switch (MpeBitRate) { case 32 : case 40 : case 48 : case 56 : case 64 : case 80 : case 96 : case 112 : case 128 : case 160 : //Allowed bit rates in MPEG1 and MPEG2 break; case 192 : case 224 : case 256 : case 320 : //Allowed only in MPEG1 if (dwMpegVersion != MPEG1) { throw new ArgumentOutOfRangeException("MpsBitRate", "Bit rate not compatible with input format"); } break; case 8 : case 16 : case 24 : case 144 : //Allowed only in MPEG2 if (dwMpegVersion != MPEG2) { throw new ArgumentOutOfRangeException("MpsBitRate", "Bit rate not compatible with input format"); } break; default : throw new ArgumentOutOfRangeException("MpsBitRate", "Unsupported bit rate"); } dwBitrate = MpeBitRate; // MINIMUM BIT RATE nPreset = LAME_QUALITY_PRESET.LQP_NORMAL_QUALITY; // QUALITY PRESET SETTING dwPsyModel = 0; // USE DEFAULT PSYCHOACOUSTIC MODEL dwEmphasis = 0; // NO EMPHASIS TURNED ON bOriginal = 1; // SET ORIGINAL FLAG bWriteVBRHeader = 0; bNoRes = 0; // No Bit resorvoir bCopyright = 0; bCRC = 0; bEnableVBR = 0; bPrivate = 0; bStrictIso = 0; dwMaxBitrate = 0; dwVbrAbr_bps = 0; nQuality = 0; nVbrMethod = VBRMETHOD.VBR_METHOD_NONE; nVBRQuality = 0; } } [StructLayout(LayoutKind.Sequential), Serializable] public struct ACC { public uint dwSampleRate; public byte byMode; public ushort wBitrate; public byte byEncodingMethod; } [StructLayout(LayoutKind.Explicit), Serializable] public class Format { [FieldOffset(0)] public MP3 mp3; [FieldOffset(0)] public LHV1 lhv1; [FieldOffset(0)] public ACC acc; public Format(WaveFormat format, uint MpeBitRate) { lhv1 = new LHV1(format, MpeBitRate); } } [StructLayout(LayoutKind.Sequential), Serializable] public class BE_CONFIG { // encoding formats public const uint BE_CONFIG_MP3 = 0; public const uint BE_CONFIG_LAME = 256; public uint dwConfig; public Format format; public BE_CONFIG(WaveFormat format, uint MpeBitRate) { this.dwConfig = BE_CONFIG_LAME; this.format = new Format(format, MpeBitRate); } public BE_CONFIG(WaveFormat format) : this(format, 128) { } } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)] public class BE_VERSION { public const uint BE_MAX_HOMEPAGE = 256; public byte byDLLMajorVersion; public byte byDLLMinorVersion; public byte byMajorVersion; public byte byMinorVersion; // DLL Release date public byte byDay; public byte byMonth; public ushort wYear; //Homepage URL [MarshalAs(UnmanagedType.ByValTStr, SizeConst=257/*BE_MAX_HOMEPAGE+1*/)] public string zHomepage; public byte byAlphaLevel; public byte byBetaLevel; public byte byMMXEnabled; [MarshalAs(UnmanagedType.ByValArray, SizeConst=125)] public byte[] btReserved; public BE_VERSION() { btReserved = new byte[125]; } } /// <summary> /// Lame_enc DLL functions /// </summary> public class Lame_encDll { //Error codes public const uint BE_ERR_SUCCESSFUL = 0; public const uint BE_ERR_INVALID_FORMAT = 1; public const uint BE_ERR_INVALID_FORMAT_PARAMETERS = 2; public const uint BE_ERR_NO_MORE_HANDLES = 3; public const uint BE_ERR_INVALID_HANDLE = 4; /// <summary> /// This function is the first to call before starting an encoding stream. /// </summary> /// <param name="pbeConfig">Encoder settings</param> /// <param name="dwSamples">Receives the number of samples (not bytes, each sample is a SHORT) to send to each beEncodeChunk() on return.</param> /// <param name="dwBufferSize">Receives the minimun number of bytes that must have the output(result) buffer</param> /// <param name="phbeStream">Receives the stream handle on return</param> /// <returns>On success: BE_ERR_SUCCESSFUL</returns> [DllImport("Lame_enc.dll")] public static extern uint beInitStream(BE_CONFIG pbeConfig, ref uint dwSamples, ref uint dwBufferSize, ref uint phbeStream); /// <summary> /// Encodes a chunk of samples. Please note that if you have set the output to /// generate mono MP3 files you must feed beEncodeChunk() with mono samples /// </summary> /// <param name="hbeStream">Handle of the stream.</param> /// <param name="nSamples">Number of samples to be encoded for this call. /// This should be identical to what is returned by beInitStream(), /// unless you are encoding the last chunk, which might be smaller.</param> /// <param name="pInSamples">Array of 16-bit signed samples to be encoded. /// These should be in stereo when encoding a stereo MP3 /// and mono when encoding a mono MP3</param> /// <param name="pOutput">Buffer where to write the encoded data. /// This buffer should be at least of the minimum size returned by beInitStream().</param> /// <param name="pdwOutput">Returns the number of bytes of encoded data written. /// The amount of data written might vary from chunk to chunk</param> /// <returns>On success: BE_ERR_SUCCESSFUL</returns> [DllImport("Lame_enc.dll")] public static extern uint beEncodeChunk(uint hbeStream, uint nSamples, short[] pInSamples, [In, Out] byte[] pOutput, ref uint pdwOutput); /// <summary> /// Encodes a chunk of samples. Please note that if you have set the output to /// generate mono MP3 files you must feed beEncodeChunk() with mono samples /// </summary> /// <param name="hbeStream">Handle of the stream.</param> /// <param name="nSamples">Number of samples to be encoded for this call. /// This should be identical to what is returned by beInitStream(), /// unless you are encoding the last chunk, which might be smaller.</param> /// <param name="pSamples">Pointer at the 16-bit signed samples to be encoded. /// InPtr is used to pass any type of array without need of make memory copy, /// then gaining in performance. Note that nSamples is not the number of bytes, /// but samples (is sample is a SHORT)</param> /// <param name="pOutput">Buffer where to write the encoded data. /// This buffer should be at least of the minimum size returned by beInitStream().</param> /// <param name="pdwOutput">Returns the number of bytes of encoded data written. /// The amount of data written might vary from chunk to chunk</param> /// <returns>On success: BE_ERR_SUCCESSFUL</returns> [DllImport("Lame_enc.dll")] protected static extern uint beEncodeChunk(uint hbeStream, uint nSamples, IntPtr pSamples, [In, Out] byte[] pOutput, ref uint pdwOutput); /// <summary> /// Encodes a chunk of samples. Samples are contained in a byte array /// </summary> /// <param name="hbeStream">Handle of the stream.</param> /// <param name="buffer">Bytes to encode</param> /// <param name="index">Position of the first byte to encode</param> /// <param name="nBytes">Number of bytes to encode (not samples, samples are two byte lenght)</param> /// <param name="pOutput">Buffer where to write the encoded data. /// This buffer should be at least of the minimum size returned by beInitStream().</param> /// <param name="pdwOutput">Returns the number of bytes of encoded data written. /// The amount of data written might vary from chunk to chunk</param> /// <returns>On success: BE_ERR_SUCCESSFUL</returns> public static uint EncodeChunk(uint hbeStream, byte[] buffer, int index, uint nBytes, byte[] pOutput, ref uint pdwOutput) { uint res; GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { IntPtr ptr = (IntPtr)(handle.AddrOfPinnedObject().ToInt32()+index); res = beEncodeChunk(hbeStream, nBytes/2/*Samples*/, ptr, pOutput, ref pdwOutput); } finally { handle.Free(); } return res; } /// <summary> /// Encodes a chunk of samples. Samples are contained in a byte array /// </summary> /// <param name="hbeStream">Handle of the stream.</param> /// <param name="buffer">Bytes to encode</param> /// <param name="pOutput">Buffer where to write the encoded data. /// This buffer should be at least of the minimum size returned by beInitStream().</param> /// <param name="pdwOutput">Returns the number of bytes of encoded data written. /// The amount of data written might vary from chunk to chunk</param> /// <returns>On success: BE_ERR_SUCCESSFUL</returns> public static uint EncodeChunk(uint hbeStream, byte[] buffer, byte[] pOutput, ref uint pdwOutput) { return EncodeChunk(hbeStream, buffer, 0, (uint)buffer.Length, pOutput, ref pdwOutput); } /// <summary> /// This function should be called after encoding the last chunk in order to flush /// the encoder. It writes any encoded data that still might be left inside the /// encoder to the output buffer. This function should NOT be called unless /// you have encoded all of the chunks in your stream. /// </summary> /// <param name="hbeStream">Handle of the stream.</param> /// <param name="pOutput">Where to write the encoded data. This buffer should be /// at least of the minimum size returned by beInitStream().</param> /// <param name="pdwOutput">Returns number of bytes of encoded data written.</param> /// <returns>On success: BE_ERR_SUCCESSFUL</returns> [DllImport("Lame_enc.dll")] public static extern uint beDeinitStream(uint hbeStream, [In, Out] byte[] pOutput, ref uint pdwOutput); /// <summary> /// Last function to be called when finished encoding a stream. /// Should unlike beDeinitStream() also be called if the encoding is canceled. /// </summary> /// <param name="hbeStream">Handle of the stream.</param> /// <returns>On success: BE_ERR_SUCCESSFUL</returns> [DllImport("Lame_enc.dll")] public static extern uint beCloseStream(uint hbeStream); /// <summary> /// Returns information like version numbers (both of the DLL and encoding engine), /// release date and URL for lame_enc's homepage. /// All this information should be made available to the user of your product /// through a dialog box or something similar. /// </summary> /// <param name="pbeVersion"Where version number, release date and URL for homepage /// is returned.</param> [DllImport("Lame_enc.dll")] public static extern void beVersion([Out] BE_VERSION pbeVersion); [DllImport("Lame_enc.dll", CharSet=CharSet.Ansi)] public static extern void beWriteVBRHeader(string pszMP3FileName); [DllImport("Lame_enc.dll")] public static extern uint beEncodeChunkFloatS16NI(uint hbeStream, uint nSamples, [In]float[] buffer_l, [In]float[] buffer_r, [In, Out]byte[] pOutput, ref uint pdwOutput); [DllImport("Lame_enc.dll")] public static extern uint beFlushNoGap(uint hbeStream, [In, Out]byte[] pOutput, ref uint pdwOutput); [DllImport("Lame_enc.dll", CharSet=CharSet.Ansi)] public static extern uint beWriteInfoTag(uint hbeStream, string lpszFileName); } }
namespace Trionic5Controls { partial class frmTuningSettings { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.groupControl1 = new DevExpress.XtraEditors.GroupControl(); this.comboBoxEdit1 = new DevExpress.XtraEditors.ComboBoxEdit(); this.comboBoxEdit2 = new DevExpress.XtraEditors.ComboBoxEdit(); this.spinEdit1 = new DevExpress.XtraEditors.SpinEdit(); this.labelControl1 = new DevExpress.XtraEditors.LabelControl(); this.labelControl2 = new DevExpress.XtraEditors.LabelControl(); this.labelControl3 = new DevExpress.XtraEditors.LabelControl(); this.labelControl4 = new DevExpress.XtraEditors.LabelControl(); this.labelControl5 = new DevExpress.XtraEditors.LabelControl(); this.labelControl6 = new DevExpress.XtraEditors.LabelControl(); this.comboBoxEdit3 = new DevExpress.XtraEditors.ComboBoxEdit(); this.checkEdit1 = new DevExpress.XtraEditors.CheckEdit(); this.labelControl7 = new DevExpress.XtraEditors.LabelControl(); this.spinEdit2 = new DevExpress.XtraEditors.SpinEdit(); this.spinEdit3 = new DevExpress.XtraEditors.SpinEdit(); this.spinEdit4 = new DevExpress.XtraEditors.SpinEdit(); this.simpleButton1 = new DevExpress.XtraEditors.SimpleButton(); this.simpleButton2 = new DevExpress.XtraEditors.SimpleButton(); ((System.ComponentModel.ISupportInitialize)(this.groupControl1)).BeginInit(); this.groupControl1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.comboBoxEdit1.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.comboBoxEdit2.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.spinEdit1.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.comboBoxEdit3.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.checkEdit1.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.spinEdit2.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.spinEdit3.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.spinEdit4.Properties)).BeginInit(); this.SuspendLayout(); // // groupControl1 // this.groupControl1.Controls.Add(this.spinEdit4); this.groupControl1.Controls.Add(this.spinEdit3); this.groupControl1.Controls.Add(this.spinEdit2); this.groupControl1.Controls.Add(this.labelControl7); this.groupControl1.Controls.Add(this.checkEdit1); this.groupControl1.Controls.Add(this.labelControl6); this.groupControl1.Controls.Add(this.comboBoxEdit3); this.groupControl1.Controls.Add(this.labelControl5); this.groupControl1.Controls.Add(this.labelControl4); this.groupControl1.Controls.Add(this.labelControl3); this.groupControl1.Controls.Add(this.labelControl2); this.groupControl1.Controls.Add(this.labelControl1); this.groupControl1.Controls.Add(this.spinEdit1); this.groupControl1.Controls.Add(this.comboBoxEdit2); this.groupControl1.Controls.Add(this.comboBoxEdit1); this.groupControl1.Location = new System.Drawing.Point(8, 10); this.groupControl1.Name = "groupControl1"; this.groupControl1.Size = new System.Drawing.Size(433, 248); this.groupControl1.TabIndex = 0; this.groupControl1.Text = "Tuning parameters"; // // comboBoxEdit1 // this.comboBoxEdit1.EditValue = "Stock"; this.comboBoxEdit1.Location = new System.Drawing.Point(164, 35); this.comboBoxEdit1.Name = "comboBoxEdit1"; this.comboBoxEdit1.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)}); this.comboBoxEdit1.Properties.Items.AddRange(new object[] { "Stock", "TD04-15T", "TD04-19T", "GT28BB", "GT28RS", "GT3071R", "HX35w", "HX40w"}); this.comboBoxEdit1.Size = new System.Drawing.Size(244, 20); this.comboBoxEdit1.TabIndex = 0; // // comboBoxEdit2 // this.comboBoxEdit2.EditValue = "Stock"; this.comboBoxEdit2.Location = new System.Drawing.Point(164, 61); this.comboBoxEdit2.Name = "comboBoxEdit2"; this.comboBoxEdit2.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)}); this.comboBoxEdit2.Properties.Items.AddRange(new object[] { "Stock", "Green Giants", "Siemens 630cc Dekas", "Siemens 875cc Dekas", "Siemens 1000cc"}); this.comboBoxEdit2.Size = new System.Drawing.Size(244, 20); this.comboBoxEdit2.TabIndex = 1; // // spinEdit1 // this.spinEdit1.EditValue = new decimal(new int[] { 145, 0, 0, 131072}); this.spinEdit1.Location = new System.Drawing.Point(164, 113); this.spinEdit1.Name = "spinEdit1"; this.spinEdit1.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton()}); this.spinEdit1.Properties.Increment = new decimal(new int[] { 1, 0, 0, 65536}); this.spinEdit1.Properties.MaxValue = new decimal(new int[] { 3, 0, 0, 0}); this.spinEdit1.Size = new System.Drawing.Size(244, 20); this.spinEdit1.TabIndex = 2; // // labelControl1 // this.labelControl1.Location = new System.Drawing.Point(33, 42); this.labelControl1.Name = "labelControl1"; this.labelControl1.Size = new System.Drawing.Size(28, 13); this.labelControl1.TabIndex = 5; this.labelControl1.Text = "Turbo"; // // labelControl2 // this.labelControl2.Location = new System.Drawing.Point(33, 68); this.labelControl2.Name = "labelControl2"; this.labelControl2.Size = new System.Drawing.Size(43, 13); this.labelControl2.TabIndex = 6; this.labelControl2.Text = "Injectors"; // // labelControl3 // this.labelControl3.Location = new System.Drawing.Point(33, 120); this.labelControl3.Name = "labelControl3"; this.labelControl3.Size = new System.Drawing.Size(53, 13); this.labelControl3.TabIndex = 7; this.labelControl3.Text = "Peak boost"; // // labelControl4 // this.labelControl4.Location = new System.Drawing.Point(33, 146); this.labelControl4.Name = "labelControl4"; this.labelControl4.Size = new System.Drawing.Size(91, 13); this.labelControl4.TabIndex = 8; this.labelControl4.Text = "Boost limit 1st gear"; // // labelControl5 // this.labelControl5.Location = new System.Drawing.Point(33, 172); this.labelControl5.Name = "labelControl5"; this.labelControl5.Size = new System.Drawing.Size(94, 13); this.labelControl5.TabIndex = 9; this.labelControl5.Text = "Boost limit 2nd gear"; // // labelControl6 // this.labelControl6.Location = new System.Drawing.Point(33, 94); this.labelControl6.Name = "labelControl6"; this.labelControl6.Size = new System.Drawing.Size(56, 13); this.labelControl6.TabIndex = 11; this.labelControl6.Text = "MAP sensor"; // // comboBoxEdit3 // this.comboBoxEdit3.EditValue = "MapSensor 2.5 bar"; this.comboBoxEdit3.Location = new System.Drawing.Point(164, 87); this.comboBoxEdit3.Name = "comboBoxEdit3"; this.comboBoxEdit3.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)}); this.comboBoxEdit3.Properties.Items.AddRange(new object[] { "MapSensor 2.5 bar", "MapSensor 3.0 bar", "MapSensor 3.5 bar", "MapSensor 4.0 bar"}); this.comboBoxEdit3.Size = new System.Drawing.Size(244, 20); this.comboBoxEdit3.TabIndex = 10; // // checkEdit1 // this.checkEdit1.Location = new System.Drawing.Point(162, 217); this.checkEdit1.Name = "checkEdit1"; this.checkEdit1.Properties.Caption = "Always run in open loop "; this.checkEdit1.Size = new System.Drawing.Size(246, 20); this.checkEdit1.TabIndex = 12; // // labelControl7 // this.labelControl7.Location = new System.Drawing.Point(33, 198); this.labelControl7.Name = "labelControl7"; this.labelControl7.Size = new System.Drawing.Size(63, 13); this.labelControl7.TabIndex = 14; this.labelControl7.Text = "Fuel cut level"; // // spinEdit2 // this.spinEdit2.EditValue = new decimal(new int[] { 5, 0, 0, 65536}); this.spinEdit2.Location = new System.Drawing.Point(164, 139); this.spinEdit2.Name = "spinEdit2"; this.spinEdit2.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton()}); this.spinEdit2.Properties.Increment = new decimal(new int[] { 1, 0, 0, 65536}); this.spinEdit2.Properties.MaxValue = new decimal(new int[] { 3, 0, 0, 0}); this.spinEdit2.Size = new System.Drawing.Size(244, 20); this.spinEdit2.TabIndex = 15; // // spinEdit3 // this.spinEdit3.EditValue = new decimal(new int[] { 12, 0, 0, 65536}); this.spinEdit3.Location = new System.Drawing.Point(164, 165); this.spinEdit3.Name = "spinEdit3"; this.spinEdit3.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton()}); this.spinEdit3.Properties.Increment = new decimal(new int[] { 1, 0, 0, 65536}); this.spinEdit3.Properties.MaxValue = new decimal(new int[] { 3, 0, 0, 0}); this.spinEdit3.Size = new System.Drawing.Size(244, 20); this.spinEdit3.TabIndex = 16; // // spinEdit4 // this.spinEdit4.EditValue = new decimal(new int[] { 155, 0, 0, 131072}); this.spinEdit4.Location = new System.Drawing.Point(164, 191); this.spinEdit4.Name = "spinEdit4"; this.spinEdit4.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton()}); this.spinEdit4.Properties.Increment = new decimal(new int[] { 1, 0, 0, 65536}); this.spinEdit4.Properties.MaxValue = new decimal(new int[] { 3, 0, 0, 0}); this.spinEdit4.Size = new System.Drawing.Size(244, 20); this.spinEdit4.TabIndex = 17; // // simpleButton1 // this.simpleButton1.Location = new System.Drawing.Point(366, 264); this.simpleButton1.Name = "simpleButton1"; this.simpleButton1.Size = new System.Drawing.Size(75, 23); this.simpleButton1.TabIndex = 1; this.simpleButton1.Text = "Ok"; this.simpleButton1.Click += new System.EventHandler(this.simpleButton1_Click); // // simpleButton2 // this.simpleButton2.Location = new System.Drawing.Point(285, 264); this.simpleButton2.Name = "simpleButton2"; this.simpleButton2.Size = new System.Drawing.Size(75, 23); this.simpleButton2.TabIndex = 2; this.simpleButton2.Text = "Cancel"; this.simpleButton2.Click += new System.EventHandler(this.simpleButton2_Click); // // frmTuningSettings // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(452, 296); this.ControlBox = false; this.Controls.Add(this.simpleButton2); this.Controls.Add(this.simpleButton1); this.Controls.Add(this.groupControl1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Name = "frmTuningSettings"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Tune to stage \'X\'"; ((System.ComponentModel.ISupportInitialize)(this.groupControl1)).EndInit(); this.groupControl1.ResumeLayout(false); this.groupControl1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.comboBoxEdit1.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.comboBoxEdit2.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.spinEdit1.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.comboBoxEdit3.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.checkEdit1.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.spinEdit2.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.spinEdit3.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.spinEdit4.Properties)).EndInit(); this.ResumeLayout(false); } #endregion private DevExpress.XtraEditors.GroupControl groupControl1; private DevExpress.XtraEditors.LabelControl labelControl5; private DevExpress.XtraEditors.LabelControl labelControl4; private DevExpress.XtraEditors.LabelControl labelControl3; private DevExpress.XtraEditors.LabelControl labelControl2; private DevExpress.XtraEditors.LabelControl labelControl1; private DevExpress.XtraEditors.SpinEdit spinEdit1; private DevExpress.XtraEditors.ComboBoxEdit comboBoxEdit2; private DevExpress.XtraEditors.ComboBoxEdit comboBoxEdit1; private DevExpress.XtraEditors.LabelControl labelControl6; private DevExpress.XtraEditors.ComboBoxEdit comboBoxEdit3; private DevExpress.XtraEditors.CheckEdit checkEdit1; private DevExpress.XtraEditors.LabelControl labelControl7; private DevExpress.XtraEditors.SpinEdit spinEdit4; private DevExpress.XtraEditors.SpinEdit spinEdit3; private DevExpress.XtraEditors.SpinEdit spinEdit2; private DevExpress.XtraEditors.SimpleButton simpleButton1; private DevExpress.XtraEditors.SimpleButton simpleButton2; } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Messages.Messages File: InMemoryMessageChannel.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Messages { using System; using System.Collections.Generic; using System.Globalization; using Ecng.Collections; using Ecng.Common; using StockSharp.Localization; using StockSharp.Logging; /// <summary> /// Message channel, based on the queue and operate within a single process. /// </summary> public class InMemoryMessageChannel : Cloneable<IMessageChannel>, IMessageChannel { private class BlockingPriorityQueue : BaseBlockingQueue<KeyValuePair<DateTimeOffset, Message>, OrderedPriorityQueue<DateTimeOffset, Message>> { public BlockingPriorityQueue() : base(new OrderedPriorityQueue<DateTimeOffset, Message>()) { } protected override void OnEnqueue(KeyValuePair<DateTimeOffset, Message> item, bool force) { InnerCollection.Enqueue(item.Key, item.Value); } protected override KeyValuePair<DateTimeOffset, Message> OnDequeue() { return InnerCollection.Dequeue(); } protected override KeyValuePair<DateTimeOffset, Message> OnPeek() { return InnerCollection.Peek(); } } private static readonly MemoryStatisticsValue<Message> _msgStat = new MemoryStatisticsValue<Message>(LocalizedStrings.Messages); static InMemoryMessageChannel() { MemoryStatistics.Instance.Values.Add(_msgStat); } private readonly Action<Exception> _errorHandler; private readonly Action<Message> _initMessage; private readonly BlockingPriorityQueue _messageQueue = new BlockingPriorityQueue(); /// <summary> /// Initializes a new instance of the <see cref="InMemoryMessageChannel"/>. /// </summary> /// <param name="name">Channel name.</param> /// <param name="errorHandler">Error handler.</param> /// <param name="initMessage"> default: null</param> public InMemoryMessageChannel(string name, Action<Exception> errorHandler, Action<Message> initMessage = null) { if (name.IsEmpty()) throw new ArgumentNullException(nameof(name)); if (errorHandler == null) throw new ArgumentNullException(nameof(errorHandler)); Name = name; _errorHandler = errorHandler; _initMessage = initMessage; _messageQueue.Close(); } /// <summary> /// Handler name. /// </summary> public string Name { get; } /// <summary> /// Message queue count. /// </summary> public int MessageCount => _messageQueue.Count; /// <summary> /// Max message queue count. /// </summary> /// <remarks> /// The default value is -1, which corresponds to the size without limitations. /// </remarks> public int MaxMessageCount { get { return _messageQueue.MaxSize; } set { _messageQueue.MaxSize = value; } } /// <summary> /// Channel closing event. /// </summary> public event Action Closed; /// <summary> /// Is channel opened. /// </summary> public bool IsOpened => !_messageQueue.IsClosed; /// <summary> /// Open channel. /// </summary> public void Open() { _messageQueue.Open(); ThreadingHelper .Thread(() => CultureInfo.InvariantCulture.DoInCulture(() => { while (!_messageQueue.IsClosed) { try { KeyValuePair<DateTimeOffset, Message> pair; if (!_messageQueue.TryDequeue(out pair)) { break; } //if (!(message is TimeMessage) && message.GetType().Name != "BasketMessage") // Console.WriteLine("<< ({0}) {1}", System.Threading.Thread.CurrentThread.Name, message); _msgStat.Remove(pair.Value); NewOutMessage.SafeInvoke(pair.Value); } catch (Exception ex) { _errorHandler(ex); } } Closed.SafeInvoke(); })) .Name("{0} channel thread.".Put(Name)) //.Culture(CultureInfo.InvariantCulture) .Launch(); } /// <summary> /// Close channel. /// </summary> public void Close() { _messageQueue.Close(); } /// <summary> /// Send message. /// </summary> /// <param name="message">Message.</param> public void SendInMessage(Message message) { if (!IsOpened) throw new InvalidOperationException(); //if (!(message is TimeMessage) && message.GetType().Name != "BasketMessage") // Console.WriteLine(">> ({0}) {1}", System.Threading.Thread.CurrentThread.Name, message); _initMessage?.Invoke(message); _msgStat.Add(message); _messageQueue.Enqueue(new KeyValuePair<DateTimeOffset, Message>(message.LocalTime, message)); } /// <summary> /// New message event. /// </summary> public event Action<Message> NewOutMessage; void IDisposable.Dispose() { Close(); } /// <summary> /// Create a copy of <see cref="InMemoryMessageChannel"/>. /// </summary> /// <returns>Copy.</returns> public override IMessageChannel Clone() { return new InMemoryMessageChannel(Name, _errorHandler) { MaxMessageCount = MaxMessageCount }; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System.Collections.Generic; using System.Buffers; namespace System.Binary.Base64.Tests { public class Base64Tests { [Fact] public void BasicEncodingDecoding() { var bytes = new byte[byte.MaxValue + 1]; for (int i = 0; i < byte.MaxValue + 1; i++) { bytes[i] = (byte)i; } for (int value = 0; value < 256; value++) { Span<byte> sourceBytes = bytes.AsSpan().Slice(0, value + 1); Span<byte> encodedBytes = new byte[Base64.BytesToUtf8Length(sourceBytes.Length)]; Assert.Equal(OperationStatus.Done, Base64.BytesToUtf8(sourceBytes, encodedBytes, out int consumed, out int encodedBytesCount)); Assert.Equal(encodedBytes.Length, encodedBytesCount); string encodedText = Text.Encoding.ASCII.GetString(encodedBytes.ToArray()); string expectedText = Convert.ToBase64String(bytes, 0, value + 1); Assert.Equal(expectedText, encodedText); if (encodedBytes.Length % 4 == 0) { Span<byte> decodedBytes = new byte[Base64.Utf8ToBytesLength(encodedBytes)]; Assert.Equal(OperationStatus.Done, Base64.Utf8ToBytes(encodedBytes, decodedBytes, out consumed, out int decodedByteCount)); Assert.Equal(sourceBytes.Length, decodedByteCount); Assert.True(sourceBytes.SequenceEqual(decodedBytes)); } } } [Fact] public void BasicEncoding() { var rnd = new Random(42); for (int i = 0; i < 10; i++) { int numBytes = rnd.Next(100, 1000 * 1000); Span<byte> source = new byte[numBytes]; Base64TestHelper.InitalizeBytes(source, numBytes); Span<byte> encodedBytes = new byte[Base64.BytesToUtf8Length(source.Length)]; Assert.Equal(OperationStatus.Done, Base64.BytesToUtf8(source, encodedBytes, out int consumed, out int encodedBytesCount)); Assert.Equal(encodedBytes.Length, encodedBytesCount); string encodedText = Text.Encoding.ASCII.GetString(encodedBytes.ToArray()); string expectedText = Convert.ToBase64String(source.ToArray()); Assert.Equal(expectedText, encodedText); } } [Fact] public void EncodingOutputTooSmall() { Span<byte> source = new byte[750]; Base64TestHelper.InitalizeBytes(source); int outputSize = 320; int requiredSize = Base64.BytesToUtf8Length(source.Length); Span<byte> encodedBytes = new byte[outputSize]; Assert.Equal(OperationStatus.DestinationTooSmall, Base64.BytesToUtf8(source, encodedBytes, out int consumed, out int written)); Assert.Equal(encodedBytes.Length, written); Assert.Equal(encodedBytes.Length / 4 * 3, consumed); encodedBytes = new byte[requiredSize - outputSize]; Assert.Equal(OperationStatus.Done, Base64.BytesToUtf8(source.Slice(consumed), encodedBytes, out consumed, out written)); Assert.Equal(encodedBytes.Length, written); Assert.Equal(encodedBytes.Length / 4 * 3, consumed); string encodedText = Text.Encoding.ASCII.GetString(encodedBytes.ToArray()); string expectedText = Convert.ToBase64String(source.ToArray()).Substring(outputSize); Assert.Equal(expectedText, encodedText); } [Fact] public void BasicDecoding() { var rnd = new Random(42); for (int i = 0; i < 10; i++) { int numBytes = rnd.Next(100, 1000 * 1000); while (numBytes % 4 != 0) { numBytes = rnd.Next(100, 1000 * 1000); } Span<byte> source = new byte[numBytes]; Base64TestHelper.InitalizeDecodableBytes(source, numBytes); Span<byte> decodedBytes = new byte[Base64.Utf8ToBytesLength(source)]; Assert.Equal(OperationStatus.Done, Base64.Utf8ToBytes(source, decodedBytes, out int consumed, out int decodedByteCount)); Assert.Equal(decodedBytes.Length, decodedByteCount); string expectedStr = Text.Encoding.ASCII.GetString(source.ToArray()); byte[] expectedText = Convert.FromBase64String(expectedStr); Assert.True(expectedText.AsSpan().SequenceEqual(decodedBytes)); } } [Fact] public void DecodingInvalidBytes() { int[] invalidBytes = Base64TestHelper.s_decodingMap.FindAllIndexOf(Base64TestHelper.s_invalidByte); for (int j = 0; j < 8; j++) { Span<byte> source = new byte[] { 50, 50, 50, 50, 80, 80, 80, 80 }; Span<byte> decodedBytes = new byte[Base64.Utf8ToBytesLength(source)]; for (int i = 0; i < invalidBytes.Length; i++) { // Don't test padding, which is tested in DecodingInvalidBytesPadding if ((byte)invalidBytes[i] == Base64TestHelper.s_encodingPad) continue; source[j] = (byte)invalidBytes[i]; Assert.Equal(OperationStatus.InvalidData, Base64.Utf8ToBytes(source, decodedBytes, out int consumed, out int decodedByteCount)); } } } [Fact] public void DecodingInvalidBytesPadding() { // Only last 2 bytes can be padding, all other occurrence of padding is invalid for (int j = 0; j < 7; j++) { Span<byte> source = new byte[] { 50, 50, 50, 50, 80, 80, 80, 80 }; Span<byte> decodedBytes = new byte[Base64.Utf8ToBytesLength(source)]; source[j] = Base64TestHelper.s_encodingPad; Assert.Equal(OperationStatus.InvalidData, Base64.Utf8ToBytes(source, decodedBytes, out int consumed, out int decodedByteCount)); } { Span<byte> source = new byte[] { 50, 50, 50, 50, 80, 80, 80, 80 }; Span<byte> decodedBytes = new byte[Base64.Utf8ToBytesLength(source)]; source[6] = Base64TestHelper.s_encodingPad; source[7] = Base64TestHelper.s_encodingPad; Assert.Equal(OperationStatus.Done, Base64.Utf8ToBytes(source, decodedBytes, out int consumed, out int decodedByteCount)); source = new byte[] { 50, 50, 50, 50, 80, 80, 80, 80 }; source[7] = Base64TestHelper.s_encodingPad; Assert.Equal(OperationStatus.Done, Base64.Utf8ToBytes(source, decodedBytes, out consumed, out decodedByteCount)); } } [Fact] public void DecodingOutputTooSmall() { Span<byte> source = new byte[1000]; Base64TestHelper.InitalizeDecodableBytes(source); int outputSize = 240; int requiredSize = Base64.Utf8ToBytesLength(source); Span<byte> decodedBytes = new byte[outputSize]; Assert.Equal(OperationStatus.DestinationTooSmall, Base64.Utf8ToBytes(source, decodedBytes, out int consumed, out int decodedByteCount)); Assert.Equal(decodedBytes.Length, decodedByteCount); Assert.Equal(decodedBytes.Length / 3 * 4, consumed); decodedBytes = new byte[requiredSize - outputSize]; Assert.Equal(OperationStatus.Done, Base64.Utf8ToBytes(source.Slice(consumed), decodedBytes, out consumed, out decodedByteCount)); Assert.Equal(decodedBytes.Length, decodedByteCount); Assert.Equal(decodedBytes.Length / 3 * 4, consumed); string expectedStr = Text.Encoding.ASCII.GetString(source.ToArray()); byte[] expectedText = Convert.FromBase64String(expectedStr); Assert.True(expectedText.AsSpan().Slice(outputSize).SequenceEqual(decodedBytes)); } [Fact] public void ComputeEncodedLength() { // (int.MaxValue - 4)/(4/3) => 1610612733, otherwise integer overflow int[] input = { 0, 1, 2, 3, 4, 5, 6, 1610612728, 1610612729, 1610612730, 1610612731, 1610612732, 1610612733 }; int[] expected = { 0, 4, 4, 4, 8, 8, 8, 2147483640, 2147483640, 2147483640, 2147483644, 2147483644, 2147483644 }; for (int i = 0; i < input.Length; i++) { Assert.Equal(expected[i], Base64.BytesToUtf8Length(input[i])); } Assert.True(Base64.BytesToUtf8Length(1610612734) < 0); // integer overflow } [Fact] public void ComputeDecodedLength() { Span<byte> sourceEmpty = Span<byte>.Empty; Assert.Equal(0, Base64.Utf8ToBytesLength(sourceEmpty)); int[] input = { 4, 8, 12, 16, 20 }; int[] expected = { 3, 6, 9, 12, 15 }; for (int i = 0; i < input.Length; i++) { int sourceLength = input[i]; Span<byte> source = new byte[sourceLength]; Assert.Equal(expected[i], Base64.Utf8ToBytesLength(source)); source[sourceLength - 1] = Base64TestHelper.s_encodingPad; // single character padding Assert.Equal(expected[i] - 1, Base64.Utf8ToBytesLength(source)); source[sourceLength - 2] = Base64TestHelper.s_encodingPad; // two characters padding Assert.Equal(expected[i] - 2, Base64.Utf8ToBytesLength(source)); } // int.MaxValue - (int.MaxValue % 4) => 2147483644, largest multiple of 4 less than int.MaxValue // CLR default limit of 2 gigabytes (GB). try { int sourceLength = 2000000000; int expectedLength = 1500000000; Span<byte> source = new byte[sourceLength]; Assert.Equal(expectedLength, Base64.Utf8ToBytesLength(source)); source[sourceLength - 1] = Base64TestHelper.s_encodingPad; // single character padding Assert.Equal(expectedLength - 1, Base64.Utf8ToBytesLength(source)); source[sourceLength - 2] = Base64TestHelper.s_encodingPad; // two characters padding Assert.Equal(expectedLength - 2, Base64.Utf8ToBytesLength(source)); } catch (OutOfMemoryException) { // do nothing } // Lengths that are not a multiple of 4. int[] lengthsNotMultipleOfFour = { 1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15, 1001, 1002, 1003 }; int[] expectedOutput = { 0, 0, 0, 3, 3, 3, 6, 6, 6, 9, 9, 9, 750, 750, 750 }; for (int i = 0; i < lengthsNotMultipleOfFour.Length; i++) { int sourceLength = lengthsNotMultipleOfFour[i]; Span<byte> source = new byte[sourceLength]; Assert.Equal(expectedOutput[i], Base64.Utf8ToBytesLength(source)); source[sourceLength - 1] = Base64TestHelper.s_encodingPad; Assert.Equal(expectedOutput[i], Base64.Utf8ToBytesLength(source)); if (sourceLength > 1) { source[sourceLength - 2] = Base64TestHelper.s_encodingPad; Assert.Equal(expectedOutput[i], Base64.Utf8ToBytesLength(source)); } } } [Fact] public void DecodeInPlace() { var list = new List<byte>(); for (int value = 0; value < 256; value++) { list.Add((byte)value); } var testBytes = list.ToArray(); for (int value = 0; value < 256; value++) { var sourceBytes = testBytes.AsSpan().Slice(0, value + 1); var buffer = new byte[Base64.BytesToUtf8Length(sourceBytes.Length)]; var bufferSlice = buffer.AsSpan(); Base64.BytesToUtf8(sourceBytes, bufferSlice, out int consumed, out int written); var encodedText = Text.Encoding.ASCII.GetString(bufferSlice.ToArray()); var expectedText = Convert.ToBase64String(testBytes, 0, value + 1); Assert.Equal(expectedText, encodedText); Assert.Equal(OperationStatus.Done, Base64.Utf8ToBytesInPlace(bufferSlice, out int bytesConsumed, out int bytesWritten)); Assert.Equal(sourceBytes.Length, bytesWritten); Assert.Equal(bufferSlice.Length, bytesConsumed); for (int i = 0; i < bytesWritten; i++) { Assert.Equal(sourceBytes[i], bufferSlice[i]); } } } [Fact] public void ValidInputOnlyMultiByte() { Span<byte> inputSpan = new byte[1000]; Base64TestHelper.InitalizeDecodableBytes(inputSpan); int requiredLength = Base64.Utf8ToBytesLength(inputSpan); Span<byte> expected = new byte[requiredLength]; Assert.Equal(OperationStatus.Done, Base64.Utf8ToBytes(inputSpan, expected, out int bytesConsumed, out int bytesWritten)); byte[][] input = new byte[10][]; int[] split = { 100, 102, 98, 101, 2, 97, 101, 1, 2, 396 }; int sum = 0; for (int i = 0; i < split.Length; i++) { int splitter = split[i]; input[i] = inputSpan.Slice(sum, splitter).ToArray(); sum += splitter; } Assert.Equal(1000, sum); var output = new TestOutput(); Base64.Utf8ToBytesDecoder.Pipe(ReadOnlyBytes.Create(input), output); Assert.True(expected.SequenceEqual(output.GetBuffer.Slice(0, requiredLength))); } [Fact] public void EncodeInPlace() { const int numberOfBytes = 15; var list = new List<byte>(); for (int value = 0; value < numberOfBytes; value++) { list.Add((byte)value); } // padding for (int i = 0; i < (numberOfBytes / 3) + 2; i++) { list.Add(0); } var testBytes = list.ToArray(); for (int numberOfBytesToTest = 1; numberOfBytesToTest <= numberOfBytes; numberOfBytesToTest++) { var copy = testBytes.Clone(); var expectedText = Convert.ToBase64String(testBytes, 0, numberOfBytesToTest); Assert.Equal(OperationStatus.Done, Base64.BytesToUtf8InPlace(testBytes, numberOfBytesToTest, out int bytesWritten)); Assert.Equal(Base64.BytesToUtf8Length(numberOfBytesToTest), bytesWritten); var encodedText = Text.Encoding.ASCII.GetString(testBytes, 0, bytesWritten); Assert.Equal(expectedText, encodedText); } } } class TestOutput : IOutput { byte[] _buffer = new byte[1000]; int _written = 0; public Span<byte> GetBuffer => _buffer; public Span<byte> Buffer => _buffer.Slice(_written); public void Advance(int bytes) { _written += bytes; } public void Enlarge(int desiredBufferLength = 0) { } } }
using System; using System.IO; using System.Text; using System.Xml; using Google.GData.Client; namespace Google.GData.Extensions { /// <summary> /// GData schema extension describing a nested feed link. /// </summary> public class FeedLink : IExtensionElementFactory { /// <summary>holds the feed property</summary> private AtomFeed feed; /// <summary>holds the href property</summary> private string href; /// <summary>holds the readOnly property</summary> private bool readOnly; private bool readOnlySet; /// <summary>holds the rel attribute of the EntryLink element</summary> private string rel; /// <summary> /// constructor /// </summary> public FeedLink() { CountHint = -1; readOnly = true; } /// <summary> /// Entry URI /// </summary> public string Href { get { return href; } set { href = value; } } /// <summary> /// Read only flag. /// </summary> public bool ReadOnly { get { return readOnly; } set { readOnly = value; readOnlySet = true; } } /// <summary> /// Count hint. /// </summary> public int CountHint { get; set; } /// <summary> /// Nested entry (optional). /// </summary> public AtomFeed Feed { get { return feed; } set { feed = value; } } ////////////////////////////////////////////////////////////////////// /// <summary>accessor method public string Rel</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public string Rel { get { return rel; } set { rel = value; } } #region overloaded for persistence /// <summary> /// Persistence method for the FeedLink object /// </summary> /// <param name="writer">the xmlwriter to write into</param> public void Save(XmlWriter writer) { if (Utilities.IsPersistable(Href) || Feed != null) { writer.WriteStartElement(XmlPrefix, XmlName, XmlNameSpace); if (Utilities.IsPersistable(Href)) { writer.WriteAttributeString(GDataParserNameTable.XmlAttributeHref, Href); } // do not save the default if (readOnlySet) { writer.WriteAttributeString(GDataParserNameTable.XmlAttributeReadOnly, Utilities.ConvertBooleanToXSDString(ReadOnly)); } if (Utilities.IsPersistable(Rel)) { writer.WriteAttributeString(GDataParserNameTable.XmlAttributeRel, Rel); } if (CountHint > -1) { writer.WriteAttributeString(GDataParserNameTable.XmlAttributeCountHint, CountHint.ToString()); } if (Feed != null) { Feed.SaveToXml(writer); } writer.WriteEndElement(); } } #endregion ///////////////////////////////////////////////////////////////////////////// #region FeedLink Parser ////////////////////////////////////////////////////////////////////// /// <summary>Parses an xml node to create an FeedLink object.</summary> /// <param name="node">feedLink node</param> /// <returns> the created FeedLink object</returns> ////////////////////////////////////////////////////////////////////// public static FeedLink ParseFeedLink(XmlNode node) { Tracing.TraceCall(); FeedLink link = null; Tracing.Assert(node != null, "node should not be null"); if (node == null) { throw new ArgumentNullException("node"); } object localname = node.LocalName; if (localname.Equals(GDataParserNameTable.XmlFeedLinkElement)) { link = new FeedLink(); if (node.Attributes != null) { if (node.Attributes[GDataParserNameTable.XmlAttributeHref] != null) { link.Href = node.Attributes[GDataParserNameTable.XmlAttributeHref].Value; } if (node.Attributes[GDataParserNameTable.XmlAttributeReadOnly] != null) { link.ReadOnly = node.Attributes[GDataParserNameTable.XmlAttributeReadOnly].Value.Equals(Utilities.XSDTrue); } if (node.Attributes[GDataParserNameTable.XmlAttributeRel] != null) { link.Rel = node.Attributes[GDataParserNameTable.XmlAttributeRel].Value; } if (node.Attributes[GDataParserNameTable.XmlAttributeCountHint] != null) { try { link.CountHint = int.Parse(node.Attributes[GDataParserNameTable.XmlAttributeCountHint].Value); } catch (FormatException fe) { throw new ArgumentException("Invalid g:feedLink/@countHint.", fe); } } } if (node.HasChildNodes) { XmlNode feedChild = node.FirstChild; while (feedChild != null && feedChild is XmlElement) { if (feedChild.LocalName == AtomParserNameTable.XmlFeedElement && feedChild.NamespaceURI == BaseNameTable.NSAtom) { if (link.Feed == null) { link.Feed = new AtomFeed(null, new Service()); Stream feedStream = new MemoryStream(ASCIIEncoding.Default.GetBytes(feedChild.OuterXml)); link.Feed.Parse(feedStream, AlternativeFormat.Atom); } else { throw new ArgumentException("Only one feed is allowed inside the g:feedLink"); } } feedChild = feedChild.NextSibling; } } } return link; } #endregion #region overloaded from IExtensionElementFactory ////////////////////////////////////////////////////////////////////// /// <summary>Parses an xml node to create a Where object.</summary> /// <param name="node">the node to parse node</param> /// <param name="parser">the xml parser to use if we need to dive deeper</param> /// <returns>the created Where object</returns> ////////////////////////////////////////////////////////////////////// public IExtensionElementFactory CreateInstance(XmlNode node, AtomFeedParser parser) { return ParseFeedLink(node); } ////////////////////////////////////////////////////////////////////// /// <summary>Returns the constant representing this XML element.</summary> ////////////////////////////////////////////////////////////////////// public string XmlName { get { return GDataParserNameTable.XmlFeedLinkElement; } } ////////////////////////////////////////////////////////////////////// /// <summary>Returns the constant representing this XML element.</summary> ////////////////////////////////////////////////////////////////////// public string XmlNameSpace { get { return BaseNameTable.gNamespace; } } ////////////////////////////////////////////////////////////////////// /// <summary>Returns the constant representing this XML element.</summary> ////////////////////////////////////////////////////////////////////// public string XmlPrefix { get { return BaseNameTable.gDataPrefix; } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; namespace System.ComponentModel { /// <summary> /// <para> /// Declares an array of attributes for a member and defines /// the properties and methods that give you access to the attributes in the array. /// All attributes must derive from <see cref='System.Attribute'/>. /// </para> /// </summary> public abstract class MemberDescriptor { private readonly string _name; private readonly string _displayName; private readonly int _nameHash; private AttributeCollection _attributeCollection; private Attribute[] _attributes; private Attribute[] _originalAttributes; private bool _attributesFiltered = false; private bool _attributesFilled = false; private int _metadataVersion; private string _category; private string _description; private object _lockCookie = new object(); /// <summary> /// <para> /// Initializes a new instance of the <see cref='System.ComponentModel.MemberDescriptor'/> class with the specified <paramref name="name"/> and no attributes. /// </para> /// </summary> protected MemberDescriptor(string name) : this(name, null) { } /// <summary> /// <para> /// Initializes a new instance of the <see cref='System.ComponentModel.MemberDescriptor'/> class with the specified <paramref name="name"/> and <paramref name="attributes "/> array. /// </para> /// </summary> protected MemberDescriptor(string name, Attribute[] attributes) { if (name == null || name.Length == 0) { throw new ArgumentException(SR.InvalidMemberName); } _name = name; _displayName = name; _nameHash = name.GetHashCode(); if (attributes != null) { _attributes = attributes; _attributesFiltered = false; } _originalAttributes = _attributes; } /// <summary> /// <para> /// Initializes a new instance of the <see cref='System.ComponentModel.MemberDescriptor'/> class with the specified <see cref='System.ComponentModel.MemberDescriptor'/>. /// </para> /// </summary> protected MemberDescriptor(MemberDescriptor descr) { _name = descr.Name; _displayName = _name; _nameHash = _name.GetHashCode(); _attributes = new Attribute[descr.Attributes.Count]; descr.Attributes.CopyTo(_attributes, 0); _attributesFiltered = true; _originalAttributes = _attributes; } /// <summary> /// <para> /// Initializes a new instance of the <see cref='System.ComponentModel.MemberDescriptor'/> class with the name in the specified /// <see cref='System.ComponentModel.MemberDescriptor'/> and the attributes /// in both the old <see cref='System.ComponentModel.MemberDescriptor'/> and the <see cref='System.Attribute'/> array. /// </para> /// </summary> protected MemberDescriptor(MemberDescriptor oldMemberDescriptor, Attribute[] newAttributes) { _name = oldMemberDescriptor.Name; _displayName = oldMemberDescriptor.DisplayName; _nameHash = _name.GetHashCode(); ArrayList newArray = new ArrayList(); if (oldMemberDescriptor.Attributes.Count != 0) { foreach (object o in oldMemberDescriptor.Attributes) { newArray.Add(o); } } if (newAttributes != null) { foreach (object o in newAttributes) { newArray.Add(o); } } _attributes = new Attribute[newArray.Count]; newArray.CopyTo(_attributes, 0); _attributesFiltered = false; _originalAttributes = _attributes; } /// <summary> /// <para> /// Gets or sets an array of /// attributes. /// </para> /// </summary> protected virtual Attribute[] AttributeArray { get { CheckAttributesValid(); FilterAttributesIfNeeded(); return _attributes; } set { lock (_lockCookie) { _attributes = value; _originalAttributes = value; _attributesFiltered = false; _attributeCollection = null; } } } /// <summary> /// <para> /// Gets the collection of attributes for this member. /// </para> /// </summary> public virtual AttributeCollection Attributes { get { CheckAttributesValid(); AttributeCollection attrs = _attributeCollection; if (attrs == null) { lock (_lockCookie) { attrs = CreateAttributeCollection(); _attributeCollection = attrs; } } return attrs; } } /// <summary> /// <para> /// Gets the name of the category that the member belongs to, as specified /// in the <see cref='System.ComponentModel.CategoryAttribute'/>. /// </para> /// </summary> public virtual string Category { get { if (_category == null) { _category = ((CategoryAttribute)Attributes[typeof(CategoryAttribute)]).Category; } return _category; } } /// <summary> /// <para> /// Gets the description of /// the member as specified in the <see cref='System.ComponentModel.DescriptionAttribute'/>. /// </para> /// </summary> public virtual string Description { get { if (_description == null) { _description = ((DescriptionAttribute)Attributes[typeof(DescriptionAttribute)]).Description; } return _description; } } /// <summary> /// <para> /// Gets a value indicating whether the member is browsable as specified in the /// <see cref='System.ComponentModel.BrowsableAttribute'/>. /// </para> /// </summary> public virtual bool IsBrowsable { get { return ((BrowsableAttribute)Attributes[typeof(BrowsableAttribute)]).Browsable; } } /// <summary> /// <para> /// Gets the /// name of the member. /// </para> /// </summary> public virtual string Name { get { if (_name == null) { return ""; } return _name; } } /// <summary> /// <para> /// Gets the hash /// code for the name of the member as specified in <see cref='System.String.GetHashCode'/>. /// </para> /// </summary> protected virtual int NameHashCode { get { return _nameHash; } } /// <summary> /// <para> /// Determines whether this member should be set only at /// design time as specified in the <see cref='System.ComponentModel.DesignOnlyAttribute'/>. /// </para> /// </summary> public virtual bool DesignTimeOnly { get { return (DesignOnlyAttribute.Yes.Equals(Attributes[typeof(DesignOnlyAttribute)])); } } /// <summary> /// <para> /// Gets the name that can be displayed in a window like a /// properties window. /// </para> /// </summary> public virtual string DisplayName { get { DisplayNameAttribute displayNameAttr = Attributes[typeof(DisplayNameAttribute)] as DisplayNameAttribute; if (displayNameAttr == null || displayNameAttr.IsDefaultAttribute()) { return _displayName; } return displayNameAttr.DisplayName; } } /// <summary> /// Called each time we access the attribtes on /// this member descriptor to give deriving classes /// a chance to change them on the fly. /// </summary> private void CheckAttributesValid() { if (_attributesFiltered) { if (_metadataVersion != TypeDescriptor.MetadataVersion) { _attributesFilled = false; _attributesFiltered = false; _attributeCollection = null; } } } /// <include file='doc\MemberDescriptor.uex' path='docs/doc[@for="MemberDescriptor.CreateAttributeCollection"]/*' /> /// <summary> /// <para> /// Creates a collection of attributes using the /// array of attributes that you passed to the constructor. /// </para> /// </summary> protected virtual AttributeCollection CreateAttributeCollection() { return new AttributeCollection(AttributeArray); } /// <summary> /// <para> /// Compares this instance to the specified <see cref='System.ComponentModel.MemberDescriptor'/> to see if they are equivalent. /// NOTE: If you make a change here, you likely need to change GetHashCode() as well. /// </para> /// </summary> public override bool Equals(object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (obj.GetType() != GetType()) { return false; } MemberDescriptor mdObj = (MemberDescriptor)obj; FilterAttributesIfNeeded(); mdObj.FilterAttributesIfNeeded(); if (mdObj._nameHash != _nameHash) { return false; } if ((mdObj._category == null) != (_category == null) || (_category != null && !mdObj._category.Equals(_category))) { return false; } if ((mdObj._description == null) != (_description == null) || (_description != null && !mdObj._description.Equals(_description))) { return false; } if ((mdObj._attributes == null) != (_attributes == null)) { return false; } bool sameAttrs = true; if (_attributes != null) { if (_attributes.Length != mdObj._attributes.Length) { return false; } for (int i = 0; i < _attributes.Length; i++) { if (!_attributes[i].Equals(mdObj._attributes[i])) { sameAttrs = false; break; } } } return sameAttrs; } /// <summary> /// <para> /// In an inheriting class, adds the attributes of the inheriting class to the /// specified list of attributes in the parent class. For duplicate attributes, /// the last one added to the list will be kept. /// </para> /// </summary> protected virtual void FillAttributes(IList attributeList) { if (_originalAttributes != null) { foreach (Attribute attr in _originalAttributes) { attributeList.Add(attr); } } } private void FilterAttributesIfNeeded() { if (!_attributesFiltered) { List<Attribute> list; if (!_attributesFilled) { list = new List<Attribute>(); try { FillAttributes(list); } catch (Exception e) { Debug.Fail($"{_name}>>{e}"); } } else { list = new List<Attribute>(_attributes); } var set = new HashSet<object>(); for (int i = 0; i < list.Count;) { if (set.Add(list[i].GetTypeId())) { ++i; } else { list.RemoveAt(i); } } Attribute[] newAttributes = list.ToArray(); lock (_lockCookie) { _attributes = newAttributes; _attributesFiltered = true; _attributesFilled = true; _metadataVersion = TypeDescriptor.MetadataVersion; } } } /// <summary> /// <para> /// Finds the given method through reflection. This method only looks for public methods. /// </para> /// </summary> protected static MethodInfo FindMethod(Type componentClass, string name, Type[] args, Type returnType) { return FindMethod(componentClass, name, args, returnType, true); } /// <summary> /// <para> /// Finds the given method through reflection. /// </para> /// </summary> protected static MethodInfo FindMethod(Type componentClass, string name, Type[] args, Type returnType, bool publicOnly) { MethodInfo result = null; if (publicOnly) { result = componentClass.GetTypeInfo().GetMethod(name, args); } else { // The original impementation requires the method https://msdn.microsoft.com/en-us/library/5fed8f59(v=vs.110).aspx which is not // available on .NET Core. The replacement will use the default BindingFlags, which may miss some methods that had been found // on .NET Framework. #if FEATURE_GETMETHOD_WITHTYPES result = componentClass.GetTypeInfo().GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, args, null); #else result = componentClass.GetTypeInfo().GetMethod(name, args); #endif } if (result != null && !result.ReturnType.GetTypeInfo().IsEquivalentTo(returnType)) { result = null; } return result; } /// <summary> /// Try to keep this reasonable in [....] with Equals(). Specifically, /// if A.Equals(B) returns true, A & B should have the same hash code. /// </summary> public override int GetHashCode() { return _nameHash; } /// <summary> /// This method returns the object that should be used during invocation of members. /// Normally the return value will be the same as the instance passed in. If /// someone associated another object with this instance, or if the instance is a /// custom type descriptor, GetInvocationTarget may return a different value. /// </summary> protected virtual object GetInvocationTarget(Type type, object instance) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (instance == null) { throw new ArgumentNullException(nameof(instance)); } return TypeDescriptor.GetAssociation(type, instance); } /// <summary> /// <para> /// Gets a component site /// for the given component. /// </para> /// </summary> protected static ISite GetSite(object component) { if (!(component is IComponent)) { return null; } return ((IComponent)component).Site; } } }
//--------------------------------------------------------------------------- // // <copyright file="LinearGradientBrush.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.KnownBoxes; using MS.Internal.Collections; using MS.Internal.PresentationCore; using MS.Utility; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.ComponentModel.Design.Serialization; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Media.Effects; using System.Windows.Media.Media3D; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using System.Windows.Media.Imaging; using System.Windows.Markup; using System.Windows.Media.Converters; using System.Security; using System.Security.Permissions; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; // These types are aliased to match the unamanaged names used in interop using BOOL = System.UInt32; using WORD = System.UInt16; using Float = System.Single; namespace System.Windows.Media { sealed partial class LinearGradientBrush : GradientBrush { //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Shadows inherited Clone() with a strongly typed /// version for convenience. /// </summary> public new LinearGradientBrush Clone() { return (LinearGradientBrush)base.Clone(); } /// <summary> /// Shadows inherited CloneCurrentValue() with a strongly typed /// version for convenience. /// </summary> public new LinearGradientBrush CloneCurrentValue() { return (LinearGradientBrush)base.CloneCurrentValue(); } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ private static void StartPointPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { LinearGradientBrush target = ((LinearGradientBrush) d); target.PropertyChanged(StartPointProperty); } private static void EndPointPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { LinearGradientBrush target = ((LinearGradientBrush) d); target.PropertyChanged(EndPointProperty); } #region Public Properties /// <summary> /// StartPoint - Point. Default value is new Point(0,0). /// </summary> public Point StartPoint { get { return (Point) GetValue(StartPointProperty); } set { SetValueInternal(StartPointProperty, value); } } /// <summary> /// EndPoint - Point. Default value is new Point(1,1). /// </summary> public Point EndPoint { get { return (Point) GetValue(EndPointProperty); } set { SetValueInternal(EndPointProperty, value); } } #endregion Public Properties //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new LinearGradientBrush(); } #endregion ProtectedMethods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods /// <SecurityNote> /// Critical: This code calls into an unsafe code block /// TreatAsSafe: This code does not return any critical data.It is ok to expose /// Channels are safe to call into and do not go cross domain and cross process /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] internal override void UpdateResource(DUCE.Channel channel, bool skipOnChannelCheck) { ManualUpdateResource(channel, skipOnChannelCheck); base.UpdateResource(channel, skipOnChannelCheck); } internal override DUCE.ResourceHandle AddRefOnChannelCore(DUCE.Channel channel) { if (_duceResource.CreateOrAddRefOnChannel(this, channel, System.Windows.Media.Composition.DUCE.ResourceType.TYPE_LINEARGRADIENTBRUSH)) { Transform vTransform = Transform; if (vTransform != null) ((DUCE.IResource)vTransform).AddRefOnChannel(channel); Transform vRelativeTransform = RelativeTransform; if (vRelativeTransform != null) ((DUCE.IResource)vRelativeTransform).AddRefOnChannel(channel); AddRefOnChannelAnimations(channel); UpdateResource(channel, true /* skip "on channel" check - we already know that we're on channel */ ); } return _duceResource.GetHandle(channel); } internal override void ReleaseOnChannelCore(DUCE.Channel channel) { Debug.Assert(_duceResource.IsOnChannel(channel)); if (_duceResource.ReleaseOnChannel(channel)) { Transform vTransform = Transform; if (vTransform != null) ((DUCE.IResource)vTransform).ReleaseOnChannel(channel); Transform vRelativeTransform = RelativeTransform; if (vRelativeTransform != null) ((DUCE.IResource)vRelativeTransform).ReleaseOnChannel(channel); ReleaseOnChannelAnimations(channel); } } internal override DUCE.ResourceHandle GetHandleCore(DUCE.Channel channel) { // Note that we are in a lock here already. return _duceResource.GetHandle(channel); } internal override int GetChannelCountCore() { // must already be in composition lock here return _duceResource.GetChannelCount(); } internal override DUCE.Channel GetChannelCore(int index) { // Note that we are in a lock here already. return _duceResource.GetChannel(index); } #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties // // This property finds the correct initial size for the _effectiveValues store on the // current DependencyObject as a performance optimization // // This includes: // GradientStops // StartPoint // EndPoint // internal override int EffectiveValuesInitialSize { get { return 3; } } #endregion Internal Properties //------------------------------------------------------ // // Dependency Properties // //------------------------------------------------------ #region Dependency Properties /// <summary> /// The DependencyProperty for the LinearGradientBrush.StartPoint property. /// </summary> public static readonly DependencyProperty StartPointProperty; /// <summary> /// The DependencyProperty for the LinearGradientBrush.EndPoint property. /// </summary> public static readonly DependencyProperty EndPointProperty; #endregion Dependency Properties //------------------------------------------------------ // // Internal Fields // //------------------------------------------------------ #region Internal Fields internal System.Windows.Media.Composition.DUCE.MultiChannelResource _duceResource = new System.Windows.Media.Composition.DUCE.MultiChannelResource(); internal static Point s_StartPoint = new Point(0,0); internal static Point s_EndPoint = new Point(1,1); #endregion Internal Fields #region Constructors //------------------------------------------------------ // // Constructors // //------------------------------------------------------ static LinearGradientBrush() { // We check our static default fields which are of type Freezable // to make sure that they are not mutable, otherwise we will throw // if these get touched by more than one thread in the lifetime // of your app. (Windows OS Bug #947272) // // Initializations Type typeofThis = typeof(LinearGradientBrush); StartPointProperty = RegisterProperty("StartPoint", typeof(Point), typeofThis, new Point(0,0), new PropertyChangedCallback(StartPointPropertyChanged), null, /* isIndependentlyAnimated = */ true, /* coerceValueCallback */ null); EndPointProperty = RegisterProperty("EndPoint", typeof(Point), typeofThis, new Point(1,1), new PropertyChangedCallback(EndPointPropertyChanged), null, /* isIndependentlyAnimated = */ true, /* coerceValueCallback */ null); } #endregion Constructors } }
// 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: The contract class allows for expressing preconditions, ** postconditions, and object invariants about methods in source ** code for runtime checking & static analysis. ** ** Two classes (Contract and ContractHelper) are split into partial classes ** in order to share the public front for multiple platforms (this file) ** while providing separate implementation details for each platform. ** ===========================================================*/ #define DEBUG // The behavior of this contract library should be consistent regardless of build type. #if SILVERLIGHT #define FEATURE_UNTRUSTED_CALLERS #elif REDHAWK_RUNTIME #elif BARTOK_RUNTIME #else // CLR #define FEATURE_UNTRUSTED_CALLERS #define FEATURE_RELIABILITY_CONTRACTS #define FEATURE_SERIALIZATION #endif using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; #if FEATURE_RELIABILITY_CONTRACTS using System.Runtime.ConstrainedExecution; #endif #if FEATURE_UNTRUSTED_CALLERS using System.Security; using System.Security.Permissions; #endif namespace System.Diagnostics.Contracts { #region Attributes /// <summary> /// Methods and classes marked with this attribute can be used within calls to Contract methods. Such methods not make any visible state changes. /// </summary> [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Delegate | AttributeTargets.Class | AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)] public sealed class PureAttribute : Attribute { } /// <summary> /// Types marked with this attribute specify that a separate type contains the contracts for this type. /// </summary> [Conditional("CONTRACTS_FULL")] [Conditional("DEBUG")] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] public sealed class ContractClassAttribute : Attribute { private Type _typeWithContracts; public ContractClassAttribute(Type typeContainingContracts) { _typeWithContracts = typeContainingContracts; } public Type TypeContainingContracts { get { return _typeWithContracts; } } } /// <summary> /// Types marked with this attribute specify that they are a contract for the type that is the argument of the constructor. /// </summary> [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public sealed class ContractClassForAttribute : Attribute { private Type _typeIAmAContractFor; public ContractClassForAttribute(Type typeContractsAreFor) { _typeIAmAContractFor = typeContractsAreFor; } public Type TypeContractsAreFor { get { return _typeIAmAContractFor; } } } /// <summary> /// This attribute is used to mark a method as being the invariant /// method for a class. The method can have any name, but it must /// return "void" and take no parameters. The body of the method /// must consist solely of one or more calls to the method /// Contract.Invariant. A suggested name for the method is /// "ObjectInvariant". /// </summary> [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public sealed class ContractInvariantMethodAttribute : Attribute { } /// <summary> /// Attribute that specifies that an assembly is a reference assembly with contracts. /// </summary> [AttributeUsage(AttributeTargets.Assembly)] public sealed class ContractReferenceAssemblyAttribute : Attribute { } /// <summary> /// Methods (and properties) marked with this attribute can be used within calls to Contract methods, but have no runtime behavior associated with them. /// </summary> [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class ContractRuntimeIgnoredAttribute : Attribute { } /* [Serializable] internal enum Mutability { Immutable, // read-only after construction, except for lazy initialization & caches // Do we need a "deeply immutable" value? Mutable, HasInitializationPhase, // read-only after some point. // Do we need a value for mutable types with read-only wrapper subclasses? } // Note: This hasn't been thought through in any depth yet. Consider it experimental. // We should replace this with Joe's concepts. [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)] [SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments", Justification = "Thank you very much, but we like the names we've defined for the accessors")] internal sealed class MutabilityAttribute : Attribute { private Mutability _mutabilityMarker; public MutabilityAttribute(Mutability mutabilityMarker) { _mutabilityMarker = mutabilityMarker; } public Mutability Mutability { get { return _mutabilityMarker; } } } */ /// <summary> /// Instructs downstream tools whether to assume the correctness of this assembly, type or member without performing any verification or not. /// Can use [ContractVerification(false)] to explicitly mark assembly, type or member as one to *not* have verification performed on it. /// Most specific element found (member, type, then assembly) takes precedence. /// (That is useful if downstream tools allow a user to decide which polarity is the default, unmarked case.) /// </summary> /// <remarks> /// Apply this attribute to a type to apply to all members of the type, including nested types. /// Apply this attribute to an assembly to apply to all types and members of the assembly. /// Apply this attribute to a property to apply to both the getter and setter. /// </remarks> [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property)] public sealed class ContractVerificationAttribute : Attribute { private bool _value; public ContractVerificationAttribute(bool value) { _value = value; } public bool Value { get { return _value; } } } /// <summary> /// Allows a field f to be used in the method contracts for a method m when f has less visibility than m. /// For instance, if the method is public, but the field is private. /// </summary> [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Field)] [SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments", Justification = "Thank you very much, but we like the names we've defined for the accessors")] public sealed class ContractPublicPropertyNameAttribute : Attribute { private String _publicName; public ContractPublicPropertyNameAttribute(String name) { _publicName = name; } public String Name { get { return _publicName; } } } /// <summary> /// Enables factoring legacy if-then-throw into separate methods for reuse and full control over /// thrown exception and arguments /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] [Conditional("CONTRACTS_FULL")] public sealed class ContractArgumentValidatorAttribute : Attribute { } /// <summary> /// Enables writing abbreviations for contracts that get copied to other methods /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] [Conditional("CONTRACTS_FULL")] public sealed class ContractAbbreviatorAttribute : Attribute { } /// <summary> /// Allows setting contract and tool options at assembly, type, or method granularity. /// </summary> [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] [Conditional("CONTRACTS_FULL")] public sealed class ContractOptionAttribute : Attribute { private String _category; private String _setting; private bool _enabled; private String _value; public ContractOptionAttribute(String category, String setting, bool enabled) { _category = category; _setting = setting; _enabled = enabled; } public ContractOptionAttribute(String category, String setting, String value) { _category = category; _setting = setting; _value = value; } public String Category { get { return _category; } } public String Setting { get { return _setting; } } public bool Enabled { get { return _enabled; } } public String Value { get { return _value; } } } #endregion Attributes /// <summary> /// Contains static methods for representing program contracts such as preconditions, postconditions, and invariants. /// </summary> /// <remarks> /// WARNING: A binary rewriter must be used to insert runtime enforcement of these contracts. /// Otherwise some contracts like Ensures can only be checked statically and will not throw exceptions during runtime when contracts are violated. /// Please note this class uses conditional compilation to help avoid easy mistakes. Defining the preprocessor /// symbol CONTRACTS_PRECONDITIONS will include all preconditions expressed using Contract.Requires in your /// build. The symbol CONTRACTS_FULL will include postconditions and object invariants, and requires the binary rewriter. /// </remarks> public static partial class Contract { #region User Methods #region Assume /// <summary> /// Instructs code analysis tools to assume the expression <paramref name="condition"/> is true even if it can not be statically proven to always be true. /// </summary> /// <param name="condition">Expression to assume will always be true.</param> /// <remarks> /// At runtime this is equivalent to an <seealso cref="System.Diagnostics.Contracts.Contract.Assert(bool)"/>. /// </remarks> [Pure] [Conditional("DEBUG")] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Assume(bool condition) { if (!condition) { ReportFailure(ContractFailureKind.Assume, null, null, null); } } /// <summary> /// Instructs code analysis tools to assume the expression <paramref name="condition"/> is true even if it can not be statically proven to always be true. /// </summary> /// <param name="condition">Expression to assume will always be true.</param> /// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param> /// <remarks> /// At runtime this is equivalent to an <seealso cref="System.Diagnostics.Contracts.Contract.Assert(bool)"/>. /// </remarks> [Pure] [Conditional("DEBUG")] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Assume(bool condition, String userMessage) { if (!condition) { ReportFailure(ContractFailureKind.Assume, userMessage, null, null); } } #endregion Assume #region Assert /// <summary> /// In debug builds, perform a runtime check that <paramref name="condition"/> is true. /// </summary> /// <param name="condition">Expression to check to always be true.</param> [Pure] [Conditional("DEBUG")] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Assert(bool condition) { if (!condition) ReportFailure(ContractFailureKind.Assert, null, null, null); } /// <summary> /// In debug builds, perform a runtime check that <paramref name="condition"/> is true. /// </summary> /// <param name="condition">Expression to check to always be true.</param> /// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param> [Pure] [Conditional("DEBUG")] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Assert(bool condition, String userMessage) { if (!condition) ReportFailure(ContractFailureKind.Assert, userMessage, null, null); } #endregion Assert #region Requires /// <summary> /// Specifies a contract such that the expression <paramref name="condition"/> must be true before the enclosing method or property is invoked. /// </summary> /// <param name="condition">Boolean expression representing the contract.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// Use this form when backward compatibility does not force you to throw a particular exception. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Requires(bool condition) { AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires"); } /// <summary> /// Specifies a contract such that the expression <paramref name="condition"/> must be true before the enclosing method or property is invoked. /// </summary> /// <param name="condition">Boolean expression representing the contract.</param> /// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// Use this form when backward compatibility does not force you to throw a particular exception. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Requires(bool condition, String userMessage) { AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires"); } /// <summary> /// Specifies a contract such that the expression <paramref name="condition"/> must be true before the enclosing method or property is invoked. /// </summary> /// <param name="condition">Boolean expression representing the contract.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// Use this form when you want to throw a particular exception. /// </remarks> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "condition")] [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")] [Pure] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Requires<TException>(bool condition) where TException : Exception { AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires<TException>"); } /// <summary> /// Specifies a contract such that the expression <paramref name="condition"/> must be true before the enclosing method or property is invoked. /// </summary> /// <param name="condition">Boolean expression representing the contract.</param> /// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// Use this form when you want to throw a particular exception. /// </remarks> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "userMessage")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "condition")] [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")] [Pure] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Requires<TException>(bool condition, String userMessage) where TException : Exception { AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires<TException>"); } #endregion Requires #region Ensures /// <summary> /// Specifies a public contract such that the expression <paramref name="condition"/> will be true when the enclosing method or property returns normally. /// </summary> /// <param name="condition">Boolean expression representing the contract. May include <seealso cref="OldValue"/> and <seealso cref="Result"/>.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this postcondition. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Ensures(bool condition) { AssertMustUseRewriter(ContractFailureKind.Postcondition, "Ensures"); } /// <summary> /// Specifies a public contract such that the expression <paramref name="condition"/> will be true when the enclosing method or property returns normally. /// </summary> /// <param name="condition">Boolean expression representing the contract. May include <seealso cref="OldValue"/> and <seealso cref="Result"/>.</param> /// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this postcondition. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Ensures(bool condition, String userMessage) { AssertMustUseRewriter(ContractFailureKind.Postcondition, "Ensures"); } /// <summary> /// Specifies a contract such that if an exception of type <typeparamref name="TException"/> is thrown then the expression <paramref name="condition"/> will be true when the enclosing method or property terminates abnormally. /// </summary> /// <typeparam name="TException">Type of exception related to this postcondition.</typeparam> /// <param name="condition">Boolean expression representing the contract. May include <seealso cref="OldValue"/> and <seealso cref="Result"/>.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference types and members at least as visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this postcondition. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Exception type used in tools.")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void EnsuresOnThrow<TException>(bool condition) where TException : Exception { AssertMustUseRewriter(ContractFailureKind.PostconditionOnException, "EnsuresOnThrow"); } /// <summary> /// Specifies a contract such that if an exception of type <typeparamref name="TException"/> is thrown then the expression <paramref name="condition"/> will be true when the enclosing method or property terminates abnormally. /// </summary> /// <typeparam name="TException">Type of exception related to this postcondition.</typeparam> /// <param name="condition">Boolean expression representing the contract. May include <seealso cref="OldValue"/> and <seealso cref="Result"/>.</param> /// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference types and members at least as visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this postcondition. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Exception type used in tools.")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void EnsuresOnThrow<TException>(bool condition, String userMessage) where TException : Exception { AssertMustUseRewriter(ContractFailureKind.PostconditionOnException, "EnsuresOnThrow"); } #region Old, Result, and Out Parameters /// <summary> /// Represents the result (a.k.a. return value) of a method or property. /// </summary> /// <typeparam name="T">Type of return value of the enclosing method or property.</typeparam> /// <returns>Return value of the enclosing method or property.</returns> /// <remarks> /// This method can only be used within the argument to the <seealso cref="Ensures(bool)"/> contract. /// </remarks> [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Not intended to be called at runtime.")] [Pure] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #endif public static T Result<T>() { return default(T); } /// <summary> /// Represents the final (output) value of an out parameter when returning from a method. /// </summary> /// <typeparam name="T">Type of the out parameter.</typeparam> /// <param name="value">The out parameter.</param> /// <returns>The output value of the out parameter.</returns> /// <remarks> /// This method can only be used within the argument to the <seealso cref="Ensures(bool)"/> contract. /// </remarks> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#", Justification = "Not intended to be called at runtime.")] [Pure] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #endif public static T ValueAtReturn<T>(out T value) { value = default(T); return value; } /// <summary> /// Represents the value of <paramref name="value"/> as it was at the start of the method or property. /// </summary> /// <typeparam name="T">Type of <paramref name="value"/>. This can be inferred.</typeparam> /// <param name="value">Value to represent. This must be a field or parameter.</param> /// <returns>Value of <paramref name="value"/> at the start of the method or property.</returns> /// <remarks> /// This method can only be used within the argument to the <seealso cref="Ensures(bool)"/> contract. /// </remarks> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "value")] [Pure] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #endif public static T OldValue<T>(T value) { return default(T); } #endregion Old, Result, and Out Parameters #endregion Ensures #region Invariant /// <summary> /// Specifies a contract such that the expression <paramref name="condition"/> will be true after every method or property on the enclosing class. /// </summary> /// <param name="condition">Boolean expression representing the contract.</param> /// <remarks> /// This contact can only be specified in a dedicated invariant method declared on a class. /// This contract is not exposed to clients so may reference members less visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this invariant. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Invariant(bool condition) { AssertMustUseRewriter(ContractFailureKind.Invariant, "Invariant"); } /// <summary> /// Specifies a contract such that the expression <paramref name="condition"/> will be true after every method or property on the enclosing class. /// </summary> /// <param name="condition">Boolean expression representing the contract.</param> /// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param> /// <remarks> /// This contact can only be specified in a dedicated invariant method declared on a class. /// This contract is not exposed to clients so may reference members less visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this invariant. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static void Invariant(bool condition, String userMessage) { AssertMustUseRewriter(ContractFailureKind.Invariant, "Invariant"); } #endregion Invariant #region Quantifiers #region ForAll /// <summary> /// Returns whether the <paramref name="predicate"/> returns <c>true</c> /// for all integers starting from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1. /// </summary> /// <param name="fromInclusive">First integer to pass to <paramref name="predicate"/>.</param> /// <param name="toExclusive">One greater than the last integer to pass to <paramref name="predicate"/>.</param> /// <param name="predicate">Function that is evaluated from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.</param> /// <returns><c>true</c> if <paramref name="predicate"/> returns <c>true</c> for all integers /// starting from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.</returns> /// <seealso cref="System.Collections.Generic.List&lt;T&gt;.TrueForAll"/> [Pure] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] // Assumes predicate obeys CER rules. #endif public static bool ForAll(int fromInclusive, int toExclusive, Predicate<int> predicate) { if (fromInclusive > toExclusive) #if INSIDE_CLR throw new ArgumentException(Environment.GetResourceString("Argument_ToExclusiveLessThanFromExclusive")); #else throw new ArgumentException("fromInclusive must be less than or equal to toExclusive."); #endif if (predicate == null) throw new ArgumentNullException("predicate"); Contract.EndContractBlock(); for (int i = fromInclusive; i < toExclusive; i++) if (!predicate(i)) return false; return true; } /// <summary> /// Returns whether the <paramref name="predicate"/> returns <c>true</c> /// for all elements in the <paramref name="collection"/>. /// </summary> /// <param name="collection">The collection from which elements will be drawn from to pass to <paramref name="predicate"/>.</param> /// <param name="predicate">Function that is evaluated on elements from <paramref name="collection"/>.</param> /// <returns><c>true</c> if and only if <paramref name="predicate"/> returns <c>true</c> for all elements in /// <paramref name="collection"/>.</returns> /// <seealso cref="System.Collections.Generic.List&lt;T&gt;.TrueForAll"/> [Pure] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] // Assumes predicate & collection enumerator obey CER rules. #endif public static bool ForAll<T>(IEnumerable<T> collection, Predicate<T> predicate) { if (collection == null) throw new ArgumentNullException("collection"); if (predicate == null) throw new ArgumentNullException("predicate"); Contract.EndContractBlock(); foreach (T t in collection) if (!predicate(t)) return false; return true; } #endregion ForAll #region Exists /// <summary> /// Returns whether the <paramref name="predicate"/> returns <c>true</c> /// for any integer starting from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1. /// </summary> /// <param name="fromInclusive">First integer to pass to <paramref name="predicate"/>.</param> /// <param name="toExclusive">One greater than the last integer to pass to <paramref name="predicate"/>.</param> /// <param name="predicate">Function that is evaluated from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.</param> /// <returns><c>true</c> if <paramref name="predicate"/> returns <c>true</c> for any integer /// starting from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.</returns> /// <seealso cref="System.Collections.Generic.List&lt;T&gt;.Exists"/> [Pure] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] // Assumes predicate obeys CER rules. #endif public static bool Exists(int fromInclusive, int toExclusive, Predicate<int> predicate) { if (fromInclusive > toExclusive) #if INSIDE_CLR throw new ArgumentException(Environment.GetResourceString("Argument_ToExclusiveLessThanFromExclusive")); #else throw new ArgumentException("fromInclusive must be less than or equal to toExclusive."); #endif if (predicate == null) throw new ArgumentNullException("predicate"); Contract.EndContractBlock(); for (int i = fromInclusive; i < toExclusive; i++) if (predicate(i)) return true; return false; } /// <summary> /// Returns whether the <paramref name="predicate"/> returns <c>true</c> /// for any element in the <paramref name="collection"/>. /// </summary> /// <param name="collection">The collection from which elements will be drawn from to pass to <paramref name="predicate"/>.</param> /// <param name="predicate">Function that is evaluated on elements from <paramref name="collection"/>.</param> /// <returns><c>true</c> if and only if <paramref name="predicate"/> returns <c>true</c> for an element in /// <paramref name="collection"/>.</returns> /// <seealso cref="System.Collections.Generic.List&lt;T&gt;.Exists"/> [Pure] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] // Assumes predicate & collection enumerator obey CER rules. #endif public static bool Exists<T>(IEnumerable<T> collection, Predicate<T> predicate) { if (collection == null) throw new ArgumentNullException("collection"); if (predicate == null) throw new ArgumentNullException("predicate"); Contract.EndContractBlock(); foreach (T t in collection) if (predicate(t)) return true; return false; } #endregion Exists #endregion Quantifiers #region Pointers #if FEATURE_UNSAFE_CONTRACTS /// <summary> /// Runtime checking for pointer bounds is not currently feasible. Thus, at runtime, we just return /// a very long extent for each pointer that is writable. As long as assertions are of the form /// WritableBytes(ptr) >= ..., the runtime assertions will not fail. /// The runtime value is 2^64 - 1 or 2^32 - 1. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1802", Justification = "FxCop is confused")] static readonly ulong MaxWritableExtent = (UIntPtr.Size == 4) ? UInt32.MaxValue : UInt64.MaxValue; /// <summary> /// Allows specifying a writable extent for a UIntPtr, similar to SAL's writable extent. /// NOTE: this is for static checking only. No useful runtime code can be generated for this /// at the moment. /// </summary> /// <param name="startAddress">Start of memory region</param> /// <returns>The result is the number of bytes writable starting at <paramref name="startAddress"/></returns> [CLSCompliant(false)] [Pure] [ContractRuntimeIgnored] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static ulong WritableBytes(UIntPtr startAddress) { return MaxWritableExtent - startAddress.ToUInt64(); } /// <summary> /// Allows specifying a writable extent for a UIntPtr, similar to SAL's writable extent. /// NOTE: this is for static checking only. No useful runtime code can be generated for this /// at the moment. /// </summary> /// <param name="startAddress">Start of memory region</param> /// <returns>The result is the number of bytes writable starting at <paramref name="startAddress"/></returns> [CLSCompliant(false)] [Pure] [ContractRuntimeIgnored] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static ulong WritableBytes(IntPtr startAddress) { return MaxWritableExtent - (ulong)startAddress; } /// <summary> /// Allows specifying a writable extent for a UIntPtr, similar to SAL's writable extent. /// NOTE: this is for static checking only. No useful runtime code can be generated for this /// at the moment. /// </summary> /// <param name="startAddress">Start of memory region</param> /// <returns>The result is the number of bytes writable starting at <paramref name="startAddress"/></returns> [CLSCompliant(false)] [Pure] [ContractRuntimeIgnored] [SecurityCritical] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif unsafe public static ulong WritableBytes(void* startAddress) { return MaxWritableExtent - (ulong)startAddress; } /// <summary> /// Allows specifying a readable extent for a UIntPtr, similar to SAL's readable extent. /// NOTE: this is for static checking only. No useful runtime code can be generated for this /// at the moment. /// </summary> /// <param name="startAddress">Start of memory region</param> /// <returns>The result is the number of bytes readable starting at <paramref name="startAddress"/></returns> [CLSCompliant(false)] [Pure] [ContractRuntimeIgnored] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static ulong ReadableBytes(UIntPtr startAddress) { return MaxWritableExtent - startAddress.ToUInt64(); } /// <summary> /// Allows specifying a readable extent for a UIntPtr, similar to SAL's readable extent. /// NOTE: this is for static checking only. No useful runtime code can be generated for this /// at the moment. /// </summary> /// <param name="startAddress">Start of memory region</param> /// <returns>The result is the number of bytes readable starting at <paramref name="startAddress"/></returns> [CLSCompliant(false)] [Pure] [ContractRuntimeIgnored] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static ulong ReadableBytes(IntPtr startAddress) { return MaxWritableExtent - (ulong)startAddress; } /// <summary> /// Allows specifying a readable extent for a UIntPtr, similar to SAL's readable extent. /// NOTE: this is for static checking only. No useful runtime code can be generated for this /// at the moment. /// </summary> /// <param name="startAddress">Start of memory region</param> /// <returns>The result is the number of bytes readable starting at <paramref name="startAddress"/></returns> [CLSCompliant(false)] [Pure] [ContractRuntimeIgnored] [SecurityCritical] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif unsafe public static ulong ReadableBytes(void* startAddress) { return MaxWritableExtent - (ulong)startAddress; } #endif // FEATURE_UNSAFE_CONTRACTS #endregion #region Misc. /// <summary> /// Marker to indicate the end of the contract section of a method. /// </summary> [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #endif public static void EndContractBlock() { } #endregion #endregion User Methods #region Failure Behavior /// <summary> /// Without contract rewriting, failing Assert/Assumes end up calling this method. /// Code going through the contract rewriter never calls this method. Instead, the rewriter produced failures call /// System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent, followed by /// System.Runtime.CompilerServices.ContractHelper.TriggerFailure. /// </summary> static partial void ReportFailure(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException); /// <summary> /// This method is used internally to trigger a failure indicating to the "programmer" that he is using the interface incorrectly. /// It is NEVER used to indicate failure of actual contracts at runtime. /// </summary> static partial void AssertMustUseRewriter(ContractFailureKind kind, String contractKind); #endregion } public enum ContractFailureKind { Precondition, [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Postcondition")] Postcondition, [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Postcondition")] PostconditionOnException, Invariant, Assert, Assume, } } // Note: In .NET FX 4.5, we duplicated the ContractHelper class in the System.Runtime.CompilerServices // namespace to remove an ugly wart of a namespace from the Windows 8 profile. But we still need the // old locations left around, so we can support rewritten .NET FX 4.0 libraries. Consider removing // these from our reference assembly in a future version. namespace System.Diagnostics.Contracts.Internal { [Obsolete("Use the ContractHelper class in the System.Runtime.CompilerServices namespace instead.")] public static class ContractHelper { #region Rewriter Failure Hooks /// <summary> /// Rewriter will call this method on a contract failure to allow listeners to be notified. /// The method should not perform any failure (assert/throw) itself. /// </summary> /// <returns>null if the event was handled and should not trigger a failure. /// Otherwise, returns the localized failure message</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static string RaiseContractFailedEvent(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException) { return System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent(failureKind, userMessage, conditionText, innerException); } /// <summary> /// Rewriter calls this method to get the default failure behavior. /// </summary> [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #endif public static void TriggerFailure(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException) { System.Runtime.CompilerServices.ContractHelper.TriggerFailure(kind, displayMessage, userMessage, conditionText, innerException); } #endregion Rewriter Failure Hooks } } // namespace System.Diagnostics.Contracts.Internal namespace System.Runtime.CompilerServices { public static partial class ContractHelper { #region Rewriter Failure Hooks /// <summary> /// Rewriter will call this method on a contract failure to allow listeners to be notified. /// The method should not perform any failure (assert/throw) itself. /// </summary> /// <returns>null if the event was handled and should not trigger a failure. /// Otherwise, returns the localized failure message</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public static string RaiseContractFailedEvent(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException) { var resultFailureMessage = "Contract failed"; // default in case implementation does not assign anything. RaiseContractFailedEventImplementation(failureKind, userMessage, conditionText, innerException, ref resultFailureMessage); return resultFailureMessage; } /// <summary> /// Rewriter calls this method to get the default failure behavior. /// </summary> [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #endif public static void TriggerFailure(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException) { TriggerFailureImplementation(kind, displayMessage, userMessage, conditionText, innerException); } #endregion Rewriter Failure Hooks #region Implementation Stubs /// <summary> /// Rewriter will call this method on a contract failure to allow listeners to be notified. /// The method should not perform any failure (assert/throw) itself. /// This method has 3 functions: /// 1. Call any contract hooks (such as listeners to Contract failed events) /// 2. Determine if the listeneres deem the failure as handled (then resultFailureMessage should be set to null) /// 3. Produce a localized resultFailureMessage used in advertising the failure subsequently. /// </summary> /// <param name="resultFailureMessage">Should really be out (or the return value), but partial methods are not flexible enough. /// On exit: null if the event was handled and should not trigger a failure. /// Otherwise, returns the localized failure message</param> static partial void RaiseContractFailedEventImplementation(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException, ref string resultFailureMessage); /// <summary> /// Implements the default failure behavior of the platform. Under the BCL, it triggers an Assert box. /// </summary> static partial void TriggerFailureImplementation(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException); #endregion Implementation Stubs } } // namespace System.Runtime.CompilerServices
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gagr = Google.Api.Gax.ResourceNames; using gcmv = Google.Cloud.Monitoring.V3; namespace Google.Cloud.Monitoring.V3 { public partial class ListUptimeCheckConfigsRequest { /// <summary> /// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::ProjectName ParentAsProjectName { get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagr::OrganizationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::OrganizationName ParentAsOrganizationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::OrganizationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagr::FolderName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::FolderName ParentAsFolderName { get => string.IsNullOrEmpty(Parent) ? null : gagr::FolderName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gax::IResourceName ParentAsResourceName { get { if (string.IsNullOrEmpty(Parent)) { return null; } if (gagr::ProjectName.TryParse(Parent, out gagr::ProjectName project)) { return project; } if (gagr::OrganizationName.TryParse(Parent, out gagr::OrganizationName organization)) { return organization; } if (gagr::FolderName.TryParse(Parent, out gagr::FolderName folder)) { return folder; } return gax::UnparsedResourceName.Parse(Parent); } set => Parent = value?.ToString() ?? ""; } } public partial class GetUptimeCheckConfigRequest { /// <summary> /// <see cref="gcmv::UptimeCheckConfigName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcmv::UptimeCheckConfigName UptimeCheckConfigName { get => string.IsNullOrEmpty(Name) ? null : gcmv::UptimeCheckConfigName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="gax::IResourceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gax::IResourceName ResourceName { get { if (string.IsNullOrEmpty(Name)) { return null; } if (gcmv::UptimeCheckConfigName.TryParse(Name, out gcmv::UptimeCheckConfigName uptimeCheckConfig)) { return uptimeCheckConfig; } return gax::UnparsedResourceName.Parse(Name); } set => Name = value?.ToString() ?? ""; } } public partial class CreateUptimeCheckConfigRequest { /// <summary> /// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::ProjectName ParentAsProjectName { get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagr::OrganizationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::OrganizationName ParentAsOrganizationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::OrganizationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagr::FolderName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::FolderName ParentAsFolderName { get => string.IsNullOrEmpty(Parent) ? null : gagr::FolderName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gax::IResourceName ParentAsResourceName { get { if (string.IsNullOrEmpty(Parent)) { return null; } if (gagr::ProjectName.TryParse(Parent, out gagr::ProjectName project)) { return project; } if (gagr::OrganizationName.TryParse(Parent, out gagr::OrganizationName organization)) { return organization; } if (gagr::FolderName.TryParse(Parent, out gagr::FolderName folder)) { return folder; } return gax::UnparsedResourceName.Parse(Parent); } set => Parent = value?.ToString() ?? ""; } } public partial class DeleteUptimeCheckConfigRequest { /// <summary> /// <see cref="gcmv::UptimeCheckConfigName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcmv::UptimeCheckConfigName UptimeCheckConfigName { get => string.IsNullOrEmpty(Name) ? null : gcmv::UptimeCheckConfigName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="gax::IResourceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gax::IResourceName ResourceName { get { if (string.IsNullOrEmpty(Name)) { return null; } if (gcmv::UptimeCheckConfigName.TryParse(Name, out gcmv::UptimeCheckConfigName uptimeCheckConfig)) { return uptimeCheckConfig; } return gax::UnparsedResourceName.Parse(Name); } set => Name = value?.ToString() ?? ""; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Reflection; using Xunit; namespace System.Linq.Expressions.Tests { public static class CallTests { private struct Mutable { private int x; public int X { get { return x; } set { x = value; } } public int this[int i] { get { return x; } set { x = value; } } public int Foo() { return x++; } } private class Wrapper<T> { public const int Zero = 0; public T Field; #pragma warning disable 649 // For testing purposes public readonly T ReadOnlyField; #pragma warning restore public T Property { get { return Field; } set { Field = value; } } } private static class Methods { public static void ByRef(ref int x) { ++x; } } [Theory] [ClassData(typeof(CompilationTypes))] public static void UnboxReturnsReference(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(object)); UnaryExpression unbox = Expression.Unbox(p, typeof(Mutable)); MethodCallExpression call = Expression.Call(unbox, typeof(Mutable).GetMethod("Foo")); Func<object, int> lambda = Expression.Lambda<Func<object, int>>(call, p).Compile(useInterpreter); object boxed = new Mutable(); Assert.Equal(0, lambda(boxed)); Assert.Equal(1, lambda(boxed)); Assert.Equal(2, lambda(boxed)); Assert.Equal(3, lambda(boxed)); } [Theory] [ClassData(typeof(CompilationTypes))] public static void ArrayWriteBack(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(Mutable[])); BinaryExpression indexed = Expression.ArrayIndex(p, Expression.Constant(0)); MethodCallExpression call = Expression.Call(indexed, typeof(Mutable).GetMethod("Foo")); Func<Mutable[], int> lambda = Expression.Lambda<Func<Mutable[], int>>(call, p).Compile(useInterpreter); var array = new Mutable[1]; Assert.Equal(0, lambda(array)); Assert.Equal(1, lambda(array)); Assert.Equal(2, lambda(array)); } [Theory] [ClassData(typeof(CompilationTypes))] public static void EnumArgAndReturn(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(NonGenericClass.E1)); MethodCallExpression call = Expression.Call(typeof(NonGenericClass).GetMethod("FooEnum"), p); Func<NonGenericClass.E1, NonGenericClass.E2> lambda = Expression.Lambda<Func<NonGenericClass.E1, NonGenericClass.E2>>(call, p).Compile(useInterpreter); Assert.Equal(NonGenericClass.E2.One, lambda(NonGenericClass.E1.One)); Assert.Equal(NonGenericClass.E2.Two, lambda(NonGenericClass.E1.Two)); } [Theory] [ClassData(typeof(CompilationTypes))] public static void MultiRankArrayWriteBack(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(Mutable[,])); MethodCallExpression indexed = Expression.ArrayIndex(p, Expression.Constant(0), Expression.Constant(0)); MethodCallExpression call = Expression.Call(indexed, typeof(Mutable).GetMethod("Foo")); Func<Mutable[,], int> lambda = Expression.Lambda<Func<Mutable[,], int>>(call, p).Compile(useInterpreter); var array = new Mutable[1, 1]; Assert.Equal(0, lambda(array)); Assert.Equal(1, lambda(array)); Assert.Equal(2, lambda(array)); } [Theory] [ClassData(typeof(CompilationTypes))] public static void ArrayAccessWriteBack(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(Mutable[])); IndexExpression indexed = Expression.ArrayAccess(p, Expression.Constant(0)); MethodCallExpression call = Expression.Call(indexed, typeof(Mutable).GetMethod("Foo")); Func<Mutable[], int> lambda = Expression.Lambda<Func<Mutable[], int>>(call, p).Compile(useInterpreter); var array = new Mutable[1]; Assert.Equal(0, lambda(array)); Assert.Equal(1, lambda(array)); Assert.Equal(2, lambda(array)); } [Theory] [ClassData(typeof(CompilationTypes))] public static void MultiRankArrayAccessWriteBack(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(Mutable[,])); IndexExpression indexed = Expression.ArrayAccess(p, Expression.Constant(0), Expression.Constant(0)); MethodCallExpression call = Expression.Call(indexed, typeof(Mutable).GetMethod("Foo")); Func<Mutable[,], int> lambda = Expression.Lambda<Func<Mutable[,], int>>(call, p).Compile(useInterpreter); var array = new Mutable[1, 1]; Assert.Equal(0, lambda(array)); Assert.Equal(1, lambda(array)); Assert.Equal(2, lambda(array)); } [Theory] [ClassData(typeof(CompilationTypes))] public static void IndexedPropertyAccessNoWriteBack(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(List<Mutable>)); IndexExpression indexed = Expression.Property(p, typeof(List<Mutable>).GetProperty("Item"), Expression.Constant(0)); MethodCallExpression call = Expression.Call(indexed, typeof(Mutable).GetMethod("Foo")); Func<List<Mutable>, int> lambda = Expression.Lambda<Func<List<Mutable>, int>>(call, p).Compile(useInterpreter); var list = new List<Mutable> { new Mutable() }; Assert.Equal(0, lambda(list)); Assert.Equal(0, lambda(list)); } [Theory] [ClassData(typeof(CompilationTypes))] public static void FieldAccessWriteBack(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(Wrapper<Mutable>)); MemberExpression member = Expression.Field(p, typeof(Wrapper<Mutable>).GetField("Field")); MethodCallExpression call = Expression.Call(member, typeof(Mutable).GetMethod("Foo")); Func<Wrapper<Mutable>, int> lambda = Expression.Lambda<Func<Wrapper<Mutable>, int>>(call, p).Compile(useInterpreter); var wrapper = new Wrapper<Mutable>(); Assert.Equal(0, lambda(wrapper)); Assert.Equal(1, lambda(wrapper)); Assert.Equal(2, lambda(wrapper)); } [Theory] [ClassData(typeof(CompilationTypes))] public static void PropertyAccessNoWriteBack(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(Wrapper<Mutable>)); MemberExpression member = Expression.Property(p, typeof(Wrapper<Mutable>).GetProperty("Property")); MethodCallExpression call = Expression.Call(member, typeof(Mutable).GetMethod("Foo")); Func<Wrapper<Mutable>, int> lambda = Expression.Lambda<Func<Wrapper<Mutable>, int>>(call, p).Compile(useInterpreter); var wrapper = new Wrapper<Mutable>(); Assert.Equal(0, lambda(wrapper)); Assert.Equal(0, lambda(wrapper)); } [Theory] [ClassData(typeof(CompilationTypes))] public static void ReadonlyFieldAccessWriteBack(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(Wrapper<Mutable>)); MemberExpression member = Expression.Field(p, typeof(Wrapper<Mutable>).GetField("ReadOnlyField")); MethodCallExpression call = Expression.Call(member, typeof(Mutable).GetMethod("Foo")); Func<Wrapper<Mutable>, int> lambda = Expression.Lambda<Func<Wrapper<Mutable>, int>>(call, p).Compile(useInterpreter); var wrapper = new Wrapper<Mutable>(); Assert.Equal(0, lambda(wrapper)); Assert.Equal(0, lambda(wrapper)); Assert.Equal(0, lambda(wrapper)); } [Theory] [ClassData(typeof(CompilationTypes))] public static void ConstFieldAccessWriteBack(bool useInterpreter) { MemberExpression member = Expression.Field(null, typeof(Wrapper<Mutable>).GetField("Zero")); MethodCallExpression call = Expression.Call(member, typeof(int).GetMethod("GetType")); Func<Type> lambda = Expression.Lambda<Func<Type>>(call).Compile(useInterpreter); var wrapper = new Wrapper<Mutable>(); Assert.Equal(typeof(int), lambda()); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CallByRefMutableStructPropertyWriteBack(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(Mutable)); MemberExpression x = Expression.Property(p, "X"); MethodCallExpression call = Expression.Call(typeof(Methods).GetMethod("ByRef"), x); BlockExpression body = Expression.Block(call, x); Func<Mutable, int> lambda = Expression.Lambda<Func<Mutable, int>>(body, p).Compile(useInterpreter); var m = new Mutable() { X = 41 }; Assert.Equal(42, lambda(m)); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CallByRefMutableStructIndexWriteBack(bool useInterpreter) { // Should not produce tail-call, but should still succeed ParameterExpression p = Expression.Parameter(typeof(Mutable)); IndexExpression x = Expression.MakeIndex(p, typeof(Mutable).GetProperty("Item"), new[] { Expression.Constant(0) }); MethodCallExpression call = Expression.Call(typeof(Methods).GetMethod("ByRef"), x); Action<Mutable> act = Expression.Lambda<Action<Mutable>>(call, true, p).Compile(useInterpreter); Mutable m = new Mutable { X = 41 }; act(m); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CallByRefAttemptTailCall(bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(Mutable)); IndexExpression x = Expression.MakeIndex(p, typeof(Mutable).GetProperty("Item"), new[] { Expression.Constant(0) }); MethodCallExpression call = Expression.Call(typeof(Methods).GetMethod("ByRef"), x); BlockExpression body = Expression.Block(call, x); Func<Mutable, int> lambda = Expression.Lambda<Func<Mutable, int>>(body, p).Compile(useInterpreter); var m = new Mutable() { X = 41 }; Assert.Equal(42, lambda(m)); } [Theory] [ClassData(typeof(CompilationTypes))] public static void Call_InstanceNullInside_ThrowsNullReferenceExceptionOnInvocation(bool useInterpreter) { Expression call = Expression.Call(Expression.Constant(null, typeof(NonGenericClass)), typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.InstanceMethod))); Action compiledDelegate = Expression.Lambda<Action>(call).Compile(useInterpreter); TargetInvocationException exception = Assert.Throws<TargetInvocationException>(() => compiledDelegate.DynamicInvoke()); Assert.IsType<NullReferenceException>(exception.InnerException); } public static IEnumerable<object[]> Call_NoParameters_TestData() { // Basic yield return new object[] { Expression.Constant(new ClassWithInterface1()), typeof(ClassWithInterface1).GetMethod(nameof(ClassWithInterface1.Method)), 2 }; yield return new object[] { Expression.Constant(new StructWithInterface1()), typeof(StructWithInterface1).GetMethod(nameof(StructWithInterface1.Method)), 2 }; // Object method yield return new object[] { Expression.Constant(new ClassWithInterface1()), typeof(object).GetMethod(nameof(object.GetType)), typeof(ClassWithInterface1) }; yield return new object[] { Expression.Constant(new StructWithInterface1()), typeof(object).GetMethod(nameof(object.GetType)), typeof(StructWithInterface1) }; yield return new object[] { Expression.Constant(Int32Enum.A), typeof(object).GetMethod(nameof(object.GetType)), typeof(Int32Enum) }; // ValueType method from struct yield return new object[] { Expression.Constant(new StructWithInterface1()), typeof(ValueType).GetMethod(nameof(ValueType.ToString)), new StructWithInterface1().ToString() }; // Enum method from enum yield return new object[] { Expression.Constant(Int32Enum.A), typeof(Enum).GetMethod(nameof(Enum.ToString), new Type[0]), "A" }; // Interface method yield return new object[] { Expression.Constant(new ClassWithInterface1()), typeof(Interface1).GetMethod(nameof(Interface1.InterfaceMethod)), 1 }; yield return new object[] { Expression.Constant(new StructWithInterface1()), typeof(Interface1).GetMethod(nameof(Interface1.InterfaceMethod)), 1 }; yield return new object[] { Expression.Constant(new ClassWithCompoundInterface()), typeof(Interface1).GetMethod(nameof(Interface1.InterfaceMethod)), 1 }; yield return new object[] { Expression.Constant(new StructWithCompoundInterface()), typeof(Interface1).GetMethod(nameof(Interface1.InterfaceMethod)), 1 }; // Interface method, interface type yield return new object[] { Expression.Constant(new ClassWithInterface1(), typeof(Interface1)), typeof(Interface1).GetMethod(nameof(Interface1.InterfaceMethod)), 1 }; yield return new object[] { Expression.Constant(new StructWithInterface1(), typeof(Interface1)), typeof(Interface1).GetMethod(nameof(Interface1.InterfaceMethod)), 1 }; } [Theory] [PerCompilationType(nameof(Call_NoParameters_TestData))] public static void Call_NoParameters(Expression instance, MethodInfo method, object expected, bool useInterpreter) { Expression call = Expression.Call(instance, method); Delegate compiledDelegate = Expression.Lambda(call).Compile(useInterpreter); Assert.Equal(expected, compiledDelegate.DynamicInvoke()); } private static Expression s_valid => Expression.Constant(5); private static MethodInfo s_method0 = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.Method0)); private static MethodInfo s_method1 = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.Method1)); private static MethodInfo s_method2 = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.Method2)); private static MethodInfo s_method3 = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.Method3)); private static MethodInfo s_method4 = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.Method4)); private static MethodInfo s_method5 = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.Method5)); private static MethodInfo s_method6 = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.Method6)); private static MethodInfo s_method7 = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.Method7)); public static IEnumerable<object[]> Method_Invalid_TestData() { yield return new object[] { null, typeof(ArgumentNullException) }; yield return new object[] { typeof(GenericClass<>).GetMethod(nameof(GenericClass<string>.NonGenericMethod)), typeof(ArgumentException) }; yield return new object[] { typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.GenericMethod)), typeof(ArgumentException) }; } [Theory] [MemberData(nameof(Method_Invalid_TestData))] public static void Method_Invalid_ThrowsArgumentException(MethodInfo method, Type exceptionType) { AssertArgumentException(() => Expression.Call(null, method), exceptionType, "method"); AssertArgumentException(() => Expression.Call(null, method, s_valid, s_valid), exceptionType, "method"); AssertArgumentException(() => Expression.Call(null, method, s_valid, s_valid, s_valid), exceptionType, "method"); AssertArgumentException(() => Expression.Call(null, method, new Expression[0]), exceptionType, "method"); AssertArgumentException(() => Expression.Call(null, method, (IEnumerable<Expression>)new Expression[0]), exceptionType, "method"); AssertArgumentException(() => Expression.Call(method, s_valid), exceptionType, "method"); AssertArgumentException(() => Expression.Call(method, s_valid, s_valid), exceptionType, "method"); AssertArgumentException(() => Expression.Call(method, s_valid, s_valid, s_valid), exceptionType, "method"); AssertArgumentException(() => Expression.Call(method, s_valid, s_valid, s_valid, s_valid), exceptionType, "method"); AssertArgumentException(() => Expression.Call(method, s_valid, s_valid, s_valid, s_valid, s_valid), exceptionType, "method"); AssertArgumentException(() => Expression.Call(method, new Expression[0]), exceptionType, "method"); AssertArgumentException(() => Expression.Call(method, (IEnumerable<Expression>)new Expression[0]), exceptionType, "method"); } [Fact] public static void Method_Invalid_Via_Name() { AssertExtensions.Throws<ArgumentException>("method", () => Expression.Call(typeof(GenericClass<>), nameof(GenericClass<string>.NonGenericMethod), Type.EmptyTypes)); AssertExtensions.Throws<ArgumentException>("method", () => Expression.Call(typeof(GenericClass<>).MakeGenericType(typeof(GenericClass<>)), nameof(GenericClass<string>.NonGenericMethod), Type.EmptyTypes)); } public static IEnumerable<object[]> Method_DoesntBelongToInstance_TestData() { // Different declaring type yield return new object[] { Expression.Constant(new ClassWithInterface1()), typeof(OtherClassWithInterface1).GetMethod(nameof(Interface1.InterfaceMethod)) }; yield return new object[] { Expression.Constant(new StructWithInterface1()), typeof(OtherStructWithInterface1).GetMethod(nameof(Interface1.InterfaceMethod)) }; // Different interface yield return new object[] { Expression.Constant(new ClassWithInterface1()), typeof(Interface2).GetMethod(nameof(Interface2.InterfaceMethod)) }; yield return new object[] { Expression.Constant(new StructWithInterface1()), typeof(Interface2).GetMethod(nameof(Interface2.InterfaceMethod)) }; // Custom type yield return new object[] { Expression.Constant(new ClassWithInterface1(), typeof(object)), typeof(ClassWithInterface1).GetMethod(nameof(ClassWithInterface1.Method)) }; yield return new object[] { Expression.Constant(new StructWithInterface1(), typeof(object)), typeof(ClassWithInterface1).GetMethod(nameof(ClassWithInterface1.Method)) }; } [Theory] [MemberData(nameof(Method_DoesntBelongToInstance_TestData))] public static void Method_DoesntBelongToInstance_ThrowsArgumentException(Expression instance, MethodInfo method) { AssertExtensions.Throws<ArgumentException>(null, () => Expression.Call(instance, method)); } [Fact] public static void InstanceMethod_NullInstance_ThrowsArgumentException() { MethodInfo method = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.InstanceMethod)); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Call(method, s_valid)); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Call(method, s_valid, s_valid)); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Call(method, s_valid, s_valid, s_valid)); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Call(method, s_valid, s_valid, s_valid, s_valid)); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Call(method, s_valid, s_valid, s_valid, s_valid, s_valid)); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Call(method, new Expression[0])); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Call(method, (IEnumerable<Expression>)new Expression[0])); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Call(null, method, s_valid)); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Call(null, method, s_valid, s_valid)); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Call(null, method, s_valid, s_valid, s_valid)); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Call(null, method, new Expression[0])); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Call(null, method, (IEnumerable<Expression>)new Expression[0])); } [Fact] public static void StaticMethod_NonNullInstance_ThrowsArgumentException() { Expression instance = Expression.Constant(new NonGenericClass()); MethodInfo method = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.StaticMethod)); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Call(instance, method, s_valid)); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Call(instance, method, s_valid, s_valid)); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Call(instance, method, s_valid, s_valid, s_valid)); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Call(instance, method, new Expression[0])); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Call(instance, method, (IEnumerable<Expression>)new Expression[0])); } public static IEnumerable<object[]> InvalidArg_TestData() { yield return new object[] { null, typeof(ArgumentNullException) }; yield return new object[] { Expression.Property(null, typeof(Unreadable<string>), nameof(Unreadable<string>.WriteOnly)), typeof(ArgumentException) }; yield return new object[] { Expression.Constant("abc"), typeof(ArgumentException) }; } [Theory] [MemberData(nameof(InvalidArg_TestData))] public static void Arg0_Invalid(Expression arg, Type exceptionType) { AssertArgumentException(() => Expression.Call(s_method1, arg), exceptionType, "arg0"); AssertArgumentException(() => Expression.Call(s_method2, arg, s_valid), exceptionType, "arg0"); AssertArgumentException(() => Expression.Call(s_method3, arg, s_valid, s_valid), exceptionType, "arg0"); AssertArgumentException(() => Expression.Call(s_method4, arg, s_valid, s_valid, s_valid), exceptionType, "arg0"); AssertArgumentException(() => Expression.Call(s_method5, arg, s_valid, s_valid, s_valid, s_valid), exceptionType, "arg0"); AssertArgumentException(() => Expression.Call(null, s_method1, arg), exceptionType, "arg0"); AssertArgumentException(() => Expression.Call(null, s_method2, arg, s_valid), exceptionType, "arg0"); AssertArgumentException(() => Expression.Call(null, s_method3, arg, s_valid, s_valid), exceptionType, "arg0"); } [Theory] [MemberData(nameof(InvalidArg_TestData))] public static void Arg1_Invalid(Expression arg, Type exceptionType) { AssertArgumentException(() => Expression.Call(s_method2, s_valid, arg), exceptionType, "arg1"); AssertArgumentException(() => Expression.Call(s_method3, s_valid, arg, s_valid), exceptionType, "arg1"); AssertArgumentException(() => Expression.Call(s_method4, s_valid, arg, s_valid, s_valid), exceptionType, "arg1"); AssertArgumentException(() => Expression.Call(s_method5, s_valid, arg, s_valid, s_valid, s_valid), exceptionType, "arg1"); AssertArgumentException(() => Expression.Call(null, s_method2, s_valid, arg), exceptionType, "arg1"); AssertArgumentException(() => Expression.Call(null, s_method3, s_valid, arg, s_valid), exceptionType, "arg1"); } [Theory] [MemberData(nameof(InvalidArg_TestData))] public static void Arg2_Invalid(Expression arg, Type exceptionType) { AssertArgumentException(() => Expression.Call(s_method3, s_valid, s_valid, arg), exceptionType, "arg2"); AssertArgumentException(() => Expression.Call(s_method4, s_valid, s_valid, arg, s_valid), exceptionType, "arg2"); AssertArgumentException(() => Expression.Call(s_method5, s_valid, s_valid, arg, s_valid, s_valid), exceptionType, "arg2"); AssertArgumentException(() => Expression.Call(null, s_method3, s_valid, s_valid, arg), exceptionType, "arg2"); } [Theory] [MemberData(nameof(InvalidArg_TestData))] public static void Arg3_Invalid(Expression arg, Type exceptionType) { AssertArgumentException(() => Expression.Call(s_method4, s_valid, s_valid, s_valid, arg), exceptionType, "arg3"); AssertArgumentException(() => Expression.Call(s_method5, s_valid, s_valid, s_valid, arg, s_valid), exceptionType, "arg3"); } [Theory] [MemberData(nameof(InvalidArg_TestData))] public static void Arg4_Invalid(Expression arg, Type exceptionType) { AssertArgumentException(() => Expression.Call(s_method5, s_valid, s_valid, s_valid, s_valid, arg), exceptionType, "arg4"); } private static void AssertArgumentException(Action action, Type exceptionType, string paramName) { ArgumentException ex = (ArgumentException)Assert.Throws(exceptionType, action); Assert.Equal(paramName, ex.ParamName); } [Theory] [InlineData(typeof(NonGenericClass), nameof(NonGenericClass.Method0), 0)] [InlineData(typeof(NonGenericClass), nameof(NonGenericClass.Method1), 1)] [InlineData(typeof(NonGenericClass), nameof(NonGenericClass.Method2), 2)] [InlineData(typeof(NonGenericClass), nameof(NonGenericClass.Method3), 3)] [InlineData(typeof(NonGenericClass), nameof(NonGenericClass.Method4), 4)] [InlineData(typeof(NonGenericClass), nameof(NonGenericClass.Method5), 5)] public static void InvalidArgumentCount_ThrowsArgumentException(Type type, string name, int count) { MethodInfo method = type.GetMethod(name); Expression arg = Expression.Constant("abc"); if (count != 0) { AssertExtensions.Throws<ArgumentException>("method", () => Expression.Call(method)); AssertExtensions.Throws<ArgumentException>("method", () => Expression.Call(null, method)); } if (count != 1) { AssertExtensions.Throws<ArgumentException>("method", () => Expression.Call(method, arg)); AssertExtensions.Throws<ArgumentException>("method", () => Expression.Call(null, method, arg)); } if (count != 2) { AssertExtensions.Throws<ArgumentException>("method", () => Expression.Call(method, arg, arg)); AssertExtensions.Throws<ArgumentException>("method", () => Expression.Call(null, method, arg, arg)); } if (count != 3) { AssertExtensions.Throws<ArgumentException>("method", () => Expression.Call(method, arg, arg, arg)); AssertExtensions.Throws<ArgumentException>("method", () => Expression.Call(null, method, arg, arg, arg)); } if (count != 4) { AssertExtensions.Throws<ArgumentException>("method", () => Expression.Call(method, arg, arg, arg, arg)); } if (count != 5) { AssertExtensions.Throws<ArgumentException>("method", () => Expression.Call(method, arg, arg, arg, arg, arg)); } AssertExtensions.Throws<ArgumentException>("method", () => Expression.Call(method, Enumerable.Repeat(arg, count + 1).ToArray())); AssertExtensions.Throws<ArgumentException>("method", () => Expression.Call(method, Enumerable.Repeat(arg, count + 1))); AssertExtensions.Throws<ArgumentException>("method", () => Expression.Call(null, method, Enumerable.Repeat(arg, count + 1).ToArray())); AssertExtensions.Throws<ArgumentException>("method", () => Expression.Call(null, method, Enumerable.Repeat(arg, count + 1))); } [Fact] public static void MethodName_NullInstance_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("instance", () => Expression.Call((Expression)null, "methodName", new Type[0], new Expression[0])); } [Fact] public static void MethodName_NullType_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("type", () => Expression.Call((Type)null, "methodName", new Type[0], new Expression[0])); } [Fact] public static void NullMethodName_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("methodName", () => Expression.Call(Expression.Constant(new NonGenericClass()), null, new Type[0], new Expression[0])); AssertExtensions.Throws<ArgumentNullException>("methodName", () => Expression.Call(typeof(NonGenericClass), null, new Type[0], new Expression[0])); } [Fact] public static void MethodName_DoesNotExist_ThrowsInvalidOperationException() { Assert.Throws<InvalidOperationException>(() => Expression.Call(Expression.Constant(new NonGenericClass()), "NoSuchMethod", null)); Assert.Throws<InvalidOperationException>(() => Expression.Call(typeof(NonGenericClass), "NoSuchMethod", null)); } public static IEnumerable<object[]> InvalidTypeArgs_TestData() { yield return new object[] { null }; yield return new object[] { new Type[0] }; yield return new object[] { new Type[2] }; } [Theory] [MemberData(nameof(InvalidTypeArgs_TestData))] public static void MethodName_NoSuchGenericMethodWithTypeArgs_ThrowsInvalidOperationException(Type[] typeArgs) { Assert.Throws<InvalidOperationException>(() => Expression.Call(Expression.Constant(new NonGenericClass()), nameof(NonGenericClass.GenericInstanceMethod), typeArgs)); Assert.Throws<InvalidOperationException>(() => Expression.Call(typeof(NonGenericClass), nameof(NonGenericClass.GenericStaticMethod), typeArgs)); } [Fact] public static void MethodName_TypeArgsDontMatchConstraints_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>(null, () => Expression.Call(Expression.Constant(new NonGenericClass()), nameof(NonGenericClass.ConstrainedInstanceMethod), new Type[] { typeof(object) })); AssertExtensions.Throws<ArgumentException>(null, () => Expression.Call(typeof(NonGenericClass), nameof(NonGenericClass.ConstrainedStaticMethod), new Type[] { typeof(object) })); } [Fact] public static void MethodName_NonGenericMethodHasTypeArgs_ThrowsInvalidOperationException() { Assert.Throws<InvalidOperationException>(() => Expression.Call(Expression.Constant(new NonGenericClass()), nameof(NonGenericClass.InstanceMethod), new Type[1])); Assert.Throws<InvalidOperationException>(() => Expression.Call(typeof(NonGenericClass), nameof(NonGenericClass.StaticMethod), new Type[1])); } [Fact] public static void MethodName_TypeArgsHasNullValue_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>(null, () => Expression.Call(Expression.Constant(new NonGenericClass()), nameof(NonGenericClass.GenericInstanceMethod), new Type[] { null })); AssertExtensions.Throws<ArgumentNullException>(null, () => Expression.Call(typeof(NonGenericClass), nameof(NonGenericClass.GenericStaticMethod), new Type[] { null })); } [Fact] public static void MethodName_ArgumentsHasNullValue_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("arguments", () => Expression.Call(Expression.Constant(new NonGenericClass()), nameof(NonGenericClass.InstanceMethod1), new Type[0], new Expression[] { null })); AssertExtensions.Throws<ArgumentNullException>("arguments", () => Expression.Call(typeof(NonGenericClass), nameof(NonGenericClass.StaticMethod1), new Type[0], new Expression[] { null })); } [Fact] public static void MethodName_ArgumentsHasNullValueButDifferentCount_ThrowsInvalidOperationException() { Assert.Throws<InvalidOperationException>(() => Expression.Call(Expression.Constant(new NonGenericClass()), nameof(NonGenericClass.InstanceMethod1), new Type[0], new Expression[] { null, Expression.Constant("") })); Assert.Throws<InvalidOperationException>(() => Expression.Call(typeof(NonGenericClass), nameof(NonGenericClass.StaticMethod1), new Type[0], new Expression[] { null, Expression.Constant("") })); } [Fact] public static void ToStringTest() { // NB: Static methods are inconsistent compared to static members; the declaring type is not included MethodCallExpression e1 = Expression.Call(null, typeof(SomeMethods).GetMethod(nameof(SomeMethods.S0), BindingFlags.Static | BindingFlags.Public)); Assert.Equal("S0()", e1.ToString()); MethodCallExpression e2 = Expression.Call(null, typeof(SomeMethods).GetMethod(nameof(SomeMethods.S1), BindingFlags.Static | BindingFlags.Public), Expression.Parameter(typeof(int), "x")); Assert.Equal("S1(x)", e2.ToString()); MethodCallExpression e3 = Expression.Call(null, typeof(SomeMethods).GetMethod(nameof(SomeMethods.S2), BindingFlags.Static | BindingFlags.Public), Expression.Parameter(typeof(int), "x"), Expression.Parameter(typeof(int), "y")); Assert.Equal("S2(x, y)", e3.ToString()); MethodCallExpression e4 = Expression.Call(Expression.Parameter(typeof(SomeMethods), "o"), typeof(SomeMethods).GetMethod(nameof(SomeMethods.I0), BindingFlags.Instance | BindingFlags.Public)); Assert.Equal("o.I0()", e4.ToString()); MethodCallExpression e5 = Expression.Call(Expression.Parameter(typeof(SomeMethods), "o"), typeof(SomeMethods).GetMethod(nameof(SomeMethods.I1), BindingFlags.Instance | BindingFlags.Public), Expression.Parameter(typeof(int), "x")); Assert.Equal("o.I1(x)", e5.ToString()); MethodCallExpression e6 = Expression.Call(Expression.Parameter(typeof(SomeMethods), "o"), typeof(SomeMethods).GetMethod(nameof(SomeMethods.I2), BindingFlags.Instance | BindingFlags.Public), Expression.Parameter(typeof(int), "x"), Expression.Parameter(typeof(int), "y")); Assert.Equal("o.I2(x, y)", e6.ToString()); MethodCallExpression e7 = Expression.Call(null, typeof(ExtensionMethods).GetMethod(nameof(ExtensionMethods.E0), BindingFlags.Static | BindingFlags.Public), Expression.Parameter(typeof(int), "x")); Assert.Equal("x.E0()", e7.ToString()); MethodCallExpression e8 = Expression.Call(null, typeof(ExtensionMethods).GetMethod(nameof(ExtensionMethods.E1), BindingFlags.Static | BindingFlags.Public), Expression.Parameter(typeof(int), "x"), Expression.Parameter(typeof(int), "y")); Assert.Equal("x.E1(y)", e8.ToString()); MethodCallExpression e9 = Expression.Call(null, typeof(ExtensionMethods).GetMethod(nameof(ExtensionMethods.E2), BindingFlags.Static | BindingFlags.Public), Expression.Parameter(typeof(int), "x"), Expression.Parameter(typeof(int), "y"), Expression.Parameter(typeof(int), "z")); Assert.Equal("x.E2(y, z)", e9.ToString()); } [Fact] public static void GetArguments() { VerifyGetArguments(Expression.Call(null, s_method0)); VerifyGetArguments(Expression.Call(null, s_method1, Expression.Constant(0))); VerifyGetArguments( Expression.Call(null, s_method2, Enumerable.Range(0, 2).Select(i => Expression.Constant(i)))); VerifyGetArguments( Expression.Call(null, s_method3, Enumerable.Range(0, 3).Select(i => Expression.Constant(i)))); VerifyGetArguments( Expression.Call(null, s_method4, Enumerable.Range(0, 4).Select(i => Expression.Constant(i)))); VerifyGetArguments( Expression.Call(null, s_method5, Enumerable.Range(0, 5).Select(i => Expression.Constant(i)))); VerifyGetArguments( Expression.Call(null, s_method6, Enumerable.Range(0, 6).Select(i => Expression.Constant(i)))); VerifyGetArguments( Expression.Call(null, s_method7, Enumerable.Range(0, 7).Select(i => Expression.Constant(i)))); var site = Expression.Default(typeof(NonGenericClass)); VerifyGetArguments(Expression.Call(site, nameof(NonGenericClass.InstanceMethod0), null)); VerifyGetArguments( Expression.Call(site, nameof(NonGenericClass.InstanceMethod1), null, Expression.Constant(0))); VerifyGetArguments( Expression.Call( site, nameof(NonGenericClass.InstanceMethod2), null, Enumerable.Range(0, 2).Select(i => Expression.Constant(i)).ToArray())); VerifyGetArguments( Expression.Call( site, nameof(NonGenericClass.InstanceMethod3), null, Enumerable.Range(0, 3).Select(i => Expression.Constant(i)).ToArray())); VerifyGetArguments( Expression.Call( site, nameof(NonGenericClass.InstanceMethod4), null, Enumerable.Range(0, 4).Select(i => Expression.Constant(i)).ToArray())); } private static void VerifyGetArguments(MethodCallExpression call) { var args = call.Arguments; Assert.Equal(args.Count, call.ArgumentCount); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => call.GetArgument(-1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => call.GetArgument(args.Count)); for (int i = 0; i != args.Count; ++i) { Assert.Same(args[i], call.GetArgument(i)); Assert.Equal(i, ((ConstantExpression)call.GetArgument(i)).Value); } } [Theory] [ClassData(typeof(CompilationTypes))] public static void EnumReturnType0(bool useInterpreter) { Expression<Func<DayOfWeek[]>> expr = () => new[] { ToDayOfWeek0() }; Assert.Equal(DayOfWeek.Monday, expr.Compile(useInterpreter)()[0]); } [Theory] [ClassData(typeof(CompilationTypes))] public static void EnumReturnType1(bool useInterpreter) { Expression<Func<DayOfWeek[]>> expr = () => new[] { ToDayOfWeek1(1) }; Assert.Equal(DayOfWeek.Monday, expr.Compile(useInterpreter)()[0]); } [Theory] [ClassData(typeof(CompilationTypes))] public static void EnumReturnType2(bool useInterpreter) { Expression<Func<DayOfWeek[]>> expr = () => new[] { ToDayOfWeek2(0, 1) }; Assert.Equal(DayOfWeek.Monday, expr.Compile(useInterpreter)()[0]); } private static DayOfWeek ToDayOfWeek0() => DayOfWeek.Monday; private static DayOfWeek ToDayOfWeek1(int i) => (DayOfWeek)i; private static DayOfWeek ToDayOfWeek2(int i, int j) => (DayOfWeek)(i + j); [Theory] [ClassData(typeof(CompilationTypes))] public static void NullableEnumReturnType0(bool useInterpreter) { Expression<Func<DayOfWeek?[]>> expr = () => new[] { ToDayOfWeekOpt0() }; Assert.Equal(DayOfWeek.Monday, expr.Compile(useInterpreter)()[0].Value); } [Theory] [ClassData(typeof(CompilationTypes))] public static void NullableEnumReturnType1(bool useInterpreter) { Expression<Func<DayOfWeek?[]>> expr = () => new[] { ToDayOfWeekOpt1(1) }; Assert.Equal(DayOfWeek.Monday, expr.Compile(useInterpreter)()[0].Value); } [Theory] [ClassData(typeof(CompilationTypes))] public static void NullableEnumReturnType2(bool useInterpreter) { Expression<Func<DayOfWeek?[]>> expr = () => new[] { ToDayOfWeekOpt2(0, 1) }; Assert.Equal(DayOfWeek.Monday, expr.Compile(useInterpreter)()[0].Value); } private static DayOfWeek? ToDayOfWeekOpt0() => DayOfWeek.Monday; private static DayOfWeek? ToDayOfWeekOpt1(int i) => (DayOfWeek)i; private static DayOfWeek? ToDayOfWeekOpt2(int i, int j) => (DayOfWeek)(i + j); public class GenericClass<T> { public static void NonGenericMethod() { } } public static class Unreadable<T> { public static T WriteOnly { set { } } } public class NonGenericClass { public static void GenericMethod<T>() { } public void InstanceMethod() { } public static void StaticMethod() { } public static void Method0() { } public static void Method1(int i1) { } public static void Method2(int i1, int i2) { } public static void Method3(int i1, int i2, int i3) { } public static void Method4(int i1, int i2, int i3, int i4) { } public static void Method5(int i1, int i2, int i3, int i4, int i5) { } public static void Method6(int i1, int i2, int i3, int i4, int i5, int i6) { } public static void Method7(int i1, int i2, int i3, int i4, int i5, int i6, int i7) { } public void staticSameName(uint i1) { } public void instanceSameName(int i1) { } public static void StaticSameName(uint i1) { } public static void staticSameName(int i1) { } public void GenericInstanceMethod<T>(T t1) { } public static void GenericStaticMethod<T>(T t1) { } public void ConstrainedInstanceMethod<T>(T t1) where T : struct { } public static void ConstrainedStaticMethod<T>(T t1) where T : struct { } public void InstanceMethod0() { } public void InstanceMethod1(int i1) { } public void InstanceMethod2(int i1, int i2) { } public void InstanceMethod3(int i1, int i2, int i3) { } public void InstanceMethod4(int i1, int i2, int i3, int i4) { } public static void StaticMethod1(int i1) { } public enum E1 : byte { One, Two } public enum E2 : int { One, Two } public static E2 FooEnum(E1 arg) { return (E2)arg; } } public interface Interface1 { int InterfaceMethod(); } public interface Interface2 { int InterfaceMethod(); } public interface CompoundInterface : Interface1 { } public class ClassWithInterface1 : Interface1 { public int InterfaceMethod() => 1; public int Method() => 2; } public class OtherClassWithInterface1 : Interface1 { public int InterfaceMethod() => 1; } public struct StructWithInterface1 : Interface1 { public int InterfaceMethod() => 1; public int Method() => 2; } public struct OtherStructWithInterface1 : Interface1 { public int InterfaceMethod() => 1; } public class ClassWithCompoundInterface : CompoundInterface { public int InterfaceMethod() => 1; } public struct StructWithCompoundInterface : CompoundInterface { public int InterfaceMethod() => 1; } } class SomeMethods { public static void S0() { } public static void S1(int x) { } public static void S2(int x, int y) { } public void I0() { } public void I1(int x) { } public void I2(int x, int y) { } } static class ExtensionMethods { public static void E0(this int x) { } public static void E1(this int x, int y) { } public static void E2(this int x, int y, int z) { } } }
using System; using BACnet.Types; using BACnet.Types.Schemas; namespace BACnet.Ashrae { public abstract partial class UnconfirmedServiceRequest { public abstract Tags Tag { get; } public bool IsIAm { get { return this.Tag == Tags.IAm; } } public IAmRequest AsIAm { get { return ((IAmWrapper)this).Item; } } public static UnconfirmedServiceRequest NewIAm(IAmRequest iAm) { return new IAmWrapper(iAm); } public bool IsIHave { get { return this.Tag == Tags.IHave; } } public IHaveRequest AsIHave { get { return ((IHaveWrapper)this).Item; } } public static UnconfirmedServiceRequest NewIHave(IHaveRequest iHave) { return new IHaveWrapper(iHave); } public bool IsUnconfirmedCOVNotification { get { return this.Tag == Tags.UnconfirmedCOVNotification; } } public UnconfirmedCOVNotificationRequest AsUnconfirmedCOVNotification { get { return ((UnconfirmedCOVNotificationWrapper)this).Item; } } public static UnconfirmedServiceRequest NewUnconfirmedCOVNotification(UnconfirmedCOVNotificationRequest unconfirmedCOVNotification) { return new UnconfirmedCOVNotificationWrapper(unconfirmedCOVNotification); } public bool IsUnconfirmedEventNotification { get { return this.Tag == Tags.UnconfirmedEventNotification; } } public UnconfirmedEventNotificationRequest AsUnconfirmedEventNotification { get { return ((UnconfirmedEventNotificationWrapper)this).Item; } } public static UnconfirmedServiceRequest NewUnconfirmedEventNotification(UnconfirmedEventNotificationRequest unconfirmedEventNotification) { return new UnconfirmedEventNotificationWrapper(unconfirmedEventNotification); } public bool IsUnconfirmedPrivateTransfer { get { return this.Tag == Tags.UnconfirmedPrivateTransfer; } } public UnconfirmedPrivateTransferRequest AsUnconfirmedPrivateTransfer { get { return ((UnconfirmedPrivateTransferWrapper)this).Item; } } public static UnconfirmedServiceRequest NewUnconfirmedPrivateTransfer(UnconfirmedPrivateTransferRequest unconfirmedPrivateTransfer) { return new UnconfirmedPrivateTransferWrapper(unconfirmedPrivateTransfer); } public bool IsUnconfirmedTextMessage { get { return this.Tag == Tags.UnconfirmedTextMessage; } } public UnconfirmedTextMessageRequest AsUnconfirmedTextMessage { get { return ((UnconfirmedTextMessageWrapper)this).Item; } } public static UnconfirmedServiceRequest NewUnconfirmedTextMessage(UnconfirmedTextMessageRequest unconfirmedTextMessage) { return new UnconfirmedTextMessageWrapper(unconfirmedTextMessage); } public bool IsTimeSynchronization { get { return this.Tag == Tags.TimeSynchronization; } } public TimeSynchronizationRequest AsTimeSynchronization { get { return ((TimeSynchronizationWrapper)this).Item; } } public static UnconfirmedServiceRequest NewTimeSynchronization(TimeSynchronizationRequest timeSynchronization) { return new TimeSynchronizationWrapper(timeSynchronization); } public bool IsWhoHas { get { return this.Tag == Tags.WhoHas; } } public WhoHasRequest AsWhoHas { get { return ((WhoHasWrapper)this).Item; } } public static UnconfirmedServiceRequest NewWhoHas(WhoHasRequest whoHas) { return new WhoHasWrapper(whoHas); } public bool IsWhoIs { get { return this.Tag == Tags.WhoIs; } } public WhoIsRequest AsWhoIs { get { return ((WhoIsWrapper)this).Item; } } public static UnconfirmedServiceRequest NewWhoIs(WhoIsRequest whoIs) { return new WhoIsWrapper(whoIs); } public bool IsUtcTimeSynchronization { get { return this.Tag == Tags.UtcTimeSynchronization; } } public UTCTimeSynchronizationRequest AsUtcTimeSynchronization { get { return ((UtcTimeSynchronizationWrapper)this).Item; } } public static UnconfirmedServiceRequest NewUtcTimeSynchronization(UTCTimeSynchronizationRequest utcTimeSynchronization) { return new UtcTimeSynchronizationWrapper(utcTimeSynchronization); } public static readonly ISchema Schema = new ChoiceSchema(false, new FieldSchema("IAm", 0, Value<IAmRequest>.Schema), new FieldSchema("IHave", 1, Value<IHaveRequest>.Schema), new FieldSchema("UnconfirmedCOVNotification", 2, Value<UnconfirmedCOVNotificationRequest>.Schema), new FieldSchema("UnconfirmedEventNotification", 3, Value<UnconfirmedEventNotificationRequest>.Schema), new FieldSchema("UnconfirmedPrivateTransfer", 4, Value<UnconfirmedPrivateTransferRequest>.Schema), new FieldSchema("UnconfirmedTextMessage", 5, Value<UnconfirmedTextMessageRequest>.Schema), new FieldSchema("TimeSynchronization", 6, Value<TimeSynchronizationRequest>.Schema), new FieldSchema("WhoHas", 7, Value<WhoHasRequest>.Schema), new FieldSchema("WhoIs", 8, Value<WhoIsRequest>.Schema), new FieldSchema("UtcTimeSynchronization", 9, Value<UTCTimeSynchronizationRequest>.Schema)); public static UnconfirmedServiceRequest Load(IValueStream stream) { UnconfirmedServiceRequest ret = null; Tags tag = (Tags)stream.EnterChoice(); switch(tag) { case Tags.IAm: ret = Value<IAmWrapper>.Load(stream); break; case Tags.IHave: ret = Value<IHaveWrapper>.Load(stream); break; case Tags.UnconfirmedCOVNotification: ret = Value<UnconfirmedCOVNotificationWrapper>.Load(stream); break; case Tags.UnconfirmedEventNotification: ret = Value<UnconfirmedEventNotificationWrapper>.Load(stream); break; case Tags.UnconfirmedPrivateTransfer: ret = Value<UnconfirmedPrivateTransferWrapper>.Load(stream); break; case Tags.UnconfirmedTextMessage: ret = Value<UnconfirmedTextMessageWrapper>.Load(stream); break; case Tags.TimeSynchronization: ret = Value<TimeSynchronizationWrapper>.Load(stream); break; case Tags.WhoHas: ret = Value<WhoHasWrapper>.Load(stream); break; case Tags.WhoIs: ret = Value<WhoIsWrapper>.Load(stream); break; case Tags.UtcTimeSynchronization: ret = Value<UtcTimeSynchronizationWrapper>.Load(stream); break; default: throw new Exception(); } stream.LeaveChoice(); return ret; } public static void Save(IValueSink sink, UnconfirmedServiceRequest value) { sink.EnterChoice((byte)value.Tag); switch(value.Tag) { case Tags.IAm: Value<IAmWrapper>.Save(sink, (IAmWrapper)value); break; case Tags.IHave: Value<IHaveWrapper>.Save(sink, (IHaveWrapper)value); break; case Tags.UnconfirmedCOVNotification: Value<UnconfirmedCOVNotificationWrapper>.Save(sink, (UnconfirmedCOVNotificationWrapper)value); break; case Tags.UnconfirmedEventNotification: Value<UnconfirmedEventNotificationWrapper>.Save(sink, (UnconfirmedEventNotificationWrapper)value); break; case Tags.UnconfirmedPrivateTransfer: Value<UnconfirmedPrivateTransferWrapper>.Save(sink, (UnconfirmedPrivateTransferWrapper)value); break; case Tags.UnconfirmedTextMessage: Value<UnconfirmedTextMessageWrapper>.Save(sink, (UnconfirmedTextMessageWrapper)value); break; case Tags.TimeSynchronization: Value<TimeSynchronizationWrapper>.Save(sink, (TimeSynchronizationWrapper)value); break; case Tags.WhoHas: Value<WhoHasWrapper>.Save(sink, (WhoHasWrapper)value); break; case Tags.WhoIs: Value<WhoIsWrapper>.Save(sink, (WhoIsWrapper)value); break; case Tags.UtcTimeSynchronization: Value<UtcTimeSynchronizationWrapper>.Save(sink, (UtcTimeSynchronizationWrapper)value); break; default: throw new Exception(); } sink.LeaveChoice(); } public enum Tags : byte { IAm = 0, IHave = 1, UnconfirmedCOVNotification = 2, UnconfirmedEventNotification = 3, UnconfirmedPrivateTransfer = 4, UnconfirmedTextMessage = 5, TimeSynchronization = 6, WhoHas = 7, WhoIs = 8, UtcTimeSynchronization = 9 } public partial class IAmWrapper : UnconfirmedServiceRequest { public override Tags Tag { get { return Tags.IAm; } } public IAmRequest Item { get; private set; } public IAmWrapper(IAmRequest item) { this.Item = item; } public static readonly new ISchema Schema = Value<IAmRequest>.Schema; public static new IAmWrapper Load(IValueStream stream) { var temp = Value<IAmRequest>.Load(stream); return new IAmWrapper(temp); } public static void Save(IValueSink sink, IAmWrapper value) { Value<IAmRequest>.Save(sink, value.Item); } } public partial class IHaveWrapper : UnconfirmedServiceRequest { public override Tags Tag { get { return Tags.IHave; } } public IHaveRequest Item { get; private set; } public IHaveWrapper(IHaveRequest item) { this.Item = item; } public static readonly new ISchema Schema = Value<IHaveRequest>.Schema; public static new IHaveWrapper Load(IValueStream stream) { var temp = Value<IHaveRequest>.Load(stream); return new IHaveWrapper(temp); } public static void Save(IValueSink sink, IHaveWrapper value) { Value<IHaveRequest>.Save(sink, value.Item); } } public partial class UnconfirmedCOVNotificationWrapper : UnconfirmedServiceRequest { public override Tags Tag { get { return Tags.UnconfirmedCOVNotification; } } public UnconfirmedCOVNotificationRequest Item { get; private set; } public UnconfirmedCOVNotificationWrapper(UnconfirmedCOVNotificationRequest item) { this.Item = item; } public static readonly new ISchema Schema = Value<UnconfirmedCOVNotificationRequest>.Schema; public static new UnconfirmedCOVNotificationWrapper Load(IValueStream stream) { var temp = Value<UnconfirmedCOVNotificationRequest>.Load(stream); return new UnconfirmedCOVNotificationWrapper(temp); } public static void Save(IValueSink sink, UnconfirmedCOVNotificationWrapper value) { Value<UnconfirmedCOVNotificationRequest>.Save(sink, value.Item); } } public partial class UnconfirmedEventNotificationWrapper : UnconfirmedServiceRequest { public override Tags Tag { get { return Tags.UnconfirmedEventNotification; } } public UnconfirmedEventNotificationRequest Item { get; private set; } public UnconfirmedEventNotificationWrapper(UnconfirmedEventNotificationRequest item) { this.Item = item; } public static readonly new ISchema Schema = Value<UnconfirmedEventNotificationRequest>.Schema; public static new UnconfirmedEventNotificationWrapper Load(IValueStream stream) { var temp = Value<UnconfirmedEventNotificationRequest>.Load(stream); return new UnconfirmedEventNotificationWrapper(temp); } public static void Save(IValueSink sink, UnconfirmedEventNotificationWrapper value) { Value<UnconfirmedEventNotificationRequest>.Save(sink, value.Item); } } public partial class UnconfirmedPrivateTransferWrapper : UnconfirmedServiceRequest { public override Tags Tag { get { return Tags.UnconfirmedPrivateTransfer; } } public UnconfirmedPrivateTransferRequest Item { get; private set; } public UnconfirmedPrivateTransferWrapper(UnconfirmedPrivateTransferRequest item) { this.Item = item; } public static readonly new ISchema Schema = Value<UnconfirmedPrivateTransferRequest>.Schema; public static new UnconfirmedPrivateTransferWrapper Load(IValueStream stream) { var temp = Value<UnconfirmedPrivateTransferRequest>.Load(stream); return new UnconfirmedPrivateTransferWrapper(temp); } public static void Save(IValueSink sink, UnconfirmedPrivateTransferWrapper value) { Value<UnconfirmedPrivateTransferRequest>.Save(sink, value.Item); } } public partial class UnconfirmedTextMessageWrapper : UnconfirmedServiceRequest { public override Tags Tag { get { return Tags.UnconfirmedTextMessage; } } public UnconfirmedTextMessageRequest Item { get; private set; } public UnconfirmedTextMessageWrapper(UnconfirmedTextMessageRequest item) { this.Item = item; } public static readonly new ISchema Schema = Value<UnconfirmedTextMessageRequest>.Schema; public static new UnconfirmedTextMessageWrapper Load(IValueStream stream) { var temp = Value<UnconfirmedTextMessageRequest>.Load(stream); return new UnconfirmedTextMessageWrapper(temp); } public static void Save(IValueSink sink, UnconfirmedTextMessageWrapper value) { Value<UnconfirmedTextMessageRequest>.Save(sink, value.Item); } } public partial class TimeSynchronizationWrapper : UnconfirmedServiceRequest { public override Tags Tag { get { return Tags.TimeSynchronization; } } public TimeSynchronizationRequest Item { get; private set; } public TimeSynchronizationWrapper(TimeSynchronizationRequest item) { this.Item = item; } public static readonly new ISchema Schema = Value<TimeSynchronizationRequest>.Schema; public static new TimeSynchronizationWrapper Load(IValueStream stream) { var temp = Value<TimeSynchronizationRequest>.Load(stream); return new TimeSynchronizationWrapper(temp); } public static void Save(IValueSink sink, TimeSynchronizationWrapper value) { Value<TimeSynchronizationRequest>.Save(sink, value.Item); } } public partial class WhoHasWrapper : UnconfirmedServiceRequest { public override Tags Tag { get { return Tags.WhoHas; } } public WhoHasRequest Item { get; private set; } public WhoHasWrapper(WhoHasRequest item) { this.Item = item; } public static readonly new ISchema Schema = Value<WhoHasRequest>.Schema; public static new WhoHasWrapper Load(IValueStream stream) { var temp = Value<WhoHasRequest>.Load(stream); return new WhoHasWrapper(temp); } public static void Save(IValueSink sink, WhoHasWrapper value) { Value<WhoHasRequest>.Save(sink, value.Item); } } public partial class WhoIsWrapper : UnconfirmedServiceRequest { public override Tags Tag { get { return Tags.WhoIs; } } public WhoIsRequest Item { get; private set; } public WhoIsWrapper(WhoIsRequest item) { this.Item = item; } public static readonly new ISchema Schema = Value<WhoIsRequest>.Schema; public static new WhoIsWrapper Load(IValueStream stream) { var temp = Value<WhoIsRequest>.Load(stream); return new WhoIsWrapper(temp); } public static void Save(IValueSink sink, WhoIsWrapper value) { Value<WhoIsRequest>.Save(sink, value.Item); } } public partial class UtcTimeSynchronizationWrapper : UnconfirmedServiceRequest { public override Tags Tag { get { return Tags.UtcTimeSynchronization; } } public UTCTimeSynchronizationRequest Item { get; private set; } public UtcTimeSynchronizationWrapper(UTCTimeSynchronizationRequest item) { this.Item = item; } public static readonly new ISchema Schema = Value<UTCTimeSynchronizationRequest>.Schema; public static new UtcTimeSynchronizationWrapper Load(IValueStream stream) { var temp = Value<UTCTimeSynchronizationRequest>.Load(stream); return new UtcTimeSynchronizationWrapper(temp); } public static void Save(IValueSink sink, UtcTimeSynchronizationWrapper value) { Value<UTCTimeSynchronizationRequest>.Save(sink, value.Item); } } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoad.Business.ERCLevel { /// <summary> /// D05_SubContinent_Child (editable child object).<br/> /// This is a generated base class of <see cref="D05_SubContinent_Child"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="D04_SubContinent"/> collection. /// </remarks> [Serializable] public partial class D05_SubContinent_Child : BusinessBase<D05_SubContinent_Child> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="SubContinent_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> SubContinent_Child_NameProperty = RegisterProperty<string>(p => p.SubContinent_Child_Name, "Sub Continent Child Name"); /// <summary> /// Gets or sets the Sub Continent Child Name. /// </summary> /// <value>The Sub Continent Child Name.</value> public string SubContinent_Child_Name { get { return GetProperty(SubContinent_Child_NameProperty); } set { SetProperty(SubContinent_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="D05_SubContinent_Child"/> object. /// </summary> /// <returns>A reference to the created <see cref="D05_SubContinent_Child"/> object.</returns> internal static D05_SubContinent_Child NewD05_SubContinent_Child() { return DataPortal.CreateChild<D05_SubContinent_Child>(); } /// <summary> /// Factory method. Loads a <see cref="D05_SubContinent_Child"/> object, based on given parameters. /// </summary> /// <param name="subContinent_ID1">The SubContinent_ID1 parameter of the D05_SubContinent_Child to fetch.</param> /// <returns>A reference to the fetched <see cref="D05_SubContinent_Child"/> object.</returns> internal static D05_SubContinent_Child GetD05_SubContinent_Child(int subContinent_ID1) { return DataPortal.FetchChild<D05_SubContinent_Child>(subContinent_ID1); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="D05_SubContinent_Child"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public D05_SubContinent_Child() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="D05_SubContinent_Child"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="D05_SubContinent_Child"/> object from the database, based on given criteria. /// </summary> /// <param name="subContinent_ID1">The Sub Continent ID1.</param> protected void Child_Fetch(int subContinent_ID1) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("GetD05_SubContinent_Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@SubContinent_ID1", subContinent_ID1).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, subContinent_ID1); OnFetchPre(args); Fetch(cmd); OnFetchPost(args); } } } private void Fetch(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { if (dr.Read()) { Fetch(dr); } } } /// <summary> /// Loads a <see cref="D05_SubContinent_Child"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(SubContinent_Child_NameProperty, dr.GetString("SubContinent_Child_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="D05_SubContinent_Child"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(D04_SubContinent parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddD05_SubContinent_Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@SubContinent_ID1", parent.SubContinent_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@SubContinent_Child_Name", ReadProperty(SubContinent_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); } } } /// <summary> /// Updates in the database all changes made to the <see cref="D05_SubContinent_Child"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(D04_SubContinent parent) { if (!IsDirty) return; using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateD05_SubContinent_Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@SubContinent_ID1", parent.SubContinent_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@SubContinent_Child_Name", ReadProperty(SubContinent_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="D05_SubContinent_Child"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(D04_SubContinent parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteD05_SubContinent_Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@SubContinent_ID1", parent.SubContinent_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; using System.Xml; using Microsoft.Build.BuildEngine.Shared; namespace Microsoft.Build.BuildEngine { /// <summary> /// This class represents a single Import element in a project file /// </summary> /// <owner>LukaszG</owner> public class Import : IItemPropertyGrouping { #region Properties private Project parentProject = null; /// <summary> /// Returns the parent MSBuild Project object. /// </summary> internal Project ParentProject { get { return this.parentProject; } set { this.parentProject = value; } } private XmlElement importElement = null; /// <summary> /// Returns the source XmlElement this Import is based on. /// </summary> internal XmlElement ImportElement { get { return this.importElement; } } private bool importedFromAnotherProject; /// <summary> /// Returns true if this Import came from an imported project /// </summary> /// <owner>LukaszG</owner> public bool IsImported { get { return this.importedFromAnotherProject; } } private XmlAttribute projectPathAttribute = null; /// <summary> /// Returns the original import path from the Import element /// </summary> /// <owner>LukaszG</owner> public string ProjectPath { get { return (this.projectPathAttribute != null) ? this.projectPathAttribute.Value : null; } set { ImportElement.SetAttribute(XMakeAttributes.project, value); ParentProject.MarkProjectAsDirtyForReprocessXml(); } } /// <summary> /// Internal accessor for the project path XML attribute /// </summary> /// <owner>LukaszG</owner> internal XmlAttribute ProjectPathAttribute { get { return this.projectPathAttribute; } } private string evaluatedProjectPath = null; /// <summary> /// Returns the full evaluated import path /// </summary> /// <owner>LukaszG</owner> public string EvaluatedProjectPath { get { return this.evaluatedProjectPath; } } private XmlAttribute conditionAttribute = null; /// <summary> /// The condition string for this UsingTask /// </summary> /// <owner>LukaszG</owner> public string Condition { get { return (this.conditionAttribute != null) ? this.conditionAttribute.Value : null; } set { ImportElement.SetAttribute(XMakeAttributes.condition, value); if (conditionAttribute == null) { conditionAttribute = ImportElement.Attributes[XMakeAttributes.condition]; } ParentProject.MarkProjectAsDirtyForReprocessXml(); } } /// <summary> /// Internal accessor for the condition XML attribute /// </summary> internal XmlAttribute ConditionAttribute { get { return this.conditionAttribute; } } #endregion #region Constructors /// <summary> /// Internal constructor /// </summary> /// <param name="importElement"></param> /// <param name="isImported"></param> /// <owner>LukaszG</owner> internal Import(XmlElement importElement, Project parentProject, bool isImported) { this.importedFromAnotherProject = isImported; // Make sure the <Import> node has been given to us. ErrorUtilities.VerifyThrow(importElement != null, "Need an XML node representing the <Import> element."); this.importElement = importElement; // Make sure we have a valid parent Project ErrorUtilities.VerifyThrow(parentProject != null, "Need a parent Project object to instantiate an Import."); this.parentProject = parentProject; // Make sure this really is the <Import> node. ProjectXmlUtilities.VerifyThrowElementName(importElement, XMakeElements.import); // Loop through the list of attributes on the <Import> element. foreach (XmlAttribute importAttribute in importElement.Attributes) { switch (importAttribute.Name) { // The "project" attribute points us at the project file to import. case XMakeAttributes.project: // Just store the attribute value at this point. We want to make sure that we evaluate any // Condition attribute before looking at the Project attribute - if the Condition is going to be false, // it's legitimate for the value of the Project attribute to be completely invalid. // For example, <Import Project="$(A)" Condition="$(A)!=''"/> should not cause an error // that the Project attribute is empty. this.projectPathAttribute = importAttribute; break; // If the "condition" attribute is present, then it must evaluate to "true". case XMakeAttributes.condition: this.conditionAttribute = importAttribute; break; // We've come across an attribute in the <Import> element that we // don't recognize. Fail due to invalid project file. default: ProjectXmlUtilities.ThrowProjectInvalidAttribute(importAttribute); break; } } ProjectErrorUtilities.VerifyThrowInvalidProject((this.projectPathAttribute != null) && (this.projectPathAttribute.Value.Length != 0), importElement, "MissingRequiredAttribute", XMakeAttributes.project, XMakeElements.import); // Make sure this node has no children. Our schema doesn't support having // children beneath the <Import> element. if (importElement.HasChildNodes) { // Don't put the "if" condition inside the first parameter to // VerifyThrow..., because we'll get null reference exceptions, // since the parameter importElement.FirstChild.Name is being // passed in regardless of whether the condition holds true or not. ProjectXmlUtilities.ThrowProjectInvalidChildElement(importElement.FirstChild); } } #endregion /// <summary> /// Sets the full evaluated project path for this import. /// </summary> /// <param name="newEvaluatedProjectPath"></param> /// <owner>LukaszG</owner> internal void SetEvaluatedProjectPath(string newEvaluatedProjectPath) { this.evaluatedProjectPath = newEvaluatedProjectPath; } } }
// 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 class represents the Default COM+ binder. // // namespace System { using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Diagnostics.Contracts; using CultureInfo = System.Globalization.CultureInfo; //Marked serializable even though it has no state. [Serializable] internal class DefaultBinder : Binder { // This method is passed a set of methods and must choose the best // fit. The methods all have the same number of arguments and the object // array args. On exit, this method will choice the best fit method // and coerce the args to match that method. By match, we mean all primitive // arguments are exact matchs and all object arguments are exact or subclasses // of the target. If the target OR is an interface, the object must implement // that interface. There are a couple of exceptions // thrown when a method cannot be returned. If no method matchs the args and // ArgumentException is thrown. If multiple methods match the args then // an AmbiguousMatchException is thrown. // // The most specific match will be selected. // [System.Security.SecuritySafeCritical] // auto-generated public override MethodBase BindToMethod( BindingFlags bindingAttr, MethodBase[] match, ref Object[] args, ParameterModifier[] modifiers, CultureInfo cultureInfo, String[] names, out Object state) { if (match == null || match.Length == 0) throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), "match"); Contract.EndContractBlock(); MethodBase[] candidates = (MethodBase[]) match.Clone(); int i; int j; state = null; #region Map named parameters to candidate parameter postions // We are creating an paramOrder array to act as a mapping // between the order of the args and the actual order of the // parameters in the method. This order may differ because // named parameters (names) may change the order. If names // is not provided, then we assume the default mapping (0,1,...) int[][] paramOrder = new int[candidates.Length][]; for (i = 0; i < candidates.Length; i++) { ParameterInfo[] par = candidates[i].GetParametersNoCopy(); // args.Length + 1 takes into account the possibility of a last paramArray that can be omitted paramOrder[i] = new int[(par.Length > args.Length) ? par.Length : args.Length]; if (names == null) { // Default mapping for (j = 0; j < args.Length; j++) paramOrder[i][j] = j; } else { // Named parameters, reorder the mapping. If CreateParamOrder fails, it means that the method // doesn't have a name that matchs one of the named parameters so we don't consider it any further. if (!CreateParamOrder(paramOrder[i], par, names)) candidates[i] = null; } } #endregion Type[] paramArrayTypes = new Type[candidates.Length]; Type[] argTypes = new Type[args.Length]; #region Cache the type of the provided arguments // object that contain a null are treated as if they were typeless (but match either object // references or value classes). We mark this condition by placing a null in the argTypes array. for (i = 0; i < args.Length; i++) { if (args[i] != null) { argTypes[i] = args[i].GetType(); } } #endregion // Find the method that matches... int CurIdx = 0; bool defaultValueBinding = ((bindingAttr & BindingFlags.OptionalParamBinding) != 0); Type paramArrayType = null; #region Filter methods by parameter count and type for (i = 0; i < candidates.Length; i++) { paramArrayType = null; // If we have named parameters then we may have a hole in the candidates array. if (candidates[i] == null) continue; // Validate the parameters. ParameterInfo[] par = candidates[i].GetParametersNoCopy(); #region Match method by parameter count if (par.Length == 0) { #region No formal parameters if (args.Length != 0) { if ((candidates[i].CallingConvention & CallingConventions.VarArgs) == 0) continue; } // This is a valid routine so we move it up the candidates list. paramOrder[CurIdx] = paramOrder[i]; candidates[CurIdx++] = candidates[i]; continue; #endregion } else if (par.Length > args.Length) { #region Shortage of provided parameters // If the number of parameters is greater than the number of args then // we are in the situation were we may be using default values. for (j = args.Length; j < par.Length - 1; j++) { if (par[j].DefaultValue == System.DBNull.Value) break; } if (j != par.Length - 1) continue; if (par[j].DefaultValue == System.DBNull.Value) { if (!par[j].ParameterType.IsArray) continue; if (!par[j].IsDefined(typeof(ParamArrayAttribute), true)) continue; paramArrayType = par[j].ParameterType.GetElementType(); } #endregion } else if (par.Length < args.Length) { #region Excess provided parameters // test for the ParamArray case int lastArgPos = par.Length - 1; if (!par[lastArgPos].ParameterType.IsArray) continue; if (!par[lastArgPos].IsDefined(typeof(ParamArrayAttribute), true)) continue; if (paramOrder[i][lastArgPos] != lastArgPos) continue; paramArrayType = par[lastArgPos].ParameterType.GetElementType(); #endregion } else { #region Test for paramArray, save paramArray type int lastArgPos = par.Length - 1; if (par[lastArgPos].ParameterType.IsArray && par[lastArgPos].IsDefined(typeof(ParamArrayAttribute), true) && paramOrder[i][lastArgPos] == lastArgPos) { if (!par[lastArgPos].ParameterType.IsAssignableFrom(argTypes[lastArgPos])) paramArrayType = par[lastArgPos].ParameterType.GetElementType(); } #endregion } #endregion Type pCls = null; int argsToCheck = (paramArrayType != null) ? par.Length - 1 : args.Length; #region Match method by parameter type for (j = 0; j < argsToCheck; j++) { #region Classic argument coersion checks // get the formal type pCls = par[j].ParameterType; if (pCls.IsByRef) pCls = pCls.GetElementType(); // the type is the same if (pCls == argTypes[paramOrder[i][j]]) continue; // a default value is available if (defaultValueBinding && args[paramOrder[i][j]] == Type.Missing) continue; // the argument was null, so it matches with everything if (args[paramOrder[i][j]] == null) continue; // the type is Object, so it will match everything if (pCls == typeof(Object)) continue; // now do a "classic" type check if (pCls.IsPrimitive) { if (argTypes[paramOrder[i][j]] == null || !CanConvertPrimitiveObjectToType(args[paramOrder[i][j]],(RuntimeType)pCls)) { break; } } else { if (argTypes[paramOrder[i][j]] == null) continue; if (!pCls.IsAssignableFrom(argTypes[paramOrder[i][j]])) { if (argTypes[paramOrder[i][j]].IsCOMObject) { if (pCls.IsInstanceOfType(args[paramOrder[i][j]])) continue; } break; } } #endregion } if (paramArrayType != null && j == par.Length - 1) { #region Check that excess arguments can be placed in the param array for (; j < args.Length; j++) { if (paramArrayType.IsPrimitive) { if (argTypes[j] == null || !CanConvertPrimitiveObjectToType(args[j], (RuntimeType)paramArrayType)) break; } else { if (argTypes[j] == null) continue; if (!paramArrayType.IsAssignableFrom(argTypes[j])) { if (argTypes[j].IsCOMObject) { if (paramArrayType.IsInstanceOfType(args[j])) continue; } break; } } } #endregion } #endregion if (j == args.Length) { #region This is a valid routine so we move it up the candidates list paramOrder[CurIdx] = paramOrder[i]; paramArrayTypes[CurIdx] = paramArrayType; candidates[CurIdx++] = candidates[i]; #endregion } } #endregion // If we didn't find a method if (CurIdx == 0) throw new MissingMethodException(Environment.GetResourceString("MissingMember")); if (CurIdx == 1) { #region Found only one method if (names != null) { state = new BinderState((int[])paramOrder[0].Clone(), args.Length, paramArrayTypes[0] != null); ReorderParams(paramOrder[0],args); } // If the parameters and the args are not the same length or there is a paramArray // then we need to create a argument array. ParameterInfo[] parms = candidates[0].GetParametersNoCopy(); if (parms.Length == args.Length) { if (paramArrayTypes[0] != null) { Object[] objs = new Object[parms.Length]; int lastPos = parms.Length - 1; Array.Copy(args, 0, objs, 0, lastPos); objs[lastPos] = Array.UnsafeCreateInstance(paramArrayTypes[0], 1); ((Array)objs[lastPos]).SetValue(args[lastPos], 0); args = objs; } } else if (parms.Length > args.Length) { Object[] objs = new Object[parms.Length]; for (i=0;i<args.Length;i++) objs[i] = args[i]; for (;i<parms.Length - 1;i++) objs[i] = parms[i].DefaultValue; if (paramArrayTypes[0] != null) objs[i] = Array.UnsafeCreateInstance(paramArrayTypes[0], 0); // create an empty array for the else objs[i] = parms[i].DefaultValue; args = objs; } else { if ((candidates[0].CallingConvention & CallingConventions.VarArgs) == 0) { Object[] objs = new Object[parms.Length]; int paramArrayPos = parms.Length - 1; Array.Copy(args, 0, objs, 0, paramArrayPos); objs[paramArrayPos] = Array.UnsafeCreateInstance(paramArrayTypes[0], args.Length - paramArrayPos); Array.Copy(args, paramArrayPos, (System.Array)objs[paramArrayPos], 0, args.Length - paramArrayPos); args = objs; } } #endregion return candidates[0]; } int currentMin = 0; bool ambig = false; for (i = 1; i < CurIdx; i++) { #region Walk all of the methods looking the most specific method to invoke int newMin = FindMostSpecificMethod(candidates[currentMin], paramOrder[currentMin], paramArrayTypes[currentMin], candidates[i], paramOrder[i], paramArrayTypes[i], argTypes, args); if (newMin == 0) { ambig = true; } else if (newMin == 2) { currentMin = i; ambig = false; } #endregion } if (ambig) throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException")); // Reorder (if needed) if (names != null) { state = new BinderState((int[])paramOrder[currentMin].Clone(), args.Length, paramArrayTypes[currentMin] != null); ReorderParams(paramOrder[currentMin], args); } // If the parameters and the args are not the same length or there is a paramArray // then we need to create a argument array. ParameterInfo[] parameters = candidates[currentMin].GetParametersNoCopy(); if (parameters.Length == args.Length) { if (paramArrayTypes[currentMin] != null) { Object[] objs = new Object[parameters.Length]; int lastPos = parameters.Length - 1; Array.Copy(args, 0, objs, 0, lastPos); objs[lastPos] = Array.UnsafeCreateInstance(paramArrayTypes[currentMin], 1); ((Array)objs[lastPos]).SetValue(args[lastPos], 0); args = objs; } } else if (parameters.Length > args.Length) { Object[] objs = new Object[parameters.Length]; for (i=0;i<args.Length;i++) objs[i] = args[i]; for (;i<parameters.Length - 1;i++) objs[i] = parameters[i].DefaultValue; if (paramArrayTypes[currentMin] != null) { objs[i] = Array.UnsafeCreateInstance(paramArrayTypes[currentMin], 0); } else { objs[i] = parameters[i].DefaultValue; } args = objs; } else { if ((candidates[currentMin].CallingConvention & CallingConventions.VarArgs) == 0) { Object[] objs = new Object[parameters.Length]; int paramArrayPos = parameters.Length - 1; Array.Copy(args, 0, objs, 0, paramArrayPos); objs[paramArrayPos] = Array.UnsafeCreateInstance(paramArrayTypes[currentMin], args.Length - paramArrayPos); Array.Copy(args, paramArrayPos, (System.Array)objs[paramArrayPos], 0, args.Length - paramArrayPos); args = objs; } } return candidates[currentMin]; } // Given a set of fields that match the base criteria, select a field. // if value is null then we have no way to select a field [System.Security.SecuritySafeCritical] // auto-generated public override FieldInfo BindToField(BindingFlags bindingAttr,FieldInfo[] match, Object value,CultureInfo cultureInfo) { if (match == null) { throw new ArgumentNullException("match"); } int i; // Find the method that match... int CurIdx = 0; Type valueType = null; FieldInfo[] candidates = (FieldInfo[]) match.Clone(); // If we are a FieldSet, then use the value's type to disambiguate if ((bindingAttr & BindingFlags.SetField) != 0) { valueType = value.GetType(); for (i=0;i<candidates.Length;i++) { Type pCls = candidates[i].FieldType; if (pCls == valueType) { candidates[CurIdx++] = candidates[i]; continue; } if (value == Empty.Value) { // the object passed in was null which would match any non primitive non value type if (pCls.IsClass) { candidates[CurIdx++] = candidates[i]; continue; } } if (pCls == typeof(Object)) { candidates[CurIdx++] = candidates[i]; continue; } if (pCls.IsPrimitive) { if (CanConvertPrimitiveObjectToType(value,(RuntimeType)pCls)) { candidates[CurIdx++] = candidates[i]; continue; } } else { if (pCls.IsAssignableFrom(valueType)) { candidates[CurIdx++] = candidates[i]; continue; } } } if (CurIdx == 0) throw new MissingFieldException(Environment.GetResourceString("MissingField")); if (CurIdx == 1) return candidates[0]; } // Walk all of the methods looking the most specific method to invoke int currentMin = 0; bool ambig = false; for (i=1;i<CurIdx;i++) { int newMin = FindMostSpecificField(candidates[currentMin], candidates[i]); if (newMin == 0) ambig = true; else { if (newMin == 2) { currentMin = i; ambig = false; } } } if (ambig) throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException")); return candidates[currentMin]; } // Given a set of methods that match the base criteria, select a method based // upon an array of types. This method should return null if no method matchs // the criteria. [System.Security.SecuritySafeCritical] // auto-generated public override MethodBase SelectMethod(BindingFlags bindingAttr,MethodBase[] match,Type[] types,ParameterModifier[] modifiers) { int i; int j; Type[] realTypes = new Type[types.Length]; for (i=0;i<types.Length;i++) { realTypes[i] = types[i].UnderlyingSystemType; if (!(realTypes[i] is RuntimeType)) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"types"); } types = realTypes; // We don't automatically jump out on exact match. if (match == null || match.Length == 0) throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), "match"); MethodBase[] candidates = (MethodBase[]) match.Clone(); // Find all the methods that can be described by the types parameter. // Remove all of them that cannot. int CurIdx = 0; for (i=0;i<candidates.Length;i++) { ParameterInfo[] par = candidates[i].GetParametersNoCopy(); if (par.Length != types.Length) continue; for (j=0;j<types.Length;j++) { Type pCls = par[j].ParameterType; if (pCls == types[j]) continue; if (pCls == typeof(Object)) continue; if (pCls.IsPrimitive) { if (!(types[j].UnderlyingSystemType is RuntimeType) || !CanConvertPrimitive((RuntimeType)types[j].UnderlyingSystemType,(RuntimeType)pCls.UnderlyingSystemType)) break; } else { if (!pCls.IsAssignableFrom(types[j])) break; } } if (j == types.Length) candidates[CurIdx++] = candidates[i]; } if (CurIdx == 0) return null; if (CurIdx == 1) return candidates[0]; // Walk all of the methods looking the most specific method to invoke int currentMin = 0; bool ambig = false; int[] paramOrder = new int[types.Length]; for (i=0;i<types.Length;i++) paramOrder[i] = i; for (i=1;i<CurIdx;i++) { int newMin = FindMostSpecificMethod(candidates[currentMin], paramOrder, null, candidates[i], paramOrder, null, types, null); if (newMin == 0) ambig = true; else { if (newMin == 2) { currentMin = i; ambig = false; currentMin = i; } } } if (ambig) throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException")); return candidates[currentMin]; } // Given a set of properties that match the base criteria, select one. [System.Security.SecuritySafeCritical] // auto-generated public override PropertyInfo SelectProperty(BindingFlags bindingAttr,PropertyInfo[] match,Type returnType, Type[] indexes,ParameterModifier[] modifiers) { // Allow a null indexes array. But if it is not null, every element must be non-null as well. if (indexes != null && !Contract.ForAll(indexes, delegate(Type t) { return t != null; })) { throw new ArgumentNullException("indexes"); } if (match == null || match.Length == 0) throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), "match"); Contract.EndContractBlock(); PropertyInfo[] candidates = (PropertyInfo[]) match.Clone(); int i,j = 0; // Find all the properties that can be described by type indexes parameter int CurIdx = 0; int indexesLength = (indexes != null) ? indexes.Length : 0; for (i=0;i<candidates.Length;i++) { if (indexes != null) { ParameterInfo[] par = candidates[i].GetIndexParameters(); if (par.Length != indexesLength) continue; for (j=0;j<indexesLength;j++) { Type pCls = par[j]. ParameterType; // If the classes exactly match continue if (pCls == indexes[j]) continue; if (pCls == typeof(Object)) continue; if (pCls.IsPrimitive) { if (!(indexes[j].UnderlyingSystemType is RuntimeType) || !CanConvertPrimitive((RuntimeType)indexes[j].UnderlyingSystemType,(RuntimeType)pCls.UnderlyingSystemType)) break; } else { if (!pCls.IsAssignableFrom(indexes[j])) break; } } } if (j == indexesLength) { if (returnType != null) { if (candidates[i].PropertyType.IsPrimitive) { if (!(returnType.UnderlyingSystemType is RuntimeType) || !CanConvertPrimitive((RuntimeType)returnType.UnderlyingSystemType,(RuntimeType)candidates[i].PropertyType.UnderlyingSystemType)) continue; } else { if (!candidates[i].PropertyType.IsAssignableFrom(returnType)) continue; } } candidates[CurIdx++] = candidates[i]; } } if (CurIdx == 0) return null; if (CurIdx == 1) return candidates[0]; // Walk all of the properties looking the most specific method to invoke int currentMin = 0; bool ambig = false; int[] paramOrder = new int[indexesLength]; for (i=0;i<indexesLength;i++) paramOrder[i] = i; for (i=1;i<CurIdx;i++) { int newMin = FindMostSpecificType(candidates[currentMin].PropertyType, candidates[i].PropertyType,returnType); if (newMin == 0 && indexes != null) newMin = FindMostSpecific(candidates[currentMin].GetIndexParameters(), paramOrder, null, candidates[i].GetIndexParameters(), paramOrder, null, indexes, null); if (newMin == 0) { newMin = FindMostSpecificProperty(candidates[currentMin], candidates[i]); if (newMin == 0) ambig = true; } if (newMin == 2) { ambig = false; currentMin = i; } } if (ambig) throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException")); return candidates[currentMin]; } // ChangeType // The default binder doesn't support any change type functionality. // This is because the default is built into the low level invoke code. public override Object ChangeType(Object value,Type type,CultureInfo cultureInfo) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_ChangeType")); } public override void ReorderArgumentArray(ref Object[] args, Object state) { BinderState binderState = (BinderState)state; ReorderParams(binderState.m_argsMap, args); if (binderState.m_isParamArray) { int paramArrayPos = args.Length - 1; if (args.Length == binderState.m_originalSize) args[paramArrayPos] = ((Object[])args[paramArrayPos])[0]; else { // must be args.Length < state.originalSize Object[] newArgs = new Object[args.Length]; Array.Copy(args, 0, newArgs, 0, paramArrayPos); for (int i = paramArrayPos, j = 0; i < newArgs.Length; i++, j++) { newArgs[i] = ((Object[])args[paramArrayPos])[j]; } args = newArgs; } } else { if (args.Length > binderState.m_originalSize) { Object[] newArgs = new Object[binderState.m_originalSize]; Array.Copy(args, 0, newArgs, 0, binderState.m_originalSize); args = newArgs; } } } // Return any exact bindings that may exist. (This method is not defined on the // Binder and is used by RuntimeType.) public static MethodBase ExactBinding(MethodBase[] match,Type[] types,ParameterModifier[] modifiers) { if (match==null) throw new ArgumentNullException("match"); Contract.EndContractBlock(); MethodBase[] aExactMatches = new MethodBase[match.Length]; int cExactMatches = 0; for (int i=0;i<match.Length;i++) { ParameterInfo[] par = match[i].GetParametersNoCopy(); if (par.Length == 0) { continue; } int j; for (j=0;j<types.Length;j++) { Type pCls = par[j]. ParameterType; // If the classes exactly match continue if (!pCls.Equals(types[j])) break; } if (j < types.Length) continue; // Add the exact match to the array of exact matches. aExactMatches[cExactMatches] = match[i]; cExactMatches++; } if (cExactMatches == 0) return null; if (cExactMatches == 1) return aExactMatches[0]; return FindMostDerivedNewSlotMeth(aExactMatches, cExactMatches); } // Return any exact bindings that may exist. (This method is not defined on the // Binder and is used by RuntimeType.) public static PropertyInfo ExactPropertyBinding(PropertyInfo[] match,Type returnType,Type[] types,ParameterModifier[] modifiers) { if (match==null) throw new ArgumentNullException("match"); Contract.EndContractBlock(); PropertyInfo bestMatch = null; int typesLength = (types != null) ? types.Length : 0; for (int i=0;i<match.Length;i++) { ParameterInfo[] par = match[i].GetIndexParameters(); int j; for (j=0;j<typesLength;j++) { Type pCls = par[j].ParameterType; // If the classes exactly match continue if (pCls != types[j]) break; } if (j < typesLength) continue; if (returnType != null && returnType != match[i].PropertyType) continue; if (bestMatch != null) throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException")); bestMatch = match[i]; } return bestMatch; } private static int FindMostSpecific(ParameterInfo[] p1, int[] paramOrder1, Type paramArrayType1, ParameterInfo[] p2, int[] paramOrder2, Type paramArrayType2, Type[] types, Object[] args) { // A method using params is always less specific than one not using params if (paramArrayType1 != null && paramArrayType2 == null) return 2; if (paramArrayType2 != null && paramArrayType1 == null) return 1; // now either p1 and p2 both use params or neither does. bool p1Less = false; bool p2Less = false; for (int i = 0; i < types.Length; i++) { if (args != null && args[i] == Type.Missing) continue; Type c1, c2; // If a param array is present, then either // the user re-ordered the parameters in which case // the argument to the param array is either an array // in which case the params is conceptually ignored and so paramArrayType1 == null // or the argument to the param array is a single element // in which case paramOrder[i] == p1.Length - 1 for that element // or the user did not re-order the parameters in which case // the paramOrder array could contain indexes larger than p.Length - 1 (see VSW 577286) // so any index >= p.Length - 1 is being put in the param array if (paramArrayType1 != null && paramOrder1[i] >= p1.Length - 1) c1 = paramArrayType1; else c1 = p1[paramOrder1[i]].ParameterType; if (paramArrayType2 != null && paramOrder2[i] >= p2.Length - 1) c2 = paramArrayType2; else c2 = p2[paramOrder2[i]].ParameterType; if (c1 == c2) continue; switch (FindMostSpecificType(c1, c2, types[i])) { case 0: return 0; case 1: p1Less = true; break; case 2: p2Less = true; break; } } // Two way p1Less and p2Less can be equal. All the arguments are the // same they both equal false, otherwise there were things that both // were the most specific type on.... if (p1Less == p2Less) { // if we cannot tell which is a better match based on parameter types (p1Less == p2Less), // let's see which one has the most matches without using the params array (the longer one wins). if (!p1Less && args != null) { if (p1.Length > p2.Length) { return 1; } else if (p2.Length > p1.Length) { return 2; } } return 0; } else { return (p1Less == true) ? 1 : 2; } } [System.Security.SecuritySafeCritical] // auto-generated private static int FindMostSpecificType(Type c1, Type c2, Type t) { // If the two types are exact move on... if (c1 == c2) return 0; if (c1 == t) return 1; if (c2 == t) return 2; bool c1FromC2; bool c2FromC1; if (c1.IsByRef || c2.IsByRef) { if (c1.IsByRef && c2.IsByRef) { c1 = c1.GetElementType(); c2 = c2.GetElementType(); } else if (c1.IsByRef) { if (c1.GetElementType() == c2) return 2; c1 = c1.GetElementType(); } else { if (c2.GetElementType() == c1) return 1; c2 = c2.GetElementType(); } } if (c1.IsPrimitive && c2.IsPrimitive) { c1FromC2 = CanConvertPrimitive((RuntimeType)c2, (RuntimeType)c1); c2FromC1 = CanConvertPrimitive((RuntimeType)c1, (RuntimeType)c2); } else { c1FromC2 = c1.IsAssignableFrom(c2); c2FromC1 = c2.IsAssignableFrom(c1); } if (c1FromC2 == c2FromC1) return 0; if (c1FromC2) { return 2; } else { return 1; } } private static int FindMostSpecificMethod(MethodBase m1, int[] paramOrder1, Type paramArrayType1, MethodBase m2, int[] paramOrder2, Type paramArrayType2, Type[] types, Object[] args) { // Find the most specific method based on the parameters. int res = FindMostSpecific(m1.GetParametersNoCopy(), paramOrder1, paramArrayType1, m2.GetParametersNoCopy(), paramOrder2, paramArrayType2, types, args); // If the match was not ambigous then return the result. if (res != 0) return res; // Check to see if the methods have the exact same name and signature. if (CompareMethodSigAndName(m1, m2)) { // Determine the depth of the declaring types for both methods. int hierarchyDepth1 = GetHierarchyDepth(m1.DeclaringType); int hierarchyDepth2 = GetHierarchyDepth(m2.DeclaringType); // The most derived method is the most specific one. if (hierarchyDepth1 == hierarchyDepth2) { return 0; } else if (hierarchyDepth1 < hierarchyDepth2) { return 2; } else { return 1; } } // The match is ambigous. return 0; } private static int FindMostSpecificField(FieldInfo cur1,FieldInfo cur2) { // Check to see if the fields have the same name. if (cur1.Name == cur2.Name) { int hierarchyDepth1 = GetHierarchyDepth(cur1.DeclaringType); int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType); if (hierarchyDepth1 == hierarchyDepth2) { Contract.Assert(cur1.IsStatic != cur2.IsStatic, "hierarchyDepth1 == hierarchyDepth2"); return 0; } else if (hierarchyDepth1 < hierarchyDepth2) return 2; else return 1; } // The match is ambigous. return 0; } private static int FindMostSpecificProperty(PropertyInfo cur1,PropertyInfo cur2) { // Check to see if the fields have the same name. if (cur1.Name == cur2.Name) { int hierarchyDepth1 = GetHierarchyDepth(cur1.DeclaringType); int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType); if (hierarchyDepth1 == hierarchyDepth2) { return 0; } else if (hierarchyDepth1 < hierarchyDepth2) return 2; else return 1; } // The match is ambigous. return 0; } internal static bool CompareMethodSigAndName(MethodBase m1, MethodBase m2) { ParameterInfo[] params1 = m1.GetParametersNoCopy(); ParameterInfo[] params2 = m2.GetParametersNoCopy(); if (params1.Length != params2.Length) return false; int numParams = params1.Length; for (int i = 0; i < numParams; i++) { if (params1[i].ParameterType != params2[i].ParameterType) return false; } return true; } internal static int GetHierarchyDepth(Type t) { int depth = 0; Type currentType = t; do { depth++; currentType = currentType.BaseType; } while (currentType != null); return depth; } internal static MethodBase FindMostDerivedNewSlotMeth(MethodBase[] match, int cMatches) { int deepestHierarchy = 0; MethodBase methWithDeepestHierarchy = null; for (int i = 0; i < cMatches; i++) { // Calculate the depth of the hierarchy of the declaring type of the // current method. int currentHierarchyDepth = GetHierarchyDepth(match[i].DeclaringType); // The two methods have the same name, signature, and hierarchy depth. // This can only happen if at least one is vararg or generic. if (currentHierarchyDepth == deepestHierarchy) { throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException")); } // Check to see if this method is on the most derived class. if (currentHierarchyDepth > deepestHierarchy) { deepestHierarchy = currentHierarchyDepth; methWithDeepestHierarchy = match[i]; } } return methWithDeepestHierarchy; } // CanConvertPrimitive // This will determine if the source can be converted to the target type [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool CanConvertPrimitive(RuntimeType source,RuntimeType target); // CanConvertPrimitiveObjectToType // This method will determine if the primitive object can be converted // to a type. [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] static internal extern bool CanConvertPrimitiveObjectToType(Object source,RuntimeType type); // This method will sort the vars array into the mapping order stored // in the paramOrder array. private static void ReorderParams(int[] paramOrder,Object[] vars) { object[] varsCopy = new object[vars.Length]; for (int i = 0; i < vars.Length; i ++) varsCopy[i] = vars[i]; for (int i = 0; i < vars.Length; i ++) vars[i] = varsCopy[paramOrder[i]]; } // This method will create the mapping between the Parameters and the underlying // data based upon the names array. The names array is stored in the same order // as the values and maps to the parameters of the method. We store the mapping // from the parameters to the names in the paramOrder array. All parameters that // don't have matching names are then stored in the array in order. private static bool CreateParamOrder(int[] paramOrder,ParameterInfo[] pars,String[] names) { bool[] used = new bool[pars.Length]; // Mark which parameters have not been found in the names list for (int i=0;i<pars.Length;i++) paramOrder[i] = -1; // Find the parameters with names. for (int i=0;i<names.Length;i++) { int j; for (j=0;j<pars.Length;j++) { if (names[i].Equals(pars[j].Name)) { paramOrder[j] = i; used[i] = true; break; } } // This is an error condition. The name was not found. This // method must not match what we sent. if (j == pars.Length) return false; } // Now we fill in the holes with the parameters that are unused. int pos = 0; for (int i=0;i<pars.Length;i++) { if (paramOrder[i] == -1) { for (;pos<pars.Length;pos++) { if (!used[pos]) { paramOrder[i] = pos; pos++; break; } } } } return true; } internal class BinderState { internal int[] m_argsMap; internal int m_originalSize; internal bool m_isParamArray; internal BinderState(int[] argsMap, int originalSize, bool isParamArray) { m_argsMap = argsMap; m_originalSize = originalSize; m_isParamArray = isParamArray; } } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ #region Using directives using Axiom.Collections; using Axiom.Configuration; using Axiom.Core; using Axiom.Graphics; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; #endregion namespace Multiverse.Base { partial class ConfigDialog : Form { public DisplaySettings settings; List<DisplayMode> validModes = null; int inhibit = 0; const string LogoPicture = "../logopicture.jpg"; public ConfigDialog(DisplaySettings settings) { this.settings = new DisplaySettings(settings); InitializeComponent(); inhibit = 0; this.DialogResult = DialogResult.None; List<RenderSystem> renderSystems = Root.Instance.RenderSystems; foreach (RenderSystem rs in renderSystems) renderSystemComboBox.Items.Add(rs.Name); renderSystemComboBox.SelectedIndex = 0; logoPicture.Load(LogoPicture); logoPicture.Size = logoPicture.Image.Size; ApplySettingsToUI(); } private string GetDisplayString(DisplayMode mode) { return string.Format("{0} x {1} at {2} bit color", mode.Width, mode.Height, mode.Depth); } private string GetDisplayString(bool val) { if (val) return "Yes"; else return "No"; } private bool YesOrNoToBool(string yesOrNo) { return yesOrNo == "Yes"; } private void ApplySettingsToUI() { DisplayConfig config = settings.renderSystem.ConfigOptions; List<DisplayMode> displayModes = config.FullscreenModes; validModes = new List<DisplayMode>(); for (int i = 0; i < displayModes.Count; ++i) { if (displayModes[i].Width >= settings.minScreenWidth && displayModes[i].Height >= settings.minScreenHeight) { DisplayMode mode = displayModes[i]; validModes.Add(mode); videoModeComboBox.Items.Add(GetDisplayString(mode)); } } DisplayMode displayMode = settings.displayMode; int index = videoModeComboBox.Items.IndexOf(GetDisplayString(displayMode)); if (index < 0) videoModeComboBox.SelectedIndex = 0; else videoModeComboBox.SelectedIndex = index; setRadioButtonPair(fullScreenYesButton, displayMode.Fullscreen, fullScreenNoButton); fullScreenGroupBox.Visible = settings.allowFullScreen; setRadioButtonPair(vsyncYesButton, settings.vSync, vsyncNoButton); setRadioButtonPair(nvPerfHUDYesButton, settings.allowNVPerfHUD, nvPerfHUDNoButton); Dictionary<string, ConfigOption>rsConfigOptions = settings.renderSystem.GetConfigOptions(); string currentAAVal = "None"; if (rsConfigOptions.ContainsKey("Anti Aliasing")) { ConfigOption aaConfig = rsConfigOptions["Anti Aliasing"]; // add the possible values to the combo box foreach (string s in aaConfig.possibleValues) { aaComboBox.Items.Add(s); } // if current value from settings is valid, use it, otherwise default to None if (aaConfig.possibleValues.Contains(settings.antiAliasing)) { currentAAVal = settings.antiAliasing; } } else { // render system doesn't have AA settings aaComboBox.Items.Add("None"); } aaComboBox.SelectedIndex = aaComboBox.Items.IndexOf(currentAAVal); } private void setRadioButtonPair(RadioButton button1, bool button1Checked, RadioButton button2) { button1.Checked = button1Checked; button2.Checked = !button1Checked; } private void CaptureUISettings() { DisplayMode m = validModes[videoModeComboBox.SelectedIndex]; settings.displayMode = new DisplayMode(m.Width, m.Height, m.Depth, settings.allowFullScreen && fullScreenYesButton.Checked); settings.vSync = vsyncYesButton.Checked; settings.allowNVPerfHUD = nvPerfHUDYesButton.Checked; settings.antiAliasing = aaComboBox.Text; } private void buttonOk_Click(object sender, EventArgs e) { CaptureUISettings(); this.DialogResult = DialogResult.OK; } private void ConfigDialog_FormClosing(object sender, FormClosingEventArgs e) { if (this.DialogResult == DialogResult.None) this.DialogResult = DialogResult.Cancel; } private void fullScreenYesButton_CheckedChanged(object sender, EventArgs e) { if (inhibit == 0) { inhibit++; fullScreenNoButton.Checked = !fullScreenYesButton.Checked; inhibit--; } } private void fullScreenNoButton_CheckedChanged(object sender, EventArgs e) { if (inhibit == 0) { inhibit++; fullScreenYesButton.Checked = !fullScreenNoButton.Checked; inhibit--; } } private void vsyncYesButton_CheckedChanged(object sender, EventArgs e) { if (inhibit == 0) { inhibit++; vsyncYesButton.Checked = !vsyncNoButton.Checked; inhibit--; } } private void vsyncNoButton_CheckedChanged(object sender, EventArgs e) { if (inhibit == 0) { inhibit++; vsyncNoButton.Checked = !vsyncYesButton.Checked; inhibit--; } } private void nvPerfHUDYesButton_CheckedChanged(object sender, EventArgs e) { if (inhibit == 0) { inhibit++; nvPerfHUDNoButton.Checked = !nvPerfHUDYesButton.Checked; inhibit--; } } private void nvPerfHUDNoButton_CheckedChanged(object sender, EventArgs e) { if (inhibit == 0) { inhibit++; nvPerfHUDYesButton.Checked = !nvPerfHUDNoButton.Checked; inhibit--; } } private void f(object sender, EventArgs e) { } } }
// 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.Runtime.InteropServices; internal static partial class Interop { internal static partial class Shell32 { internal const int COR_E_PLATFORMNOTSUPPORTED = unchecked((int)0x80131539); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb762188.aspx [DllImport(Libraries.Shell32, CharSet = CharSet.Unicode, SetLastError = false, BestFitMapping = false, ExactSpelling = true)] internal static extern int SHGetKnownFolderPath( [MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint dwFlags, IntPtr hToken, out string ppszPath); // https://msdn.microsoft.com/en-us/library/windows/desktop/dd378457.aspx internal static class KnownFolders { /// <summary> /// (CSIDL_ADMINTOOLS) Per user Administrative Tools /// "%APPDATA%\Microsoft\Windows\Start Menu\Programs\Administrative Tools" /// </summary> internal const string AdminTools = "{724EF170-A42D-4FEF-9F26-B60E846FBA4F}"; /// <summary> /// (CSIDL_CDBURN_AREA) Temporary Burn folder /// "%LOCALAPPDATA%\Microsoft\Windows\Burn\Burn" /// </summary> internal const string CDBurning = "{9E52AB10-F80D-49DF-ACB8-4330F5687855}"; /// <summary> /// (CSIDL_COMMON_ADMINTOOLS) Common Administrative Tools /// "%ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs\Administrative Tools" /// </summary> internal const string CommonAdminTools = "{D0384E7D-BAC3-4797-8F14-CBA229B392B5}"; /// <summary> /// (CSIDL_COMMON_OEM_LINKS) OEM Links folder /// "%ALLUSERSPROFILE%\OEM Links" /// </summary> internal const string CommonOEMLinks = "{C1BAE2D0-10DF-4334-BEDD-7AA20B227A9D}"; /// <summary> /// (CSIDL_COMMON_PROGRAMS) Common Programs folder /// "%ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs" /// </summary> internal const string CommonPrograms = "{0139D44E-6AFE-49F2-8690-3DAFCAE6FFB8}"; /// <summary> /// (CSIDL_COMMON_STARTMENU) Common Start Menu folder /// "%ALLUSERSPROFILE%\Microsoft\Windows\Start Menu" /// </summary> internal const string CommonStartMenu = "{A4115719-D62E-491D-AA7C-E74B8BE3B067}"; /// <summary> /// (CSIDL_COMMON_STARTUP, CSIDL_COMMON_ALTSTARTUP) Common Startup folder /// "%ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs\StartUp" /// </summary> internal const string CommonStartup = "{82A5EA35-D9CD-47C5-9629-E15D2F714E6E}"; /// <summary> /// (CSIDL_COMMON_TEMPLATES) Common Templates folder /// "%ALLUSERSPROFILE%\Microsoft\Windows\Templates" /// </summary> internal const string CommonTemplates = "{B94237E7-57AC-4347-9151-B08C6C32D1F7}"; /// <summary> /// (CSIDL_DRIVES) Computer virtual folder /// </summary> internal const string ComputerFolder = "{0AC0837C-BBF8-452A-850D-79D08E667CA7}"; /// <summary> /// (CSIDL_CONNECTIONS) Network Connections virtual folder /// </summary> internal const string ConnectionsFolder = "{6F0CD92B-2E97-45D1-88FF-B0D186B8DEDD}"; /// <summary> /// (CSIDL_CONTROLS) Control Panel virtual folder /// </summary> internal const string ControlPanelFolder = "{82A74AEB-AEB4-465C-A014-D097EE346D63}"; /// <summary> /// (CSIDL_COOKIES) Cookies folder /// "%APPDATA%\Microsoft\Windows\Cookies" /// </summary> internal const string Cookies = "{2B0F765D-C0E9-4171-908E-08A611B84FF6}"; /// <summary> /// (CSIDL_DESKTOP, CSIDL_DESKTOPDIRECTORY) Desktop folder /// "%USERPROFILE%\Desktop" /// </summary> internal const string Desktop = "{B4BFCC3A-DB2C-424C-B029-7FE99A87C641}"; /// <summary> /// (CSIDL_MYDOCUMENTS, CSIDL_PERSONAL) Documents (My Documents) folder /// "%USERPROFILE%\Documents" /// </summary> internal const string Documents = "{FDD39AD0-238F-46AF-ADB4-6C85480369C7}"; /// <summary> /// (CSIDL_FAVORITES, CSIDL_COMMON_FAVORITES) Favorites folder /// "%USERPROFILE%\Favorites" /// </summary> internal const string Favorites = "{1777F761-68AD-4D8A-87BD-30B759FA33DD}"; /// <summary> /// (CSIDL_FONTS) Fonts folder /// "%windir%\Fonts" /// </summary> internal const string Fonts = "{FD228CB7-AE11-4AE3-864C-16F3910AB8FE}"; /// <summary> /// (CSIDL_HISTORY) History folder /// "%LOCALAPPDATA%\Microsoft\Windows\History" /// </summary> internal const string History = "{D9DC8A3B-B784-432E-A781-5A1130A75963}"; /// <summary> /// (CSIDL_INTERNET_CACHE) Temporary Internet Files folder /// "%LOCALAPPDATA%\Microsoft\Windows\Temporary Internet Files" /// </summary> internal const string InternetCache = "{352481E8-33BE-4251-BA85-6007CAEDCF9D}"; /// <summary> /// (CSIDL_INTERNET) The Internet virtual folder /// </summary> internal const string InternetFolder = "{4D9F7874-4E0C-4904-967B-40B0D20C3E4B}"; /// <summary> /// (CSIDL_LOCAL_APPDATA) Local folder /// "%LOCALAPPDATA%" ("%USERPROFILE%\AppData\Local") /// </summary> internal const string LocalAppData = "{F1B32785-6FBA-4FCF-9D55-7B8E7F157091}"; /// <summary> /// (CSIDL_RESOURCES_LOCALIZED) Fixed localized resources folder /// "%windir%\resources\0409" (per active codepage) /// </summary> internal const string LocalizedResourcesDir = "{2A00375E-224C-49DE-B8D1-440DF7EF3DDC}"; /// <summary> /// (CSIDL_MYMUSIC) Music folder /// "%USERPROFILE%\Music" /// </summary> internal const string Music = "{4BD8D571-6D19-48D3-BE97-422220080E43}"; /// <summary> /// (CSIDL_NETHOOD) Network shortcuts folder "%APPDATA%\Microsoft\Windows\Network Shortcuts" /// </summary> internal const string NetHood = "{C5ABBF53-E17F-4121-8900-86626FC2C973}"; /// <summary> /// (CSIDL_NETWORK, CSIDL_COMPUTERSNEARME) Network virtual folder /// </summary> internal const string NetworkFolder = "{D20BEEC4-5CA8-4905-AE3B-BF251EA09B53}"; /// <summary> /// (CSIDL_MYPICTURES) Pictures folder "%USERPROFILE%\Pictures" /// </summary> internal const string Pictures = "{33E28130-4E1E-4676-835A-98395C3BC3BB}"; /// <summary> /// (CSIDL_PRINTERS) Printers virtual folder /// </summary> internal const string PrintersFolder = "{76FC4E2D-D6AD-4519-A663-37BD56068185}"; /// <summary> /// (CSIDL_PRINTHOOD) Printer Shortcuts folder /// "%APPDATA%\Microsoft\Windows\Printer Shortcuts" /// </summary> internal const string PrintHood = "{9274BD8D-CFD1-41C3-B35E-B13F55A758F4}"; /// <summary> /// (CSIDL_PROFILE) The root users profile folder "%USERPROFILE%" /// ("%SystemDrive%\Users\%USERNAME%") /// </summary> internal const string Profile = "{5E6C858F-0E22-4760-9AFE-EA3317B67173}"; /// <summary> /// (CSIDL_COMMON_APPDATA) ProgramData folder /// "%ALLUSERSPROFILE%" ("%ProgramData%", "%SystemDrive%\ProgramData") /// </summary> internal const string ProgramData = "{62AB5D82-FDC1-4DC3-A9DD-070D1D495D97}"; /// <summary> /// (CSIDL_PROGRAM_FILES) Program Files folder for the current process architecture /// "%ProgramFiles%" ("%SystemDrive%\Program Files") /// </summary> internal const string ProgramFiles = "{905e63b6-c1bf-494e-b29c-65b732d3d21a}"; /// <summary> /// (CSIDL_PROGRAM_FILESX86) 32 bit Program Files folder (available to both 32/64 bit processes) /// </summary> internal const string ProgramFilesX86 = "{7C5A40EF-A0FB-4BFC-874A-C0F2E0B9FA8E}"; /// <summary> /// (CSIDL_PROGRAM_FILES_COMMON) Common Program Files folder for the current process architecture /// "%ProgramFiles%\Common Files" /// </summary> internal const string ProgramFilesCommon = "{F7F1ED05-9F6D-47A2-AAAE-29D317C6F066}"; /// <summary> /// (CSIDL_PROGRAM_FILES_COMMONX86) Common 32 bit Program Files folder (available to both 32/64 bit processes) /// </summary> internal const string ProgramFilesCommonX86 = "{DE974D24-D9C6-4D3E-BF91-F4455120B917}"; /// <summary> /// (CSIDL_PROGRAMS) Start menu Programs folder /// "%APPDATA%\Microsoft\Windows\Start Menu\Programs" /// </summary> internal const string Programs = "{A77F5D77-2E2B-44C3-A6A2-ABA601054A51}"; /// <summary> /// (CSIDL_COMMON_DESKTOPDIRECTORY) Public Desktop folder /// "%PUBLIC%\Desktop" /// </summary> internal const string PublicDesktop = "{C4AA340D-F20F-4863-AFEF-F87EF2E6BA25}"; /// <summary> /// (CSIDL_COMMON_DOCUMENTS) Public Documents folder /// "%PUBLIC%\Documents" /// </summary> internal const string PublicDocuments = "{ED4824AF-DCE4-45A8-81E2-FC7965083634}"; /// <summary> /// (CSIDL_COMMON_MUSIC) Public Music folder /// "%PUBLIC%\Music" /// </summary> internal const string PublicMusic = "{3214FAB5-9757-4298-BB61-92A9DEAA44FF}"; /// <summary> /// (CSIDL_COMMON_PICTURES) Public Pictures folder /// "%PUBLIC%\Pictures" /// </summary> internal const string PublicPictures = "{B6EBFB86-6907-413C-9AF7-4FC2ABF07CC5}"; /// <summary> /// (CSIDL_COMMON_VIDEO) Public Videos folder /// "%PUBLIC%\Videos" /// </summary> internal const string PublicVideos = "{2400183A-6185-49FB-A2D8-4A392A602BA3}"; /// <summary> /// (CSIDL_RECENT) Recent Items folder /// "%APPDATA%\Microsoft\Windows\Recent" /// </summary> internal const string Recent = "{AE50C081-EBD2-438A-8655-8A092E34987A}"; /// <summary> /// (CSIDL_BITBUCKET) Recycle Bin virtual folder /// </summary> internal const string RecycleBinFolder = "{B7534046-3ECB-4C18-BE4E-64CD4CB7D6AC}"; /// <summary> /// (CSIDL_RESOURCES) Resources fixed folder /// "%windir%\Resources" /// </summary> internal const string ResourceDir = "{8AD10C31-2ADB-4296-A8F7-E4701232C972}"; /// <summary> /// (CSIDL_APPDATA) Roaming user application data folder /// "%APPDATA%" ("%USERPROFILE%\AppData\Roaming") /// </summary> internal const string RoamingAppData = "{3EB685DB-65F9-4CF6-A03A-E3EF65729F3D}"; /// <summary> /// (CSIDL_SENDTO) SendTo folder /// "%APPDATA%\Microsoft\Windows\SendTo" /// </summary> internal const string SendTo = "{8983036C-27C0-404B-8F08-102D10DCFD74}"; /// <summary> /// (CSIDL_STARTMENU) Start Menu folder /// "%APPDATA%\Microsoft\Windows\Start Menu" /// </summary> internal const string StartMenu = "{625B53C3-AB48-4EC1-BA1F-A1EF4146FC19}"; /// <summary> /// (CSIDL_STARTUP, CSIDL_ALTSTARTUP) Startup folder /// "%APPDATA%\Microsoft\Windows\Start Menu\Programs\StartUp" /// </summary> internal const string Startup = "{B97D20BB-F46A-4C97-BA10-5E3608430854}"; /// <summary> /// (CSIDL_SYSTEM) System32 folder /// "%windir%\system32" /// </summary> internal const string System = "{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}"; /// <summary> /// (CSIDL_SYSTEMX86) X86 System32 folder /// "%windir%\system32" or "%windir%\syswow64" /// </summary> internal const string SystemX86 = "{D65231B0-B2F1-4857-A4CE-A8E7C6EA7D27}"; /// <summary> /// (CSIDL_TEMPLATES) Templates folder /// "%APPDATA%\Microsoft\Windows\Templates" /// </summary> internal const string Templates = "{A63293E8-664E-48DB-A079-DF759E0509F7}"; /// <summary> /// (CSIDL_MYVIDEO) Videos folder /// "%USERPROFILE%\Videos" /// </summary> internal const string Videos = "{18989B1D-99B5-455B-841C-AB7C74E4DDFC}"; /// <summary> /// (CSIDL_WINDOWS) Windows folder "%windir%" /// </summary> internal const string Windows = "{F38BF404-1D43-42F2-9305-67DE0B28FC23}"; } } }
using System.Data; using System.Data.SqlClient; using Rainbow.Framework.Settings; namespace Rainbow.Framework.Content.Data { /// <summary> /// Class that encapsulates all data logic necessary to add/query/delete /// links within the Portal database. /// </summary> public class LinkDB { /// <summary> /// The GetLinks method returns a SqlDataReader containing all of the /// links for a specific portal module from the announcements /// database. /// </summary> /// <param name="moduleID">The module ID.</param> /// <param name="version">The version.</param> /// <returns></returns> public SqlDataReader GetLinks(int moduleID, WorkFlowVersion version) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_GetLinks", myConnection); // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4); parameterModuleID.Value = moduleID; myCommand.Parameters.Add(parameterModuleID); // Change by [email protected] // Date: 7/2/2003 SqlParameter parameterWorkflowVersion = new SqlParameter("@WorkflowVersion", SqlDbType.Int, 4); parameterWorkflowVersion.Value = (int) version; myCommand.Parameters.Add(parameterWorkflowVersion); // End Change [email protected] // Execute the command myConnection.Open(); SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection); // Return the datareader return result; } /// <summary> /// The GetSingleLink method returns a SqlDataReader containing details /// about a specific link from the Links database table. /// </summary> /// <param name="itemID">The item ID.</param> /// <param name="version">The version.</param> /// <returns></returns> public SqlDataReader GetSingleLink(int itemID, WorkFlowVersion version) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_GetSingleLink", myConnection); // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Value = itemID; myCommand.Parameters.Add(parameterItemID); // Change by [email protected] // Date: 7/2/2003 SqlParameter parameterWorkflowVersion = new SqlParameter("@WorkflowVersion", SqlDbType.Int, 4); parameterWorkflowVersion.Value = (int) version; myCommand.Parameters.Add(parameterWorkflowVersion); // End Change [email protected] // Execute the command myConnection.Open(); SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection); // Return the datareader return result; } /// <summary> /// The DeleteLink method deletes a specified link from /// the Links database table. /// </summary> /// <param name="itemID">The item ID.</param> public void DeleteLink(int itemID) { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_DeleteLink", myConnection); // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Value = itemID; myCommand.Parameters.Add(parameterItemID); myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } } /// <summary> /// The AddLink method adds a new link within the /// links database table, and returns ItemID value as a result. /// </summary> /// <param name="moduleID">The module ID.</param> /// <param name="itemID">The item ID.</param> /// <param name="userName">Name of the user.</param> /// <param name="title">The title.</param> /// <param name="url">The URL.</param> /// <param name="mobileUrl">The mobile URL.</param> /// <param name="viewOrder">The view order.</param> /// <param name="description">The description.</param> /// <param name="target">The target.</param> /// <returns></returns> public int AddLink(int moduleID, int itemID, string userName, string title, string url, string mobileUrl, int viewOrder, string description, string target) { if (userName.Length < 1) { userName = "unknown"; } // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_AddLink", myConnection); // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Direction = ParameterDirection.Output; myCommand.Parameters.Add(parameterItemID); SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4); parameterModuleID.Value = moduleID; myCommand.Parameters.Add(parameterModuleID); SqlParameter parameterUserName = new SqlParameter("@UserName", SqlDbType.NVarChar, 100); parameterUserName.Value = userName; myCommand.Parameters.Add(parameterUserName); SqlParameter parameterTitle = new SqlParameter("@Title", SqlDbType.NVarChar, 100); parameterTitle.Value = title; myCommand.Parameters.Add(parameterTitle); SqlParameter parameterDescription = new SqlParameter("@Description", SqlDbType.NVarChar, 100); parameterDescription.Value = description; myCommand.Parameters.Add(parameterDescription); SqlParameter parameterTarget = new SqlParameter("@Target", SqlDbType.NVarChar, 10); parameterTarget.Value = target; myCommand.Parameters.Add(parameterTarget); SqlParameter parameterUrl = new SqlParameter("@Url", SqlDbType.NVarChar, 800); parameterUrl.Value = url; myCommand.Parameters.Add(parameterUrl); SqlParameter parameterMobileUrl = new SqlParameter("@MobileUrl", SqlDbType.NVarChar, 250); parameterMobileUrl.Value = mobileUrl; myCommand.Parameters.Add(parameterMobileUrl); SqlParameter parameterViewOrder = new SqlParameter("@ViewOrder", SqlDbType.Int, 4); parameterViewOrder.Value = viewOrder; myCommand.Parameters.Add(parameterViewOrder); myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } return (int) parameterItemID.Value; } /// <summary> /// The UpdateLink method updates a specified link within /// the Links database table. /// </summary> /// <param name="moduleID">The module ID.</param> /// <param name="itemID">The item ID.</param> /// <param name="userName">Name of the user.</param> /// <param name="title">The title.</param> /// <param name="url">The URL.</param> /// <param name="mobileUrl">The mobile URL.</param> /// <param name="viewOrder">The view order.</param> /// <param name="description">The description.</param> /// <param name="target">The target.</param> public void UpdateLink(int moduleID, int itemID, string userName, string title, string url, string mobileUrl, int viewOrder, string description, string target) { if (userName.Length < 1) { userName = "unknown"; } // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_UpdateLink", myConnection); // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterItemID = new SqlParameter("@ItemID", SqlDbType.Int, 4); parameterItemID.Value = itemID; myCommand.Parameters.Add(parameterItemID); SqlParameter parameterUserName = new SqlParameter("@UserName", SqlDbType.NVarChar, 100); parameterUserName.Value = userName; myCommand.Parameters.Add(parameterUserName); SqlParameter parameterTitle = new SqlParameter("@Title", SqlDbType.NVarChar, 100); parameterTitle.Value = title; myCommand.Parameters.Add(parameterTitle); SqlParameter parameterDescription = new SqlParameter("@Description", SqlDbType.NVarChar, 100); parameterDescription.Value = description; myCommand.Parameters.Add(parameterDescription); SqlParameter parameterUrl = new SqlParameter("@Url", SqlDbType.NVarChar, 800); parameterUrl.Value = url; myCommand.Parameters.Add(parameterUrl); SqlParameter parameterMobileUrl = new SqlParameter("@MobileUrl", SqlDbType.NVarChar, 250); parameterMobileUrl.Value = mobileUrl; myCommand.Parameters.Add(parameterMobileUrl); SqlParameter parameterViewOrder = new SqlParameter("@ViewOrder", SqlDbType.Int, 4); parameterViewOrder.Value = viewOrder; myCommand.Parameters.Add(parameterViewOrder); SqlParameter parameterTarget = new SqlParameter("@Target", SqlDbType.NVarChar, 10); parameterTarget.Value = target; myCommand.Parameters.Add(parameterTarget); myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } } } }
// // AssemblyNameTest.cs - NUnit Test Cases for AssemblyName // // Author: // Sebastien Pouliot <[email protected]> // // (C) 2002 Motus Technologies Inc. (http://www.motus.com) // Copyright (C) 2005 Novell, Inc (http://www.novell.com) // using NUnit.Framework; using System; using System.Configuration.Assemblies; using System.IO; using System.Reflection; using System.Reflection.Emit; using System.Runtime.Serialization; using System.Threading; using System.Globalization; using System.Runtime.Serialization.Formatters.Binary; namespace MonoTests.System.Reflection { [TestFixture] public class AssemblyNameTest { static public void AssertEqualsByteArrays (string msg, byte[] array1, byte[] array2) { if ((array1 == null) && (array2 == null)) return; if (array1 == null) Assert.Fail (msg + " -> First array is NULL"); if (array2 == null) Assert.Fail (msg + " -> Second array is NULL"); bool a = (array1.Length == array2.Length); if (a) { for (int i = 0; i < array1.Length; i++) { if (array1 [i] != array2 [i]) { a = false; break; } } } msg += " -> Expected " + (array1.Length > 0 ? BitConverter.ToString (array1, 0) : "<empty>"); msg += " is different than " + (array2.Length > 0 ? BitConverter.ToString (array2, 0) : "<empty>"); Assert.IsTrue (a, msg); } private AssemblyName an; private string tempDir = Path.Combine (Path.GetTempPath (), "MonoTests.System.Reflection.AssemblyNameTest"); private AppDomain domain; // created with "sn -o test.snk test.txt" static byte[] publicKey = { 0x07, 0x02, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x52, 0x53, 0x41, 0x32, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x3D, 0xBD, 0x72, 0x08, 0xC6, 0x2B, 0x0E, 0xA8, 0xC1, 0xC0, 0x58, 0x07, 0x2B, 0x63, 0x5F, 0x7C, 0x9A, 0xBD, 0xCB, 0x22, 0xDB, 0x20, 0xB2, 0xA9, 0xDA, 0xDA, 0xEF, 0xE8, 0x00, 0x64, 0x2F, 0x5D, 0x8D, 0xEB, 0x78, 0x02, 0xF7, 0xA5, 0x36, 0x77, 0x28, 0xD7, 0x55, 0x8D, 0x14, 0x68, 0xDB, 0xEB, 0x24, 0x09, 0xD0, 0x2B, 0x13, 0x1B, 0x92, 0x6E, 0x2E, 0x59, 0x54, 0x4A, 0xAC, 0x18, 0xCF, 0xC9, 0x09, 0x02, 0x3F, 0x4F, 0xA8, 0x3E, 0x94, 0x00, 0x1F, 0xC2, 0xF1, 0x1A, 0x27, 0x47, 0x7D, 0x10, 0x84, 0xF5, 0x14, 0xB8, 0x61, 0x62, 0x1A, 0x0C, 0x66, 0xAB, 0xD2, 0x4C, 0x4B, 0x9F, 0xC9, 0x0F, 0x3C, 0xD8, 0x92, 0x0F, 0xF5, 0xFF, 0xCE, 0xD7, 0x6E, 0x5C, 0x6F, 0xB1, 0xF5, 0x7D, 0xD3, 0x56, 0xF9, 0x67, 0x27, 0xA4, 0xA5, 0x48, 0x5B, 0x07, 0x93, 0x44, 0x00, 0x4A, 0xF8, 0xFF, 0xA4, 0xCB, 0x73, 0xC0, 0x6A, 0x62, 0xB4, 0xB7, 0xC8, 0x92, 0x58, 0x87, 0xCD, 0x07, 0x0C, 0x7D, 0x6C, 0xC1, 0x4A, 0xFC, 0x82, 0x57, 0x0E, 0x43, 0x85, 0x09, 0x75, 0x98, 0x51, 0xBB, 0x35, 0xF5, 0x64, 0x83, 0xC7, 0x79, 0x89, 0x5C, 0x55, 0x36, 0x66, 0xAB, 0x27, 0xA4, 0xD9, 0xD4, 0x7E, 0x6B, 0x67, 0x64, 0xC1, 0x54, 0x4E, 0x37, 0xF1, 0x4E, 0xCA, 0xB3, 0xE5, 0x63, 0x91, 0x57, 0x12, 0x14, 0xA6, 0xEA, 0x8F, 0x8F, 0x2B, 0xFE, 0xF3, 0xE9, 0x16, 0x08, 0x2B, 0x86, 0xBC, 0x26, 0x0D, 0xD0, 0xC6, 0xC4, 0x1A, 0x72, 0x43, 0x76, 0xDC, 0xFF, 0x28, 0x52, 0xA1, 0xDE, 0x8D, 0xFA, 0xD5, 0x1F, 0x0B, 0xB5, 0x4F, 0xAF, 0x06, 0x79, 0x11, 0xEE, 0xA8, 0xEC, 0xD3, 0x74, 0x55, 0xA2, 0x80, 0xFC, 0xF8, 0xD9, 0x50, 0x69, 0x48, 0x01, 0xC2, 0x5A, 0x04, 0x56, 0xB4, 0x3E, 0x24, 0x32, 0x20, 0xB5, 0x2C, 0xDE, 0xBB, 0xBD, 0x13, 0xFD, 0x13, 0xF7, 0x03, 0x3E, 0xE3, 0x37, 0x84, 0x74, 0xE7, 0xD0, 0x5E, 0x9E, 0xB6, 0x26, 0xAE, 0x6E, 0xB0, 0x55, 0x6A, 0x52, 0x63, 0x6F, 0x5A, 0x9D, 0xF2, 0x67, 0xD6, 0x61, 0x4F, 0x7A, 0x45, 0xEE, 0x5C, 0x3D, 0x2B, 0x7C, 0xB2, 0x40, 0x79, 0x54, 0x84, 0xD1, 0xBE, 0x61, 0x3E, 0x5E, 0xD6, 0x18, 0x8E, 0x14, 0x98, 0xFC, 0x35, 0xBF, 0x5F, 0x1A, 0x20, 0x2E, 0x1A, 0xD8, 0xFF, 0xC4, 0x6B, 0xC0, 0xC9, 0x7D, 0x06, 0xEF, 0x09, 0xF9, 0xF3, 0x69, 0xFC, 0xBC, 0xA2, 0xE6, 0x80, 0x22, 0xB9, 0x79, 0x7E, 0xEF, 0x57, 0x9F, 0x49, 0xE1, 0xBC, 0x0D, 0xB6, 0xA1, 0xFE, 0x8D, 0xBC, 0xBB, 0xA3, 0x05, 0x02, 0x6B, 0x04, 0x45, 0xF7, 0x5D, 0xEE, 0x43, 0x06, 0xD6, 0x9C, 0x94, 0x48, 0x1A, 0x0B, 0x9C, 0xBC, 0xB4, 0x4E, 0x93, 0x60, 0x87, 0xCD, 0x58, 0xD6, 0x9A, 0x39, 0xA6, 0xC0, 0x7F, 0x8E, 0xFF, 0x25, 0xC1, 0xD7, 0x2C, 0xF6, 0xF4, 0x6F, 0x24, 0x52, 0x0B, 0x39, 0x42, 0x1B, 0x0D, 0x04, 0xC1, 0x93, 0x2A, 0x19, 0x1C, 0xF0, 0xB1, 0x9B, 0xC1, 0x24, 0x6D, 0x1B, 0x0B, 0xDA, 0x1C, 0x8B, 0x72, 0x48, 0xF0, 0x3E, 0x52, 0xBF, 0x0A, 0x84, 0x3A, 0x9B, 0xC8, 0x6D, 0x13, 0x1E, 0x72, 0xF4, 0x46, 0x93, 0x88, 0x1A, 0x5F, 0x4C, 0x3C, 0xE5, 0x9D, 0x6E, 0xBB, 0x4E, 0xDD, 0x5D, 0x1F, 0x11, 0x40, 0xF4, 0xD7, 0xAF, 0xB3, 0xAB, 0x9A, 0x99, 0x15, 0xF0, 0xDC, 0xAA, 0xFF, 0x9F, 0x2D, 0x9E, 0x56, 0x4F, 0x35, 0x5B, 0xBA, 0x06, 0x99, 0xEA, 0xC6, 0xB4, 0x48, 0x51, 0x17, 0x1E, 0xD1, 0x95, 0x84, 0x81, 0x18, 0xC0, 0xF1, 0x71, 0xDE, 0x44, 0x42, 0x02, 0x06, 0xAC, 0x0E, 0xA8, 0xE2, 0xF3, 0x1F, 0x96, 0x1F, 0xBE, 0xB6, 0x1F, 0xB5, 0x3E, 0xF6, 0x81, 0x05, 0x20, 0xFA, 0x2E, 0x40, 0x2E, 0x4D, 0xA0, 0x0E, 0xDA, 0x42, 0x9C, 0x05, 0xAA, 0x9E, 0xAF, 0x5C, 0xF7, 0x3A, 0x3F, 0xBB, 0x91, 0x73, 0x45, 0x27, 0xA8, 0xA2, 0x07, 0x4A, 0xEF, 0x59, 0x1E, 0x97, 0x9D, 0xE0, 0x30, 0x5A, 0x83, 0xCE, 0x1E, 0x57, 0x32, 0x89, 0x43, 0x41, 0x28, 0x7D, 0x14, 0x8D, 0x8B, 0x41, 0x1A, 0x56, 0x76, 0x43, 0xDB, 0x64, 0x86, 0x41, 0x64, 0x8D, 0x4C, 0x91, 0x83, 0x4E, 0xF5, 0x6C }; static byte[] token = { 0xFF, 0xEF, 0x94, 0x53, 0x67, 0x69, 0xDA, 0x06 }; [SetUp] public void SetUp () { try { if (Directory.Exists (tempDir)) Directory.Delete (tempDir, true); } catch (Exception) { } Directory.CreateDirectory (tempDir); domain = Thread.GetDomain (); } [TearDown] public void TearDown () { try { if (Directory.Exists (tempDir)) Directory.Delete (tempDir, true); } catch (Exception) { // This can happen on windows when the directory contains // files opened by the CLR } } [Test] public void EmptyAssembly () { an = new AssemblyName (); Assert.IsNull (an.CodeBase, "CodeBase"); Assert.IsNull (an.CultureInfo, "CultureInfo"); Assert.IsNull (an.EscapedCodeBase, "EscapedCodeBase"); Assert.AreEqual (AssemblyNameFlags.None, an.Flags, "Flags"); Assert.IsNull (an.FullName, "FullName"); Assert.AreEqual (AssemblyHashAlgorithm.None, an.HashAlgorithm, "HashAlgorithm"); Assert.IsNull (an.KeyPair, "KeyPair"); Assert.IsNull (an.Name, "Name"); Assert.IsNull (an.Version, "Version"); Assert.AreEqual (AssemblyVersionCompatibility.SameMachine, an.VersionCompatibility, "VersionCompatibility"); } [Test] public void PublicKey () { an = new AssemblyName (); Assert.IsNull (an.GetPublicKey (), "PublicKey(empty)"); an.SetPublicKey (publicKey); Assert.AreEqual (AssemblyNameFlags.PublicKey, an.Flags, "Flags"); // strangly it doesn't affect the KeyPair ? Assert.IsNull (an.KeyPair, "KeyPair"); AssertEqualsByteArrays ("PublicKey", publicKey, an.GetPublicKey ()); AssertEqualsByteArrays ("PublicKeyToken", token, an.GetPublicKeyToken ()); } [Test] public void PublicKeyToken () { an = new AssemblyName (); an.SetPublicKeyToken (token); Assert.AreEqual (AssemblyNameFlags.None, an.Flags, "Flags"); Assert.IsNull (an.KeyPair, "KeyPair"); Assert.IsNull (an.GetPublicKey (), "PublicKey"); AssertEqualsByteArrays ("PublicKeyToken", token, an.GetPublicKeyToken ()); } [Test] public void KeyPair () { an = new AssemblyName (); an.KeyPair = new StrongNameKeyPair (publicKey); Assert.AreEqual (AssemblyNameFlags.None, an.Flags, "Flags"); Assert.IsNotNull (an.KeyPair, "KeyPair"); Assert.IsNull (an.GetPublicKey (), "PublicKey"); Assert.IsNull (an.GetPublicKeyToken (), "PublicKeyToken"); } // !!! this assembly MUST NOT use a StrongName !!! [Test] public void Self () { Assembly a = Assembly.GetExecutingAssembly (); AssemblyName an = a.GetName (); Assert.IsNotNull (an.GetPublicKey (), "PublicKey(self)"); Assert.AreEqual (0, an.GetPublicKey ().Length, "PublicKey.Length"); } [Test] public void FullName1 () { // !!! we assume the mscorlib has a strong name !!! AssemblyName an = typeof(int).Assembly.GetName (); Assert.IsNotNull (an.FullName, "FullName1#1"); Assert.IsTrue (an.FullName.IndexOf ("Version=") != -1, "FullName1#2"); Assert.IsTrue (an.FullName.IndexOf("Culture=") != -1, "FullName1#3"); Assert.IsTrue (an.FullName.IndexOf ("PublicKeyToken=") != -1, "FullName1#4"); } [Test] public void FullName2 () { const string assemblyName = "TestAssembly"; // tests for AssemblyName with only name AssemblyName an = new AssemblyName (); an.Name = assemblyName; Assert.IsNotNull (an.FullName, "FullName2#1"); Assert.AreEqual (an.Name, an.FullName, "FullName2#2"); Assert.AreEqual (-1, an.FullName.IndexOf ("Culture="), "FullName2#3"); Assert.AreEqual (-1, an.FullName.IndexOf ("PublicKeyToken="), "FullName2#4"); } [Test] public void FullName3 () { const string assemblyName = "TestAssembly"; const string assemblyVersion = "1.2"; // tests for AssemblyName with name and version AssemblyName an = new AssemblyName (); an.Name = assemblyName; an.Version = new Version (assemblyVersion); Assert.AreEqual (assemblyName + ", Version=" + assemblyVersion, an.FullName, "FullName3#1"); } [Test] public void FullName4 () { const string assemblyName = "TestAssembly"; // tests for AssemblyName with name and neutral culture AssemblyName an = new AssemblyName (); an.Name = assemblyName; an.CultureInfo = CultureInfo.InvariantCulture; Assert.AreEqual (assemblyName + ", Culture=neutral", an.FullName, "FullName4#1"); } [Test] public void FullName5 () { const string assemblyName = "TestAssembly"; // tests for AssemblyName with name and public key AssemblyName an = new AssemblyName (); an.Name = assemblyName; an.SetPublicKey (publicKey); Assert.AreEqual (assemblyName + ", PublicKeyToken=" + GetTokenString(token), an.FullName, "FullName5#1"); } [Test] public void FullName6 () { const string assemblyName = "TestAssembly"; const string assemblyVersion = "1.2"; // tests for AssemblyName with name, version and neutral culture AssemblyName an = new AssemblyName (); an.Name = assemblyName; an.Version = new Version (assemblyVersion); an.CultureInfo = CultureInfo.InvariantCulture; Assert.AreEqual (assemblyName + ", Version=" + assemblyVersion + ", Culture=neutral", an.FullName, "FullName6#1"); } [Test] public void FullName7 () { const string assemblyName = "TestAssembly"; const string assemblyVersion = "1.2"; // tests for AssemblyName with name, version and public key AssemblyName an = new AssemblyName (); an.Name = assemblyName; an.Version = new Version (assemblyVersion); an.SetPublicKey (publicKey); Assert.AreEqual (assemblyName + ", Version=" + assemblyVersion + ", PublicKeyToken=" + GetTokenString (token), an.FullName, "FullName7#1"); } [Test] public void FullName8 () { const string assemblyName = "TestAssembly"; // tests for AssemblyName with name, culture and public key AssemblyName an = new AssemblyName (); an.Name = assemblyName; an.CultureInfo = CultureInfo.InvariantCulture; an.SetPublicKey (publicKey); Assert.AreEqual (assemblyName + ", Culture=neutral" + ", PublicKeyToken=" + GetTokenString (token), an.FullName, "FullName8#1"); } static int nameIndex = 0; private AssemblyName GenAssemblyName () { AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = "MonoTests.System.Reflection.AssemblyNameTest" + (nameIndex ++); return assemblyName; } private Assembly GenerateAssembly (AssemblyName name) { AssemblyBuilder ab = domain.DefineDynamicAssembly ( name, AssemblyBuilderAccess.RunAndSave, tempDir); ab.DefineDynamicModule ("def_module"); ab.Save (name.Name + ".dll"); return Assembly.LoadFrom (Path.Combine (tempDir, name.Name + ".dll")); } private AssemblyBuilder GenerateDynamicAssembly (AssemblyName name) { AssemblyBuilder ab = domain.DefineDynamicAssembly ( name, AssemblyBuilderAccess.Run); return ab; } [Test] public void TestCultureInfo () { AssemblyName name = GenAssemblyName (); name.CultureInfo = CultureInfo.CreateSpecificCulture ("ar-DZ"); Assembly a = GenerateAssembly (name); Assert.AreEqual (a.GetName ().CultureInfo.Name, "ar-DZ"); } [Test] public void Version () { AssemblyName name = GenAssemblyName (); name.Version = new Version (1, 2, 3, 4); Assembly a = GenerateAssembly (name); Assert.AreEqual ("1.2.3.4", a.GetName ().Version.ToString ()); AssemblyBuilder ab = GenerateDynamicAssembly (name); Assert.AreEqual ("1.2.3.4", ab.GetName ().Version.ToString ()); name = GenAssemblyName (); name.Version = new Version (1, 2, 3); a = GenerateAssembly (name); Assert.AreEqual ("1.2.3.0", a.GetName ().Version.ToString ()); ab = GenerateDynamicAssembly (name); Assert.AreEqual ("1.2.3.0", ab.GetName ().Version.ToString ()); name = GenAssemblyName (); name.Version = new Version (1, 2); a = GenerateAssembly (name); Assert.AreEqual ("1.2.0.0", a.GetName ().Version.ToString ()); ab = GenerateDynamicAssembly (name); Assert.AreEqual ("1.2.0.0", ab.GetName ().Version.ToString ()); } [Test] public void HashAlgorithm () { Assert.AreEqual (AssemblyHashAlgorithm.SHA1, typeof (int).Assembly.GetName ().HashAlgorithm); } [Test] public void Serialization () { AssemblyName an = new AssemblyName (); an.CodeBase = "http://www.test.com/test.dll"; an.CultureInfo = CultureInfo.InvariantCulture; an.Flags = AssemblyNameFlags.PublicKey; an.HashAlgorithm = AssemblyHashAlgorithm.MD5; an.KeyPair = new StrongNameKeyPair (publicKey); an.Name = "TestAssembly"; an.Version = new Version (1, 5); an.VersionCompatibility = AssemblyVersionCompatibility.SameProcess; MemoryStream ms = new MemoryStream (); BinaryFormatter bf = new BinaryFormatter (); bf.Serialize (ms, an); // reset position of memorystream ms.Position = 0; // deserialze assembly name AssemblyName dsAssemblyName = (AssemblyName) bf.Deserialize (ms); // close the memorystream ms.Close (); // compare orginal and deserialized assembly name Assert.AreEqual (an.CodeBase, dsAssemblyName.CodeBase, "CodeBase"); Assert.AreEqual (an.CultureInfo, dsAssemblyName.CultureInfo, "CultureInfo"); Assert.AreEqual (an.Flags, dsAssemblyName.Flags, "Flags"); Assert.AreEqual (an.HashAlgorithm, dsAssemblyName.HashAlgorithm, "HashAlgorithm"); Assert.AreEqual (an.Name, dsAssemblyName.Name, "Name"); Assert.AreEqual (an.Version, dsAssemblyName.Version, "Version"); Assert.AreEqual (an.VersionCompatibility, dsAssemblyName.VersionCompatibility, "VersionCompatibility"); Assert.AreEqual (an.EscapedCodeBase, dsAssemblyName.EscapedCodeBase, "EscapedCodeBase"); Assert.AreEqual (an.FullName, dsAssemblyName.FullName, "FullName"); Assert.AreEqual (an.ToString (), dsAssemblyName.ToString (), "ToString"); AssertEqualsByteArrays ("PublicKey", an.GetPublicKey (), dsAssemblyName.GetPublicKey ()); AssertEqualsByteArrays ("PublicToken", an.GetPublicKeyToken (), dsAssemblyName.GetPublicKeyToken ()); } [Test] public void Serialization_WithoutStrongName () { AssemblyName an = new AssemblyName (); an.CodeBase = "http://www.test.com/test.dll"; an.CultureInfo = CultureInfo.InvariantCulture; an.Flags = AssemblyNameFlags.None; an.HashAlgorithm = AssemblyHashAlgorithm.SHA1; an.KeyPair = null; an.Name = "TestAssembly2"; an.Version = new Version (1, 5, 0, 0); an.VersionCompatibility = AssemblyVersionCompatibility.SameMachine; MemoryStream ms = new MemoryStream (); BinaryFormatter bf = new BinaryFormatter (); bf.Serialize (ms, an); // reset position of memorystream ms.Position = 0; // deserialze assembly name AssemblyName dsAssemblyName = (AssemblyName) bf.Deserialize (ms); // close the memorystream ms.Close (); // compare orginal and deserialized assembly name Assert.AreEqual (an.CodeBase, dsAssemblyName.CodeBase, "CodeBase"); Assert.AreEqual (an.CultureInfo, dsAssemblyName.CultureInfo, "CultureInfo"); Assert.AreEqual (an.Flags, dsAssemblyName.Flags, "Flags"); Assert.AreEqual (an.HashAlgorithm, dsAssemblyName.HashAlgorithm, "HashAlgorithm"); Assert.AreEqual (an.Name, dsAssemblyName.Name, "Name"); Assert.AreEqual (an.Version, dsAssemblyName.Version, "Version"); Assert.AreEqual (an.VersionCompatibility, dsAssemblyName.VersionCompatibility, "VersionCompatibility"); Assert.AreEqual (an.EscapedCodeBase, dsAssemblyName.EscapedCodeBase, "EscapedCodeBase"); Assert.AreEqual (an.FullName, dsAssemblyName.FullName, "FullName"); Assert.AreEqual (an.ToString (), dsAssemblyName.ToString (), "ToString"); AssertEqualsByteArrays ("PublicKey", an.GetPublicKey (), dsAssemblyName.GetPublicKey ()); AssertEqualsByteArrays ("PublicToken", an.GetPublicKeyToken (), dsAssemblyName.GetPublicKeyToken ()); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void GetObjectData_Null () { AssemblyName an = new AssemblyName (); an.GetObjectData (null, new StreamingContext (StreamingContextStates.All)); } [Test] public void Clone_Empty () { an = new AssemblyName (); AssemblyName clone = (AssemblyName) an.Clone (); Assert.IsNull (clone.CodeBase, "CodeBase"); Assert.IsNull (clone.CultureInfo, "CultureInfo"); Assert.IsNull (clone.EscapedCodeBase, "EscapedCodeBase"); Assert.AreEqual (AssemblyNameFlags.None, clone.Flags, "Flags"); Assert.IsNull (clone.FullName, "FullName"); Assert.AreEqual (AssemblyHashAlgorithm.None, clone.HashAlgorithm, "HashAlgorithm"); Assert.IsNull (clone.KeyPair, "KeyPair"); Assert.IsNull (clone.Name, "Name"); Assert.IsNull (clone.Version, "Version"); Assert.AreEqual (AssemblyVersionCompatibility.SameMachine, clone.VersionCompatibility, "VersionCompatibility"); } [Test] public void Clone_Self () { an = Assembly.GetExecutingAssembly ().GetName (); AssemblyName clone = (AssemblyName) an.Clone (); Assert.AreEqual (an.CodeBase, clone.CodeBase, "CodeBase"); Assert.AreEqual (an.CultureInfo, clone.CultureInfo, "CultureInfo"); Assert.AreEqual (an.EscapedCodeBase, clone.EscapedCodeBase, "EscapedCodeBase"); Assert.AreEqual (an.Flags, clone.Flags, "Flags"); Assert.AreEqual (an.FullName, clone.FullName, "FullName"); Assert.AreEqual (an.HashAlgorithm, clone.HashAlgorithm, "HashAlgorithm"); Assert.AreEqual (an.KeyPair, clone.KeyPair, "KeyPair"); Assert.AreEqual (an.Name, clone.Name, "Name"); Assert.AreEqual (an.Version, clone.Version, "Version"); Assert.AreEqual (an.VersionCompatibility, clone.VersionCompatibility, "VersionCompatibility"); } // helpers private string GetTokenString (byte[] value) { string tokenString = ""; for (int i = 0; i < value.Length; i++) { tokenString += value[i].ToString ("x2"); } return tokenString; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Collections.Generic; using Microsoft.Protocols.TestTools.StackSdk; namespace Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpeusb { /// <summary> /// The builder is used to build various URB objects. /// </summary> public class UrbBuilder { #region Private Members private URB_FUNCTIONID function; private uint requestId; private byte noAck; #endregion #region Build Methods /// <summary> /// Constructor /// </summary> /// <param name="function">The URB function.</param> /// <param name="requestId">An ID that uniquely identifies the TRANSFER_IN_REQUEST or TRANSFER_OUT_REQUEST.</param> /// <param name="noAck">f this bit is nonzero the client should not send a URB_COMPLETION message for this /// TRANSFER_OUT_REQUEST. This bit can be nonzero only if the NoAckIsochWriteJitterBufferSizeInMs field /// in USB_DEVICE_CAPABILITIES is nonzero and URB Function is set to URB_FUNCTION_ISOCH_TRANSFER. /// If the RequestId field is set to TRANSFER_IN_REQUEST, this field MUST be set to zero.</param> public UrbBuilder(URB_FUNCTIONID function, uint requestId, byte noAck) { this.function = function; this.requestId = requestId; this.noAck = noAck; } /// <summary> /// Builds a particular request for a string descriptor from the device. /// </summary> /// <param name="index">Specifies the device-defined index of the descriptor that is being retrieved or set.</param> /// <returns>The string descriptor request.</returns> public TS_URB_CONTROL_DESCRIPTOR_REQUEST BuildStringDescriptorRequest(byte index) { return BuildStringDescriptorRequest(index, 0x0409); } /// <summary> /// Builds a particular request for a string descriptor from the device. /// </summary> /// <param name="index">Specifies the device-defined index of the descriptor that is being retrieved or set.</param> /// <param name="languageId">Locale ID of the language.</param> /// <returns>The string descriptor request.</returns> public TS_URB_CONTROL_DESCRIPTOR_REQUEST BuildStringDescriptorRequest(byte index, ushort languageId) { TS_URB_CONTROL_DESCRIPTOR_REQUEST des = new TS_URB_CONTROL_DESCRIPTOR_REQUEST(); des.Header.Size = 12; des.Header.URB_Function = URB_FUNCTIONID.URB_FUNCTION_GET_DESCRIPTOR_FROM_DEVICE; des.Header.RequestId = this.requestId; des.Header.NoAck = this.noAck; des.Index = index; des.DescriptorType = (byte)UsbDescriptorTypes.USB_STRING_DESCRIPTOR_TYPE; // English (U.S.) des.LanguageId = languageId; return des; } /// <summary> /// Builds a descriptor request to get the information of the whole device. /// </summary> /// <returns>The device descriptor request</returns> public TS_URB_CONTROL_DESCRIPTOR_REQUEST BuildDeviceDescriptorRequest() { TS_URB_CONTROL_DESCRIPTOR_REQUEST des = new TS_URB_CONTROL_DESCRIPTOR_REQUEST(); des.Header.Size = 12; des.Header.URB_Function = URB_FUNCTIONID.URB_FUNCTION_GET_DESCRIPTOR_FROM_DEVICE; des.Header.RequestId = this.requestId; des.Header.NoAck = this.noAck; des.Index = 0; // this parameter not used for device descriptors des.DescriptorType = (byte)UsbDescriptorTypes.USB_DEVICE_DESCRIPTOR_TYPE; des.LanguageId = 0; // this parameter not used for device descriptors return des; } /// <summary> /// Builds a descriptor request to get the information of the configurations. /// </summary> /// <param name="index">number of configuration descriptor</param> /// <returns>The configuration descriptor request</returns> public TS_URB_CONTROL_DESCRIPTOR_REQUEST BuildConfigurationDescriptorRequest(byte index) { TS_URB_CONTROL_DESCRIPTOR_REQUEST des = new TS_URB_CONTROL_DESCRIPTOR_REQUEST(); des.Header.Size = 12; des.Header.URB_Function = URB_FUNCTIONID.URB_FUNCTION_GET_DESCRIPTOR_FROM_DEVICE; des.Header.RequestId = this.requestId; des.Header.NoAck = this.noAck; des.Index = index; des.DescriptorType = (byte)UsbDescriptorTypes.USB_CONFIGURATION_DESCRIPTOR_TYPE; des.LanguageId = 0; // this parameter not used for configuration descriptors return des; } /// <summary> /// Builds a configuration-selection request. /// </summary> /// <param name="interfaces">The interface information field.</param> /// <param name="configDescriptor">The configuration descriptor.</param> /// <returns>The configuration-selection request.</returns> public TS_URB_SELECT_CONFIGURATION BuildSelectConfigRequest( TS_USBD_INTERFACE_INFORMATION[] interfaces, byte[] configDescriptor ) { TS_URB_SELECT_CONFIGURATION req = new TS_URB_SELECT_CONFIGURATION( this.requestId, this.noAck ); // TS_URB_HEADER (8 bytes) + ConfigurationDescriptorIsValid (1 byte) + Padding (3 bytes) // NumInterfaces (4 bytes) + TS_USBD_INTERFACE_INFORMATION + USB_CONFIGURATION_DESCRIPTOR int interfaceLength = 0; foreach (TS_USBD_INTERFACE_INFORMATION i in interfaces) { interfaceLength += i.Length; } req.Header.Size = (ushort)(8 + 1 + 3 + 4 + interfaceLength + configDescriptor.Length); req.Header.URB_Function = URB_FUNCTIONID.URB_FUNCTION_SELECT_CONFIGURATION; req.Interfaces = interfaces; req.NumInterfaces = (uint)interfaces.Length; req.UsbConfDesc = configDescriptor; req.ConfigurationDescriptorIsValid = (configDescriptor != null ? (byte)1 : (byte)0); return req; } /// <summary> /// Builds an interface-selection request. /// </summary> /// <param name="configuration">The result of configuration-selection.</param> /// <param name="index">The index of the interface to be selected.</param> /// <returns>The interface-selection request.</returns> public TS_URB_SELECT_INTERFACE BuildSelectionInterfaceRequest(TS_URB_SELECT_CONFIGURATION_RESULT configuration, int index) { if (null == configuration) { throw new ArgumentNullException("configuration"); } if (index >= configuration.Interface.Length || null == configuration.Interface[index]) { throw new ArgumentException("index specified interface doesn't exist."); } TS_URB_SELECT_INTERFACE urb = new TS_URB_SELECT_INTERFACE(this.requestId, this.noAck); urb.ConfigurationHandle = configuration.ConfigurationHandle; urb.Header.Size = 8 + 4; // Header + ConfigurationHandle urb.TsUsbdIInfo = new TS_USBD_INTERFACE_INFORMATION(); TS_USBD_INTERFACE_INFORMATION_RESULT inf = configuration.Interface[index]; if (inf.NumberOfPipes != inf.Pipes.Length) { throw new ArgumentException(String.Format( "The selecting interface count doesn't match. NumberOfPipes: {0}, Pipes count: {1}.", inf.NumberOfPipes, inf.Pipes.Length )); } urb.TsUsbdIInfo.Length = 2 + 2 + 1 + 1 + 2 + 4; urb.TsUsbdIInfo.NumberOfPipesExpected = (ushort)inf.NumberOfPipes; urb.TsUsbdIInfo.InterfaceNumber = inf.InterfaceNumber; urb.TsUsbdIInfo.AlternateSetting = inf.AlternateSetting; urb.TsUsbdIInfo.Padding = PaddingGenerator.GeneratePadding(); urb.TsUsbdIInfo.NumberOfPipes = inf.NumberOfPipes; urb.TsUsbdIInfo.Infomations = new TS_USBD_PIPE_INFORMATION[inf.NumberOfPipes]; for (int i = 0; i < inf.NumberOfPipes; i++) { urb.TsUsbdIInfo.Length += 2 + 2 + 4 + 4; // count Pipe sizes urb.TsUsbdIInfo.Infomations[i] = new TS_USBD_PIPE_INFORMATION(); urb.TsUsbdIInfo.Infomations[i].MaximumPacketSize = inf.Pipes[i].MaximumPacketSize; urb.TsUsbdIInfo.Infomations[i].Padding = PaddingGenerator.GeneratePadding(); urb.TsUsbdIInfo.Infomations[i].MaximumTransferSize = inf.Pipes[i].MaximumTransferSize; urb.TsUsbdIInfo.Infomations[i].PipeFlags = inf.Pipes[i].PipeFlags; } urb.Header.Size += urb.TsUsbdIInfo.Length; // interface information size. return urb; } /// <summary> /// Builds a vendor command request. /// </summary> /// <param name="request">Specifies the USB or vendor-defined request code for the device, interface, endpoint, or other device-defined target. </param> /// <param name="value">Specifies a value, specific to Request, that becomes part of the USB-defined setup packet for the target. This value is defined by the creator of the code used in Request.</param> /// <param name="flag">Specifies zero, one, or a combination of the flags of type TransferFlags.</param> /// <returns>The vendor command request.</returns> public TS_URB_CONTROL_VENDOR_OR_CLASS_REQUEST BuildVendorCommandRequest(byte request, ushort value, TransferFlags flag) { TS_URB_CONTROL_VENDOR_OR_CLASS_REQUEST req = new TS_URB_CONTROL_VENDOR_OR_CLASS_REQUEST( this.requestId, this.noAck, URB_FUNCTIONID.URB_FUNCTION_VENDOR_DEVICE ); req.Header.Size = 8 + 4 + 1 + 1 + 2 + 2 + 2; req.TransferFlags = (uint)flag; req.RequestTypeReservedBits = 0; req.Request = request; req.Value = value; req.Index = 0; req.Padding = 0;// PaddingGenerator.GeneratePadding(); return req; } /// <summary> /// Overloaded method to build a partial vendor command request. /// </summary> /// <returns>The partial vendor command request.</returns> public TS_URB_CONTROL_VENDOR_OR_CLASS_REQUEST BuildVendorCommandRequest() { return BuildVendorCommandRequest(0, 0, TransferFlags.USBD_TRANSFER_DIRECTION_OUT); } /// <summary> /// Builds a request to receive data on a bulk pipe, or receive data on an interrupt pipe. /// </summary> /// <param name="endpoints">All information of the pipes to be searched.</param> /// <param name="endpointNumber">The endpoint number.</param> /// <param name="flag">The endpoint flag.</param> /// <param name="type">The type of the endpoint.</param> /// <returns>The request containing the pipe handle found to receive data on a bulk pipe, or receive data on an interrupt pipe.</returns> public TS_URB_BULK_OR_INTERRUPT_TRANSFER BuildInterruptTransferRequest(TS_USBD_PIPE_INFORMATION_RESULT[] endpoints, byte endpointNumber, TransferFlags flag, USBD_PIPE_TYPE type) { if (((flag & TransferFlags.USBD_TRANSFER_DIRECTION_IN) != TransferFlags.USBD_TRANSFER_DIRECTION_IN) && ((flag & TransferFlags.USBD_TRANSFER_DIRECTION_OUT) != TransferFlags.USBD_TRANSFER_DIRECTION_OUT)) { throw new ArgumentException("flag must contain the direction flag."); } TS_URB_BULK_OR_INTERRUPT_TRANSFER req = new TS_URB_BULK_OR_INTERRUPT_TRANSFER( this.requestId, this.noAck ); req.Header.URB_Function = this.function; req.Header.Size = 8 + 4 + 4; req.TransferFlags = (uint)flag; bool found = false; // Looking for the correct pipe handle. foreach (TS_USBD_PIPE_INFORMATION_RESULT e in endpoints) { byte num = (byte)(e.EndpointAddress & 0x0F); if (num == endpointNumber) { VerifyEndpointDirection(e.EndpointAddress, flag); VerifyType(e.PipeType, type); req.PipeHandle = e.PipeHandle; found = true; break; } } if (!found) { throw new ArgumentException(String.Format("Specified endpoint ({0}) cannot be found.", endpointNumber)); } return req; } /// <summary> /// Builds a request to clear a stall condition on an endpoint. /// </summary> /// <param name="pipeHandle">Specifies an opaque handle to the bulk or interrupt pipe.</param> /// <returns></returns> public TS_URB_PIPE_REQUEST BuildPipeRequest(uint pipeHandle) { TS_URB_PIPE_REQUEST req = new TS_URB_PIPE_REQUEST( this.requestId, this.noAck, this.function); req.Header.Size = 8 + 4; req.PipeHandle = pipeHandle; return req; } /// <summary> /// Builds a request to retrieve the current alternate interface setting for an interface in the current configuration. /// </summary> /// <param name="interfaceIndex">Specifies the device-defined index of the interface descriptor being retrieved.</param> /// <returns>The request to retrieve the current alternate interface setting.</returns> public TS_URB_CONTROL_GET_INTERFACE_REQUEST BuildGetInterfaceRequest(ushort interfaceIndex) { TS_URB_CONTROL_GET_INTERFACE_REQUEST req = new TS_URB_CONTROL_GET_INTERFACE_REQUEST( this.requestId, 0); req.Interface = interfaceIndex; req.Padding = PaddingGenerator.GeneratePadding(); return req; } /// <summary> /// Builds a request to retrieve Microsoft OS Feature Descriptors from a USB device or an interface on a USB device. /// </summary> /// <param name="recipient">Specifies whether the recipient is the USB device or an interface on the USB device.</param> /// <param name="interfaceNumber">Indicates the interface number that is the recipient of the request, if the Recipient member value is 1. Must be set to 0 if the USB device is the recipient.</param> /// <param name="msPageIndex">Must be set to 0. Page index of the 64K page of the MS OS Feature Descriptor to be returned. Current implementation only supports a maximum descriptor size of 4K.</param> /// <param name="msFeatureDescriptorIndex">Index for MS OS Feature Descriptor to be requested.</param> /// <returns>The request to retrieve Microsoft OS Feature Descriptors from a USB device or an interface on a USB device.</returns> public TS_URB_OS_FEATURE_DESCRIPTOR_REQUEST BuildOSFeatureDescriptor(Recipient recipient, byte interfaceNumber, byte msPageIndex, ushort msFeatureDescriptorIndex) { TS_URB_OS_FEATURE_DESCRIPTOR_REQUEST req = new TS_URB_OS_FEATURE_DESCRIPTOR_REQUEST( this.requestId, this.noAck ); req.Recipient = (byte)recipient; req.InterfaceNumber = recipient == Recipient.Interface ? (byte)interfaceNumber : (byte)0; req.MS_PageIndex = msPageIndex; req.MS_FeatureDescriptorIndex = msFeatureDescriptorIndex; return req; } #endregion #region Private Methods private void VerifyEndpointDirection(byte endpointAddress, TransferFlags expectedFlag) { // Verify direction bool isFlagDirIn = (expectedFlag & TransferFlags.USBD_TRANSFER_DIRECTION_IN) == TransferFlags.USBD_TRANSFER_DIRECTION_IN; bool isEndpointDirIn = (endpointAddress >> 7) == 1; if (isFlagDirIn != isEndpointDirIn) { throw new ArgumentException(String.Format( "flag is not consistent to endpoint direction. flag: {0}, Endpoint: {1}.", expectedFlag, isEndpointDirIn ? "In" : "Out" )); } } private void VerifyType(uint pipeType, USBD_PIPE_TYPE expectedType) { if ((USBD_PIPE_TYPE)pipeType != expectedType) { throw new ArgumentException(String.Format( "type is not consistent to endpoint type. type: {0}, Endpoint: {1}.", (USBD_PIPE_TYPE)pipeType, expectedType )); } } #endregion } /// <summary> /// Used to parse a structure instance from a buffer. /// </summary> public class UsbStructParser { /// <summary> /// Parses the structure instance from an EusbUrbCompletionPdu object. /// </summary> /// <typeparam name="T">The type of the structure</typeparam> /// <param name="pdu">The an EusbUrbCompletionPdu object containing the buffer to be parsed</param> /// <returns>The structure instance.</returns> public static T Parse<T>(EusbUrbCompletionPdu pdu) where T : UsbStructure, new() { if (null == pdu.OutputBuffer || pdu.OutputBufferSize <= 0 || pdu.HResult != (uint)HRESULT_FROM_WIN32.ERROR_SUCCESS) { return default(T); } T us = new T(); if (!PduMarshaler.Unmarshal(pdu.OutputBuffer, us)) { return default(T); } return us; } } /// <summary> /// The parser used to parse the result of USB configuration. /// </summary> public class UsbConfigurationParser { #region Private Members private List<TS_USBD_INTERFACE_INFORMATION> interfaces = new List<TS_USBD_INTERFACE_INFORMATION>(); private MemoryStream ms = null; // BUGBUG: Check if this is still valid. // In Windows XP, Windows Server 2003 and later operating system, the MaximumTransferSize member of // the USBD_PIPE_INFORMATION structure is obsolete. private const uint USBD_DEFAULT_MAXIMUM_TRANSFER_SIZE = uint.MaxValue; #endregion #region Public Members /// <summary> /// The parsed TS_USBD_INTERFACE_INFORMATION result. /// </summary> public TS_USBD_INTERFACE_INFORMATION[] Interfaces { get { return interfaces.ToArray(); } } /// <summary> /// The parsed USB_CONFIGURATION_DESCRIPTOR result. /// </summary> public byte[] configDescriptor { get; private set; } /// <summary> /// Parses all information of the configuration result. /// </summary> /// <param name="pdu">The EusbUrbCompletionPdu to be parsed.</param> /// <returns>true indicates successful.</returns> public bool ParseAll(EusbUrbCompletionPdu pdu) { if (pdu.OutputBuffer == null) { return false; } ms = new MemoryStream(pdu.OutputBuffer); USB_CONFIGURATION_DESCRIPTOR cd = UsbStructParser.Parse<USB_CONFIGURATION_DESCRIPTOR>(pdu); ms.Seek(USB_CONFIGURATION_DESCRIPTOR.DefaultSize, SeekOrigin.Begin); if (ms.Length != cd.wTotalLength) { return false; } configDescriptor = pdu.OutputBuffer; USB_INTERFACE_DESCRIPTOR interfaceDes = (USB_INTERFACE_DESCRIPTOR)GetNextDescriptor(UsbDescriptorTypes.USB_INTERFACE_DESCRIPTOR_TYPE); while (null != interfaceDes) { TS_USBD_INTERFACE_INFORMATION interfaceInfo = new TS_USBD_INTERFACE_INFORMATION(); interfaceInfo.NumberOfPipesExpected = interfaceDes.bNumEndpoints; interfaceInfo.InterfaceNumber = interfaceDes.bInterfaceNumber; interfaceInfo.AlternateSetting = interfaceDes.bAlternateSetting; // Padding can be set to any value and MUST be ignored upon receipt. interfaceInfo.Padding = PaddingGenerator.GeneratePadding(); GeneratePipeInformation(interfaceDes, interfaceInfo); interfaces.Add(interfaceInfo); interfaceDes = (USB_INTERFACE_DESCRIPTOR)GetNextDescriptor(UsbDescriptorTypes.USB_INTERFACE_DESCRIPTOR_TYPE); } return true; } #endregion #region Private Methods private void GeneratePipeInformation(USB_INTERFACE_DESCRIPTOR interfaceDes, TS_USBD_INTERFACE_INFORMATION interfaceInfo) { uint pipeCount = interfaceDes.bNumEndpoints; interfaceInfo.NumberOfPipes = pipeCount; interfaceInfo.Infomations = new TS_USBD_PIPE_INFORMATION[pipeCount]; ushort lenExpectPipeInfo = 2 + 2 + 1 + 1 + 2 + 4; interfaceInfo.Length = (ushort)(lenExpectPipeInfo + pipeCount * (2 + 2 + 4 + 4)); for (int i = 0; i < pipeCount; i++) { interfaceInfo.Infomations[i] = new TS_USBD_PIPE_INFORMATION(); // TODO: // In Windows XP, Windows Server 2003 and later operating system, Alt settings for an interface or restrict the maximum packet size by setting // MaximumPacketSize to some value less than or equal to the value of of wMaxPacketSize defined in device firmware for the current Alt settings. interfaceInfo.Infomations[i].MaximumPacketSize = 0; interfaceInfo.Infomations[i].Padding = PaddingGenerator.GeneratePadding(); // In Windows XP, Windows Server 2003 and later operating system, the MaximumTransferSize member of the USBD_PIPE_INFORMATION structure is obsolete. interfaceInfo.Infomations[i].MaximumTransferSize = USBD_DEFAULT_MAXIMUM_TRANSFER_SIZE; interfaceInfo.Infomations[i].PipeFlags = 0; } } private UsbDescriptorStructure GetNextDescriptor(UsbDescriptorTypes descriptorType) { byte[] temp = new byte[2]; UsbDescriptorStructure result = null; while (ms.Position < ms.Length - 2) { if (2 != ms.Read(temp, 0, 2)) { return null; } UsbDescriptorStructure des = new UsbDescriptorStructure(); PduMarshaler.Unmarshal(temp, des); if (des.bDescriptorType == descriptorType) { ms.Seek(-2, SeekOrigin.Current); switch (des.bDescriptorType) { case UsbDescriptorTypes.USB_INTERFACE_DESCRIPTOR_TYPE: result = new USB_INTERFACE_DESCRIPTOR(); if (ParseDescriptor(USB_INTERFACE_DESCRIPTOR.DefaultSize, result)) { return result; } break; default: throw new NotImplementedException(); //break; } } else { ms.Seek(des.bLength - 1, SeekOrigin.Current); } } return result; } private bool ParseDescriptor(int length, UsbDescriptorStructure des) { byte[] temp = new byte[length]; if(length != ms.Read(temp, 0, length)) { return false; } return PduMarshaler.Unmarshal(temp, des); } #endregion } /// <summary> /// Test helper class used to generate a unique unsigned integer ID. /// </summary> public static class IdGenerator { private static uint NextId = 0; /// <summary> /// Generates a new ID. /// </summary> /// <returns>Next avaliable ID.</returns> public static uint NewId() { if (NextId == uint.MaxValue) { NextId = 0; return uint.MaxValue; } return NextId++; } } /// <summary> /// Test helper class used to generate random paddings. /// </summary> public static class PaddingGenerator { /// <summary> /// Generates randmon ushort padding. /// </summary> /// <returns>Padding</returns> public static ushort GeneratePadding() { return (ushort)(new Random().Next()); } /// <summary> /// Generates random byte array padding /// </summary> /// <param name="length">The length of the padding buffer.</param> /// <returns>Padding</returns> public static byte[] GeneratePadding(int length) { byte[] p = new byte[length]; new Random().NextBytes(p); return p; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Text.RegularExpressions; using NDesk.Options; using Sep.Git.Tfs.Core; using StructureMap; namespace Sep.Git.Tfs.Commands { [Pluggable("init")] [Description("init [options] tfs-url-or-instance-name repository-path [git-repository]")] public class Init : GitTfsCommand { private readonly InitOptions initOptions; private readonly RemoteOptions remoteOptions; private readonly Globals globals; private readonly TextWriter output; private readonly IGitHelpers gitHelper; private readonly IHelpHelper _help; public Init(RemoteOptions remoteOptions, InitOptions initOptions, Globals globals, TextWriter output, IGitHelpers gitHelper, IHelpHelper help) { this.remoteOptions = remoteOptions; this.gitHelper = gitHelper; _help = help; this.output = output; this.globals = globals; this.initOptions = initOptions; } public OptionSet OptionSet { get { return initOptions.OptionSet.Merge(remoteOptions.OptionSet); } } public bool IsBare { get { return initOptions.IsBare; } } public IGitHelpers GitHelper { get { return gitHelper; } } public int Run(string tfsUrl, string tfsRepositoryPath) { tfsRepositoryPath.AssertValidTfsPathOrRoot(); DoGitInitDb(); GitTfsInit(tfsUrl, tfsRepositoryPath); return 0; } public int Run(string tfsUrl, string tfsRepositoryPath, string gitRepositoryPath) { tfsRepositoryPath.AssertValidTfsPathOrRoot(); if (!initOptions.IsBare) { InitSubdir(gitRepositoryPath); } else { Environment.CurrentDirectory = gitRepositoryPath; globals.GitDir = "."; } var runResult = Run(tfsUrl, tfsRepositoryPath); try { File.WriteAllText(@".git\description", tfsRepositoryPath + "\n" + HideUserCredentials(globals.CommandLineRun)); } catch (Exception) { Trace.WriteLine("warning: Unable to update de repository description!"); } return runResult; } public static string HideUserCredentials(string commandLineRun) { Regex rgx = new Regex("(--username|-u)[= ][^ ]+"); commandLineRun = rgx.Replace(commandLineRun, "--username=xxx"); rgx = new Regex("(--password|-p)[= ][^ ]+"); return rgx.Replace(commandLineRun, "--password=xxx"); } private void InitSubdir(string repositoryPath) { if(!Directory.Exists(repositoryPath)) Directory.CreateDirectory(repositoryPath); Environment.CurrentDirectory = repositoryPath; globals.GitDir = ".git"; } private void DoGitInitDb() { if(!Directory.Exists(globals.GitDir) || initOptions.IsBare) { gitHelper.CommandNoisy(BuildInitCommand()); } globals.Repository = gitHelper.MakeRepository(globals.GitDir); if (!string.IsNullOrWhiteSpace(initOptions.WorkspacePath)) { Trace.WriteLine("workspace path:" + initOptions.WorkspacePath); try { var dir = Directory.CreateDirectory(initOptions.WorkspacePath); globals.Repository.SetConfig(GitTfsConstants.WorkspaceConfigKey, initOptions.WorkspacePath); } catch (Exception) { throw new GitTfsException("error: workspace path is invalid!"); } } globals.Repository.SetConfig(GitTfsConstants.IgnoreBranches, false.ToString()); } private string[] BuildInitCommand() { var initCommand = new List<string> {"init"}; if(initOptions.GitInitTemplate!= null) initCommand.Add("--template=" + initOptions.GitInitTemplate); if(initOptions.IsBare) initCommand.Add("--bare"); if(initOptions.GitInitShared is string) initCommand.Add("--shared=" + initOptions.GitInitShared); else if(initOptions.GitInitShared != null) initCommand.Add("--shared"); return initCommand.ToArray(); } private void GitTfsInit(string tfsUrl, string tfsRepositoryPath) { globals.Repository.CreateTfsRemote(new RemoteInfo { Id = globals.RemoteId, Url = tfsUrl, Repository = tfsRepositoryPath, RemoteOptions = remoteOptions, },initOptions.GitInitAutoCrlf,initOptions.GitInitIgnoreCase); } } public static class Ext { private static Regex ValidTfsPath = new Regex("^\\$/.+"); public static bool IsValidTfsPath(this string tfsPath) { return ValidTfsPath.IsMatch(tfsPath); } public static void AssertValidTfsPathOrRoot(this string tfsPath) { if (tfsPath == GitTfsConstants.TfsRoot) return; AssertValidTfsPath(tfsPath); } public static void AssertValidTfsPath(this string tfsPath) { if (!ValidTfsPath.IsMatch(tfsPath)) throw new GitTfsException("TFS repository can not be root and must start with \"$/\".", SuggestPaths(tfsPath)); } private static IEnumerable<string> SuggestPaths(string tfsPath) { if (tfsPath == "$" || tfsPath == "$/") yield return "Cloning an entire TFS repository is not supported. Try using a subdirectory of the root (e.g. $/MyProject)."; else if (tfsPath.StartsWith("$")) yield return "Try using $/" + tfsPath.Substring(1); else yield return "Try using $/" + tfsPath; } public static string ToGitRefName(this string expectedRefName) { expectedRefName = System.Text.RegularExpressions.Regex.Replace(expectedRefName, @"[!~$?[*^: \\]", string.Empty); expectedRefName = expectedRefName.Replace("@{", string.Empty); expectedRefName = expectedRefName.Replace("..", string.Empty); expectedRefName = expectedRefName.Replace("//", string.Empty); expectedRefName = expectedRefName.Replace("/.", "/"); expectedRefName = expectedRefName.TrimEnd('.', '/'); return expectedRefName.Trim('/'); } public static string ToGitBranchNameFromTfsRepositoryPath(this string tfsRepositoryPath, bool includeTeamProjectName = false) { if (includeTeamProjectName) { return tfsRepositoryPath .Replace("$/", String.Empty) .ToGitRefName(); } string gitBranchNameExpected = tfsRepositoryPath.IndexOf("$/") == 0 ? tfsRepositoryPath.Remove(0, tfsRepositoryPath.IndexOf('/', 2) + 1) : tfsRepositoryPath; return gitBranchNameExpected.ToGitRefName(); } public static string ToTfsTeamProjectRepositoryPath(this string tfsRepositoryPath) { if (!tfsRepositoryPath.StartsWith("$/")) { return tfsRepositoryPath; } var index = tfsRepositoryPath.IndexOf('/', 2); if (index == -1) { return tfsRepositoryPath; } return tfsRepositoryPath.Remove(index, tfsRepositoryPath.Length - index); } public static string ToLocalGitRef(this string refName) { return "refs/heads/" + refName; } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// User interaction: +1. /// </summary> public class UserPlusOnes_Core : TypeCore, IUserInteraction { public UserPlusOnes_Core() { this._TypeId = 281; this._Id = "UserPlusOnes"; this._Schema_Org_Url = "http://schema.org/UserPlusOnes"; string label = ""; GetLabel(out label, "UserPlusOnes", typeof(UserPlusOnes_Core)); this._Label = label; this._Ancestors = new int[]{266,98,277}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{277}; this._Properties = new int[]{67,108,143,229,19,71,82,130,151,158,214,216,218}; } /// <summary> /// A person attending the event. /// </summary> private Attendees_Core attendees; public Attendees_Core Attendees { get { return attendees; } set { attendees = value; SetPropertyInstance(attendees); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// The duration of the item (movie, audio recording, event, etc.) in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>. /// </summary> private Properties.Duration_Core duration; public Properties.Duration_Core Duration { get { return duration; } set { duration = value; SetPropertyInstance(duration); } } /// <summary> /// The end date and time of the event (in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>). /// </summary> private EndDate_Core endDate; public EndDate_Core EndDate { get { return endDate; } set { endDate = value; SetPropertyInstance(endDate); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// An offer to sell this item\u2014for example, an offer to sell a product, the DVD of a movie, or tickets to an event. /// </summary> private Offers_Core offers; public Offers_Core Offers { get { return offers; } set { offers = value; SetPropertyInstance(offers); } } /// <summary> /// The main performer or performers of the event\u2014for example, a presenter, musician, or actor. /// </summary> private Performers_Core performers; public Performers_Core Performers { get { return performers; } set { performers = value; SetPropertyInstance(performers); } } /// <summary> /// The start date and time of the event (in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>). /// </summary> private StartDate_Core startDate; public StartDate_Core StartDate { get { return startDate; } set { startDate = value; SetPropertyInstance(startDate); } } /// <summary> /// Events that are a part of this event. For example, a conference event includes many presentations, each are subEvents of the conference. /// </summary> private SubEvents_Core subEvents; public SubEvents_Core SubEvents { get { return subEvents; } set { subEvents = value; SetPropertyInstance(subEvents); } } /// <summary> /// An event that this event is a part of. For example, a collection of individual music performances might each have a music festival as their superEvent. /// </summary> private SuperEvent_Core superEvent; public SuperEvent_Core SuperEvent { get { return superEvent; } set { superEvent = value; SetPropertyInstance(superEvent); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DataLake.Store { using Azure; using DataLake; using Management; using Azure; using Management; using DataLake; using Models; using Newtonsoft.Json; using Rest; using Rest.Azure; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// TrustedIdProvidersOperations operations. /// </summary> internal partial class TrustedIdProvidersOperations : IServiceOperations<DataLakeStoreAccountManagementClient>, ITrustedIdProvidersOperations { /// <summary> /// Initializes a new instance of the TrustedIdProvidersOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal TrustedIdProvidersOperations(DataLakeStoreAccountManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the DataLakeStoreAccountManagementClient /// </summary> public DataLakeStoreAccountManagementClient Client { get; private set; } /// <summary> /// Creates or updates the specified trusted identity provider. During update, /// the trusted identity provider with the specified name will be replaced with /// this new provider /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account to which to add the trusted /// identity provider. /// </param> /// <param name='trustedIdProviderName'> /// The name of the trusted identity provider. This is used for differentiation /// of providers in the account. /// </param> /// <param name='parameters'> /// Parameters supplied to create the create the trusted identity provider. /// </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<TrustedIdProvider>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string accountName, string trustedIdProviderName, TrustedIdProvider parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (trustedIdProviderName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "trustedIdProviderName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("accountName", accountName); tracingParameters.Add("trustedIdProviderName", trustedIdProviderName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", 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.DataLakeStore/accounts/{accountName}/trustedIdProviders/{trustedIdProviderName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{trustedIdProviderName}", System.Uri.EscapeDataString(trustedIdProviderName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.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<TrustedIdProvider>(); _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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<TrustedIdProvider>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified trusted identity provider from the specified Data /// Lake Store account /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to delete the trusted /// identity provider. /// </param> /// <param name='trustedIdProviderName'> /// The name of the trusted identity provider to delete. /// </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> DeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, string trustedIdProviderName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (trustedIdProviderName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "trustedIdProviderName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("accountName", accountName); tracingParameters.Add("trustedIdProviderName", trustedIdProviderName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", 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.DataLakeStore/accounts/{accountName}/trustedIdProviders/{trustedIdProviderName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{trustedIdProviderName}", System.Uri.EscapeDataString(trustedIdProviderName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("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 != 200 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } 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> /// Gets the specified Data Lake Store trusted identity provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to get the trusted /// identity provider. /// </param> /// <param name='trustedIdProviderName'> /// The name of the trusted identity provider to retrieve. /// </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<TrustedIdProvider>> GetWithHttpMessagesAsync(string resourceGroupName, string accountName, string trustedIdProviderName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (trustedIdProviderName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "trustedIdProviderName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("accountName", accountName); tracingParameters.Add("trustedIdProviderName", trustedIdProviderName); 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.DataLakeStore/accounts/{accountName}/trustedIdProviders/{trustedIdProviderName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{trustedIdProviderName}", System.Uri.EscapeDataString(trustedIdProviderName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.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<TrustedIdProvider>(); _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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<TrustedIdProvider>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists the Data Lake Store trusted identity providers within the specified /// Data Lake Store account. /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to get the trusted /// identity providers. /// </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<TrustedIdProvider>>> ListByAccountWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("accountName", accountName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByAccount", 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.DataLakeStore/accounts/{accountName}/trustedIdProviders").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.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<TrustedIdProvider>>(); _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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<TrustedIdProvider>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists the Data Lake Store trusted identity providers within the specified /// Data Lake Store account. /// </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<TrustedIdProvider>>> ListByAccountNextWithHttpMessagesAsync(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, "ListByAccountNext", 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 System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.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<TrustedIdProvider>>(); _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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<TrustedIdProvider>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
#pragma warning disable 0168 using System; using System.Collections.Generic; using System.Linq; using nHydrate.Dsl; namespace nHydrate.DslPackage { public static class Extensions { public static Microsoft.VisualStudio.Modeling.Diagrams.ShapeElement GetEntity(this Microsoft.VisualStudio.Modeling.Diagrams.Diagram diagram, string entityName) { foreach (var item in diagram.NestedChildShapes) { if (item.ModelElement is Entity) { var e = item.ModelElement as Entity; if (e != null && e.Name == entityName) return item; } } return null; } public static string GetCorePropertiesHash(this IEnumerable<nHydrate.DataImport.Field> list) { var sortedList = new SortedDictionary<string, nHydrate.DataImport.Field>(); foreach (var c in list.OrderBy(x => x.Name)) { sortedList.Add(c.Name + "-" + c.ID, c); } var hash = string.Empty; foreach (var key in sortedList.Keys) { var c = sortedList[key]; hash += c.CorePropertiesHash; } return hash; } public static string GetCorePropertiesHash(this EntityHasEntities relation) { try { var prehash = relation.SourceEntity.Name.ToLower() + "|" + relation.TargetEntity.Name.ToLower() + " | "; var columnList = relation.FieldMapList().Where(x => x.GetTargetField(relation) != null && x.GetSourceField(relation) != null).ToList(); columnList = columnList.OrderBy(x => x.GetTargetField(relation).Name.ToLower()).ToList(); prehash += string.Join("-|-", columnList.Select(x => x.GetTargetField(relation).Name.ToLower())) + "~"; prehash += string.Join("-|-", columnList.Select(x => x.GetSourceField(relation).Name.ToLower())) + "~"; return prehash; } catch (Exception ex) { throw; } } public static List<T> ToList<T>(this System.Collections.IList l) { var retval = new List<T>(); foreach (T o in l) { retval.Add(o); } return retval; } /// <summary> /// Get all nodes recursively /// </summary> public static List<System.Windows.Forms.TreeNode> GetAllNodes(this System.Windows.Forms.TreeNodeCollection l) { var retval = new List<System.Windows.Forms.TreeNode>(); foreach (System.Windows.Forms.TreeNode o in l) { retval.Add(o); retval.AddRange(GetAllNodes(o.Nodes)); } return retval; } public static void CleanUp(this nHydrate.DataImport.Database database) { foreach (var item in database.EntityList) { foreach (var field in item.FieldList) { //Length var dt = (DataTypeConstants)Enum.Parse(typeof(DataTypeConstants), field.DataType.ToString()); var l = dt.GetPredefinedSize(); if (l != -1) field.Length = l; //Scale l = dt.GetPredefinedScale(); if (l != -1) field.Scale = l; } } } public static void SetupIdMap(this nHydrate.DataImport.Database database, nHydrate.DataImport.Database master) { //Entities foreach (var item in database.EntityList) { var o = master.EntityList.FirstOrDefault(x => x.Name == item.Name); if (o != null) { item.ID = o.ID; foreach (var f in item.FieldList) { var f2 = o.FieldList.FirstOrDefault(x => x.Name == f.Name); if (f2 != null) f.ID = f2.ID; } } } //Views foreach (var item in database.ViewList) { var o = master.ViewList.FirstOrDefault(x => x.Name == item.Name); if (o != null) item.ID = o.ID; } } #region GetChangedText public static string GetChangedText(this nHydrate.DataImport.Field item, nHydrate.DataImport.Field target) { var retval = string.Empty; if (item.DataType != target.DataType) retval += "DataType: " + item.DataType + "->" + target.DataType + "\r\n"; if (item.DefaultValue != target.DefaultValue) retval += "DefaultValue: " + item.DefaultValue + "->" + target.DefaultValue + "\r\n"; if (item.Identity != target.Identity) retval += "Identity: " + item.Identity + "->" + target.Identity + "\r\n"; if (item.IsBrowsable != target.IsBrowsable) retval += "IsBrowsable: " + item.IsBrowsable + "->" + target.IsBrowsable + "\r\n"; if (item.IsIndexed != target.IsIndexed) retval += "IsIndexed: " + item.IsIndexed + "->" + target.IsIndexed + "\r\n"; if (item.IsReadOnly != target.IsReadOnly) retval += "IsReadOnly: " + item.IsReadOnly + "->" + target.IsReadOnly + "\r\n"; if (item.Length != target.Length) retval += "Length: " + item.Length + "->" + target.Length + "\r\n"; if (item.Nullable != target.Nullable) retval += "Nullable: " + item.Nullable + "->" + target.Nullable + "\r\n"; if (item.PrimaryKey != target.PrimaryKey) retval += "PrimaryKey: " + item.PrimaryKey + "->" + target.PrimaryKey + "\r\n"; if (item.Scale != target.Scale) retval += "Scale: " + item.Scale + "->" + target.Scale + "\r\n"; if (item.Name != target.Name) retval += "Name: " + item.Name + "->" + target.Name + "\r\n"; return retval; } public static string GetChangedText(this nHydrate.DataImport.Entity item, nHydrate.DataImport.Entity target) { var retval = string.Empty; #region Fields var addedFields = target.FieldList.Where(x => !item.FieldList.Select(z => z.Name).Contains(x.Name)).ToList(); var deletedFields = item.FieldList.Where(x => !target.FieldList.Select(z => z.Name).Contains(x.Name)).ToList(); var commonFields = item.FieldList.Where(x => target.FieldList.Select(z => z.Name).Contains(x.Name)).ToList(); if (addedFields.Count > 0) { retval += "\r\nAdded fields: " + string.Join(", ", addedFields.Select(x => x.Name).OrderBy(x => x).ToList()) + "\r\n"; } if (deletedFields.Count > 0) { retval += "\r\nDeleted fields: " + string.Join(", ", deletedFields.Select(x => x.Name).OrderBy(x => x).ToList()) + "\r\n"; } foreach (var field in commonFields) { var t = field.GetChangedText(target.FieldList.FirstOrDefault(x => x.Name == field.Name)); if (!string.IsNullOrEmpty(t)) retval += "Changed field (" + field.Name + ")\r\n" + t + "\r\n"; } #endregion return retval; } public static string GetChangedText(this nHydrate.DataImport.View item, nHydrate.DataImport.View target) { var retval = string.Empty; if (item.Name != target.Name) retval += "Name: " + item.Name + "->" + target.Name + "\r\n"; if (item.Schema != target.Schema) retval += "Schema: " + item.Schema + "->" + target.Schema + "\r\n"; if (item.SQL != target.SQL) retval += "Original SQL\r\n" + item.SQL + "\r\n\r\nNew SQL\r\n" + target.SQL + "\r\n"; #region Fields var addedFields = target.FieldList.Where(x => !item.FieldList.Select(z => z.Name).Contains(x.Name)).ToList(); var deletedFields = item.FieldList.Where(x => !target.FieldList.Select(z => z.Name).Contains(x.Name)).ToList(); var commonFields = item.FieldList.Where(x => target.FieldList.Select(z => z.Name).Contains(x.Name)).ToList(); if (addedFields.Count > 0) { retval += "\r\nAdded fields: " + string.Join(", ", addedFields.Select(x => x.Name).OrderBy(x => x).ToList()) + "\r\n"; } if (deletedFields.Count > 0) { retval += "\r\nDeleted fields: " + string.Join(", ", deletedFields.Select(x => x.Name).OrderBy(x => x).ToList()) + "\r\n"; } foreach (var field in commonFields) { var t = field.GetChangedText(target.FieldList.FirstOrDefault(x => x.Name == field.Name)); if (!string.IsNullOrEmpty(t)) retval += "Changed field (" + field.Name + ")\r\n" + t + "\r\n"; } #endregion return retval; } public static string GetChangedText(this nHydrate.DataImport.DatabaseBaseObject item, nHydrate.DataImport.DatabaseBaseObject target) { if (item is nHydrate.DataImport.Entity) return ((nHydrate.DataImport.Entity)item).GetChangedText((nHydrate.DataImport.Entity)target); if (item is nHydrate.DataImport.View) return ((nHydrate.DataImport.View)item).GetChangedText((nHydrate.DataImport.View)target); if (item is nHydrate.DataImport.Field) return ((nHydrate.DataImport.Field)item).GetChangedText((nHydrate.DataImport.Field)target); return string.Empty; } #endregion public static string ToElapsedTimeString(double seconds) { var h = (int)(seconds / 3600); seconds %= 3600; var m = (int)(seconds / 60); seconds %= 60; var retval = string.Empty; if (h > 0) retval += h.ToString("00") + ":"; retval += m.ToString("00") + ":"; retval += seconds.ToString("00"); return retval; } public static List<System.Windows.Forms.ListViewItem> ToList(this System.Windows.Forms.ListView.SelectedListViewItemCollection list) { var retval = new List<System.Windows.Forms.ListViewItem>(); foreach (System.Windows.Forms.ListViewItem item in list) { retval.Add(item); } return retval; } public static List<System.Windows.Forms.ListViewItem> ToList(this System.Windows.Forms.ListView.ListViewItemCollection list) { var retval = new List<System.Windows.Forms.ListViewItem>(); foreach (System.Windows.Forms.ListViewItem item in list) { retval.Add(item); } return retval; } public static bool IsMatch(this DataImport.Index index, Index other) { var validColumnList = other.IndexColumns.Where(x => x.GetField() != null).ToList(); if (index.FieldList.Count != validColumnList.Count) return false; for (var ii = 0; ii < index.FieldList.Count; ii++) { var q = index.FieldList[ii]; var w = validColumnList[ii]; if (w.GetField().Name != q.Name || w.Ascending == q.IsDescending) { return false; } } return true; } public static nHydrate.DataImport.SQLObject ToDatabaseObject(this Entity item) { var retval = new DataImport.Entity(); retval.Name = item.Name; retval.Schema = item.Schema; retval.AllowCreateAudit = item.AllowCreateAudit; retval.AllowModifyAudit = item.AllowModifyAudit; retval.AllowTimestamp = item.AllowTimestamp; retval.IsTenant = item.IsTenant; //Fields foreach (var f in item.Fields) { retval.FieldList.Add(new nHydrate.DataImport.Field() { DataType = (System.Data.SqlDbType)Enum.Parse(typeof(System.Data.SqlDbType), f.DataType.ToString(), true), DefaultValue = f.Default, Identity = (f.Identity == IdentityTypeConstants.Database), IsIndexed = f.IsIndexed, IsUnique = f.IsUnique, Length = f.Length, Name = f.Name, Nullable = f.Nullable, PrimaryKey = f.IsPrimaryKey, Scale = f.Scale, SortOrder = f.SortOrder, }); } return retval; } public static nHydrate.DataImport.SQLObject ToDatabaseObject(this View item) { var retval = new DataImport.View(); retval.Name = item.Name; retval.Schema = item.Schema; retval.SQL = item.SQL; //Fields foreach (var f in item.Fields) { retval.FieldList.Add(new nHydrate.DataImport.Field() { DataType = (System.Data.SqlDbType)Enum.Parse(typeof(System.Data.SqlDbType), f.DataType.ToString(), true), DefaultValue = f.Default, Length = f.Length, Name = f.Name, Nullable = f.Nullable, Scale = f.Scale, }); } return retval; } public static List<T> ToList<T>(this System.Collections.ICollection list) { var retval = new List<T>(); foreach (T item in list) { retval.Add(item); } return retval; } public static string ToXml(object obj) { using (var writer = new System.IO.StringWriter()) { var settings = new System.Xml.XmlWriterSettings(); settings.OmitXmlDeclaration = true; settings.Indent = true; settings.IndentChars = "\t"; var xmlWriter = System.Xml.XmlWriter.Create(writer, settings); var ns = new System.Xml.Serialization.XmlSerializerNamespaces(); ns.Add(string.Empty, "http://www.w3.org/2001/XMLSchema-instance"); ns.Add(string.Empty, "http://www.w3.org/2001/XMLSchema"); var serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType()); serializer.Serialize(xmlWriter, obj, ns); return writer.ToString(); } } public static T FromXml<T>(string xml) where T : class, new() { if (string.IsNullOrEmpty(xml)) return new T(); var reader = new System.IO.StringReader(xml); var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T)); var xmlReader = new System.Xml.XmlTextReader(reader); return serializer.Deserialize(xmlReader) as T; } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace OmniSharp.Intellisense { static class SemanticModelExtensions { public static IEnumerable<ITypeSymbol> LookupTypeRegardlessOfArity( this SemanticModel semanticModel, SyntaxToken name, CancellationToken cancellationToken) { var expression = name.Parent as ExpressionSyntax; if (expression != null) { var results = semanticModel.LookupName(expression, namespacesAndTypesOnly: true, cancellationToken: cancellationToken); if (results.Length > 0) { return results.OfType<ITypeSymbol>(); } } return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } public static ImmutableArray<ISymbol> LookupName( this SemanticModel semanticModel, SyntaxToken name, bool namespacesAndTypesOnly, CancellationToken cancellationToken) { var expression = name.Parent as ExpressionSyntax; if (expression != null) { return semanticModel.LookupName(expression, namespacesAndTypesOnly, cancellationToken); } return ImmutableArray.Create<ISymbol>(); } /// <summary> /// Decomposes a name or member access expression into its component parts. /// </summary> /// <param name="expression">The name or member access expression.</param> /// <param name="qualifier">The qualifier (or left-hand-side) of the name expression. This may be null if there is no qualifier.</param> /// <param name="name">The name of the expression.</param> /// <param name="arity">The number of generic type parameters.</param> private static void DecomposeName(ExpressionSyntax expression, out ExpressionSyntax qualifier, out string name, out int arity) { switch (expression.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: var max = (MemberAccessExpressionSyntax)expression; qualifier = max.Expression; name = max.Name.Identifier.ValueText; arity = max.Name.Arity; break; case SyntaxKind.QualifiedName: var qn = (QualifiedNameSyntax)expression; qualifier = qn.Left; name = qn.Right.Identifier.ValueText; arity = qn.Arity; break; case SyntaxKind.AliasQualifiedName: var aq = (AliasQualifiedNameSyntax)expression; qualifier = aq.Alias; name = aq.Name.Identifier.ValueText; arity = aq.Name.Arity; break; case SyntaxKind.GenericName: var gx = (GenericNameSyntax)expression; qualifier = null; name = gx.Identifier.ValueText; arity = gx.Arity; break; case SyntaxKind.IdentifierName: var nx = (IdentifierNameSyntax)expression; qualifier = null; name = nx.Identifier.ValueText; arity = 0; break; default: qualifier = null; name = null; arity = 0; break; } } public static ImmutableArray<ISymbol> LookupName( this SemanticModel semanticModel, ExpressionSyntax expression, bool namespacesAndTypesOnly, CancellationToken cancellationToken) { var expr = SyntaxFactory.GetStandaloneExpression(expression); ExpressionSyntax qualifier; string name; int arity; DecomposeName(expr, out qualifier, out name, out arity); INamespaceOrTypeSymbol symbol = null; if (qualifier != null) { var typeInfo = semanticModel.GetTypeInfo(qualifier, cancellationToken); var symbolInfo = semanticModel.GetSymbolInfo(qualifier, cancellationToken); if (typeInfo.Type != null) { symbol = typeInfo.Type; } else if (symbolInfo.Symbol != null) { symbol = symbolInfo.Symbol as INamespaceOrTypeSymbol; } } return semanticModel.LookupSymbols(expr.SpanStart, container: symbol, name: name, includeReducedExtensionMethods: true); } public static SymbolInfo GetSymbolInfo(this SemanticModel semanticModel, SyntaxToken token) { if (!CanBindToken(token)) { return default(SymbolInfo); } var expression = token.Parent as ExpressionSyntax; if (expression != null) { return semanticModel.GetSymbolInfo(expression); } var attribute = token.Parent as AttributeSyntax; if (attribute != null) { return semanticModel.GetSymbolInfo(attribute); } var constructorInitializer = token.Parent as ConstructorInitializerSyntax; if (constructorInitializer != null) { return semanticModel.GetSymbolInfo(constructorInitializer); } return default(SymbolInfo); } private static bool CanBindToken(SyntaxToken token) { // Add more token kinds if necessary; switch (token.Kind()) { case SyntaxKind.CommaToken: case SyntaxKind.DelegateKeyword: return false; } return true; } /// <summary> /// Given an argument node, tries to generate an appropriate name that can be used for that /// argument. /// </summary> public static string GenerateNameForArgument( this SemanticModel semanticModel, ArgumentSyntax argument) { // If it named argument then we use the name provided. if (argument.NameColon != null) { return argument.NameColon.Name.Identifier.ValueText; } return semanticModel.GenerateNameForExpression(argument.Expression); } public static string GenerateNameForArgument( this SemanticModel semanticModel, AttributeArgumentSyntax argument) { // If it named argument then we use the name provided. if (argument.NameEquals != null) { return argument.NameEquals.Name.Identifier.ValueText; } return semanticModel.GenerateNameForExpression(argument.Expression); } /// <summary> /// Given an expression node, tries to generate an appropriate name that can be used for /// that expression. /// </summary> public static string GenerateNameForExpression( this SemanticModel semanticModel, ExpressionSyntax expression, bool capitalize = false) { // Try to find a usable name node that we can use to name the // parameter. If we have an expression that has a name as part of it // then we try to use that part. var current = expression; while (true) { current = current.WalkDownParentheses(); if (current.Kind() == SyntaxKind.IdentifierName) { return ((IdentifierNameSyntax)current).Identifier.ValueText.ToCamelCase(); } else if (current is MemberAccessExpressionSyntax) { return ((MemberAccessExpressionSyntax)current).Name.Identifier.ValueText.ToCamelCase(); } else if (current is MemberBindingExpressionSyntax) { return ((MemberBindingExpressionSyntax)current).Name.Identifier.ValueText.ToCamelCase(); } else if (current is ConditionalAccessExpressionSyntax) { current = ((ConditionalAccessExpressionSyntax)current).WhenNotNull; } else if (current is CastExpressionSyntax) { current = ((CastExpressionSyntax)current).Expression; } else { break; } } // Otherwise, figure out the type of the expression and generate a name from that // isntead. var info = semanticModel.GetTypeInfo(expression); // If we can't determine the type, then fallback to some placeholders. var type = info.Type; return type.CreateParameterName(capitalize); } public static IList<string> GenerateParameterNames( this SemanticModel semanticModel, ArgumentListSyntax argumentList) { return semanticModel.GenerateParameterNames(argumentList.Arguments); } public static IList<string> GenerateParameterNames( this SemanticModel semanticModel, AttributeArgumentListSyntax argumentList) { return semanticModel.GenerateParameterNames(argumentList.Arguments); } public static IList<string> GenerateParameterNames( this SemanticModel semanticModel, IEnumerable<ArgumentSyntax> arguments, IList<string> reservedNames = null) { reservedNames = reservedNames ?? SpecializedCollections.EmptyList<string>(); // We can't change the names of named parameters. Any other names we're flexible on. var isFixed = reservedNames.Select(s => true).Concat( arguments.Select(a => a.NameColon != null)).ToList(); var parameterNames = reservedNames.Concat( arguments.Select(a => semanticModel.GenerateNameForArgument(a))).ToList(); return NameGenerator.EnsureUniqueness(parameterNames, isFixed).Skip(reservedNames.Count).ToList(); } public static IList<string> GenerateParameterNames( this SemanticModel semanticModel, IEnumerable<AttributeArgumentSyntax> arguments, IList<string> reservedNames = null) { reservedNames = reservedNames ?? SpecializedCollections.EmptyList<string>(); // We can't change the names of named parameters. Any other names we're flexible on. var isFixed = reservedNames.Select(s => true).Concat( arguments.Select(a => a.NameEquals != null)).ToList(); var parameterNames = reservedNames.Concat( arguments.Select(a => semanticModel.GenerateNameForArgument(a))).ToList(); return NameGenerator.EnsureUniqueness(parameterNames, isFixed).Skip(reservedNames.Count).ToList(); } public static ISet<INamespaceSymbol> GetUsingNamespacesInScope(this SemanticModel semanticModel, SyntaxNode location) { // Avoiding linq here for perf reasons. This is used heavily in the AddImport service HashSet<INamespaceSymbol> result = null; foreach (var @using in location.GetEnclosingUsingDirectives()) { if (@using.Alias == null) { var symbolInfo = semanticModel.GetSymbolInfo(@using.Name); if (symbolInfo.Symbol != null && symbolInfo.Symbol.Kind == SymbolKind.Namespace) { result = result ?? new HashSet<INamespaceSymbol>(); result.Add((INamespaceSymbol)symbolInfo.Symbol); } } } return result ?? SpecializedCollections.EmptySet<INamespaceSymbol>(); } public static Accessibility DetermineAccessibilityConstraint( this SemanticModel semanticModel, TypeSyntax type, CancellationToken cancellationToken) { if (type == null) { return Accessibility.Private; } type = GetOutermostType(type); // Interesting cases based on 3.5.4 Accessibility constraints in the language spec. // If any of the below hold, then we will override the default accessibility if the // constraint wants the type to be more accessible. i.e. if by default we generate // 'internal', but a constraint makes us 'public', then be public. // 1) The direct base class of a class type must be at least as accessible as the // class type itself. // // 2) The explicit base interfaces of an interface type must be at least as accessible // as the interface type itself. if (type != null) { if (type.Parent is BaseTypeSyntax && type.Parent.IsParentKind(SyntaxKind.BaseList) && ((BaseTypeSyntax)type.Parent).Type == type) { var containingType = semanticModel.GetDeclaredSymbol(type.GetAncestor<BaseTypeDeclarationSyntax>(), cancellationToken) as INamedTypeSymbol; if (containingType != null && containingType.TypeKind == TypeKind.Interface) { return containingType.DeclaredAccessibility; } else if (((BaseListSyntax)type.Parent.Parent).Types[0] == type.Parent) { return containingType.DeclaredAccessibility; } } } // 4) The type of a constant must be at least as accessible as the constant itself. // 5) The type of a field must be at least as accessible as the field itself. if (type.IsParentKind(SyntaxKind.VariableDeclaration) && type.Parent.IsParentKind(SyntaxKind.FieldDeclaration)) { var variableDeclaration = (VariableDeclarationSyntax)type.Parent; return ((ISymbol)semanticModel.GetDeclaredSymbol( variableDeclaration.Variables[0], cancellationToken)).DeclaredAccessibility; } // 3) The return type of a delegate type must be at least as accessible as the // delegate type itself. // 6) The return type of a method must be at least as accessible as the method // itself. // 7) The type of a property must be at least as accessible as the property itself. // 8) The type of an event must be at least as accessible as the event itself. // 9) The type of an indexer must be at least as accessible as the indexer itself. // 10) The return type of an operator must be at least as accessible as the operator // itself. if (type.IsParentKind(SyntaxKind.DelegateDeclaration) || type.IsParentKind(SyntaxKind.MethodDeclaration) || type.IsParentKind(SyntaxKind.PropertyDeclaration) || type.IsParentKind(SyntaxKind.EventDeclaration) || type.IsParentKind(SyntaxKind.IndexerDeclaration) || type.IsParentKind(SyntaxKind.OperatorDeclaration)) { return semanticModel.GetDeclaredSymbol( type.Parent, cancellationToken).DeclaredAccessibility; } // 3) The parameter types of a delegate type must be at least as accessible as the // delegate type itself. // 6) The parameter types of a method must be at least as accessible as the method // itself. // 9) The parameter types of an indexer must be at least as accessible as the // indexer itself. // 10) The parameter types of an operator must be at least as accessible as the // operator itself. // 11) The parameter types of an instance constructor must be at least as accessible // as the instance constructor itself. if (type.IsParentKind(SyntaxKind.Parameter) && type.Parent.IsParentKind(SyntaxKind.ParameterList)) { if (type.Parent.Parent.IsParentKind(SyntaxKind.DelegateDeclaration) || type.Parent.Parent.IsParentKind(SyntaxKind.MethodDeclaration) || type.Parent.Parent.IsParentKind(SyntaxKind.IndexerDeclaration) || type.Parent.Parent.IsParentKind(SyntaxKind.OperatorDeclaration)) { return semanticModel.GetDeclaredSymbol( type.Parent.Parent.Parent, cancellationToken).DeclaredAccessibility; } if (type.Parent.Parent.IsParentKind(SyntaxKind.ConstructorDeclaration)) { var symbol = semanticModel.GetDeclaredSymbol(type.Parent.Parent.Parent, cancellationToken); if (!symbol.IsStatic) { return symbol.DeclaredAccessibility; } } } // 8) The type of an event must be at least as accessible as the event itself. if (type.IsParentKind(SyntaxKind.VariableDeclaration) && type.Parent.IsParentKind(SyntaxKind.EventFieldDeclaration)) { var variableDeclaration = (VariableDeclarationSyntax)type.Parent; var symbol = semanticModel.GetDeclaredSymbol(variableDeclaration.Variables[0], cancellationToken); if (symbol != null) { return ((ISymbol)symbol).DeclaredAccessibility; } } return Accessibility.Private; } private static TypeSyntax GetOutermostType(TypeSyntax type) { return type.GetAncestorsOrThis<TypeSyntax>().Last(); } public static SemanticMap GetSemanticMap(this SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) { return SemanticMap.From(semanticModel, node, cancellationToken); } /// <summary> /// Gets semantic information, such as type, symbols, and diagnostics, about the parent of a token. /// </summary> /// <param name="semanticModel">The SemanticModel object to get semantic information /// from.</param> /// <param name="token">The token to get semantic information from. This must be part of the /// syntax tree associated with the binding.</param> /// <param name="cancellationToken">A cancellation token.</param> public static SymbolInfo GetSymbolInfo(this SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken) { return semanticModel.GetSymbolInfo(token.Parent, cancellationToken); } public static TSymbol GetEnclosingSymbol<TSymbol>(this SemanticModel semanticModel, int position, CancellationToken cancellationToken) where TSymbol : ISymbol { for (var symbol = semanticModel.GetEnclosingSymbol(position, cancellationToken); symbol != null; symbol = symbol.ContainingSymbol) { if (symbol is TSymbol) { return (TSymbol)symbol; } } return default(TSymbol); } public static ISymbol GetEnclosingNamedTypeOrAssembly(this SemanticModel semanticModel, int position, CancellationToken cancellationToken) { return semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(position, cancellationToken) ?? (ISymbol)semanticModel.Compilation.Assembly; } public static INamedTypeSymbol GetEnclosingNamedType(this SemanticModel semanticModel, int position, CancellationToken cancellationToken) { return semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(position, cancellationToken); } public static INamespaceSymbol GetEnclosingNamespace(this SemanticModel semanticModel, int position, CancellationToken cancellationToken) { return semanticModel.GetEnclosingSymbol<INamespaceSymbol>(position, cancellationToken); } public static ITypeSymbol GetType( this SemanticModel semanticModel, SyntaxNode expression, CancellationToken cancellationToken) { var typeInfo = semanticModel.GetTypeInfo(expression, cancellationToken); var symbolInfo = semanticModel.GetSymbolInfo(expression, cancellationToken); return typeInfo.Type ?? symbolInfo.GetAnySymbol().ConvertToType(semanticModel.Compilation); } // public static IEnumerable<ISymbol> GetSymbols( // this SemanticModel semanticModel, // SyntaxToken token, // Workspace workspace, // bool bindLiteralsToUnderlyingType, // CancellationToken cancellationToken) // { // var languageServices = workspace.Services.GetLanguageServices(token.Language); // var syntaxFacts = languageServices.GetService<ISyntaxFactsService>(); // if (!syntaxFacts.IsBindableToken(token)) // { // return SpecializedCollections.EmptyEnumerable<ISymbol>(); // } // // var semanticFacts = languageServices.GetService<ISemanticFactsService>(); // // return GetSymbolsEnumerable( // semanticModel, semanticFacts, syntaxFacts, // token, bindLiteralsToUnderlyingType, cancellationToken) // .WhereNotNull() // .Select(MapSymbol); // } private static ISymbol MapSymbol(ISymbol symbol) { return symbol.IsConstructor() && symbol.ContainingType.IsAnonymousType ? symbol.ContainingType : symbol; } // private static IEnumerable<ISymbol> GetSymbolsEnumerable( // SemanticModel semanticModel, // ISemanticFactsService semanticFacts, // ISyntaxFactsService syntaxFacts, // SyntaxToken token, // bool bindLiteralsToUnderlyingType, // CancellationToken cancellationToken) // { // var declaredSymbol = semanticFacts.GetDeclaredSymbol(semanticModel, token, cancellationToken); // if (declaredSymbol != null) // { // yield return declaredSymbol; // yield break; // } // // var aliasInfo = semanticModel.GetAliasInfo(token.Parent, cancellationToken); // if (aliasInfo != null) // { // yield return aliasInfo; // } // // var bindableParent = syntaxFacts.GetBindableParent(token); // var allSymbols = semanticModel.GetSymbolInfo(bindableParent, cancellationToken).GetBestOrAllSymbols().ToList(); // var type = semanticModel.GetTypeInfo(bindableParent, cancellationToken).Type; // // if (type != null && allSymbols.Count == 0) // { // if ((bindLiteralsToUnderlyingType && syntaxFacts.IsLiteral(token)) || // syntaxFacts.IsAwaitKeyword(token)) // { // yield return type; // } // // if (type.Kind == SymbolKind.NamedType) // { // var namedType = (INamedTypeSymbol)type; // if (namedType.TypeKind == TypeKind.Delegate || // namedType.AssociatedSymbol != null) // { // yield return type; // } // } // } // // foreach (var symbol in allSymbols) // { // if (symbol.IsThisParameter() && type != null) // { // yield return type; // } // else if (symbol.IsFunctionValue()) // { // var method = symbol.ContainingSymbol as IMethodSymbol; // // if (method != null) // { // if (method.AssociatedSymbol != null) // { // yield return method.AssociatedSymbol; // } // else // { // yield return method; // } // } // else // { // yield return symbol; // } // } // else // { // yield return symbol; // } // } // } public static SemanticModel GetOriginalSemanticModel(this SemanticModel semanticModel) { if (!semanticModel.IsSpeculativeSemanticModel) { return semanticModel; } // Contract.ThrowIfNull(semanticModel.ParentModel); // Contract.ThrowIfTrue(semanticModel.ParentModel.IsSpeculativeSemanticModel); // Contract.ThrowIfTrue(semanticModel.ParentModel.ParentModel != null); return semanticModel.ParentModel; } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // TaskRunSync.cs // // // Test class using UnitTestDriver that ensures that the Runsynchronously method works as excepted // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using Xunit; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Security; using System.Threading; using System.Threading.Tasks; using System.Diagnostics; namespace System.Threading.Tasks.Tests { #region Helper Classes / Enums public enum PreTaskStatus { Created, // task has been created Continued, // task is a continuation task Running, // task has started running, could be waiting-to-run in the queue Canceled, // task has been canceled before running Completed, // task has been completed } public enum PostRunSyncAction { Wait, //to test you can wait on a task that was run synchronously Cancel, //to test you can cancel the token that was used by the task ContinueWith, //to test you can continuewith on a task that was run synchronously } public enum WorkloadType { CreateChildTask, //Start a attached childTask in the workload CreateDetachedChildTask, //start a detached childTask in the workload ContinueInside, //Invoke continuewith as the workload inside the task RunWithUserScheduler, //create a task with custom task scheduler that runs that task inline ThrowException, //throw an exception } public enum TaskSchedulerType { Default, //Use the default taskscheduler TaskScheduler.Current Null, //pass null as the Task Scheduler CustomWithInlineExecution, //Use a custom TaskScheduler that runs the Task inline CustomWithoutInlineExecution //Use a custom TaskScheduler that does not run the Task inline } /// <summary> /// An implementation of TaskScheduler that is able to perform RunSynchronously, and /// keep track of number of times Task was executed synchronously /// </summary> public class TaskRunSyncTaskScheduler : TaskScheduler, IDisposable { public bool AbleToExecuteInline { get; set; } public int RunSyncCalledCount { get; set; } private Task[] _threads; private BlockingCollection<Task> _tasks = new BlockingCollection<Task>(); public TaskRunSyncTaskScheduler(bool ableToExecuteInline) { AbleToExecuteInline = ableToExecuteInline; /*need at least two threads since we might schedule two tasks (parent-child)*/ int numberOfThreads = Math.Max(Environment.ProcessorCount, 2); _threads = new Task[numberOfThreads]; for (int i = 0; i < numberOfThreads; i++) { _threads[i] = Task.Run(() => { foreach (var task in _tasks.GetConsumingEnumerable()) { if (task.Status == TaskStatus.WaitingToRun) { ExecuteTask(task); } } }); } } [SecuritySafeCritical] private bool ExecuteTask(Task task) { return TryExecuteTask(task); } [SecurityCritical] protected override void QueueTask(Task task) { _tasks.Add(task); } public override int MaximumConcurrencyLevel { get { return _threads.Length; } } [SecurityCritical] protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { RunSyncCalledCount++; if (taskWasPreviouslyQueued) { return false; } if (AbleToExecuteInline) { return ExecuteTask(task); } else { return false; } } [SecurityCritical] protected override IEnumerable<Task> GetScheduledTasks() { return _tasks; } public void Dispose() { if (_threads != null) { _tasks.CompleteAdding(); Task task; while (_tasks.TryTake(out task)) ; Task.WaitAll(_threads); _threads = null; } } } public class TestParameters_RunSync { public readonly PreTaskStatus PreTaskStatus; public readonly PostRunSyncAction PostRunSyncAction; public readonly WorkloadType WorkloadType; public readonly TaskCreationOptions TaskCreationOptions; public readonly TaskSchedulerType TaskSchedulerType; public TestParameters_RunSync(PreTaskStatus preTaskStatus, PostRunSyncAction postRunSyncAction, WorkloadType workType, TaskCreationOptions taskCreationOptions, TaskSchedulerType taskScheduler) { PreTaskStatus = preTaskStatus; PostRunSyncAction = postRunSyncAction; WorkloadType = workType; TaskCreationOptions = taskCreationOptions; TaskSchedulerType = taskScheduler; } } #endregion public sealed class TaskRunSyncTest { private PreTaskStatus _preTaskStatus; private PostRunSyncAction _postRunSyncAction; private WorkloadType _workloadType; private TaskCreationOptions _option; private TaskSchedulerType _taskSchedulerType; private Task _task; // the main task to be run synchronously private CancellationTokenSource _cts; // The CancellationTokenSource of which the Token is apssed to the Main task private int _taskThreadID; public TaskRunSyncTest(TestParameters_RunSync parameters) { _preTaskStatus = parameters.PreTaskStatus; _postRunSyncAction = parameters.PostRunSyncAction; _workloadType = parameters.WorkloadType; _option = parameters.TaskCreationOptions; _taskSchedulerType = parameters.TaskSchedulerType; } /// <summary> /// The main test method that execute the API. There are five steps involved in the execution of the test /// </summary> internal void RealRun() { TaskScheduler ts = TaskScheduler.Default; switch (_taskSchedulerType) { case TaskSchedulerType.Null: ts = null; break; case TaskSchedulerType.CustomWithInlineExecution: ts = new TaskRunSyncTaskScheduler(true); break; case TaskSchedulerType.CustomWithoutInlineExecution: ts = new TaskRunSyncTaskScheduler(false); break; default: ts = TaskScheduler.Default; break; } // Stage 1 -- create task CreateTask(); // Stage 2 - start with the pre-action switch (_preTaskStatus) { case PreTaskStatus.Continued: _task = _task.ContinueWith((t) => { }, _cts.Token, TaskContinuationOptions.None, ts); break; case PreTaskStatus.Running: _task.Start(ts); break; case PreTaskStatus.Canceled: _cts.Cancel(); break; case PreTaskStatus.Completed: _task.Start(ts); ((IAsyncResult)_task).AsyncWaitHandle.WaitOne(); // wait on AsyncWaitHandle to avoid getting exp break; } int expectedThreadID = Environment.CurrentManagedThreadId; // Stage 3 - exercise the API try { if (_taskSchedulerType == TaskSchedulerType.Default) _task.RunSynchronously(); else _task.RunSynchronously(ts); if (ExpectRunSyncFailure) Assert.True(false, string.Format("Fail to throw expected InvalidOperationException")); if (_taskSchedulerType == TaskSchedulerType.Null) Assert.True(false, string.Format("Fail to throw expected ArgumentNullException")); } catch (InvalidOperationException ex) { if (!ExpectRunSyncFailure) Assert.True(false, string.Format("Caught un-expected InvalidOperationException - {0}", ex)); else { Debug.WriteLine("Caught expected InvalidOperationException"); DisposeScheduler(ts); return; } } catch (ArgumentNullException ex) { if (_taskSchedulerType != TaskSchedulerType.Null) Assert.True(false, string.Format("Caught un-expected ArgumentNullException - {0}", ex)); else { Debug.WriteLine("Caught expected ArgumentNullException"); DisposeScheduler(ts); return; } } // Stage 4 - do verification against Context, IsCompleted and the TaskStatus if (_taskSchedulerType == TaskSchedulerType.CustomWithInlineExecution) Assert.Equal(expectedThreadID, _taskThreadID); else if (_taskSchedulerType == TaskSchedulerType.CustomWithoutInlineExecution) Assert.NotEqual(expectedThreadID, _taskThreadID); else if (_taskThreadID != expectedThreadID) Debug.WriteLine("Warning: RunSynchronously request ignored -- Task did not run under the same context"); Assert.True(_task.IsCompleted, "RunSynchronously contract broken -- Task is not complete when the call return"); if (_workloadType == WorkloadType.ThrowException) { if (_task.Status != TaskStatus.Faulted) Assert.True(false, string.Format("Wrong final task status on a faulty workload")); CheckExpectedAggregateException(_task.Exception); //Assert.True(false, string.Format("Fail to record the test exception in Task.Exception")); } else { if (_task.Status != TaskStatus.RanToCompletion) Assert.True(false, string.Format("Wrong final task status on a regular workload")); } // // Extra verification to ensure the Task was RunSynchronously on // specified TaskScheduler // if (_taskSchedulerType == TaskSchedulerType.CustomWithInlineExecution || _taskSchedulerType == TaskSchedulerType.CustomWithoutInlineExecution) { if (((TaskRunSyncTaskScheduler)ts).RunSyncCalledCount <= 0) Assert.True(false, string.Format("Task wasn't RunSynchronously with TaskScheduler specified")); } // Stage 5 - follow with the post-action switch (_postRunSyncAction) { case PostRunSyncAction.Wait: try { if (_postRunSyncAction == PostRunSyncAction.Wait) _task.Wait(0); if (_workloadType == WorkloadType.ThrowException) Assert.True(false, string.Format("expected failure is not propogated out of Wait")); } catch (AggregateException ae) { CheckExpectedAggregateException(ae); } break; case PostRunSyncAction.Cancel: _cts.Cancel(); break; case PostRunSyncAction.ContinueWith: _task.ContinueWith((t) => { }).Wait(); break; } DisposeScheduler(ts); } private static void DisposeScheduler(TaskScheduler ts) { if (ts is TaskRunSyncTaskScheduler) { ((TaskRunSyncTaskScheduler)ts).Dispose(); } } private void CreateTask() { _cts = new CancellationTokenSource(); _task = new Task((o) => { _taskThreadID = Environment.CurrentManagedThreadId; switch (_workloadType) { case WorkloadType.CreateChildTask: case WorkloadType.CreateDetachedChildTask: Task.Factory.StartNew(() => { }, _workloadType == WorkloadType.CreateDetachedChildTask ? TaskCreationOptions.None : TaskCreationOptions.AttachedToParent); break; case WorkloadType.ContinueInside: _task.ContinueWith((t) => { }); break; case WorkloadType.RunWithUserScheduler: TaskScheduler ts = new TaskRunSyncTaskScheduler(true); Task.Factory.StartNew(() => { }, _cts.Token, TaskCreationOptions.AttachedToParent, ts).ContinueWith((task) => DisposeScheduler(ts), TaskScheduler.Default); break; case WorkloadType.ThrowException: throw new TPLTestException(); } }, null, _cts.Token, _option); } private bool ExpectRunSyncFailure { get { // The following cases will cause an exception // 1. Task already started / canceled / disposed / completed // 2. Task is an contination task return (_preTaskStatus != PreTaskStatus.Created); } } /// <summary> /// Method that checks to ensure that the AggregateException contains TPLException (the one throw by the workload) /// </summary> /// <param name="ae"></param> /// <returns></returns> private void CheckExpectedAggregateException(AggregateException ae) { if (_workloadType == WorkloadType.ThrowException) ae.Flatten().Handle((e) => e is TPLTestException); else Assert.True(false, string.Format("Caught un-expected exception - {0]. Fail to re-progogate the test exception via Wait", ae)); } } public class TaskRunSyncTests { static TaskRunSyncTests() { // Tests that create tasks which need to run concurrently require us to bump up the number // of threads in the pool, or else we need to wait for it to grow dynamically to the desired number ThreadPoolHelpers.EnsureMinThreadsAtLeast(10); } #region Test methods [Fact] public static void TaskRunSyncTest0() { TestParameters_RunSync parameters = new TestParameters_RunSync(PreTaskStatus.Canceled, PostRunSyncAction.Wait, WorkloadType.CreateChildTask, TaskCreationOptions.None, TaskSchedulerType.CustomWithInlineExecution); TaskRunSyncTest test = new TaskRunSyncTest(parameters); test.RealRun(); } [Fact] public static void TaskRunSyncTest1() { TestParameters_RunSync parameters = new TestParameters_RunSync(PreTaskStatus.Canceled, PostRunSyncAction.Wait, WorkloadType.CreateChildTask, TaskCreationOptions.None, TaskSchedulerType.CustomWithoutInlineExecution); TaskRunSyncTest test = new TaskRunSyncTest(parameters); test.RealRun(); } [Fact] public static void TaskRunSyncTest2() { TestParameters_RunSync parameters = new TestParameters_RunSync(PreTaskStatus.Canceled, PostRunSyncAction.Wait, WorkloadType.CreateChildTask, TaskCreationOptions.None, TaskSchedulerType.Default); TaskRunSyncTest test = new TaskRunSyncTest(parameters); test.RealRun(); } [Fact] [OuterLoop] public static void TaskRunSyncTest3() { TestParameters_RunSync parameters = new TestParameters_RunSync(PreTaskStatus.Completed, PostRunSyncAction.Wait, WorkloadType.CreateChildTask, TaskCreationOptions.None, TaskSchedulerType.CustomWithInlineExecution); TaskRunSyncTest test = new TaskRunSyncTest(parameters); test.RealRun(); } [Fact] public static void TaskRunSyncTest4() { TestParameters_RunSync parameters = new TestParameters_RunSync(PreTaskStatus.Completed, PostRunSyncAction.Wait, WorkloadType.CreateChildTask, TaskCreationOptions.None, TaskSchedulerType.CustomWithoutInlineExecution); TaskRunSyncTest test = new TaskRunSyncTest(parameters); test.RealRun(); } [Fact] public static void TaskRunSyncTest5() { TestParameters_RunSync parameters = new TestParameters_RunSync(PreTaskStatus.Completed, PostRunSyncAction.Wait, WorkloadType.CreateChildTask, TaskCreationOptions.None, TaskSchedulerType.Default); TaskRunSyncTest test = new TaskRunSyncTest(parameters); test.RealRun(); } [Fact] public static void TaskRunSyncTest6() { TestParameters_RunSync parameters = new TestParameters_RunSync(PreTaskStatus.Continued, PostRunSyncAction.Wait, WorkloadType.CreateChildTask, TaskCreationOptions.None, TaskSchedulerType.CustomWithInlineExecution); TaskRunSyncTest test = new TaskRunSyncTest(parameters); test.RealRun(); } [Fact] public static void TaskRunSyncTest7() { TestParameters_RunSync parameters = new TestParameters_RunSync(PreTaskStatus.Continued, PostRunSyncAction.Wait, WorkloadType.CreateChildTask, TaskCreationOptions.None, TaskSchedulerType.CustomWithoutInlineExecution); TaskRunSyncTest test = new TaskRunSyncTest(parameters); test.RealRun(); } [Fact] public static void TaskRunSyncTest8() { TestParameters_RunSync parameters = new TestParameters_RunSync(PreTaskStatus.Continued, PostRunSyncAction.Wait, WorkloadType.CreateChildTask, TaskCreationOptions.None, TaskSchedulerType.Default); TaskRunSyncTest test = new TaskRunSyncTest(parameters); test.RealRun(); } [Fact] public static void TaskRunSyncTest9() { TestParameters_RunSync parameters = new TestParameters_RunSync(PreTaskStatus.Created, PostRunSyncAction.Cancel, WorkloadType.ContinueInside, TaskCreationOptions.LongRunning, TaskSchedulerType.Default); TaskRunSyncTest test = new TaskRunSyncTest(parameters); test.RealRun(); } [Fact] public static void TaskRunSyncTest10() { TestParameters_RunSync parameters = new TestParameters_RunSync(PreTaskStatus.Created, PostRunSyncAction.Cancel, WorkloadType.CreateChildTask, TaskCreationOptions.LongRunning, TaskSchedulerType.CustomWithoutInlineExecution); TaskRunSyncTest test = new TaskRunSyncTest(parameters); test.RealRun(); } [Fact] public static void TaskRunSyncTest11() { TestParameters_RunSync parameters = new TestParameters_RunSync(PreTaskStatus.Created, PostRunSyncAction.Cancel, WorkloadType.CreateDetachedChildTask, TaskCreationOptions.AttachedToParent, TaskSchedulerType.CustomWithoutInlineExecution); TaskRunSyncTest test = new TaskRunSyncTest(parameters); test.RealRun(); } [Fact] public static void TaskRunSyncTest12() { TestParameters_RunSync parameters = new TestParameters_RunSync(PreTaskStatus.Created, PostRunSyncAction.Cancel, WorkloadType.CreateDetachedChildTask, TaskCreationOptions.None, TaskSchedulerType.CustomWithInlineExecution); TaskRunSyncTest test = new TaskRunSyncTest(parameters); test.RealRun(); } [Fact] public static void TaskRunSyncTest13() { TestParameters_RunSync parameters = new TestParameters_RunSync(PreTaskStatus.Created, PostRunSyncAction.Cancel, WorkloadType.RunWithUserScheduler, TaskCreationOptions.None, TaskSchedulerType.Default); TaskRunSyncTest test = new TaskRunSyncTest(parameters); test.RealRun(); } [Fact] public static void TaskRunSyncTest14() { TestParameters_RunSync parameters = new TestParameters_RunSync(PreTaskStatus.Created, PostRunSyncAction.Cancel, WorkloadType.ThrowException, TaskCreationOptions.AttachedToParent, TaskSchedulerType.CustomWithInlineExecution); TaskRunSyncTest test = new TaskRunSyncTest(parameters); test.RealRun(); } [Fact] [OuterLoop] public static void TaskRunSyncTest15() { TestParameters_RunSync parameters = new TestParameters_RunSync(PreTaskStatus.Created, PostRunSyncAction.ContinueWith, WorkloadType.ContinueInside, TaskCreationOptions.None, TaskSchedulerType.CustomWithInlineExecution); TaskRunSyncTest test = new TaskRunSyncTest(parameters); test.RealRun(); } [Fact] public static void TaskRunSyncTest16() { TestParameters_RunSync parameters = new TestParameters_RunSync(PreTaskStatus.Created, PostRunSyncAction.ContinueWith, WorkloadType.CreateChildTask, TaskCreationOptions.AttachedToParent, TaskSchedulerType.Default); TaskRunSyncTest test = new TaskRunSyncTest(parameters); test.RealRun(); } [Fact] [OuterLoop] public static void TaskRunSyncTest17() { TestParameters_RunSync parameters = new TestParameters_RunSync(PreTaskStatus.Created, PostRunSyncAction.ContinueWith, WorkloadType.CreateDetachedChildTask, TaskCreationOptions.AttachedToParent, TaskSchedulerType.CustomWithInlineExecution); TaskRunSyncTest test = new TaskRunSyncTest(parameters); test.RealRun(); } [Fact] [OuterLoop] public static void TaskRunSyncTest18() { TestParameters_RunSync parameters = new TestParameters_RunSync(PreTaskStatus.Created, PostRunSyncAction.ContinueWith, WorkloadType.RunWithUserScheduler, TaskCreationOptions.LongRunning, TaskSchedulerType.CustomWithInlineExecution); TaskRunSyncTest test = new TaskRunSyncTest(parameters); test.RealRun(); } [Fact] [OuterLoop] public static void TaskRunSyncTest19() { TestParameters_RunSync parameters = new TestParameters_RunSync(PreTaskStatus.Created, PostRunSyncAction.ContinueWith, WorkloadType.ThrowException, TaskCreationOptions.LongRunning, TaskSchedulerType.CustomWithoutInlineExecution); TaskRunSyncTest test = new TaskRunSyncTest(parameters); test.RealRun(); } [Fact] [OuterLoop] public static void TaskRunSyncTest20() { TestParameters_RunSync parameters = new TestParameters_RunSync(PreTaskStatus.Created, PostRunSyncAction.Wait, WorkloadType.ContinueInside, TaskCreationOptions.AttachedToParent, TaskSchedulerType.CustomWithoutInlineExecution); TaskRunSyncTest test = new TaskRunSyncTest(parameters); test.RealRun(); } [Fact] public static void TaskRunSyncTest21() { TestParameters_RunSync parameters = new TestParameters_RunSync(PreTaskStatus.Created, PostRunSyncAction.Wait, WorkloadType.CreateChildTask, TaskCreationOptions.None, TaskSchedulerType.Null); TaskRunSyncTest test = new TaskRunSyncTest(parameters); test.RealRun(); } [Fact] public static void TaskRunSyncTest22() { TestParameters_RunSync parameters = new TestParameters_RunSync(PreTaskStatus.Created, PostRunSyncAction.Wait, WorkloadType.CreateDetachedChildTask, TaskCreationOptions.LongRunning, TaskSchedulerType.Default); TaskRunSyncTest test = new TaskRunSyncTest(parameters); test.RealRun(); } [Fact] [OuterLoop] public static void TaskRunSyncTest23() { TestParameters_RunSync parameters = new TestParameters_RunSync(PreTaskStatus.Created, PostRunSyncAction.Wait, WorkloadType.RunWithUserScheduler, TaskCreationOptions.AttachedToParent, TaskSchedulerType.CustomWithoutInlineExecution); TaskRunSyncTest test = new TaskRunSyncTest(parameters); test.RealRun(); } [Fact] [OuterLoop] public static void TaskRunSyncTest24() { TestParameters_RunSync parameters = new TestParameters_RunSync(PreTaskStatus.Created, PostRunSyncAction.Wait, WorkloadType.ThrowException, TaskCreationOptions.None, TaskSchedulerType.Default); TaskRunSyncTest test = new TaskRunSyncTest(parameters); test.RealRun(); } [Fact] public static void TaskRunSyncTest28() { TestParameters_RunSync parameters = new TestParameters_RunSync(PreTaskStatus.Running, PostRunSyncAction.Wait, WorkloadType.CreateChildTask, TaskCreationOptions.None, TaskSchedulerType.CustomWithInlineExecution); TaskRunSyncTest test = new TaskRunSyncTest(parameters); test.RealRun(); } [Fact] public static void TaskRunSyncTest29() { TestParameters_RunSync parameters = new TestParameters_RunSync(PreTaskStatus.Running, PostRunSyncAction.Wait, WorkloadType.CreateChildTask, TaskCreationOptions.None, TaskSchedulerType.CustomWithoutInlineExecution); TaskRunSyncTest test = new TaskRunSyncTest(parameters); test.RealRun(); } [Fact] public static void TaskRunSyncTest30() { TestParameters_RunSync parameters = new TestParameters_RunSync(PreTaskStatus.Running, PostRunSyncAction.Wait, WorkloadType.CreateChildTask, TaskCreationOptions.None, TaskSchedulerType.Default); TaskRunSyncTest test = new TaskRunSyncTest(parameters); test.RealRun(); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Net { [System.FlagsAttribute] public enum AuthenticationSchemes { Anonymous = 32768, Basic = 8, Digest = 1, IntegratedWindowsAuthentication = 6, Negotiate = 2, None = 0, Ntlm = 4, } public sealed partial class Cookie { public Cookie() { } public Cookie(string name, string value) { } public Cookie(string name, string value, string path) { } public Cookie(string name, string value, string path, string domain) { } public string Comment { get { throw null; } set { } } public System.Uri CommentUri { get { throw null; } set { } } public bool Discard { get { throw null; } set { } } public string Domain { get { throw null; } set { } } public bool Expired { get { throw null; } set { } } public System.DateTime Expires { get { throw null; } set { } } public bool HttpOnly { get { throw null; } set { } } public string Name { get { throw null; } set { } } public string Path { get { throw null; } set { } } public string Port { get { throw null; } set { } } public bool Secure { get { throw null; } set { } } public System.DateTime TimeStamp { get { throw null; } } public string Value { get { throw null; } set { } } public int Version { get { throw null; } set { } } public override bool Equals(object comparand) { throw null; } public override int GetHashCode() { throw null; } public override string ToString() { throw null; } } public partial class CookieCollection : System.Collections.ICollection, System.Collections.IEnumerable { public CookieCollection() { } public int Count { get { throw null; } } public System.Net.Cookie this[string name] { get { throw null; } } public System.Net.Cookie this[int index] { get { throw null; } } public bool IsSynchronized { get { throw null; } } public object SyncRoot { get { throw null; } } public void Add(System.Net.Cookie cookie) { } public void Add(System.Net.CookieCollection cookies) { } public System.Collections.IEnumerator GetEnumerator() { throw null; } public void CopyTo(System.Array array, int index) { } public void CopyTo(Cookie[] array, int index) { } public bool IsReadOnly { get { throw null; } } } public partial class CookieContainer { public const int DefaultCookieLengthLimit = 4096; public const int DefaultCookieLimit = 300; public const int DefaultPerDomainCookieLimit = 20; public CookieContainer() { } public int Capacity { get { throw null; } set { } } public int Count { get { throw null; } } public int MaxCookieSize { get { throw null; } set { } } public int PerDomainCapacity { get { throw null; } set { } } public void Add(System.Uri uri, System.Net.Cookie cookie) { } public void Add(System.Uri uri, System.Net.CookieCollection cookies) { } public string GetCookieHeader(System.Uri uri) { throw null; } public System.Net.CookieCollection GetCookies(System.Uri uri) { throw null; } public void SetCookies(System.Uri uri, string cookieHeader) { } public CookieContainer(int capacity) { } public CookieContainer(int capacity, int perDomainCapacity, int maxCookieSize) { } public void Add(CookieCollection cookies) { } public void Add(Cookie cookie) { } } public partial class CookieException : System.FormatException, System.Runtime.Serialization.ISerializable { public CookieException() { } protected CookieException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } public override void GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } } public partial class CredentialCache : System.Collections.IEnumerable, System.Net.ICredentials, System.Net.ICredentialsByHost { public CredentialCache() { } public static System.Net.ICredentials DefaultCredentials { get { throw null; } } public static System.Net.NetworkCredential DefaultNetworkCredentials { get { throw null; } } public void Add(string host, int port, string authenticationType, System.Net.NetworkCredential credential) { } public void Add(System.Uri uriPrefix, string authType, System.Net.NetworkCredential cred) { } public System.Net.NetworkCredential GetCredential(string host, int port, string authenticationType) { throw null; } public System.Net.NetworkCredential GetCredential(System.Uri uriPrefix, string authType) { throw null; } public System.Collections.IEnumerator GetEnumerator() { throw null; } public void Remove(string host, int port, string authenticationType) { } public void Remove(System.Uri uriPrefix, string authType) { } } [System.FlagsAttribute] public enum DecompressionMethods { Deflate = 2, GZip = 1, None = 0, } public partial class DnsEndPoint : System.Net.EndPoint { public DnsEndPoint(string host, int port) { } public DnsEndPoint(string host, int port, System.Net.Sockets.AddressFamily addressFamily) { } public override System.Net.Sockets.AddressFamily AddressFamily { get { throw null; } } public string Host { get { throw null; } } public int Port { get { throw null; } } public override bool Equals(object comparand) { throw null; } public override int GetHashCode() { throw null; } public override string ToString() { throw null; } } public abstract partial class EndPoint { protected EndPoint() { } public virtual System.Net.Sockets.AddressFamily AddressFamily { get { throw null; } } public virtual System.Net.EndPoint Create(System.Net.SocketAddress socketAddress) { throw null; } public virtual System.Net.SocketAddress Serialize() { throw null; } } public enum HttpStatusCode { Accepted = 202, AlreadyReported = 208, Ambiguous = 300, BadGateway = 502, BadRequest = 400, Conflict = 409, Continue = 100, Created = 201, EarlyHints = 103, ExpectationFailed = 417, FailedDependency = 424, Forbidden = 403, Found = 302, GatewayTimeout = 504, Gone = 410, HttpVersionNotSupported = 505, IMUsed = 226, InsufficientStorage = 507, InternalServerError = 500, LengthRequired = 411, Locked = 423, LoopDetected = 508, MethodNotAllowed = 405, MisdirectedRequest = 421, Moved = 301, MovedPermanently = 301, MultipleChoices = 300, MultiStatus = 207, NetworkAuthenticationRequired = 511, NoContent = 204, NonAuthoritativeInformation = 203, NotAcceptable = 406, NotExtended = 510, NotFound = 404, NotImplemented = 501, NotModified = 304, OK = 200, PartialContent = 206, PaymentRequired = 402, PermanentRedirect = 308, PreconditionFailed = 412, PreconditionRequired = 428, Processing = 102, ProxyAuthenticationRequired = 407, Redirect = 302, RedirectKeepVerb = 307, RedirectMethod = 303, RequestedRangeNotSatisfiable = 416, RequestEntityTooLarge = 413, RequestHeaderFieldsTooLarge = 431, RequestTimeout = 408, RequestUriTooLong = 414, ResetContent = 205, SeeOther = 303, ServiceUnavailable = 503, SwitchingProtocols = 101, TemporaryRedirect = 307, TooManyRequests = 429, Unauthorized = 401, UnavailableForLegalReasons = 451, UnprocessableEntity = 422, UnsupportedMediaType = 415, Unused = 306, UpgradeRequired = 426, UseProxy = 305, VariantAlsoNegotiates = 506 } public partial interface ICredentials { System.Net.NetworkCredential GetCredential(System.Uri uri, string authType); } public partial interface ICredentialsByHost { System.Net.NetworkCredential GetCredential(string host, int port, string authenticationType); } public partial class IPAddress { public static readonly System.Net.IPAddress Any; public static readonly System.Net.IPAddress Broadcast; public static readonly System.Net.IPAddress IPv6Any; public static readonly System.Net.IPAddress IPv6Loopback; public static readonly System.Net.IPAddress IPv6None; public static readonly System.Net.IPAddress Loopback; public static readonly System.Net.IPAddress None; public IPAddress(byte[] address) { } public IPAddress(ReadOnlySpan<byte> address) { } public IPAddress(byte[] address, long scopeid) { } public IPAddress(ReadOnlySpan<byte> address, long scopeid) { } public IPAddress(long newAddress) { } public System.Net.Sockets.AddressFamily AddressFamily { get { throw null; } } public bool IsIPv4MappedToIPv6 { get { throw null; } } public bool IsIPv6LinkLocal { get { throw null; } } public bool IsIPv6Multicast { get { throw null; } } public bool IsIPv6SiteLocal { get { throw null; } } public bool IsIPv6Teredo { get { throw null; } } public long ScopeId { get { throw null; } set { } } public override bool Equals(object comparand) { throw null; } public byte[] GetAddressBytes() { throw null; } public bool TryWriteBytes(Span<byte> destination, out int bytesWritten) { throw null; } public override int GetHashCode() { throw null; } public static short HostToNetworkOrder(short host) { throw null; } public static int HostToNetworkOrder(int host) { throw null; } public static long HostToNetworkOrder(long host) { throw null; } public static bool IsLoopback(System.Net.IPAddress address) { throw null; } public System.Net.IPAddress MapToIPv4() { throw null; } public System.Net.IPAddress MapToIPv6() { throw null; } public static short NetworkToHostOrder(short network) { throw null; } public static int NetworkToHostOrder(int network) { throw null; } public static long NetworkToHostOrder(long network) { throw null; } public static System.Net.IPAddress Parse(string ipString) { throw null; } public static System.Net.IPAddress Parse(ReadOnlySpan<char> ipString) { throw null; } public override string ToString() { throw null; } public bool TryFormat(Span<char> destination, out int charsWritten) { throw null; } public static bool TryParse(string ipString, out System.Net.IPAddress address) { throw null; } public static bool TryParse(ReadOnlySpan<char> ipString, out System.Net.IPAddress address) { throw null; } [Obsolete("This property has been deprecated. It is address family dependent. Please use IPAddress.Equals method to perform comparisons. http://go.microsoft.com/fwlink/?linkid=14202")] public long Address { get { throw null; } set { } } } public partial class IPEndPoint : System.Net.EndPoint { public const int MaxPort = 65535; public const int MinPort = 0; public IPEndPoint(long address, int port) { } public IPEndPoint(System.Net.IPAddress address, int port) { } public System.Net.IPAddress Address { get { throw null; } set { } } public override System.Net.Sockets.AddressFamily AddressFamily { get { throw null; } } public int Port { get { throw null; } set { } } public override System.Net.EndPoint Create(System.Net.SocketAddress socketAddress) { throw null; } public override bool Equals(object comparand) { throw null; } public override int GetHashCode() { throw null; } public override System.Net.SocketAddress Serialize() { throw null; } public override string ToString() { throw null; } } public partial interface IWebProxy { System.Net.ICredentials Credentials { get; set; } System.Uri GetProxy(System.Uri destination); bool IsBypassed(System.Uri host); } public partial class NetworkCredential : System.Net.ICredentials, System.Net.ICredentialsByHost { public NetworkCredential() { } public NetworkCredential(string userName, string password) { } [System.CLSCompliant(false)] public NetworkCredential(string userName, System.Security.SecureString password) { } public NetworkCredential(string userName, string password, string domain) { } [System.CLSCompliant(false)] public NetworkCredential(string userName, System.Security.SecureString password, string domain) { } public string Domain { get { throw null; } set { } } public string Password { get { throw null; } set { } } [System.CLSCompliant(false)] public System.Security.SecureString SecurePassword { get { throw null; } set { } } public string UserName { get { throw null; } set { } } public System.Net.NetworkCredential GetCredential(string host, int port, string authenticationType) { throw null; } public System.Net.NetworkCredential GetCredential(System.Uri uri, string authType) { throw null; } } public partial class SocketAddress { public SocketAddress(System.Net.Sockets.AddressFamily family) { } public SocketAddress(System.Net.Sockets.AddressFamily family, int size) { } public System.Net.Sockets.AddressFamily Family { get { throw null; } } public byte this[int offset] { get { throw null; } set { } } public int Size { get { throw null; } } public override bool Equals(object comparand) { throw null; } public override int GetHashCode() { throw null; } public override string ToString() { throw null; } } public abstract partial class TransportContext { protected TransportContext() { } public abstract System.Security.Authentication.ExtendedProtection.ChannelBinding GetChannelBinding(System.Security.Authentication.ExtendedProtection.ChannelBindingKind kind); } public static class HttpVersion { public static readonly Version Unknown = new Version(0, 0); public static readonly Version Version10 = new Version(1, 0); public static readonly Version Version11 = new Version(1, 1); public static readonly Version Version20 = new Version(2, 0); } } namespace System.Net.Cache { public enum RequestCacheLevel { Default = 0, BypassCache = 1, CacheOnly = 2, CacheIfAvailable = 3, Revalidate = 4, Reload = 5, NoCacheNoStore = 6 } public class RequestCachePolicy { public RequestCachePolicy() { } public RequestCachePolicy(System.Net.Cache.RequestCacheLevel level) { } public System.Net.Cache.RequestCacheLevel Level { get { throw null; } } public override string ToString() { throw null; } } } namespace System.Net.NetworkInformation { public partial class IPAddressCollection : System.Collections.Generic.ICollection<System.Net.IPAddress>, System.Collections.Generic.IEnumerable<System.Net.IPAddress>, System.Collections.IEnumerable { protected internal IPAddressCollection() { } public virtual int Count { get { throw null; } } public virtual bool IsReadOnly { get { throw null; } } public virtual System.Net.IPAddress this[int index] { get { throw null; } } public virtual void Add(System.Net.IPAddress address) { } public virtual void Clear() { } public virtual bool Contains(System.Net.IPAddress address) { throw null; } public virtual void CopyTo(System.Net.IPAddress[] array, int offset) { } public virtual System.Collections.Generic.IEnumerator<System.Net.IPAddress> GetEnumerator() { throw null; } public virtual bool Remove(System.Net.IPAddress address) { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } } namespace System.Net.Security { public enum AuthenticationLevel { MutualAuthRequested = 1, MutualAuthRequired = 2, None = 0, } [System.FlagsAttribute] public enum SslPolicyErrors { None = 0, RemoteCertificateChainErrors = 4, RemoteCertificateNameMismatch = 2, RemoteCertificateNotAvailable = 1, } } namespace System.Net.Sockets { public enum AddressFamily { AppleTalk = 16, Atm = 22, Banyan = 21, Ccitt = 10, Chaos = 5, Cluster = 24, DataKit = 9, DataLink = 13, DecNet = 12, Ecma = 8, FireFox = 19, HyperChannel = 15, Ieee12844 = 25, ImpLink = 3, InterNetwork = 2, InterNetworkV6 = 23, Ipx = 6, Irda = 26, Iso = 7, Lat = 14, Max = 29, NetBios = 17, NetworkDesigners = 28, NS = 6, Osi = 7, Pup = 4, Sna = 11, Unix = 1, Unknown = -1, Unspecified = 0, VoiceView = 18, } public enum SocketError { AccessDenied = 10013, AddressAlreadyInUse = 10048, AddressFamilyNotSupported = 10047, AddressNotAvailable = 10049, AlreadyInProgress = 10037, ConnectionAborted = 10053, ConnectionRefused = 10061, ConnectionReset = 10054, DestinationAddressRequired = 10039, Disconnecting = 10101, Fault = 10014, HostDown = 10064, HostNotFound = 11001, HostUnreachable = 10065, InProgress = 10036, Interrupted = 10004, InvalidArgument = 10022, IOPending = 997, IsConnected = 10056, MessageSize = 10040, NetworkDown = 10050, NetworkReset = 10052, NetworkUnreachable = 10051, NoBufferSpaceAvailable = 10055, NoData = 11004, NoRecovery = 11003, NotConnected = 10057, NotInitialized = 10093, NotSocket = 10038, OperationAborted = 995, OperationNotSupported = 10045, ProcessLimit = 10067, ProtocolFamilyNotSupported = 10046, ProtocolNotSupported = 10043, ProtocolOption = 10042, ProtocolType = 10041, Shutdown = 10058, SocketError = -1, SocketNotSupported = 10044, Success = 0, SystemNotReady = 10091, TimedOut = 10060, TooManyOpenSockets = 10024, TryAgain = 11002, TypeNotFound = 10109, VersionNotSupported = 10092, WouldBlock = 10035, } public partial class SocketException : System.ComponentModel.Win32Exception { public SocketException() { } public SocketException(int errorCode) { } protected SocketException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } public override int ErrorCode { get { throw null; } } public override string Message { get { throw null; } } public System.Net.Sockets.SocketError SocketErrorCode { get { throw null; } } } } namespace System.Security.Authentication { public enum CipherAlgorithmType { Aes = 26129, Aes128 = 26126, Aes192 = 26127, Aes256 = 26128, Des = 26113, None = 0, Null = 24576, Rc2 = 26114, Rc4 = 26625, TripleDes = 26115, } public enum ExchangeAlgorithmType { DiffieHellman = 43522, None = 0, RsaKeyX = 41984, RsaSign = 9216, } public enum HashAlgorithmType { Md5 = 32771, None = 0, Sha1 = 32772, Sha256 = 32780, Sha384 = 32781, Sha512 = 32782 } [System.FlagsAttribute] public enum SslProtocols { None = 0, [Obsolete("This value has been deprecated. It is no longer supported. http://go.microsoft.com/fwlink/?linkid=14202")] Ssl2 = 12, [Obsolete("This value has been deprecated. It is no longer supported. http://go.microsoft.com/fwlink/?linkid=14202")] Ssl3 = 48, Tls = 192, Tls11 = 768, Tls12 = 3072, [Obsolete("This value has been deprecated. It is no longer supported. http://go.microsoft.com/fwlink/?linkid=14202")] Default = Ssl3 | Tls } } namespace System.Security.Authentication.ExtendedProtection { public abstract partial class ChannelBinding : Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid { protected ChannelBinding() : base(default(bool)) { } protected ChannelBinding(bool ownsHandle) : base(default(bool)) { } public abstract int Size { get; } } public enum ChannelBindingKind { Endpoint = 26, Unique = 25, Unknown = 0, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Net.Security; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; namespace System.Net.Http { internal sealed class ManagedHandler : HttpMessageHandler { private readonly HttpConnectionSettings _settings = new HttpConnectionSettings(); private HttpMessageHandler _handler; private bool _disposed; private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(nameof(ManagedHandler)); } } private void CheckDisposedOrStarted() { CheckDisposed(); if (_handler != null) { throw new InvalidOperationException(SR.net_http_operation_started); } } public bool SupportsAutomaticDecompression => true; public bool SupportsProxy => true; public bool SupportsRedirectConfiguration => true; public bool UseCookies { get => _settings._useCookies; set { CheckDisposedOrStarted(); _settings._useCookies = value; } } public CookieContainer CookieContainer { get => _settings._cookieContainer ?? (_settings._cookieContainer = new CookieContainer()); set { CheckDisposedOrStarted(); _settings._cookieContainer = value; } } public ClientCertificateOption ClientCertificateOptions { get => _settings._clientCertificateOptions; set { if (value != ClientCertificateOption.Manual && value != ClientCertificateOption.Automatic) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _settings._clientCertificateOptions = value; } } public DecompressionMethods AutomaticDecompression { get => _settings._automaticDecompression; set { CheckDisposedOrStarted(); _settings._automaticDecompression = value; } } public bool UseProxy { get => _settings._useProxy; set { CheckDisposedOrStarted(); _settings._useProxy = value; } } public IWebProxy Proxy { get => _settings._proxy; set { CheckDisposedOrStarted(); _settings._proxy = value; } } public ICredentials DefaultProxyCredentials { get => _settings._defaultProxyCredentials; set { CheckDisposedOrStarted(); _settings._defaultProxyCredentials = value; } } public bool PreAuthenticate { get => _settings._preAuthenticate; set { CheckDisposedOrStarted(); _settings._preAuthenticate = value; } } public bool UseDefaultCredentials { get => _settings._useDefaultCredentials; set { CheckDisposedOrStarted(); _settings._useDefaultCredentials = value; } } public ICredentials Credentials { get => _settings._credentials; set { CheckDisposedOrStarted(); _settings._credentials = value; } } public bool AllowAutoRedirect { get => _settings._allowAutoRedirect; set { CheckDisposedOrStarted(); _settings._allowAutoRedirect = value; } } public int MaxAutomaticRedirections { get => _settings._maxAutomaticRedirections; set { if (value < 1) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _settings._maxAutomaticRedirections = value; } } public int MaxConnectionsPerServer { get => _settings._maxConnectionsPerServer; set { if (value < 1) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _settings._maxConnectionsPerServer = value; } } public int MaxResponseHeadersLength { get => _settings._maxResponseHeadersLength; set { if (value <= 0) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _settings._maxResponseHeadersLength = value; } } public X509CertificateCollection ClientCertificates { get { if (_settings._clientCertificateOptions != ClientCertificateOption.Manual) { throw new InvalidOperationException(SR.Format(SR.net_http_invalid_enable_first, nameof(ClientCertificateOptions), nameof(ClientCertificateOption.Manual))); } return _settings._clientCertificates ?? (_settings._clientCertificates = new X509Certificate2Collection()); } } public Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> ServerCertificateCustomValidationCallback { get => _settings._serverCertificateCustomValidationCallback; set { CheckDisposedOrStarted(); _settings._serverCertificateCustomValidationCallback = value; } } public bool CheckCertificateRevocationList { get => _settings._checkCertificateRevocationList; set { CheckDisposedOrStarted(); _settings._checkCertificateRevocationList = value; } } public SslProtocols SslProtocols { get => _settings._sslProtocols; set { SecurityProtocol.ThrowOnNotAllowed(value, allowNone: true); CheckDisposedOrStarted(); _settings._sslProtocols = value; } } public IDictionary<string, object> Properties => _settings._properties ?? (_settings._properties = new Dictionary<string, object>()); protected override void Dispose(bool disposing) { if (disposing && !_disposed) { _disposed = true; _handler?.Dispose(); } base.Dispose(disposing); } private HttpMessageHandler SetupHandlerChain() { HttpMessageHandler handler = new HttpConnectionHandler(_settings); if (_settings._useProxy && (_settings._proxy != null || HttpProxyConnectionHandler.EnvironmentProxyConfigured)) { handler = new HttpProxyConnectionHandler(_settings, handler); } if (_settings._useCookies) { handler = new CookieHandler(CookieContainer, handler); } if (_settings._credentials != null) { handler = new AuthenticationHandler(_settings._preAuthenticate, _settings._credentials, handler); } if (_settings._allowAutoRedirect) { handler = new AutoRedirectHandler(_settings._maxAutomaticRedirections, handler); } if (_settings._automaticDecompression != DecompressionMethods.None) { handler = new DecompressionHandler(_settings._automaticDecompression, handler); } if (Interlocked.CompareExchange(ref _handler, handler, null) == null) { return handler; } else { handler.Dispose(); return _handler; } } protected internal override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { CheckDisposed(); HttpMessageHandler handler = _handler ?? SetupHandlerChain(); return handler.SendAsync(request, cancellationToken); } } }
//----------------------------------------------------------------------- // // Microsoft Windows Client Platform // Copyright (C) Microsoft Corporation, 2002 // // File: FontFamily.cs // // Contents: FontFamily // // Created : 5-25-2003 Worachai Chaoweeraprasit (wchao) // Modified : 8-08-2008 [....] - Integrating with DWrite. // //------------------------------------------------------------------------ using System; using System.Text; using System.IO; using System.Globalization; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Windows; using System.Windows.Markup; // for XmlLanguage using System.ComponentModel; using System.ComponentModel.Design; using MS.Utility; using MS.Internal; using MS.Internal.FontCache; using MS.Internal.FontFace; using MS.Internal.Shaping; using System.Security; using SR = MS.Internal.PresentationCore.SR; using SRID = MS.Internal.PresentationCore.SRID; // Since we disable PreSharp warnings in this file, we first need to disable warnings about unknown message numbers and unknown pragmas. #pragma warning disable 1634, 1691 namespace System.Windows.Media { /// <summary> /// Represents a family of related fonts. Fonts in a FontFamily differ only in style, /// weight, or stretch. /// </summary> [TypeConverter(typeof(FontFamilyConverter))] [ValueSerializer(typeof(FontFamilyValueSerializer))] [Localizability(LocalizationCategory.Font)] public class FontFamily { /// <summary> /// Family name originally passed to by user and information derived from it. /// </summary> private FontFamilyIdentifier _familyIdentifier; /// <summary> /// The first valid font family. If no valid font family can be resolved from /// the given name, this will point to a NullFontFamily object. /// </summary> private IFontFamily _firstFontFamily; /// <summary> /// Null font is the font that has metrics but logically does not support any Unicode codepoint /// so whatever text we throw at it would result in being mapped to missing glyph. /// </summary> internal static readonly CanonicalFontFamilyReference NullFontFamilyCanonicalName = CanonicalFontFamilyReference.Create(null, "#ARIAL"); internal const string GlobalUI = "#GLOBAL USER INTERFACE"; internal static FontFamily FontFamilyGlobalUI = new FontFamily(GlobalUI); private static volatile FamilyCollection _defaultFamilyCollection = PreCreateDefaultFamilyCollection(); private static FontFamilyMapCollection _emptyFamilyMaps = null; /// <summary> /// Constructs FontFamily from a string. /// </summary> /// <param name="familyName">Specifies one or more comma-separated family names, each /// of which may be either a regular family name string (e.g., "Arial") or a URI /// (e.g., "file:///c:/windows/fonts/#Arial").</param> public FontFamily(string familyName) : this(null, familyName) {} /// <summary> /// Constructs FontFamily from a string and an optional base URI. /// </summary> /// <param name="baseUri">Specifies the base URI used to resolve family names, typically /// the URI of the document or element that refers to the font family. Can be null.</param> /// <param name="familyName">Specifies one or more comma-separated family names, each /// of which may be either a regular family name string (e.g., "Arial") or a URI /// (e.g., "file:///c:/windows/fonts/#Arial").</param> public FontFamily(Uri baseUri, string familyName) { if (familyName == null) throw new ArgumentNullException("familyName"); if (baseUri != null && !baseUri.IsAbsoluteUri) throw new ArgumentException(SR.Get(SRID.UriNotAbsolute), "baseUri"); _familyIdentifier = new FontFamilyIdentifier(familyName, baseUri); } internal FontFamily(FontFamilyIdentifier familyIdentifier) { _familyIdentifier = familyIdentifier; } /// <summary> /// Construct an anonymous font family, i.e., a composite font that is created /// programatically instead of referenced by name or URI. /// </summary> public FontFamily() { _familyIdentifier = new FontFamilyIdentifier(null, null); _firstFontFamily = new CompositeFontFamily(); } /// <summary> /// Collection of culture-dependant family names. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public LanguageSpecificStringDictionary FamilyNames { get { CompositeFontFamily compositeFont = FirstFontFamily as CompositeFontFamily; if (compositeFont != null) { // Return the read/write dictionary of family names. return compositeFont.FamilyNames; } else { // Return a wrapper for the cached family's read-only dictionary. return new LanguageSpecificStringDictionary(FirstFontFamily.Names); } } } /// <summary> /// List of FamilyTypeface objects. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public FamilyTypefaceCollection FamilyTypefaces { get { CompositeFontFamily compositeFont = FirstFontFamily as CompositeFontFamily; if (compositeFont != null) { // Return the read/write list of typefaces for the font. return compositeFont.FamilyTypefaces; } else { // Return a wrapper for the read-only collection of typefaces. return new FamilyTypefaceCollection(FirstFontFamily.GetTypefaces(_familyIdentifier)); } } } /// <summary> /// Collection of FontFamilyMap objects for an anonymous font family. For named font /// families, this property returns an empty, read-only list. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public FontFamilyMapCollection FamilyMaps { get { CompositeFontFamily compositeFont = FirstFontFamily as CompositeFontFamily; if (compositeFont != null) { // Read the read/write list of family maps for the font. return compositeFont.FamilyMaps; } else { // Return an empty, read-only collection of FamilyMaps. if (_emptyFamilyMaps == null) { _emptyFamilyMaps = new FontFamilyMapCollection(null); } return _emptyFamilyMaps; } } } /// <summary> /// Family names and/or URIs used to construct the font family. /// </summary> public string Source { get { return _familyIdentifier.Source; } } /// <summary> /// Base URI used to resolve family names, typically the URI of the document or element /// that refers to the font family. /// </summary> /// <remarks> /// Family names are interpreted first relative to the base URI (if not null) and then /// relative to the default folder for installed fonts. /// </remarks> public Uri BaseUri { get { return _familyIdentifier.BaseUri; } } /// <summary> /// Return Source if there is one or String.Empty for unnamed /// font family. /// </summary> public override string ToString() { string source = _familyIdentifier.Source; return source != null ? source : string.Empty; } internal FontFamilyIdentifier FamilyIdentifier { get { return _familyIdentifier; } } /// <summary> /// Distance from character cell top to English baseline relative to em size. /// </summary> public double Baseline { get { return FirstFontFamily.BaselineDesign; } set { VerifyMutable().SetBaseline(value); } } /// <summary> /// Recommended baseline-to-baseline distance for the text in this font relative to em size. /// </summary> public double LineSpacing { get { return FirstFontFamily.LineSpacingDesign; } set { VerifyMutable().SetLineSpacing(value); } } internal double GetLineSpacingForDisplayMode(double emSize) { return FirstFontFamily.LineSpacing(emSize, 1, Util.PixelsPerDip, TextFormattingMode.Display); } /// <summary> /// Font families from the default system font location. /// </summary> /// <value>Collection of FontFamly objects from the default system font location.</value> [CLSCompliant(false)] public ICollection<Typeface> GetTypefaces() { return FirstFontFamily.GetTypefaces(_familyIdentifier); } /// <summary> /// Create correspondent hash code for the object /// </summary> /// <returns>object hash code</returns> public override int GetHashCode() { if (_familyIdentifier.Source != null) { // named font family: hash based on canonical name return _familyIdentifier.GetHashCode(); } else { // unnamed family: hash is based on object identity return base.GetHashCode(); } } /// <summary> /// Equality check /// </summary> public override bool Equals(object o) { FontFamily f = o as FontFamily; if (f == null) { // different types or o == null return false; } else if (_familyIdentifier.Source != null) { // named font family; compare canonical names return _familyIdentifier.Equals(f._familyIdentifier); } else { // unnamed font families are equal only if they're the same instance return base.Equals(o); } } /// <summary> /// Verifies that the FontFamily can be changed and returns a CompositeFontFamily /// </summary> private CompositeFontFamily VerifyMutable() { CompositeFontFamily mutableFamily = _firstFontFamily as CompositeFontFamily; if (mutableFamily == null) { throw new NotSupportedException(SR.Get(SRID.FontFamily_ReadOnly)); } return mutableFamily; } /// <summary> /// First font family /// </summary> internal IFontFamily FirstFontFamily { get { IFontFamily family = _firstFontFamily; if (family == null) { // Call Canonicalize() directly so it won't just be called on the boxed object. _familyIdentifier.Canonicalize(); // Look up first font family from cache. If not found, construct a new one. family = TypefaceMetricsCache.ReadonlyLookup(FamilyIdentifier) as IFontFamily; if (family == null) { FontStyle style = FontStyles.Normal; FontWeight weight = FontWeights.Normal; FontStretch stretch = FontStretches.Normal; family = FindFirstFontFamilyAndFace(ref style, ref weight, ref stretch); if (family == null) { // fall back to null font family = LookupFontFamily(NullFontFamilyCanonicalName); Invariant.Assert(family != null); } TypefaceMetricsCache.Add(FamilyIdentifier, family); } _firstFontFamily = family; } return family; } } #region Resolving family name to font family /// <summary> /// Scan the friendly name string finding the first valid font family /// </summary> internal static IFontFamily FindFontFamilyFromFriendlyNameList(string friendlyNameList) { IFontFamily firstFontFamily = null; // Split limits the number of tokens in a family name. FontFamilyIdentifier identifier = new FontFamilyIdentifier(friendlyNameList, null); for (int i = 0, c = identifier.Count; firstFontFamily == null && i < c; i++) { firstFontFamily = LookupFontFamily(identifier[i]); } if (firstFontFamily == null) { // cannot find first font family, assume null font for first font family firstFontFamily = LookupFontFamily(NullFontFamilyCanonicalName); // null font family should always exist Invariant.Assert(firstFontFamily != null); } return firstFontFamily; } /// <summary> /// Create font family from canonical family and ensure at least a /// fallback family is created if the specified name cannot be resolved. /// </summary> internal static IFontFamily SafeLookupFontFamily( CanonicalFontFamilyReference canonicalName, out bool nullFont ) { nullFont = false; IFontFamily fontFamily = LookupFontFamily(canonicalName); if(fontFamily == null) { nullFont = true; fontFamily = LookupFontFamily(NullFontFamilyCanonicalName); Invariant.Assert(fontFamily != null, "Unable to create null font family"); } return fontFamily; } /// <summary> /// Look up font family from canonical name /// </summary> /// <param name="canonicalName">font family canonical name</param> internal static IFontFamily LookupFontFamily(CanonicalFontFamilyReference canonicalName) { FontStyle style = FontStyles.Normal; FontWeight weight = FontWeights.Normal; FontStretch stretch = FontStretches.Normal; return LookupFontFamilyAndFace(canonicalName, ref style, ref weight, ref stretch); } #endregion #region Resolving face name into font family and implied face /// <summary> /// Precreates family collection for Windows Fonts folder, so that we don't have to repeat lookup /// every time for it. /// </summary> /// <returns></returns> /// <SecurityNote> /// Critical - Exposes windows font information. /// Safe - as this doesn't expose sensitive font directly /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] private static FamilyCollection PreCreateDefaultFamilyCollection() { FamilyCollection familyCollection = FamilyCollection.FromWindowsFonts(Util.WindowsFontsUriObject); return familyCollection; } /// <summary> /// Find the first valid IFontFamily, if any, for this FontFamily and sets the style, weight, /// and stretch to valies implied by the font family (e.g., "Arial Bold" implies FontWeight.Bold). /// </summary> internal IFontFamily FindFirstFontFamilyAndFace( ref FontStyle style, ref FontWeight weight, ref FontStretch stretch ) { if (_familyIdentifier.Source == null) { Invariant.Assert(_firstFontFamily != null, "Unnamed FontFamily should have a non-null first font family"); return _firstFontFamily; } IFontFamily firstFontFamily = null; _familyIdentifier.Canonicalize(); for (int i = 0, c = _familyIdentifier.Count; firstFontFamily == null && i < c; ++i) { firstFontFamily = LookupFontFamilyAndFace( _familyIdentifier[i], ref style, ref weight, ref stretch); } return firstFontFamily; } /// <summary> /// Lookup font family from canonical name. /// </summary> /// <param name="canonicalFamilyReference">font face canonical name</param> /// <param name="style">FontStyle implied by the font family.</param> /// <param name="weight">FontWeight implied by the font family.</param> /// <param name="stretch">FontStretch implied by the font family.</param> /// <returns>The font family object.</returns> /// <SecurityNote> /// Critical - This method accesses the Util.WindowsFontsUriObject which is privileged information /// and looks up from the font cache which is a critical operation. /// Safe - This method returns a IFontFamily which is safe to passed around. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] internal static IFontFamily LookupFontFamilyAndFace( CanonicalFontFamilyReference canonicalFamilyReference, ref FontStyle style, ref FontWeight weight, ref FontStretch stretch ) { if (canonicalFamilyReference == null || object.ReferenceEquals(canonicalFamilyReference, CanonicalFontFamilyReference.Unresolved)) { // no canonical name, e.g., because the friendly name was an empty string // or could not be canonicalized return null; } try { FamilyCollection familyCollection; if (canonicalFamilyReference.LocationUri == null && canonicalFamilyReference.EscapedFileName == null) { // No explicit location; use the default family collection. familyCollection = _defaultFamilyCollection; } else if (canonicalFamilyReference.LocationUri != null) { // Look in the location specified by the font family reference. familyCollection = FamilyCollection.FromUri(canonicalFamilyReference.LocationUri); } else // canonicalFamilyReference.EscapedFileName != null { // Look in the specified file in the Windows Fonts folder // Note: CanonicalFamilyReference.EscapedFileName is safe to combine with Util.WindowsFontsUriObject because CanonicalFamilyReference guarantees that it will be a simple filename // without relative path or directory components. Uri locationUri = new Uri(Util.WindowsFontsUriObject, canonicalFamilyReference.EscapedFileName); familyCollection = FamilyCollection.FromWindowsFonts(locationUri); } IFontFamily fontFamily = familyCollection.LookupFamily( canonicalFamilyReference.FamilyName, ref style, ref weight, ref stretch ); return fontFamily; } // The method returns null in case of malformed/non-existent fonts and we fall back to the next font. // Therefore, we can disable PreSharp warning about empty catch bodies. #pragma warning disable 6502 catch (FileFormatException) { // malformed font file } catch (IOException) { // canonical name points to a place that doesn't exist or can't be read for some reason } catch (UnauthorizedAccessException) { // canonical name points to a place caller doesn't have permission to access } catch (ArgumentException) { // canonical name points to a valid Uri that doesn't point to a well formed // OS local path } catch (NotSupportedException) { // canonical name points to a Uri that specifies an unregistered scheme } catch (UriFormatException) { // canonical name points to a malformed Uri } #pragma warning restore 6502 // we want to fall back to the default fallback font instead of crashing return null; } #endregion } }
#region copyright // VZF // Copyright (C) 2014-2016 Vladimir Zakharov // // http://www.code.coolhobby.ru/ // File DB.cs created on 2.6.2015 in 6:31 AM. // Last changed on 5.21.2016 in 1:10 PM. // 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. // #endregion namespace YAF.Providers.Profile { using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Globalization; using System.IO; using System.Linq; using System.Text; using VZF.Data.Common; using VZF.Data.DAL; using VZF.Data.Firebird.Mappers; using VZF.Data.Utils; using YAF.Classes.Pattern; /// <summary> /// The fb db. /// </summary> public class FbDB { /// <summary> /// Gets the current. /// </summary> public static FbDB Current { get { return PageSingleton<FbDB>.Instance; } } /// <summary> /// The encode profile data. /// </summary> /// <param name="collection"> /// The collection. /// </param> /// <param name="isAuthenticated"> /// The is authenticated. /// </param> /// <param name="index"> /// The index. /// </param> /// <param name="stringData"> /// The string data. /// </param> /// <param name="binaryData"> /// The binary data. /// </param> /// <returns> /// The <see cref="int"/>. /// </returns> private static int EncodeProfileData( SettingsPropertyValueCollection collection, bool isAuthenticated, ref string index, ref string stringData, ref byte[] binaryData) { bool itemsToSave = collection.Cast<SettingsPropertyValue>().Where(value => value.IsDirty) .Any(value => !value.Property.Attributes["AllowAnonymous"].Equals(false) || isAuthenticated); // first we need to determine if there are any items that need saving // this is an optimization if (!itemsToSave) { return 0; } var indexBuilder = new StringBuilder(); var stringDataBuilder = new StringBuilder(); var binaryBuilder = new MemoryStream(); int count = 0; // ok, we have some values that need to be saved so we go back through foreach (SettingsPropertyValue value in collection) { // if the value has not been written to and is still using the default value // no need to save it if (value.UsingDefaultValue && !value.IsDirty) { continue; } // we don't save properties that require the user to be authenticated when the // current user is not authenticated. if (value.Property.Attributes["AllowAnonymous"].Equals(false) && !isAuthenticated) { continue; } count++; object propValue = value.SerializedValue; if ((value.Deserialized && value.PropertyValue == null) || value.SerializedValue == null) { indexBuilder.AppendFormat("{0}//0/-1:", value.Name); } else if (propValue is string) { indexBuilder.AppendFormat( "{0}/0/{1}/{2}:", value.Name, stringDataBuilder.Length, (propValue as string).Length); stringDataBuilder.Append(propValue); } else { var binaryValue = (byte[])propValue; indexBuilder.AppendFormat("{0}/1/{1}/{2}:", value.Name, binaryBuilder.Position, binaryValue.Length); binaryBuilder.Write(binaryValue, 0, binaryValue.Length); } } index = indexBuilder.ToString(); stringData = stringDataBuilder.ToString(); binaryData = binaryBuilder.ToArray(); return count; } /// <summary> /// The decode profile data. /// </summary> /// <param name="profileRow"> /// The profile row. /// </param> /// <param name="values"> /// The values. /// </param> public static void DecodeProfileData(DataRow profileRow, SettingsPropertyValueCollection values) { byte[] binaryData = null; string indexData = null; string stringData = null; indexData = profileRow["valueindex"].ToString(); stringData = profileRow["stringData"].ToString(); if (profileRow["binaryData"] != DBNull.Value) { binaryData = (byte[])profileRow["binaryData"]; } string[] indexes = indexData.Split(':'); foreach (string index in indexes) { string[] parts = index.Split('/'); SettingsPropertyValue value = values[parts[0]]; if (value == null) { continue; } int pos = int.Parse(parts[2], CultureInfo.InvariantCulture); int len = int.Parse(parts[3], CultureInfo.InvariantCulture); if (len == -1) { value.PropertyValue = null; value.IsDirty = false; value.Deserialized = true; } else if (parts[1].Equals("0")) { value.SerializedValue = stringData.Substring(pos, len); } else { var buf = new byte[len]; Buffer.BlockCopy(binaryData, pos, buf, 0, len); value.SerializedValue = buf; } } } /// <summary> /// The get profiles. /// </summary> /// <param name="connectionStringName"> /// The connection string name. /// </param> /// <param name="appName"> /// The app name. /// </param> /// <param name="pageIndex"> /// The page index. /// </param> /// <param name="pageSize"> /// The page size. /// </param> /// <param name="userNameToMatch"> /// The user name to match. /// </param> /// <param name="inactiveSinceDate"> /// The inactive since date. /// </param> /// <returns> /// The <see cref="DataTable"/>. /// </returns> public DataTable GetProfiles(string connectionStringName, object appName, object pageIndex, object pageSize, object userNameToMatch, object inactiveSinceDate) { using (var sc = new VzfSqlCommand(connectionStringName)) { sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_applicationname", appName)); sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "I_PROFILEAUTHOPTIONS", 1)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_USERNAMETOMATCH", userNameToMatch)); sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "I_INACTIVESINCEDATE", inactiveSinceDate)); sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "I_PAGEINDEX", pageIndex)); sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "I_PAGESIZE", pageSize)); sc.CommandText.AppendObjectQuery("P_profile_getprofiles", connectionStringName); return sc.ExecuteDataTableFromReader(CommandBehavior.Default, CommandType.StoredProcedure, false); } } /// <summary> /// The get profile structure. /// </summary> /// <param name="connectionStringName"> /// The connection string name. /// </param> /// <returns> /// The <see cref="DataTable"/>. /// </returns> public DataTable GetProfileStructure(string connectionStringName) { return CommonDb.GetProfileStructure(connectionStringName, "P_profile"); } /// <summary> /// The add profile column. /// </summary> /// <param name="connectionStringName"> /// The connection string name. /// </param> /// <param name="Name"> /// The name. /// </param> /// <param name="columnType"> /// The column type. /// </param> /// <param name="size"> /// The size. /// </param> public void AddProfileColumn(string connectionStringName, string Name, string columnType, int size) { string type = DataTypeMappers.typeToDbValueMap(Name, columnType, size); using (var sc = new VzfSqlCommand(connectionStringName)) { sc.CommandText.AppendQuery(@"ALTER TABLE "); sc.CommandText.AppendObjectQuery("P_profile", connectionStringName); sc.CommandText.AppendQuery(string.Format(@" ADD {0} {1};", Name, type)); sc.ExecuteNonQuery(CommandType.Text, false); } } /// <summary> /// The get provider user key. /// </summary> /// <param name="connectionStringName"> /// The connection string name. /// </param> /// <param name="appName"> /// The app name. /// </param> /// <param name="username"> /// The username. /// </param> /// <returns> /// The <see cref="object"/>. /// </returns> public object GetProviderUserKey(string connectionStringName, object appName, object username) { DataRow row = YAF.Providers.Membership.FbDB.Current.GetUser(connectionStringName, appName.ToString(), null, username.ToString(), false); if (row != null) { return row["UserID"]; } return null; } /// <summary> /// The set profile properties. /// </summary> /// <param name="connectionStringName"> /// The connection string name. /// </param> /// <param name="appName"> /// The app name. /// </param> /// <param name="userID"> /// The user id. /// </param> /// <param name="values"> /// The values. /// </param> /// <param name="settingsColumnsList"> /// The settings columns list. /// </param> public void SetProfileProperties(string connectionStringName, object appName, object userID, SettingsPropertyValueCollection values, List<SettingsPropertyColumn> settingsColumnsList) { // connectionStringName = SqlDbAccess.GetConnectionStringNameFromConnectionString(connectionStringName); // EOF 'apply new profile properties' if (string.IsNullOrEmpty(userID.ToString())) { return; } if (values.Count <= 0) { return; } string index = string.Empty; string stringData = string.Empty; byte[] binaryData = null; bool isAuthenticated = true; int count = EncodeProfileData(values, isAuthenticated, ref index, ref stringData, ref binaryData); if (count < 1) { return; } bool profileExists = false; using (var sc = new VzfSqlCommand(connectionStringName)) { // cmd.Parameters.Add(new FbParameter("@I_USERID", FbDbType.VarChar)).Value = userID; sc.CommandText.AppendQuery(string.Format(@"SELECT COUNT(1) FROM {0} WHERE USERID =CHAR_TO_UUID('{1}');", SqlDbAccess.GetVzfObjectNameFromConnectionString("P_profile", connectionStringName), userID)); profileExists = Convert.ToBoolean(sc.ExecuteScalar(CommandType.Text, false)); } if (profileExists) { /* using (FbCommand cmd = FbDbAccess.GetCommand( String.Format(@"UPDATE {0} SET valueindex ='{1}',stringdata='{2}',binarydata='{3}',LASTUPDATEDDATE='{4}' WHERE USERID =CHAR_TO_UUID('{5}');", YAF.Classes.Data.FbDbAccess.GetObjectName("P_PROFILE"), index, stringData, binaryData, DateTime.UtcNow, userID), true)) { */ using (var sc = new VzfSqlCommand(connectionStringName)) { sc.Parameters.Add(sc.CreateParameter(DbType.Binary, "I_valueindex", index)); sc.Parameters.Add(sc.CreateParameter(DbType.Binary, "I_stringdata", stringData)); sc.Parameters.Add(sc.CreateParameter(DbType.Binary, "I_binarydata", binaryData)); sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "current_utctimestamp", DateTime.Now)); // cmd.Parameters.Add(new FbParameter("@I_USERID", FbDbType.VarChar)).Value = userID; sc.CommandText.AppendQuery( string.Format( @"UPDATE {0} SET valueindex = ?,stringdata=?,binarydata=?,LASTUPDATEDDATE=? WHERE USERID =CHAR_TO_UUID('{1}');", SqlDbAccess.GetVzfObjectNameFromConnectionString("P_profile", connectionStringName), userID)); sc.ExecuteNonQuery(CommandType.Text, false); } } else { using (var sc = new VzfSqlCommand(connectionStringName)) { sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_USERID", userID)); sc.Parameters.Add(sc.CreateParameter(DbType.Binary, "I_valueindex", index)); sc.Parameters.Add(sc.CreateParameter(DbType.Binary, "I_stringdata", stringData)); sc.Parameters.Add(sc.CreateParameter(DbType.Binary, "I_binarydata", binaryData)); sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "current_utctimestamp", DateTime.Now)); // cmd.Parameters.Add(new FbParameter("@I_USERID", FbDbType.VarChar)).Value = userID; sc.CommandText.AppendQuery( string.Format( @"INSERT INTO {0}(USERID,valueindex,stringdata,binarydata,LASTUPDATEDDATE) VALUES(CHAR_TO_UUID(@I_USERID), @I_valueindex, @I_stringdata, @I_binarydata,@current_utctimestamp);", SqlDbAccess.GetVzfObjectNameFromConnectionString("P_profile", connectionStringName))); sc.ExecuteNonQuery(CommandType.Text, false); } } } /// <summary> /// The delete profiles. /// </summary> /// <param name="connectionStringName"> /// The connection string name. /// </param> /// <param name="appName"> /// The app name. /// </param> /// <param name="userNames"> /// The user names. /// </param> /// <returns> /// The <see cref="int"/>. /// </returns> public int DeleteProfiles(string connectionStringName, object appName, object userNames) { // connectionStringName = SqlDbAccess.GetConnectionStringNameFromConnectionString(connectionStringName); int deleted = 0; char[] sep = new[] { ',' }; string[] userNamesArr = userNames.ToString().Split(sep[0]); for (int i = 0; i <= userNamesArr.Length; i++) { using (var sc = new VzfSqlCommand(connectionStringName)) { sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_applicationname", appName)); sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_USERNAME", userNamesArr[i])); sc.CommandText.AppendObjectQuery("P_profile_deleteprofile", connectionStringName); deleted += Convert.ToInt32(sc.ExecuteScalar(CommandType.StoredProcedure, false)); } } return deleted; } /// <summary> /// The delete inactive profiles. /// </summary> /// <param name="connectionStringName"> /// The connection string name. /// </param> /// <param name="appName"> /// The app name. /// </param> /// <param name="inactiveSinceDate"> /// The inactive since date. /// </param> /// <returns> /// The <see cref="int"/>. /// </returns> public int DeleteInactiveProfiles(string connectionStringName, object appName, object inactiveSinceDate) { // connectionStringName = SqlDbAccess.GetConnectionStringNameFromConnectionString(connectionStringName); using (var sc = new VzfSqlCommand(connectionStringName)) { sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_APPLICATIONNAME", appName)); sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "I_INACTIVESINCEDATE", inactiveSinceDate)); sc.CommandText.AppendObjectQuery("P_profile_deleteinactive", connectionStringName); return Convert.ToInt32(sc.ExecuteScalar(CommandType.StoredProcedure, false)); } } /// <summary> /// The get number inactive profiles. /// </summary> /// <param name="connectionStringName"> /// The connection string name. /// </param> /// <param name="appName"> /// The app name. /// </param> /// <param name="inactiveSinceDate"> /// The inactive since date. /// </param> /// <returns> /// The <see cref="int"/>. /// </returns> public int GetNumberInactiveProfiles(string connectionStringName, object appName, object inactiveSinceDate) { // connectionStringName = SqlDbAccess.GetConnectionStringNameFromConnectionString(connectionStringName); using (var sc = new VzfSqlCommand(connectionStringName)) { sc.Parameters.Add(sc.CreateParameter(DbType.String, "I_APPLICATIONNAME", appName)); sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "I_INACTIVESINCEDATE", inactiveSinceDate)); sc.CommandText.AppendObjectQuery("P_PROFILE_GETNUMINACT", connectionStringName); return Convert.ToInt32(sc.ExecuteScalar(CommandType.StoredProcedure, false)); } } /* public void ValidateAddColumnInProfile( string columnName, NpgsqlTypes.NpgsqlDbType columnType ) { FbCommand cmd = new FbCommand( sprocName ); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add( "@ApplicationName", appName ); cmd.Parameters.Add( "@Username", username ); cmd.Parameters.Add( "@IsUserAnonymous", isAnonymous ); return cmd; } */ } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.RecoveryServices; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// ReplicationRecoveryServicesProvidersOperations operations. /// </summary> public partial interface IReplicationRecoveryServicesProvidersOperations { /// <summary> /// Refresh details from the recovery services provider. /// </summary> /// <remarks> /// The operation to refresh the information from the recovery services /// provider. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='providerName'> /// Recovery services provider name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RecoveryServicesProvider>> RefreshProviderWithHttpMessagesAsync(string fabricName, string providerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes provider from fabric. /// Note: Deleting provider for any fabric other than SingleHost is /// unsupported. To /// maintain backward compatibility for released clients the object /// "deleteRspInput" is /// used (if the object is empty we assume that it is old client and /// continue the old /// behavior). /// </summary> /// <remarks> /// The operation to removes/delete(unregister) a recovery services /// provider from the vault /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='providerName'> /// Recovery services provider name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string fabricName, string providerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the details of a recovery services provider. /// </summary> /// <remarks> /// Gets the details of registered recovery services provider. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='providerName'> /// Recovery services provider name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RecoveryServicesProvider>> GetWithHttpMessagesAsync(string fabricName, string providerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Purges recovery service provider from fabric /// </summary> /// <remarks> /// The operation to purge(force delete) a recovery services provider /// from the vault. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='providerName'> /// Recovery services provider name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> PurgeWithHttpMessagesAsync(string fabricName, string providerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the list of registered recovery services providers for the /// fabric. /// </summary> /// <remarks> /// Lists the registered recovery services providers for the specified /// fabric. /// </remarks> /// <param name='fabricName'> /// Fabric name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<RecoveryServicesProvider>>> ListByReplicationFabricsWithHttpMessagesAsync(string fabricName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the list of registered recovery services providers in the /// vault. /// This is a view only api. /// </summary> /// <remarks> /// Lists the registered recovery services providers in the vault /// </remarks> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<RecoveryServicesProvider>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Refresh details from the recovery services provider. /// </summary> /// <remarks> /// The operation to refresh the information from the recovery services /// provider. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='providerName'> /// Recovery services provider name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RecoveryServicesProvider>> BeginRefreshProviderWithHttpMessagesAsync(string fabricName, string providerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes provider from fabric. /// Note: Deleting provider for any fabric other than SingleHost is /// unsupported. To /// maintain backward compatibility for released clients the object /// "deleteRspInput" is /// used (if the object is empty we assume that it is old client and /// continue the old /// behavior). /// </summary> /// <remarks> /// The operation to removes/delete(unregister) a recovery services /// provider from the vault /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='providerName'> /// Recovery services provider name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string fabricName, string providerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Purges recovery service provider from fabric /// </summary> /// <remarks> /// The operation to purge(force delete) a recovery services provider /// from the vault. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='providerName'> /// Recovery services provider name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginPurgeWithHttpMessagesAsync(string fabricName, string providerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the list of registered recovery services providers for the /// fabric. /// </summary> /// <remarks> /// Lists the registered recovery services providers for the specified /// fabric. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<RecoveryServicesProvider>>> ListByReplicationFabricsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the list of registered recovery services providers in the /// vault. /// This is a view only api. /// </summary> /// <remarks> /// Lists the registered recovery services providers in the vault /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<RecoveryServicesProvider>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
#region Apache License // // 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. // #endregion using System; using System.Collections; using System.Reflection; #if !NETCF using System.Runtime.Serialization; using System.Xml; #endif namespace log4net.Util { /// <summary> /// String keyed object map that is read only. /// </summary> /// <remarks> /// <para> /// This collection is readonly and cannot be modified. /// </para> /// <para> /// While this collection is serializable only member /// objects that are serializable will /// be serialized along with this collection. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> #if NETCF public class ReadOnlyPropertiesDictionary : IDictionary #else [Serializable] public class ReadOnlyPropertiesDictionary : ISerializable, IDictionary #endif { #region Private Instance Fields /// <summary> /// The Hashtable used to store the properties data /// </summary> private readonly Hashtable m_hashtable = new Hashtable(); #endregion Private Instance Fields #region Public Instance Constructors /// <summary> /// Constructor /// </summary> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="ReadOnlyPropertiesDictionary" /> class. /// </para> /// </remarks> public ReadOnlyPropertiesDictionary() { } /// <summary> /// Copy Constructor /// </summary> /// <param name="propertiesDictionary">properties to copy</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="ReadOnlyPropertiesDictionary" /> class. /// </para> /// </remarks> public ReadOnlyPropertiesDictionary(ReadOnlyPropertiesDictionary propertiesDictionary) { foreach(DictionaryEntry entry in propertiesDictionary) { InnerHashtable.Add(entry.Key, entry.Value); } } #endregion Public Instance Constructors #region Private Instance Constructors #if !(NETCF || NETSTANDARD1_3) /// <summary> /// Deserialization constructor /// </summary> /// <param name="info">The <see cref="SerializationInfo" /> that holds the serialized object data.</param> /// <param name="context">The <see cref="StreamingContext" /> that contains contextual information about the source or destination.</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="ReadOnlyPropertiesDictionary" /> class /// with serialized data. /// </para> /// </remarks> protected ReadOnlyPropertiesDictionary(SerializationInfo info, StreamingContext context) { foreach(SerializationEntry entry in info) { // The keys are stored as Xml encoded names InnerHashtable[XmlConvert.DecodeName(entry.Name)] = entry.Value; } } #endif #endregion Protected Instance Constructors #region Public Instance Properties /// <summary> /// Gets the key names. /// </summary> /// <returns>An array of all the keys.</returns> /// <remarks> /// <para> /// Gets the key names. /// </para> /// </remarks> public string[] GetKeys() { string[] keys = new String[InnerHashtable.Count]; InnerHashtable.Keys.CopyTo(keys, 0); return keys; } /// <summary> /// Gets or sets the value of the property with the specified key. /// </summary> /// <value> /// The value of the property with the specified key. /// </value> /// <param name="key">The key of the property to get or set.</param> /// <remarks> /// <para> /// The property value will only be serialized if it is serializable. /// If it cannot be serialized it will be silently ignored if /// a serialization operation is performed. /// </para> /// </remarks> public virtual object this[string key] { get { return InnerHashtable[key]; } set { throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); } } #endregion Public Instance Properties #region Public Instance Methods /// <summary> /// Test if the dictionary contains a specified key /// </summary> /// <param name="key">the key to look for</param> /// <returns>true if the dictionary contains the specified key</returns> /// <remarks> /// <para> /// Test if the dictionary contains a specified key /// </para> /// </remarks> public bool Contains(string key) { return InnerHashtable.Contains(key); } #endregion /// <summary> /// The hashtable used to store the properties /// </summary> /// <value> /// The internal collection used to store the properties /// </value> /// <remarks> /// <para> /// The hashtable used to store the properties /// </para> /// </remarks> protected Hashtable InnerHashtable { get { return m_hashtable; } } #region Implementation of ISerializable #if !NETCF /// <summary> /// Serializes this object into the <see cref="SerializationInfo" /> provided. /// </summary> /// <param name="info">The <see cref="SerializationInfo" /> to populate with data.</param> /// <param name="context">The destination for this serialization.</param> /// <remarks> /// <para> /// Serializes this object into the <see cref="SerializationInfo" /> provided. /// </para> /// </remarks> #if NET_4_0 || MONO_4_0 || NETSTANDARD1_3 [System.Security.SecurityCritical] #else [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter=true)] #endif public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { foreach(DictionaryEntry entry in InnerHashtable.Clone() as IDictionary) { string entryKey = entry.Key as string; object entryValue = entry.Value; if (entryKey == null || entryValue == null) { continue; } // If value is serializable then we add it to the list #if NETSTANDARD1_3 bool isSerializable = entryValue.GetType().GetTypeInfo().IsSerializable; #else bool isSerializable = entryValue.GetType().IsSerializable; #endif if (isSerializable) { // Store the keys as an Xml encoded local name as it may contain colons (':') // which are NOT escaped by the Xml Serialization framework. // This must be a bug in the serialization framework as we cannot be expected // to know the implementation details of all the possible transport layers. info.AddValue(XmlConvert.EncodeLocalName(entryKey), entryValue); } } } #endif #endregion Implementation of ISerializable #region Implementation of IDictionary /// <summary> /// See <see cref="IDictionary.GetEnumerator"/> /// </summary> IDictionaryEnumerator IDictionary.GetEnumerator() { return InnerHashtable.GetEnumerator(); } /// <summary> /// See <see cref="IDictionary.Remove"/> /// </summary> /// <param name="key"></param> void IDictionary.Remove(object key) { throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); } /// <summary> /// See <see cref="IDictionary.Contains"/> /// </summary> /// <param name="key"></param> /// <returns></returns> bool IDictionary.Contains(object key) { return InnerHashtable.Contains(key); } /// <summary> /// Remove all properties from the properties collection /// </summary> public virtual void Clear() { throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); } /// <summary> /// See <see cref="IDictionary.Add"/> /// </summary> /// <param name="key"></param> /// <param name="value"></param> void IDictionary.Add(object key, object value) { throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); } /// <summary> /// See <see cref="IDictionary.IsReadOnly"/> /// </summary> bool IDictionary.IsReadOnly { get { return true; } } /// <summary> /// See <see cref="IDictionary.this[object]"/> /// </summary> object IDictionary.this[object key] { get { if (!(key is string)) throw new ArgumentException("key must be a string"); return InnerHashtable[key]; } set { throw new NotSupportedException("This is a Read Only Dictionary and can not be modified"); } } /// <summary> /// See <see cref="IDictionary.Values"/> /// </summary> ICollection IDictionary.Values { get { return InnerHashtable.Values; } } /// <summary> /// See <see cref="IDictionary.Keys"/> /// </summary> ICollection IDictionary.Keys { get { return InnerHashtable.Keys; } } /// <summary> /// See <see cref="IDictionary.IsFixedSize"/> /// </summary> bool IDictionary.IsFixedSize { get { return InnerHashtable.IsFixedSize; } } #endregion #region Implementation of ICollection /// <summary> /// See <see cref="ICollection.CopyTo"/> /// </summary> /// <param name="array"></param> /// <param name="index"></param> void ICollection.CopyTo(Array array, int index) { InnerHashtable.CopyTo(array, index); } /// <summary> /// See <see cref="ICollection.IsSynchronized"/> /// </summary> bool ICollection.IsSynchronized { get { return InnerHashtable.IsSynchronized; } } /// <summary> /// The number of properties in this collection /// </summary> public int Count { get { return InnerHashtable.Count; } } /// <summary> /// See <see cref="ICollection.SyncRoot"/> /// </summary> object ICollection.SyncRoot { get { return InnerHashtable.SyncRoot; } } #endregion #region Implementation of IEnumerable /// <summary> /// See <see cref="IEnumerable.GetEnumerator"/> /// </summary> IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)InnerHashtable).GetEnumerator(); } #endregion } }
// <copyright file="StatisticsTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2015 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using System.Collections.Generic; using System.Linq; using MathNet.Numerics.Distributions; using MathNet.Numerics.Random; using MathNet.Numerics.TestData; using NUnit.Framework; // ReSharper disable InvokeAsExtensionMethod namespace MathNet.Numerics.UnitTests.StatisticsTests { using Statistics; /// <summary> /// Statistics Tests /// </summary> [TestFixture, Category("Statistics")] public class StatisticsTests { readonly IDictionary<string, StatTestData> _data = new Dictionary<string, StatTestData> { { "lottery", new StatTestData("NIST.Lottery.dat") }, { "lew", new StatTestData("NIST.Lew.dat") }, { "mavro", new StatTestData("NIST.Mavro.dat") }, { "michelso", new StatTestData("NIST.Michelso.dat") }, { "numacc1", new StatTestData("NIST.NumAcc1.dat") }, { "numacc2", new StatTestData("NIST.NumAcc2.dat") }, { "numacc3", new StatTestData("NIST.NumAcc3.dat") }, { "numacc4", new StatTestData("NIST.NumAcc4.dat") }, { "meixner", new StatTestData("NIST.Meixner.dat") } }; [Test] public void ThrowsOnNullData() { double[] data = null; // ReSharper disable ExpressionIsAlwaysNull Assert.That(() => Statistics.Minimum(data), Throws.Exception); Assert.That(() => Statistics.Maximum(data), Throws.Exception); Assert.That(() => Statistics.Mean(data), Throws.Exception); Assert.That(() => Statistics.HarmonicMean(data), Throws.Exception); Assert.That(() => Statistics.GeometricMean(data), Throws.Exception); Assert.That(() => Statistics.Median(data), Throws.Exception); Assert.That(() => Statistics.Quantile(data, 0.3), Throws.Exception); Assert.That(() => Statistics.Variance(data), Throws.Exception); Assert.That(() => Statistics.StandardDeviation(data), Throws.Exception); Assert.That(() => Statistics.PopulationVariance(data), Throws.Exception); Assert.That(() => Statistics.PopulationStandardDeviation(data), Throws.Exception); Assert.That(() => Statistics.Covariance(data, data), Throws.Exception); Assert.That(() => Statistics.PopulationCovariance(data, data), Throws.Exception); Assert.That(() => Statistics.RootMeanSquare(data), Throws.Exception); Assert.That(() => SortedArrayStatistics.Minimum(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => SortedArrayStatistics.Minimum(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => SortedArrayStatistics.Maximum(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => SortedArrayStatistics.OrderStatistic(data, 1), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => SortedArrayStatistics.Median(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => SortedArrayStatistics.LowerQuartile(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => SortedArrayStatistics.UpperQuartile(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => SortedArrayStatistics.Percentile(data, 30), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => SortedArrayStatistics.Quantile(data, 0.3), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => SortedArrayStatistics.QuantileCustom(data, 0.3, 0, 0, 1, 0), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => SortedArrayStatistics.QuantileCustom(data, 0.3, QuantileDefinition.Nearest), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => SortedArrayStatistics.InterquartileRange(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => SortedArrayStatistics.FiveNumberSummary(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => ArrayStatistics.Minimum(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => ArrayStatistics.Maximum(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => ArrayStatistics.OrderStatisticInplace(data, 1), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => ArrayStatistics.Mean(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => ArrayStatistics.HarmonicMean(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => ArrayStatistics.GeometricMean(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => ArrayStatistics.Variance(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => ArrayStatistics.StandardDeviation(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => ArrayStatistics.PopulationVariance(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => ArrayStatistics.PopulationStandardDeviation(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => ArrayStatistics.Covariance(data, data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => ArrayStatistics.PopulationCovariance(data, data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => ArrayStatistics.RootMeanSquare(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => ArrayStatistics.MedianInplace(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => ArrayStatistics.QuantileInplace(data, 0.3), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => StreamingStatistics.Minimum(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => StreamingStatistics.Maximum(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => StreamingStatistics.Mean(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => StreamingStatistics.HarmonicMean(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => StreamingStatistics.GeometricMean(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => StreamingStatistics.Variance(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => StreamingStatistics.StandardDeviation(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => StreamingStatistics.PopulationVariance(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => StreamingStatistics.PopulationStandardDeviation(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => StreamingStatistics.Covariance(data, data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => StreamingStatistics.PopulationCovariance(data, data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => StreamingStatistics.RootMeanSquare(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => StreamingStatistics.Entropy(data), Throws.Exception.TypeOf<NullReferenceException>()); Assert.That(() => new RunningStatistics(data), Throws.Exception); Assert.That(() => new RunningStatistics().PushRange(data), Throws.Exception); // ReSharper restore ExpressionIsAlwaysNull } [Test] public void DoesNotThrowOnEmptyData() { double[] data = new double[0]; Assert.DoesNotThrow(() => Statistics.Minimum(data)); Assert.DoesNotThrow(() => Statistics.Maximum(data)); Assert.DoesNotThrow(() => Statistics.Mean(data)); Assert.DoesNotThrow(() => Statistics.HarmonicMean(data)); Assert.DoesNotThrow(() => Statistics.GeometricMean(data)); Assert.DoesNotThrow(() => Statistics.Median(data)); Assert.DoesNotThrow(() => Statistics.Quantile(data, 0.3)); Assert.DoesNotThrow(() => Statistics.Variance(data)); Assert.DoesNotThrow(() => Statistics.StandardDeviation(data)); Assert.DoesNotThrow(() => Statistics.PopulationVariance(data)); Assert.DoesNotThrow(() => Statistics.PopulationStandardDeviation(data)); Assert.DoesNotThrow(() => Statistics.Covariance(data, data)); Assert.DoesNotThrow(() => Statistics.PopulationCovariance(data, data)); Assert.DoesNotThrow(() => Statistics.RootMeanSquare(data)); Assert.DoesNotThrow(() => SortedArrayStatistics.Minimum(data)); Assert.DoesNotThrow(() => SortedArrayStatistics.Maximum(data)); Assert.DoesNotThrow(() => SortedArrayStatistics.OrderStatistic(data, 1)); Assert.DoesNotThrow(() => SortedArrayStatistics.Median(data)); Assert.DoesNotThrow(() => SortedArrayStatistics.LowerQuartile(data)); Assert.DoesNotThrow(() => SortedArrayStatistics.UpperQuartile(data)); Assert.DoesNotThrow(() => SortedArrayStatistics.Percentile(data, 30)); Assert.DoesNotThrow(() => SortedArrayStatistics.Quantile(data, 0.3)); Assert.DoesNotThrow(() => SortedArrayStatistics.QuantileCustom(data, 0.3, 0, 0, 1, 0)); Assert.DoesNotThrow(() => SortedArrayStatistics.QuantileCustom(data, 0.3, QuantileDefinition.Nearest)); Assert.DoesNotThrow(() => SortedArrayStatistics.InterquartileRange(data)); Assert.DoesNotThrow(() => SortedArrayStatistics.FiveNumberSummary(data)); Assert.DoesNotThrow(() => ArrayStatistics.Minimum(data)); Assert.DoesNotThrow(() => ArrayStatistics.Maximum(data)); Assert.DoesNotThrow(() => ArrayStatistics.OrderStatisticInplace(data, 1)); Assert.DoesNotThrow(() => ArrayStatistics.Mean(data)); Assert.DoesNotThrow(() => ArrayStatistics.Variance(data)); Assert.DoesNotThrow(() => ArrayStatistics.StandardDeviation(data)); Assert.DoesNotThrow(() => ArrayStatistics.PopulationVariance(data)); Assert.DoesNotThrow(() => ArrayStatistics.PopulationStandardDeviation(data)); Assert.DoesNotThrow(() => ArrayStatistics.Covariance(data, data)); Assert.DoesNotThrow(() => ArrayStatistics.PopulationCovariance(data, data)); Assert.DoesNotThrow(() => ArrayStatistics.RootMeanSquare(data)); Assert.DoesNotThrow(() => ArrayStatistics.MedianInplace(data)); Assert.DoesNotThrow(() => ArrayStatistics.QuantileInplace(data, 0.3)); Assert.DoesNotThrow(() => StreamingStatistics.Minimum(data)); Assert.DoesNotThrow(() => StreamingStatistics.Maximum(data)); Assert.DoesNotThrow(() => StreamingStatistics.Mean(data)); Assert.DoesNotThrow(() => StreamingStatistics.Variance(data)); Assert.DoesNotThrow(() => StreamingStatistics.StandardDeviation(data)); Assert.DoesNotThrow(() => StreamingStatistics.PopulationVariance(data)); Assert.DoesNotThrow(() => StreamingStatistics.PopulationStandardDeviation(data)); Assert.DoesNotThrow(() => StreamingStatistics.Covariance(data, data)); Assert.DoesNotThrow(() => StreamingStatistics.PopulationCovariance(data, data)); Assert.DoesNotThrow(() => StreamingStatistics.RootMeanSquare(data)); Assert.DoesNotThrow(() => StreamingStatistics.Entropy(data)); Assert.That(() => new RunningStatistics(data), Throws.Nothing); Assert.That(() => new RunningStatistics().PushRange(data), Throws.Nothing); Assert.That(() => new RunningStatistics(data).Minimum, Throws.Nothing); Assert.That(() => new RunningStatistics(data).Maximum, Throws.Nothing); Assert.That(() => new RunningStatistics(data).Mean, Throws.Nothing); Assert.That(() => new RunningStatistics(data).Variance, Throws.Nothing); Assert.That(() => new RunningStatistics(data).StandardDeviation, Throws.Nothing); Assert.That(() => new RunningStatistics(data).Skewness, Throws.Nothing); Assert.That(() => new RunningStatistics(data).Kurtosis, Throws.Nothing); Assert.That(() => new RunningStatistics(data).PopulationVariance, Throws.Nothing); Assert.That(() => new RunningStatistics(data).PopulationStandardDeviation, Throws.Nothing); Assert.That(() => new RunningStatistics(data).PopulationSkewness, Throws.Nothing); Assert.That(() => new RunningStatistics(data).PopulationKurtosis, Throws.Nothing); } [TestCase("lottery")] [TestCase("lew")] [TestCase("mavro")] [TestCase("michelso")] [TestCase("numacc1")] [TestCase("numacc2")] [TestCase("numacc3")] [TestCase("numacc4")] public void MeanConsistentWithNistData(string dataSet) { var data = _data[dataSet]; AssertHelpers.AlmostEqualRelative(data.Mean, Statistics.Mean(data.Data), 14); AssertHelpers.AlmostEqualRelative(data.Mean, ArrayStatistics.Mean(data.Data), 14); AssertHelpers.AlmostEqualRelative(data.Mean, StreamingStatistics.Mean(data.Data), 14); AssertHelpers.AlmostEqualRelative(data.Mean, Statistics.MeanVariance(data.Data).Item1, 14); AssertHelpers.AlmostEqualRelative(data.Mean, ArrayStatistics.MeanVariance(data.Data).Item1, 14); AssertHelpers.AlmostEqualRelative(data.Mean, StreamingStatistics.MeanVariance(data.Data).Item1, 14); AssertHelpers.AlmostEqualRelative(data.Mean, new RunningStatistics(data.Data).Mean, 14); } [TestCase("lottery")] [TestCase("lew")] [TestCase("mavro")] [TestCase("michelso")] [TestCase("numacc1")] [TestCase("numacc2")] [TestCase("numacc3")] [TestCase("numacc4")] public void NullableMeanConsistentWithNistData(string dataSet) { var data = _data[dataSet]; AssertHelpers.AlmostEqualRelative(data.Mean, Statistics.Mean(data.DataWithNulls), 14); } [TestCase("lottery", 14)] [TestCase("lew", 14)] [TestCase("mavro", 11)] [TestCase("michelso", 11)] [TestCase("numacc1", 15)] [TestCase("numacc2", 13)] [TestCase("numacc3", 9)] [TestCase("numacc4", 7)] public void StandardDeviationConsistentWithNistData(string dataSet, int digits) { var data = _data[dataSet]; AssertHelpers.AlmostEqualRelative(data.StandardDeviation, Statistics.StandardDeviation(data.Data), digits); AssertHelpers.AlmostEqualRelative(data.StandardDeviation, ArrayStatistics.StandardDeviation(data.Data), digits); AssertHelpers.AlmostEqualRelative(data.StandardDeviation, StreamingStatistics.StandardDeviation(data.Data), digits); AssertHelpers.AlmostEqualRelative(data.StandardDeviation, Math.Sqrt(Statistics.MeanVariance(data.Data).Item2), digits); AssertHelpers.AlmostEqualRelative(data.StandardDeviation, Math.Sqrt(ArrayStatistics.MeanVariance(data.Data).Item2), digits); AssertHelpers.AlmostEqualRelative(data.StandardDeviation, Math.Sqrt(StreamingStatistics.MeanVariance(data.Data).Item2), digits); AssertHelpers.AlmostEqualRelative(data.StandardDeviation, new RunningStatistics(data.Data).StandardDeviation, digits); } [TestCase("lottery", 14)] [TestCase("lew", 14)] [TestCase("mavro", 11)] [TestCase("michelso", 11)] [TestCase("numacc1", 15)] [TestCase("numacc2", 13)] [TestCase("numacc3", 9)] [TestCase("numacc4", 7)] public void NullableStandardDeviationConsistentWithNistData(string dataSet, int digits) { var data = _data[dataSet]; AssertHelpers.AlmostEqualRelative(data.StandardDeviation, Statistics.StandardDeviation(data.DataWithNulls), digits); } [Test] public void MinimumMaximumOnShortSequence() { var samples = new[] { -1.0, 5, 0, -3, 10, -0.5, 4 }; Assert.That(Statistics.Minimum(samples), Is.EqualTo(-3), "Min"); Assert.That(Statistics.Maximum(samples), Is.EqualTo(10), "Max"); Assert.That(ArrayStatistics.Minimum(samples), Is.EqualTo(-3), "Min"); Assert.That(ArrayStatistics.Maximum(samples), Is.EqualTo(10), "Max"); Assert.That(StreamingStatistics.Minimum(samples), Is.EqualTo(-3), "Min"); Assert.That(StreamingStatistics.Maximum(samples), Is.EqualTo(10), "Max"); Assert.That(new RunningStatistics(samples).Minimum, Is.EqualTo(-3), "Min"); Assert.That(new RunningStatistics(samples).Maximum, Is.EqualTo(10), "Max"); Array.Sort(samples); Assert.That(SortedArrayStatistics.Minimum(samples), Is.EqualTo(-3), "Min"); Assert.That(SortedArrayStatistics.Maximum(samples), Is.EqualTo(10), "Max"); } [Test] public void MinimumMaximumOnShortSequence32() { var samples = new[] { -1.0f, 5f, 0f, -3f, 10f, -0.5f, 4f }; Assert.That(Statistics.Minimum(samples), Is.EqualTo(-3), "Min"); Assert.That(Statistics.Maximum(samples), Is.EqualTo(10), "Max"); Assert.That(ArrayStatistics.Minimum(samples), Is.EqualTo(-3), "Min"); Assert.That(ArrayStatistics.Maximum(samples), Is.EqualTo(10), "Max"); Assert.That(StreamingStatistics.Minimum(samples), Is.EqualTo(-3), "Min"); Assert.That(StreamingStatistics.Maximum(samples), Is.EqualTo(10), "Max"); Array.Sort(samples); Assert.That(SortedArrayStatistics.Minimum(samples), Is.EqualTo(-3), "Min"); Assert.That(SortedArrayStatistics.Maximum(samples), Is.EqualTo(10), "Max"); } [Test] public void OrderStatisticsOnShortSequence() { // -3 -1 -0.5 0 1 4 5 6 10 var samples = new[] { -1, 5, 0, -3, 10, -0.5, 4, 1, 6 }; var f = Statistics.OrderStatisticFunc(samples); Assert.That(f(0), Is.NaN, "Order-0 (bad)"); Assert.That(f(1), Is.EqualTo(-3), "Order-1"); Assert.That(f(2), Is.EqualTo(-1), "Order-2"); Assert.That(f(3), Is.EqualTo(-0.5), "Order-3"); Assert.That(f(7), Is.EqualTo(5), "Order-7"); Assert.That(f(8), Is.EqualTo(6), "Order-8"); Assert.That(f(9), Is.EqualTo(10), "Order-9"); Assert.That(f(10), Is.NaN, "Order-10 (bad)"); Assert.That(Statistics.OrderStatistic(samples, 0), Is.NaN, "Order-0 (bad)"); Assert.That(Statistics.OrderStatistic(samples, 1), Is.EqualTo(-3), "Order-1"); Assert.That(Statistics.OrderStatistic(samples, 2), Is.EqualTo(-1), "Order-2"); Assert.That(Statistics.OrderStatistic(samples, 3), Is.EqualTo(-0.5), "Order-3"); Assert.That(Statistics.OrderStatistic(samples, 7), Is.EqualTo(5), "Order-7"); Assert.That(Statistics.OrderStatistic(samples, 8), Is.EqualTo(6), "Order-8"); Assert.That(Statistics.OrderStatistic(samples, 9), Is.EqualTo(10), "Order-9"); Assert.That(Statistics.OrderStatistic(samples, 10), Is.NaN, "Order-10 (bad)"); Assert.That(ArrayStatistics.OrderStatisticInplace(samples, 0), Is.NaN, "Order-0 (bad)"); Assert.That(ArrayStatistics.OrderStatisticInplace(samples, 1), Is.EqualTo(-3), "Order-1"); Assert.That(ArrayStatistics.OrderStatisticInplace(samples, 2), Is.EqualTo(-1), "Order-2"); Assert.That(ArrayStatistics.OrderStatisticInplace(samples, 3), Is.EqualTo(-0.5), "Order-3"); Assert.That(ArrayStatistics.OrderStatisticInplace(samples, 7), Is.EqualTo(5), "Order-7"); Assert.That(ArrayStatistics.OrderStatisticInplace(samples, 8), Is.EqualTo(6), "Order-8"); Assert.That(ArrayStatistics.OrderStatisticInplace(samples, 9), Is.EqualTo(10), "Order-9"); Assert.That(ArrayStatistics.OrderStatisticInplace(samples, 10), Is.NaN, "Order-10 (bad)"); Array.Sort(samples); Assert.That(SortedArrayStatistics.OrderStatistic(samples, 0), Is.NaN, "Order-0 (bad)"); Assert.That(SortedArrayStatistics.OrderStatistic(samples, 1), Is.EqualTo(-3), "Order-1"); Assert.That(SortedArrayStatistics.OrderStatistic(samples, 2), Is.EqualTo(-1), "Order-2"); Assert.That(SortedArrayStatistics.OrderStatistic(samples, 3), Is.EqualTo(-0.5), "Order-3"); Assert.That(SortedArrayStatistics.OrderStatistic(samples, 7), Is.EqualTo(5), "Order-7"); Assert.That(SortedArrayStatistics.OrderStatistic(samples, 8), Is.EqualTo(6), "Order-8"); Assert.That(SortedArrayStatistics.OrderStatistic(samples, 9), Is.EqualTo(10), "Order-9"); Assert.That(SortedArrayStatistics.OrderStatistic(samples, 10), Is.NaN, "Order-10 (bad)"); } [TestCase(0d, -3d)] [TestCase(1d, 10d)] [TestCase(0.5d, 1/5d)] [TestCase(0.2d, -1d)] [TestCase(0.7d, 4d)] [TestCase(0.01d, -3d)] [TestCase(0.99d, 10d)] [TestCase(0.52d, 1d)] [TestCase(0.325d, 0d)] public void QuantileR1EmpiricalInvCDFOnShortSequence(double tau, double expected) { // R: quantile(c(-1,5,0,-3,10,-0.5,4,0.2,1,6),probs=c(0,1,0.5,0.2,0.7,0.01,0.99,0.52,0.325),type=1) // Mathematica: Quantile[{-1,5,0,-3,10,-1/2,4,1/5,1,6},{0,1,1/2,1/5,7/10,1/100,99/100,13/25,13/40},{{0,0},{1,0}}] var samples = new[] { -1, 5, 0, -3, 10, -0.5, 4, 0.2, 1, 6 }; Assert.AreEqual(expected, Statistics.EmpiricalInvCDF(samples, tau), 1e-14); Assert.AreEqual(expected, Statistics.EmpiricalInvCDFFunc(samples)(tau), 1e-14); Assert.AreEqual(expected, Statistics.QuantileCustom(samples, tau, QuantileDefinition.EmpiricalInvCDF), 1e-14); Assert.AreEqual(expected, Statistics.QuantileCustomFunc(samples, QuantileDefinition.EmpiricalInvCDF)(tau), 1e-14); Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, QuantileDefinition.EmpiricalInvCDF), 1e-14); Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, 0d, 0d, 1d, 0d), 1e-14); Array.Sort(samples); Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, QuantileDefinition.EmpiricalInvCDF), 1e-14); Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, 0d, 0d, 1d, 0d), 1e-14); } [TestCase(0d, -3d)] [TestCase(1d, 10d)] [TestCase(0.5d, 3/5d)] [TestCase(0.2d, -3/4d)] [TestCase(0.7d, 9/2d)] [TestCase(0.01d, -3d)] [TestCase(0.99d, 10d)] [TestCase(0.52d, 1d)] [TestCase(0.325d, 0d)] public void QuantileR2EmpiricalInvCDFAverageOnShortSequence(double tau, double expected) { // R: quantile(c(-1,5,0,-3,10,-0.5,4,0.2,1,6),probs=c(0,1,0.5,0.2,0.7,0.01,0.99,0.52,0.325),type=2) // Mathematica: Not Supported var samples = new[] { -1, 5, 0, -3, 10, -0.5, 4, 0.2, 1, 6 }; Assert.AreEqual(expected, Statistics.QuantileCustom(samples, tau, QuantileDefinition.R2), 1e-14); Assert.AreEqual(expected, Statistics.QuantileCustomFunc(samples, QuantileDefinition.R2)(tau), 1e-14); Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, QuantileDefinition.EmpiricalInvCDFAverage), 1e-14); Array.Sort(samples); Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, QuantileDefinition.EmpiricalInvCDFAverage), 1e-14); } [TestCase(0d, -3d)] [TestCase(1d, 10d)] [TestCase(0.5d, 1/5d)] [TestCase(0.2d, -1d)] [TestCase(0.7d, 4d)] [TestCase(0.01d, -3d)] [TestCase(0.99d, 10d)] [TestCase(0.52d, 1/5d)] [TestCase(0.325d, -1/2d)] public void QuantileR3NearestOnShortSequence(double tau, double expected) { // R: quantile(c(-1,5,0,-3,10,-0.5,4,0.2,1,6),probs=c(0,1,0.5,0.2,0.7,0.01,0.99,0.52,0.325),type=3) // Mathematica: Quantile[{-1,5,0,-3,10,-1/2,4,1/5,1,6},{0,1,1/2,1/5,7/10,1/100,99/100,13/25,13/40},{{1/2,0},{0,0}}] var samples = new[] { -1, 5, 0, -3, 10, -0.5, 4, 0.2, 1, 6 }; Assert.AreEqual(expected, Statistics.QuantileCustom(samples, tau, QuantileDefinition.R3), 1e-14); Assert.AreEqual(expected, Statistics.QuantileCustomFunc(samples, QuantileDefinition.R3)(tau), 1e-14); Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, QuantileDefinition.Nearest), 1e-14); Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, 0.5d, 0d, 0d, 0d), 1e-14); Array.Sort(samples); Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, QuantileDefinition.Nearest), 1e-14); Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, 0.5d, 0d, 0d, 0d), 1e-14); } [TestCase(0d, -3d)] [TestCase(1d, 10d)] [TestCase(0.5d, 1/5d)] [TestCase(0.2d, -1d)] [TestCase(0.7d, 4d)] [TestCase(0.01d, -3d)] [TestCase(0.99d, 48/5d)] [TestCase(0.52d, 9/25d)] [TestCase(0.325d, -3/8d)] public void QuantileR4CaliforniaOnShortSequence(double tau, double expected) { // R: quantile(c(-1,5,0,-3,10,-0.5,4,0.2,1,6),probs=c(0,1,0.5,0.2,0.7,0.01,0.99,0.52,0.325),type=4) // Mathematica: Quantile[{-1,5,0,-3,10,-1/2,4,1/5,1,6},{0,1,1/2,1/5,7/10,1/100,99/100,13/25,13/40},{{0,0},{0,1}}] var samples = new[] { -1, 5, 0, -3, 10, -0.5, 4, 0.2, 1, 6 }; Assert.AreEqual(expected, Statistics.QuantileCustom(samples, tau, QuantileDefinition.R4), 1e-14); Assert.AreEqual(expected, Statistics.QuantileCustomFunc(samples, QuantileDefinition.R4)(tau), 1e-14); Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, QuantileDefinition.California), 1e-14); Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, 0d, 0d, 0d, 1d), 1e-14); Array.Sort(samples); Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, QuantileDefinition.California), 1e-14); Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, 0d, 0d, 0d, 1d), 1e-14); } [TestCase(0d, -3d)] [TestCase(1d, 10d)] [TestCase(0.5d, 3/5d)] [TestCase(0.2d, -3/4d)] [TestCase(0.7d, 9/2d)] [TestCase(0.01d, -3d)] [TestCase(0.99d, 10d)] [TestCase(0.52d, 19/25d)] [TestCase(0.325d, -1/8d)] public void QuantileR5HydrologyOnShortSequence(double tau, double expected) { // R: quantile(c(-1,5,0,-3,10,-0.5,4,0.2,1,6),probs=c(0,1,0.5,0.2,0.7,0.01,0.99,0.52,0.325),type=5) // Mathematica: Quantile[{-1,5,0,-3,10,-1/2,4,1/5,1,6},{0,1,1/2,1/5,7/10,1/100,99/100,13/25,13/40},{{1/2,0},{0,1}}] var samples = new[] { -1, 5, 0, -3, 10, -0.5, 4, 0.2, 1, 6 }; Assert.AreEqual(expected, Statistics.QuantileCustom(samples, tau, QuantileDefinition.R5), 1e-14); Assert.AreEqual(expected, Statistics.QuantileCustomFunc(samples, QuantileDefinition.R5)(tau), 1e-14); Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, QuantileDefinition.Hydrology), 1e-14); Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, 0.5d, 0d, 0d, 1d), 1e-14); Array.Sort(samples); Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, QuantileDefinition.Hydrology), 1e-14); Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, 0.5d, 0d, 0d, 1d), 1e-14); } [TestCase(0d, -3d)] [TestCase(1d, 10d)] [TestCase(0.5d, 3/5d)] [TestCase(0.2d, -9/10d)] [TestCase(0.7d, 47/10d)] [TestCase(0.01d, -3d)] [TestCase(0.99d, 10d)] [TestCase(0.52d, 97/125d)] [TestCase(0.325d, -17/80d)] public void QuantileR6WeibullOnShortSequence(double tau, double expected) { // R: quantile(c(-1,5,0,-3,10,-0.5,4,0.2,1,6),probs=c(0,1,0.5,0.2,0.7,0.01,0.99,0.52,0.325),type=6) // Mathematica: Quantile[{-1,5,0,-3,10,-1/2,4,1/5,1,6},{0,1,1/2,1/5,7/10,1/100,99/100,13/25,13/40},{{0,1},{0,1}}] var samples = new[] { -1, 5, 0, -3, 10, -0.5, 4, 0.2, 1, 6 }; Assert.AreEqual(expected, Statistics.QuantileCustom(samples, tau, QuantileDefinition.R6), 1e-14); Assert.AreEqual(expected, Statistics.QuantileCustomFunc(samples, QuantileDefinition.R6)(tau), 1e-14); Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, QuantileDefinition.Weibull), 1e-14); Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, 0d, 1d, 0d, 1d), 1e-14); Array.Sort(samples); Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, QuantileDefinition.Weibull), 1e-14); Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, 0d, 1d, 0d, 1d), 1e-14); } [TestCase(0d, -3d)] [TestCase(1d, 10d)] [TestCase(0.5d, 3/5d)] [TestCase(0.2d, -3/5d)] [TestCase(0.7d, 43/10d)] [TestCase(0.01d, -141/50d)] [TestCase(0.99d, 241/25d)] [TestCase(0.52d, 93/125d)] [TestCase(0.325d, -3/80d)] public void QuantileR7ExcelOnShortSequence(double tau, double expected) { // R: quantile(c(-1,5,0,-3,10,-0.5,4,0.2,1,6),probs=c(0,1,0.5,0.2,0.7,0.01,0.99,0.52,0.325),type=7) // Mathematica: Quantile[{-1,5,0,-3,10,-1/2,4,1/5,1,6},{0,1,1/2,1/5,7/10,1/100,99/100,13/25,13/40},{{1,-1},{0,1}}] var samples = new[] { -1, 5, 0, -3, 10, -0.5, 4, 0.2, 1, 6 }; Assert.AreEqual(expected, Statistics.QuantileCustom(samples, tau, QuantileDefinition.R7), 1e-14); Assert.AreEqual(expected, Statistics.QuantileCustomFunc(samples, QuantileDefinition.R7)(tau), 1e-14); Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, QuantileDefinition.Excel), 1e-14); Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, 1d, -1d, 0d, 1d), 1e-14); Array.Sort(samples); Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, QuantileDefinition.Excel), 1e-14); Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, 1d, -1d, 0d, 1d), 1e-14); } [TestCase(0d, -3d)] [TestCase(1d, 10d)] [TestCase(0.5d, 3/5d)] [TestCase(0.2d, -4/5d)] [TestCase(0.7d, 137/30d)] [TestCase(0.01d, -3d)] [TestCase(0.99d, 10d)] [TestCase(0.52d, 287/375d)] [TestCase(0.325d, -37/240d)] public void QuantileR8MedianOnShortSequence(double tau, double expected) { // R: quantile(c(-1,5,0,-3,10,-0.5,4,0.2,1,6),probs=c(0,1,0.5,0.2,0.7,0.01,0.99,0.52,0.325),type=8) // Mathematica: Quantile[{-1,5,0,-3,10,-1/2,4,1/5,1,6},{0,1,1/2,1/5,7/10,1/100,99/100,13/25,13/40},{{1/3,1/3},{0,1}}] var samples = new[] { -1, 5, 0, -3, 10, -0.5, 4, 0.2, 1, 6 }; Assert.AreEqual(expected, Statistics.Quantile(samples, tau), 1e-14); Assert.AreEqual(expected, Statistics.QuantileCustom(samples, tau, QuantileDefinition.R8), 1e-14); Assert.AreEqual(expected, Statistics.QuantileCustomFunc(samples, QuantileDefinition.R8)(tau), 1e-14); Assert.AreEqual(expected, ArrayStatistics.QuantileInplace(samples, tau), 1e-14); Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, QuantileDefinition.Median), 1e-14); Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, 1/3d, 1/3d, 0d, 1d), 1e-14); Array.Sort(samples); Assert.AreEqual(expected, SortedArrayStatistics.Quantile(samples, tau), 1e-14); Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, QuantileDefinition.Median), 1e-14); Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, 1/3d, 1/3d, 0d, 1d), 1e-14); } [TestCase(0d, -3d)] [TestCase(1d, 10d)] [TestCase(0.5d, 3/5d)] [TestCase(0.2d, -63/80d)] [TestCase(0.7d, 91/20d)] [TestCase(0.01d, -3d)] [TestCase(0.99d, 10d)] [TestCase(0.52d, 191/250d)] [TestCase(0.325d, -47/320d)] public void QuantileR9NormalOnShortSequence(double tau, double expected) { // R: quantile(c(-1,5,0,-3,10,-0.5,4,0.2,1,6),probs=c(0,1,0.5,0.2,0.7,0.01,0.99,0.52,0.325),type=9) // Mathematica: Quantile[{-1,5,0,-3,10,-1/2,4,1/5,1,6},{0,1,1/2,1/5,7/10,1/100,99/100,13/25,13/40},{{3/8,1/4},{0,1}}] var samples = new[] { -1, 5, 0, -3, 10, -0.5, 4, 0.2, 1, 6 }; Assert.AreEqual(expected, Statistics.QuantileCustom(samples, tau, QuantileDefinition.R9), 1e-14); Assert.AreEqual(expected, Statistics.QuantileCustomFunc(samples, QuantileDefinition.R9)(tau), 1e-14); Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, QuantileDefinition.Normal), 1e-14); Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, 3/8d, 1/4d, 0d, 1d), 1e-14); Array.Sort(samples); Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, QuantileDefinition.Normal), 1e-14); Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, 3/8d, 1/4d, 0d, 1d), 1e-14); } [Test] public void RanksSortedArray() { var distinct = new double[] { 1, 2, 4, 7, 8, 9, 10, 12 }; var ties = new double[] { 1, 2, 2, 7, 9, 9, 10, 12 }; // R: rank(sort(data), ties.method="average") Assert.That( SortedArrayStatistics.Ranks(distinct, RankDefinition.Average), Is.EqualTo(new[] { 1.0, 2, 3, 4, 5, 6, 7, 8 }).AsCollection.Within(1e-8)); Assert.That( SortedArrayStatistics.Ranks(ties, RankDefinition.Average), Is.EqualTo(new[] { 1, 2.5, 2.5, 4, 5.5, 5.5, 7, 8 }).AsCollection.Within(1e-8)); // R: rank(data, ties.method="min") Assert.That( SortedArrayStatistics.Ranks(distinct, RankDefinition.Min), Is.EqualTo(new[] { 1.0, 2, 3, 4, 5, 6, 7, 8 }).AsCollection.Within(1e-8)); Assert.That( SortedArrayStatistics.Ranks(ties, RankDefinition.Min), Is.EqualTo(new[] { 1.0, 2, 2, 4, 5, 5, 7, 8 }).AsCollection.Within(1e-8)); // R: rank(data, ties.method="max") Assert.That( SortedArrayStatistics.Ranks(distinct, RankDefinition.Max), Is.EqualTo(new[] { 1.0, 2, 3, 4, 5, 6, 7, 8 }).AsCollection.Within(1e-8)); Assert.That( SortedArrayStatistics.Ranks(ties, RankDefinition.Max), Is.EqualTo(new[] { 1.0, 3, 3, 4, 6, 6, 7, 8 }).AsCollection.Within(1e-8)); // R: rank(data, ties.method="first") Assert.That( SortedArrayStatistics.Ranks(distinct, RankDefinition.First), Is.EqualTo(new[] { 1.0, 2, 3, 4, 5, 6, 7, 8 }).AsCollection.Within(1e-8)); Assert.That( SortedArrayStatistics.Ranks(ties, RankDefinition.First), Is.EqualTo(new[] { 1.0, 2, 3, 4, 5, 6, 7, 8 }).AsCollection.Within(1e-8)); } [Test] public void RanksArray() { var distinct = new double[] { 1, 8, 12, 7, 2, 9, 10, 4 }; var ties = new double[] { 1, 9, 12, 7, 2, 9, 10, 2 }; // R: rank(data, ties.method="average") Assert.That( ArrayStatistics.RanksInplace((double[])distinct.Clone(), RankDefinition.Average), Is.EqualTo(new[] { 1.0, 5, 8, 4, 2, 6, 7, 3 }).AsCollection.Within(1e-8)); Assert.That( ArrayStatistics.RanksInplace((double[])ties.Clone(), RankDefinition.Average), Is.EqualTo(new[] { 1, 5.5, 8, 4, 2.5, 5.5, 7, 2.5 }).AsCollection.Within(1e-8)); // R: rank(data, ties.method="min") Assert.That( ArrayStatistics.RanksInplace((double[])distinct.Clone(), RankDefinition.Min), Is.EqualTo(new[] { 1.0, 5, 8, 4, 2, 6, 7, 3 }).AsCollection.Within(1e-8)); Assert.That( ArrayStatistics.RanksInplace((double[])ties.Clone(), RankDefinition.Min), Is.EqualTo(new[] { 1.0, 5, 8, 4, 2, 5, 7, 2 }).AsCollection.Within(1e-8)); // R: rank(data, ties.method="max") Assert.That( ArrayStatistics.RanksInplace((double[])distinct.Clone(), RankDefinition.Max), Is.EqualTo(new[] { 1.0, 5, 8, 4, 2, 6, 7, 3 }).AsCollection.Within(1e-8)); Assert.That( ArrayStatistics.RanksInplace((double[])ties.Clone(), RankDefinition.Max), Is.EqualTo(new[] { 1.0, 6, 8, 4, 3, 6, 7, 3 }).AsCollection.Within(1e-8)); // R: rank(data, ties.method="first") Assert.That( ArrayStatistics.RanksInplace((double[])distinct.Clone(), RankDefinition.First), Is.EqualTo(new[] { 1.0, 5, 8, 4, 2, 6, 7, 3 }).AsCollection.Within(1e-8)); Assert.That( ArrayStatistics.RanksInplace((double[])ties.Clone(), RankDefinition.First), Is.EqualTo(new[] { 1.0, 5, 8, 4, 2, 6, 7, 3 }).AsCollection.Within(1e-8)); } [Test] public void Ranks() { var distinct = new double[] { 1, 8, 12, 7, 2, 9, 10, 4 }; var ties = new double[] { 1, 9, 12, 7, 2, 9, 10, 2 }; // R: rank(data, ties.method="average") Assert.That( Statistics.Ranks(distinct, RankDefinition.Average), Is.EqualTo(new[] { 1.0, 5, 8, 4, 2, 6, 7, 3 }).AsCollection.Within(1e-8)); Assert.That( Statistics.Ranks(ties, RankDefinition.Average), Is.EqualTo(new[] { 1, 5.5, 8, 4, 2.5, 5.5, 7, 2.5 }).AsCollection.Within(1e-8)); // R: rank(data, ties.method="min") Assert.That( Statistics.Ranks(distinct, RankDefinition.Min), Is.EqualTo(new[] { 1.0, 5, 8, 4, 2, 6, 7, 3 }).AsCollection.Within(1e-8)); Assert.That( Statistics.Ranks(ties, RankDefinition.Min), Is.EqualTo(new[] { 1.0, 5, 8, 4, 2, 5, 7, 2 }).AsCollection.Within(1e-8)); // R: rank(data, ties.method="max") Assert.That( Statistics.Ranks(distinct, RankDefinition.Max), Is.EqualTo(new[] { 1.0, 5, 8, 4, 2, 6, 7, 3 }).AsCollection.Within(1e-8)); Assert.That( Statistics.Ranks(ties, RankDefinition.Max), Is.EqualTo(new[] { 1.0, 6, 8, 4, 3, 6, 7, 3 }).AsCollection.Within(1e-8)); // R: rank(data, ties.method="first") Assert.That( Statistics.Ranks(distinct, RankDefinition.First), Is.EqualTo(new[] { 1.0, 5, 8, 4, 2, 6, 7, 3 }).AsCollection.Within(1e-8)); Assert.That( Statistics.Ranks(ties, RankDefinition.First), Is.EqualTo(new[] { 1.0, 5, 8, 4, 2, 6, 7, 3 }).AsCollection.Within(1e-8)); } [Test] public void EmpiricalCDF() { // R: ecdf(data)(x) var ties = new double[] { 1, 9, 12, 7, 2, 9, 10, 2 }; Assert.That(Statistics.EmpiricalCDF(ties, -1.0), Is.EqualTo(0.0).Within(1e-8)); Assert.That(Statistics.EmpiricalCDF(ties, 0.0), Is.EqualTo(0.0).Within(1e-8)); Assert.That(Statistics.EmpiricalCDF(ties, 1.0), Is.EqualTo(0.125).Within(1e-8)); Assert.That(Statistics.EmpiricalCDF(ties, 2.0), Is.EqualTo(0.375).Within(1e-8)); Assert.That(Statistics.EmpiricalCDF(ties, 3.0), Is.EqualTo(0.375).Within(1e-8)); Assert.That(Statistics.EmpiricalCDF(ties, 4.0), Is.EqualTo(0.375).Within(1e-8)); Assert.That(Statistics.EmpiricalCDF(ties, 5.0), Is.EqualTo(0.375).Within(1e-8)); Assert.That(Statistics.EmpiricalCDF(ties, 6.0), Is.EqualTo(0.375).Within(1e-8)); Assert.That(Statistics.EmpiricalCDF(ties, 7.0), Is.EqualTo(0.5).Within(1e-8)); Assert.That(Statistics.EmpiricalCDF(ties, 8.0), Is.EqualTo(0.5).Within(1e-8)); Assert.That(Statistics.EmpiricalCDF(ties, 9.0), Is.EqualTo(0.75).Within(1e-8)); Assert.That(Statistics.EmpiricalCDF(ties, 10.0), Is.EqualTo(0.875).Within(1e-8)); Assert.That(Statistics.EmpiricalCDF(ties, 11.0), Is.EqualTo(0.875).Within(1e-8)); Assert.That(Statistics.EmpiricalCDF(ties, 12.0), Is.EqualTo(1.0).Within(1e-8)); Assert.That(Statistics.EmpiricalCDF(ties, 13.0), Is.EqualTo(1.0).Within(1e-8)); } [Test] public void EmpiricalCDFSortedArray() { // R: ecdf(data)(x) var ties = new double[] { 1, 9, 12, 7, 2, 9, 10, 2 }; Array.Sort(ties); Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, -1.0), Is.EqualTo(0.0).Within(1e-8)); Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, 0.0), Is.EqualTo(0.0).Within(1e-8)); Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, 1.0), Is.EqualTo(0.125).Within(1e-8)); Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, 2.0), Is.EqualTo(0.375).Within(1e-8)); Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, 3.0), Is.EqualTo(0.375).Within(1e-8)); Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, 4.0), Is.EqualTo(0.375).Within(1e-8)); Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, 5.0), Is.EqualTo(0.375).Within(1e-8)); Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, 6.0), Is.EqualTo(0.375).Within(1e-8)); Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, 7.0), Is.EqualTo(0.5).Within(1e-8)); Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, 8.0), Is.EqualTo(0.5).Within(1e-8)); Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, 9.0), Is.EqualTo(0.75).Within(1e-8)); Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, 10.0), Is.EqualTo(0.875).Within(1e-8)); Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, 11.0), Is.EqualTo(0.875).Within(1e-8)); Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, 12.0), Is.EqualTo(1.0).Within(1e-8)); Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, 13.0), Is.EqualTo(1.0).Within(1e-8)); Assert.That(SortedArrayStatistics.QuantileRank(ties, -1.0, RankDefinition.EmpiricalCDF), Is.EqualTo(0.0).Within(1e-8)); Assert.That(SortedArrayStatistics.QuantileRank(ties, 0.0, RankDefinition.EmpiricalCDF), Is.EqualTo(0.0).Within(1e-8)); Assert.That(SortedArrayStatistics.QuantileRank(ties, 1.0, RankDefinition.EmpiricalCDF), Is.EqualTo(0.125).Within(1e-8)); Assert.That(SortedArrayStatistics.QuantileRank(ties, 2.0, RankDefinition.EmpiricalCDF), Is.EqualTo(0.375).Within(1e-8)); Assert.That(SortedArrayStatistics.QuantileRank(ties, 3.0, RankDefinition.EmpiricalCDF), Is.EqualTo(0.375).Within(1e-8)); Assert.That(SortedArrayStatistics.QuantileRank(ties, 4.0, RankDefinition.EmpiricalCDF), Is.EqualTo(0.375).Within(1e-8)); Assert.That(SortedArrayStatistics.QuantileRank(ties, 5.0, RankDefinition.EmpiricalCDF), Is.EqualTo(0.375).Within(1e-8)); Assert.That(SortedArrayStatistics.QuantileRank(ties, 6.0, RankDefinition.EmpiricalCDF), Is.EqualTo(0.375).Within(1e-8)); Assert.That(SortedArrayStatistics.QuantileRank(ties, 7.0, RankDefinition.EmpiricalCDF), Is.EqualTo(0.5).Within(1e-8)); Assert.That(SortedArrayStatistics.QuantileRank(ties, 8.0, RankDefinition.EmpiricalCDF), Is.EqualTo(0.5).Within(1e-8)); Assert.That(SortedArrayStatistics.QuantileRank(ties, 9.0, RankDefinition.EmpiricalCDF), Is.EqualTo(0.75).Within(1e-8)); Assert.That(SortedArrayStatistics.QuantileRank(ties, 10.0, RankDefinition.EmpiricalCDF), Is.EqualTo(0.875).Within(1e-8)); Assert.That(SortedArrayStatistics.QuantileRank(ties, 11.0, RankDefinition.EmpiricalCDF), Is.EqualTo(0.875).Within(1e-8)); Assert.That(SortedArrayStatistics.QuantileRank(ties, 12.0, RankDefinition.EmpiricalCDF), Is.EqualTo(1.0).Within(1e-8)); Assert.That(SortedArrayStatistics.QuantileRank(ties, 13.0, RankDefinition.EmpiricalCDF), Is.EqualTo(1.0).Within(1e-8)); } [Test] public void MedianOnShortSequence() { // R: median(c(-1,5,0,-3,10,-0.5,4,0.2,1,6)) // Mathematica: Median[{-1,5,0,-3,10,-1/2,4,1/5,1,6}] var even = new[] { -1, 5, 0, -3, 10, -0.5, 4, 0.2, 1, 6 }; Assert.AreEqual(0.6d, Statistics.Median(even), 1e-14); Assert.AreEqual(0.6d, ArrayStatistics.MedianInplace(even), 1e-14); Array.Sort(even); Assert.AreEqual(0.6d, SortedArrayStatistics.Median(even), 1e-14); // R: median(c(-1,5,0,-3,10,-0.5,4,0.2,1)) // Mathematica: Median[{-1,5,0,-3,10,-1/2,4,1/5,1}] var odd = new[] { -1, 5, 0, -3, 10, -0.5, 4, 0.2, 1 }; Assert.AreEqual(0.2d, Statistics.Median(odd), 1e-14); Assert.AreEqual(0.2d, ArrayStatistics.MedianInplace(odd), 1e-14); Array.Sort(even); Assert.AreEqual(0.2d, SortedArrayStatistics.Median(odd), 1e-14); } [Test] public void MedianOnLongConstantSequence() { var even = Generate.Repeat(100000, 2.0); Assert.AreEqual(2.0,SortedArrayStatistics.Median(even), 1e-14); var odd = Generate.Repeat(100001, 2.0); Assert.AreEqual(2.0, SortedArrayStatistics.Median(odd), 1e-14); } /// <summary> /// Validate Median/Variance/StdDev on a longer fixed-random sequence of a, /// large mean but only a very small variance, verifying the numerical stability. /// Naive summation algorithms generally fail this test. /// </summary> [Test] public void StabilityMeanVariance() { // Test around 10^9, potential stability issues var gaussian = new Normal(1e+9, 2, new MersenneTwister(100)); AssertHelpers.AlmostEqualRelative(1e+9, Statistics.Mean(gaussian.Samples().Take(10000)), 10); AssertHelpers.AlmostEqualRelative(4d, Statistics.Variance(gaussian.Samples().Take(10000)), 0); AssertHelpers.AlmostEqualRelative(2d, Statistics.StandardDeviation(gaussian.Samples().Take(10000)), 1); AssertHelpers.AlmostEqualRelative(1e+9, Statistics.RootMeanSquare(gaussian.Samples().Take(10000)), 10); AssertHelpers.AlmostEqualRelative(1e+9, ArrayStatistics.Mean(gaussian.Samples().Take(10000).ToArray()), 10); AssertHelpers.AlmostEqualRelative(4d, ArrayStatistics.Variance(gaussian.Samples().Take(10000).ToArray()), 0); AssertHelpers.AlmostEqualRelative(2d, ArrayStatistics.StandardDeviation(gaussian.Samples().Take(10000).ToArray()), 1); AssertHelpers.AlmostEqualRelative(1e+9, ArrayStatistics.RootMeanSquare(gaussian.Samples().Take(10000).ToArray()), 10); AssertHelpers.AlmostEqualRelative(1e+9, StreamingStatistics.Mean(gaussian.Samples().Take(10000)), 10); AssertHelpers.AlmostEqualRelative(4d, StreamingStatistics.Variance(gaussian.Samples().Take(10000)), 0); AssertHelpers.AlmostEqualRelative(2d, StreamingStatistics.StandardDeviation(gaussian.Samples().Take(10000)), 1); AssertHelpers.AlmostEqualRelative(1e+9, StreamingStatistics.RootMeanSquare(gaussian.Samples().Take(10000)), 10); AssertHelpers.AlmostEqualRelative(1e+9, new RunningStatistics(gaussian.Samples().Take(10000)).Mean, 10); AssertHelpers.AlmostEqualRelative(4d, new RunningStatistics(gaussian.Samples().Take(10000)).Variance, 0); AssertHelpers.AlmostEqualRelative(2d, new RunningStatistics(gaussian.Samples().Take(10000)).StandardDeviation, 1); } [TestCase("lottery")] [TestCase("lew")] [TestCase("mavro")] [TestCase("michelso")] [TestCase("numacc1")] public void CovarianceConsistentWithVariance(string dataSet) { var data = _data[dataSet]; AssertHelpers.AlmostEqualRelative(Statistics.Variance(data.Data), Statistics.Covariance(data.Data, data.Data), 10); AssertHelpers.AlmostEqualRelative(ArrayStatistics.Variance(data.Data), ArrayStatistics.Covariance(data.Data, data.Data), 10); AssertHelpers.AlmostEqualRelative(StreamingStatistics.Variance(data.Data), StreamingStatistics.Covariance(data.Data, data.Data), 10); } [TestCase("lottery")] [TestCase("lew")] [TestCase("mavro")] [TestCase("michelso")] [TestCase("numacc1")] public void PopulationCovarianceConsistentWithPopulationVariance(string dataSet) { var data = _data[dataSet]; AssertHelpers.AlmostEqualRelative(Statistics.PopulationVariance(data.Data), Statistics.PopulationCovariance(data.Data, data.Data), 10); AssertHelpers.AlmostEqualRelative(ArrayStatistics.PopulationVariance(data.Data), ArrayStatistics.PopulationCovariance(data.Data, data.Data), 10); AssertHelpers.AlmostEqualRelative(StreamingStatistics.PopulationVariance(data.Data), StreamingStatistics.PopulationCovariance(data.Data, data.Data), 10); } [Test] public void CovarianceIsSymmetric() { var dataA = _data["lottery"].Data.Take(200).ToArray(); var dataB = _data["lew"].Data.Take(200).ToArray(); AssertHelpers.AlmostEqualRelative(Statistics.Covariance(dataA, dataB), Statistics.Covariance(dataB, dataA), 12); AssertHelpers.AlmostEqualRelative(StreamingStatistics.Covariance(dataA, dataB), StreamingStatistics.Covariance(dataB, dataA), 12); AssertHelpers.AlmostEqualRelative(ArrayStatistics.Covariance(dataA.ToArray(), dataB.ToArray()), ArrayStatistics.Covariance(dataB.ToArray(), dataA.ToArray()), 12); AssertHelpers.AlmostEqualRelative(Statistics.PopulationCovariance(dataA, dataB), Statistics.PopulationCovariance(dataB, dataA), 12); AssertHelpers.AlmostEqualRelative(StreamingStatistics.PopulationCovariance(dataA, dataB), StreamingStatistics.PopulationCovariance(dataB, dataA), 12); AssertHelpers.AlmostEqualRelative(ArrayStatistics.PopulationCovariance(dataA.ToArray(), dataB.ToArray()), ArrayStatistics.PopulationCovariance(dataB.ToArray(), dataA.ToArray()), 12); } [TestCase("lottery")] [TestCase("lew")] [TestCase("mavro")] [TestCase("michelso")] [TestCase("numacc1")] [TestCase("numacc2")] [TestCase("meixner")] public void ArrayStatisticsConsistentWithStreamimgStatistics(string dataSet) { var data = _data[dataSet]; Assert.That(ArrayStatistics.Mean(data.Data), Is.EqualTo(StreamingStatistics.Mean(data.Data)).Within(1e-15), "Mean"); Assert.That(ArrayStatistics.Variance(data.Data), Is.EqualTo(StreamingStatistics.Variance(data.Data)).Within(1e-15), "Variance"); Assert.That(ArrayStatistics.StandardDeviation(data.Data), Is.EqualTo(StreamingStatistics.StandardDeviation(data.Data)).Within(1e-15), "StandardDeviation"); Assert.That(ArrayStatistics.PopulationVariance(data.Data), Is.EqualTo(StreamingStatistics.PopulationVariance(data.Data)).Within(1e-15), "PopulationVariance"); Assert.That(ArrayStatistics.PopulationStandardDeviation(data.Data), Is.EqualTo(StreamingStatistics.PopulationStandardDeviation(data.Data)).Within(1e-15), "PopulationStandardDeviation"); Assert.That(ArrayStatistics.Covariance(data.Data, data.Data), Is.EqualTo(StreamingStatistics.Covariance(data.Data, data.Data)).Within(1e-10), "Covariance"); Assert.That(ArrayStatistics.PopulationCovariance(data.Data, data.Data), Is.EqualTo(StreamingStatistics.PopulationCovariance(data.Data, data.Data)).Within(1e-10), "PopulationCovariance"); Assert.That(ArrayStatistics.RootMeanSquare(data.Data), Is.EqualTo(StreamingStatistics.RootMeanSquare(data.Data)).Within(1e-15), "RootMeanSquare"); } [TestCase("lottery")] [TestCase("lew")] [TestCase("mavro")] [TestCase("michelso")] [TestCase("numacc1")] [TestCase("numacc2")] [TestCase("meixner")] public void RunningStatisticsConsistentWithDescriptiveStatistics(string dataSet) { var data = _data[dataSet]; var running = new RunningStatistics(data.Data); var descriptive = new DescriptiveStatistics(data.Data); Assert.That(running.Minimum, Is.EqualTo(descriptive.Minimum), "Minimum"); Assert.That(running.Maximum, Is.EqualTo(descriptive.Maximum), "Maximum"); Assert.That(running.Mean, Is.EqualTo(descriptive.Mean).Within(1e-15), "Mean"); Assert.That(running.Variance, Is.EqualTo(descriptive.Variance).Within(1e-15), "Variance"); Assert.That(running.StandardDeviation, Is.EqualTo(descriptive.StandardDeviation).Within(1e-15), "StandardDeviation"); Assert.That(running.Skewness, Is.EqualTo(descriptive.Skewness).Within(1e-15), "Skewness"); Assert.That(running.Kurtosis, Is.EqualTo(descriptive.Kurtosis).Within(1e-14), "Kurtosis"); } [Test] public void MinimumOfEmptyMustBeNaN() { Assert.That(Statistics.Minimum(new double[0]), Is.NaN); Assert.That(Statistics.Minimum(new[] { 2d }), Is.Not.NaN); Assert.That(ArrayStatistics.Minimum(new double[0]), Is.NaN); Assert.That(ArrayStatistics.Minimum(new[] { 2d }), Is.Not.NaN); Assert.That(SortedArrayStatistics.Minimum(new double[0]), Is.NaN); Assert.That(SortedArrayStatistics.Minimum(new[] { 2d }), Is.Not.NaN); Assert.That(StreamingStatistics.Minimum(new double[0]), Is.NaN); Assert.That(StreamingStatistics.Minimum(new[] { 2d }), Is.Not.NaN); Assert.That(new RunningStatistics(new double[0]).Minimum, Is.NaN); Assert.That(new RunningStatistics(new[] { 2d }).Minimum, Is.Not.NaN); } [Test] public void MaximumOfEmptyMustBeNaN() { Assert.That(Statistics.Maximum(new double[0]), Is.NaN); Assert.That(Statistics.Maximum(new[] { 2d }), Is.Not.NaN); Assert.That(ArrayStatistics.Maximum(new double[0]), Is.NaN); Assert.That(ArrayStatistics.Maximum(new[] { 2d }), Is.Not.NaN); Assert.That(SortedArrayStatistics.Maximum(new double[0]), Is.NaN); Assert.That(SortedArrayStatistics.Maximum(new[] { 2d }), Is.Not.NaN); Assert.That(StreamingStatistics.Maximum(new double[0]), Is.NaN); Assert.That(StreamingStatistics.Maximum(new[] { 2d }), Is.Not.NaN); Assert.That(new RunningStatistics(new double[0]).Maximum, Is.NaN); Assert.That(new RunningStatistics(new[] { 2d }).Maximum, Is.Not.NaN); } [Test] public void MeanOfEmptyMustBeNaN() { Assert.That(Statistics.Mean(new double[0]), Is.NaN); Assert.That(Statistics.Mean(new[] { 2d }), Is.Not.NaN); Assert.That(ArrayStatistics.Mean(new double[0]), Is.NaN); Assert.That(ArrayStatistics.Mean(new[] { 2d }), Is.Not.NaN); Assert.That(StreamingStatistics.Mean(new double[0]), Is.NaN); Assert.That(StreamingStatistics.Mean(new[] { 2d }), Is.Not.NaN); Assert.That(new RunningStatistics(new double[0]).Mean, Is.NaN); Assert.That(new RunningStatistics(new[] { 2d }).Mean, Is.Not.NaN); } [Test] public void RootMeanSquareOfEmptyMustBeNaN() { Assert.That(Statistics.RootMeanSquare(new double[0]), Is.NaN); Assert.That(Statistics.RootMeanSquare(new[] { 2d }), Is.Not.NaN); Assert.That(ArrayStatistics.RootMeanSquare(new double[0]), Is.NaN); Assert.That(ArrayStatistics.RootMeanSquare(new[] { 2d }), Is.Not.NaN); Assert.That(StreamingStatistics.RootMeanSquare(new double[0]), Is.NaN); Assert.That(StreamingStatistics.RootMeanSquare(new[] { 2d }), Is.Not.NaN); } [Test] public void SampleVarianceOfEmptyAndSingleMustBeNaN() { Assert.That(Statistics.Variance(new double[0]), Is.NaN); Assert.That(Statistics.Variance(new[] { 2d }), Is.NaN); Assert.That(Statistics.Variance(new[] { 2d, 3d }), Is.Not.NaN); Assert.That(ArrayStatistics.Variance(new double[0]), Is.NaN); Assert.That(ArrayStatistics.Variance(new[] { 2d }), Is.NaN); Assert.That(ArrayStatistics.Variance(new[] { 2d, 3d }), Is.Not.NaN); Assert.That(StreamingStatistics.Variance(new double[0]), Is.NaN); Assert.That(StreamingStatistics.Variance(new[] { 2d }), Is.NaN); Assert.That(StreamingStatistics.Variance(new[] { 2d, 3d }), Is.Not.NaN); Assert.That(new RunningStatistics(new[] { 2d }).Variance, Is.NaN); Assert.That(new RunningStatistics(new[] { 2d, 3d }).Variance, Is.Not.NaN); } [Test] public void PopulationVarianceOfEmptyMustBeNaN() { Assert.That(Statistics.PopulationVariance(new double[0]), Is.NaN); Assert.That(Statistics.PopulationVariance(new[] { 2d }), Is.Not.NaN); Assert.That(Statistics.PopulationVariance(new[] { 2d, 3d }), Is.Not.NaN); Assert.That(ArrayStatistics.PopulationVariance(new double[0]), Is.NaN); Assert.That(ArrayStatistics.PopulationVariance(new[] { 2d }), Is.Not.NaN); Assert.That(ArrayStatistics.PopulationVariance(new[] { 2d, 3d }), Is.Not.NaN); Assert.That(StreamingStatistics.PopulationVariance(new double[0]), Is.NaN); Assert.That(StreamingStatistics.PopulationVariance(new[] { 2d }), Is.Not.NaN); Assert.That(StreamingStatistics.PopulationVariance(new[] { 2d, 3d }), Is.Not.NaN); Assert.That(new RunningStatistics(new[] { 2d }).PopulationVariance, Is.NaN); Assert.That(new RunningStatistics(new[] { 2d, 3d }).PopulationVariance, Is.Not.NaN); } /// <summary> /// URL http://mathnetnumerics.codeplex.com/workitem/5667 /// </summary> [Test] public void Median_CodeplexIssue5667() { var seq = Data.ReadAllLines("Codeplex-5667.csv").Select(double.Parse); Assert.AreEqual(1.0, Statistics.Median(seq)); var array = seq.ToArray(); Assert.AreEqual(1.0, ArrayStatistics.MedianInplace(array)); Array.Sort(array); Assert.AreEqual(1.0, SortedArrayStatistics.Median(array)); } [Test] public void VarianceDenominatorMustNotOverflow_GitHubIssue137() { var a = new double[46342]; a[a.Length - 1] = 1000d; Assert.AreEqual(21.578697, a.Variance(), 1e-5); Assert.AreEqual(21.578231, a.PopulationVariance(), 1e-5); Assert.AreEqual(21.578697, new RunningStatistics(a).Variance, 1e-5); Assert.AreEqual(21.578231, new RunningStatistics(a).PopulationVariance, 1e-5); } [Test] public void MedianIsRobustOnCloseInfinities() { Assert.That(Statistics.Median(new[] { 2.0, double.NegativeInfinity, double.PositiveInfinity }), Is.EqualTo(2.0)); Assert.That(Statistics.Median(new[] { 2.0, double.NegativeInfinity, 3.0, double.PositiveInfinity }), Is.EqualTo(2.5)); Assert.That(ArrayStatistics.MedianInplace(new[] { 2.0, double.NegativeInfinity, double.PositiveInfinity }), Is.EqualTo(2.0)); Assert.That(ArrayStatistics.MedianInplace(new[] { double.NegativeInfinity, 2.0, double.PositiveInfinity }), Is.EqualTo(2.0)); Assert.That(ArrayStatistics.MedianInplace(new[] { double.NegativeInfinity, double.PositiveInfinity, 2.0 }), Is.EqualTo(2.0)); Assert.That(ArrayStatistics.MedianInplace(new[] { double.NegativeInfinity, 2.0, 3.0, double.PositiveInfinity }), Is.EqualTo(2.5)); Assert.That(ArrayStatistics.MedianInplace(new[] { double.NegativeInfinity, 2.0, double.PositiveInfinity, 3.0 }), Is.EqualTo(2.5)); Assert.That(SortedArrayStatistics.Median(new[] { double.NegativeInfinity, 2.0, double.PositiveInfinity }), Is.EqualTo(2.0)); Assert.That(SortedArrayStatistics.Median(new[] { double.NegativeInfinity, 2.0, 3.0, double.PositiveInfinity }), Is.EqualTo(2.5)); } [Test] public void RobustOnLargeSampleSets() { // 0, 0.25, 0.5, 0.75, 0, 0.25, 0.5, 0.75, ... var shorter = Generate.Periodic(4*4096, 4, 1); var longer = Generate.Periodic(4*32768, 4, 1); Assert.That(Statistics.Mean(shorter), Is.EqualTo(0.375).Within(1e-14), "Statistics.Mean: shorter"); Assert.That(Statistics.Mean(longer), Is.EqualTo(0.375).Within(1e-14), "Statistics.Mean: longer"); Assert.That(new DescriptiveStatistics(shorter).Mean, Is.EqualTo(0.375).Within(1e-14), "DescriptiveStatistics.Mean: shorter"); Assert.That(new DescriptiveStatistics(longer).Mean, Is.EqualTo(00.375).Within(1e-14), "DescriptiveStatistics.Mean: longer"); Assert.That(Statistics.RootMeanSquare(shorter), Is.EqualTo(Math.Sqrt(0.21875)).Within(1e-14), "Statistics.RootMeanSquare: shorter"); Assert.That(Statistics.RootMeanSquare(longer), Is.EqualTo(Math.Sqrt(0.21875)).Within(1e-14), "Statistics.RootMeanSquare: longer"); Assert.That(Statistics.Skewness(shorter), Is.EqualTo(0.0).Within(1e-12), "Statistics.Skewness: shorter"); Assert.That(Statistics.Skewness(longer), Is.EqualTo(0.0).Within(1e-12), "Statistics.Skewness: longer"); Assert.That(new DescriptiveStatistics(shorter).Skewness, Is.EqualTo(0.0).Within(1e-12), "DescriptiveStatistics.Skewness: shorter"); Assert.That(new DescriptiveStatistics(longer).Skewness, Is.EqualTo(0.0).Within(1e-12), "DescriptiveStatistics.Skewness: longer"); Assert.That(Statistics.Kurtosis(shorter), Is.EqualTo(-1.36).Within(1e-4), "Statistics.Kurtosis: shorter"); Assert.That(Statistics.Kurtosis(longer), Is.EqualTo(-1.36).Within(1e-4), "Statistics.Kurtosis: longer"); Assert.That(new DescriptiveStatistics(shorter).Kurtosis, Is.EqualTo(-1.36).Within(1e-4), "DescriptiveStatistics.Kurtosis: shorter"); Assert.That(new DescriptiveStatistics(longer).Kurtosis, Is.EqualTo(-1.36).Within(1e-4), "DescriptiveStatistics.Kurtosis: longer"); } [Test] public void RootMeanSquareOfSinusoidal() { var data = Generate.Sinusoidal(128, 64, 16, 2.0); Assert.That(Statistics.RootMeanSquare(data), Is.EqualTo(2.0/Constants.Sqrt2).Within(1e-12)); } [Test] public void EntropyIsMinimum() { var data1 = new double[] { 1, 1, 1, 1, 1 }; Assert.That(StreamingStatistics.Entropy(data1) == 0); var data2 = new double[] { 0, 0 }; Assert.That(StreamingStatistics.Entropy(data2) == 0); } [Test] public void EntropyIsMaximum() { var data1 = new double[] { 1, 2 }; Assert.That(StreamingStatistics.Entropy(data1) == 1.0); var data2 = new double[] { 1, 2, 3, 4 }; Assert.That(StreamingStatistics.Entropy(data2) == 2.0); } [Test] public void EntropyOfNaNIsNaN() { var data = new double[] { 1, 2, double.NaN }; Assert.That(double.IsNaN(StreamingStatistics.Entropy(data))); } [Test] public void MinimumMagnitudePhase() { var a = new[] { new Complex32(1.0f, 2.0f), new Complex32(float.PositiveInfinity, float.NegativeInfinity), new Complex32(-2.0f, 4.0f) }; Assert.That(ArrayStatistics.MinimumMagnitudePhase(a), Is.EqualTo(a[0])); } [Test] public void MinimumMagnitudePhaseOfNaNIsNaN() { var a = new[] { new Complex32(1.0f, 2.0f), new Complex32(float.NaN, float.NegativeInfinity), new Complex32(-2.0f, 4.0f) }; Assert.That(ArrayStatistics.MinimumMagnitudePhase(a).IsNaN(), Is.True); } [Test] public void MaximumMagnitudePhase() { var a = new[] { new Complex32(1.0f, 2.0f), new Complex32(float.PositiveInfinity, float.NegativeInfinity), new Complex32(-2.0f, 4.0f) }; Assert.That(ArrayStatistics.MaximumMagnitudePhase(a), Is.EqualTo(a[1])); } [Test] public void MaximumMagnitudePhaseOfNaNIsNaN() { var a = new[] { new Complex32(1.0f, 2.0f), new Complex32(float.NaN, float.NegativeInfinity), new Complex32(-2.0f, 4.0f) }; Assert.That(ArrayStatistics.MaximumMagnitudePhase(a).IsNaN(), Is.True); } } } // ReSharper restore InvokeAsExtensionMethod
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using 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.V9.Services { /// <summary>Settings for <see cref="PaymentsAccountServiceClient"/> instances.</summary> public sealed partial class PaymentsAccountServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="PaymentsAccountServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="PaymentsAccountServiceSettings"/>.</returns> public static PaymentsAccountServiceSettings GetDefault() => new PaymentsAccountServiceSettings(); /// <summary> /// Constructs a new <see cref="PaymentsAccountServiceSettings"/> object with default settings. /// </summary> public PaymentsAccountServiceSettings() { } private PaymentsAccountServiceSettings(PaymentsAccountServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); ListPaymentsAccountsSettings = existing.ListPaymentsAccountsSettings; OnCopy(existing); } partial void OnCopy(PaymentsAccountServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>PaymentsAccountServiceClient.ListPaymentsAccounts</c> and /// <c>PaymentsAccountServiceClient.ListPaymentsAccountsAsync</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 ListPaymentsAccountsSettings { 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="PaymentsAccountServiceSettings"/> object.</returns> public PaymentsAccountServiceSettings Clone() => new PaymentsAccountServiceSettings(this); } /// <summary> /// Builder class for <see cref="PaymentsAccountServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class PaymentsAccountServiceClientBuilder : gaxgrpc::ClientBuilderBase<PaymentsAccountServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public PaymentsAccountServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public PaymentsAccountServiceClientBuilder() { UseJwtAccessWithScopes = PaymentsAccountServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref PaymentsAccountServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<PaymentsAccountServiceClient> task); /// <summary>Builds the resulting client.</summary> public override PaymentsAccountServiceClient Build() { PaymentsAccountServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<PaymentsAccountServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<PaymentsAccountServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private PaymentsAccountServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return PaymentsAccountServiceClient.Create(callInvoker, Settings); } private async stt::Task<PaymentsAccountServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return PaymentsAccountServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => PaymentsAccountServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => PaymentsAccountServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => PaymentsAccountServiceClient.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>PaymentsAccountService client wrapper, for convenient use.</summary> /// <remarks> /// Service to provide payments accounts that can be used to set up consolidated /// billing. /// </remarks> public abstract partial class PaymentsAccountServiceClient { /// <summary> /// The default endpoint for the PaymentsAccountService 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 PaymentsAccountService scopes.</summary> /// <remarks> /// The default PaymentsAccountService 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="PaymentsAccountServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="PaymentsAccountServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="PaymentsAccountServiceClient"/>.</returns> public static stt::Task<PaymentsAccountServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new PaymentsAccountServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="PaymentsAccountServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="PaymentsAccountServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="PaymentsAccountServiceClient"/>.</returns> public static PaymentsAccountServiceClient Create() => new PaymentsAccountServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="PaymentsAccountServiceClient"/> 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="PaymentsAccountServiceSettings"/>.</param> /// <returns>The created <see cref="PaymentsAccountServiceClient"/>.</returns> internal static PaymentsAccountServiceClient Create(grpccore::CallInvoker callInvoker, PaymentsAccountServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } PaymentsAccountService.PaymentsAccountServiceClient grpcClient = new PaymentsAccountService.PaymentsAccountServiceClient(callInvoker); return new PaymentsAccountServiceClientImpl(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 PaymentsAccountService client</summary> public virtual PaymentsAccountService.PaymentsAccountServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns all payments accounts associated with all managers /// between the login customer ID and specified serving customer in the /// hierarchy, inclusive. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [PaymentsAccountError]() /// [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 ListPaymentsAccountsResponse ListPaymentsAccounts(ListPaymentsAccountsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns all payments accounts associated with all managers /// between the login customer ID and specified serving customer in the /// hierarchy, inclusive. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [PaymentsAccountError]() /// [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<ListPaymentsAccountsResponse> ListPaymentsAccountsAsync(ListPaymentsAccountsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns all payments accounts associated with all managers /// between the login customer ID and specified serving customer in the /// hierarchy, inclusive. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [PaymentsAccountError]() /// [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<ListPaymentsAccountsResponse> ListPaymentsAccountsAsync(ListPaymentsAccountsRequest request, st::CancellationToken cancellationToken) => ListPaymentsAccountsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns all payments accounts associated with all managers /// between the login customer ID and specified serving customer in the /// hierarchy, inclusive. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [PaymentsAccountError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer to apply the PaymentsAccount list operation to. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual ListPaymentsAccountsResponse ListPaymentsAccounts(string customerId, gaxgrpc::CallSettings callSettings = null) => ListPaymentsAccounts(new ListPaymentsAccountsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), }, callSettings); /// <summary> /// Returns all payments accounts associated with all managers /// between the login customer ID and specified serving customer in the /// hierarchy, inclusive. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [PaymentsAccountError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer to apply the PaymentsAccount list operation to. /// </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<ListPaymentsAccountsResponse> ListPaymentsAccountsAsync(string customerId, gaxgrpc::CallSettings callSettings = null) => ListPaymentsAccountsAsync(new ListPaymentsAccountsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), }, callSettings); /// <summary> /// Returns all payments accounts associated with all managers /// between the login customer ID and specified serving customer in the /// hierarchy, inclusive. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [PaymentsAccountError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer to apply the PaymentsAccount list operation to. /// </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<ListPaymentsAccountsResponse> ListPaymentsAccountsAsync(string customerId, st::CancellationToken cancellationToken) => ListPaymentsAccountsAsync(customerId, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>PaymentsAccountService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to provide payments accounts that can be used to set up consolidated /// billing. /// </remarks> public sealed partial class PaymentsAccountServiceClientImpl : PaymentsAccountServiceClient { private readonly gaxgrpc::ApiCall<ListPaymentsAccountsRequest, ListPaymentsAccountsResponse> _callListPaymentsAccounts; /// <summary> /// Constructs a client wrapper for the PaymentsAccountService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="PaymentsAccountServiceSettings"/> used within this client. /// </param> public PaymentsAccountServiceClientImpl(PaymentsAccountService.PaymentsAccountServiceClient grpcClient, PaymentsAccountServiceSettings settings) { GrpcClient = grpcClient; PaymentsAccountServiceSettings effectiveSettings = settings ?? PaymentsAccountServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callListPaymentsAccounts = clientHelper.BuildApiCall<ListPaymentsAccountsRequest, ListPaymentsAccountsResponse>(grpcClient.ListPaymentsAccountsAsync, grpcClient.ListPaymentsAccounts, effectiveSettings.ListPaymentsAccountsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callListPaymentsAccounts); Modify_ListPaymentsAccountsApiCall(ref _callListPaymentsAccounts); 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_ListPaymentsAccountsApiCall(ref gaxgrpc::ApiCall<ListPaymentsAccountsRequest, ListPaymentsAccountsResponse> call); partial void OnConstruction(PaymentsAccountService.PaymentsAccountServiceClient grpcClient, PaymentsAccountServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC PaymentsAccountService client</summary> public override PaymentsAccountService.PaymentsAccountServiceClient GrpcClient { get; } partial void Modify_ListPaymentsAccountsRequest(ref ListPaymentsAccountsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns all payments accounts associated with all managers /// between the login customer ID and specified serving customer in the /// hierarchy, inclusive. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [PaymentsAccountError]() /// [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 ListPaymentsAccountsResponse ListPaymentsAccounts(ListPaymentsAccountsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListPaymentsAccountsRequest(ref request, ref callSettings); return _callListPaymentsAccounts.Sync(request, callSettings); } /// <summary> /// Returns all payments accounts associated with all managers /// between the login customer ID and specified serving customer in the /// hierarchy, inclusive. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [PaymentsAccountError]() /// [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<ListPaymentsAccountsResponse> ListPaymentsAccountsAsync(ListPaymentsAccountsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListPaymentsAccountsRequest(ref request, ref callSettings); return _callListPaymentsAccounts.Async(request, callSettings); } } }
// // 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.Subscriptions.Csm { 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); } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Linq; using NodaTime; using QuantConnect.Securities; namespace QuantConnect.Scheduling { /// <summary> /// Provides a builder class to allow for fluent syntax when constructing new events /// </summary> /// <remarks> /// This builder follows the following steps for event creation: /// /// 1. Specify an event name (optional) /// 2. Specify an IDateRule /// 3. Specify an ITimeRule /// a. repeat 3. to define extra time rules (optional) /// 4. Specify additional where clause (optional) /// 5. Register event via call to Run /// </remarks> public class FluentScheduledEventBuilder : IFluentSchedulingDateSpecifier, IFluentSchedulingRunnable { private IDateRule _dateRule; private ITimeRule _timeRule; private Func<DateTime, bool> _predicate; private readonly string _name; private readonly ScheduleManager _schedule; private readonly SecurityManager _securities; /// <summary> /// Initializes a new instance of the <see cref="FluentScheduledEventBuilder"/> class /// </summary> /// <param name="schedule">The schedule to send created events to</param> /// <param name="securities">The algorithm's security manager</param> /// <param name="name">A specific name for this event</param> public FluentScheduledEventBuilder(ScheduleManager schedule, SecurityManager securities, string name = null) { _name = name; _schedule = schedule; _securities = securities; } private FluentScheduledEventBuilder SetTimeRule(ITimeRule rule) { // if it's not set, just set it if (_timeRule == null) { _timeRule = rule; return this; } // if it's already a composite, open it up and make a new composite // prevent nesting composites var compositeTimeRule = _timeRule as CompositeTimeRule; if (compositeTimeRule != null) { var rules = compositeTimeRule.Rules; _timeRule = new CompositeTimeRule(rules.Concat(new[] { rule })); return this; } // create a composite from the existing rule and the new rules _timeRule = new CompositeTimeRule(_timeRule, rule); return this; } #region DateRules and TimeRules delegation /// <summary> /// Creates events on each of the specified day of week /// </summary> IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.Every(params DayOfWeek[] days) { _dateRule = _schedule.DateRules.Every(days); return this; } /// <summary> /// Creates events on every day of the year /// </summary> IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.EveryDay() { _dateRule = _schedule.DateRules.EveryDay(); return this; } /// <summary> /// Creates events on every trading day of the year for the symbol /// </summary> IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.EveryDay(Symbol symbol) { _dateRule = _schedule.DateRules.EveryDay(symbol); return this; } /// <summary> /// Creates events on the first day of the month /// </summary> IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.MonthStart() { _dateRule = _schedule.DateRules.MonthStart(); return this; } /// <summary> /// Creates events on the first trading day of the month /// </summary> IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.MonthStart(Symbol symbol) { _dateRule = _schedule.DateRules.MonthStart(symbol); return this; } /// <summary> /// Filters the event times using the predicate /// </summary> IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.Where(Func<DateTime, bool> predicate) { _predicate = _predicate == null ? predicate : (time => _predicate(time) && predicate(time)); return this; } /// <summary> /// Creates events that fire at the specific time of day in the algorithm's time zone /// </summary> IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.At(TimeSpan timeOfDay) { return SetTimeRule(_schedule.TimeRules.At(timeOfDay)); } /// <summary> /// Creates events that fire a specified number of minutes after market open /// </summary> IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.AfterMarketOpen(Symbol symbol, double minutesAfterOpen, bool extendedMarketOpen) { return SetTimeRule(_schedule.TimeRules.AfterMarketOpen(symbol, minutesAfterOpen, extendedMarketOpen)); } /// <summary> /// Creates events that fire a specified numer of minutes before market close /// </summary> IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.BeforeMarketClose(Symbol symbol, double minuteBeforeClose, bool extendedMarketClose) { return SetTimeRule(_schedule.TimeRules.BeforeMarketClose(symbol, minuteBeforeClose, extendedMarketClose)); } /// <summary> /// Creates events that fire on a period define by the specified interval /// </summary> IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.Every(TimeSpan interval) { return SetTimeRule(_schedule.TimeRules.Every(interval)); } /// <summary> /// Filters the event times using the predicate /// </summary> IFluentSchedulingTimeSpecifier IFluentSchedulingTimeSpecifier.Where(Func<DateTime, bool> predicate) { _predicate = _predicate == null ? predicate : (time => _predicate(time) && predicate(time)); return this; } /// <summary> /// Register the defined event with the callback /// </summary> ScheduledEvent IFluentSchedulingRunnable.Run(Action callback) { return ((IFluentSchedulingRunnable)this).Run((name, time) => callback()); } /// <summary> /// Register the defined event with the callback /// </summary> ScheduledEvent IFluentSchedulingRunnable.Run(Action<DateTime> callback) { return ((IFluentSchedulingRunnable)this).Run((name, time) => callback(time)); } /// <summary> /// Register the defined event with the callback /// </summary> ScheduledEvent IFluentSchedulingRunnable.Run(Action<string, DateTime> callback) { var name = _name ?? _dateRule.Name + ": " + _timeRule.Name; // back the date up to ensure we get all events, the event scheduler will skip past events that whose time has passed var dates = _dateRule.GetDates(_securities.UtcTime.Date.AddDays(-1), Time.EndOfTime); var eventTimes = _timeRule.CreateUtcEventTimes(dates); if (_predicate != null) { eventTimes = eventTimes.Where(_predicate); } var scheduledEvent = new ScheduledEvent(name, eventTimes, callback); _schedule.Add(scheduledEvent); return scheduledEvent; } /// <summary> /// Filters the event times using the predicate /// </summary> IFluentSchedulingRunnable IFluentSchedulingRunnable.Where(Func<DateTime, bool> predicate) { _predicate = _predicate == null ? predicate : (time => _predicate(time) && predicate(time)); return this; } /// <summary> /// Filters the event times to only include times where the symbol's market is considered open /// </summary> IFluentSchedulingRunnable IFluentSchedulingRunnable.DuringMarketHours(Symbol symbol, bool extendedMarket) { var security = GetSecurity(symbol); Func<DateTime, bool> predicate = time => { var localTime = time.ConvertFromUtc(security.Exchange.TimeZone); return security.Exchange.IsOpenDuringBar(localTime, localTime, extendedMarket); }; _predicate = _predicate == null ? predicate : (time => _predicate(time) && predicate(time)); return this; } IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.On(int year, int month, int day) { _dateRule = _schedule.DateRules.On(year, month, day); return this; } IFluentSchedulingTimeSpecifier IFluentSchedulingDateSpecifier.On(params DateTime[] dates) { _dateRule = _schedule.DateRules.On(dates); return this; } IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.At(int hour, int minute, int second) { return SetTimeRule(_schedule.TimeRules.At(hour, minute, second)); } IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.At(int hour, int minute, DateTimeZone timeZone) { return SetTimeRule(_schedule.TimeRules.At(hour, minute, 0, timeZone)); } IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.At(int hour, int minute, int second, DateTimeZone timeZone) { return SetTimeRule(_schedule.TimeRules.At(hour, minute, second, timeZone)); } IFluentSchedulingRunnable IFluentSchedulingTimeSpecifier.At(TimeSpan timeOfDay, DateTimeZone timeZone) { return SetTimeRule(_schedule.TimeRules.At(timeOfDay, timeZone)); } private Security GetSecurity(Symbol symbol) { Security security; if (!_securities.TryGetValue(symbol, out security)) { throw new Exception(symbol.SID + " not found in portfolio. Request this data when initializing the algorithm."); } return security; } #endregion } /// <summary> /// Specifies the date rule component of a scheduled event /// </summary> public interface IFluentSchedulingDateSpecifier { /// <summary> /// Filters the event times using the predicate /// </summary> IFluentSchedulingTimeSpecifier Where(Func<DateTime, bool> predicate); /// <summary> /// Creates events only on the specified date /// </summary> IFluentSchedulingTimeSpecifier On(int year, int month, int day); /// <summary> /// Creates events only on the specified dates /// </summary> IFluentSchedulingTimeSpecifier On(params DateTime[] dates); /// <summary> /// Creates events on each of the specified day of week /// </summary> IFluentSchedulingTimeSpecifier Every(params DayOfWeek[] days); /// <summary> /// Creates events on every day of the year /// </summary> IFluentSchedulingTimeSpecifier EveryDay(); /// <summary> /// Creates events on every trading day of the year for the symbol /// </summary> IFluentSchedulingTimeSpecifier EveryDay(Symbol symbol); /// <summary> /// Creates events on the first day of the month /// </summary> IFluentSchedulingTimeSpecifier MonthStart(); /// <summary> /// Creates events on the first trading day of the month /// </summary> IFluentSchedulingTimeSpecifier MonthStart(Symbol symbol); } /// <summary> /// Specifies the time rule component of a scheduled event /// </summary> public interface IFluentSchedulingTimeSpecifier { /// <summary> /// Filters the event times using the predicate /// </summary> IFluentSchedulingTimeSpecifier Where(Func<DateTime, bool> predicate); /// <summary> /// Creates events that fire at the specified time of day in the specified time zone /// </summary> IFluentSchedulingRunnable At(int hour, int minute, int second = 0); /// <summary> /// Creates events that fire at the specified time of day in the specified time zone /// </summary> IFluentSchedulingRunnable At(int hour, int minute, DateTimeZone timeZone); /// <summary> /// Creates events that fire at the specified time of day in the specified time zone /// </summary> IFluentSchedulingRunnable At(int hour, int minute, int second, DateTimeZone timeZone); /// <summary> /// Creates events that fire at the specified time of day in the specified time zone /// </summary> IFluentSchedulingRunnable At(TimeSpan timeOfDay, DateTimeZone timeZone); /// <summary> /// Creates events that fire at the specific time of day in the algorithm's time zone /// </summary> IFluentSchedulingRunnable At(TimeSpan timeOfDay); /// <summary> /// Creates events that fire on a period define by the specified interval /// </summary> IFluentSchedulingRunnable Every(TimeSpan interval); /// <summary> /// Creates events that fire a specified number of minutes after market open /// </summary> IFluentSchedulingRunnable AfterMarketOpen(Symbol symbol, double minutesAfterOpen = 0, bool extendedMarketOpen = false); /// <summary> /// Creates events that fire a specified numer of minutes before market close /// </summary> IFluentSchedulingRunnable BeforeMarketClose(Symbol symbol, double minuteBeforeClose = 0, bool extendedMarketClose = false); } /// <summary> /// Specifies the callback component of a scheduled event, as well as final filters /// </summary> public interface IFluentSchedulingRunnable : IFluentSchedulingTimeSpecifier { /// <summary> /// Filters the event times using the predicate /// </summary> new IFluentSchedulingRunnable Where(Func<DateTime, bool> predicate); /// <summary> /// Filters the event times to only include times where the symbol's market is considered open /// </summary> IFluentSchedulingRunnable DuringMarketHours(Symbol symbol, bool extendedMarket = false); /// <summary> /// Register the defined event with the callback /// </summary> ScheduledEvent Run(Action callback); /// <summary> /// Register the defined event with the callback /// </summary> ScheduledEvent Run(Action<DateTime> callback); /// <summary> /// Register the defined event with the callback /// </summary> ScheduledEvent Run(Action<string, DateTime> callback); } }
using System; using System.Collections.Generic; using SharpKit.JavaScript; namespace SharpKit.NodeJs.net { /// <summary> /// <p>This object is an abstraction of a TCP or UNIX socket. <code>net.Socket</code> /// instances implement a duplex Stream interface. They can be created by the /// user and used as a client (with <code>connect()</code>) or they can be created by Node /// and passed to the user through the <code>&#39;connection&#39;</code> event of a server. /// </p> /// </summary> public partial class Socket { public Socket() { } /// <summary> /// <p>Construct a new socket object. /// </p> /// <p><code>options</code> is an object with the following defaults: /// </p> /// <pre><code>{ fd: null /// type: null /// allowHalfOpen: false /// }</code></pre> /// <p><code>fd</code> allows you to specify the existing file descriptor of socket. <code>type</code> /// specified underlying protocol. It can be <code>&#39;tcp4&#39;</code>, <code>&#39;tcp6&#39;</code>, or <code>&#39;unix&#39;</code>. /// About <code>allowHalfOpen</code>, refer to <code>createServer()</code> and <code>&#39;end&#39;</code> event. /// </p> /// </summary> public Socket(SocketOptions options) { } /// <summary> /// <p>Returns the bound address, the address family name and port of the /// socket as reported by the operating system. Returns an object with /// three properties, e.g. /// <code>{ port: 12346, family: &#39;IPv4&#39;, address: &#39;127.0.0.1&#39; }</code> /// </p> /// </summary> public object address() { return null; } /// <summary> /// <p>Opens the connection for a given socket. If <code>port</code> and <code>host</code> are given, /// then the socket will be opened as a TCP socket, if <code>host</code> is omitted, /// <code>localhost</code> will be assumed. If a <code>path</code> is given, the socket will be /// opened as a unix socket to that path. /// </p> /// <p>Normally this method is not needed, as <code>net.createConnection</code> opens the /// socket. Use this only if you are implementing a custom Socket or if a /// Socket is closed and you want to reuse it to connect to another server. /// </p> /// <p>This function is asynchronous. When the [&#39;connect&#39;][] event is emitted the /// socket is established. If there is a problem connecting, the <code>&#39;connect&#39;</code> event /// will not be emitted, the <code>&#39;error&#39;</code> event will be emitted with the exception. /// </p> /// <p>The <code>connectListener</code> parameter will be added as an listener for the /// [&#39;connect&#39;][] event. /// </p> /// </summary> public object connect(object path) { return null; } /// <summary> /// <p>Opens the connection for a given socket. If <code>port</code> and <code>host</code> are given, /// then the socket will be opened as a TCP socket, if <code>host</code> is omitted, /// <code>localhost</code> will be assumed. If a <code>path</code> is given, the socket will be /// opened as a unix socket to that path. /// </p> /// <p>Normally this method is not needed, as <code>net.createConnection</code> opens the /// socket. Use this only if you are implementing a custom Socket or if a /// Socket is closed and you want to reuse it to connect to another server. /// </p> /// <p>This function is asynchronous. When the [&#39;connect&#39;][] event is emitted the /// socket is established. If there is a problem connecting, the <code>&#39;connect&#39;</code> event /// will not be emitted, the <code>&#39;error&#39;</code> event will be emitted with the exception. /// </p> /// <p>The <code>connectListener</code> parameter will be added as an listener for the /// [&#39;connect&#39;][] event. /// </p> /// </summary> public object connect(object path, object connectListener) { return null; } /// <summary> /// <p>Opens the connection for a given socket. If <code>port</code> and <code>host</code> are given, /// then the socket will be opened as a TCP socket, if <code>host</code> is omitted, /// <code>localhost</code> will be assumed. If a <code>path</code> is given, the socket will be /// opened as a unix socket to that path. /// </p> /// <p>Normally this method is not needed, as <code>net.createConnection</code> opens the /// socket. Use this only if you are implementing a custom Socket or if a /// Socket is closed and you want to reuse it to connect to another server. /// </p> /// <p>This function is asynchronous. When the [&#39;connect&#39;][] event is emitted the /// socket is established. If there is a problem connecting, the <code>&#39;connect&#39;</code> event /// will not be emitted, the <code>&#39;error&#39;</code> event will be emitted with the exception. /// </p> /// <p>The <code>connectListener</code> parameter will be added as an listener for the /// [&#39;connect&#39;][] event. /// </p> /// </summary> public object connect(object port, object host, object connectListener) { return null; } /// <summary> /// <p>Ensures that no more I/O activity happens on this socket. Only necessary in /// case of errors (parse error or so). /// </p> /// </summary> public object destroy() { return null; } /// <summary> /// <p>Half-closes the socket. i.e., it sends a FIN packet. It is possible the /// server will still send some data. /// </p> /// <p>If <code>data</code> is specified, it is equivalent to calling /// <code>socket.write(data, encoding)</code> followed by <code>socket.end()</code>. /// </p> /// </summary> public object end() { return null; } /// <summary> /// <p>Half-closes the socket. i.e., it sends a FIN packet. It is possible the /// server will still send some data. /// </p> /// <p>If <code>data</code> is specified, it is equivalent to calling /// <code>socket.write(data, encoding)</code> followed by <code>socket.end()</code>. /// </p> /// </summary> public object end(object encoding) { return null; } /// <summary> /// <p>Half-closes the socket. i.e., it sends a FIN packet. It is possible the /// server will still send some data. /// </p> /// <p>If <code>data</code> is specified, it is equivalent to calling /// <code>socket.write(data, encoding)</code> followed by <code>socket.end()</code>. /// </p> /// </summary> public object end(object data, object encoding) { return null; } /// <summary> /// <p>Pauses the reading of data. That is, <code>&#39;data&#39;</code> events will not be emitted. /// Useful to throttle back an upload. /// </p> /// </summary> public object pause() { return null; } /// <summary> /// <p>Resumes reading after a call to <code>pause()</code>. /// </p> /// </summary> public object resume() { return null; } /// <summary> /// <p>Set the encoding for the socket as a Readable Stream. See /// [stream.setEncoding()][] for more information. /// </p> /// </summary> public object setEncoding() { return null; } /// <summary> /// <p>Set the encoding for the socket as a Readable Stream. See /// [stream.setEncoding()][] for more information. /// </p> /// </summary> public object setEncoding(object encoding) { return null; } /// <summary> /// <p>Enable/disable keep-alive functionality, and optionally set the initial /// delay before the first keepalive probe is sent on an idle socket. /// <code>enable</code> defaults to <code>false</code>. /// </p> /// <p>Set <code>initialDelay</code> (in milliseconds) to set the delay between the last /// data packet received and the first keepalive probe. Setting 0 for /// initialDelay will leave the value unchanged from the default /// (or previous) setting. Defaults to <code>0</code>. /// </p> /// </summary> public object setKeepAlive() { return null; } /// <summary> /// <p>Enable/disable keep-alive functionality, and optionally set the initial /// delay before the first keepalive probe is sent on an idle socket. /// <code>enable</code> defaults to <code>false</code>. /// </p> /// <p>Set <code>initialDelay</code> (in milliseconds) to set the delay between the last /// data packet received and the first keepalive probe. Setting 0 for /// initialDelay will leave the value unchanged from the default /// (or previous) setting. Defaults to <code>0</code>. /// </p> /// </summary> public object setKeepAlive(object initialDelay) { return null; } /// <summary> /// <p>Enable/disable keep-alive functionality, and optionally set the initial /// delay before the first keepalive probe is sent on an idle socket. /// <code>enable</code> defaults to <code>false</code>. /// </p> /// <p>Set <code>initialDelay</code> (in milliseconds) to set the delay between the last /// data packet received and the first keepalive probe. Setting 0 for /// initialDelay will leave the value unchanged from the default /// (or previous) setting. Defaults to <code>0</code>. /// </p> /// </summary> public object setKeepAlive(bool enable, object initialDelay) { return null; } /// <summary> /// <p>Disables the Nagle algorithm. By default TCP connections use the Nagle /// algorithm, they buffer data before sending it off. Setting <code>true</code> for /// <code>noDelay</code> will immediately fire off data each time <code>socket.write()</code> is called. /// <code>noDelay</code> defaults to <code>true</code>. /// </p> /// </summary> public object setNoDelay() { return null; } /// <summary> /// <p>Disables the Nagle algorithm. By default TCP connections use the Nagle /// algorithm, they buffer data before sending it off. Setting <code>true</code> for /// <code>noDelay</code> will immediately fire off data each time <code>socket.write()</code> is called. /// <code>noDelay</code> defaults to <code>true</code>. /// </p> /// </summary> public object setNoDelay(bool noDelay) { return null; } /// <summary> /// <p>Sets the socket to timeout after <code>timeout</code> milliseconds of inactivity on /// the socket. By default <code>net.Socket</code> do not have a timeout. /// </p> /// <p>When an idle timeout is triggered the socket will receive a <code>&#39;timeout&#39;</code> /// event but the connection will not be severed. The user must manually <code>end()</code> /// or <code>destroy()</code> the socket. /// </p> /// <p>If <code>timeout</code> is 0, then the existing idle timeout is disabled. /// </p> /// <p>The optional <code>callback</code> parameter will be added as a one time listener for the /// <code>&#39;timeout&#39;</code> event. /// </p> /// </summary> public object setTimeout(object timeout) { return null; } /// <summary> /// <p>Sets the socket to timeout after <code>timeout</code> milliseconds of inactivity on /// the socket. By default <code>net.Socket</code> do not have a timeout. /// </p> /// <p>When an idle timeout is triggered the socket will receive a <code>&#39;timeout&#39;</code> /// event but the connection will not be severed. The user must manually <code>end()</code> /// or <code>destroy()</code> the socket. /// </p> /// <p>If <code>timeout</code> is 0, then the existing idle timeout is disabled. /// </p> /// <p>The optional <code>callback</code> parameter will be added as a one time listener for the /// <code>&#39;timeout&#39;</code> event. /// </p> /// </summary> public object setTimeout(object timeout, JsAction callback) { return null; } /// <summary> /// <p>Sends data on the socket. The second parameter specifies the encoding in the /// case of a string--it defaults to UTF8 encoding. /// </p> /// <p>Returns <code>true</code> if the entire data was flushed successfully to the kernel /// buffer. Returns <code>false</code> if all or part of the data was queued in user memory. /// <code>&#39;drain&#39;</code> will be emitted when the buffer is again free. /// </p> /// <p>The optional <code>callback</code> parameter will be executed when the data is finally /// written out - this may not be immediately. /// </p> /// </summary> public bool write(object data) { return false; } /// <summary> /// <p>Sends data on the socket. The second parameter specifies the encoding in the /// case of a string--it defaults to UTF8 encoding. /// </p> /// <p>Returns <code>true</code> if the entire data was flushed successfully to the kernel /// buffer. Returns <code>false</code> if all or part of the data was queued in user memory. /// <code>&#39;drain&#39;</code> will be emitted when the buffer is again free. /// </p> /// <p>The optional <code>callback</code> parameter will be executed when the data is finally /// written out - this may not be immediately. /// </p> /// </summary> public bool write(object data, object callback) { return false; } /// <summary> /// <p>Sends data on the socket. The second parameter specifies the encoding in the /// case of a string--it defaults to UTF8 encoding. /// </p> /// <p>Returns <code>true</code> if the entire data was flushed successfully to the kernel /// buffer. Returns <code>false</code> if all or part of the data was queued in user memory. /// <code>&#39;drain&#39;</code> will be emitted when the buffer is again free. /// </p> /// <p>The optional <code>callback</code> parameter will be executed when the data is finally /// written out - this may not be immediately. /// </p> /// </summary> public bool write(object data, object encoding, JsAction callback) { return false; } #region Events /// <summary> /// Emitted when a socket connection is successfully established. See connect(). /// </summary> [JsProperty(Name= "conect")] public JsAction connectEvent { get; set; } /// <summary> /// Emitted when data is received. The argument data will be a Buffer or String. Encoding of data is set by socket.setEncoding(). (See the Readable Stream section for more information.) /// /// Note that the data will be lost if there is no listener when a Socket emits a 'data' event. /// </summary> public JsAction<Buffer> data { get; set; } /// <summary> /// Emitted when the other end of the socket sends a FIN packet. /// By default (allowHalfOpen == false) the socket will destroy its file descriptor once it has written out its pending write queue. However, by setting allowHalfOpen == true the socket will not automatically end() its side allowing the user to write arbitrary amounts of data, with the caveat that the user is required to end() their side now. /// </summary> [JsProperty(Name = "end")] public JsAction endEvent { get; set; } /// <summary> /// Emitted if the socket times out from inactivity. This is only to notify that the socket has been idle. The user must manually close the connection. /// See also: socket.setTimeout() /// </summary> public JsAction timeout { get; set; } /// <summary> /// Emitted when the write buffer becomes empty. Can be used to throttle uploads. /// /// See also: the return values of socket.write() /// </summary> public JsAction drain { get; set; } /// <summary> /// Emitted when an error occurs. The 'close' event will be called directly following this event. /// </summary> public JsAction<object> error { get; set; } /// <summary> /// Emitted once the socket is fully closed. The argument had_error is a boolean which says if the socket was closed due to a transmission error. /// </summary> public JsAction<bool> close { get; set; } #endregion } [JsType(JsMode.Json)] public partial class SocketOptions { public JsNumber fd { get; set; } public object type { get; set; } public bool allowHalfOpen { get; set; } } }
using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; public class tk2dSystemUtility { static string GetObjectGUID(Object obj) { return AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(obj)); } // Make this asset loadable at runtime, using the guid and the given name // The guid MUST match the GUID of the object. // The name is arbitrary and should be unique to make all assets findable using name, // but doesn't have to be. Name can be an empty string, but not null. public static bool MakeLoadableAsset(Object obj, string name) { string guid = GetObjectGUID(obj); // Check if it already is Loadable bool isLoadable = IsLoadableAsset(obj); if (isLoadable) { // Update name if it is different foreach (tk2dResourceTocEntry t in tk2dSystem.inst.Editor__Toc) { if (t.assetGUID == guid) { t.assetName = name; break; } } EditorUtility.SetDirty(tk2dSystem.inst); // Already loadable return true; } // Create resource object string resourcePath = GetOrCreateResourcesDir() + "/" + "tk2d_" + guid + ".asset"; tk2dResource resource = ScriptableObject.CreateInstance<tk2dResource>(); resource.objectReference = obj; AssetDatabase.CreateAsset(resource, resourcePath); AssetDatabase.SaveAssets(); // Add index entry tk2dResourceTocEntry tocEntry = new tk2dResourceTocEntry(); tocEntry.resourceGUID = AssetDatabase.AssetPathToGUID(resourcePath); tocEntry.assetName = (name.Length == 0)?obj.name:name; tocEntry.assetGUID = guid; List<tk2dResourceTocEntry> toc = new List<tk2dResourceTocEntry>(tk2dSystem.inst.Editor__Toc); toc.Add(tocEntry); tk2dSystem.inst.Editor__Toc = toc.ToArray(); EditorUtility.SetDirty(tk2dSystem.inst); AssetDatabase.SaveAssets(); return true; } // Deletes the asset from the global asset dictionary // and removes the associated the asset from the build public static bool UnmakeLoadableAsset(Object obj) { string guid = GetObjectGUID(obj); List<tk2dResourceTocEntry> toc = new List<tk2dResourceTocEntry>(tk2dSystem.inst.Editor__Toc); foreach (tk2dResourceTocEntry entry in toc) { if (entry.assetGUID == guid) { // Delete the corresponding resource object string resourceObjectPath = AssetDatabase.GUIDToAssetPath(entry.resourceGUID); AssetDatabase.DeleteAsset(resourceObjectPath); // remove from TOC toc.Remove(entry); break; } } if (tk2dSystem.inst.Editor__Toc.Length == toc.Count) { Debug.LogError("tk2dSystem.UnmakeLoadableAsset - Unable to delete asset"); return false; } else { tk2dSystem.inst.Editor__Toc = toc.ToArray(); EditorUtility.SetDirty(tk2dSystem.inst); AssetDatabase.SaveAssets(); return true; } } // Update asset name public static void UpdateAssetName(Object obj, string name) { MakeLoadableAsset(obj, name); } // This will return false if the system hasn't been initialized, without initializing it. public static bool IsLoadableAsset(Object obj) { string resourcesDir = GetResourcesDir(); if (resourcesDir.Length == 0) // tk2dSystem hasn't been initialized yet return false; string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(obj)); string resourcePath = GetResourcesDir() + "/tk2d_" + guid + ".asset"; return System.IO.File.Exists(resourcePath); } // Returns the path to the global resources directory // It is /Assets/TK2DSYSTEM/Resources by default, but can be moved anywhere // When the tk2dSystem object exists, the path to the object will be returned public static string GetOrCreateResourcesDir() { tk2dSystem inst = tk2dSystem.inst; string assetPath = AssetDatabase.GetAssetPath(inst); if (assetPath.Length > 0) { // This has already been serialized, just return path as is return System.IO.Path.GetDirectoryName(assetPath).Replace('\\', '/'); // already serialized } else { // Create the system asset const string resPath = "Assets/Resources"; if (!System.IO.Directory.Exists(resPath)) System.IO.Directory.CreateDirectory(resPath); const string basePath = resPath + "/tk2d"; if (!System.IO.Directory.Exists(basePath)) System.IO.Directory.CreateDirectory(basePath); assetPath = basePath + "/" + tk2dSystem.assetFileName; AssetDatabase.CreateAsset(inst, assetPath); return basePath; } } // Returns the path to the global resources directory // Will not create if it doesn't exists static string GetResourcesDir() { tk2dSystem inst = tk2dSystem.inst_NoCreate; if (inst == null) return ""; else return GetOrCreateResourcesDir(); // this already exists, so this function will follow the correct path } // Call when platform has changed public static void PlatformChanged() { List<tk2dSpriteCollectionData> changedSpriteCollections = new List<tk2dSpriteCollectionData>(); tk2dSpriteCollectionData[] allSpriteCollections = Resources.FindObjectsOfTypeAll(typeof(tk2dSpriteCollectionData)) as tk2dSpriteCollectionData[]; foreach (tk2dSpriteCollectionData scd in allSpriteCollections) { if (scd.hasPlatformData) { scd.ResetPlatformData(); changedSpriteCollections.Add(scd); } } allSpriteCollections = null; tk2dFontData[] allFontDatas = Resources.FindObjectsOfTypeAll(typeof(tk2dFontData)) as tk2dFontData[]; foreach (tk2dFontData fd in allFontDatas) { if (fd.hasPlatformData) { fd.ResetPlatformData(); } } allFontDatas = null; if (changedSpriteCollections.Count == 0) return; // nothing worth changing has changed // Scan all loaded sprite assets and rebuild them foreach (var assembly in System.AppDomain.CurrentDomain.GetAssemblies()) { try { System.Type[] types = assembly.GetTypes(); foreach (var type in types) { if (type.GetInterface("tk2dRuntime.ISpriteCollectionForceBuild") != null) { Object[] objects = Resources.FindObjectsOfTypeAll(type); foreach (var spriteCollectionData in changedSpriteCollections) { foreach (var o in objects) { if (tk2dEditorUtility.IsPrefab(o)) continue; tk2dRuntime.ISpriteCollectionForceBuild isc = o as tk2dRuntime.ISpriteCollectionForceBuild; if (isc.UsesSpriteCollection(spriteCollectionData)) isc.ForceBuild(); } } } } } catch { } } } public static void RebuildResources() { // Delete all existing resources string systemFileName = tk2dSystem.assetFileName.ToLower(); string tk2dIndexDir = "Assets/Resources/tk2d"; if (System.IO.Directory.Exists(tk2dIndexDir)) { string[] files = System.IO.Directory.GetFiles(tk2dIndexDir); foreach (string file in files) { string filename = System.IO.Path.GetFileName(file).ToLower(); if (filename.IndexOf(systemFileName) != -1) continue; // don't delete system object if (filename.IndexOf("tk2d_") == -1) { Debug.LogError(string.Format("Unknown file '{0}' in tk2d resources directory, ignoring.", filename)); continue; } AssetDatabase.DeleteAsset(file); } } // Delete all referenced resources, in the event they've been moved out of the directory if (tk2dSystem.inst_NoCreate != null) { tk2dSystem sys = tk2dSystem.inst; tk2dResourceTocEntry[] toc = sys.Editor__Toc; for (int i = 0; i < toc.Length; ++i) { string path = AssetDatabase.GUIDToAssetPath(toc[i].resourceGUID); if (path.Length > 0) AssetDatabase.DeleteAsset(path); } sys.Editor__Toc = new tk2dResourceTocEntry[0]; // clear index EditorUtility.SetDirty(sys); AssetDatabase.SaveAssets(); } AssetDatabase.Refresh(); // Need to create new index? tk2dSpriteCollectionIndex[] spriteCollectionIndex = tk2dEditorUtility.GetExistingIndex().GetSpriteCollectionIndex(); tk2dGenericIndexItem[] fontIndex = tk2dEditorUtility.GetExistingIndex().GetFonts(); int numLoadableAssets = 0; foreach (tk2dGenericIndexItem font in fontIndex) { if (font.managed || font.loadable) numLoadableAssets++; } foreach (tk2dSpriteCollectionIndex sc in spriteCollectionIndex) { if (sc.managedSpriteCollection || sc.loadable) numLoadableAssets++; } // Need an index if (numLoadableAssets > 0) { // If it already existed, the index would have been cleared by now tk2dSystem sys = tk2dSystem.inst; foreach (tk2dGenericIndexItem font in fontIndex) { if (font.managed || font.loadable) AddFontFromIndex(font); tk2dEditorUtility.CollectAndUnloadUnusedAssets(); } foreach (tk2dSpriteCollectionIndex sc in spriteCollectionIndex) { if (sc.managedSpriteCollection || sc.loadable) AddSpriteCollectionFromIndex(sc); tk2dEditorUtility.CollectAndUnloadUnusedAssets(); } Debug.Log(string.Format("Rebuilt {0} resources for tk2dSystem", sys.Editor__Toc.Length)); } tk2dEditorUtility.CollectAndUnloadUnusedAssets(); } static void AddSpriteCollectionFromIndex(tk2dSpriteCollectionIndex indexEntry) { string path = AssetDatabase.GUIDToAssetPath( indexEntry.spriteCollectionDataGUID ); tk2dSpriteCollectionData data = AssetDatabase.LoadAssetAtPath(path, typeof(tk2dSpriteCollectionData)) as tk2dSpriteCollectionData; if (data == null) { Debug.LogError(string.Format("Unable to load sprite collection '{0}' at path '{1}'", indexEntry.name, path)); return; } MakeLoadableAsset(data, indexEntry.managedSpriteCollection ? " " : data.assetName); data = null; } static void AddFontFromIndex(tk2dGenericIndexItem indexEntry) { string path = AssetDatabase.GUIDToAssetPath( indexEntry.dataGUID ); tk2dFontData data = AssetDatabase.LoadAssetAtPath(path, typeof(tk2dFontData)) as tk2dFontData; if (data == null) { Debug.LogError(string.Format("Unable to load font data '{0}' at path '{1}'", indexEntry.AssetName, path)); return; } MakeLoadableAsset(data, ""); // can't make it directly loadable, hence no asset name data = null; } }
using J2N.Collections.Generic.Extensions; using J2N.Threading; using Lucene.Net.Documents; using NUnit.Framework; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Text; using System.Threading; using Assert = Lucene.Net.TestFramework.Assert; using Console = Lucene.Net.Util.SystemConsole; namespace Lucene.Net.Index { /* * 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 BytesRef = Lucene.Net.Util.BytesRef; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using Field = Field; using FieldType = FieldType; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using TestUtil = Lucene.Net.Util.TestUtil; /// <summary> /// Simple test that adds numeric terms, where each term has the /// totalTermFreq of its integer value, and checks that the totalTermFreq is correct. /// </summary> // TODO: somehow factor this with BagOfPostings? its almost the same [SuppressCodecs("Direct", "Memory", "Lucene3x")] // at night this makes like 200k/300k docs and will make Direct's heart beat! // Lucene3x doesnt have totalTermFreq, so the test isn't interesting there. [TestFixture] public class TestBagOfPositions : LuceneTestCase { [Test] [Slow] public virtual void Test() { IList<string> postingsList = new List<string>(); int numTerms = AtLeast(300); int maxTermsPerDoc = TestUtil.NextInt32(Random, 10, 20); bool isSimpleText = "SimpleText".Equals(TestUtil.GetPostingsFormat("field"), StringComparison.Ordinal); IndexWriterConfig iwc = NewIndexWriterConfig(Random, TEST_VERSION_CURRENT, new MockAnalyzer(Random)); if ((isSimpleText || iwc.MergePolicy is MockRandomMergePolicy) && (TestNightly || RandomMultiplier > 1)) { // Otherwise test can take way too long (> 2 hours) //numTerms /= 2; // LUCENENET specific - To keep this under the 1 hour free limit // of Azure DevOps, this was reduced from /2 to /6. numTerms /= 6; } if (Verbose) { Console.WriteLine("maxTermsPerDoc=" + maxTermsPerDoc); Console.WriteLine("numTerms=" + numTerms); } for (int i = 0; i < numTerms; i++) { string term = Convert.ToString(i, CultureInfo.InvariantCulture); for (int j = 0; j < i; j++) { postingsList.Add(term); } } postingsList.Shuffle(Random); ConcurrentQueue<string> postings = new ConcurrentQueue<string>(postingsList); Directory dir = NewFSDirectory(CreateTempDir(GetFullMethodName())); RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwc); int threadCount = TestUtil.NextInt32(Random, 1, 5); if (Verbose) { Console.WriteLine("config: " + iw.IndexWriter.Config); Console.WriteLine("threadCount=" + threadCount); } Field prototype = NewTextField("field", "", Field.Store.NO); FieldType fieldType = new FieldType(prototype.FieldType); if (Random.NextBoolean()) { fieldType.OmitNorms = true; } int options = Random.Next(3); if (options == 0) { fieldType.IndexOptions = IndexOptions.DOCS_AND_FREQS; // we dont actually need positions fieldType.StoreTermVectors = true; // but enforce term vectors when we do this so we check SOMETHING } else if (options == 1 && !DoesntSupportOffsets.Contains(TestUtil.GetPostingsFormat("field"))) { fieldType.IndexOptions = IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS; } // else just positions ThreadJob[] threads = new ThreadJob[threadCount]; CountdownEvent startingGun = new CountdownEvent(1); for (int threadID = 0; threadID < threadCount; threadID++) { Random threadRandom = new Random(Random.Next()); Document document = new Document(); Field field = new Field("field", "", fieldType); document.Add(field); threads[threadID] = new ThreadAnonymousInnerClassHelper(this, numTerms, maxTermsPerDoc, postings, iw, startingGun, threadRandom, document, field); threads[threadID].Start(); } startingGun.Signal(); foreach (ThreadJob t in threads) { t.Join(); } iw.ForceMerge(1); DirectoryReader ir = iw.GetReader(); Assert.AreEqual(1, ir.Leaves.Count); AtomicReader air = (AtomicReader)ir.Leaves[0].Reader; Terms terms = air.GetTerms("field"); // numTerms-1 because there cannot be a term 0 with 0 postings: Assert.AreEqual(numTerms - 1, terms.Count); TermsEnum termsEnum = terms.GetEnumerator(); while (termsEnum.MoveNext()) { int value = Convert.ToInt32(termsEnum.Term.Utf8ToString(), CultureInfo.InvariantCulture); Assert.AreEqual(value, termsEnum.TotalTermFreq); // don't really need to check more than this, as CheckIndex // will verify that totalTermFreq == total number of positions seen // from a docsAndPositionsEnum. } ir.Dispose(); iw.Dispose(); dir.Dispose(); } private class ThreadAnonymousInnerClassHelper : ThreadJob { private readonly TestBagOfPositions outerInstance; private readonly int numTerms; private readonly int maxTermsPerDoc; private readonly ConcurrentQueue<string> postings; private readonly RandomIndexWriter iw; private readonly CountdownEvent startingGun; private readonly Random threadRandom; private readonly Document document; private readonly Field field; public ThreadAnonymousInnerClassHelper(TestBagOfPositions outerInstance, int numTerms, int maxTermsPerDoc, ConcurrentQueue<string> postings, RandomIndexWriter iw, CountdownEvent startingGun, Random threadRandom, Document document, Field field) { this.outerInstance = outerInstance; this.numTerms = numTerms; this.maxTermsPerDoc = maxTermsPerDoc; this.postings = postings; this.iw = iw; this.startingGun = startingGun; this.threadRandom = threadRandom; this.document = document; this.field = field; } public override void Run() { try { startingGun.Wait(); while (!(postings.Count == 0)) { StringBuilder text = new StringBuilder(); int numTerms = threadRandom.Next(maxTermsPerDoc); for (int i = 0; i < numTerms; i++) { string token; if (!postings.TryDequeue(out token)) { break; } text.Append(' '); text.Append(token); } field.SetStringValue(text.ToString()); iw.AddDocument(document); } } catch (Exception e) { throw new Exception(e.Message, e); } } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using 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.Cloud.ApigeeConnect.V1 { /// <summary>Settings for <see cref="TetherClient"/> instances.</summary> public sealed partial class TetherSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="TetherSettings"/>.</summary> /// <returns>A new instance of the default <see cref="TetherSettings"/>.</returns> public static TetherSettings GetDefault() => new TetherSettings(); /// <summary>Constructs a new <see cref="TetherSettings"/> object with default settings.</summary> public TetherSettings() { } private TetherSettings(TetherSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); EgressSettings = existing.EgressSettings; EgressStreamingSettings = existing.EgressStreamingSettings; OnCopy(existing); } partial void OnCopy(TetherSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>TetherClient.Egress</c> and /// <c>TetherClient.EgressAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings EgressSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary> /// <see cref="gaxgrpc::BidirectionalStreamingSettings"/> for calls to <c>TetherClient.Egress</c> and /// <c>TetherClient.EgressAsync</c>. /// </summary> /// <remarks>The default local send queue size is 100.</remarks> public gaxgrpc::BidirectionalStreamingSettings EgressStreamingSettings { get; set; } = new gaxgrpc::BidirectionalStreamingSettings(100); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="TetherSettings"/> object.</returns> public TetherSettings Clone() => new TetherSettings(this); } /// <summary> /// Builder class for <see cref="TetherClient"/> to provide simple configuration of credentials, endpoint etc. /// </summary> public sealed partial class TetherClientBuilder : gaxgrpc::ClientBuilderBase<TetherClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public TetherSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public TetherClientBuilder() { UseJwtAccessWithScopes = TetherClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref TetherClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<TetherClient> task); /// <summary>Builds the resulting client.</summary> public override TetherClient Build() { TetherClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<TetherClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<TetherClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private TetherClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return TetherClient.Create(callInvoker, Settings); } private async stt::Task<TetherClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return TetherClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => TetherClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => TetherClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => TetherClient.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>Tether client wrapper, for convenient use.</summary> /// <remarks> /// Tether provides a way for the control plane to send HTTP API requests to /// services in data planes that runs in a remote datacenter without /// requiring customers to open firewalls on their runtime plane. /// </remarks> public abstract partial class TetherClient { /// <summary> /// The default endpoint for the Tether service, which is a host of "apigeeconnect.googleapis.com" and a port of /// 443. /// </summary> public static string DefaultEndpoint { get; } = "apigeeconnect.googleapis.com:443"; /// <summary>The default Tether scopes.</summary> /// <remarks> /// The default Tether scopes are: /// <list type="bullet"> /// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="TetherClient"/> using the default credentials, endpoint and settings. To /// specify custom credentials or other settings, use <see cref="TetherClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="TetherClient"/>.</returns> public static stt::Task<TetherClient> CreateAsync(st::CancellationToken cancellationToken = default) => new TetherClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="TetherClient"/> using the default credentials, endpoint and settings. To /// specify custom credentials or other settings, use <see cref="TetherClientBuilder"/>. /// </summary> /// <returns>The created <see cref="TetherClient"/>.</returns> public static TetherClient Create() => new TetherClientBuilder().Build(); /// <summary> /// Creates a <see cref="TetherClient"/> 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="TetherSettings"/>.</param> /// <returns>The created <see cref="TetherClient"/>.</returns> internal static TetherClient Create(grpccore::CallInvoker callInvoker, TetherSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } Tether.TetherClient grpcClient = new Tether.TetherClient(callInvoker); return new TetherClientImpl(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 Tether client</summary> public virtual Tether.TetherClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Bidirectional streaming methods for /// <see cref="Egress(gaxgrpc::CallSettings,gaxgrpc::BidirectionalStreamingSettings)"/>. /// </summary> public abstract partial class EgressStream : gaxgrpc::BidirectionalStreamingBase<EgressResponse, EgressRequest> { } /// <summary> /// Egress streams egress requests and responses. Logically, this is not /// actually a streaming request, but uses streaming as a mechanism to flip /// the client-server relationship of gRPC so that the server can act as a /// client. /// The listener, the RPC server, accepts connections from the dialer, /// the RPC client. /// The listener streams http requests and the dialer streams http responses. /// </summary> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <param name="streamingSettings">If not null, applies streaming overrides to this RPC call.</param> /// <returns>The client-server stream.</returns> public virtual EgressStream Egress(gaxgrpc::CallSettings callSettings = null, gaxgrpc::BidirectionalStreamingSettings streamingSettings = null) => throw new sys::NotImplementedException(); } /// <summary>Tether client wrapper implementation, for convenient use.</summary> /// <remarks> /// Tether provides a way for the control plane to send HTTP API requests to /// services in data planes that runs in a remote datacenter without /// requiring customers to open firewalls on their runtime plane. /// </remarks> public sealed partial class TetherClientImpl : TetherClient { private readonly gaxgrpc::ApiBidirectionalStreamingCall<EgressResponse, EgressRequest> _callEgress; /// <summary> /// Constructs a client wrapper for the Tether service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="TetherSettings"/> used within this client.</param> public TetherClientImpl(Tether.TetherClient grpcClient, TetherSettings settings) { GrpcClient = grpcClient; TetherSettings effectiveSettings = settings ?? TetherSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callEgress = clientHelper.BuildApiCall<EgressResponse, EgressRequest>(grpcClient.Egress, effectiveSettings.EgressSettings, effectiveSettings.EgressStreamingSettings); Modify_ApiCall(ref _callEgress); Modify_EgressApiCall(ref _callEgress); 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_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiBidirectionalStreamingCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_EgressApiCall(ref gaxgrpc::ApiBidirectionalStreamingCall<EgressResponse, EgressRequest> call); partial void OnConstruction(Tether.TetherClient grpcClient, TetherSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC Tether client</summary> public override Tether.TetherClient GrpcClient { get; } partial void Modify_EgressResponseCallSettings(ref gaxgrpc::CallSettings settings); partial void Modify_EgressResponseRequest(ref EgressResponse request); internal sealed partial class EgressStreamImpl : EgressStream { /// <summary>Construct the bidirectional streaming method for <c>Egress</c>.</summary> /// <param name="service">The service containing this streaming method.</param> /// <param name="call">The underlying gRPC duplex streaming call.</param> /// <param name="writeBuffer"> /// The <see cref="gaxgrpc::BufferedClientStreamWriter{EgressResponse}"/> instance associated with this /// streaming call. /// </param> public EgressStreamImpl(TetherClientImpl service, grpccore::AsyncDuplexStreamingCall<EgressResponse, EgressRequest> call, gaxgrpc::BufferedClientStreamWriter<EgressResponse> writeBuffer) { _service = service; GrpcCall = call; _writeBuffer = writeBuffer; } private TetherClientImpl _service; private gaxgrpc::BufferedClientStreamWriter<EgressResponse> _writeBuffer; public override grpccore::AsyncDuplexStreamingCall<EgressResponse, EgressRequest> GrpcCall { get; } private EgressResponse ModifyRequest(EgressResponse request) { _service.Modify_EgressResponseRequest(ref request); return request; } public override stt::Task TryWriteAsync(EgressResponse message) => _writeBuffer.TryWriteAsync(ModifyRequest(message)); public override stt::Task WriteAsync(EgressResponse message) => _writeBuffer.WriteAsync(ModifyRequest(message)); public override stt::Task TryWriteAsync(EgressResponse message, grpccore::WriteOptions options) => _writeBuffer.TryWriteAsync(ModifyRequest(message), options); public override stt::Task WriteAsync(EgressResponse message, grpccore::WriteOptions options) => _writeBuffer.WriteAsync(ModifyRequest(message), options); public override stt::Task TryWriteCompleteAsync() => _writeBuffer.TryWriteCompleteAsync(); public override stt::Task WriteCompleteAsync() => _writeBuffer.WriteCompleteAsync(); } /// <summary> /// Egress streams egress requests and responses. Logically, this is not /// actually a streaming request, but uses streaming as a mechanism to flip /// the client-server relationship of gRPC so that the server can act as a /// client. /// The listener, the RPC server, accepts connections from the dialer, /// the RPC client. /// The listener streams http requests and the dialer streams http responses. /// </summary> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <param name="streamingSettings">If not null, applies streaming overrides to this RPC call.</param> /// <returns>The client-server stream.</returns> public override TetherClient.EgressStream Egress(gaxgrpc::CallSettings callSettings = null, gaxgrpc::BidirectionalStreamingSettings streamingSettings = null) { Modify_EgressResponseCallSettings(ref callSettings); gaxgrpc::BidirectionalStreamingSettings effectiveStreamingSettings = streamingSettings ?? _callEgress.StreamingSettings; grpccore::AsyncDuplexStreamingCall<EgressResponse, EgressRequest> call = _callEgress.Call(callSettings); gaxgrpc::BufferedClientStreamWriter<EgressResponse> writeBuffer = new gaxgrpc::BufferedClientStreamWriter<EgressResponse>(call.RequestStream, effectiveStreamingSettings.BufferedClientWriterCapacity); return new EgressStreamImpl(this, call, writeBuffer); } } }
using System; using System.Linq.Expressions; using System.Reflection; using Signum.Utilities; using System.ComponentModel; using Signum.Entities.Basics; using Signum.Entities.Authorization; using Signum.Entities; namespace Signum.Entities.Processes { [Serializable] public class ProcessAlgorithmSymbol : Symbol { private ProcessAlgorithmSymbol() { } public ProcessAlgorithmSymbol(Type declaringType, string fieldName) : base(declaringType, fieldName) { } } [Serializable, EntityKind(EntityKind.Main, EntityData.Transactional), TicksColumn(false)] public class ProcessEntity : Entity { internal ProcessEntity() { } public ProcessEntity(ProcessAlgorithmSymbol process) { this.Algorithm = process; } public ProcessAlgorithmSymbol Algorithm { get; private set; } public IProcessDataEntity? Data { get; set; } public const string None = "none"; [StringLengthValidator(Min = 3, Max = 100)] public string MachineName { get; set; } [StringLengthValidator(Min = 3, Max = 100)] public string ApplicationName { get; set; } public Lite<IUserEntity> User { get; set; } public ProcessState State { get; set; } public DateTime CreationDate { get; private set; } = TimeZoneManager.Now; [DateTimePrecisionValidator(DateTimePrecision.Milliseconds)] public DateTime? PlannedDate { get; set; } [DateTimePrecisionValidator(DateTimePrecision.Milliseconds)] public DateTime? CancelationDate { get; set; } [DateTimePrecisionValidator(DateTimePrecision.Milliseconds)] public DateTime? QueuedDate { get; set; } DateTime? executionStart; [DateTimePrecisionValidator(DateTimePrecision.Milliseconds)] public DateTime? ExecutionStart { get { return executionStart; } set { if (Set(ref executionStart, value)) Notify(() => ExecutionEnd); } } DateTime? executionEnd; [DateTimePrecisionValidator(DateTimePrecision.Milliseconds)] public DateTime? ExecutionEnd { get { return executionEnd; } set { if (Set(ref executionEnd, value)) Notify(() => ExecutionStart); } } static Expression<Func<ProcessEntity, double?>> DurationExpression = log => (double?)(log.ExecutionEnd - log.ExecutionStart)!.Value.TotalMilliseconds; [ExpressionField("DurationExpression")] public double? Duration { get { return ExecutionEnd == null ? null : DurationExpression.Evaluate(this); } } static Expression<Func<ProcessEntity, TimeSpan?>> DurationSpanExpression = log => log.ExecutionEnd - log.ExecutionStart; [ExpressionField("DurationSpanExpression")] public TimeSpan? DurationSpan { get { return ExecutionEnd == null ? null : DurationSpanExpression.Evaluate(this); } } public DateTime? SuspendDate { get; set; } public DateTime? ExceptionDate { get; set; } public Lite<ExceptionEntity>? Exception { get; set; } [NumberBetweenValidator(0, 1), Format("p")] public decimal? Progress { get; set; } [DbType(Size = int.MaxValue)] public string? Status { get; set; } static StateValidator<ProcessEntity, ProcessState> stateValidator = new StateValidator<ProcessEntity, ProcessState> (e => e.State, e => e.PlannedDate, e => e.CancelationDate, e => e.QueuedDate, e => e.ExecutionStart, e => e.ExecutionEnd, e => e.SuspendDate, e => e.Progress, e => e.Status, e => e.ExceptionDate, e => e.Exception, e => e.MachineName, e => e.ApplicationName) { {ProcessState.Created, false, false, false, false, false, false, false, false, false, false, null, null }, {ProcessState.Planned, true, null, null, null, false, null, null, null, null, null , null, null }, {ProcessState.Canceled, null, true, null, null, false, null, null, null, null, null , null, null }, {ProcessState.Queued, null, null, true, false, false, false, false, false, false, false, null, null }, {ProcessState.Executing, null, null, true, true, false, false, true, null, false, false, true, true }, {ProcessState.Suspending,null, null, true, true, false, true, true, null, false, false, true, true }, {ProcessState.Suspended, null, null, true, true, false, true, true, null, false, false, null, null }, {ProcessState.Finished, null, null, true, true, true, false, false, null, false, false, null, null }, {ProcessState.Error, null, null, null, null, null, null, null, null, true, true , null, null }, }; protected override string? PropertyValidation(PropertyInfo pi) { if (pi.Name == nameof(ExecutionStart) || pi.Name == nameof(ExecutionEnd)) { if (this.ExecutionEnd < this.ExecutionStart) return ProcessMessage.ProcessStartIsGreaterThanProcessEnd.NiceToString(); if (this.ExecutionStart == null && this.ExecutionEnd != null) return ProcessMessage.ProcessStartIsNullButProcessEndIsNot.NiceToString(); } return stateValidator.Validate(this, pi) ?? base.PropertyValidation(pi); } public override string ToString() { switch (State) { case ProcessState.Created: return "{0} {1} on {2}".FormatWith(Algorithm, ProcessState.Created.NiceToString(), CreationDate); case ProcessState.Planned: return "{0} {1} for {2}".FormatWith(Algorithm, ProcessState.Planned.NiceToString(), PlannedDate); case ProcessState.Canceled: return "{0} {1} on {2}".FormatWith(Algorithm, ProcessState.Canceled.NiceToString(), CancelationDate); case ProcessState.Queued: return "{0} {1} on {2}".FormatWith(Algorithm, ProcessState.Queued.NiceToString(), QueuedDate); case ProcessState.Executing: return "{0} {1} since {2}".FormatWith(Algorithm, ProcessState.Executing.NiceToString(), executionStart); case ProcessState.Suspending: return "{0} {1} since {2}".FormatWith(Algorithm, ProcessState.Suspending.NiceToString(), SuspendDate); case ProcessState.Suspended: return "{0} {1} on {2}".FormatWith(Algorithm, ProcessState.Suspended.NiceToString(), SuspendDate); case ProcessState.Finished: return "{0} {1} on {2}".FormatWith(Algorithm, ProcessState.Finished.NiceToString(), executionEnd); case ProcessState.Error: return "{0} {1} on {2}".FormatWith(Algorithm, ProcessState.Error.NiceToString(), executionEnd); default: return "{0} ??".FormatWith(Algorithm); } } } public interface IProcessDataEntity : IEntity { } public interface IProcessLineDataEntity : IEntity { } public enum ProcessState { Created, Planned, Canceled, Queued, Executing, Suspending, Suspended, Finished, Error, } [AutoInit] public static class ProcessOperation { public static ExecuteSymbol<ProcessEntity> Plan; public static ExecuteSymbol<ProcessEntity> Save; public static ExecuteSymbol<ProcessEntity> Cancel; public static ExecuteSymbol<ProcessEntity> Execute; public static ExecuteSymbol<ProcessEntity> Suspend; public static ConstructSymbol<ProcessEntity>.From<ProcessEntity> Retry; } [AutoInit] public static class ProcessPermission { public static PermissionSymbol ViewProcessPanel; } public enum ProcessMessage { [Description("Process {0} is not running anymore")] Process0IsNotRunningAnymore, [Description("Process Start is greater than Process End")] ProcessStartIsGreaterThanProcessEnd, [Description("Process Start is null but Process End is not")] ProcessStartIsNullButProcessEndIsNot, Lines, LastProcess, ExceptionLines, [Description("Suspend in the safer way of stoping a running process. Cancel anyway?")] SuspendIsTheSaferWayOfStoppingARunningProcessCancelAnyway } [Serializable, EntityKind(EntityKind.System, EntityData.Transactional)] public class ProcessExceptionLineEntity : Entity { [DbType(Size = int.MaxValue)] public string? ElementInfo { get; set; } public Lite<IProcessLineDataEntity>? Line { get; set; } public Lite<ProcessEntity> Process { get; set; } public Lite<ExceptionEntity> Exception { get; set; } static Expression<Func<ProcessExceptionLineEntity, string>> ToStringExpression = pel => "ProcessExceptionLine (" + pel.Id + ")"; [ExpressionField("ToStringExpression")] public override string ToString() => "ProcessExceptionLine (" + (this.IdOrNull == null ? "New" : this.Id.ToString()) + ")"; } }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="LocalLB.ProfilePersistenceBinding", Namespace="urn:iControl")] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileEnabledState))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfilePersistenceProfileCookieEncryption))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileString))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileULong))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileCookiePersistenceMethod))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfilePersistenceProfilePersistenceHashMethod))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileIPAddress))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfilePersistenceMode))] public partial class LocalLBProfilePersistence : iControlInterface { public LocalLBProfilePersistence() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // create //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void create( string [] profile_names, LocalLBPersistenceMode [] modes ) { this.Invoke("create", new object [] { profile_names, modes}); } public System.IAsyncResult Begincreate(string [] profile_names,LocalLBPersistenceMode [] modes, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("create", new object[] { profile_names, modes}, callback, asyncState); } public void Endcreate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_all_profiles //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void delete_all_profiles( ) { this.Invoke("delete_all_profiles", new object [0]); } public System.IAsyncResult Begindelete_all_profiles(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_all_profiles", new object[0], callback, asyncState); } public void Enddelete_all_profiles(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void delete_profile( string [] profile_names ) { this.Invoke("delete_profile", new object [] { profile_names}); } public System.IAsyncResult Begindelete_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_profile", new object[] { profile_names}, callback, asyncState); } public void Enddelete_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // get_across_pool_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileEnabledState [] get_across_pool_state( string [] profile_names ) { object [] results = this.Invoke("get_across_pool_state", new object [] { profile_names}); return ((LocalLBProfileEnabledState [])(results[0])); } public System.IAsyncResult Beginget_across_pool_state(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_across_pool_state", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileEnabledState [] Endget_across_pool_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_across_service_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileEnabledState [] get_across_service_state( string [] profile_names ) { object [] results = this.Invoke("get_across_service_state", new object [] { profile_names}); return ((LocalLBProfileEnabledState [])(results[0])); } public System.IAsyncResult Beginget_across_service_state(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_across_service_state", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileEnabledState [] Endget_across_service_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_across_virtual_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileEnabledState [] get_across_virtual_state( string [] profile_names ) { object [] results = this.Invoke("get_across_virtual_state", new object [] { profile_names}); return ((LocalLBProfileEnabledState [])(results[0])); } public System.IAsyncResult Beginget_across_virtual_state(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_across_virtual_state", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileEnabledState [] Endget_across_virtual_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_cookie_always_send_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileEnabledState [] get_cookie_always_send_state( string [] profile_names ) { object [] results = this.Invoke("get_cookie_always_send_state", new object [] { profile_names}); return ((LocalLBProfileEnabledState [])(results[0])); } public System.IAsyncResult Beginget_cookie_always_send_state(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_cookie_always_send_state", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileEnabledState [] Endget_cookie_always_send_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_cookie_encryption //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfilePersistenceProfileCookieEncryption [] get_cookie_encryption( string [] profile_names ) { object [] results = this.Invoke("get_cookie_encryption", new object [] { profile_names}); return ((LocalLBProfilePersistenceProfileCookieEncryption [])(results[0])); } public System.IAsyncResult Beginget_cookie_encryption(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_cookie_encryption", new object[] { profile_names}, callback, asyncState); } public LocalLBProfilePersistenceProfileCookieEncryption [] Endget_cookie_encryption(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfilePersistenceProfileCookieEncryption [])(results[0])); } //----------------------------------------------------------------------- // get_cookie_encryption_passphrase //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileString [] get_cookie_encryption_passphrase( string [] profile_names ) { object [] results = this.Invoke("get_cookie_encryption_passphrase", new object [] { profile_names}); return ((LocalLBProfileString [])(results[0])); } public System.IAsyncResult Beginget_cookie_encryption_passphrase(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_cookie_encryption_passphrase", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileString [] Endget_cookie_encryption_passphrase(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileString [])(results[0])); } //----------------------------------------------------------------------- // get_cookie_expiration //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileULong [] get_cookie_expiration( string [] profile_names ) { object [] results = this.Invoke("get_cookie_expiration", new object [] { profile_names}); return ((LocalLBProfileULong [])(results[0])); } public System.IAsyncResult Beginget_cookie_expiration(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_cookie_expiration", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileULong [] Endget_cookie_expiration(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileULong [])(results[0])); } //----------------------------------------------------------------------- // get_cookie_hash_length //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileULong [] get_cookie_hash_length( string [] profile_names ) { object [] results = this.Invoke("get_cookie_hash_length", new object [] { profile_names}); return ((LocalLBProfileULong [])(results[0])); } public System.IAsyncResult Beginget_cookie_hash_length(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_cookie_hash_length", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileULong [] Endget_cookie_hash_length(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileULong [])(results[0])); } //----------------------------------------------------------------------- // get_cookie_hash_offset //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileULong [] get_cookie_hash_offset( string [] profile_names ) { object [] results = this.Invoke("get_cookie_hash_offset", new object [] { profile_names}); return ((LocalLBProfileULong [])(results[0])); } public System.IAsyncResult Beginget_cookie_hash_offset(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_cookie_hash_offset", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileULong [] Endget_cookie_hash_offset(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileULong [])(results[0])); } //----------------------------------------------------------------------- // get_cookie_httponly_attribute //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileEnabledState [] get_cookie_httponly_attribute( string [] profile_names ) { object [] results = this.Invoke("get_cookie_httponly_attribute", new object [] { profile_names}); return ((LocalLBProfileEnabledState [])(results[0])); } public System.IAsyncResult Beginget_cookie_httponly_attribute(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_cookie_httponly_attribute", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileEnabledState [] Endget_cookie_httponly_attribute(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_cookie_name //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileString [] get_cookie_name( string [] profile_names ) { object [] results = this.Invoke("get_cookie_name", new object [] { profile_names}); return ((LocalLBProfileString [])(results[0])); } public System.IAsyncResult Beginget_cookie_name(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_cookie_name", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileString [] Endget_cookie_name(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileString [])(results[0])); } //----------------------------------------------------------------------- // get_cookie_persistence_method //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileCookiePersistenceMethod [] get_cookie_persistence_method( string [] profile_names ) { object [] results = this.Invoke("get_cookie_persistence_method", new object [] { profile_names}); return ((LocalLBProfileCookiePersistenceMethod [])(results[0])); } public System.IAsyncResult Beginget_cookie_persistence_method(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_cookie_persistence_method", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileCookiePersistenceMethod [] Endget_cookie_persistence_method(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileCookiePersistenceMethod [])(results[0])); } //----------------------------------------------------------------------- // get_cookie_secure_attribute //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileEnabledState [] get_cookie_secure_attribute( string [] profile_names ) { object [] results = this.Invoke("get_cookie_secure_attribute", new object [] { profile_names}); return ((LocalLBProfileEnabledState [])(results[0])); } public System.IAsyncResult Beginget_cookie_secure_attribute(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_cookie_secure_attribute", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileEnabledState [] Endget_cookie_secure_attribute(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_default_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_default_profile( string [] profile_names ) { object [] results = this.Invoke("get_default_profile", new object [] { profile_names}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_default_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_default_profile", new object[] { profile_names}, callback, asyncState); } public string [] Endget_default_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_description( string [] profile_names ) { object [] results = this.Invoke("get_description", new object [] { profile_names}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_description(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_description", new object[] { profile_names}, callback, asyncState); } public string [] Endget_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_ending_hash_pattern //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileString [] get_ending_hash_pattern( string [] profile_names ) { object [] results = this.Invoke("get_ending_hash_pattern", new object [] { profile_names}); return ((LocalLBProfileString [])(results[0])); } public System.IAsyncResult Beginget_ending_hash_pattern(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_ending_hash_pattern", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileString [] Endget_ending_hash_pattern(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileString [])(results[0])); } //----------------------------------------------------------------------- // get_hash_length //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileULong [] get_hash_length( string [] profile_names ) { object [] results = this.Invoke("get_hash_length", new object [] { profile_names}); return ((LocalLBProfileULong [])(results[0])); } public System.IAsyncResult Beginget_hash_length(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_hash_length", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileULong [] Endget_hash_length(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileULong [])(results[0])); } //----------------------------------------------------------------------- // get_hash_method //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfilePersistenceProfilePersistenceHashMethod [] get_hash_method( string [] profile_names ) { object [] results = this.Invoke("get_hash_method", new object [] { profile_names}); return ((LocalLBProfilePersistenceProfilePersistenceHashMethod [])(results[0])); } public System.IAsyncResult Beginget_hash_method(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_hash_method", new object[] { profile_names}, callback, asyncState); } public LocalLBProfilePersistenceProfilePersistenceHashMethod [] Endget_hash_method(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfilePersistenceProfilePersistenceHashMethod [])(results[0])); } //----------------------------------------------------------------------- // get_hash_more_data_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileEnabledState [] get_hash_more_data_state( string [] profile_names ) { object [] results = this.Invoke("get_hash_more_data_state", new object [] { profile_names}); return ((LocalLBProfileEnabledState [])(results[0])); } public System.IAsyncResult Beginget_hash_more_data_state(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_hash_more_data_state", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileEnabledState [] Endget_hash_more_data_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_hash_offset //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileULong [] get_hash_offset( string [] profile_names ) { object [] results = this.Invoke("get_hash_offset", new object [] { profile_names}); return ((LocalLBProfileULong [])(results[0])); } public System.IAsyncResult Beginget_hash_offset(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_hash_offset", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileULong [] Endget_hash_offset(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileULong [])(results[0])); } //----------------------------------------------------------------------- // get_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_list( ) { object [] results = this.Invoke("get_list", new object [0]); return ((string [])(results[0])); } public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_list", new object[0], callback, asyncState); } public string [] Endget_list(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_map_proxy_address //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileIPAddress [] get_map_proxy_address( string [] profile_names ) { object [] results = this.Invoke("get_map_proxy_address", new object [] { profile_names}); return ((LocalLBProfileIPAddress [])(results[0])); } public System.IAsyncResult Beginget_map_proxy_address(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_map_proxy_address", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileIPAddress [] Endget_map_proxy_address(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileIPAddress [])(results[0])); } //----------------------------------------------------------------------- // get_map_proxy_class //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileString [] get_map_proxy_class( string [] profile_names ) { object [] results = this.Invoke("get_map_proxy_class", new object [] { profile_names}); return ((LocalLBProfileString [])(results[0])); } public System.IAsyncResult Beginget_map_proxy_class(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_map_proxy_class", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileString [] Endget_map_proxy_class(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileString [])(results[0])); } //----------------------------------------------------------------------- // get_map_proxy_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileEnabledState [] get_map_proxy_state( string [] profile_names ) { object [] results = this.Invoke("get_map_proxy_state", new object [] { profile_names}); return ((LocalLBProfileEnabledState [])(results[0])); } public System.IAsyncResult Beginget_map_proxy_state(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_map_proxy_state", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileEnabledState [] Endget_map_proxy_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_mask //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileIPAddress [] get_mask( string [] profile_names ) { object [] results = this.Invoke("get_mask", new object [] { profile_names}); return ((LocalLBProfileIPAddress [])(results[0])); } public System.IAsyncResult Beginget_mask(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_mask", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileIPAddress [] Endget_mask(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileIPAddress [])(results[0])); } //----------------------------------------------------------------------- // get_maximum_hash_buffer_size //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileULong [] get_maximum_hash_buffer_size( string [] profile_names ) { object [] results = this.Invoke("get_maximum_hash_buffer_size", new object [] { profile_names}); return ((LocalLBProfileULong [])(results[0])); } public System.IAsyncResult Beginget_maximum_hash_buffer_size(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_maximum_hash_buffer_size", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileULong [] Endget_maximum_hash_buffer_size(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileULong [])(results[0])); } //----------------------------------------------------------------------- // get_mirror_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileEnabledState [] get_mirror_state( string [] profile_names ) { object [] results = this.Invoke("get_mirror_state", new object [] { profile_names}); return ((LocalLBProfileEnabledState [])(results[0])); } public System.IAsyncResult Beginget_mirror_state(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_mirror_state", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileEnabledState [] Endget_mirror_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_msrdp_without_session_directory_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileEnabledState [] get_msrdp_without_session_directory_state( string [] profile_names ) { object [] results = this.Invoke("get_msrdp_without_session_directory_state", new object [] { profile_names}); return ((LocalLBProfileEnabledState [])(results[0])); } public System.IAsyncResult Beginget_msrdp_without_session_directory_state(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_msrdp_without_session_directory_state", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileEnabledState [] Endget_msrdp_without_session_directory_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_override_connection_limit_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileEnabledState [] get_override_connection_limit_state( string [] profile_names ) { object [] results = this.Invoke("get_override_connection_limit_state", new object [] { profile_names}); return ((LocalLBProfileEnabledState [])(results[0])); } public System.IAsyncResult Beginget_override_connection_limit_state(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_override_connection_limit_state", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileEnabledState [] Endget_override_connection_limit_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_persistence_mode //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfilePersistenceMode [] get_persistence_mode( string [] profile_names ) { object [] results = this.Invoke("get_persistence_mode", new object [] { profile_names}); return ((LocalLBProfilePersistenceMode [])(results[0])); } public System.IAsyncResult Beginget_persistence_mode(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_persistence_mode", new object[] { profile_names}, callback, asyncState); } public LocalLBProfilePersistenceMode [] Endget_persistence_mode(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfilePersistenceMode [])(results[0])); } //----------------------------------------------------------------------- // get_rule //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileString [] get_rule( string [] profile_names ) { object [] results = this.Invoke("get_rule", new object [] { profile_names}); return ((LocalLBProfileString [])(results[0])); } public System.IAsyncResult Beginget_rule(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_rule", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileString [] Endget_rule(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileString [])(results[0])); } //----------------------------------------------------------------------- // get_sip_info //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileString [] get_sip_info( string [] profile_names ) { object [] results = this.Invoke("get_sip_info", new object [] { profile_names}); return ((LocalLBProfileString [])(results[0])); } public System.IAsyncResult Beginget_sip_info(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_sip_info", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileString [] Endget_sip_info(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileString [])(results[0])); } //----------------------------------------------------------------------- // get_starting_hash_pattern //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileString [] get_starting_hash_pattern( string [] profile_names ) { object [] results = this.Invoke("get_starting_hash_pattern", new object [] { profile_names}); return ((LocalLBProfileString [])(results[0])); } public System.IAsyncResult Beginget_starting_hash_pattern(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_starting_hash_pattern", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileString [] Endget_starting_hash_pattern(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileString [])(results[0])); } //----------------------------------------------------------------------- // get_timeout //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileULong [] get_timeout( string [] profile_names ) { object [] results = this.Invoke("get_timeout", new object [] { profile_names}); return ((LocalLBProfileULong [])(results[0])); } public System.IAsyncResult Beginget_timeout(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_timeout", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileULong [] Endget_timeout(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileULong [])(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // is_base_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public bool [] is_base_profile( string [] profile_names ) { object [] results = this.Invoke("is_base_profile", new object [] { profile_names}); return ((bool [])(results[0])); } public System.IAsyncResult Beginis_base_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("is_base_profile", new object[] { profile_names}, callback, asyncState); } public bool [] Endis_base_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((bool [])(results[0])); } //----------------------------------------------------------------------- // is_system_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public bool [] is_system_profile( string [] profile_names ) { object [] results = this.Invoke("is_system_profile", new object [] { profile_names}); return ((bool [])(results[0])); } public System.IAsyncResult Beginis_system_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("is_system_profile", new object[] { profile_names}, callback, asyncState); } public bool [] Endis_system_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((bool [])(results[0])); } //----------------------------------------------------------------------- // set_across_pool_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_across_pool_state( string [] profile_names, LocalLBProfileEnabledState [] states ) { this.Invoke("set_across_pool_state", new object [] { profile_names, states}); } public System.IAsyncResult Beginset_across_pool_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_across_pool_state", new object[] { profile_names, states}, callback, asyncState); } public void Endset_across_pool_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_across_service_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_across_service_state( string [] profile_names, LocalLBProfileEnabledState [] states ) { this.Invoke("set_across_service_state", new object [] { profile_names, states}); } public System.IAsyncResult Beginset_across_service_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_across_service_state", new object[] { profile_names, states}, callback, asyncState); } public void Endset_across_service_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_across_virtual_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_across_virtual_state( string [] profile_names, LocalLBProfileEnabledState [] states ) { this.Invoke("set_across_virtual_state", new object [] { profile_names, states}); } public System.IAsyncResult Beginset_across_virtual_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_across_virtual_state", new object[] { profile_names, states}, callback, asyncState); } public void Endset_across_virtual_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_cookie_always_send_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_cookie_always_send_state( string [] profile_names, LocalLBProfileEnabledState [] states ) { this.Invoke("set_cookie_always_send_state", new object [] { profile_names, states}); } public System.IAsyncResult Beginset_cookie_always_send_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_cookie_always_send_state", new object[] { profile_names, states}, callback, asyncState); } public void Endset_cookie_always_send_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_cookie_encryption //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_cookie_encryption( string [] profile_names, LocalLBProfilePersistenceProfileCookieEncryption [] types ) { this.Invoke("set_cookie_encryption", new object [] { profile_names, types}); } public System.IAsyncResult Beginset_cookie_encryption(string [] profile_names,LocalLBProfilePersistenceProfileCookieEncryption [] types, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_cookie_encryption", new object[] { profile_names, types}, callback, asyncState); } public void Endset_cookie_encryption(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_cookie_encryption_passphrase //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_cookie_encryption_passphrase( string [] profile_names, LocalLBProfileString [] encryption_passphrases ) { this.Invoke("set_cookie_encryption_passphrase", new object [] { profile_names, encryption_passphrases}); } public System.IAsyncResult Beginset_cookie_encryption_passphrase(string [] profile_names,LocalLBProfileString [] encryption_passphrases, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_cookie_encryption_passphrase", new object[] { profile_names, encryption_passphrases}, callback, asyncState); } public void Endset_cookie_encryption_passphrase(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_cookie_expiration //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_cookie_expiration( string [] profile_names, LocalLBProfileULong [] expirations ) { this.Invoke("set_cookie_expiration", new object [] { profile_names, expirations}); } public System.IAsyncResult Beginset_cookie_expiration(string [] profile_names,LocalLBProfileULong [] expirations, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_cookie_expiration", new object[] { profile_names, expirations}, callback, asyncState); } public void Endset_cookie_expiration(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_cookie_hash_length //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_cookie_hash_length( string [] profile_names, LocalLBProfileULong [] lengths ) { this.Invoke("set_cookie_hash_length", new object [] { profile_names, lengths}); } public System.IAsyncResult Beginset_cookie_hash_length(string [] profile_names,LocalLBProfileULong [] lengths, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_cookie_hash_length", new object[] { profile_names, lengths}, callback, asyncState); } public void Endset_cookie_hash_length(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_cookie_hash_offset //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_cookie_hash_offset( string [] profile_names, LocalLBProfileULong [] offsets ) { this.Invoke("set_cookie_hash_offset", new object [] { profile_names, offsets}); } public System.IAsyncResult Beginset_cookie_hash_offset(string [] profile_names,LocalLBProfileULong [] offsets, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_cookie_hash_offset", new object[] { profile_names, offsets}, callback, asyncState); } public void Endset_cookie_hash_offset(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_cookie_httponly_attribute //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_cookie_httponly_attribute( string [] profile_names, LocalLBProfileEnabledState [] states ) { this.Invoke("set_cookie_httponly_attribute", new object [] { profile_names, states}); } public System.IAsyncResult Beginset_cookie_httponly_attribute(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_cookie_httponly_attribute", new object[] { profile_names, states}, callback, asyncState); } public void Endset_cookie_httponly_attribute(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_cookie_name //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_cookie_name( string [] profile_names, LocalLBProfileString [] cookie_names ) { this.Invoke("set_cookie_name", new object [] { profile_names, cookie_names}); } public System.IAsyncResult Beginset_cookie_name(string [] profile_names,LocalLBProfileString [] cookie_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_cookie_name", new object[] { profile_names, cookie_names}, callback, asyncState); } public void Endset_cookie_name(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_cookie_persistence_method //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_cookie_persistence_method( string [] profile_names, LocalLBProfileCookiePersistenceMethod [] methods ) { this.Invoke("set_cookie_persistence_method", new object [] { profile_names, methods}); } public System.IAsyncResult Beginset_cookie_persistence_method(string [] profile_names,LocalLBProfileCookiePersistenceMethod [] methods, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_cookie_persistence_method", new object[] { profile_names, methods}, callback, asyncState); } public void Endset_cookie_persistence_method(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_cookie_secure_attribute //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_cookie_secure_attribute( string [] profile_names, LocalLBProfileEnabledState [] states ) { this.Invoke("set_cookie_secure_attribute", new object [] { profile_names, states}); } public System.IAsyncResult Beginset_cookie_secure_attribute(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_cookie_secure_attribute", new object[] { profile_names, states}, callback, asyncState); } public void Endset_cookie_secure_attribute(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_default_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_default_profile( string [] profile_names, string [] defaults ) { this.Invoke("set_default_profile", new object [] { profile_names, defaults}); } public System.IAsyncResult Beginset_default_profile(string [] profile_names,string [] defaults, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_default_profile", new object[] { profile_names, defaults}, callback, asyncState); } public void Endset_default_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_description( string [] profile_names, string [] descriptions ) { this.Invoke("set_description", new object [] { profile_names, descriptions}); } public System.IAsyncResult Beginset_description(string [] profile_names,string [] descriptions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_description", new object[] { profile_names, descriptions}, callback, asyncState); } public void Endset_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_ending_hash_pattern //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_ending_hash_pattern( string [] profile_names, LocalLBProfileString [] patterns ) { this.Invoke("set_ending_hash_pattern", new object [] { profile_names, patterns}); } public System.IAsyncResult Beginset_ending_hash_pattern(string [] profile_names,LocalLBProfileString [] patterns, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_ending_hash_pattern", new object[] { profile_names, patterns}, callback, asyncState); } public void Endset_ending_hash_pattern(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_hash_length //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_hash_length( string [] profile_names, LocalLBProfileULong [] lengths ) { this.Invoke("set_hash_length", new object [] { profile_names, lengths}); } public System.IAsyncResult Beginset_hash_length(string [] profile_names,LocalLBProfileULong [] lengths, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_hash_length", new object[] { profile_names, lengths}, callback, asyncState); } public void Endset_hash_length(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_hash_method //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_hash_method( string [] profile_names, LocalLBProfilePersistenceProfilePersistenceHashMethod [] methods ) { this.Invoke("set_hash_method", new object [] { profile_names, methods}); } public System.IAsyncResult Beginset_hash_method(string [] profile_names,LocalLBProfilePersistenceProfilePersistenceHashMethod [] methods, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_hash_method", new object[] { profile_names, methods}, callback, asyncState); } public void Endset_hash_method(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_hash_more_data_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_hash_more_data_state( string [] profile_names, LocalLBProfileEnabledState [] states ) { this.Invoke("set_hash_more_data_state", new object [] { profile_names, states}); } public System.IAsyncResult Beginset_hash_more_data_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_hash_more_data_state", new object[] { profile_names, states}, callback, asyncState); } public void Endset_hash_more_data_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_hash_offset //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_hash_offset( string [] profile_names, LocalLBProfileULong [] offsets ) { this.Invoke("set_hash_offset", new object [] { profile_names, offsets}); } public System.IAsyncResult Beginset_hash_offset(string [] profile_names,LocalLBProfileULong [] offsets, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_hash_offset", new object[] { profile_names, offsets}, callback, asyncState); } public void Endset_hash_offset(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_map_proxy_address //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_map_proxy_address( string [] profile_names, LocalLBProfileIPAddress [] addresses ) { this.Invoke("set_map_proxy_address", new object [] { profile_names, addresses}); } public System.IAsyncResult Beginset_map_proxy_address(string [] profile_names,LocalLBProfileIPAddress [] addresses, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_map_proxy_address", new object[] { profile_names, addresses}, callback, asyncState); } public void Endset_map_proxy_address(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_map_proxy_class //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_map_proxy_class( string [] profile_names, LocalLBProfileString [] classes ) { this.Invoke("set_map_proxy_class", new object [] { profile_names, classes}); } public System.IAsyncResult Beginset_map_proxy_class(string [] profile_names,LocalLBProfileString [] classes, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_map_proxy_class", new object[] { profile_names, classes}, callback, asyncState); } public void Endset_map_proxy_class(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_map_proxy_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_map_proxy_state( string [] profile_names, LocalLBProfileEnabledState [] states ) { this.Invoke("set_map_proxy_state", new object [] { profile_names, states}); } public System.IAsyncResult Beginset_map_proxy_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_map_proxy_state", new object[] { profile_names, states}, callback, asyncState); } public void Endset_map_proxy_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_mask //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_mask( string [] profile_names, LocalLBProfileIPAddress [] masks ) { this.Invoke("set_mask", new object [] { profile_names, masks}); } public System.IAsyncResult Beginset_mask(string [] profile_names,LocalLBProfileIPAddress [] masks, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_mask", new object[] { profile_names, masks}, callback, asyncState); } public void Endset_mask(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_maximum_hash_buffer_size //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_maximum_hash_buffer_size( string [] profile_names, LocalLBProfileULong [] sizes ) { this.Invoke("set_maximum_hash_buffer_size", new object [] { profile_names, sizes}); } public System.IAsyncResult Beginset_maximum_hash_buffer_size(string [] profile_names,LocalLBProfileULong [] sizes, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_maximum_hash_buffer_size", new object[] { profile_names, sizes}, callback, asyncState); } public void Endset_maximum_hash_buffer_size(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_mirror_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_mirror_state( string [] profile_names, LocalLBProfileEnabledState [] states ) { this.Invoke("set_mirror_state", new object [] { profile_names, states}); } public System.IAsyncResult Beginset_mirror_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_mirror_state", new object[] { profile_names, states}, callback, asyncState); } public void Endset_mirror_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_msrdp_without_session_directory_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_msrdp_without_session_directory_state( string [] profile_names, LocalLBProfileEnabledState [] states ) { this.Invoke("set_msrdp_without_session_directory_state", new object [] { profile_names, states}); } public System.IAsyncResult Beginset_msrdp_without_session_directory_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_msrdp_without_session_directory_state", new object[] { profile_names, states}, callback, asyncState); } public void Endset_msrdp_without_session_directory_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_override_connection_limit_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_override_connection_limit_state( string [] profile_names, LocalLBProfileEnabledState [] states ) { this.Invoke("set_override_connection_limit_state", new object [] { profile_names, states}); } public System.IAsyncResult Beginset_override_connection_limit_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_override_connection_limit_state", new object[] { profile_names, states}, callback, asyncState); } public void Endset_override_connection_limit_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_persistence_mode //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_persistence_mode( string [] profile_names, LocalLBProfilePersistenceMode [] modes ) { this.Invoke("set_persistence_mode", new object [] { profile_names, modes}); } public System.IAsyncResult Beginset_persistence_mode(string [] profile_names,LocalLBProfilePersistenceMode [] modes, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_persistence_mode", new object[] { profile_names, modes}, callback, asyncState); } public void Endset_persistence_mode(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_rule //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_rule( string [] profile_names, LocalLBProfileString [] rules ) { this.Invoke("set_rule", new object [] { profile_names, rules}); } public System.IAsyncResult Beginset_rule(string [] profile_names,LocalLBProfileString [] rules, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_rule", new object[] { profile_names, rules}, callback, asyncState); } public void Endset_rule(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_sip_info //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_sip_info( string [] profile_names, LocalLBProfileString [] sip_info_headers ) { this.Invoke("set_sip_info", new object [] { profile_names, sip_info_headers}); } public System.IAsyncResult Beginset_sip_info(string [] profile_names,LocalLBProfileString [] sip_info_headers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_sip_info", new object[] { profile_names, sip_info_headers}, callback, asyncState); } public void Endset_sip_info(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_starting_hash_pattern //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_starting_hash_pattern( string [] profile_names, LocalLBProfileString [] patterns ) { this.Invoke("set_starting_hash_pattern", new object [] { profile_names, patterns}); } public System.IAsyncResult Beginset_starting_hash_pattern(string [] profile_names,LocalLBProfileString [] patterns, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_starting_hash_pattern", new object[] { profile_names, patterns}, callback, asyncState); } public void Endset_starting_hash_pattern(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_timeout //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePersistence", RequestNamespace="urn:iControl:LocalLB/ProfilePersistence", ResponseNamespace="urn:iControl:LocalLB/ProfilePersistence")] public void set_timeout( string [] profile_names, LocalLBProfileULong [] timeouts ) { this.Invoke("set_timeout", new object [] { profile_names, timeouts}); } public System.IAsyncResult Beginset_timeout(string [] profile_names,LocalLBProfileULong [] timeouts, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_timeout", new object[] { profile_names, timeouts}, callback, asyncState); } public void Endset_timeout(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfilePersistence.CookieEncryption", Namespace = "urn:iControl")] public enum LocalLBProfilePersistenceCookieEncryption { PERSISTENCE_COOKIE_ENCRYPTION_UNKNOWN, PERSISTENCE_COOKIE_ENCRYPTION_PREFERRED, PERSISTENCE_COOKIE_ENCRYPTION_REQUIRED, PERSISTENCE_COOKIE_ENCRYPTION_OFF, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfilePersistence.PersistenceHashMethod", Namespace = "urn:iControl")] public enum LocalLBProfilePersistencePersistenceHashMethod { PERSISTENCE_HASH_NONE, PERSISTENCE_HASH_DEFAULT, PERSISTENCE_HASH_CARP, PERSISTENCE_HASH_UNKNOWN, } //======================================================================= // Structs //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfilePersistence.ProfileCookieEncryption", Namespace = "urn:iControl")] public partial class LocalLBProfilePersistenceProfileCookieEncryption { private LocalLBProfilePersistenceCookieEncryption valueField; public LocalLBProfilePersistenceCookieEncryption value { get { return this.valueField; } set { this.valueField = value; } } private bool default_flagField; public bool default_flag { get { return this.default_flagField; } set { this.default_flagField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfilePersistence.ProfilePersistenceHashMethod", Namespace = "urn:iControl")] public partial class LocalLBProfilePersistenceProfilePersistenceHashMethod { private LocalLBProfilePersistencePersistenceHashMethod valueField; public LocalLBProfilePersistencePersistenceHashMethod value { get { return this.valueField; } set { this.valueField = value; } } private bool default_flagField; public bool default_flag { get { return this.default_flagField; } set { this.default_flagField = value; } } }; }
namespace System.Activities.Presentation.PropertyEditing { using System; using System.Runtime; /// <summary> /// Concrete implementation of PropertyValueSource for a PropertyEntry that represents a Dependency Property /// </summary> [Fx.Tag.XamlVisible(false)] public class DependencyPropertyValueSource : PropertyValueSource { private static DependencyPropertyValueSource _dataBound; private static DependencyPropertyValueSource _systemResource; private static DependencyPropertyValueSource _localDynamicResource; private static DependencyPropertyValueSource _localStaticResource; private static DependencyPropertyValueSource _templateBinding; private static DependencyPropertyValueSource _customMarkupExtension; private static DependencyPropertyValueSource _local; private static DependencyPropertyValueSource _defaultValue; private static DependencyPropertyValueSource _inherited; private readonly ValueSource _source; /// <summary> /// The property is set to a value that is a data binding. /// </summary> public static DependencyPropertyValueSource DataBound { get { if (_dataBound == null) _dataBound = new DependencyPropertyValueSource(ValueSource.DataBound); return _dataBound; } } /// <summary> /// The property is set to a system resource. /// </summary> public static DependencyPropertyValueSource SystemResource { get { if (_systemResource == null) _systemResource = new DependencyPropertyValueSource(ValueSource.SystemResource); return _systemResource; } } /// <summary> /// The property is set to a DynamicResource reference. /// </summary> public static DependencyPropertyValueSource LocalDynamicResource { get { if (_localDynamicResource == null) _localDynamicResource = new DependencyPropertyValueSource(ValueSource.LocalDynamicResource); return _localDynamicResource; } } /// <summary> /// The property is set to a StaticResource reference. /// </summary> public static DependencyPropertyValueSource LocalStaticResource { get { if (_localStaticResource == null) _localStaticResource = new DependencyPropertyValueSource(ValueSource.LocalStaticResource); return _localStaticResource; } } /// <summary> /// The property is set to a TemplateBinding markup extension. /// </summary> public static DependencyPropertyValueSource TemplateBinding { get { if (_templateBinding == null) _templateBinding = new DependencyPropertyValueSource(ValueSource.TemplateBinding); return _templateBinding; } } /// <summary> /// The property is set to a custom markup extension. /// </summary> public static DependencyPropertyValueSource CustomMarkupExtension { get { if (_customMarkupExtension == null) _customMarkupExtension = new DependencyPropertyValueSource(ValueSource.CustomMarkupExtension); return _customMarkupExtension; } } /// <summary> /// The property is set to a local value. /// </summary> public static DependencyPropertyValueSource Local { get { if (_local == null) _local = new DependencyPropertyValueSource(ValueSource.Local); return _local; } } /// <summary> /// The property is set to its default value (ie. it does not have a value set in XAML and /// it's not inheriting any value from its parent) /// </summary> public static DependencyPropertyValueSource DefaultValue { get { if (_defaultValue == null) _defaultValue = new DependencyPropertyValueSource(ValueSource.DefaultValue); return _defaultValue; } } /// <summary> /// The property is inherited from a parent property. /// </summary> public static DependencyPropertyValueSource Inherited { get { if (_inherited == null) _inherited = new DependencyPropertyValueSource(ValueSource.Inherited); return _inherited; } } private DependencyPropertyValueSource(ValueSource source) { _source = source; } /// <summary> /// Read-only property that returns true if the property is set to an expression /// i.e. (DataBound, LocalDynamicResource, LocalStaticResource, SystemResource, TemplateBinding or /// CustomMarkupExtension) /// </summary> public bool IsExpression { get { return _source == ValueSource.DataBound || _source == ValueSource.LocalDynamicResource || _source == ValueSource.LocalStaticResource || _source == ValueSource.SystemResource || _source == ValueSource.TemplateBinding || _source == ValueSource.CustomMarkupExtension; } } /// <summary> /// Read-only property that returns true if the property is set to a system or local resource /// </summary> public bool IsResource { get { return _source == ValueSource.SystemResource || _source == ValueSource.LocalDynamicResource || _source == ValueSource.LocalStaticResource; } } /// <summary> /// Read-only property that returns true if the property is set to a data binding expression. /// </summary> public bool IsDataBound { get { return _source == ValueSource.DataBound; } } /// <summary> /// Read-only property that returns true if the property is set to a system resource /// </summary> public bool IsSystemResource { get { return _source == ValueSource.SystemResource; } } /// <summary> /// Read-only property that returns true if the property is set to a DynamicResource /// </summary> public bool IsLocalResource { get { return _source == ValueSource.LocalDynamicResource || _source == ValueSource.LocalStaticResource; } } /// <summary> /// Read-only property that returns true if the property is set to a TemplateBinding markup extension /// </summary> public bool IsTemplateBinding { get { return _source == ValueSource.TemplateBinding; } } /// <summary> /// Read-only property that returns true if the property is set to a custom markup extension. /// </summary> public bool IsCustomMarkupExtension { get { return _source == ValueSource.CustomMarkupExtension; } } /// <summary> /// Read-only property that returns true if the property is set to a local value. /// </summary> public bool IsLocal { get { return _source == ValueSource.Local; } } /// <summary> /// Read-only property that returns true if the property is set to its default value /// (ie. it does not have a value set in XAML and it's not inheriting any value from /// its parent) /// </summary> public bool IsDefaultValue { get { return _source == ValueSource.DefaultValue; } } /// <summary> /// Read-only property that returns true if the property is inherited. /// </summary> public bool IsInherited { get { return _source == ValueSource.Inherited; } } private enum ValueSource { DataBound, SystemResource, LocalDynamicResource, LocalStaticResource, TemplateBinding, CustomMarkupExtension, Local, DefaultValue, Inherited } } }
/* * GNUTLS.cs - Implementation of the "DotGNU.SSL.GNUTLS" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software, you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY, without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program, if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace DotGNU.SSL { #if CONFIG_RUNTIME_INFRA using System; using System.IO; using System.Runtime.InteropServices; using System.Security; using OpenSystem.Platform; // Secure session provider object that uses the GNUTLS library to // provide the underlying security functionality. internal unsafe sealed class GNUTLS : ISecureSessionProvider { // Internal state. private static bool initialized = false; // Constructor. public GNUTLS() { // Make sure that the GNUTLS library is initialized. lock(typeof(GNUTLS)) { if(!initialized) { try { gnutls_global_init(); } catch(Exception) { // Could not find the functions to execute, // so we probably don't have GNUTLS on this // system or it isn't on the LD_LIBRARY_PATH. throw new NotSupportedException(); } initialized = true; } } } // Implement the ISecureSessionProvider interface. public ISecureSession CreateClientSession(Protocol protocol) { return new GNUTLSSession(protocol, true); } public ISecureSession CreateServerSession(Protocol protocol) { return new GNUTLSSession(protocol, false); } // Credentials object for GNUTLS. private abstract class GNUTLSCredentials : IDisposable { // Internal state. protected IntPtr cred; private bool isDisposed; // Constructor. protected GNUTLSCredentials() {} // Finalizer. ~GNUTLSCredentials() { if(isDisposed == false) { Dispose(); } } // Get the credential pointer. public IntPtr Cred { get { return cred; } } // Get the credential type. public abstract int CredType { get; } // Dispose of this object. public virtual void Dispose() { cred = IntPtr.Zero; isDisposed = true; } }; // class GNUTLSCredentials // Credentials object that is based on a certificate/private key pair. private sealed class GNUTLSCertificateCredentials : GNUTLSCredentials { private bool isDisposed; // Constructor. public GNUTLSCertificateCredentials(byte[] certificate, byte[] key) { gnutls_certificate_allocate_credentials(out cred); gnutls_datum c = new gnutls_datum(certificate); gnutls_datum k = new gnutls_datum(key); gnutls_certificate_set_x509_key_mem (cred, ref c, ref k, 0 /* GNUTLS_X509_FMT_DER */); c.Free(); k.Free(); } // Finalizer. ~GNUTLSCertificateCredentials() { if(isDisposed == false) { Dispose(); } } // Get the credential type. public override int CredType { get { return 1; // GNUTLS_CRD_CERTIFICATE } } // Dispose of this object. public override void Dispose() { if(cred != IntPtr.Zero) { gnutls_certificate_free_credentials(cred); base.Dispose(); } } }; // class GNUTLSCertificateCredentials // Credentials object for anonymous access. private sealed class GNUTLSAnonCredentials : GNUTLSCredentials { private bool isDisposed; // Constructor. public GNUTLSAnonCredentials() { gnutls_certificate_allocate_credentials(out cred); } // Finalizer. ~GNUTLSAnonCredentials() { if(isDisposed == false) { Dispose(); } } // Get the credential type. public override int CredType { get { return 1; // GNUTLS_CRD_CERTIFICATE } } // Dispose of this object. public override void Dispose() { if(cred != IntPtr.Zero) { gnutls_certificate_free_credentials(cred); base.Dispose(); } isDisposed = true; } }; // class GNUTLSAnonCredentials // Session handling object for GNUTLS. private sealed class GNUTLSSession : ISecureSession, IDisposable { // Internal state. private Protocol protocol; private bool isClient; private byte[] certificate; private byte[] privateKey; private byte[] remoteCertificate; private GNUTLSStream stream; // Constructor. public GNUTLSSession(Protocol protocol, bool isClient) { this.protocol = protocol; this.isClient = isClient; } // Destructor. ~GNUTLSSession() { Dispose(); } // Implement the ISecureSession interface. public bool IsClient { get { return isClient; } } public byte[] Certificate { get { return certificate; } set { lock(this) { if(value == null) { throw new ArgumentNullException("value"); } if(certificate != null) { throw new InvalidOperationException(); } certificate = value; } } } public byte[] PrivateKey { get { return privateKey; } set { lock(this) { if(value == null) { throw new ArgumentNullException("value"); } if(privateKey != null) { throw new InvalidOperationException(); } privateKey = value; } } } public byte[] RemoteCertificate { get { return remoteCertificate; } } public Stream PerformHandshake(Object socket) { lock(this) { // Validate the parameter and state. if(socket == null) { throw new ArgumentNullException("socket"); } int fd = Utils.GetSocketFd(socket); if(fd == -1) { throw new ArgumentException(); } if(stream != null) { throw new InvalidOperationException(); } // Allocate and set the credentials object. GNUTLSCredentials cred; if(certificate != null && privateKey != null) { cred = new GNUTLSCertificateCredentials (certificate, privateKey); } else { cred = new GNUTLSAnonCredentials(); } if(cred.Cred == IntPtr.Zero) { throw new NotSupportedException(); } // Initialize the session object. IntPtr session = IntPtr.Zero; if(isClient) { gnutls_init(ref session, (Int)2 /* GNUTLS_CLIENT */); } else { gnutls_init(ref session, (Int)1 /* GNUTLS_SERVER */); } if(session == IntPtr.Zero) { cred.Dispose(); throw new NotSupportedException(); } // Set the default priority values and then // override for the protocol specifics. gnutls_set_default_priority(session); gnutls_certificate_type_set_priority (session, new Int [] {(Int)1, (Int)2, (Int)0}); switch(protocol) { case Protocol.AutoDetect: { // The defaults are already set up for this. } break; // Note: GNUTLS does not support SSLv2, so // we use SSLv3 in that case. case Protocol.SSLv2: case Protocol.SSLv3: { gnutls_protocol_set_priority (session, new Int [] {(Int)1, (Int)0}); } break; case Protocol.TLSv1: { gnutls_protocol_set_priority (session, new Int [] {(Int)2, (Int)0}); } break; default: { // Don't know what protocol to use. gnutls_deinit(session); cred.Dispose(); throw new NotSupportedException(); } } // Set the local X.509 credentials if necessary. gnutls_credentials_set (session, (Int)(cred.CredType), cred.Cred); // Associate the socket fd with the session. gnutls_transport_set_ptr(session, new IntPtr(fd)); // Attempt to connect or accept. int result = (int)gnutls_handshake(session); if(result < 0) { gnutls_deinit(session); cred.Dispose(); throw new SecurityException (gnutls_strerror((Int)result)); } // Get the remote certificate and record it. UInt size; gnutls_datum *x509 = gnutls_certificate_get_peers (session, out size); if(x509 != null) { int length = (int)(x509->size); if(length > 0) { remoteCertificate = new byte [length]; Marshal.Copy(x509->data, remoteCertificate, 0, length); } } // Create the stream object and return it. stream = new GNUTLSStream(session, cred); return stream; } } public Stream SecureStream { get { return stream; } } // Implement the IDisposable interface. public void Dispose() { if(stream != null) stream.Close(); } }; // class GNUTLSSession // Stream object for managing a secure connection. private sealed class GNUTLSStream : Stream { // Internal state. private IntPtr session; private GNUTLSCredentials cred; // Constructor. public GNUTLSStream(IntPtr session, GNUTLSCredentials cred) { this.session = session; this.cred = cred; } // Destructor. ~GNUTLSStream() { Close(); } // Close the stream. public override void Close() { lock(this) { if(session != IntPtr.Zero) { gnutls_bye(session, 0 /* GNUTLS_SHUT_RDWR */); gnutls_deinit(session); session = IntPtr.Zero; cred.Dispose(); } } } // Flush the pending contents in this stream. public override void Flush() { // Nothing to do here. } // Read data from this stream. public override int Read(byte[] buffer, int offset, int count) { Utils.ValidateBuffer(buffer, offset, count); lock(this) { if(session == IntPtr.Zero) { throw new ObjectDisposedException("stream"); } if(offset == 0) { return (int)gnutls_record_recv (session, buffer, (Int)count); } else { byte[] temp = new byte [count]; int result = (int)gnutls_record_recv (session, temp, (Int)count); if(result > 0) { Array.Copy(temp, 0, buffer, offset, result); } Array.Clear(temp, 0, count); return result; } } } // Seek to a new position within this stream. public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } // Set the length of this stream. public override void SetLength(long value) { throw new NotSupportedException(); } // Write to the stream, with a guaranteed zero-based offset. private void Write(byte[] buffer, int count) { int result; for(;;) { result = (int)gnutls_record_send (session, buffer, (Int)count); if(result != -52 && // GNUTLS_E_INTERRUPTED result != -28) // GNUTLS_E_AGAIN { break; } } } // Write a buffer of bytes to this stream. public override void Write(byte[] buffer, int offset, int count) { Utils.ValidateBuffer(buffer, offset, count); lock(this) { if(session == IntPtr.Zero) { throw new ObjectDisposedException("stream"); } if(offset == 0) { Write(buffer, count); } else if(count > 0) { byte[] temp = new byte [count]; Array.Copy(buffer, offset, temp, 0, count); Write(temp, count); Array.Clear(temp, 0, count); } } } // Determine if it is possible to read from this stream. public override bool CanRead { get { return true; } } // Determine if it is possible to seek within this stream. public override bool CanSeek { get { return false; } } // Determine if it is possible to write to this stream. public override bool CanWrite { get { return true; } } // Get the length of this stream. public override long Length { get { throw new NotSupportedException(); } } // Get the current position within the stream. public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } }; // class GNUTLSStream // Import the functions we need from the GNUTLS library. [DllImport("gnutls")] extern private static Int gnutls_global_init(); [DllImport("gnutls")] extern private static Int gnutls_certificate_allocate_credentials (out IntPtr sc); [DllImport("gnutls")] extern private static void gnutls_certificate_free_credentials(IntPtr sc); [DllImport("gnutls")] extern private static Int gnutls_anon_allocate_client_credentials (out IntPtr sc); [DllImport("gnutls")] extern private static void gnutls_anon_free_client_credentials(IntPtr sc); [DllImport("gnutls")] extern private static Int gnutls_anon_allocate_server_credentials (out IntPtr sc); [DllImport("gnutls")] extern private static void gnutls_anon_free_server_credentials(IntPtr sc); [DllImport("gnutls")] extern private static Int gnutls_init(ref IntPtr session, Int con_end); [DllImport("gnutls")] extern private static void gnutls_deinit(IntPtr session); [DllImport("gnutls")] extern private static Int gnutls_set_default_priority(IntPtr session); [DllImport("gnutls")] extern private static Int gnutls_protocol_set_priority (IntPtr session, Int[] list); [DllImport("gnutls")] extern private static Int gnutls_certificate_type_set_priority (IntPtr session, Int[] list); [DllImport("gnutls")] extern private static void gnutls_transport_set_ptr (IntPtr session, IntPtr ptr); [DllImport("gnutls")] extern private static Int gnutls_handshake(IntPtr session); [DllImport("gnutls")] extern private static String gnutls_strerror(Int error); [DllImport("gnutls")] extern private static Int gnutls_credentials_set (IntPtr session, Int type, IntPtr cred); [DllImport("gnutls")] extern private static gnutls_datum *gnutls_certificate_get_peers (IntPtr session, out UInt size); [DllImport("gnutls")] extern private static Int gnutls_bye(IntPtr session, Int how); [DllImport("gnutls")] extern private static Int gnutls_record_send (IntPtr session, byte[] data, Int size); [DllImport("gnutls")] extern private static Int gnutls_record_recv (IntPtr session, byte[] data, Int size); [DllImport("gnutls")] extern private static Int gnutls_certificate_set_x509_key_mem (IntPtr cred, ref gnutls_datum cert, ref gnutls_datum key, Int type); [StructLayout(LayoutKind.Sequential)] private struct gnutls_datum : IDisposable { public IntPtr data; public UInt size; private bool isDisposed; // Constructor. public gnutls_datum(byte[] value) { data = Marshal.AllocHGlobal(value.Length); Marshal.Copy(value, 0, data, value.Length); size = (UInt)(value.Length); } // Finalizer. // structs do not normally have finalizers, however // this one has unmanaged resources that needs to be freed ~gnutls_datum() { if(isDisposed == false) { Free(); } } // IDisposable interface because we have unmanaged resources public void Dispose() { if(isDisposed == false) { Free(); } isDisposed = true; } // Free the data in this object. public void Free() { Marshal.FreeHGlobal(data); data = IntPtr.Zero; size = (UInt)0; } }; // struct gnutls_datum }; // class GNUTLS #endif // CONFIG_RUNTIME_INFRA }; // namespace DotGNU.SSL
namespace Microsoft.Protocols.TestSuites.MS_OXORULE { using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestTools; /// <summary> /// Interface of MS-OXORULEAdapter. /// </summary> public interface IMS_OXORULEAdapter : IAdapter { /// <summary> /// Gets or sets the TargetOfRop. /// </summary> TargetOfRop TargetOfRop { get; set; } #region Defined in MS-OXORULE /// <summary> /// This ROP gets the rules table of a folder. /// </summary> /// <param name="objHandle">This index refers to the location in the Server object handle table used to find the handle for this operation.</param> /// <param name="tableFlags">These Flags control the Type of table. The possible values are specified in [MS-OXORULE].</param> /// <param name="getRulesTableResponse">Structure of RopGetRulesTableResponse.</param> /// <returns>Table handle.</returns> uint RopGetRulesTable(uint objHandle, TableFlags tableFlags, out RopGetRulesTableResponse getRulesTableResponse); /// <summary> /// This ROP updates the entry IDs in the deferred action messages. /// </summary> /// <param name="objHandle">This index refers to the location in the Server object handle table used to find the handle for this operation.</param> /// <param name="serverEntryId">This value specifies the ID of the message on the server.</param> /// <param name="clientEntryId">This value specifies the ID of the downloaded message on the client.</param> /// <returns>Structure of RopUpdateDeferredActionMessagesResponse.</returns> RopUpdateDeferredActionMessagesResponse RopUpdateDeferredActionMessages(uint objHandle, byte[] serverEntryId, byte[] clientEntryId); /// <summary> /// This ROP modifies the rules associated with a folder. /// </summary> /// <param name="objHandle">This index refers to the handle in the Server object handle table used as input for this operation.</param> /// <param name="modifyRulesFlags">The possible values are specified in [MS-OXORULE]. These Flags specify behavior of this operation.</param> /// <param name="ruleData">An array of RuleData structures, each of which specifies details about a standard rule.</param> /// <returns>Structure of RopModifyRulesResponse.</returns> RopModifyRulesResponse RopModifyRules(uint objHandle, ModifyRuleFlag modifyRulesFlags, RuleData[] ruleData); #endregion /// <summary> /// Clean environment. /// </summary> void CleanUp(); /// <summary> /// Get properties from nspi table. /// </summary> /// <param name="server">Server address.</param> /// <param name="userName">The value of User name.</param> /// <param name="domain">The value of Domain.</param> /// <param name="password">Password of the user.</param> /// <param name="columns">PropertyTags to be query.</param> /// <returns>Results in PropertyRowSet format.</returns> PropertyRowSet_r? GetRecipientInfo(string server, string userName, string domain, string password, PropertyTagArray_r? columns); #region Related ROPs /// <summary> /// This ROP gets specific properties of a message. /// </summary> /// <param name="objHandle">This index specifies the location in the Server object handle table where the handle for the input Server object is stored.</param> /// <param name="propertyTags">This field specifies the properties requested.</param> /// <returns>Structure of RopGetPropertiesSpecificResponse.</returns> RopGetPropertiesSpecificResponse RopGetPropertiesSpecific(uint objHandle, PropertyTag[] propertyTags); /// <summary> /// This ROP adds or modifies recipients on a message. /// </summary> /// <param name="objHandle">Handle to operate.</param> /// <param name="recipientColumns">Array of PropertyTag structures. The number of structures contained in this field is specified by the ColumnCount field. This field specifies the property values that can be included for each recipient.</param> /// <param name="recipientRows">List of ModifyRecipientRow structures. The number of structures contained in this field is specified by the RowCount field. .</param> /// <returns>Response of RopModifyRecipients.</returns> RopModifyRecipientsResponse RopModifyRecipients(uint objHandle, PropertyTag[] recipientColumns, ModifyRecipientRow[] recipientRows); /// <summary> /// This ROP submits a message for sending. /// </summary> /// <param name="objHandle">Handle to operate.</param> /// <param name="submitFlags">8-bit Flags structure. These Flags specify special behavior for submitting the message.</param> /// <returns>Structure of RopSubmitMessageResponse.</returns> RopSubmitMessageResponse RopSubmitMessage(uint objHandle, SubmitFlag submitFlags); /// <summary> /// This ROP deletes specific properties on a message. /// </summary> /// <param name="objHandle">This index specifies the location in the Server object handle table where the handle for the input Server object is stored.</param> /// <param name="propertyTags">Array of PropertyTag structures. This field specifies the property values to be deleted from the object.</param> /// <returns>Structure of RopDeletePropertiesResponse.</returns> RopDeletePropertiesResponse RopDeleteProperties(uint objHandle, PropertyTag[] propertyTags); /// <summary> /// This ROP gets the contents table of a container. /// </summary> /// <param name="handle">Handle to operate.</param> /// <param name="tableFlags">8-bit Flags structure. These Flags control the Type of table.</param> /// <param name="tableHandle">Handle of contents table.</param> /// <returns>Response of RopGetContentsTable.</returns> RopGetContentsTableResponse RopGetContentsTable(uint handle, ContentTableFlag tableFlags, out uint tableHandle); /// <summary> /// This ROP creates a new subfolder. /// </summary> /// <param name="handle">Handle to operate.</param> /// <param name="displayName">This value specifies the name of the created folder. .</param> /// <param name="comment">This value specifies the folder comment that is associated with the created folder.</param> /// <param name="createFolderResponse">Response of this ROP.</param> /// <returns>Handle of new folder.</returns> uint RopCreateFolder(uint handle, string displayName, string comment, out RopCreateFolderResponse createFolderResponse); /// <summary> /// This ROP sets specific properties on a message. /// </summary> /// <param name="objHandle">This index specifies the location in the Server object handle table where the handle for the input Server object is stored.</param> /// <param name="taggedPropertyValueArray">Array of TaggedPropertyValue structures. This field specifies the property values to be set on the object.</param> /// <returns>Structure of RopSetPropertiesResponse.</returns> RopSetPropertiesResponse RopSetProperties(uint objHandle, TaggedPropertyValue[] taggedPropertyValueArray); /// <summary> /// This ROP commits the changes made to a message. /// </summary> /// <param name="handle">Handle to operate.</param> /// <returns>Response of this ROP.</returns> RopSaveChangesMessageResponse RopSaveChangesMessage(uint handle); /// <summary> /// This ROP gets all properties on a message. /// </summary> /// <param name="objHandle">This index specifies the location in the Server object handle table where the handle for the input Server object is stored.</param> /// <param name="propertySizeLimit">This value specifies the maximum Size allowed for a property value returned.</param> /// <param name="wantUnicode">This value specifies whether to return string properties in Unicode.</param> /// <returns>Structure of RopGetPropertiesAllResponse.</returns> RopGetPropertiesAllResponse RopGetPropertiesAll(uint objHandle, ushort propertySizeLimit, ushort wantUnicode); /// <summary> /// This ROP creates a Message object in a mailbox. /// </summary> /// <param name="handle">Handle to operate.</param> /// <param name="folderId">This value identifies the parent folder.</param> /// <param name="isFAIMessage">8-bit Boolean. This value specifies whether the message is a folder associated information (FAI) message.</param> /// <param name="createMessageResponse">Response of this ROP.</param> /// <returns>Handle of the create message.</returns> uint RopCreateMessage(uint handle, ulong folderId, byte isFAIMessage, out RopCreateMessageResponse createMessageResponse); /// <summary> /// This ROP opens an existing message in a mailbox. /// </summary> /// <param name="handle">Handle to operate.</param> /// <param name="folderId">64-bit identifier. This value identifies the parent folder of the message to be opened.</param> /// <param name="messageId">64-bit identifier. This value identifies the message to be opened.</param> /// <param name="openMessageResponse">Response of this ROP.</param> /// <returns>Handle of the open message.</returns> uint RopOpenMessage(uint handle, ulong folderId, ulong messageId, out RopOpenMessageResponse openMessageResponse); /// <summary> /// This ROP logs on to a mailbox or public folder. /// </summary> /// <param name="logonType">This Type specifies ongoing action on the mailbox or public folder.</param> /// <param name="userESSDN">A string that identifies the user to log on to the server.</param> /// <param name="logonResponse">Response of this ROP.</param> /// <returns>Handle of logon object.</returns> uint RopLogon(LogonType logonType, string userESSDN, out RopLogonResponse logonResponse); /// <summary> /// This ROP opens an existing folder in a mailbox. /// </summary> /// <param name="handle">Handle to operate.</param> /// <param name="folderId">64-bit identifier. This identifier specifies the folder to be opened.</param> /// <param name="openFolderResponse">Response of this ROP.</param> /// <returns>Handle of the open folder.</returns> uint RopOpenFolder(uint handle, ulong folderId, out RopOpenFolderResponse openFolderResponse); /// <summary> /// This ROP deletes all messages and subfolders from a folder. /// </summary> /// <param name="handle">Handle to operate.</param> /// <param name="wantAsynchronous">8-bit Boolean. This value specifies whether the operation is to be executed asynchronously with status reported via RopProgress.</param> /// <returns>Response of this ROP.</returns> RopEmptyFolderResponse RopEmptyFolder(uint handle, byte wantAsynchronous); /// <summary> /// This ROP sets the properties visible on a table. /// </summary> /// <param name="objHandle">Handle to operate.</param> /// <param name="setColumnsFlags">8-bit Flags structure. These Flags control this operation.</param> /// <param name="propertyTags">Array of PropertyTag structures. This field specifies the property values that are visible in table rows.</param> /// <returns>Response of this ROP.</returns> RopSetColumnsResponse RopSetColumns(uint objHandle, byte setColumnsFlags, PropertyTag[] propertyTags); /// <summary> /// This ROP retrieves rows from a table. /// </summary> /// <param name="objHandle">Handle to operate.</param> /// <param name="queryRowsFlags">8-bit Flags structure. The possible values are specified in [MS-OXCTABL]. These Flags control this operation.</param> /// <param name="forwardRead">8-bit Boolean. This value specifies the direction to read rows.</param> /// <param name="rowCount">Unsigned 16-bit integer. This value specifies the number of requested rows.</param> /// <returns>Response of this ROP.</returns> RopQueryRowsResponse RopQueryRows(uint objHandle, byte queryRowsFlags, byte forwardRead, ushort rowCount); /// <summary> /// Delete specific folder. /// </summary> /// <param name="objHandle">object handle .</param> /// <param name="folderId">ID of the folder will be deleted.</param> /// <returns>ROP response of RopDeleteFolder.</returns> RopDeleteFolderResponse RopDeleteFolder(uint objHandle, ulong folderId); /// <summary> /// Release resources. /// </summary> /// <param name="handle">Unsigned integer value indicates the Server object Handle</param> void ReleaseRop(uint handle); /// <summary> /// Create rpc connection. /// </summary> /// <param name="connectionType">The type of connection.</param> /// <param name="userName">A string value indicates the domain account name that connects to server.</param> /// <param name="userESSDN">A string that identifies user who is making the EcDoConnectEx call</param> /// <param name="userPassword">A string value indicates the password of the user which is used.</param> /// <returns>Identify if the connection has been established.</returns> bool Connect(ConnectionType connectionType, string userName, string userESSDN, string userPassword); #endregion #region Help method /// <summary> /// Create Reply Template use settings in Util.cs file. /// It will be used by create Rule of ActioType: OP_REPLY /// </summary> /// <param name="inboxFolderHandle">The inbox folder's handle.</param> /// <param name="inboxFolderID">The inbox folder's ID.</param> /// <param name="isOOFReplyTemplate">Indicate whether the template to be created is a template for OP_REPLY or OP_OOF_REPLY .</param> /// <param name="templateSubject">The name of the template.</param> /// <param name="addedProperties">The properties that need to add to the reply template.</param> /// <param name="messageId">Message id of reply template message.</param> /// <param name="messageHandler">The reply message Handler.</param> /// <returns>Return the ReplyTemplateGUID.</returns> byte[] CreateReplyTemplate(uint inboxFolderHandle, ulong inboxFolderID, bool isOOFReplyTemplate, string templateSubject, TaggedPropertyValue[] addedProperties, out ulong messageId, out uint messageHandler); /// <summary> /// Query properties in contents table. /// </summary> /// <param name="tableHandle">Handle of a specific contents table.</param> /// <param name="propertyTags">Array of PropertyTag structures. This field specifies the property values that are visible in table rows.</param> /// <returns>Response of this query rows.</returns> RopQueryRowsResponse QueryPropertiesInTable(uint tableHandle, PropertyTag[] propertyTags); /// <summary> /// Get LongTermId from object id. /// </summary> /// <param name="objHandle">object handle.</param> /// <param name="objId">Object id value.</param> /// <returns>ROP response.</returns> RopLongTermIdFromIdResponse GetLongTermId(uint objHandle, ulong objId); /// <summary> /// Get notification detail from server. /// </summary> /// <returns>Notify ROP response.</returns> RopNotifyResponse NotificationProcess(); /// <summary> /// Get folder entryid bytes array. /// </summary> /// <param name="storeObjectType">Identify the store object is a mailbox or a public folder.</param> /// <param name="objHandle">Logon handle.</param> /// <param name="folderid">Folder id value.</param> /// <returns>Folder entryid bytes array.</returns> byte[] GetFolderEntryId(StoreObjectType storeObjectType, uint objHandle, ulong folderid); /// <summary> /// Get message EntryID bytes array. /// </summary> /// <param name="folderHandle">Folder handle which the message exist.</param> /// <param name="folderId">Folder id value.</param> /// <param name="messageHandle">message handle.</param> /// <param name="messageId">Message id value.</param> /// <returns>Message EntryID bytes array.</returns> byte[] GetMessageEntryId(uint folderHandle, ulong folderId, uint messageHandle, ulong messageId); #endregion } }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; using System.Text; namespace FileSystemTest { public class MemoryStreamWrite : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // TODO: Add your set up steps here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } //TODO Test with position longer then length #region Local Helper methods private bool TestWrite(MemoryStream ms, int length) { return TestWrite(ms, length, length, 0); } private bool TestWrite(MemoryStream ms, int length, long ExpectedLength) { return TestWrite(ms, length, length, 0, ExpectedLength); } private bool TestWrite(MemoryStream ms, int BufferLength, int BytesToWrite, int Offset) { return TestWrite(ms, BufferLength, BytesToWrite, Offset, ms.Position + BytesToWrite); } private bool TestWrite(MemoryStream ms, int BufferLength, int BytesToWrite, int Offset, long ExpectedLength) { bool result = true; long startLength = ms.Position; byte nextbyte = (byte)(startLength & 0xFF); byte[] byteBuffer = new byte[BufferLength]; for (int i = Offset; i < (Offset + BytesToWrite); i++) { byteBuffer[i] = (byte)nextbyte; nextbyte++; } ms.Write(byteBuffer, Offset, BytesToWrite); ms.Flush(); if (ExpectedLength < ms.Length) { result = false; Log.Exception("Expeceted final length of " + ExpectedLength + " bytes, but got " + ms.Length + " bytes"); } return result; } #endregion Local Helper methods #region Test Cases [TestMethod] public MFTestResults InvalidCases() { MemoryStream fs = new MemoryStream(); byte[] writebuff = new byte[1024]; MFTestResults result = MFTestResults.Pass; try { try { Log.Comment("Write to null buffer"); fs.Write(null, 0, writebuff.Length); Log.Exception( "Expected ArgumentNullException" ); return MFTestResults.Fail; } catch (ArgumentNullException ane) { /* pass case */ Log.Comment( "Got correct exception: " + ane.Message ); result = MFTestResults.Pass; } try { Log.Comment("Write to negative offset"); fs.Write(writebuff, -1, writebuff.Length); Log.Exception( "Expected ArgumentOutOfRangeException" ); return MFTestResults.Fail; } catch (ArgumentOutOfRangeException aoore) { /* pass case */ Log.Comment( "Got correct exception: " + aoore.Message ); result = MFTestResults.Pass; } try { Log.Comment("Write to out of range offset"); fs.Write(writebuff, writebuff.Length + 1, writebuff.Length); Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("Write negative count"); fs.Write(writebuff, 0, -1); // previous Bug # 21669 Log.Exception( "Expected ArgumentOutOfRangeException" ); return MFTestResults.Fail; } catch (ArgumentOutOfRangeException aoore) { /* pass case */ Log.Comment( "Got correct exception: " + aoore.Message ); result = MFTestResults.Pass; } try { Log.Comment("Write count larger then buffer"); fs.Write(writebuff, 0, writebuff.Length + 1); Log.Exception( "Expected ArgumentException" ); return MFTestResults.Fail; } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); result = MFTestResults.Pass; } try { Log.Comment("Write closed stream"); fs.Close(); fs.Write(writebuff, 0, writebuff.Length); Log.Exception( "Expected ObjectDisposedException" ); return MFTestResults.Fail; } catch (ObjectDisposedException ode) { /* pass case */ Log.Comment( "Got correct exception: " + ode.Message ); result = MFTestResults.Pass; } try { Log.Comment("Write disposed stream"); fs = new MemoryStream(); fs.Dispose(); fs.Write(writebuff, 0, writebuff.Length); Log.Exception( "Expected ObjectDisposedException" ); return MFTestResults.Fail; } catch (ObjectDisposedException ode) { /* pass case */ Log.Comment( "Got correct exception: " + ode.Message ); result = MFTestResults.Pass; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } finally { if (fs != null) fs.Dispose(); } return result; } [TestMethod] public MFTestResults VanillaWrite_Dynamic_Ctor() { MFTestResults result = MFTestResults.Pass; try { using (MemoryStream ms = new MemoryStream()) { Log.Comment("Write 256 bytes of data"); if (!TestWrite(ms, 256)) return MFTestResults.Fail; Log.Comment("Write middle of buffer"); if (!TestWrite(ms, 256, 100, 100)) return MFTestResults.Fail; // 1000 - 256 - 100 = 644 Log.Comment("Write start of buffer"); if (!TestWrite(ms, 1000, 644, 0)) return MFTestResults.Fail; Log.Comment("Write end of buffer"); if (!TestWrite(ms, 1000, 900, 100)) return MFTestResults.Fail; Log.Comment("Rewind and verify all bytes written"); ms.Seek(0, SeekOrigin.Begin); if (!MemoryStreamHelper.VerifyRead(ms)) return MFTestResults.Fail; Log.Comment("Verify Read validation with UTF8 string"); ms.SetLength(0); string test = "MFFramework Test"; ms.Write(UTF8Encoding.UTF8.GetBytes(test), 0, test.Length); ms.Flush(); ms.Seek(0, SeekOrigin.Begin); byte[] readbuff = new byte[20]; int readlen = ms.Read(readbuff, 0, readbuff.Length); string testResult = new string(Encoding.UTF8.GetChars(readbuff, 0, readlen)); if (test != testResult) { Log.Comment( "Exepected: " + test + ", but got: " + testResult ); return MFTestResults.Fail; } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults VanillaWrite_Static_Ctor() { MFTestResults result = MFTestResults.Pass; try { byte[] buffer = new byte[1024]; using (MemoryStream ms = new MemoryStream(buffer)) { Log.Comment("Write 256 bytes of data"); if (!TestWrite(ms, 256, 1024)) return MFTestResults.Fail; Log.Comment("Write middle of buffer"); if (!TestWrite(ms, 256, 100, 100, 1024)) return MFTestResults.Fail; // 1000 - 256 - 100 = 644 Log.Comment("Write start of buffer"); if (!TestWrite(ms, 1000, 644, 0, 1024)) return MFTestResults.Fail; Log.Comment("Write past end of buffer"); try { TestWrite(ms, 50, 1024); Log.Exception( "Expected NotSupportedException" ); return MFTestResults.Fail; } catch (NotSupportedException nse) { /* pass case */ Log.Comment( "Got correct exception: " + nse.Message ); result = MFTestResults.Pass; } Log.Comment("Verify failed Write did not move position"); if (ms.Position != 1000) { Log.Comment( "Expected position to be 1000, but it is " + ms.Position ); return MFTestResults.Fail; } Log.Comment("Write final 24 bytes of static buffer"); if (!TestWrite(ms, 24)) return MFTestResults.Fail; Log.Comment("Rewind and verify all bytes written"); ms.Seek(0, SeekOrigin.Begin); if (!MemoryStreamHelper.VerifyRead(ms)) return MFTestResults.Fail; Log.Comment("Verify Read validation with UTF8 string"); ms.SetLength(0); string test = "MFFramework Test"; ms.Write(UTF8Encoding.UTF8.GetBytes(test), 0, test.Length); ms.Flush(); ms.Seek(0, SeekOrigin.Begin); byte[] readbuff = new byte[20]; int readlen = ms.Read(readbuff, 0, readbuff.Length); string testResult = new string(Encoding.UTF8.GetChars(readbuff, 0, readlen)); if (test != testResult) { Log.Comment( "Exepected: " + test + ", but got: " + testResult ); return MFTestResults.Fail; } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ShiftBuffer() { MFTestResults result = MFTestResults.Pass; try { int bufSize; int iCountErrors = 0; for (int i = 1; i < 10; i++) { bufSize = i; MemoryStream ms = new MemoryStream(); for (int j = 0; j < bufSize; ++j) ms.WriteByte((byte)j); // Move everything forward by 1 byte ms.Seek(0, SeekOrigin.Begin); byte[] buf = ms.ToArray(); ms.Write(buf, 1, bufSize - 1); ms.Seek(0, SeekOrigin.Begin); //we'll read till one before the last since these should be shifted by 1 for (int j = 0; j < ms.Length - 1; ++j) { int bit = ms.ReadByte(); if (bit != j + 1) { ++iCountErrors; Log.Exception("Err_8324t! Check VSWhdibey #458551, Returned: " + bit + ", Expected: " + (j + 1)); } } //last bit should be the same if (ms.ReadByte() != i - 1) { ++iCountErrors; Log.Exception("Err_32947gs! Last bit is not correct Check VSWhdibey #458551"); } } //Buffer sizes of 9 (10 here since we shift by 1) and above doesn't have the above 'optimization' problem for (int i = 10; i < 64; i++) { bufSize = i; MemoryStream ms = new MemoryStream(); for (int j = 0; j < bufSize; ++j) ms.WriteByte((byte)j); // Move everything forward by 1 byte ms.Seek(0, SeekOrigin.Begin); byte[] buf = ms.ToArray(); ms.Write(buf, 1, bufSize - 1); ms.Seek(0, SeekOrigin.Begin); for (int j = 0; j < ms.Length; ++j) { int bit = ms.ReadByte(); if (j != ms.Length - 1) { if (bit != (j + 1)) { ++iCountErrors; Log.Exception("Err_235radg_" + i + "! Check VSWhdibey #458551, Returned: " + bit + ", Expected: " + (j + 1)); } } else if (bit != j) { ++iCountErrors; Log.Exception("Err_235radg_" + i + "! Check VSWhdibey #458551, Returned: " + bit + ", Expected:" + (j + 1)); } } } if (iCountErrors > 0) return MFTestResults.Fail; } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults BoundaryCheck() { MFTestResults result = MFTestResults.Pass; try { for (int i = 250; i < 260; i++) { using (MemoryStream ms = new MemoryStream()) { TestWrite(ms, i); ms.Position = 0; if (!MemoryStreamHelper.VerifyRead(ms)) return MFTestResults.Fail; Log.Comment("Position: " + ms.Position); Log.Comment("Length: " + ms.Length); if (i != ms.Position | i != ms.Length) { Log.Exception( "Expected Position and Length to be " + i ); return MFTestResults.Fail; } } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( InvalidCases, "InvalidCases" ), new MFTestMethod( VanillaWrite_Dynamic_Ctor, "VanillaWrite_Dynamic_Ctor" ), new MFTestMethod( VanillaWrite_Static_Ctor, "VanillaWrite_Static_Ctor" ), new MFTestMethod( ShiftBuffer, "ShiftBuffer" ), new MFTestMethod( BoundaryCheck, "BoundaryCheck" ), }; } } } }
using System.Linq; using System.Threading; using System.Collections.Generic; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Formatting; namespace RefactoringEssentials.CSharp.CodeRefactorings { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = "Import static class with using directive in file")] public class ImportStaticClassWithUsingCodeRefactoringProvider : CodeRefactoringProvider { public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var document = context.Document; if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) return; var span = context.Span; if (!span.IsEmpty) return; var cancellationToken = context.CancellationToken; if (cancellationToken.IsCancellationRequested) return; var options = document.Project.ParseOptions as CSharpParseOptions; if (options != null && options.LanguageVersion < LanguageVersion.CSharp6) return; var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); if (model.IsFromGeneratedCode(cancellationToken)) return; var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var node = root.FindToken(span.Start).Parent; if (!(node.Parent is MemberAccessExpressionSyntax)) return; var info = model.GetSymbolInfo(node, cancellationToken); if (info.Symbol == null || info.Symbol.Kind != SymbolKind.NamedType || !info.Symbol.IsStatic) return; context.RegisterRefactoring( CodeActionFactory.Create( node.Span, DiagnosticSeverity.Info, GettextCatalog.GetString("Import static class with using"), t2 => { return ImportStaticClassWithUsing(document, model, root, node, info, t2); } ) ); } async Task<Document> ImportStaticClassWithUsing(Document document, SemanticModel model, SyntaxNode root, SyntaxNode node, SymbolInfo info, CancellationToken cancellationToken) { var cu = root as CompilationUnitSyntax; var staticUsing = SyntaxFactory .UsingDirective(SyntaxFactory.ParseName(info.Symbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat))) .WithStaticKeyword(SyntaxFactory.Token(SyntaxKind.StaticKeyword)) .WithAdditionalAnnotations(Formatter.Annotation); cu = cu.AddUsingDirective(staticUsing, node, true); var newDoc = document.WithSyntaxRoot(cu); var newModel = await newDoc.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var visitor = new SearchImportReplacementsVisitor(newModel, info, cancellationToken); var newRoot = await newModel.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); visitor.Visit(newRoot); cu = (CompilationUnitSyntax)newRoot.TrackNodes(visitor.ReplaceNodes); foreach (var ma in visitor.ReplaceNodes) { var current = cu.GetCurrentNode<MemberAccessExpressionSyntax>(ma); cu = cu.ReplaceNode(current, current.Name.WithAdditionalAnnotations(Formatter.Annotation)); } return document.WithSyntaxRoot(cu); } class SearchImportReplacementsVisitor : CSharpSyntaxWalker { readonly SemanticModel model; readonly SymbolInfo info; readonly CancellationToken cancellationToken; public List<MemberAccessExpressionSyntax> ReplaceNodes = new List<MemberAccessExpressionSyntax>(); public SearchImportReplacementsVisitor(Microsoft.CodeAnalysis.SemanticModel model, Microsoft.CodeAnalysis.SymbolInfo info, CancellationToken cancellationToken) { this.cancellationToken = cancellationToken; this.model = model; this.info = info; } public override void VisitBlock(BlockSyntax node) { cancellationToken.ThrowIfCancellationRequested(); var tokens = new List<SyntaxToken>(); foreach (var statement in node.Statements) { if (statement.Kind() == SyntaxKind.LocalDeclarationStatement) { var declarationStatement = (LocalDeclarationStatementSyntax)statement; tokens.AddRange(declarationStatement.Declaration.Variables.Select(d => d.Identifier)); } } foreach (var token in tokens) AddName(token.ValueText); DefaultVisit(node); foreach (var token in tokens) RemoveName(token.ValueText); } List<string> GetMemberNames(TypeDeclarationSyntax node) { var result = new List<string>(); var sym = model.GetSymbolInfo(node).Symbol as INamedTypeSymbol; if (sym != null) { result.AddRange(sym.MemberNames); } else { foreach (var member in node.Members) { result.Add(GetNameToken(member).ValueText); } } return result; } public static SyntaxToken GetNameToken(MemberDeclarationSyntax member) { if (member != null) { switch (member.Kind()) { case SyntaxKind.EnumDeclaration: return ((EnumDeclarationSyntax)member).Identifier; case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: return ((TypeDeclarationSyntax)member).Identifier; case SyntaxKind.DelegateDeclaration: return ((DelegateDeclarationSyntax)member).Identifier; case SyntaxKind.FieldDeclaration: return ((FieldDeclarationSyntax)member).Declaration.Variables.First().Identifier; case SyntaxKind.EventFieldDeclaration: return ((EventFieldDeclarationSyntax)member).Declaration.Variables.First().Identifier; case SyntaxKind.PropertyDeclaration: return ((PropertyDeclarationSyntax)member).Identifier; case SyntaxKind.EventDeclaration: return ((EventDeclarationSyntax)member).Identifier; case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)member).Identifier; } } // Constructors, destructors, indexers and operators don't have names. return default(SyntaxToken); } public override void VisitClassDeclaration(ClassDeclarationSyntax node) { var memberNames = GetMemberNames(node); foreach (var token in memberNames) AddName(token); base.VisitClassDeclaration(node); foreach (var token in memberNames) RemoveName(token); } Dictionary<string, int> conflictNames = new Dictionary<string, int>(); void RemoveName(string name) { if (conflictNames.ContainsKey(name)) { conflictNames[name]--; } } void AddName(string name) { if (!conflictNames.ContainsKey(name)) { conflictNames[name] = 1; return; } conflictNames[name]++; } public override void VisitStructDeclaration(StructDeclarationSyntax node) { var memberNames = GetMemberNames(node); foreach (var token in memberNames) AddName(token); base.VisitStructDeclaration(node); foreach (var token in memberNames) RemoveName(token); } public override void VisitMemberAccessExpression(MemberAccessExpressionSyntax node) { if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { var baseInfo = model.GetSymbolInfo(node.Expression); if (baseInfo.Symbol == info.Symbol) { var name = node.Name.ToString(); if (!conflictNames.ContainsKey(name) || conflictNames[name] <= 0) ReplaceNodes.Add(node); } } base.VisitMemberAccessExpression(node); } } } }
using System.ComponentModel; using System.Data; using System.Drawing.Printing; using DevExpress.XtraPrinting; using DevExpress.XtraReports.UI; using EIDSS.Reports.BaseControls.BaseDataSetTableAdapters; namespace EIDSS.Reports.BaseControls.Report { partial class BaseReport { /// <summary> /// Required designer variable. /// </summary> protected IContainer components; /// <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() { ComponentResourceManager resources = new ComponentResourceManager(typeof(BaseReport)); this.Detail = new DetailBand(); this.PageHeader = new PageHeaderBand(); this.PageFooter = new PageFooterBand(); this.xrPageInfo1 = new XRPageInfo(); this.formattingRule1 = new FormattingRule(); this.m_BaseDataSet = new BaseDataSet(); this.ReportHeader = new ReportHeaderBand(); this.tableBaseHeader = new XRTable(); this.rowReportName = new XRTableRow(); this.cellBaseLeftHeader = new XRTableCell(); this.tableBaseInnerHeader = new XRTable(); this.rowBaseDate = new XRTableRow(); this.cellDateHeader = new XRTableCell(); this.cellDate = new XRTableCell(); this.rowBaseTime = new XRTableRow(); this.cellTimeHeader = new XRTableCell(); this.cellTime = new XRTableCell(); this.rowBaseLanguage = new XRTableRow(); this.cellLanguageHeader = new XRTableCell(); this.cellLanguage = new XRTableCell(); this.cellReportHeader = new XRTableCell(); this.lblReportName = new XRLabel(); this.rowBaseCountrySite = new XRTableRow(); this.cellBaseCountry = new XRTableCell(); this.cellBaseSite = new XRTableCell(); this.m_BaseAdapter = new BaseAdapter(); this.topMarginBand1 = new TopMarginBand(); this.bottomMarginBand1 = new BottomMarginBand(); ((ISupportInitialize)(this.m_BaseDataSet)).BeginInit(); ((ISupportInitialize)(this.tableBaseHeader)).BeginInit(); ((ISupportInitialize)(this.tableBaseInnerHeader)).BeginInit(); ((ISupportInitialize)(this)).BeginInit(); // // Detail // resources.ApplyResources(this.Detail, "Detail"); this.Detail.Name = "Detail"; this.Detail.Padding = new PaddingInfo(0, 2, 0, 2, 100F); this.Detail.StylePriority.UseFont = false; this.Detail.StylePriority.UsePadding = false; // // PageHeader // resources.ApplyResources(this.PageHeader, "PageHeader"); this.PageHeader.Name = "PageHeader"; this.PageHeader.Padding = new PaddingInfo(2, 2, 2, 2, 100F); this.PageHeader.StylePriority.UseFont = false; this.PageHeader.StylePriority.UsePadding = false; // // PageFooter // this.PageFooter.Borders = ((BorderSide)((((BorderSide.Left | BorderSide.Top) | BorderSide.Right) | BorderSide.Bottom))); this.PageFooter.Controls.AddRange(new XRControl[] { this.xrPageInfo1}); resources.ApplyResources(this.PageFooter, "PageFooter"); this.PageFooter.Name = "PageFooter"; this.PageFooter.Padding = new PaddingInfo(0, 0, 0, 0, 100F); this.PageFooter.StylePriority.UseBorders = false; // // xrPageInfo1 // this.xrPageInfo1.Borders = BorderSide.None; resources.ApplyResources(this.xrPageInfo1, "xrPageInfo1"); this.xrPageInfo1.Name = "xrPageInfo1"; this.xrPageInfo1.Padding = new PaddingInfo(2, 2, 0, 0, 100F); this.xrPageInfo1.StylePriority.UseBorders = false; // // formattingRule1 // this.formattingRule1.DataSource = this.m_BaseDataSet; this.formattingRule1.Name = "formattingRule1"; // // baseDataSet1 // this.m_BaseDataSet.DataSetName = "BaseDataSet"; this.m_BaseDataSet.SchemaSerializationMode = SchemaSerializationMode.IncludeSchema; // // ReportHeader // this.ReportHeader.Controls.AddRange(new XRControl[] { this.tableBaseHeader}); resources.ApplyResources(this.ReportHeader, "ReportHeader"); this.ReportHeader.Name = "ReportHeader"; // // tableBaseHeader // this.tableBaseHeader.Borders = ((BorderSide)((((BorderSide.Left | BorderSide.Top) | BorderSide.Right) | BorderSide.Bottom))); this.tableBaseHeader.BorderWidth = 2; resources.ApplyResources(this.tableBaseHeader, "tableBaseHeader"); this.tableBaseHeader.Name = "tableBaseHeader"; this.tableBaseHeader.Padding = new PaddingInfo(2, 2, 0, 0, 100F); this.tableBaseHeader.Rows.AddRange(new XRTableRow[] { this.rowReportName, this.rowBaseCountrySite}); this.tableBaseHeader.StylePriority.UseBorders = false; this.tableBaseHeader.StylePriority.UseBorderWidth = false; this.tableBaseHeader.StylePriority.UseFont = false; this.tableBaseHeader.StylePriority.UsePadding = false; this.tableBaseHeader.StylePriority.UseTextAlignment = false; // // rowReportName // this.rowReportName.Cells.AddRange(new XRTableCell[] { this.cellBaseLeftHeader, this.cellReportHeader}); resources.ApplyResources(this.rowReportName, "rowReportName"); this.rowReportName.Name = "rowReportName"; this.rowReportName.Weight = 3.0454320987654322; // // cellBaseLeftHeader // this.cellBaseLeftHeader.Controls.AddRange(new XRControl[] { this.tableBaseInnerHeader}); resources.ApplyResources(this.cellBaseLeftHeader, "cellBaseLeftHeader"); this.cellBaseLeftHeader.Name = "cellBaseLeftHeader"; this.cellBaseLeftHeader.Weight = 1.1309915624438993; // // tableBaseInnerHeader // this.tableBaseInnerHeader.Borders = ((BorderSide)((((BorderSide.Left | BorderSide.Top) | BorderSide.Right) | BorderSide.Bottom))); this.tableBaseInnerHeader.BorderWidth = 2; resources.ApplyResources(this.tableBaseInnerHeader, "tableBaseInnerHeader"); this.tableBaseInnerHeader.Name = "tableBaseInnerHeader"; this.tableBaseInnerHeader.Padding = new PaddingInfo(2, 2, 0, 0, 100F); this.tableBaseInnerHeader.Rows.AddRange(new XRTableRow[] { this.rowBaseDate, this.rowBaseTime, this.rowBaseLanguage}); this.tableBaseInnerHeader.StylePriority.UseBorders = false; this.tableBaseInnerHeader.StylePriority.UseBorderWidth = false; this.tableBaseInnerHeader.StylePriority.UseFont = false; this.tableBaseInnerHeader.StylePriority.UsePadding = false; this.tableBaseInnerHeader.StylePriority.UseTextAlignment = false; // // rowBaseDate // this.rowBaseDate.Cells.AddRange(new XRTableCell[] { this.cellDateHeader, this.cellDate}); resources.ApplyResources(this.rowBaseDate, "rowBaseDate"); this.rowBaseDate.Name = "rowBaseDate"; this.rowBaseDate.Weight = 1; // // cellDateHeader // resources.ApplyResources(this.cellDateHeader, "cellDateHeader"); this.cellDateHeader.Name = "cellDateHeader"; this.cellDateHeader.Weight = 0.40595618793024008; // // cellDate // resources.ApplyResources(this.cellDate, "cellDate"); this.cellDate.Name = "cellDate"; this.cellDate.Padding = new PaddingInfo(4, 4, 0, 0, 100F); this.cellDate.Weight = 0.2044202108490073; // // rowBaseTime // this.rowBaseTime.Cells.AddRange(new XRTableCell[] { this.cellTimeHeader, this.cellTime}); resources.ApplyResources(this.rowBaseTime, "rowBaseTime"); this.rowBaseTime.Name = "rowBaseTime"; this.rowBaseTime.StylePriority.UseBorders = false; this.rowBaseTime.Weight = 1; // // cellTimeHeader // resources.ApplyResources(this.cellTimeHeader, "cellTimeHeader"); this.cellTimeHeader.Name = "cellTimeHeader"; this.cellTimeHeader.Weight = 0.40595618793024008; // // cellTime // resources.ApplyResources(this.cellTime, "cellTime"); this.cellTime.Name = "cellTime"; this.cellTime.Padding = new PaddingInfo(4, 4, 0, 0, 100F); this.cellTime.Weight = 0.2044202108490073; // // rowBaseLanguage // this.rowBaseLanguage.Cells.AddRange(new XRTableCell[] { this.cellLanguageHeader, this.cellLanguage}); resources.ApplyResources(this.rowBaseLanguage, "rowBaseLanguage"); this.rowBaseLanguage.Name = "rowBaseLanguage"; this.rowBaseLanguage.Weight = 1; // // cellLanguageHeader // resources.ApplyResources(this.cellLanguageHeader, "cellLanguageHeader"); this.cellLanguageHeader.Multiline = true; this.cellLanguageHeader.Name = "cellLanguageHeader"; this.cellLanguageHeader.Weight = 0.40595618793024008; // // cellLanguage // this.cellLanguage.DataBindings.AddRange(new XRBinding[] { new XRBinding("Text", null, "sprepGetBaseParameters.LanguageName")}); resources.ApplyResources(this.cellLanguage, "cellLanguage"); this.cellLanguage.Name = "cellLanguage"; this.cellLanguage.Padding = new PaddingInfo(4, 4, 0, 0, 100F); this.cellLanguage.StylePriority.UseTextAlignment = false; this.cellLanguage.Weight = 0.2044202108490073; // // cellReportHeader // this.cellReportHeader.Controls.AddRange(new XRControl[] { this.lblReportName}); resources.ApplyResources(this.cellReportHeader, "cellReportHeader"); this.cellReportHeader.Name = "cellReportHeader"; this.cellReportHeader.StylePriority.UseBorders = false; this.cellReportHeader.StylePriority.UseFont = false; this.cellReportHeader.StylePriority.UseTextAlignment = false; this.cellReportHeader.Weight = 2.8576386811082521; // // lblReportName // this.lblReportName.Borders = BorderSide.None; this.lblReportName.BorderWidth = 0; resources.ApplyResources(this.lblReportName, "lblReportName"); this.lblReportName.Name = "lblReportName"; this.lblReportName.Padding = new PaddingInfo(2, 2, 0, 0, 100F); this.lblReportName.StylePriority.UseBorders = false; this.lblReportName.StylePriority.UseBorderWidth = false; this.lblReportName.StylePriority.UseFont = false; this.lblReportName.StylePriority.UseTextAlignment = false; // // rowBaseCountrySite // this.rowBaseCountrySite.Cells.AddRange(new XRTableCell[] { this.cellBaseCountry, this.cellBaseSite}); resources.ApplyResources(this.rowBaseCountrySite, "rowBaseCountrySite"); this.rowBaseCountrySite.Name = "rowBaseCountrySite"; this.rowBaseCountrySite.StylePriority.UseFont = false; this.rowBaseCountrySite.Weight = 0.95456790123456792; // // cellBaseCountry // this.cellBaseCountry.DataBindings.AddRange(new XRBinding[] { new XRBinding("Text", null, "sprepGetBaseParameters.CountryName")}); resources.ApplyResources(this.cellBaseCountry, "cellBaseCountry"); this.cellBaseCountry.Name = "cellBaseCountry"; this.cellBaseCountry.Weight = 1.1309915624438993; // // cellBaseSite // this.cellBaseSite.DataBindings.AddRange(new XRBinding[] { new XRBinding("Text", null, "sprepGetBaseParameters.SiteName")}); resources.ApplyResources(this.cellBaseSite, "cellBaseSite"); this.cellBaseSite.Name = "cellBaseSite"; this.cellBaseSite.StylePriority.UseBorders = false; this.cellBaseSite.StylePriority.UseFont = false; this.cellBaseSite.StylePriority.UseTextAlignment = false; this.cellBaseSite.Weight = 2.8576386811082521; // // sp_rep_BaseParametersTableAdapter // this.m_BaseAdapter.ClearBeforeFill = true; // // topMarginBand1 // resources.ApplyResources(this.topMarginBand1, "topMarginBand1"); this.topMarginBand1.Name = "topMarginBand1"; // // bottomMarginBand1 // resources.ApplyResources(this.bottomMarginBand1, "bottomMarginBand1"); this.bottomMarginBand1.Name = "bottomMarginBand1"; // // BaseReport // this.Bands.AddRange(new Band[] { this.Detail, this.PageHeader, this.PageFooter, this.ReportHeader, this.topMarginBand1, this.bottomMarginBand1}); this.DataAdapter = this.m_BaseAdapter; this.DataMember = "sprepGetBaseParameters"; this.DataSource = this.m_BaseDataSet; resources.ApplyResources(this, "$this"); this.FormattingRuleSheet.AddRange(new FormattingRule[] { this.formattingRule1}); this.Landscape = true; this.PageHeight = 827; this.PageWidth = 1169; this.Version = "10.1"; ((ISupportInitialize)(this.m_BaseDataSet)).EndInit(); ((ISupportInitialize)(this.tableBaseHeader)).EndInit(); ((ISupportInitialize)(this.tableBaseInnerHeader)).EndInit(); ((ISupportInitialize)(this)).EndInit(); } #endregion private FormattingRule formattingRule1; private XRTableRow rowBaseDate; private XRTableCell cellDateHeader; private XRTableCell cellDate; private XRTableRow rowBaseTime; private XRTableCell cellTimeHeader; private XRTableCell cellTime; private XRTableRow rowBaseLanguage; private XRTableCell cellLanguageHeader; protected XRTableCell cellLanguage; protected XRLabel lblReportName; protected DetailBand Detail; protected PageHeaderBand PageHeader; protected PageFooterBand PageFooter; protected BaseAdapter m_BaseAdapter; public ReportHeaderBand ReportHeader; protected XRPageInfo xrPageInfo1; protected BaseDataSet m_BaseDataSet; protected XRTableCell cellReportHeader; private XRTableRow rowReportName; private XRTableRow rowBaseCountrySite; private XRTable tableBaseInnerHeader; protected XRTableCell cellBaseSite; protected XRTableCell cellBaseCountry; protected XRTableCell cellBaseLeftHeader; protected XRTable tableBaseHeader; private TopMarginBand topMarginBand1; private BottomMarginBand bottomMarginBand1; } }
/* ==================================================================== 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.HSSF.Record { using System; using System.Text; using System.Collections; using NPOI.DDF; using NPOI.HSSF.UserModel; using NPOI.HSSF.Model; using NPOI.Util; using System.Collections.Generic; internal class SerializationListener : EscherSerializationListener { IList spEndingOffsets; IList shapes; public SerializationListener(ref IList spEndingOffsets, ref IList shapes) { this.spEndingOffsets = spEndingOffsets; this.shapes = shapes; } #region EscherSerializationListener Members void EscherSerializationListener.BeforeRecordSerialize(int Offset, short recordId, EscherRecord record) { } void EscherSerializationListener.AfterRecordSerialize(int Offset, short recordId, int size, EscherRecord record) { if (recordId == EscherClientDataRecord.RECORD_ID || recordId == EscherTextboxRecord.RECORD_ID) { spEndingOffsets.Add(Offset); shapes.Add(record); } } #endregion } /** * This class Is used to aggregate the MSODRAWING and OBJ record * combinations. This Is necessary due to the bizare way in which * these records are Serialized. What happens Is that you Get a * combination of MSODRAWING -> OBJ -> MSODRAWING -> OBJ records * but the escher records are Serialized _across_ the MSODRAWING * records. * * It Gets even worse when you start looking at TXO records. * * So what we do with this class Is aggregate lazily. That Is * we don't aggregate the MSODRAWING -> OBJ records Unless we * need to modify them. * * * @author Glen Stampoultzis (glens at apache.org) */ internal class EscherAggregate : AbstractEscherHolderRecord { public const short sid = 9876; private static POILogger log = POILogFactory.GetLogger(typeof(EscherAggregate)); public static short ST_MIN = (short)0; public static short ST_NOT_PRIMATIVE = ST_MIN; public static short ST_RECTANGLE = (short)1; public static short ST_ROUNDRECTANGLE = (short)2; public static short ST_ELLIPSE = (short)3; public static short ST_DIAMOND = (short)4; public static short ST_ISOCELESTRIANGLE = (short)5; public static short ST_RIGHTTRIANGLE = (short)6; public static short ST_PARALLELOGRAM = (short)7; public static short ST_TRAPEZOID = (short)8; public static short ST_HEXAGON = (short)9; public static short ST_OCTAGON = (short)10; public static short ST_PLUS = (short)11; public static short ST_STAR = (short)12; public static short ST_ARROW = (short)13; public static short ST_THICKARROW = (short)14; public static short ST_HOMEPLATE = (short)15; public static short ST_CUBE = (short)16; public static short ST_BALLOON = (short)17; public static short ST_SEAL = (short)18; public static short ST_ARC = (short)19; public static short ST_LINE = (short)20; public static short ST_PLAQUE = (short)21; public static short ST_CAN = (short)22; public static short ST_DONUT = (short)23; public static short ST_TEXTSIMPLE = (short)24; public static short ST_TEXTOCTAGON = (short)25; public static short ST_TEXTHEXAGON = (short)26; public static short ST_TEXTCURVE = (short)27; public static short ST_TEXTWAVE = (short)28; public static short ST_TEXTRING = (short)29; public static short ST_TEXTONCURVE = (short)30; public static short ST_TEXTONRING = (short)31; public static short ST_STRAIGHTCONNECTOR1 = (short)32; public static short ST_BENTCONNECTOR2 = (short)33; public static short ST_BENTCONNECTOR3 = (short)34; public static short ST_BENTCONNECTOR4 = (short)35; public static short ST_BENTCONNECTOR5 = (short)36; public static short ST_CURVEDCONNECTOR2 = (short)37; public static short ST_CURVEDCONNECTOR3 = (short)38; public static short ST_CURVEDCONNECTOR4 = (short)39; public static short ST_CURVEDCONNECTOR5 = (short)40; public static short ST_CALLOUT1 = (short)41; public static short ST_CALLOUT2 = (short)42; public static short ST_CALLOUT3 = (short)43; public static short ST_ACCENTCALLOUT1 = (short)44; public static short ST_ACCENTCALLOUT2 = (short)45; public static short ST_ACCENTCALLOUT3 = (short)46; public static short ST_BORDERCALLOUT1 = (short)47; public static short ST_BORDERCALLOUT2 = (short)48; public static short ST_BORDERCALLOUT3 = (short)49; public static short ST_ACCENTBORDERCALLOUT1 = (short)50; public static short ST_ACCENTBORDERCALLOUT2 = (short)51; public static short ST_ACCENTBORDERCALLOUT3 = (short)52; public static short ST_RIBBON = (short)53; public static short ST_RIBBON2 = (short)54; public static short ST_CHEVRON = (short)55; public static short ST_PENTAGON = (short)56; public static short ST_NOSMOKING = (short)57; public static short ST_SEAL8 = (short)58; public static short ST_SEAL16 = (short)59; public static short ST_SEAL32 = (short)60; public static short ST_WEDGERECTCALLOUT = (short)61; public static short ST_WEDGERRECTCALLOUT = (short)62; public static short ST_WEDGEELLIPSECALLOUT = (short)63; public static short ST_WAVE = (short)64; public static short ST_FOLDEDCORNER = (short)65; public static short ST_LEFTARROW = (short)66; public static short ST_DOWNARROW = (short)67; public static short ST_UPARROW = (short)68; public static short ST_LEFTRIGHTARROW = (short)69; public static short ST_UPDOWNARROW = (short)70; public static short ST_IRREGULARSEAL1 = (short)71; public static short ST_IRREGULARSEAL2 = (short)72; public static short ST_LIGHTNINGBOLT = (short)73; public static short ST_HEART = (short)74; public const short ST_PICTUREFRAME = (short)75; public static short ST_QUADARROW = (short)76; public static short ST_LEFTARROWCALLOUT = (short)77; public static short ST_RIGHTARROWCALLOUT = (short)78; public static short ST_UPARROWCALLOUT = (short)79; public static short ST_DOWNARROWCALLOUT = (short)80; public static short ST_LEFTRIGHTARROWCALLOUT = (short)81; public static short ST_UPDOWNARROWCALLOUT = (short)82; public static short ST_QUADARROWCALLOUT = (short)83; public static short ST_BEVEL = (short)84; public static short ST_LEFTBRACKET = (short)85; public static short ST_RIGHTBRACKET = (short)86; public static short ST_LEFTBRACE = (short)87; public static short ST_RIGHTBRACE = (short)88; public static short ST_LEFTUPARROW = (short)89; public static short ST_BENTUPARROW = (short)90; public static short ST_BENTARROW = (short)91; public static short ST_SEAL24 = (short)92; public static short ST_STRIPEDRIGHTARROW = (short)93; public static short ST_NOTCHEDRIGHTARROW = (short)94; public static short ST_BLOCKARC = (short)95; public static short ST_SMILEYFACE = (short)96; public static short ST_VERTICALSCROLL = (short)97; public static short ST_HORIZONTALSCROLL = (short)98; public static short ST_CIRCULARARROW = (short)99; public static short ST_NOTCHEDCIRCULARARROW = (short)100; public static short ST_UTURNARROW = (short)101; public static short ST_CURVEDRIGHTARROW = (short)102; public static short ST_CURVEDLEFTARROW = (short)103; public static short ST_CURVEDUPARROW = (short)104; public static short ST_CURVEDDOWNARROW = (short)105; public static short ST_CLOUDCALLOUT = (short)106; public static short ST_ELLIPSERIBBON = (short)107; public static short ST_ELLIPSERIBBON2 = (short)108; public static short ST_FLOWCHARTProcess = (short)109; public static short ST_FLOWCHARTDECISION = (short)110; public static short ST_FLOWCHARTINPUTOUTPUT = (short)111; public static short ST_FLOWCHARTPREDEFINEDProcess = (short)112; public static short ST_FLOWCHARTINTERNALSTORAGE = (short)113; public static short ST_FLOWCHARTDOCUMENT = (short)114; public static short ST_FLOWCHARTMULTIDOCUMENT = (short)115; public static short ST_FLOWCHARTTERMINATOR = (short)116; public static short ST_FLOWCHARTPREPARATION = (short)117; public static short ST_FLOWCHARTMANUALINPUT = (short)118; public static short ST_FLOWCHARTMANUALOPERATION = (short)119; public static short ST_FLOWCHARTCONNECTOR = (short)120; public static short ST_FLOWCHARTPUNCHEDCARD = (short)121; public static short ST_FLOWCHARTPUNCHEDTAPE = (short)122; public static short ST_FLOWCHARTSUMMINGJUNCTION = (short)123; public static short ST_FLOWCHARTOR = (short)124; public static short ST_FLOWCHARTCOLLATE = (short)125; public static short ST_FLOWCHARTSORT = (short)126; public static short ST_FLOWCHARTEXTRACT = (short)127; public static short ST_FLOWCHARTMERGE = (short)128; public static short ST_FLOWCHARTOFFLINESTORAGE = (short)129; public static short ST_FLOWCHARTONLINESTORAGE = (short)130; public static short ST_FLOWCHARTMAGNETICTAPE = (short)131; public static short ST_FLOWCHARTMAGNETICDISK = (short)132; public static short ST_FLOWCHARTMAGNETICDRUM = (short)133; public static short ST_FLOWCHARTDISPLAY = (short)134; public static short ST_FLOWCHARTDELAY = (short)135; public static short ST_TEXTPLAINTEXT = (short)136; public static short ST_TEXTSTOP = (short)137; public static short ST_TEXTTRIANGLE = (short)138; public static short ST_TEXTTRIANGLEINVERTED = (short)139; public static short ST_TEXTCHEVRON = (short)140; public static short ST_TEXTCHEVRONINVERTED = (short)141; public static short ST_TEXTRINGINSIDE = (short)142; public static short ST_TEXTRINGOUTSIDE = (short)143; public static short ST_TEXTARCHUPCURVE = (short)144; public static short ST_TEXTARCHDOWNCURVE = (short)145; public static short ST_TEXTCIRCLECURVE = (short)146; public static short ST_TEXTBUTTONCURVE = (short)147; public static short ST_TEXTARCHUPPOUR = (short)148; public static short ST_TEXTARCHDOWNPOUR = (short)149; public static short ST_TEXTCIRCLEPOUR = (short)150; public static short ST_TEXTBUTTONPOUR = (short)151; public static short ST_TEXTCURVEUP = (short)152; public static short ST_TEXTCURVEDOWN = (short)153; public static short ST_TEXTCASCADEUP = (short)154; public static short ST_TEXTCASCADEDOWN = (short)155; public static short ST_TEXTWAVE1 = (short)156; public static short ST_TEXTWAVE2 = (short)157; public static short ST_TEXTWAVE3 = (short)158; public static short ST_TEXTWAVE4 = (short)159; public static short ST_TEXTINFLATE = (short)160; public static short ST_TEXTDEFLATE = (short)161; public static short ST_TEXTINFLATEBOTTOM = (short)162; public static short ST_TEXTDEFLATEBOTTOM = (short)163; public static short ST_TEXTINFLATETOP = (short)164; public static short ST_TEXTDEFLATETOP = (short)165; public static short ST_TEXTDEFLATEINFLATE = (short)166; public static short ST_TEXTDEFLATEINFLATEDEFLATE = (short)167; public static short ST_TEXTFADERIGHT = (short)168; public static short ST_TEXTFADELEFT = (short)169; public static short ST_TEXTFADEUP = (short)170; public static short ST_TEXTFADEDOWN = (short)171; public static short ST_TEXTSLANTUP = (short)172; public static short ST_TEXTSLANTDOWN = (short)173; public static short ST_TEXTCANUP = (short)174; public static short ST_TEXTCANDOWN = (short)175; public static short ST_FLOWCHARTALTERNATEProcess = (short)176; public static short ST_FLOWCHARTOFFPAGECONNECTOR = (short)177; public static short ST_CALLOUT90 = (short)178; public static short ST_ACCENTCALLOUT90 = (short)179; public static short ST_BORDERCALLOUT90 = (short)180; public static short ST_ACCENTBORDERCALLOUT90 = (short)181; public static short ST_LEFTRIGHTUPARROW = (short)182; public static short ST_SUN = (short)183; public static short ST_MOON = (short)184; public static short ST_BRACKETPAIR = (short)185; public static short ST_BRACEPAIR = (short)186; public static short ST_SEAL4 = (short)187; public static short ST_DOUBLEWAVE = (short)188; public static short ST_ACTIONBUTTONBLANK = (short)189; public static short ST_ACTIONBUTTONHOME = (short)190; public static short ST_ACTIONBUTTONHELP = (short)191; public static short ST_ACTIONBUTTONINFORMATION = (short)192; public static short ST_ACTIONBUTTONFORWARDNEXT = (short)193; public static short ST_ACTIONBUTTONBACKPREVIOUS = (short)194; public static short ST_ACTIONBUTTONEND = (short)195; public static short ST_ACTIONBUTTONBEGINNING = (short)196; public static short ST_ACTIONBUTTONRETURN = (short)197; public static short ST_ACTIONBUTTONDOCUMENT = (short)198; public static short ST_ACTIONBUTTONSOUND = (short)199; public static short ST_ACTIONBUTTONMOVIE = (short)200; public static short ST_HOSTCONTROL = (short)201; public const short ST_TEXTBOX = (short)202; public const short ST_NIL = (short)0x0FFF; protected HSSFPatriarch patriarch; /** Maps shape container objects to their OBJ records */ private Hashtable shapeToObj = new Hashtable(); private DrawingManager2 drawingManager; private short drawingGroupId; /** * list of "tail" records that need to be Serialized after all drawing Group records */ private IList tailRec = new ArrayList(); public EscherAggregate(DrawingManager2 drawingManager) { this.drawingManager = drawingManager; } /** * @return Returns the current sid. */ public override short Sid { get { return sid; } } /** * Unused since this Is an aggregate record. Use CreateAggregate(). * * @see #CreateAggregate */ public System.Collections.IList Children(byte[] data, short size, int offset) { throw new InvalidOperationException("Should not reach here"); } /** * Calculates the string representation of this record. This Is * simply a dump of all the records. */ public override String ToString() { String nl = Environment.NewLine; StringBuilder result = new StringBuilder(); result.Append('[').Append(RecordName).Append(']' + nl); for (IEnumerator iterator = EscherRecords.GetEnumerator(); iterator.MoveNext(); ) { EscherRecord escherRecord = (EscherRecord)iterator.Current; result.Append(escherRecord.ToString()); } result.Append("[/").Append(RecordName).Append(']' + nl); return result.ToString(); } internal class CustomEscherRecordFactory : DefaultEscherRecordFactory { IList shapeRecords; public CustomEscherRecordFactory(ref IList shapeRecords) { this.shapeRecords = shapeRecords; } public override EscherRecord CreateRecord(byte[] data, int offset) { EscherRecord r = base.CreateRecord(data, offset); if (r.RecordId == EscherClientDataRecord.RECORD_ID || r.RecordId == EscherTextboxRecord.RECORD_ID) { shapeRecords.Add(r); } return r; } } /** * Collapses the drawing records into an aggregate. */ public static EscherAggregate CreateAggregate(IList records, int locFirstDrawingRecord, DrawingManager2 drawingManager) { // Keep track of any shape records Created so we can match them back to the object id's. // Textbox objects are also treated as shape objects. IList shapeRecords = new ArrayList(); EscherRecordFactory recordFactory = new CustomEscherRecordFactory(ref shapeRecords); // Calculate the size of the buffer EscherAggregate agg = new EscherAggregate(drawingManager); int loc = locFirstDrawingRecord; int dataSize = 0; while (loc + 1 < records.Count && GetSid(records, loc) == DrawingRecord.sid && IsObjectRecord(records, loc + 1)) { dataSize += ((DrawingRecord)records[loc]).Data.Length; loc += 2; } // Create one big buffer byte[] buffer = new byte[dataSize]; int offset = 0; loc = locFirstDrawingRecord; while (loc + 1 < records.Count && GetSid(records, loc) == DrawingRecord.sid && IsObjectRecord(records, loc + 1)) { DrawingRecord drawingRecord = (DrawingRecord)records[loc]; Array.Copy(drawingRecord.Data, 0, buffer, offset, drawingRecord.Data.Length); offset += drawingRecord.Data.Length; loc += 2; } // Decode the shapes // agg.escherRecords = new ArrayList(); int pos = 0; while (pos < dataSize) { EscherRecord r = recordFactory.CreateRecord(buffer, pos); int bytesRead = r.FillFields(buffer, pos, recordFactory); agg.AddEscherRecord(r); pos += bytesRead; } // Associate the object records with the shapes loc = locFirstDrawingRecord; int shapeIndex = 0; agg.shapeToObj = new Hashtable(); while (loc + 1 < records.Count && GetSid(records, loc) == DrawingRecord.sid && IsObjectRecord(records, loc + 1)) { Record objRecord = (Record)records[loc + 1]; agg.shapeToObj[shapeRecords[shapeIndex++]]= objRecord; loc += 2; } return agg; } IList spEndingOffsets; IList shapes; /** * Serializes this aggregate to a byte array. Since this Is an aggregate * record it will effectively Serialize the aggregated records. * * @param offset The offset into the start of the array. * @param data The byte array to Serialize to. * @return The number of bytes Serialized. */ public override int Serialize(int offset, byte [] data) { ConvertUserModelToRecords(); // Determine buffer size IList records = EscherRecords; int size = GetEscherRecordSize(records); byte[] buffer = new byte[size]; // Serialize escher records into one big data structure and keep note of ending offsets. spEndingOffsets = new ArrayList(); shapes = new ArrayList(); int pos = 0; for (IEnumerator iterator = records.GetEnumerator(); iterator.MoveNext(); ) { EscherRecord e = (EscherRecord)iterator.Current; pos += e.Serialize(pos, buffer, new SerializationListener(ref spEndingOffsets,ref shapes)); } // todo: fix this shapes.Insert(0, null); spEndingOffsets.Insert(0, null); // Split escher records into Separate MSODRAWING and OBJ, TXO records. (We don't break on // the first one because it's the patriach). pos = offset; for (int i = 1; i < shapes.Count; i++) { int endOffset = (int)spEndingOffsets[i] - 1; int startOffset; if (i == 1) startOffset = 0; else startOffset = (int)spEndingOffsets[i - 1]; // Create and Write a new MSODRAWING record DrawingRecord drawing = new DrawingRecord(); byte[] drawingData = new byte[endOffset - startOffset + 1]; Array.Copy(buffer, startOffset, drawingData, 0, drawingData.Length); drawing.Data=drawingData; int temp = drawing.Serialize(pos, data); pos += temp; // Write the matching OBJ record Record obj = (Record)shapeToObj[shapes[i]]; temp = obj.Serialize(pos, data); pos += temp; } // Write records that need to be Serialized after all drawing Group records for (int i = 0; i < tailRec.Count; i++) { Record rec = (Record)tailRec[i]; pos += rec.Serialize(pos, data); } int bytesWritten = pos - offset; if (bytesWritten != RecordSize) throw new RecordFormatException(bytesWritten + " bytes written but RecordSize reports " + RecordSize); return bytesWritten; } /** * How many bytes do the raw escher records contain. * @param records List of escher records * @return the number of bytes */ private int GetEscherRecordSize(IList records) { int size = 0; for (IEnumerator iterator = records.GetEnumerator(); iterator.MoveNext(); ) size += ((EscherRecord)iterator.Current).RecordSize; return size; } /** * The number of bytes required to Serialize this record. */ public override int RecordSize { get { ConvertUserModelToRecords(); IList records = EscherRecords; int rawEscherSize = GetEscherRecordSize(records); int drawingRecordSize = rawEscherSize + (shapeToObj.Count) * 4; int objRecordSize = 0; for (IEnumerator iterator = shapeToObj.Values.GetEnumerator(); iterator.MoveNext(); ) { Record r = (Record)iterator.Current; objRecordSize += r.RecordSize; } int tailRecordSize = 0; for (IEnumerator iterator = tailRec.GetEnumerator(); iterator.MoveNext(); ) { Record r = (Record)iterator.Current; tailRecordSize += r.RecordSize; } return drawingRecordSize + objRecordSize + tailRecordSize; } } /** * Associates an escher record to an OBJ record or a TXO record. */ public Object AssoicateShapeToObjRecord(EscherRecord r, Record objRecord) { return shapeToObj[r]= objRecord; } public HSSFPatriarch Patriarch { get { return patriarch; } set { this.patriarch = value; } } /** * Converts the Records into UserModel * objects on the bound HSSFPatriarch */ public void ConvertRecordsToUserModel() { if (patriarch == null) { throw new InvalidOperationException("Must call SetPatriarch() first"); } // The top level container ought to have // the DgRecord and the container of one container // per shape Group (patriach overall first) EscherContainerRecord topContainer = (EscherContainerRecord)GetEscherContainer(); if (topContainer == null) { return; } topContainer = (EscherContainerRecord) topContainer.ChildContainers[0]; IList<EscherContainerRecord> tcc = topContainer.ChildContainers; if (tcc.Count == 0) { throw new InvalidOperationException("No child escher containers at the point that should hold the patriach data, and one container per top level shape!"); } // First up, Get the patriach position // This Is in the first EscherSpgrRecord, in // the first container, with a EscherSRecord too EscherContainerRecord patriachContainer = (EscherContainerRecord)tcc[0]; EscherSpgrRecord spgr = null; for (IEnumerator it = patriachContainer.ChildRecords.GetEnumerator(); it.MoveNext(); ) { EscherRecord r = (EscherRecord)it.Current; if (r is EscherSpgrRecord) { spgr = (EscherSpgrRecord)r; break; } } if (spgr != null) { patriarch.SetCoordinates( spgr.RectX1, spgr.RectY1, spgr.RectX2, spgr.RectY2 ); } // Now Process the containers for each Group // and objects for (int i = 1; i < tcc.Count; i++) { EscherContainerRecord shapeContainer = (EscherContainerRecord)tcc[i]; //Console.Error.WriteLine("\n\n*****\n\n"); //Console.Error.WriteLine(shapeContainer); // Could be a Group, or a base object if (shapeContainer.RecordId == EscherContainerRecord.SPGR_CONTAINER) { if(shapeContainer.ChildRecords.Count>0) { // Group HSSFShapeGroup group = new HSSFShapeGroup(null, new HSSFClientAnchor()); patriarch.Children.Add(group); EscherContainerRecord groupContainer = (EscherContainerRecord)shapeContainer.GetChild(0); ConvertRecordsToUserModel(groupContainer, group); } } else if (shapeContainer.RecordId == EscherContainerRecord.SP_CONTAINER) { EscherSpRecord spRecord = shapeContainer.GetChildById(EscherSpRecord.RECORD_ID); int type = spRecord.Options >> 4; switch (type) { case ST_TEXTBOX: // TextBox HSSFTextbox box = new HSSFTextbox(null, new HSSFClientAnchor()); patriarch.Children.Add(box); ConvertRecordsToUserModel(shapeContainer, box); break; case ST_PICTUREFRAME: // Duplicated from // org.apache.poi.hslf.model.Picture.getPictureIndex() EscherOptRecord opt = (EscherOptRecord)GetEscherChild(shapeContainer, EscherOptRecord.RECORD_ID); EscherSimpleProperty prop = (EscherSimpleProperty)opt.Lookup(EscherProperties.BLIP__BLIPTODISPLAY); if (prop != null) { int pictureIndex = prop.PropertyValue; EscherClientAnchorRecord anchorRecord = (EscherClientAnchorRecord)GetEscherChild(shapeContainer, EscherClientAnchorRecord.RECORD_ID); HSSFClientAnchor anchor = new HSSFClientAnchor(); anchor.Col1 = anchorRecord.Col1; anchor.Col2 = anchorRecord.Col2; anchor.Dx1 = anchorRecord.Dx1; anchor.Dx2 = anchorRecord.Dx2; anchor.Dy1 = anchorRecord.Dy1; anchor.Dy2 = anchorRecord.Dy2; anchor.Row1 = anchorRecord.Row1; anchor.Row2 = anchorRecord.Row2; HSSFPicture picture = new HSSFPicture(null, anchor); picture.PictureIndex = pictureIndex; patriarch.AddShape(picture); } break; } } else { // Base level ConvertRecordsToUserModel(shapeContainer, patriarch); } } // Now, clear any trace of what records make up // the patriarch // Otherwise, everything will go horribly wrong // when we try to Write out again.... // clearEscherRecords(); drawingManager.GetDgg().FileIdClusters=new EscherDggRecord.FileIdCluster[0]; // TODO: Support Converting our records // back into shapes log.Log(POILogger.WARN, "Not Processing objects into Patriarch!"); } private EscherRecord GetEscherChild(EscherContainerRecord owner, int recordId) { for (IEnumerator iterator = owner.ChildRecords.GetEnumerator(); iterator.MoveNext(); ) { EscherRecord escherRecord = (EscherRecord)iterator.Current; if (escherRecord.RecordId == recordId) return escherRecord; } return null; } private void ConvertRecordsToUserModel(EscherContainerRecord shapeContainer, Object model) { for (IEnumerator it = shapeContainer.ChildRecords.GetEnumerator(); it.MoveNext(); ) { EscherRecord r = (EscherRecord)it.Current; if (r is EscherSpgrRecord) { // This may be overriden by a later EscherClientAnchorRecord EscherSpgrRecord spgr = (EscherSpgrRecord)r; if (model is HSSFShapeGroup) { HSSFShapeGroup g = (HSSFShapeGroup)model; g.SetCoordinates( spgr.RectX1, spgr.RectY1, spgr.RectX2, spgr.RectY2 ); } else { throw new InvalidOperationException("Got top level anchor but not Processing a Group"); } } else if (r is EscherClientAnchorRecord) { EscherClientAnchorRecord car = (EscherClientAnchorRecord)r; if (model is HSSFShape) { HSSFShape g = (HSSFShape)model; g.Anchor.Dx1=car.Dx1; g.Anchor.Dx2=car.Dx2; g.Anchor.Dy1=car.Dy1; g.Anchor.Dy2=car.Dy2; } else { throw new InvalidOperationException("Got top level anchor but not Processing a Group or shape"); } } else if (r is EscherTextboxRecord) { EscherTextboxRecord tbr = (EscherTextboxRecord)r; // Also need to Find the TextObjectRecord too // TODO } else if (r is EscherSpRecord) { // Use flags if needed } else if (r is EscherOptRecord) { // Use properties if needed } else { //Console.Error.WriteLine(r); } } } public void Clear() { ClearEscherRecords(); shapeToObj.Clear(); // lastShapeId = 1024; } protected override String RecordName { get { return "ESCHERAGGREGATE"; } } // =============== Private methods ======================== private static bool IsObjectRecord(IList records, int loc) { return GetSid(records, loc) == ObjRecord.sid || GetSid(records, loc) == TextObjectRecord.sid; } private void ConvertUserModelToRecords() { if (patriarch != null) { shapeToObj.Clear(); tailRec.Clear(); ClearEscherRecords(); if (patriarch.Children.Count != 0) { ConvertPatriarch(patriarch); EscherContainerRecord dgContainer = (EscherContainerRecord)GetEscherRecord(0); EscherContainerRecord spgrContainer = null; for (int i = 0; i < dgContainer.ChildRecords.Count; i++) if (dgContainer.GetChild(i).RecordId == EscherContainerRecord.SPGR_CONTAINER) spgrContainer = (EscherContainerRecord)dgContainer.GetChild(i); ConvertShapes(patriarch, spgrContainer, shapeToObj); patriarch = null; } } } private void ConvertShapes(HSSFShapeContainer parent, EscherContainerRecord escherParent, Hashtable shapeToObj) { if (escherParent == null) throw new ArgumentException("Parent record required"); IList shapes = parent.Children; for (IEnumerator iterator = shapes.GetEnumerator(); iterator.MoveNext(); ) { HSSFShape shape = (HSSFShape)iterator.Current; if (shape is HSSFShapeGroup) { ConvertGroup((HSSFShapeGroup)shape, escherParent, shapeToObj); } else { AbstractShape shapeModel = AbstractShape.CreateShape( shape, drawingManager.AllocateShapeId(drawingGroupId)); shapeToObj[FindClientData(shapeModel.SpContainer)]=shapeModel.ObjRecord; if (shapeModel is TextboxShape) { EscherRecord escherTextbox = ((TextboxShape)shapeModel).EscherTextbox; shapeToObj[escherTextbox]=((TextboxShape)shapeModel).TextObjectRecord; // escherParent.AddChildRecord(escherTextbox); if (shapeModel is CommentShape) { CommentShape comment = (CommentShape)shapeModel; tailRec.Add(comment.NoteRecord); } } escherParent.AddChildRecord(shapeModel.SpContainer); } } // drawingManager.newCluster( (short)1 ); // drawingManager.newCluster( (short)2 ); } private void ConvertGroup(HSSFShapeGroup shape, EscherContainerRecord escherParent, Hashtable shapeToObj) { EscherContainerRecord spgrContainer = new EscherContainerRecord(); EscherContainerRecord spContainer = new EscherContainerRecord(); EscherSpgrRecord spgr = new EscherSpgrRecord(); EscherSpRecord sp = new EscherSpRecord(); EscherOptRecord opt = new EscherOptRecord(); EscherRecord anchor; EscherClientDataRecord clientData = new EscherClientDataRecord(); spgrContainer.RecordId = EscherContainerRecord.SPGR_CONTAINER; spgrContainer.Options = (short)0x000F; spContainer.RecordId = EscherContainerRecord.SP_CONTAINER; spContainer.Options = (short)0x000F; spgr.RecordId = EscherSpgrRecord.RECORD_ID; spgr.Options = (short)0x0001; spgr.RectX1 = shape.X1; spgr.RectY1 = shape.Y1; spgr.RectX2 = shape.X2; spgr.RectY2 = shape.Y2; sp.RecordId = EscherSpRecord.RECORD_ID; sp.Options = (short)0x0002; int shapeId = drawingManager.AllocateShapeId(drawingGroupId); sp.ShapeId = shapeId; if (shape.Anchor is HSSFClientAnchor) sp.Flags = EscherSpRecord.FLAG_GROUP | EscherSpRecord.FLAG_HAVEANCHOR; else sp.Flags = EscherSpRecord.FLAG_GROUP | EscherSpRecord.FLAG_HAVEANCHOR | EscherSpRecord.FLAG_CHILD; opt.RecordId = EscherOptRecord.RECORD_ID; opt.Options = (short)0x0023; opt.AddEscherProperty(new EscherBoolProperty(EscherProperties.PROTECTION__LOCKAGAINSTGROUPING, 0x00040004)); opt.AddEscherProperty(new EscherBoolProperty(EscherProperties.GROUPSHAPE__PRINT, 0x00080000)); anchor = ConvertAnchor.CreateAnchor(shape.Anchor); // clientAnchor.Col1( ( (HSSFClientAnchor) shape.Anchor ).Col1 ); // clientAnchor.Row1( (short) ( (HSSFClientAnchor) shape.Anchor ).Row1 ); // clientAnchor.Dx1( (short) shape.Anchor.Dx1 ); // clientAnchor.Dy1( (short) shape.Anchor.Dy1 ); // clientAnchor.Col2( ( (HSSFClientAnchor) shape.Anchor ).Col2 ); // clientAnchor.Row2( (short) ( (HSSFClientAnchor) shape.Anchor ).Row2 ); // clientAnchor.Dx2( (short) shape.Anchor.Dx2 ); // clientAnchor.Dy2( (short) shape.Anchor.Dy2 ); clientData.RecordId = (EscherClientDataRecord.RECORD_ID); clientData.Options = ((short)0x0000); spgrContainer.AddChildRecord(spContainer); spContainer.AddChildRecord(spgr); spContainer.AddChildRecord(sp); spContainer.AddChildRecord(opt); spContainer.AddChildRecord(anchor); spContainer.AddChildRecord(clientData); ObjRecord obj = new ObjRecord(); CommonObjectDataSubRecord cmo = new CommonObjectDataSubRecord(); cmo.ObjectType = CommonObjectType.GROUP; cmo.ObjectId = shapeId; cmo.IsLocked = true; cmo.IsPrintable = true; cmo.IsAutoFill = true; cmo.IsAutoline = true; GroupMarkerSubRecord gmo = new GroupMarkerSubRecord(); EndSubRecord end = new EndSubRecord(); obj.AddSubRecord(cmo); obj.AddSubRecord(gmo); obj.AddSubRecord(end); shapeToObj[clientData] = obj; escherParent.AddChildRecord(spgrContainer); ConvertShapes(shape, spgrContainer, shapeToObj); } private EscherRecord FindClientData(EscherContainerRecord spContainer) { for (IEnumerator iterator = spContainer.ChildRecords.GetEnumerator(); iterator.MoveNext(); ) { EscherRecord r = (EscherRecord)iterator.Current; if (r.RecordId == EscherClientDataRecord.RECORD_ID) return r; } throw new ArgumentException("Can not Find client data record"); } private void ConvertPatriarch(HSSFPatriarch patriarch) { EscherContainerRecord dgContainer = new EscherContainerRecord(); EscherDgRecord dg; EscherContainerRecord spgrContainer = new EscherContainerRecord(); EscherContainerRecord spContainer1 = new EscherContainerRecord(); EscherSpgrRecord spgr = new EscherSpgrRecord(); EscherSpRecord sp1 = new EscherSpRecord(); dgContainer.RecordId=EscherContainerRecord.DG_CONTAINER; dgContainer.Options=(short)0x000F; dg = drawingManager.CreateDgRecord(); drawingGroupId = dg.DrawingGroupId; // dg.Options( (short) ( drawingId << 4 ) ); // dg.NumShapes( GetNumberOfShapes( patriarch ) ); // dg.LastMSOSPID( 0 ); // populated after all shape id's are assigned. spgrContainer.RecordId=EscherContainerRecord.SPGR_CONTAINER; spgrContainer.Options=(short)0x000F; spContainer1.RecordId=EscherContainerRecord.SP_CONTAINER; spContainer1.Options=(short)0x000F; spgr.RecordId=EscherSpgrRecord.RECORD_ID; spgr.Options=(short)0x0001; // version spgr.RectX1=patriarch.X1; spgr.RectY1=patriarch.Y1; spgr.RectX2=patriarch.X2; spgr.RectY2=patriarch.Y2; sp1.RecordId=EscherSpRecord.RECORD_ID; sp1.Options=(short)0x0002; sp1.ShapeId=drawingManager.AllocateShapeId(dg.DrawingGroupId); sp1.Flags=EscherSpRecord.FLAG_GROUP | EscherSpRecord.FLAG_PATRIARCH; dgContainer.AddChildRecord(dg); dgContainer.AddChildRecord(spgrContainer); spgrContainer.AddChildRecord(spContainer1); spContainer1.AddChildRecord(spgr); spContainer1.AddChildRecord(sp1); AddEscherRecord(dgContainer); } private static short GetSid(IList records, int loc) { return ((Record)records[loc]).Sid; } } }
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Mvc.Localization; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.Extensions.DependencyInjection; using OrchardCore.DisplayManagement.Layout; using OrchardCore.DisplayManagement.Shapes; using OrchardCore.DisplayManagement.Title; namespace OrchardCore.DisplayManagement.Razor { public abstract class RazorPage<TModel> : Microsoft.AspNetCore.Mvc.Razor.RazorPage<TModel> { private dynamic _displayHelper; private IShapeFactory _shapeFactory; private void EnsureDisplayHelper() { if (_displayHelper == null) { IDisplayHelperFactory _factory = Context.RequestServices.GetService<IDisplayHelperFactory>(); _displayHelper = _factory.CreateHelper(ViewContext); } } private void EnsureShapeFactory() { if (_shapeFactory == null) { _shapeFactory = Context.RequestServices.GetService<IShapeFactory>(); } } /// <summary> /// Gets a dynamic shape factory to create new shapes. /// </summary> /// <example> /// Usage: /// <code> /// New.MyShape() /// New.MyShape(A: 1, B: "Some text") /// New.MyShape().A(1).B("Some text") /// </code> /// </example> public dynamic New { get { return Factory; } } /// <summary> /// Gets an <see cref="IShapeFactory"/> to create new shapes. /// </summary> public IShapeFactory Factory { get { EnsureShapeFactory(); return _shapeFactory; } } /// <summary> /// Renders a shape. /// </summary> /// <param name="shape">The shape.</param> public Task<IHtmlContent> DisplayAsync(dynamic shape) { EnsureDisplayHelper(); return (Task<IHtmlContent>)_displayHelper(shape); } private dynamic _themeLayout; public dynamic ThemeLayout { get { if (_themeLayout == null) { var layoutAccessor = Context.RequestServices.GetService<ILayoutAccessor>(); if (layoutAccessor == null) { throw new InvalidOperationException("Could not find a valid layout accessor"); } _themeLayout = layoutAccessor.GetLayout(); } return _themeLayout; } set { _themeLayout = value; } } private IPageTitleBuilder _pageTitleBuilder; public IPageTitleBuilder Title { get { if (_pageTitleBuilder == null) { _pageTitleBuilder = Context.RequestServices.GetRequiredService<IPageTitleBuilder>(); } return _pageTitleBuilder; } } private IViewLocalizer _t; /// <summary> /// The <see cref="IViewLocalizer"/> instance for the current view. /// </summary> public IViewLocalizer T { get { if (_t == null) { _t = Context.RequestServices.GetRequiredService<IViewLocalizer>(); ((IViewContextAware)_t).Contextualize(this.ViewContext); } return _t; } } /// <summary> /// Adds a segment to the title and returns all segments. /// </summary> /// <param name="segment">The segment to add to the title.</param> /// <param name="position">Optional. The position of the segment in the title.</param> /// <param name="separator">The html string that should separate all segments.</param> /// <returns>And <see cref="IHtmlContent"/> instance representing the full title.</returns> public IHtmlContent RenderTitleSegments(IHtmlContent segment, string position = "0", IHtmlContent separator = null) { Title.AddSegment(segment, position); return Title.GenerateTitle(separator); } /// <summary> /// Adds a segment to the title and returns all segments. /// </summary> /// <param name="segment">The segment to add to the title.</param> /// <param name="position">Optional. The position of the segment in the title.</param> /// <param name="separator">The html string that should separate all segments.</param> /// <returns>And <see cref="IHtmlContent"/> instance representing the full title.</returns> public IHtmlContent RenderTitleSegments(string segment, string position = "0", IHtmlContent separator = null) { Title.AddSegment(new HtmlString(HtmlEncoder.Encode(segment)), position); return Title.GenerateTitle(separator); } /// <summary> /// Renders the content zone of the layout. /// </summary> public IHtmlContent RenderLayoutBody() { var result = base.RenderBody(); return result; } /// <summary> /// Creates a <see cref="TagBuilder"/> to render a shape. /// </summary> /// <param name="shape">The shape.</param> /// <returns>A new <see cref="TagBuilder"/>.</returns> public TagBuilder Tag(dynamic shape) { return Shape.GetTagBuilder(shape); } public TagBuilder Tag(dynamic shape, string tag) { return Shape.GetTagBuilder(shape, tag); } public Task<IHtmlContent> RenderBodyAsync() { return DisplayAsync(ThemeLayout.Content); } /// <summary> /// Renders a zone from the layout. /// </summary> /// <param name="name">The name of the zone to render.</param> /// <param name="required">Whether the zone is required or not.</param> public new Task<IHtmlContent> RenderSectionAsync(string name, bool required) { if (name == null) { throw new ArgumentNullException(nameof(name)); } var zone = ThemeLayout[name]; if (required && zone != null && zone.Items.Count == 0) { throw new InvalidOperationException("Zone not found: " + name); } return DisplayAsync(zone); } public object OrDefault(object text, object other) { if (text == null || Convert.ToString(text) == "") { return other; } return text; } /// <summary> /// Returns the full path of the current request. /// </summary> public string FullRequestPath => Context.Request.PathBase + Context.Request.Path + Context.Request.QueryString; } public abstract class RazorPage : RazorPage<dynamic> { } }
/*** * FdpDataProvider needed FirebirdClient http://sourceforge.net/project/showfiles.php?group_id=9028&package_id=62107 tested with FirebirdClient 2.1.0 Beta 3 Known troubles: 1) Some tests fails due to Fb SQL-syntax specific 2) ResultSet mapping doesn't work - not supported by client 3) UnitTests.CS.DataAccess.OutRefTest tests: Test2 && TestNullable2 doesnt work: parameters directions should be provided correctly to functions run, that's why output parameterd would be mapped to Entity e, so asserts should be same a in Test1. "Features" 1) Type conversation due to http://www.firebirdsql.org/manual/migration-mssql-data-types.html BUT! for Binary types BLOB is used! not CHAR! 2) InOut parameters faking: InOut parameters are not suppotred by Fb, but they could be emulated: each InOut parameter should be defined in RETURNS() section, and allso has a mirror in parameter section with name [prefix][inOutParameterName], see OutRefTest SP. Faking settings: FdpDataProvider.InOutInputParameterPrefix = "in_"; FdpDataProvider.IsInOutParameterEmulation = true; 3) Returned values faking. Each parameter with "magic name" woul be treated as ReturnValue. see Scalar_ReturnParameter SP. Faking settings: FdpDataProvider.ReturnParameterName = "RETURN_VALUE"; FdpDataProvider.IsReturnValueEmulation = true; */ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Data; using System.Data.Common; using System.Linq; using BLToolkit.Data.Sql.SqlProvider; using BLToolkit.Mapping; using BLToolkit.Reflection; using FirebirdSql.Data.FirebirdClient; namespace BLToolkit.Data.DataProvider { public class FdpDataProvider : DataProviderBase { public FdpDataProvider() { MappingSchema = new FbMappingSchema(); } #region InOut & ReturnValue emulation public static string InOutInputParameterPrefix = "in_"; public static string ReturnParameterName = "RETURN_VALUE"; public static bool IsReturnValueEmulation = true; public static bool IsInOutParameterEmulation = true; public static bool QuoteIdentifiers { get { return FirebirdSqlProvider.QuoteIdentifiers; } set { FirebirdSqlProvider.QuoteIdentifiers = value; } } #endregion #region Overloads public override Type ConnectionType { get { return typeof (FbConnection); } } public override string Name { get { return DataProvider.ProviderName.Firebird; } } public override int MaxBatchSize { get { return 0; } } public override IDbConnection CreateConnectionObject() { return new FbConnection(); } public override DbDataAdapter CreateDataAdapterObject() { return new FbDataAdapter(); } public override bool DeriveParameters(IDbCommand command) { if (command is FbCommand) { FbCommandBuilder.DeriveParameters((FbCommand) command); if (IsReturnValueEmulation) foreach (IDbDataParameter par in command.Parameters) if (IsReturnValue(par)) par.Direction = ParameterDirection.ReturnValue; return true; } return false; } public override object Convert(object value, ConvertType convertType) { switch (convertType) { case ConvertType.ExceptionToErrorNumber: if (value is FbException) { var ex = (FbException) value; if (ex.Errors.Count > 0) foreach (FbError error in ex.Errors) return error.Number; } break; } return SqlProvider.Convert(value, convertType); } public override ISqlProvider CreateSqlProvider() { return new FirebirdSqlProvider(); } public override bool IsValueParameter(IDbDataParameter parameter) { return parameter.Direction != ParameterDirection.ReturnValue && parameter.Direction != ParameterDirection.Output; } private string GetInputParameterName(string ioParameterName) { return (string) Convert( InOutInputParameterPrefix + (string) Convert(ioParameterName, ConvertType.SprocParameterToName), ConvertType.NameToSprocParameter); } private static IDbDataParameter GetParameter(string parameterName, IEnumerable<IDbDataParameter> commandParameters) { return commandParameters.FirstOrDefault(par => string.Compare(parameterName, par.ParameterName, true) == 0); } private bool IsReturnValue(IDbDataParameter parameter) { if (string.Compare(parameter.ParameterName, (string) Convert(ReturnParameterName, ConvertType.NameToSprocParameter), true) == 0 ) return true; return false; } public override void PrepareCommand(ref CommandType commandType, ref string commandText, ref IDbDataParameter[] commandParameters) { if (commandParameters != null) foreach (var par in commandParameters) { if (par.Value is bool) { var value = (bool) par.Value ? "1" : "0"; par.DbType = DbType.AnsiString; par.Value = value; par.Size = value.Length; } else if (par.Value is Guid) { var value = par.Value.ToString(); par.DbType = DbType.AnsiStringFixedLength; par.Value = value; par.Size = value.Length; } #region "smart" input-output parameter detection if (commandType == CommandType.StoredProcedure && IsInOutParameterEmulation) { var iParameterName = GetInputParameterName(par.ParameterName); var fakeIOParameter = GetParameter(iParameterName, commandParameters); if (fakeIOParameter != null) { fakeIOParameter.Value = par.Value; // direction should be output, or parameter mistmath for procedure exception // would be thrown par.Direction = ParameterDirection.Output; // direction should be Input fakeIOParameter.Direction = ParameterDirection.Input; } } #endregion } base.PrepareCommand(ref commandType, ref commandText, ref commandParameters); } public override bool InitParameter(IDbDataParameter parameter) { if (parameter.Value is bool) { var value = (bool) parameter.Value ? "1" : "0"; parameter.DbType = DbType.AnsiString; parameter.Value = value; parameter.Size = value.Length; } else if (parameter.Value is Guid) { var value = parameter.Value.ToString(); parameter.DbType = DbType.AnsiStringFixedLength; parameter.Value = value; parameter.Size = value.Length; } return base.InitParameter(parameter); } public override void Configure(NameValueCollection attributes) { var inOutInputParameterPrefix = attributes["InOutInputParameterPrefix"]; if (inOutInputParameterPrefix != null) InOutInputParameterPrefix = inOutInputParameterPrefix; var returnParameterName = attributes["ReturnParameterName"]; if (returnParameterName != null) ReturnParameterName = returnParameterName; var isReturnValueEmulation = attributes["IsReturnValueEmulation"]; if (isReturnValueEmulation != null) IsReturnValueEmulation = Common.Convert.ToBoolean(isReturnValueEmulation); var isInOutParameterEmulation = attributes["IsInOutParameterEmulation"]; if (isInOutParameterEmulation != null) IsInOutParameterEmulation = Common.Convert.ToBoolean(isInOutParameterEmulation); var quoteIdentifiers = attributes["QuoteIdentifiers"]; if (quoteIdentifiers != null) QuoteIdentifiers = Common.Convert.ToBoolean(quoteIdentifiers); base.Configure(attributes); } #endregion #region FbDataReaderEx public override IDataReader GetDataReader(MappingSchema schema, IDataReader dataReader) { return dataReader is FbDataReader ? new FbDataReaderEx((FbDataReader) dataReader) : base.GetDataReader(schema, dataReader); } private class FbDataReaderEx : DataReaderBase<FbDataReader>, IDataReader { public FbDataReaderEx(FbDataReader rd) : base(rd) { } #region IDataReader Members public new object GetValue(int i) { var value = DataReader.GetValue(i); if (value is DateTime) { var dt = (DateTime) value; if (dt.Year == 1970 && dt.Month == 1 && dt.Day == 1) return new DateTime(1, 1, 1, dt.Hour, dt.Minute, dt.Second, dt.Millisecond); } return value; } public new DateTime GetDateTime(int i) { var dt = DataReader.GetDateTime(i); if (dt.Year == 1970 && dt.Month == 1 && dt.Day == 1) return new DateTime(1, 1, 1, dt.Hour, dt.Minute, dt.Second, dt.Millisecond); return dt; } #endregion } #endregion #region FbMappingSchema public class FbMappingSchema : FirebirdMappingSchema { protected override object MapInternal(InitContext initContext) { var dr = initContext.SourceObject as FbDataReader; // Fb's SP returns single row with nulls if selected object doesn't exists // so for all DBNull's (null) should be returned, instead of object instance // if (dr != null) { var i = dr.FieldCount; while (--i >= 0) if (!dr.IsDBNull(i)) break; // All field are DBNull. // if (i < 0) return null; } return base.MapInternal(initContext); } } #endregion } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using SpotifyAPI.Web.Http; using System.Runtime.CompilerServices; using System.Threading; namespace SpotifyAPI.Web { public class SpotifyClient : ISpotifyClient { private readonly IAPIConnector _apiConnector; public SpotifyClient(IToken token) : this(SpotifyClientConfig.CreateDefault(token?.AccessToken ?? throw new ArgumentNullException(nameof(token)), token.TokenType)) { } public SpotifyClient(string token, string tokenType = "Bearer") : this(SpotifyClientConfig.CreateDefault(token, tokenType)) { } public SpotifyClient(SpotifyClientConfig config) { Ensure.ArgumentNotNull(config, nameof(config)); if (config.Authenticator == null) { #pragma warning disable CA2208 throw new ArgumentNullException("Authenticator in config is null. Please supply it via `WithAuthenticator` or `WithToken`"); #pragma warning restore CA2208 } _apiConnector = config.BuildAPIConnector(); _apiConnector.ResponseReceived += (sender, response) => { LastResponse = response; }; DefaultPaginator = config.DefaultPaginator; UserProfile = new UserProfileClient(_apiConnector); Browse = new BrowseClient(_apiConnector); Shows = new ShowsClient(_apiConnector); Playlists = new PlaylistsClient(_apiConnector); Search = new SearchClient(_apiConnector); Follow = new FollowClient(_apiConnector); Tracks = new TracksClient(_apiConnector); Player = new PlayerClient(_apiConnector); Albums = new AlbumsClient(_apiConnector); Artists = new ArtistsClient(_apiConnector); Personalization = new PersonalizationClient(_apiConnector); Episodes = new EpisodesClient(_apiConnector); Library = new LibraryClient(_apiConnector); } public IPaginator DefaultPaginator { get; } public IUserProfileClient UserProfile { get; } public IBrowseClient Browse { get; } public IShowsClient Shows { get; } public IPlaylistsClient Playlists { get; } public ISearchClient Search { get; } public IFollowClient Follow { get; } public ITracksClient Tracks { get; } public IPlayerClient Player { get; } public IAlbumsClient Albums { get; } public IArtistsClient Artists { get; } public IPersonalizationClient Personalization { get; } public IEpisodesClient Episodes { get; } public ILibraryClient Library { get; } public IResponse? LastResponse { get; private set; } /// <summary> /// Fetches all pages and returns them grouped in a list. /// The default paginator will fetch all available resources without a delay between requests. /// This can drain your request limit quite fast, so consider using a custom paginator with delays. /// </summary> /// <param name="firstPage">The first page, will be included in the output list!</param> /// <param name="paginator">Optional. If not supplied, DefaultPaginator will be used</param> /// <typeparam name="T">The Paging-Type</typeparam> /// <returns>A list containing all fetched pages</returns> public Task<IList<T>> PaginateAll<T>(IPaginatable<T> firstPage, IPaginator? paginator = null) { return (paginator ?? DefaultPaginator).PaginateAll(firstPage, _apiConnector); } /// <summary> /// Fetches all pages and returns them grouped in a list. /// Some responses (e.g search response) have the pagination nested in a JSON Property. /// To workaround this limitation, the mapper is required and needs to point to the correct next pagination. /// The default paginator will fetch all available resources without a delay between requests. /// This can drain your request limit quite fast, so consider using a custom paginator with delays. /// </summary> /// <param name="firstPage">A first page, will be included in the output list!</param> /// <param name="mapper">A function which maps response objects to the next paging object</param> /// <param name="paginator">Optional. If not supplied, DefaultPaginator will be used</param> /// <typeparam name="T">The Paging-Type</typeparam> /// <typeparam name="TNext">The Response-Type</typeparam> /// <returns>A list containing all fetched pages</returns> public Task<IList<T>> PaginateAll<T, TNext>( IPaginatable<T, TNext> firstPage, Func<TNext, IPaginatable<T, TNext>> mapper, IPaginator? paginator = null ) { return (paginator ?? DefaultPaginator).PaginateAll(firstPage, mapper, _apiConnector); } private Task<T> FetchPage<T>(string? nextUrl) { if (nextUrl == null) { throw new APIPagingException("The paging object has no next page"); } return _apiConnector.Get<T>(new Uri(nextUrl, UriKind.Absolute)); } /// <summary> /// Fetches the next page of the paging object /// </summary> /// <param name="paging">A paging object which has a next page</param> /// <typeparam name="T"></typeparam> /// <returns></returns> public Task<Paging<T>> NextPage<T>(Paging<T> paging) { Ensure.ArgumentNotNull(paging, nameof(paging)); return FetchPage<Paging<T>>(paging.Next); } /// <summary> /// Fetches the next page of the cursor paging object /// </summary> /// <param name="cursorPaging">A cursor paging object which has a next page</param> /// <typeparam name="T"></typeparam> /// <returns></returns> public Task<CursorPaging<T>> NextPage<T>(CursorPaging<T> cursorPaging) { Ensure.ArgumentNotNull(cursorPaging, nameof(cursorPaging)); return FetchPage<CursorPaging<T>>(cursorPaging.Next); } /// <summary> /// Fetches the next page of the complex IPaginatable object. /// </summary> /// <param name="paginatable">A complex IPaginatable object with a next page</param> /// <typeparam name="T"></typeparam> /// <typeparam name="TNext">The type of the next page</typeparam> /// <returns></returns> public Task<TNext> NextPage<T, TNext>(IPaginatable<T, TNext> paginatable) { Ensure.ArgumentNotNull(paginatable, nameof(paginatable)); return FetchPage<TNext>(paginatable.Next); } /// <summary> /// Fetches the previous page of the paging object. /// </summary> /// <param name="paging">A paging object with a previous page</param> /// <typeparam name="T"></typeparam> /// <returns></returns> public Task<Paging<T>> PreviousPage<T>(Paging<T> paging) { Ensure.ArgumentNotNull(paging, nameof(paging)); return FetchPage<Paging<T>>(paging.Previous); } /// <summary> /// Fetches the previous page of the complex paging object. /// </summary> /// <param name="paging">A complex paging object with a previous page</param> /// <typeparam name="T"></typeparam> /// <typeparam name="TNext">The type of the next page</typeparam> /// <returns></returns> public Task<TNext> PreviousPage<T, TNext>(Paging<T, TNext> paging) { Ensure.ArgumentNotNull(paging, nameof(paging)); return FetchPage<TNext>(paging.Previous); } /// <summary> /// Paginate through pages by using IAsyncEnumerable, introduced in C# 8 /// The default paginator will fetch all available resources without a delay between requests. /// This can drain your request limit quite fast, so consider using a custom paginator with delays. /// </summary> /// <param name="firstPage">A first page, will be included in the output list!</param> /// <param name="paginator">Optional. If not supplied, DefaultPaginator will be used</param> /// <param name="cancellationToken">An optional Cancellation Token</param> /// <typeparam name="T">The Paging-Type</typeparam> /// <returns>An iterable IAsyncEnumerable</returns> public IAsyncEnumerable<T> Paginate<T>( IPaginatable<T> firstPage, IPaginator? paginator = null, CancellationToken cancellationToken = default ) { return (paginator ?? DefaultPaginator).Paginate(firstPage, _apiConnector, cancellationToken); } /// <summary> /// Paginate through pages by using IAsyncEnumerable, introduced in C# 8 /// Some responses (e.g search response) have the pagination nested in a JSON Property. /// To workaround this limitation, the mapper is required and needs to point to the correct next pagination. /// The default paginator will fetch all available resources without a delay between requests. /// This can drain your request limit quite fast, so consider using a custom paginator with delays. /// </summary> /// <param name="firstPage">A first page, will be included in the output list!</param> /// <param name="mapper">A function which maps response objects to the next paging object</param> /// <param name="paginator">Optional. If not supplied, DefaultPaginator will be used</param> /// <param name="cancellationToken">An optional Cancellation Token</param> /// <typeparam name="T">The Paging-Type</typeparam> /// <typeparam name="TNext">The Response-Type</typeparam> /// <returns></returns> public IAsyncEnumerable<T> Paginate<T, TNext>( IPaginatable<T, TNext> firstPage, Func<TNext, IPaginatable<T, TNext>> mapper, IPaginator? paginator = null, CancellationToken cancellationToken = default ) { return (paginator ?? DefaultPaginator).Paginate(firstPage, mapper, _apiConnector, cancellationToken); } /// <summary> /// Paginate through pages by using IAsyncEnumerable, introduced in C# 8 /// Some responses (e.g search response) have the pagination nested in a JSON Property. /// To workaround this limitation, the mapper is required and needs to point to the correct next pagination. /// The default paginator will fetch all available resources without a delay between requests. /// This can drain your request limit quite fast, so consider using a custom paginator with delays. /// </summary> /// <param name="getFirstPage">A Function to retrive the first page, will be included in the output list!</param> /// <param name="mapper">A function which maps response objects to the next paging object</param> /// <param name="paginator">Optional. If not supplied, DefaultPaginator will be used</param> /// <param name="cancellationToken">An optional Cancellation Token</param> /// <typeparam name="T">The Paging-Type</typeparam> /// <typeparam name="TNext">The Response-Type</typeparam> /// <returns></returns> public async IAsyncEnumerable<T> Paginate<T, TNext>( Func<Task<IPaginatable<T, TNext>>> getFirstPage, Func<TNext, IPaginatable<T, TNext>> mapper, IPaginator? paginator = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) { Ensure.ArgumentNotNull(getFirstPage, nameof(getFirstPage)); var firstPage = await getFirstPage().ConfigureAwait(false); await foreach (var item in (paginator ?? DefaultPaginator) .Paginate(firstPage, mapper, _apiConnector, cancellationToken) .WithCancellation(cancellationToken) ) { yield return item; } } /// <summary> /// Paginate through pages by using IAsyncEnumerable, introduced in C# 8 /// Some responses (e.g search response) have the pagination nested in a JSON Property. /// To workaround this limitation, the mapper is required and needs to point to the correct next pagination. /// The default paginator will fetch all available resources without a delay between requests. /// This can drain your request limit quite fast, so consider using a custom paginator with delays. /// </summary> /// <param name="firstPageTask">A Task to retrive the first page, will be included in the output list!</param> /// <param name="mapper">A function which maps response objects to the next paging object</param> /// <param name="paginator">Optional. If not supplied, DefaultPaginator will be used</param> /// <param name="cancellationToken">An optional Cancellation Token</param> /// <typeparam name="T">The Paging-Type</typeparam> /// <typeparam name="TNext">The Response-Type</typeparam> /// <returns></returns> public async IAsyncEnumerable<T> Paginate<T, TNext>( Task<IPaginatable<T, TNext>> firstPageTask, Func<TNext, IPaginatable<T, TNext>> mapper, IPaginator? paginator = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) { Ensure.ArgumentNotNull(firstPageTask, nameof(firstPageTask)); var firstPage = await firstPageTask.ConfigureAwait(false); await foreach (var item in (paginator ?? DefaultPaginator) .Paginate(firstPage, mapper, _apiConnector, cancellationToken) .WithCancellation(cancellationToken) ) { yield return item; } } } }
// --------------------------------------------------------------------------- // <copyright file="ComplexProperty.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // --------------------------------------------------------------------------- //----------------------------------------------------------------------- // <summary>Defines the ComplexProperty class.</summary> //----------------------------------------------------------------------- namespace Microsoft.Exchange.WebServices.Data { using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.Xml; /// <summary> /// Represents a property that can be sent to or retrieved from EWS. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public abstract class ComplexProperty : ISelfValidate, IJsonSerializable { private XmlNamespace xmlNamespace = XmlNamespace.Types; /// <summary> /// Initializes a new instance of the <see cref="ComplexProperty"/> class. /// </summary> internal ComplexProperty() { } /// <summary> /// Gets or sets the namespace. /// </summary> /// <value>The namespace.</value> internal XmlNamespace Namespace { get { return this.xmlNamespace; } set { this.xmlNamespace = value; } } /// <summary> /// Instance was changed. /// </summary> internal virtual void Changed() { if (this.OnChange != null) { this.OnChange(this); } } /// <summary> /// Sets value of field. /// </summary> /// <typeparam name="T">Field type.</typeparam> /// <param name="field">The field.</param> /// <param name="value">The value.</param> internal virtual void SetFieldValue<T>(ref T field, T value) { bool applyChange; if (field == null) { applyChange = value != null; } else { if (field is IComparable) { applyChange = (field as IComparable).CompareTo(value) != 0; } else { applyChange = true; } } if (applyChange) { field = value; this.Changed(); } } /// <summary> /// Clears the change log. /// </summary> internal virtual void ClearChangeLog() { } /// <summary> /// Reads the attributes from XML. /// </summary> /// <param name="reader">The reader.</param> internal virtual void ReadAttributesFromXml(EwsServiceXmlReader reader) { } /// <summary> /// Reads the text value from XML. /// </summary> /// <param name="reader">The reader.</param> internal virtual void ReadTextValueFromXml(EwsServiceXmlReader reader) { } /// <summary> /// Tries to read element from XML. /// </summary> /// <param name="reader">The reader.</param> /// <returns>True if element was read.</returns> internal virtual bool TryReadElementFromXml(EwsServiceXmlReader reader) { return false; } /// <summary> /// Tries to read element from XML to patch this property. /// </summary> /// <param name="reader">The reader.</param> /// <returns>True if element was read.</returns> internal virtual bool TryReadElementFromXmlToPatch(EwsServiceXmlReader reader) { return false; } /// <summary> /// Writes the attributes to XML. /// </summary> /// <param name="writer">The writer.</param> internal virtual void WriteAttributesToXml(EwsServiceXmlWriter writer) { } /// <summary> /// Writes elements to XML. /// </summary> /// <param name="writer">The writer.</param> internal virtual void WriteElementsToXml(EwsServiceXmlWriter writer) { } /// <summary> /// Loads from XML. /// </summary> /// <param name="reader">The reader.</param> /// <param name="xmlNamespace">The XML namespace.</param> /// <param name="xmlElementName">Name of the XML element.</param> internal virtual void LoadFromXml( EwsServiceXmlReader reader, XmlNamespace xmlNamespace, string xmlElementName) { this.InternalLoadFromXml( reader, xmlNamespace, xmlElementName, this.TryReadElementFromXml); } /// <summary> /// Loads from XML to update itself. /// </summary> /// <param name="reader">The reader.</param> /// <param name="xmlNamespace">The XML namespace.</param> /// <param name="xmlElementName">Name of the XML element.</param> internal virtual void UpdateFromXml( EwsServiceXmlReader reader, XmlNamespace xmlNamespace, string xmlElementName) { this.InternalLoadFromXml( reader, xmlNamespace, xmlElementName, this.TryReadElementFromXmlToPatch); } /// <summary> /// Loads from XML /// </summary> /// <param name="reader">The reader.</param> /// <param name="xmlNamespace">The XML namespace.</param> /// <param name="xmlElementName">Name of the XML element.</param> /// <param name="readAction"></param> private void InternalLoadFromXml( EwsServiceXmlReader reader, XmlNamespace xmlNamespace, string xmlElementName, Func<EwsServiceXmlReader, bool> readAction) { reader.EnsureCurrentNodeIsStartElement(xmlNamespace, xmlElementName); this.ReadAttributesFromXml(reader); if (!reader.IsEmptyElement) { do { reader.Read(); switch (reader.NodeType) { case XmlNodeType.Element: if (!readAction(reader)) { reader.SkipCurrentElement(); } break; case XmlNodeType.Text: this.ReadTextValueFromXml(reader); break; } } while (!reader.IsEndElement(xmlNamespace, xmlElementName)); } } /// <summary> /// Loads from XML. /// </summary> /// <param name="reader">The reader.</param> /// <param name="xmlElementName">Name of the XML element.</param> internal virtual void LoadFromXml(EwsServiceXmlReader reader, string xmlElementName) { this.LoadFromXml( reader, this.Namespace, xmlElementName); } /// <summary> /// Loads from XML to update this property. /// </summary> /// <param name="reader">The reader.</param> /// <param name="xmlElementName">Name of the XML element.</param> internal virtual void UpdateFromXml(EwsServiceXmlReader reader, string xmlElementName) { this.UpdateFromXml( reader, this.Namespace, xmlElementName); } /// <summary> /// Loads from json. /// </summary> /// <param name="jsonProperty">The json property.</param> /// <param name="service">The service.</param> internal virtual void LoadFromJson(JsonObject jsonProperty, ExchangeService service) { throw new NotImplementedException(); } /// <summary> /// Writes to XML. /// </summary> /// <param name="writer">The writer.</param> /// <param name="xmlNamespace">The XML namespace.</param> /// <param name="xmlElementName">Name of the XML element.</param> internal virtual void WriteToXml( EwsServiceXmlWriter writer, XmlNamespace xmlNamespace, string xmlElementName) { writer.WriteStartElement(xmlNamespace, xmlElementName); this.WriteAttributesToXml(writer); this.WriteElementsToXml(writer); writer.WriteEndElement(); } /// <summary> /// Writes to XML. /// </summary> /// <param name="writer">The writer.</param> /// <param name="xmlElementName">Name of the XML element.</param> internal virtual void WriteToXml(EwsServiceXmlWriter writer, string xmlElementName) { this.WriteToXml( writer, this.Namespace, xmlElementName); } /// <summary> /// Creates a JSON representation of this object. /// </summary> /// <param name="service">The service.</param> /// <returns> /// A Json value (either a JsonObject, an array of Json values, or a Json primitive) /// </returns> object IJsonSerializable.ToJson(ExchangeService service) { return this.InternalToJson(service); } /// <summary> /// Serializes the property to a Json value. /// </summary> /// <param name="service">The service.</param> /// <returns> /// A Json value (either a JsonObject, an array of Json values, or a Json primitive) /// </returns> ////internal abstract object InternalToJson(ExchangeService service); internal virtual object InternalToJson(ExchangeService service) { throw new NotImplementedException(); } /// <summary> /// Occurs when property changed. /// </summary> internal event ComplexPropertyChangedDelegate OnChange; /// <summary> /// Implements ISelfValidate.Validate. Validates this instance. /// </summary> void ISelfValidate.Validate() { this.InternalValidate(); } /// <summary> /// Validates this instance. /// </summary> internal virtual void InternalValidate() { } } }
// 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 Microsoft.Win32.SafeHandles; using System; using System.IO.Pipes; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using System.ComponentModel; using System.Security.AccessControl; using System.Security.Principal; namespace Thrift.Transport.Server { // ReSharper disable once InconsistentNaming public class TNamedPipeServerTransport : TServerTransport { /// <summary> /// This is the address of the Pipe on the localhost. /// </summary> private readonly string _pipeAddress; private bool _asyncMode = true; private volatile bool _isPending = true; private NamedPipeServerStream _stream = null; public TNamedPipeServerTransport(string pipeAddress, TConfiguration config) : base(config) { _pipeAddress = pipeAddress; } public override bool IsOpen() { return true; } public override void Listen() { // nothing to do here } public override void Close() { if (_stream != null) { try { if (_stream.IsConnected) _stream.Disconnect(); _stream.Dispose(); } finally { _stream = null; _isPending = false; } } } public override bool IsClientPending() { return _isPending; } private void EnsurePipeInstance() { if (_stream == null) { const PipeDirection direction = PipeDirection.InOut; const int maxconn = NamedPipeServerStream.MaxAllowedServerInstances; const PipeTransmissionMode mode = PipeTransmissionMode.Byte; const int inbuf = 4096; const int outbuf = 4096; var options = _asyncMode ? PipeOptions.Asynchronous : PipeOptions.None; // TODO: "CreatePipeNative" ist only a workaround, and there are have basically two possible outcomes: // - once NamedPipeServerStream() gets a CTOR that supports pipesec, remove CreatePipeNative() // - if 31190 gets resolved before, use _stream.SetAccessControl(pipesec) instead of CreatePipeNative() // EITHER WAY, // - if CreatePipeNative() finally gets removed, also remove "allow unsafe code" from the project settings try { var handle = CreatePipeNative(_pipeAddress, inbuf, outbuf); if ((handle != null) && (!handle.IsInvalid)) { _stream = new NamedPipeServerStream(PipeDirection.InOut, _asyncMode, false, handle); handle = null; // we don't own it any longer } else { handle?.Dispose(); _stream = new NamedPipeServerStream(_pipeAddress, direction, maxconn, mode, options, inbuf, outbuf/*, pipesec*/); } } catch (NotImplementedException) // Mono still does not support async, fallback to sync { if (_asyncMode) { options &= (~PipeOptions.Asynchronous); _stream = new NamedPipeServerStream(_pipeAddress, direction, maxconn, mode, options, inbuf, outbuf); _asyncMode = false; } else { throw; } } } } #region CreatePipeNative workaround [StructLayout(LayoutKind.Sequential)] internal class SECURITY_ATTRIBUTES { internal int nLength = 0; internal IntPtr lpSecurityDescriptor = IntPtr.Zero; internal int bInheritHandle = 0; } private const string Kernel32 = "kernel32.dll"; [DllImport(Kernel32, SetLastError = true)] internal static extern IntPtr CreateNamedPipe( string lpName, uint dwOpenMode, uint dwPipeMode, uint nMaxInstances, uint nOutBufferSize, uint nInBufferSize, uint nDefaultTimeOut, SECURITY_ATTRIBUTES pipeSecurityDescriptor ); // Workaround: create the pipe via API call // we have to do it this way, since NamedPipeServerStream() for netstd still lacks a few CTORs // and _stream.SetAccessControl(pipesec); only keeps throwing ACCESS_DENIED errors at us // References: // - https://github.com/dotnet/corefx/issues/30170 (closed, continued in 31190) // - https://github.com/dotnet/corefx/issues/31190 System.IO.Pipes.AccessControl package does not work // - https://github.com/dotnet/corefx/issues/24040 NamedPipeServerStream: Provide support for WRITE_DAC // - https://github.com/dotnet/corefx/issues/34400 Have a mechanism for lower privileged user to connect to a privileged user's pipe private SafePipeHandle CreatePipeNative(string name, int inbuf, int outbuf) { if (Environment.OSVersion.Platform != PlatformID.Win32NT) return null; // Windows only var pinningHandle = new GCHandle(); try { // owner gets full access, everyone else read/write var pipesec = new PipeSecurity(); using (var currentIdentity = WindowsIdentity.GetCurrent()) { var sidOwner = currentIdentity.Owner; var sidWorld = new SecurityIdentifier(WellKnownSidType.WorldSid, null); pipesec.SetOwner(sidOwner); pipesec.AddAccessRule(new PipeAccessRule(sidOwner, PipeAccessRights.FullControl, AccessControlType.Allow)); pipesec.AddAccessRule(new PipeAccessRule(sidWorld, PipeAccessRights.ReadWrite, AccessControlType.Allow)); } // create a security descriptor and assign it to the security attribs var secAttrs = new SECURITY_ATTRIBUTES(); byte[] sdBytes = pipesec.GetSecurityDescriptorBinaryForm(); pinningHandle = GCHandle.Alloc(sdBytes, GCHandleType.Pinned); unsafe { fixed (byte* pSD = sdBytes) { secAttrs.lpSecurityDescriptor = (IntPtr)pSD; } } // a bunch of constants we will need shortly const int PIPE_ACCESS_DUPLEX = 0x00000003; const int FILE_FLAG_OVERLAPPED = 0x40000000; const int WRITE_DAC = 0x00040000; const int PIPE_TYPE_BYTE = 0x00000000; const int PIPE_READMODE_BYTE = 0x00000000; const int PIPE_UNLIMITED_INSTANCES = 255; // create the pipe via API call var rawHandle = CreateNamedPipe( @"\\.\pipe\" + name, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | WRITE_DAC, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, PIPE_UNLIMITED_INSTANCES, (uint)inbuf, (uint)outbuf, 5 * 1000, secAttrs ); // make a SafePipeHandle() from it var handle = new SafePipeHandle(rawHandle, true); if (handle.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error()); // return it (to be packaged) return handle; } finally { if (pinningHandle.IsAllocated) pinningHandle.Free(); } } #endregion protected override async ValueTask<TTransport> AcceptImplementationAsync(CancellationToken cancellationToken) { try { EnsurePipeInstance(); await _stream.WaitForConnectionAsync(cancellationToken); var trans = new ServerTransport(_stream, Configuration); _stream = null; // pass ownership to ServerTransport //_isPending = false; return trans; } catch (TTransportException) { Close(); throw; } catch (Exception e) { Close(); throw new TTransportException(TTransportException.ExceptionType.NotOpen, e.Message); } } private class ServerTransport : TEndpointTransport { private readonly NamedPipeServerStream PipeStream; public ServerTransport(NamedPipeServerStream stream, TConfiguration config) : base(config) { PipeStream = stream; } public override bool IsOpen => PipeStream != null && PipeStream.IsConnected; public override Task OpenAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Task.CompletedTask; } public override void Close() { PipeStream?.Dispose(); } public override async ValueTask<int> ReadAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken) { if (PipeStream == null) { throw new TTransportException(TTransportException.ExceptionType.NotOpen); } CheckReadBytesAvailable(length); #if NETSTANDARD2_1 var numBytes = await PipeStream.ReadAsync(new Memory<byte>(buffer, offset, length), cancellationToken); #else var numBytes = await PipeStream.ReadAsync(buffer, offset, length, cancellationToken); #endif CountConsumedMessageBytes(numBytes); return numBytes; } public override async Task WriteAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken) { if (PipeStream == null) { throw new TTransportException(TTransportException.ExceptionType.NotOpen); } // if necessary, send the data in chunks // there's a system limit around 0x10000 bytes that we hit otherwise // MSDN: "Pipe write operations across a network are limited to 65,535 bytes per write. For more information regarding pipes, see the Remarks section." var nBytes = Math.Min(15 * 4096, length); // 16 would exceed the limit while (nBytes > 0) { await PipeStream.WriteAsync(buffer, offset, nBytes, cancellationToken); offset += nBytes; length -= nBytes; nBytes = Math.Min(nBytes, length); } } public override Task FlushAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ResetConsumedMessageSize(); return Task.CompletedTask; } protected override void Dispose(bool disposing) { if (disposing) { PipeStream?.Dispose(); } } } } }
#if UNITY_WINRT && !UNITY_EDITOR && !UNITY_WP8 #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Globalization; using System.Security; using Newtonsoft.Json.Utilities; using Windows.Data.Json; namespace Newtonsoft.Json.Converters { /// <summary> /// Converts a <see cref="IJsonValue"/> to and from JSON. /// </summary> public class JsonValueConverter : JsonConverter { /// <summary> /// Writes the JSON representation of the object. /// </summary> /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param> /// <param name="value">The value.</param> /// <param name="serializer">The calling serializer.</param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { WriteJsonValue(writer, (IJsonValue)value); } private void WriteJsonValue(JsonWriter writer, IJsonValue value) { switch (value.ValueType) { case JsonValueType.Array: { JsonArray a = value.GetArray(); writer.WriteStartArray(); for (int i = 0; i < a.Count; i++) { WriteJsonValue(writer, a[i]); } writer.WriteEndArray(); } break; case JsonValueType.Boolean: { writer.WriteValue(value.GetBoolean()); } break; case JsonValueType.Null: { writer.WriteNull(); } break; case JsonValueType.Number: { // JsonValue doesn't support integers // serialize whole numbers without a decimal point double d = value.GetNumber(); bool isInteger = (d % 1 == 0); if (isInteger && d <= long.MaxValue && d >= long.MinValue) writer.WriteValue(Convert.ToInt64(d)); else writer.WriteValue(d); } break; case JsonValueType.Object: { JsonObject o = value.GetObject(); writer.WriteStartObject(); foreach (KeyValuePair<string, IJsonValue> v in o) { writer.WritePropertyName(v.Key); WriteJsonValue(writer, v.Value); } writer.WriteEndObject(); } break; case JsonValueType.String: { writer.WriteValue(value.GetString()); } break; default: throw new ArgumentOutOfRangeException("ValueType"); } } /// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> to read from.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer.</param> /// <returns>The object value.</returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.None) reader.Read(); IJsonValue value = CreateJsonValue(reader); if (!objectType.IsAssignableFrom(value.GetType())) throw JsonSerializationException.Create(reader, "Could not convert '{0}' to '{1}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), objectType)); return value; } private IJsonValue CreateJsonValue(JsonReader reader) { while (reader.TokenType == JsonToken.Comment) { if (!reader.Read()) throw JsonSerializationException.Create(reader, "Unexpected end."); } switch (reader.TokenType) { case JsonToken.StartObject: { return CreateJsonObject(reader); } case JsonToken.StartArray: { JsonArray a = new JsonArray(); while (reader.Read()) { switch (reader.TokenType) { case JsonToken.EndArray: return a; default: IJsonValue value = CreateJsonValue(reader); a.Add(value); break; } } } break; case JsonToken.Integer: case JsonToken.Float: return JsonValue.CreateNumberValue(Convert.ToDouble(reader.Value, CultureInfo.InvariantCulture)); case JsonToken.String: return JsonValue.CreateStringValue(reader.Value.ToString()); case JsonToken.Boolean: return JsonValue.CreateBooleanValue(Convert.ToBoolean(reader.Value, CultureInfo.InvariantCulture)); case JsonToken.Null: // surely there is a better way to create a null value than this? return JsonValue.Parse("null"); case JsonToken.Date: return JsonValue.CreateStringValue(reader.Value.ToString()); case JsonToken.Bytes: return JsonValue.CreateStringValue(reader.Value.ToString()); default: throw JsonSerializationException.Create(reader, "Unexpected or unsupported token: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } throw JsonSerializationException.Create(reader, "Unexpected end."); } private JsonObject CreateJsonObject(JsonReader reader) { JsonObject o = new JsonObject(); string propertyName = null; while (reader.Read()) { switch (reader.TokenType) { case JsonToken.PropertyName: propertyName = (string)reader.Value; break; case JsonToken.EndObject: return o; case JsonToken.Comment: break; default: IJsonValue propertyValue = CreateJsonValue(reader); o.Add(propertyName, propertyValue); break; } } throw JsonSerializationException.Create(reader, "Unexpected end."); } /// <summary> /// Determines whether this instance can convert the specified object type. /// </summary> /// <param name="objectType">Type of the object.</param> /// <returns> /// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>. /// </returns> public override bool CanConvert(Type objectType) { return typeof(IJsonValue).IsAssignableFrom(objectType); } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Text; namespace Internal.JitInterface { // CorInfoHelpFunc defines the set of helpers (accessed via the ICorDynamicInfo::getHelperFtn()) // These helpers can be called by native code which executes in the runtime. // Compilers can emit calls to these helpers. public enum CorInfoHelpFunc { CORINFO_HELP_UNDEF, // invalid value. This should never be used /* Arithmetic helpers */ CORINFO_HELP_DIV, // For the ARM 32-bit integer divide uses a helper call :-( CORINFO_HELP_MOD, CORINFO_HELP_UDIV, CORINFO_HELP_UMOD, CORINFO_HELP_LLSH, CORINFO_HELP_LRSH, CORINFO_HELP_LRSZ, CORINFO_HELP_LMUL, CORINFO_HELP_LMUL_OVF, CORINFO_HELP_ULMUL_OVF, CORINFO_HELP_LDIV, CORINFO_HELP_LMOD, CORINFO_HELP_ULDIV, CORINFO_HELP_ULMOD, CORINFO_HELP_LNG2DBL, // Convert a signed int64 to a double CORINFO_HELP_ULNG2DBL, // Convert a unsigned int64 to a double CORINFO_HELP_DBL2INT, CORINFO_HELP_DBL2INT_OVF, CORINFO_HELP_DBL2LNG, CORINFO_HELP_DBL2LNG_OVF, CORINFO_HELP_DBL2UINT, CORINFO_HELP_DBL2UINT_OVF, CORINFO_HELP_DBL2ULNG, CORINFO_HELP_DBL2ULNG_OVF, CORINFO_HELP_FLTREM, CORINFO_HELP_DBLREM, CORINFO_HELP_FLTROUND, CORINFO_HELP_DBLROUND, /* Allocating a new object. Always use ICorClassInfo::getNewHelper() to decide which is the right helper to use to allocate an object of a given type. */ CORINFO_HELP_NEW_CROSSCONTEXT, // cross context new object CORINFO_HELP_NEWFAST, CORINFO_HELP_NEWSFAST, // allocator for small, non-finalizer, non-array object CORINFO_HELP_NEWSFAST_FINALIZE, // allocator for small, finalizable, non-array object CORINFO_HELP_NEWSFAST_ALIGN8, // allocator for small, non-finalizer, non-array object, 8 byte aligned CORINFO_HELP_NEWSFAST_ALIGN8_VC,// allocator for small, value class, 8 byte aligned CORINFO_HELP_NEWSFAST_ALIGN8_FINALIZE, // allocator for small, finalizable, non-array object, 8 byte aligned CORINFO_HELP_NEW_MDARR, // multi-dim array helper (with or without lower bounds - dimensions passed in as vararg) CORINFO_HELP_NEW_MDARR_NONVARARG,// multi-dim array helper (with or without lower bounds - dimensions passed in as unmanaged array) CORINFO_HELP_NEWARR_1_DIRECT, // helper for any one dimensional array creation CORINFO_HELP_NEWARR_1_R2R_DIRECT, // wrapper for R2R direct call, which extracts method table from ArrayTypeDesc CORINFO_HELP_NEWARR_1_OBJ, // optimized 1-D object arrays CORINFO_HELP_NEWARR_1_VC, // optimized 1-D value class arrays CORINFO_HELP_NEWARR_1_ALIGN8, // like VC, but aligns the array start CORINFO_HELP_STRCNS, // create a new string literal CORINFO_HELP_STRCNS_CURRENT_MODULE, // create a new string literal from the current module (used by NGen code) /* Object model */ CORINFO_HELP_INITCLASS, // Initialize class if not already initialized CORINFO_HELP_INITINSTCLASS, // Initialize class for instantiated type // Use ICorClassInfo::getCastingHelper to determine // the right helper to use CORINFO_HELP_ISINSTANCEOFINTERFACE, // Optimized helper for interfaces CORINFO_HELP_ISINSTANCEOFARRAY, // Optimized helper for arrays CORINFO_HELP_ISINSTANCEOFCLASS, // Optimized helper for classes CORINFO_HELP_ISINSTANCEOFANY, // Slow helper for any type CORINFO_HELP_CHKCASTINTERFACE, CORINFO_HELP_CHKCASTARRAY, CORINFO_HELP_CHKCASTCLASS, CORINFO_HELP_CHKCASTANY, CORINFO_HELP_CHKCASTCLASS_SPECIAL, // Optimized helper for classes. Assumes that the trivial cases // has been taken care of by the inlined check CORINFO_HELP_BOX, CORINFO_HELP_BOX_NULLABLE, // special form of boxing for Nullable<T> CORINFO_HELP_UNBOX, CORINFO_HELP_UNBOX_NULLABLE, // special form of unboxing for Nullable<T> CORINFO_HELP_GETREFANY, // Extract the byref from a TypedReference, checking that it is the expected type CORINFO_HELP_ARRADDR_ST, // assign to element of object array with type-checking CORINFO_HELP_LDELEMA_REF, // does a precise type comparision and returns address /* Exceptions */ CORINFO_HELP_THROW, // Throw an exception object CORINFO_HELP_RETHROW, // Rethrow the currently active exception CORINFO_HELP_USER_BREAKPOINT, // For a user program to break to the debugger CORINFO_HELP_RNGCHKFAIL, // array bounds check failed CORINFO_HELP_OVERFLOW, // throw an overflow exception CORINFO_HELP_THROWDIVZERO, // throw a divide by zero exception CORINFO_HELP_THROWNULLREF, // throw a null reference exception CORINFO_HELP_INTERNALTHROW, // Support for really fast jit CORINFO_HELP_VERIFICATION, // Throw a VerificationException CORINFO_HELP_SEC_UNMGDCODE_EXCPT, // throw a security unmanaged code exception CORINFO_HELP_FAIL_FAST, // Kill the process avoiding any exceptions or stack and data dependencies (use for GuardStack unsafe buffer checks) CORINFO_HELP_METHOD_ACCESS_EXCEPTION,//Throw an access exception due to a failed member/class access check. CORINFO_HELP_FIELD_ACCESS_EXCEPTION, CORINFO_HELP_CLASS_ACCESS_EXCEPTION, CORINFO_HELP_ENDCATCH, // call back into the EE at the end of a catch block /* Synchronization */ CORINFO_HELP_MON_ENTER, CORINFO_HELP_MON_EXIT, CORINFO_HELP_MON_ENTER_STATIC, CORINFO_HELP_MON_EXIT_STATIC, CORINFO_HELP_GETCLASSFROMMETHODPARAM, // Given a generics method handle, returns a class handle CORINFO_HELP_GETSYNCFROMCLASSHANDLE, // Given a generics class handle, returns the sync monitor // in its ManagedClassObject /* Security callout support */ CORINFO_HELP_SECURITY_PROLOG, // Required if CORINFO_FLG_SECURITYCHECK is set, or CORINFO_FLG_NOSECURITYWRAP is not set CORINFO_HELP_SECURITY_PROLOG_FRAMED, // Slow version of CORINFO_HELP_SECURITY_PROLOG. Used for instrumentation. CORINFO_HELP_METHOD_ACCESS_CHECK, // Callouts to runtime security access checks CORINFO_HELP_FIELD_ACCESS_CHECK, CORINFO_HELP_CLASS_ACCESS_CHECK, CORINFO_HELP_DELEGATE_SECURITY_CHECK, // Callout to delegate security transparency check /* Verification runtime callout support */ CORINFO_HELP_VERIFICATION_RUNTIME_CHECK, // Do a Demand for UnmanagedCode permission at runtime /* GC support */ CORINFO_HELP_STOP_FOR_GC, // Call GC (force a GC) CORINFO_HELP_POLL_GC, // Ask GC if it wants to collect CORINFO_HELP_STRESS_GC, // Force a GC, but then update the JITTED code to be a noop call CORINFO_HELP_CHECK_OBJ, // confirm that ECX is a valid object pointer (debugging only) /* GC Write barrier support */ CORINFO_HELP_ASSIGN_REF, // universal helpers with F_CALL_CONV calling convention CORINFO_HELP_CHECKED_ASSIGN_REF, CORINFO_HELP_ASSIGN_REF_ENSURE_NONHEAP, // Do the store, and ensure that the target was not in the heap. CORINFO_HELP_ASSIGN_BYREF, CORINFO_HELP_ASSIGN_STRUCT, /* Accessing fields */ // For COM object support (using COM get/set routines to update object) // and EnC and cross-context support CORINFO_HELP_GETFIELD8, CORINFO_HELP_SETFIELD8, CORINFO_HELP_GETFIELD16, CORINFO_HELP_SETFIELD16, CORINFO_HELP_GETFIELD32, CORINFO_HELP_SETFIELD32, CORINFO_HELP_GETFIELD64, CORINFO_HELP_SETFIELD64, CORINFO_HELP_GETFIELDOBJ, CORINFO_HELP_SETFIELDOBJ, CORINFO_HELP_GETFIELDSTRUCT, CORINFO_HELP_SETFIELDSTRUCT, CORINFO_HELP_GETFIELDFLOAT, CORINFO_HELP_SETFIELDFLOAT, CORINFO_HELP_GETFIELDDOUBLE, CORINFO_HELP_SETFIELDDOUBLE, CORINFO_HELP_GETFIELDADDR, CORINFO_HELP_GETSTATICFIELDADDR_CONTEXT, // Helper for context-static fields CORINFO_HELP_GETSTATICFIELDADDR_TLS, // Helper for PE TLS fields // There are a variety of specialized helpers for accessing static fields. The JIT should use // ICorClassInfo::getSharedStaticsOrCCtorHelper to determine which helper to use // Helpers for regular statics CORINFO_HELP_GETGENERICS_GCSTATIC_BASE, CORINFO_HELP_GETGENERICS_NONGCSTATIC_BASE, CORINFO_HELP_GETSHARED_GCSTATIC_BASE, CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE, CORINFO_HELP_GETSHARED_GCSTATIC_BASE_NOCTOR, CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE_NOCTOR, CORINFO_HELP_GETSHARED_GCSTATIC_BASE_DYNAMICCLASS, CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE_DYNAMICCLASS, // Helper to class initialize shared generic with dynamicclass, but not get static field address CORINFO_HELP_CLASSINIT_SHARED_DYNAMICCLASS, // Helpers for thread statics CORINFO_HELP_GETGENERICS_GCTHREADSTATIC_BASE, CORINFO_HELP_GETGENERICS_NONGCTHREADSTATIC_BASE, CORINFO_HELP_GETSHARED_GCTHREADSTATIC_BASE, CORINFO_HELP_GETSHARED_NONGCTHREADSTATIC_BASE, CORINFO_HELP_GETSHARED_GCTHREADSTATIC_BASE_NOCTOR, CORINFO_HELP_GETSHARED_NONGCTHREADSTATIC_BASE_NOCTOR, CORINFO_HELP_GETSHARED_GCTHREADSTATIC_BASE_DYNAMICCLASS, CORINFO_HELP_GETSHARED_NONGCTHREADSTATIC_BASE_DYNAMICCLASS, /* Debugger */ CORINFO_HELP_DBG_IS_JUST_MY_CODE, // Check if this is "JustMyCode" and needs to be stepped through. /* Profiling enter/leave probe addresses */ CORINFO_HELP_PROF_FCN_ENTER, // record the entry to a method (caller) CORINFO_HELP_PROF_FCN_LEAVE, // record the completion of current method (caller) CORINFO_HELP_PROF_FCN_TAILCALL, // record the completionof current method through tailcall (caller) /* Miscellaneous */ CORINFO_HELP_BBT_FCN_ENTER, // record the entry to a method for collecting Tuning data CORINFO_HELP_PINVOKE_CALLI, // Indirect pinvoke call CORINFO_HELP_TAILCALL, // Perform a tail call CORINFO_HELP_GETCURRENTMANAGEDTHREADID, CORINFO_HELP_INIT_PINVOKE_FRAME, // initialize an inlined PInvoke Frame for the JIT-compiler CORINFO_HELP_MEMSET, // Init block of memory CORINFO_HELP_MEMCPY, // Copy block of memory CORINFO_HELP_RUNTIMEHANDLE_METHOD, // determine a type/field/method handle at run-time CORINFO_HELP_RUNTIMEHANDLE_METHOD_LOG,// determine a type/field/method handle at run-time, with IBC logging CORINFO_HELP_RUNTIMEHANDLE_CLASS, // determine a type/field/method handle at run-time CORINFO_HELP_RUNTIMEHANDLE_CLASS_LOG,// determine a type/field/method handle at run-time, with IBC logging CORINFO_HELP_TYPEHANDLE_TO_RUNTIMETYPE, // Convert from a TypeHandle (native structure pointer) to RuntimeType at run-time CORINFO_HELP_TYPEHANDLE_TO_RUNTIMETYPE_MAYBENULL, // Convert from a TypeHandle (native structure pointer) to RuntimeType at run-time, the type may be null CORINFO_HELP_METHODDESC_TO_STUBRUNTIMEMETHOD, // Convert from a MethodDesc (native structure pointer) to RuntimeMethodHandle at run-time CORINFO_HELP_FIELDDESC_TO_STUBRUNTIMEFIELD, // Convert from a FieldDesc (native structure pointer) to RuntimeFieldHandle at run-time CORINFO_HELP_TYPEHANDLE_TO_RUNTIMETYPEHANDLE, // Convert from a TypeHandle (native structure pointer) to RuntimeType at run-time CORINFO_HELP_TYPEHANDLE_TO_RUNTIMETYPEHANDLE_MAYBENULL, // Convert from a TypeHandle (native structure pointer) to RuntimeTypeHandle at run-time, handle might point to a null type CORINFO_HELP_ARE_TYPES_EQUIVALENT, // Check whether two TypeHandles (native structure pointers) are equivalent CORINFO_HELP_VIRTUAL_FUNC_PTR, // look up a virtual method at run-time //CORINFO_HELP_VIRTUAL_FUNC_PTR_LOG, // look up a virtual method at run-time, with IBC logging // Not a real helpers. Instead of taking handle arguments, these helpers point to a small stub that loads the handle argument and calls the static helper. CORINFO_HELP_READYTORUN_NEW, CORINFO_HELP_READYTORUN_NEWARR_1, CORINFO_HELP_READYTORUN_ISINSTANCEOF, CORINFO_HELP_READYTORUN_CHKCAST, CORINFO_HELP_READYTORUN_STATIC_BASE, CORINFO_HELP_READYTORUN_VIRTUAL_FUNC_PTR, CORINFO_HELP_READYTORUN_GENERIC_HANDLE, CORINFO_HELP_READYTORUN_DELEGATE_CTOR, CORINFO_HELP_READYTORUN_GENERIC_STATIC_BASE, CORINFO_HELP_EE_PRESTUB, // Not real JIT helper. Used in native images. CORINFO_HELP_EE_PRECODE_FIXUP, // Not real JIT helper. Used for Precode fixup in native images. CORINFO_HELP_EE_PINVOKE_FIXUP, // Not real JIT helper. Used for PInvoke target fixup in native images. CORINFO_HELP_EE_VSD_FIXUP, // Not real JIT helper. Used for VSD cell fixup in native images. CORINFO_HELP_EE_EXTERNAL_FIXUP, // Not real JIT helper. Used for to fixup external method thunks in native images. CORINFO_HELP_EE_VTABLE_FIXUP, // Not real JIT helper. Used for inherited vtable slot fixup in native images. CORINFO_HELP_EE_REMOTING_THUNK, // Not real JIT helper. Used for remoting precode in native images. CORINFO_HELP_EE_PERSONALITY_ROUTINE,// Not real JIT helper. Used in native images. CORINFO_HELP_EE_PERSONALITY_ROUTINE_FILTER_FUNCLET,// Not real JIT helper. Used in native images to detect filter funclets. // ASSIGN_REF_EAX - CHECKED_ASSIGN_REF_EBP: NOGC_WRITE_BARRIERS JIT helper calls // // For unchecked versions EDX is required to point into GC heap. // // NOTE: these helpers are only used for x86. CORINFO_HELP_ASSIGN_REF_EAX, // EAX holds GC ptr, do a 'mov [EDX], EAX' and inform GC CORINFO_HELP_ASSIGN_REF_EBX, // EBX holds GC ptr, do a 'mov [EDX], EBX' and inform GC CORINFO_HELP_ASSIGN_REF_ECX, // ECX holds GC ptr, do a 'mov [EDX], ECX' and inform GC CORINFO_HELP_ASSIGN_REF_ESI, // ESI holds GC ptr, do a 'mov [EDX], ESI' and inform GC CORINFO_HELP_ASSIGN_REF_EDI, // EDI holds GC ptr, do a 'mov [EDX], EDI' and inform GC CORINFO_HELP_ASSIGN_REF_EBP, // EBP holds GC ptr, do a 'mov [EDX], EBP' and inform GC CORINFO_HELP_CHECKED_ASSIGN_REF_EAX, // These are the same as ASSIGN_REF above ... CORINFO_HELP_CHECKED_ASSIGN_REF_EBX, // ... but also check if EDX points into heap. CORINFO_HELP_CHECKED_ASSIGN_REF_ECX, CORINFO_HELP_CHECKED_ASSIGN_REF_ESI, CORINFO_HELP_CHECKED_ASSIGN_REF_EDI, CORINFO_HELP_CHECKED_ASSIGN_REF_EBP, CORINFO_HELP_LOOP_CLONE_CHOICE_ADDR, // Return the reference to a counter to decide to take cloned path in debug stress. CORINFO_HELP_DEBUG_LOG_LOOP_CLONING, // Print a message that a loop cloning optimization has occurred in debug mode. CORINFO_HELP_THROW_ARGUMENTEXCEPTION, // throw ArgumentException CORINFO_HELP_THROW_ARGUMENTOUTOFRANGEEXCEPTION, // throw ArgumentOutOfRangeException CORINFO_HELP_THROW_NOT_IMPLEMENTED, // throw NotImplementedException CORINFO_HELP_THROW_PLATFORM_NOT_SUPPORTED, // throw PlatformNotSupportedException CORINFO_HELP_THROW_TYPE_NOT_SUPPORTED, // throw TypeNotSupportedException CORINFO_HELP_JIT_PINVOKE_BEGIN, // Transition to preemptive mode before a P/Invoke, frame is the first argument CORINFO_HELP_JIT_PINVOKE_END, // Transition to cooperative mode after a P/Invoke, frame is the first argument CORINFO_HELP_JIT_REVERSE_PINVOKE_ENTER, // Transition to cooperative mode in reverse P/Invoke prolog, frame is the first argument CORINFO_HELP_JIT_REVERSE_PINVOKE_EXIT, // Transition to preemptive mode in reverse P/Invoke epilog, frame is the first argument CORINFO_HELP_GVMLOOKUP_FOR_SLOT, // Resolve a generic virtual method target from this pointer and runtime method handle CORINFO_HELP_STACK_PROBE, // Probes each page of the allocated stack frame CORINFO_HELP_COUNT, } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsAzureCompositeModelClient { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// BasicOperations operations. /// </summary> internal partial class BasicOperations : IServiceOperations<AzureCompositeModel>, IBasicOperations { /// <summary> /// Initializes a new instance of the BasicOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal BasicOperations(AzureCompositeModel client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AzureCompositeModel /// </summary> public AzureCompositeModel Client { get; private set; } /// <summary> /// Get complex type {id: 2, name: 'abc', color: 'YELLOW'} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Basic>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/valid").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Basic>(); _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 = SafeJsonConvert.DeserializeObject<Basic>(_responseContent, this.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> /// Please put {id: 2, name: 'abc', color: 'Magenta'} /// </summary> /// <param name='complexBody'> /// Please put {id: 2, name: 'abc', color: 'Magenta'} /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PutValidWithHttpMessagesAsync(Basic complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (complexBody == null) { throw new ValidationException(ValidationRules.CannotBeNull, "complexBody"); } string apiVersion = "2016-02-29"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/valid").ToString(); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(complexBody != null) { _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a basic complex type that is invalid for the local strong type /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Basic>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/invalid").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Basic>(); _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 = SafeJsonConvert.DeserializeObject<Basic>(_responseContent, this.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> /// Get a basic complex type that is empty /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Basic>> GetEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetEmpty", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/empty").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Basic>(); _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 = SafeJsonConvert.DeserializeObject<Basic>(_responseContent, this.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> /// Get a basic complex type whose properties are null /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Basic>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/null").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Basic>(); _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 = SafeJsonConvert.DeserializeObject<Basic>(_responseContent, this.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> /// Get a basic complex type while the server doesn't provide a response /// payload /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Basic>> GetNotProvidedWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetNotProvided", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/notprovided").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Basic>(); _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 = SafeJsonConvert.DeserializeObject<Basic>(_responseContent, this.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; } } }
namespace Nancy.Bootstrappers.Autofac { using System; using System.Collections.Generic; using global::Autofac; using global::Autofac.Core.Lifetime; using Configuration; using Diagnostics; using Bootstrapper; public abstract class AutofacNancyBootstrapper : NancyBootstrapperWithRequestContainerBase<ILifetimeScope> { protected override IDiagnostics GetDiagnostics() { return this.ApplicationContainer.Resolve<IDiagnostics>(); } /// <summary> /// Gets all registered application startup tasks /// </summary> /// <returns>An <see cref="System.Collections.Generic.IEnumerable{T}"/> instance containing <see cref="IApplicationStartup"/> instances. </returns> protected override IEnumerable<IApplicationStartup> GetApplicationStartupTasks() { return this.ApplicationContainer.Resolve<IEnumerable<IApplicationStartup>>(); } /// <summary> /// Gets all registered request startup tasks /// </summary> /// <returns>An <see cref="IEnumerable{T}"/> instance containing <see cref="IRequestStartup"/> instances.</returns> protected override IEnumerable<IRequestStartup> RegisterAndGetRequestStartupTasks(ILifetimeScope container, Type[] requestStartupTypes) { container.Update(builder => { foreach (var requestStartupType in requestStartupTypes) { builder.RegisterType(requestStartupType).As<IRequestStartup>().PreserveExistingDefaults().InstancePerDependency(); } }); return container.Resolve<IEnumerable<IRequestStartup>>(); } /// <summary> /// Gets all registered application registration tasks /// </summary> /// <returns>An <see cref="System.Collections.Generic.IEnumerable{T}"/> instance containing <see cref="IRegistrations"/> instances.</returns> protected override IEnumerable<IRegistrations> GetRegistrationTasks() { return this.ApplicationContainer.Resolve<IEnumerable<IRegistrations>>(); } /// <summary> /// Get INancyEngine /// </summary> /// <returns>INancyEngine implementation</returns> protected override INancyEngine GetEngineInternal() { return this.ApplicationContainer.Resolve<INancyEngine>(); } /// <summary> /// Gets the <see cref="INancyEnvironmentConfigurator"/> used by th. /// </summary> /// <returns>An <see cref="INancyEnvironmentConfigurator"/> instance.</returns> protected override INancyEnvironmentConfigurator GetEnvironmentConfigurator() { return this.ApplicationContainer.Resolve<INancyEnvironmentConfigurator>(); } /// <summary> /// Registers an <see cref="INancyEnvironment"/> instance in the container. /// </summary> /// <param name="container">The container to register into.</param> /// <param name="environment">The <see cref="INancyEnvironment"/> instance to register.</param> protected override void RegisterNancyEnvironment(ILifetimeScope container, INancyEnvironment environment) { container.Update(builder => builder.RegisterInstance(environment)); } /// <summary> /// Create a default, unconfigured, container /// </summary> /// <returns>Container instance</returns> protected override ILifetimeScope GetApplicationContainer() { return new ContainerBuilder().Build(); } /// <summary> /// Bind the bootstrapper's implemented types into the container. /// This is necessary so a user can pass in a populated container but not have /// to take the responsibility of registering things like INancyModuleCatalog manually. /// </summary> /// <param name="applicationContainer">Application container to register into</param> protected override void RegisterBootstrapperTypes(ILifetimeScope applicationContainer) { applicationContainer.Update(builder => builder.RegisterInstance(this).As<INancyModuleCatalog>()); } /// <summary> /// Bind the default implementations of internally used types into the container as singletons /// </summary> /// <param name="container">Container to register into</param> /// <param name="typeRegistrations">Type registrations to register</param> protected override void RegisterTypes(ILifetimeScope container, IEnumerable<TypeRegistration> typeRegistrations) { container.Update(builder => { foreach (var typeRegistration in typeRegistrations) { switch (typeRegistration.Lifetime) { case Lifetime.Transient: builder.RegisterType(typeRegistration.ImplementationType).As(typeRegistration.RegistrationType).InstancePerDependency(); break; case Lifetime.Singleton: builder.RegisterType(typeRegistration.ImplementationType).As(typeRegistration.RegistrationType).SingleInstance(); break; case Lifetime.PerRequest: throw new InvalidOperationException("Unable to directly register a per request lifetime."); default: throw new ArgumentOutOfRangeException(); } } }); } /// <summary> /// Bind the various collections into the container as singletons to later be resolved /// by IEnumerable{Type} constructor dependencies. /// </summary> /// <param name="container">Container to register into</param> /// <param name="collectionTypeRegistrations">Collection type registrations to register</param> protected override void RegisterCollectionTypes(ILifetimeScope container, IEnumerable<CollectionTypeRegistration> collectionTypeRegistrations) { container.Update(builder => { foreach (var collectionTypeRegistration in collectionTypeRegistrations) { foreach (var implementationType in collectionTypeRegistration.ImplementationTypes) { switch (collectionTypeRegistration.Lifetime) { case Lifetime.Transient: builder.RegisterType(implementationType).As(collectionTypeRegistration.RegistrationType).PreserveExistingDefaults().InstancePerDependency(); break; case Lifetime.Singleton: builder.RegisterType(implementationType).As(collectionTypeRegistration.RegistrationType).PreserveExistingDefaults().SingleInstance(); break; case Lifetime.PerRequest: throw new InvalidOperationException("Unable to directly register a per request lifetime."); default: throw new ArgumentOutOfRangeException(); } } } }); } /// <summary> /// Bind the given instances into the container /// </summary> /// <param name="container">Container to register into</param> /// <param name="instanceRegistrations">Instance registration types</param> protected override void RegisterInstances(ILifetimeScope container, IEnumerable<InstanceRegistration> instanceRegistrations) { container.Update(builder => { foreach (var instanceRegistration in instanceRegistrations) { builder.RegisterInstance(instanceRegistration.Implementation).As(instanceRegistration.RegistrationType); } }); } /// <summary> /// Creates a per request child/nested container /// </summary> /// <param name="context">Current context</param> /// <returns>Request container instance</returns> protected override ILifetimeScope CreateRequestContainer(NancyContext context) { return ApplicationContainer.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag); } /// <summary> /// Bind the given module types into the container /// </summary> /// <param name="container">Container to register into</param> /// <param name="moduleRegistrationTypes"><see cref="INancyModule"/> types</param> protected override void RegisterRequestContainerModules(ILifetimeScope container, IEnumerable<ModuleRegistration> moduleRegistrationTypes) { container.Update(builder => { foreach (var moduleRegistrationType in moduleRegistrationTypes) { builder.RegisterType(moduleRegistrationType.ModuleType).As<INancyModule>(); } }); } /// <summary> /// Retrieve all module instances from the container /// </summary> /// <param name="container">Container to use</param> /// <returns>Collection of <see cref="INancyModule"/> instances</returns> protected override IEnumerable<INancyModule> GetAllModules(ILifetimeScope container) { return container.Resolve<IEnumerable<INancyModule>>(); } /// <summary> /// Retreive a specific module instance from the container /// </summary> /// <param name="container">Container to use</param> /// <param name="moduleType">Type of the module</param> /// <returns>An <see cref="INancyModule"/> instance</returns> protected override INancyModule GetModule(ILifetimeScope container, Type moduleType) { return container.Update(builder => builder.RegisterType(moduleType).As<INancyModule>()).Resolve<INancyModule>(); } } }
using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; #if ARM64_SIMD_API_PENDING_APPROVAL_AND_OR_COREFX_MERGE using System.Runtime.Intrinsics.Arm.Arm64; #endif //ARM64_SIMD_API_PENDING_APPROVAL_AND_OR_COREFX_MERGE namespace Arm64intrisicsTest { class Program { struct DataSet<TBaseType, TVectorType> where TBaseType : struct where TVectorType : new() { private static TVectorType _vectorX; private static TVectorType _vectorY; private static TVectorType _vectorZ; public static TVectorType vectorX { get { return _vectorX; }} public static TVectorType vectorY { get { return _vectorY; }} public static TVectorType vectorZ { get { return _vectorZ; }} public static TBaseType[] arrayX { get; private set; } public static TBaseType[] arrayY { get; private set; } public static TBaseType[] arrayZ { get; private set; } public static unsafe void setData(TBaseType[] x, TBaseType[] y) { arrayX = x; arrayY = y; GCHandle handleSrc = GCHandle.Alloc(x, GCHandleType.Pinned); try { var ptrSrc = (byte*) handleSrc.AddrOfPinnedObject().ToPointer(); _vectorX = Unsafe.Read<TVectorType>(ptrSrc); } finally { handleSrc.Free(); } handleSrc = GCHandle.Alloc(y, GCHandleType.Pinned); try { var ptrSrc = (byte*) handleSrc.AddrOfPinnedObject().ToPointer(); _vectorY = Unsafe.Read<TVectorType>(ptrSrc); } finally { handleSrc.Free(); } } public static unsafe void setData(TBaseType[] x, TBaseType[] y, TBaseType[] z) { setData(x, y); arrayZ = z; GCHandle handleSrc = GCHandle.Alloc(z, GCHandleType.Pinned); try { var ptrSrc = (byte*) handleSrc.AddrOfPinnedObject().ToPointer(); _vectorZ = Unsafe.Read<TVectorType>(ptrSrc); } finally { handleSrc.Free(); } } } static unsafe TBaseType[] writeVector<TBaseType, TVectorType>(TVectorType src) where TBaseType : struct where TVectorType : new() { var length = Unsafe.SizeOf<TVectorType>() / Unsafe.SizeOf<TBaseType>(); var dst = new TBaseType[length]; GCHandle handleSrc = GCHandle.Alloc(src, GCHandleType.Pinned); GCHandle handleDst = GCHandle.Alloc(dst, GCHandleType.Pinned); try { var ptrSrc = (byte*) handleSrc.AddrOfPinnedObject().ToPointer(); var ptrDst = (byte*) handleDst.AddrOfPinnedObject().ToPointer(); for (int i = 0; i < Unsafe.SizeOf<TVectorType>(); ++i) { ptrDst[i] = ptrSrc[i]; } } finally { handleSrc.Free(); handleDst.Free(); } return dst; } static void testCryptoOp<TBaseType, TVectorType, TBaseReturnType, TVectorReturnType>(String testCaseDescription, Func<TVectorType, TVectorType, TVectorType, TVectorReturnType> cryptoOp, TBaseType[] check) where TBaseType : struct, IComparable where TVectorType : new() where TBaseReturnType : struct, IComparable where TVectorReturnType : new() { bool failed = false; try { var vX = DataSet<TBaseType, TVectorType>.vectorX; var vY = DataSet<TBaseType, TVectorType>.vectorY; var vZ = DataSet<TBaseType, TVectorType>.vectorZ; var vResult = cryptoOp(vX, vY, vZ); var result = writeVector<TBaseReturnType, TVectorReturnType>(vResult); //Console.WriteLine("res [{0}]", string.Join(", ", result)); for (int i = 0; i < result.Length; i++) { var expected = check[i]; if (result[i].CompareTo(expected) != 0) { if(!failed) { Console.WriteLine($"testCryptoOp<{typeof(TBaseType).Name}, {typeof(TVectorType).Name} >{testCaseDescription}: Check Failed"); } Console.WriteLine($"check[{i}] : result[{i}] = {result[i]}, expected {expected}"); failed = true; } } } catch { Console.WriteLine($"testCryptoOp<{typeof(TBaseType).Name}, {typeof(TVectorType).Name} >{testCaseDescription}: Unexpected exception"); throw; } if (failed) { throw new Exception($"testCryptoOp<{typeof(TBaseType).Name}, {typeof(TVectorType).Name} >{testCaseDescription}: Failed"); } else { Console.WriteLine($"testCryptoOp<{typeof(TBaseType).Name}, {typeof(TVectorType).Name} >{testCaseDescription}: Check Passed"); } } static void testThrowsTypeNotSupported<TVectorType>(String testCaseDescription, Func<TVectorType, TVectorType, TVectorType, TVectorType> cryptoOp) where TVectorType : new() { TVectorType v = new TVectorType(); bool notSupported = false; try { cryptoOp(v,v,v); } catch (PlatformNotSupportedException) { notSupported = true; } finally { Debug.Assert(notSupported, $"{typeof(TVectorType).Name} {testCaseDescription}: Failed to throw PlatformNotSupportedException"); } } static void testThrowsPlatformNotSupported<TVectorType>(String testCaseDescription, Func<TVectorType, TVectorType, TVectorType, TVectorType> cryptoOp) where TVectorType : new() { testThrowsPlatformNotSupported<TVectorType, TVectorType>(testCaseDescription, cryptoOp); } static void testThrowsPlatformNotSupported<TVectorType, TVectorTypeReturn>(String testCaseDescription, Func<TVectorType, TVectorType, TVectorType, TVectorTypeReturn> cryptoOp) where TVectorType : new() { TVectorType v = new TVectorType(); bool notSupported = false; try { cryptoOp(v,v,v); } catch (PlatformNotSupportedException) // TODO-Fixme check for Type not supported exception { notSupported = true; } finally { Debug.Assert(notSupported, $"{typeof(TVectorType).Name} {testCaseDescription}: Failed to throw TypeNotSupportedException"); } } static void TestAes() { #if ARM64_SIMD_API_PENDING_APPROVAL_AND_OR_COREFX_MERGE String name = "Aes"; if (Aes.IsSupported) { testCryptoOp<byte, Vector128<byte>, byte, Vector128<byte> >(name, (x, y, z) => Aes.Encrypt(x, y), aesEncRes); testCryptoOp<byte, Vector128<byte>, byte, Vector128<byte> >(name, (x, y, z) => Aes.Decrypt(x, y), aesDecRes); testCryptoOp<byte, Vector128<byte>, byte, Vector128<byte> >(name, (x, y, z) => Aes.MixColumns(x), aesMixRes ); testCryptoOp<byte, Vector128<byte>, byte, Vector128<byte> >(name, (x, y, z) => Aes.InverseMixColumns(x), aesInvMixRes ); } else { testThrowsPlatformNotSupported<Vector128<byte> , Vector128<byte> >(name, (x, y, z) => Aes.Encrypt(x,y)); testThrowsPlatformNotSupported<Vector128<byte> , Vector128<byte> >(name, (x, y, z) => Aes.Decrypt(x,y)); testThrowsPlatformNotSupported<Vector128<byte> , Vector128<byte> >(name, (x, y, z) => Aes.MixColumns(x)); testThrowsPlatformNotSupported<Vector128<byte> , Vector128<byte> >(name, (x, y, z) => Aes.InverseMixColumns(x)); } #endif //ARM64_SIMD_API_PENDING_APPROVAL_AND_OR_COREFX_MERGE } static void TestSha256() { #if ARM64_SIMD_API_PENDING_APPROVAL_AND_OR_COREFX_MERGE String name = "Sha256"; if (Sha256.IsSupported) { testCryptoOp<uint, Vector128<uint>, uint, Vector128<uint> >(name, (x, y, z) => Sha256.HashLower(x, y, z), sha256low); testCryptoOp<uint, Vector128<uint>, uint, Vector128<uint> >(name, (x, y, z) => Sha256.HashUpper(x, y, z), sha256high); testCryptoOp<uint, Vector128<uint>, uint, Vector128<uint> >(name, (x, y, z) => Sha256.SchedulePart1(x, y), sha256su1Res); testCryptoOp<uint, Vector128<uint>, uint, Vector128<uint> >(name, (x, y, z) => Sha256.SchedulePart2(x, y, z), sha256su2Res); } else { testThrowsPlatformNotSupported<Vector128<uint>, Vector128<uint> >(name, (x, y, z) => Sha256.HashLower(x, y, z)); testThrowsPlatformNotSupported<Vector128<uint>, Vector128<uint> >(name, (x, y, z) => Sha256.HashUpper(x, y, z)); testThrowsPlatformNotSupported<Vector128<uint>, Vector128<uint> >(name, (x, y, z) => Sha256.SchedulePart1(x, y)); testThrowsPlatformNotSupported<Vector128<uint>, Vector128<uint> >(name, (x, y, z) => Sha256.SchedulePart2(x, y, z)); } #endif //ARM64_SIMD_API_PENDING_APPROVAL_AND_OR_COREFX_MERGE } static void TestSha1() { #if ARM64_SIMD_API_PENDING_APPROVAL_AND_OR_COREFX_MERGE String name = "Sha1"; if (Sha1.IsSupported) { testCryptoOp<uint, Vector128<uint>, uint, Vector128<uint> >(name, (x, y, z) => Sha1.HashChoose(x, 20, y), sha1cRes); testCryptoOp<uint, Vector128<uint>, uint, Vector128<uint> >(name, (x, y, z) => Sha1.HashParity(x, 20, y), sha1pRes); testCryptoOp<uint, Vector128<uint>, uint, Vector128<uint> >(name, (x, y, z) => Sha1.HashMajority(x, 20, y), sha1mRes); testCryptoOp<uint, Vector128<uint>, uint, Vector128<uint> >(name, (x, y, z) => Sha1.SchedulePart1(x, y, z), sha1su1Res); testCryptoOp<uint, Vector128<uint>, uint, Vector128<uint> >(name, (x, y, z) => Sha1.SchedulePart2(x, y), sha1su2Res); if(Sha1.FixedRotate(100) != 25) throw new Exception("Sha1 FixedRotate failed.\n"); } else { testThrowsPlatformNotSupported<Vector128<uint> , Vector128<uint> >(name, (x, y, z) => Sha1.HashChoose(x, 20, y)); testThrowsPlatformNotSupported<Vector128<uint> , Vector128<uint> >(name, (x, y, z) => Sha1.HashParity(x, 20, y)); testThrowsPlatformNotSupported<Vector128<uint> , Vector128<uint> >(name, (x, y, z) => Sha1.HashMajority(x, 20, y)); testThrowsPlatformNotSupported<Vector128<uint> , Vector128<uint> >(name, (x, y, z) => Sha1.SchedulePart1(x, y, z)); testThrowsPlatformNotSupported<Vector128<uint> , Vector128<uint> >(name, (x, y, z) => Sha1.SchedulePart2(x, y)); } #endif //ARM64_SIMD_API_PENDING_APPROVAL_AND_OR_COREFX_MERGE } static void initializeDataSetDefault() { /// Data sets DataSet<byte, Vector128<byte> >.setData(new byte[] { 1, 5, 100, 0, 7, 8, 2, 9, 1, 5, 100, 0, 7, 8, 2, 9 }, new byte[] { 22, 1, 50, 0, 7, 5, 3, 33, 17, 4, 100, 120, 27, 6, 2, 6 }, new byte[] { 1, 5, 10, 0, 17, 23, 14, 33, 15, 40, 0, 20, 22, 55, 12, 5 }); DataSet<uint, Vector128<uint> >.setData(new uint[] {10, 44, 11, 81}, new uint[] {20, 41, 67, 59}, new uint[] {10, 20, 51, 96}); } // Below result values are obtained by executing the corresponding GCC arm64 crypto intrinsics (defined in arm_neon.h) // with the same input dataset on ARM64 platform. static byte[] aesEncRes = new byte[] {240, 215, 99, 118, 99, 124, 99, 99, 202, 171, 177, 52, 156, 242, 124, 188}; static byte[] aesDecRes = new byte[] {135, 215, 82, 238, 82, 48, 82, 193, 124, 243, 185, 251, 196, 09, 09, 82}; static byte[] aesMixRes = new byte[] {105, 167, 204, 98, 29, 24, 16, 17, 105, 167, 204, 98, 29, 24, 16, 17}; static byte[] aesInvMixRes = new byte[] {203, 158, 110, 91, 41, 60, 36, 53, 203, 158, 110, 91, 41, 60, 36, 53}; static uint[] sha1cRes = new uint[] {2162335592, 464120, 1073745449, 1073741936}; static uint[] sha1pRes = new uint[] {15831335, 2147977893, 3857, 2147483767}; static uint[] sha1mRes = new uint[] {12230250, 382193, 1073744809, 1073741916}; static uint[] sha1su1Res = new uint[] {11, 105, 44, 24}; static uint[] sha1su2Res = new uint[] {70,222,96,46}; static uint[] sha256low = new uint[] {3870443882, 98061066, 1597900421, 3536859796}; static uint[] sha256high = new uint[] {2024066181, 3259295072, 1866655758, 692061599}; static uint[] sha256su1Res = new uint[] {1477115919, 369279021, 2719236117, 671416403}; static uint[] sha256su2Res = new uint[] {2089011, 3932271, 203417658, 2151313268}; static void ExecuteAllTests() { TestAes(); TestSha1(); TestSha256(); } static int Main(string[] args) { #if ARM64_SIMD_API_PENDING_APPROVAL_AND_OR_COREFX_MERGE Console.WriteLine($"System.Runtime.Intrinsics.Arm.Arm64.Aes.IsSupported = {Aes.IsSupported}"); Console.WriteLine($"System.Runtime.Intrinsics.Arm.Arm64.Sha1.IsSupported = {Sha1.IsSupported}"); Console.WriteLine($"System.Runtime.Intrinsics.Arm.Arm64.Sha2.IsSupported = {Sha256.IsSupported}"); #endif //ARM64_SIMD_API_PENDING_APPROVAL_AND_OR_COREFX_MERGE initializeDataSetDefault(); Console.WriteLine("Running tests"); ExecuteAllTests(); return 100; } } }
using System; using System.Linq; using UnityEngine; namespace FarrokhGames.Inventory { public class InventoryManager : IInventoryManager { private Vector2Int _size = Vector2Int.one; private IInventoryProvider _provider; private Rect _fullRect; public InventoryManager(IInventoryProvider provider, int width, int height) { _provider = provider; Rebuild(); Resize(width, height); } /// <inheritdoc /> public int width => _size.x; /// <inheritdoc /> public int height => _size.y; /// <inheritdoc /> public void Resize(int newWidth, int newHeight) { _size.x = newWidth; _size.y = newHeight; RebuildRect(); } private void RebuildRect() { _fullRect = new Rect(0, 0, _size.x, _size.y); HandleSizeChanged(); onResized?.Invoke(); } private void HandleSizeChanged() { // Drop all items that no longer fit the inventory for (int i = 0; i < allItems.Length;) { var item = allItems[i]; var shouldBeDropped = false; var padding = Vector2.one * 0.01f; if (!_fullRect.Contains(item.GetMinPoint() + padding) || !_fullRect.Contains(item.GetMaxPoint() - padding)) { shouldBeDropped = true; } if (shouldBeDropped) { TryDrop(item); } else { i++; } } } /// <inheritdoc /> public void Rebuild() { Rebuild(false); } private void Rebuild(bool silent) { allItems = new IInventoryItem[_provider.inventoryItemCount]; for (var i = 0; i < _provider.inventoryItemCount; i++) { allItems[i] = _provider.GetInventoryItem(i); } if (!silent)onRebuilt?.Invoke(); } public void Dispose() { _provider = null; allItems = null; } /// <inheritdoc /> public bool isFull { get { if (_provider.isInventoryFull)return true; for (var x = 0; x < width; x++) { for (var y = 0; y < height; y++) { if (GetAtPoint(new Vector2Int(x, y)) == null) { return false; } } } return true; } } /// <inheritdoc /> public IInventoryItem[] allItems { get; private set; } /// <inheritdoc /> public Action onRebuilt { get; set; } /// <inheritdoc /> public Action<IInventoryItem> onItemDropped { get; set; } /// <inheritdoc /> public Action<IInventoryItem> onItemDroppedFailed { get; set; } /// <inheritdoc /> public Action<IInventoryItem> onItemAdded { get; set; } /// <inheritdoc /> public Action<IInventoryItem> onItemAddedFailed { get; set; } /// <inheritdoc /> public Action<IInventoryItem> onItemRemoved { get; set; } /// <inheritdoc /> public Action onResized { get; set; } /// <inheritdoc /> public IInventoryItem GetAtPoint(Vector2Int point) { // Single item override if (_provider.inventoryRenderMode == InventoryRenderMode.Single && _provider.isInventoryFull && allItems.Length > 0) { return allItems[0]; } foreach (var item in allItems) { if (item.Contains(point)) { return item; } } return null; } /// <inheritdoc /> public IInventoryItem[] GetAtPoint(Vector2Int point, Vector2Int size) { var posibleItems = new IInventoryItem[size.x * size.y]; var c = 0; for (var x = 0; x < size.x; x++) { for (var y = 0; y < size.y; y++) { posibleItems[c] = GetAtPoint(point + new Vector2Int(x, y)); c++; } } return posibleItems.Distinct().Where(x => x != null).ToArray(); } /// <inheritdoc /> public bool TryRemove(IInventoryItem item) { if (!CanRemove(item)) return false; if (!_provider.RemoveInventoryItem(item)) return false; Rebuild(true); onItemRemoved?.Invoke(item); return true; } /// <inheritdoc /> public bool TryDrop(IInventoryItem item) { if (!CanDrop(item) || !_provider.DropInventoryItem(item)) { onItemDroppedFailed?.Invoke(item); return false; } Rebuild(true); onItemDropped?.Invoke(item); return true; } internal bool TryForceDrop(IInventoryItem item) { if(!item.canDrop) { onItemDroppedFailed?.Invoke(item); return false; } onItemDropped?.Invoke(item); return true; } /// <inheritdoc /> public bool CanAddAt(IInventoryItem item, Vector2Int point) { if (!_provider.CanAddInventoryItem(item) || _provider.isInventoryFull) { return false; } if (_provider.inventoryRenderMode == InventoryRenderMode.Single) { return true; } var previousPoint = item.position; item.position = point; var padding = Vector2.one * 0.01f; // Check if item is outside of inventory if (!_fullRect.Contains(item.GetMinPoint() + padding) || !_fullRect.Contains(item.GetMaxPoint() - padding)) { item.position = previousPoint; return false; } // Check if item overlaps another item already in the inventory if (!allItems.Any(otherItem => item.Overlaps(otherItem))) return true; // Item can be added item.position = previousPoint; return false; } /// <inheritdoc /> public bool TryAddAt(IInventoryItem item, Vector2Int point) { if (!CanAddAt(item, point) || !_provider.AddInventoryItem(item)) { onItemAddedFailed?.Invoke(item); return false; } switch (_provider.inventoryRenderMode) { case InventoryRenderMode.Single: item.position = GetCenterPosition(item); break; case InventoryRenderMode.Grid: item.position = point; break; default: throw new NotImplementedException($"InventoryRenderMode.{_provider.inventoryRenderMode.ToString()} have not yet been implemented"); } Rebuild(true); onItemAdded?.Invoke(item); return true; } /// <inheritdoc /> public bool CanAdd(IInventoryItem item) { Vector2Int point; if (!Contains(item) && GetFirstPointThatFitsItem(item, out point)) { return CanAddAt(item, point); } return false; } /// <inheritdoc /> public bool TryAdd(IInventoryItem item) { if (!CanAdd(item))return false; Vector2Int point; return GetFirstPointThatFitsItem(item, out point) && TryAddAt(item, point); } /// <inheritdoc /> public bool CanSwap(IInventoryItem item) { return _provider.inventoryRenderMode == InventoryRenderMode.Single && DoesItemFit(item) && _provider.CanAddInventoryItem(item); } /// <inheritdoc /> public void DropAll() { var itemsToDrop = allItems.ToArray(); foreach (var item in itemsToDrop) { TryDrop(item); } } /// <inheritdoc /> public void Clear() { foreach (var item in allItems) { TryRemove(item); } } /// <inheritdoc /> public bool Contains(IInventoryItem item) => allItems.Contains(item); /// <inheritdoc /> public bool CanRemove(IInventoryItem item) => Contains(item) && _provider.CanRemoveInventoryItem(item); /// <inheritdoc /> public bool CanDrop(IInventoryItem item) => Contains(item) && _provider.CanDropInventoryItem(item) && item.canDrop; /* * Get first free point that will fit the given item */ private bool GetFirstPointThatFitsItem(IInventoryItem item, out Vector2Int point) { if (DoesItemFit(item)) { for (var x = 0; x < width - (item.width - 1); x++) { for (var y = 0; y < height - (item.height - 1); y++) { point = new Vector2Int(x, y); if (CanAddAt(item, point))return true; } } } point = Vector2Int.zero; return false; } /* * Returns true if given items physically fits within this inventory */ private bool DoesItemFit(IInventoryItem item) => item.width <= width && item.height <= height; /* * Returns the center post position for a given item within this inventory */ private Vector2Int GetCenterPosition(IInventoryItem item) { return new Vector2Int( (_size.x - item.width) / 2, (_size.y - item.height) / 2 ); } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Symbology.dll // Description: Contains the business logic for symbology layers and symbol categories. // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 5/29/2009 2:08:58 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections; using System.Collections.Generic; using System.Reflection; namespace DotSpatial.Symbology { /// <summary> /// Descriptors are simple classes that are used for storing symbology or other basic characteristics. /// They are presumed to be made up of value types and other descriptors, and are expected to be serializable. /// This being said, some basic capabilities are supported for randomizing, copying and comparing the /// properties of descriptors. /// </summary> public class Descriptor : CopyBase, IDescriptor { #region Constructors /// <summary> /// Creates a new instance of MatchableObject /// </summary> protected Descriptor() { } #endregion #region Methods /// <summary> /// For each of the publicly accessible properties found on this object, this attempts /// to copy a public property from the source object of the same name, if it can find it. /// For each matching property name/type, it will attempt to copy the value. /// </summary> /// <param name="source">The</param> public void CopyProperties(object source) { OnCopyProperties(source); } /// <summary> /// Compares the properties of this object with the specified IMatchable other. /// This does not test every property of other, but does test every property /// of this item. As long as the other item has corresponding properties /// for every property on this item, the items are said to match. /// The IMatchable interface allows custom definitions of matching. /// For collections to match, all of their sub-members must match. /// </summary> /// <param name="other"></param> /// <param name="mismatchedProperties"></param> /// <returns></returns> public bool Matches(IMatchable other, out List<string> mismatchedProperties) { mismatchedProperties = new List<string>(); return OnMatch(other, mismatchedProperties); } /// <summary> /// The default behavior is to cycle through all the properties of this /// object, and call Randomize on any that implement the IRandomizable interface. /// </summary> /// <param name="generator">The Random seed generator for controling how the random content is created</param> public void Randomize(Random generator) { OnRandomize(generator); } #endregion #region Protected Methods /// <summary> /// This occurs while copying properties from the specified source, and /// is the default handling for subclasses /// </summary> /// <param name="source"></param> protected virtual void OnCopyProperties(object source) { Type original = GetType(); Type copy = source.GetType(); PropertyInfo[] originalProperties = DistinctNames(original.GetProperties(BindingFlags.Public | BindingFlags.Instance)); PropertyInfo[] copyProperties = DistinctNames(copy.GetProperties(BindingFlags.Public | BindingFlags.Instance)); foreach (PropertyInfo originalProperty in originalProperties) { if (originalProperty.CanWrite == false) continue; if (copyProperties.Contains(originalProperty.Name) == false) continue; PropertyInfo copyProperty = copyProperties.GetFirst(originalProperty.Name); if (copyProperty == null) { // The name of the property was not found on the other object continue; } object copyValue = copyProperty.GetValue(source, null); if (copyProperty.GetCustomAttributes(typeof(ShallowCopy), true).Length == 0) { ICloneable cloneable = copyValue as ICloneable; if (cloneable != null) { originalProperty.SetValue(this, cloneable.Clone(), null); continue; } } // Use a shallow copy where ICloneable is not specifically defined. originalProperty.SetValue(this, copyValue, null); } // Public Fields --------------------------------------------------------- FieldInfo[] originalFields = original.GetFields(BindingFlags.Public | BindingFlags.Instance); FieldInfo[] copyFields = copy.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo originalField in originalFields) { FieldInfo copyField = copyFields.GetFirst(originalField.Name); if (copyFields.Contains(originalField.Name) == false) continue; if (copyField == null) { continue; } // If it can be cloned, clone it instead of using a reference copy object copyValue = copyField.GetValue(source); if (copyField.GetCustomAttributes(typeof(ShallowCopy), true).Length == 0) { ICloneable cloneable = copyValue as ICloneable; if (cloneable != null) { originalField.SetValue(this, cloneable.Clone()); continue; } } // Use a reference copy only when there is no other alternative. originalField.SetValue(this, copyValue); } } /// <summary> /// This gives sub-classes the chance to directly override, control or otherwise tamper /// with the matching process. This is also where normal matching is performed, /// so to replace it, simply don't call the base.OnMatch method. To tweak the results, /// the base method should be performed first, and the results can then be modified. /// </summary> /// <param name="other"></param> /// <param name="mismatchedProperties"></param> /// <returns></returns> protected virtual bool OnMatch(IMatchable other, List<string> mismatchedProperties) { Type original = GetType(); Type copy = other.GetType(); // Public Properties ------------------------------------------------------ PropertyInfo[] originalProperties = original.GetProperties(BindingFlags.Public | BindingFlags.Instance); PropertyInfo[] copyProperties = copy.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo originalProperty in originalProperties) { if (copyProperties.Contains(originalProperty.Name) == false) { mismatchedProperties.Add(originalProperty.Name); continue; } PropertyInfo copyProperty = copyProperties.GetFirst(originalProperty.Name); if (copyProperty == null) { // The name of the property was not found on the other object mismatchedProperties.Add(originalProperty.Name); continue; } object originalValue = originalProperty.GetValue(this, null); object copyValue = copyProperty.GetValue(other, null); if (Match(originalValue, copyValue) == false) { mismatchedProperties.Add(originalProperty.Name); } } // Public Fields --------------------------------------------------------- FieldInfo[] originalFields = original.GetFields(BindingFlags.Public | BindingFlags.Instance); FieldInfo[] copyFields = copy.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo originalField in originalFields) { if (copyFields.Contains(originalField.Name) == false) { mismatchedProperties.Add(originalField.Name); continue; } FieldInfo copyField = copyFields.GetFirst(originalField.Name); if (copyField == null) { mismatchedProperties.Add(originalField.Name); continue; } object originalValue = originalField.GetValue(this); object copyValue = copyField.GetValue(other); if (Match(originalValue, copyValue) == false) { mismatchedProperties.Add(originalField.Name); } } if (mismatchedProperties.Count > 0) { return false; } return true; } /// <summary> /// This allows overrideable behavior that can replace or extend the basic behavior, /// which is to call Randomize on any public properties that are listed as randomizeable. /// This does nothing to normal properties or non public members and needs to be overriden /// to provide the special case functionality for sub-classes. /// </summary> /// <param name="generator">The random number generator to be used during randomization</param> protected virtual void OnRandomize(Random generator) { Type original = GetType(); PropertyInfo[] originalProperties = original.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo originalProperty in originalProperties) { object prop = originalProperty.GetValue(this, null); IRandomizable rnd = prop as IRandomizable; if (rnd != null) { rnd.Randomize(generator); } } } #endregion #region Private Functions private static bool Match(object originalValue, object copyValue) { // If a custom IMatchable description exists use it to determine if there is a match IMatchable originalMatch = originalValue as IMatchable; IMatchable copyMatch = copyValue as IMatchable; if (originalMatch != null && copyMatch != null) { bool res = originalMatch.Matches(copyMatch); return res; } // Strings are enumerable, so test them first, since string.Equals should be faster than // cycling through each character. string origString = originalValue as string; if (origString != null) { string mString = copyValue as string; if (mString == null) return false; return origString.Equals(mString); } // If the object is an enumeration, test the members of the enumeration. // If any members fail the match test, then the whole collection fails the match. IEnumerable originalList = originalValue as IEnumerable; if (originalList != null) { IEnumerable copyList = copyValue as IEnumerable; if (copyList != null) { IEnumerator e = copyList.GetEnumerator(); e.MoveNext(); foreach (object originalItem in originalList) { if (Match(originalItem, e.Current) == false) { return false; } e.MoveNext(); } } return true; } if (originalValue == null && copyValue == null) return true; // If the objects are not collections and are not IMatchable, the only remaining thing we can // realistically test is simple equality. // Don't use == here! It will always be false for boxed value types. return originalValue != null && (originalValue.Equals(copyValue)); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using PygmentSharp.Core.Extensions; using PygmentSharp.Core.Utils; namespace PygmentSharp.Core.Lexing { /// <summary> /// Utility methods for working with regular expressions /// </summary> public static class RegexUtil { private static readonly string[] AllClasses = { "Cc", "Cf", "Cn", "Co", "Cs", "Ll", "Lm", "Lo", "Lt", "Lu", "Mc", "Me", "Mn", "Nd", "Nl", "No", "Pc", "Pd", "Pe", "Pf", "Pi", "Po", "Ps", "Sc", "Sk", "Sm", "So", "Zl", "Zp", "Zs" }; /// <summary> /// creates a regular expression match set that matches a character from unicode classes /// </summary> /// <param name="classes">The set of unicdeo classes to match characters from</param> /// <returns></returns> public static string Combine(params string[] classes) { return string.Join("", classes.Select(c => $@"\p{{{c}}}")); } /// <summary> /// Matches all characters except those in the provided unicode character classes /// </summary> /// <param name="classes">The unicode character classes to exclude</param> /// <returns></returns> public static string AllExcept(params string[] classes) { var passed = AllClasses.Where(c => !classes.Contains(c)).ToArray(); return Combine(passed); } private const string CharsetEscaper = @"[\^\\\-\]]"; /// <summary> /// Creates a character set that could match any of the characters in the string /// </summary> /// <remarks> /// For example: <c>"abc"</c> would become <c>"[abc]"</c> /// </remarks> /// <param name="letters">THe letters to be included in the character set</param> /// <returns>A regex string for the character set</returns> public static string MakeCharset(string letters) { return "[" + Regex.Replace(letters, CharsetEscaper, m => "\\" + m.Value) + "]"; } /// <summary> /// Creates a character set that could match any of the characters in the list /// </summary> /// <remarks> /// For example: <c>{ "a","b","c" }</c> would become <c>"[abc]"</c> /// </remarks> /// <param name="letters">THe letters to be included in the character set</param> /// <returns>A regex string for the character set</returns> public static string MakeCharset(params char[] letters) { return MakeCharset(new string(letters)); } /// <summary> /// Returns a regex that matches any string in a list /// </summary> /// <remarks> /// The strings to match must be literal strings -- they will be escaped. /// </remarks> /// <param name="strings">List of strings to match</param> /// <param name="prefix">a regex string to prepend</param> /// <param name="suffix">A regex string to append</param> /// <returns></returns> public static string OptimizedRegex(IEnumerable<string> strings, string prefix = "", string suffix = "") { var sorted = strings.OrderBy(s => s).ToArray(); return prefix + OptimizedRegexInner(sorted, "(") + suffix; } private static string OptimizedRegexInner(Slice<string> strings, string openParen) { var closeParen = openParen.PythonAnd(")").PythonOr(""); if (strings.Length == 0) return ""; var first = strings[0]; if (strings.Length == 1) return openParen + Escape(first) + closeParen; if (string.IsNullOrEmpty(first)) { //first string empty return openParen + OptimizedRegexInner(strings.SubSlice(1), "(?:") + "?" + closeParen; } if (first.Length == 1) { //multiple one-char strings? make a charset StringBuilder oneletter = new StringBuilder(); List<string> rest = new List<string>(); foreach (var s in strings) { if (s.Length == 1) oneletter.Append(s); else { rest.Add(s); } } if (oneletter.Length > 1) // do we have more than one oneletter string? { if (rest.Count > 0) { // 1-character + rest return openParen + OptimizedRegexInner(rest.ToArray(), "") + "|" + MakeCharset(oneletter.ToString()) + closeParen; } return MakeCharset(oneletter.ToString()); } } var prefix = CommonPrefix.Of(strings); if (prefix.Length > 0) { var plen = prefix.Length; // we have a prefix for all strings // print '-> prefix:', prefix return openParen + Escape(prefix) + OptimizedRegexInner(strings.Select(s => s.Substring(plen)).ToArray(), "(?:") + closeParen; } // is there a suffix? var stringsReversed = strings.Select(s => s.Backwards()).ToArray(); var suffix = CommonPrefix.Of(stringsReversed); if (suffix.Length > 0) { var slen = suffix.Length; return openParen + OptimizedRegexInner(strings.Select(s => s.Substring(s.Length - slen)).ToArray(), "(?:") + Escape(suffix.Backwards()) + closeParen; } //# recurse on common 1-string prefixes //# print '-> last resort' var groups = strings.GroupBy(s => s[0] == first[0]); return openParen + string.Join("|", groups.Select(g => OptimizedRegexInner(g.ToArray(), ""))) + closeParen; } private static string Escape(string s) { return Regex.Escape(s); } /// <summary> /// Creates an optimized regex that will match any of the listed words /// </summary> /// <param name="words"></param> /// <param name="prefix">A regex prefix to insert at the front of the optimized regex</param> /// <param name="suffix">A regex suffix to append at the end of the optimized regex</param> /// <returns></returns> public static string Words(string[] words, string prefix = "", string suffix = "") { return OptimizedRegex(words, prefix, suffix); } } }
namespace XenAdmin.SettingsPanels { partial class EditNetworkPage { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(EditNetworkPage)); this.HostNicLabel = new System.Windows.Forms.Label(); this.HostVLanLabel = new System.Windows.Forms.Label(); this.autoCheckBox = new System.Windows.Forms.CheckBox(); this.HostPNICList = new System.Windows.Forms.ComboBox(); this.numUpDownVLAN = new System.Windows.Forms.NumericUpDown(); this.nicHelpLabel = new System.Windows.Forms.Label(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.labelVLAN0Info = new System.Windows.Forms.Label(); this.panelLACPWarning = new System.Windows.Forms.Panel(); this.label2 = new System.Windows.Forms.Label(); this.pictureBox2 = new System.Windows.Forms.PictureBox(); this.labelBlurb = new System.Windows.Forms.Label(); this.panelDisruptionWarning = new System.Windows.Forms.Panel(); this.label1 = new System.Windows.Forms.Label(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.numericUpDownMTU = new System.Windows.Forms.NumericUpDown(); this.labelMTU = new System.Windows.Forms.Label(); this.warningText = new System.Windows.Forms.Label(); this.labelCannotConfigureMTU = new System.Windows.Forms.Label(); this.groupBoxBondMode = new System.Windows.Forms.GroupBox(); this.tableLayoutPanelBondMode = new System.Windows.Forms.TableLayoutPanel(); this.radioButtonLacpTcpudpPorts = new System.Windows.Forms.RadioButton(); this.radioButtonBalanceSlb = new System.Windows.Forms.RadioButton(); this.radioButtonActiveBackup = new System.Windows.Forms.RadioButton(); this.radioButtonLacpSrcMac = new System.Windows.Forms.RadioButton(); ((System.ComponentModel.ISupportInitialize)(this.numUpDownVLAN)).BeginInit(); this.tableLayoutPanel1.SuspendLayout(); this.panelLACPWarning.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit(); this.panelDisruptionWarning.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDownMTU)).BeginInit(); this.groupBoxBondMode.SuspendLayout(); this.tableLayoutPanelBondMode.SuspendLayout(); this.SuspendLayout(); // // HostNicLabel // resources.ApplyResources(this.HostNicLabel, "HostNicLabel"); this.HostNicLabel.Name = "HostNicLabel"; // // HostVLanLabel // resources.ApplyResources(this.HostVLanLabel, "HostVLanLabel"); this.HostVLanLabel.Name = "HostVLanLabel"; // // autoCheckBox // resources.ApplyResources(this.autoCheckBox, "autoCheckBox"); this.tableLayoutPanel1.SetColumnSpan(this.autoCheckBox, 4); this.autoCheckBox.Name = "autoCheckBox"; // // HostPNICList // this.tableLayoutPanel1.SetColumnSpan(this.HostPNICList, 3); this.HostPNICList.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; resources.ApplyResources(this.HostPNICList, "HostPNICList"); this.HostPNICList.FormattingEnabled = true; this.HostPNICList.Name = "HostPNICList"; this.HostPNICList.Sorted = true; this.HostPNICList.SelectedIndexChanged += new System.EventHandler(this.HostPNICList_SelectedIndexChanged); // // numUpDownVLAN // resources.ApplyResources(this.numUpDownVLAN, "numUpDownVLAN"); this.numUpDownVLAN.Maximum = new decimal(new int[] { 4094, 0, 0, 0}); this.numUpDownVLAN.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.numUpDownVLAN.Name = "numUpDownVLAN"; this.numUpDownVLAN.Value = new decimal(new int[] { 1, 0, 0, 0}); this.numUpDownVLAN.ValueChanged += new System.EventHandler(this.numUpDownVLAN_ValueChanged); // // nicHelpLabel // resources.ApplyResources(this.nicHelpLabel, "nicHelpLabel"); this.tableLayoutPanel1.SetColumnSpan(this.nicHelpLabel, 3); this.nicHelpLabel.ForeColor = System.Drawing.SystemColors.GrayText; this.nicHelpLabel.Name = "nicHelpLabel"; // // tableLayoutPanel1 // resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1"); this.tableLayoutPanel1.Controls.Add(this.labelVLAN0Info, 2, 3); this.tableLayoutPanel1.Controls.Add(this.panelLACPWarning, 0, 5); this.tableLayoutPanel1.Controls.Add(this.labelBlurb, 0, 0); this.tableLayoutPanel1.Controls.Add(this.numUpDownVLAN, 1, 3); this.tableLayoutPanel1.Controls.Add(this.nicHelpLabel, 1, 2); this.tableLayoutPanel1.Controls.Add(this.HostVLanLabel, 0, 3); this.tableLayoutPanel1.Controls.Add(this.HostNicLabel, 0, 1); this.tableLayoutPanel1.Controls.Add(this.HostPNICList, 1, 1); this.tableLayoutPanel1.Controls.Add(this.panelDisruptionWarning, 0, 11); this.tableLayoutPanel1.Controls.Add(this.numericUpDownMTU, 1, 6); this.tableLayoutPanel1.Controls.Add(this.labelMTU, 0, 6); this.tableLayoutPanel1.Controls.Add(this.autoCheckBox, 0, 8); this.tableLayoutPanel1.Controls.Add(this.warningText, 0, 9); this.tableLayoutPanel1.Controls.Add(this.labelCannotConfigureMTU, 0, 10); this.tableLayoutPanel1.Controls.Add(this.groupBoxBondMode, 0, 4); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; // // labelVLAN0Info // resources.ApplyResources(this.labelVLAN0Info, "labelVLAN0Info"); this.tableLayoutPanel1.SetColumnSpan(this.labelVLAN0Info, 2); this.labelVLAN0Info.Name = "labelVLAN0Info"; // // panelLACPWarning // resources.ApplyResources(this.panelLACPWarning, "panelLACPWarning"); this.tableLayoutPanel1.SetColumnSpan(this.panelLACPWarning, 4); this.panelLACPWarning.Controls.Add(this.label2); this.panelLACPWarning.Controls.Add(this.pictureBox2); this.panelLACPWarning.Name = "panelLACPWarning"; // // label2 // resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // pictureBox2 // resources.ApplyResources(this.pictureBox2, "pictureBox2"); this.pictureBox2.Image = global::XenAdmin.Properties.Resources._000_Alert2_h32bit_16; this.pictureBox2.Name = "pictureBox2"; this.pictureBox2.TabStop = false; // // labelBlurb // resources.ApplyResources(this.labelBlurb, "labelBlurb"); this.tableLayoutPanel1.SetColumnSpan(this.labelBlurb, 4); this.labelBlurb.Name = "labelBlurb"; // // panelDisruptionWarning // this.tableLayoutPanel1.SetColumnSpan(this.panelDisruptionWarning, 4); this.panelDisruptionWarning.Controls.Add(this.label1); this.panelDisruptionWarning.Controls.Add(this.pictureBox1); resources.ApplyResources(this.panelDisruptionWarning, "panelDisruptionWarning"); this.panelDisruptionWarning.Name = "panelDisruptionWarning"; // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // pictureBox1 // resources.ApplyResources(this.pictureBox1, "pictureBox1"); this.pictureBox1.Image = global::XenAdmin.Properties.Resources._000_Alert2_h32bit_16; this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.TabStop = false; // // numericUpDownMTU // resources.ApplyResources(this.numericUpDownMTU, "numericUpDownMTU"); this.numericUpDownMTU.Name = "numericUpDownMTU"; this.numericUpDownMTU.ValueChanged += new System.EventHandler(this.numericUpDownMTU_ValueChanged); // // labelMTU // resources.ApplyResources(this.labelMTU, "labelMTU"); this.labelMTU.Name = "labelMTU"; // // warningText // resources.ApplyResources(this.warningText, "warningText"); this.tableLayoutPanel1.SetColumnSpan(this.warningText, 4); this.warningText.Name = "warningText"; // // labelCannotConfigureMTU // resources.ApplyResources(this.labelCannotConfigureMTU, "labelCannotConfigureMTU"); this.tableLayoutPanel1.SetColumnSpan(this.labelCannotConfigureMTU, 4); this.labelCannotConfigureMTU.Name = "labelCannotConfigureMTU"; // // groupBoxBondMode // resources.ApplyResources(this.groupBoxBondMode, "groupBoxBondMode"); this.tableLayoutPanel1.SetColumnSpan(this.groupBoxBondMode, 3); this.groupBoxBondMode.Controls.Add(this.tableLayoutPanelBondMode); this.groupBoxBondMode.Name = "groupBoxBondMode"; this.groupBoxBondMode.TabStop = false; // // tableLayoutPanelBondMode // resources.ApplyResources(this.tableLayoutPanelBondMode, "tableLayoutPanelBondMode"); this.tableLayoutPanelBondMode.Controls.Add(this.radioButtonLacpTcpudpPorts, 0, 2); this.tableLayoutPanelBondMode.Controls.Add(this.radioButtonBalanceSlb, 0, 0); this.tableLayoutPanelBondMode.Controls.Add(this.radioButtonActiveBackup, 0, 1); this.tableLayoutPanelBondMode.Controls.Add(this.radioButtonLacpSrcMac, 0, 3); this.tableLayoutPanelBondMode.Name = "tableLayoutPanelBondMode"; // // radioButtonLacpTcpudpPorts // resources.ApplyResources(this.radioButtonLacpTcpudpPorts, "radioButtonLacpTcpudpPorts"); this.radioButtonLacpTcpudpPorts.Name = "radioButtonLacpTcpudpPorts"; this.radioButtonLacpTcpudpPorts.UseVisualStyleBackColor = true; this.radioButtonLacpTcpudpPorts.CheckedChanged += new System.EventHandler(this.BondMode_CheckedChanged); // // radioButtonBalanceSlb // resources.ApplyResources(this.radioButtonBalanceSlb, "radioButtonBalanceSlb"); this.radioButtonBalanceSlb.Name = "radioButtonBalanceSlb"; this.radioButtonBalanceSlb.TabStop = true; this.radioButtonBalanceSlb.UseVisualStyleBackColor = true; this.radioButtonBalanceSlb.CheckedChanged += new System.EventHandler(this.BondMode_CheckedChanged); // // radioButtonActiveBackup // resources.ApplyResources(this.radioButtonActiveBackup, "radioButtonActiveBackup"); this.radioButtonActiveBackup.Name = "radioButtonActiveBackup"; this.radioButtonActiveBackup.TabStop = true; this.radioButtonActiveBackup.UseVisualStyleBackColor = true; this.radioButtonActiveBackup.CheckedChanged += new System.EventHandler(this.BondMode_CheckedChanged); // // radioButtonLacpSrcMac // resources.ApplyResources(this.radioButtonLacpSrcMac, "radioButtonLacpSrcMac"); this.radioButtonLacpSrcMac.Name = "radioButtonLacpSrcMac"; this.radioButtonLacpSrcMac.UseVisualStyleBackColor = true; this.radioButtonLacpSrcMac.CheckedChanged += new System.EventHandler(this.BondMode_CheckedChanged); // // EditNetworkPage // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.BackColor = System.Drawing.Color.Transparent; this.Controls.Add(this.tableLayoutPanel1); this.DoubleBuffered = true; this.Name = "EditNetworkPage"; ((System.ComponentModel.ISupportInitialize)(this.numUpDownVLAN)).EndInit(); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.panelLACPWarning.ResumeLayout(false); this.panelLACPWarning.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit(); this.panelDisruptionWarning.ResumeLayout(false); this.panelDisruptionWarning.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDownMTU)).EndInit(); this.groupBoxBondMode.ResumeLayout(false); this.groupBoxBondMode.PerformLayout(); this.tableLayoutPanelBondMode.ResumeLayout(false); this.tableLayoutPanelBondMode.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Label HostNicLabel; private System.Windows.Forms.Label HostVLanLabel; private System.Windows.Forms.CheckBox autoCheckBox; private System.Windows.Forms.ComboBox HostPNICList; private System.Windows.Forms.NumericUpDown numUpDownVLAN; private System.Windows.Forms.Label nicHelpLabel; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.Label labelBlurb; private System.Windows.Forms.Label labelCannotConfigureMTU; private System.Windows.Forms.Label warningText; private System.Windows.Forms.NumericUpDown numericUpDownMTU; private System.Windows.Forms.Label labelMTU; private System.Windows.Forms.Panel panelDisruptionWarning; private System.Windows.Forms.Label label1; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.TableLayoutPanel tableLayoutPanelBondMode; private System.Windows.Forms.RadioButton radioButtonBalanceSlb; private System.Windows.Forms.RadioButton radioButtonActiveBackup; private System.Windows.Forms.RadioButton radioButtonLacpSrcMac; private System.Windows.Forms.RadioButton radioButtonLacpTcpudpPorts; private System.Windows.Forms.GroupBox groupBoxBondMode; private System.Windows.Forms.Panel panelLACPWarning; private System.Windows.Forms.Label label2; private System.Windows.Forms.PictureBox pictureBox2; private System.Windows.Forms.Label labelVLAN0Info; } }
#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.Collections.Generic; using System.Net.Mail; using System.IO; using System.Collections; using Contoso.Net.Mail; namespace Contoso.Patterns.UI.Forms.SmartFormContracts { /// <summary> /// IContract implementation that implements the ability to send a SmartForm-defined email. /// </summary> //+ dont like the mergetext function should just take a string and merge, like the one in POM public class EmailSmartFormContract : ISmartFormContract { private static object[] _defaultArgs = new object[] { null, string.Empty }; private IEmailSmartFormBodyBuilder _bodyBuilder; private SmtpClientEx _smtpClient; /// <summary> /// Initializes a new instance of the <see cref="SmartForm"/> class. /// </summary> public EmailSmartFormContract() : this(new EmailSmartFormBodyBuilder(), new SmtpClientEx()) { } /// <summary> /// Initializes a new instance of the <see cref="EmailSmartFormContract"/> class. /// </summary> /// <param name="bodyBuilder">The body builder.</param> public EmailSmartFormContract(IEmailSmartFormBodyBuilder bodyBuilder) : this(bodyBuilder, new SmtpClientEx()) { } /// <summary> /// Initializes a new instance of the <see cref="EmailSmartFormContract"/> class. /// </summary> /// <param name="smtpClient">The SMTP client.</param> public EmailSmartFormContract(SmtpClientEx smtpClient) : this(new EmailSmartFormBodyBuilder(), smtpClient) { } /// <summary> /// Initializes a new instance of the <see cref="EmailSmartFormContract"/> class. /// </summary> /// <param name="bodyBuilder">The body builder.</param> /// <param name="smtpClient">The SMTP client.</param> public EmailSmartFormContract(IEmailSmartFormBodyBuilder bodyBuilder, SmtpClientEx smtpClient) { if (bodyBuilder == null) throw new ArgumentNullException("bodyBuilder"); if (smtpClient == null) throw new ArgumentNullException("smtpClient"); _bodyBuilder = bodyBuilder; _smtpClient = smtpClient; EnsureSent = true; } /// <summary> /// Gets or sets a value indicating whether [ensure email sent]. /// </summary> /// <value> /// <c>true</c> if [ensure email sent]; otherwise, <c>false</c>. /// </value> public bool EnsureSent { get; set; } /// <summary> /// Executes the specified method. /// </summary> /// <param name="smartForm">The smart form.</param> /// <param name="method">The method.</param> /// <param name="args">The args.</param> /// <returns></returns> public object Execute(SmartForm smartForm, string method, params object[] args) { if (smartForm == null) throw new ArgumentNullException("smartForm"); if (args == null || args.Length == 0) args = _defaultArgs; // send email var emailsSent = 0; var usedToEmails = new List<string>(); for (var argIndex = 0; argIndex < args.Length; argIndex++) { var scopeKey = (args[argIndex] as string); if (scopeKey == null) throw new ArgumentNullException(string.Format("args[{0}]", argIndex)); if (scopeKey.Length > 0) scopeKey += "::"; foreach (var toEmail2 in smartForm[scopeKey + "toEmail"].Replace(";", ",").Split(',')) { var toEmail = toEmail2.Trim(); if (!string.IsNullOrEmpty(toEmail) && !usedToEmails.Contains(toEmail.ToLowerInvariant())) { var fromEmail = smartForm[scopeKey + "fromEmail"]; if (!string.IsNullOrEmpty(fromEmail)) { // execute var fromName = smartForm.CreateMergedText(scopeKey + "fromName"); var mailMessage = new MailMessage { From = (!string.IsNullOrEmpty(fromName) ? new MailAddress(fromEmail, fromName) : new MailAddress(fromEmail)), Subject = smartForm.CreateMergedText(scopeKey + "subject"), }; var replyToEmail = smartForm[scopeKey + "replyToEmail"]; if (!string.IsNullOrEmpty(replyToEmail)) { var replyToName = smartForm[scopeKey + "replyToName"]; #if CLR4 mailMessage.ReplyToList.Add(!string.IsNullOrEmpty(replyToName) ? new MailAddress(replyToEmail, replyToName) : new MailAddress(replyToEmail)); #else mailMessage.ReplyTo = (!string.IsNullOrEmpty(replyToName) ? new MailAddress(replyToEmail, replyToName) : new MailAddress(replyToEmail)); #endif } var toName = smartForm[scopeKey + "toName"]; mailMessage.To.Add(!string.IsNullOrEmpty(toName) ? new MailAddress(toEmail, toName) : new MailAddress(toEmail)); var ccEmail = smartForm[scopeKey + "ccEmail"]; if (!string.IsNullOrEmpty(ccEmail)) mailMessage.CC.Add(ccEmail.Replace(";", ",")); var bccEmail = smartForm[scopeKey + "bccEmail"]; if (!string.IsNullOrEmpty(bccEmail)) mailMessage.Bcc.Add(bccEmail.Replace(";", ",")); if (smartForm.ContainsKey(scopeKey + "attachments")) HandleAttachments(smartForm, scopeKey + "attachments", mailMessage); _bodyBuilder.Execute(smartForm, mailMessage, scopeKey); if (!smartForm.ContainsKey(scopeKey + "mhtmlBody")) _smtpClient.Send(mailMessage); else _smtpClient.SendMhtml(mailMessage); emailsSent++; } // prevent resends usedToEmails.Add(toEmail.ToLowerInvariant()); } } usedToEmails.Clear(); } if (EnsureSent && emailsSent == 0) throw new InvalidOperationException("EnsureSent"); return emailsSent; } private static void HandleAttachments(SmartForm smartForm, string key, MailMessage mailMessage) { var attachments = smartForm.Get(key); if (attachments == null) return; // String var attachmentsAsString = (attachments as string); if (!string.IsNullOrEmpty(attachmentsAsString)) { foreach (var attachment2 in attachmentsAsString.Split(';')) if (!string.IsNullOrEmpty(attachment2) && File.Exists(attachment2)) mailMessage.Attachments.Add(new Attachment(attachment2)); return; } // IEnumerable<string> var attachmentsAsEnumerable = (attachments as IEnumerable<string>); if (attachmentsAsEnumerable != null) { foreach (var attachment2 in attachmentsAsEnumerable) if (!string.IsNullOrEmpty(attachment2) && File.Exists(attachment2)) mailMessage.Attachments.Add(new Attachment(attachment2)); return; } // Attachment var attachment = (attachments as Attachment); if (attachment != null) { mailMessage.Attachments.Add(attachment); return; } // IEnumerable<Attachment> var attachmentsAsEnumerable2 = (attachments as IEnumerable<Attachment>); if (attachmentsAsEnumerable2 != null) { foreach (var attachment2 in attachmentsAsEnumerable2) mailMessage.Attachments.Add(attachment2); return; } } } }
// 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. using System; using System.Reflection; using System.Diagnostics.Contracts; namespace System { public class AppDomain { public string RelativeSearchPath { get; } public AppDomainSetup SetupInformation { get; } public string FriendlyName { get; } public string BaseDirectory { get; } public System.Security.Policy.Evidence Evidence { get; } public bool ShadowCopyFiles { get; } public string DynamicDirectory { get; } public static AppDomain! CurrentDomain { get; } public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Object[] args, System.Globalization.CultureInfo culture, Object[] activationAttributes, System.Security.Policy.Evidence securityAttributes) { return default(object); } public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, Object[] activationAttributes) { return default(object); } public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName) { return default(object); } public object CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Object[] args, System.Globalization.CultureInfo culture, Object[] activationAttributes, System.Security.Policy.Evidence securityAttributes) { return default(object); } public object CreateInstanceAndUnwrap (string assemblyName, string typeName, Object[] activationAttributes) { return default(object); } public object CreateInstanceAndUnwrap (string assemblyName, string typeName) { return default(object); } public void SetDynamicBase (string path) { } public void SetShadowCopyFiles () { } public void SetShadowCopyPath (string path) { } public static AppDomain CreateDomain (string! friendlyName, System.Security.Policy.Evidence securityInfo, AppDomainSetup info) { CodeContract.Requires(friendlyName != null); return default(AppDomain); } public static AppDomain CreateDomain (string friendlyName) { return default(AppDomain); } public static AppDomain CreateDomain (string friendlyName, System.Security.Policy.Evidence securityInfo, string appBasePath, string appRelativeSearchPath, bool shadowCopyFiles) { return default(AppDomain); } public static AppDomain CreateDomain (string friendlyName, System.Security.Policy.Evidence securityInfo) { return default(AppDomain); } public void DoCallBack (CrossAppDomainDelegate! callBackDelegate) { CodeContract.Requires(callBackDelegate != null); } public object InitializeLifetimeService () { return default(object); } public void SetPrincipalPolicy (System.Security.Principal.PrincipalPolicy policy) { } public void SetThreadPrincipal (System.Security.Principal.IPrincipal! principal) { CodeContract.Requires(principal != null); } public void SetAppDomainPolicy (System.Security.Policy.PolicyLevel! domainPolicy) { CodeContract.Requires(domainPolicy != null); } public static void Unload (AppDomain! domain) { CodeContract.Requires(domain != null); } public static int GetCurrentThreadId () { return default(int); } public object GetData (string! name) { CodeContract.Requires(name != null); return default(object); } public void SetData (string! name, object data) { CodeContract.Requires(name != null); } public void SetCachePath (string path) { } public void ClearShadowCopyPath () { } public void ClearPrivatePath () { } public void AppendPrivatePath (string path) { } public bool IsFinalizingForUnload () { return default(bool); } public System.Reflection.Assembly[] GetAssemblies () { CodeContract.Ensures(CodeContract.Result<System.Reflection.Assembly[]>() != null); return default(System.Reflection.Assembly[]); } [Pure][Reads(ReadsAttribute.Reads.Owned)] public string ToString () { CodeContract.Ensures(CodeContract.Result<string>() != null); return default(string); } public int ExecuteAssembly (string assemblyFile, System.Security.Policy.Evidence assemblySecurity, String[] args, Byte[] hashValue, System.Configuration.Assemblies.AssemblyHashAlgorithm hashAlgorithm) { return default(int); } public int ExecuteAssembly (string assemblyFile, System.Security.Policy.Evidence assemblySecurity, String[] args) { return default(int); } public int ExecuteAssembly (string assemblyFile) { return default(int); } public int ExecuteAssembly (string assemblyFile, System.Security.Policy.Evidence assemblySecurity) { return default(int); } public System.Reflection.Assembly Load (string assemblyString, System.Security.Policy.Evidence assemblySecurity) { return default(System.Reflection.Assembly); } public System.Reflection.Assembly Load (System.Reflection.AssemblyName assemblyRef, System.Security.Policy.Evidence assemblySecurity) { return default(System.Reflection.Assembly); } public System.Reflection.Assembly Load (Byte[] rawAssembly, Byte[] rawSymbolStore, System.Security.Policy.Evidence securityEvidence) { return default(System.Reflection.Assembly); } public System.Reflection.Assembly Load (Byte[] rawAssembly, Byte[] rawSymbolStore) { return default(System.Reflection.Assembly); } public System.Reflection.Assembly Load (Byte[] rawAssembly) { return default(System.Reflection.Assembly); } public System.Reflection.Assembly Load (string assemblyString) { return default(System.Reflection.Assembly); } public System.Reflection.Assembly Load (System.Reflection.AssemblyName assemblyRef) { return default(System.Reflection.Assembly); } public System.Runtime.Remoting.ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Object[] args, System.Globalization.CultureInfo culture, Object[] activationAttributes, System.Security.Policy.Evidence securityAttributes) { CodeContract.Requires(this != null); return default(System.Runtime.Remoting.ObjectHandle); } public System.Runtime.Remoting.ObjectHandle CreateInstance (string! assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Object[] args, System.Globalization.CultureInfo culture, Object[] activationAttributes, System.Security.Policy.Evidence securityAttributes) { CodeContract.Requires(this != null); CodeContract.Requires(assemblyName != null); return default(System.Runtime.Remoting.ObjectHandle); } public System.Runtime.Remoting.ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, Object[] activationAttributes) { CodeContract.Requires(this != null); return default(System.Runtime.Remoting.ObjectHandle); } public System.Runtime.Remoting.ObjectHandle CreateInstance (string! assemblyName, string typeName, Object[] activationAttributes) { CodeContract.Requires(this != null); CodeContract.Requires(assemblyName != null); return default(System.Runtime.Remoting.ObjectHandle); } public System.Runtime.Remoting.ObjectHandle CreateComInstanceFrom (string! assemblyFile, string typeName, Byte[] hashValue, System.Configuration.Assemblies.AssemblyHashAlgorithm hashAlgorithm) { CodeContract.Requires(this != null); CodeContract.Requires(assemblyFile != null); return default(System.Runtime.Remoting.ObjectHandle); } public System.Runtime.Remoting.ObjectHandle CreateComInstanceFrom (string! assemblyName, string typeName) { CodeContract.Requires(this != null); CodeContract.Requires(assemblyName != null); return default(System.Runtime.Remoting.ObjectHandle); } public System.Runtime.Remoting.ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName) { CodeContract.Requires(this != null); return default(System.Runtime.Remoting.ObjectHandle); } public System.Runtime.Remoting.ObjectHandle CreateInstance (string! assemblyName, string typeName) { CodeContract.Requires(this != null); CodeContract.Requires(assemblyName != null); return default(System.Runtime.Remoting.ObjectHandle); } public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, System.Security.Policy.Evidence evidence, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions, bool isSynchronized) { return default(System.Reflection.Emit.AssemblyBuilder); } public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, System.Security.Policy.Evidence evidence, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions) { return default(System.Reflection.Emit.AssemblyBuilder); } public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, System.Security.Policy.Evidence evidence, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions) { return default(System.Reflection.Emit.AssemblyBuilder); } public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions) { return default(System.Reflection.Emit.AssemblyBuilder); } public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, System.Security.Policy.Evidence evidence) { return default(System.Reflection.Emit.AssemblyBuilder); } public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions) { return default(System.Reflection.Emit.AssemblyBuilder); } public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, System.Security.Policy.Evidence evidence) { return default(System.Reflection.Emit.AssemblyBuilder); } public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir) { return default(System.Reflection.Emit.AssemblyBuilder); } public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access) { return default(System.Reflection.Emit.AssemblyBuilder); } [Pure][Reads(ReadsAttribute.Reads.Nothing)][ResultNotNewlyAllocated] public Type GetType () { return default(Type); } public void remove_UnhandledException (UnhandledExceptionEventHandler value) { } public void add_UnhandledException (UnhandledExceptionEventHandler value) { } public void remove_AssemblyResolve (ResolveEventHandler value) { } public void add_AssemblyResolve (ResolveEventHandler value) { } public void remove_ResourceResolve (ResolveEventHandler value) { } public void add_ResourceResolve (ResolveEventHandler value) { } public void remove_TypeResolve (ResolveEventHandler value) { } public void add_TypeResolve (ResolveEventHandler value) { } public void remove_ProcessExit (EventHandler value) { } public void add_ProcessExit (EventHandler value) { } public void remove_AssemblyLoad (AssemblyLoadEventHandler value) { } public void add_AssemblyLoad (AssemblyLoadEventHandler value) { } public void remove_DomainUnload (EventHandler value) { } public void add_DomainUnload (EventHandler value) { } } }
// * ************************************************************************** // * Copyright (c) McCreary, Veselka, Bragg & Allen, P.C. // * This source code is subject to terms and conditions of the MIT License. // * A copy of the license can be found in the License.txt file // * at the root of this distribution. // * By using this source code in any fashion, you are agreeing to be bound by // * the terms of the MIT License. // * You must not remove this notice from this software. // * ************************************************************************** using System; using System.ComponentModel; using System.Linq; using FluentAssert; using JetBrains.Annotations; using MvbaCore.CodeQuery; using NUnit.Framework; namespace MvbaCore.Tests.CodeQuery { [UsedImplicitly] public class PropertyInfoExtensionsTests { [TestFixture] public class When_asked_if_there_are_any_custom_Attributes_of_a_specific_type_for_a_PropertyInfo { [Test] public void Should_return_False_if_there_are_no_matching_attributes() { // ReSharper disable once AssignNullToNotNullAttribute var hasAttributeOfType = typeof(TestClass).GetProperty("Id").HasAttributeOfType<TestAttribute>(); hasAttributeOfType.ShouldBeFalse(); } [Test] public void Should_return_True_if_there_are_matching_attributes() { // ReSharper disable once AssignNullToNotNullAttribute var hasAttributeOfType = typeof(TestClass).GetProperty("Id").HasAttributeOfType<ReadOnlyAttribute>(); hasAttributeOfType.ShouldBeTrue(); } public class TestClass { [ReadOnly(true)] // ReSharper disable once UnusedAutoPropertyAccessor.Local public int Id { get; private set; } } } [TestFixture] public class When_asked_to_get_PropertyInfos_that_have_a_getter { [Test] public void Should_get_an_empty_container_if_there_are_no_matching_PropertyInfos() { var propertyInfos = typeof(NoGettersTestClass).GetProperties().ThatHaveAGetter().ToList(); propertyInfos.ShouldNotBeNull(); propertyInfos.Count.ShouldBeEqualTo(0); } [Test] public void Should_get_the_matching_PropertyInfos() { var propertyInfos = typeof(TestClass).GetProperties().ThatHaveAGetter().ToList(); propertyInfos.Count.ShouldBeEqualTo(1); propertyInfos.First().Name.ShouldBeEqualTo("Id"); } public class NoGettersTestClass { public int Id { set { throw new NotImplementedException(); } } } public class TestClass { public int Id { get { throw new NotImplementedException(); } } // ReSharper disable once UnusedMember.Local private string Name { get; set; } } } [TestFixture] public class When_asked_to_get_PropertyInfos_that_have_a_setter { [Test] public void Should_get_an_empty_container_if_there_are_no_matching_PropertyInfos() { var propertyInfos = typeof(NoSettersTestClass).GetProperties().ThatHaveASetter().ToList(); propertyInfos.ShouldNotBeNull(); propertyInfos.Count.ShouldBeEqualTo(0); } [Test] public void Should_get_the_matching_PropertyInfos() { var propertyInfos = typeof(TestClass).GetProperties().ThatHaveASetter().ToList(); propertyInfos.Count.ShouldBeEqualTo(1); propertyInfos.First().Name.ShouldBeEqualTo("Id"); } public class NoSettersTestClass { public int Id { get { throw new NotImplementedException(); } } } public class TestClass { public int Id { set { throw new NotImplementedException(); } } // ReSharper disable once UnusedMember.Local private string Name { get; set; } } } [TestFixture] public class When_asked_to_get_PropertyInfos_that_have_custom_Attributes_of_a_specific_type { [Test] public void Should_get_an_empty_container_if_there_are_no_matching_PropertyInfos() { var propertyInfos = typeof(TestClass).GetProperties().WithAttributeOfType<TestAttribute>().ToList(); propertyInfos.ShouldNotBeNull(); propertyInfos.Count.ShouldBeEqualTo(0); } [Test] public void Should_get_the_matching_PropertyInfos() { var propertyInfos = typeof(TestClass).GetProperties().WithAttributeOfType<ReadOnlyAttribute>().ToList(); propertyInfos.Count.ShouldBeEqualTo(1); propertyInfos.First().Name.ShouldBeEqualTo("Id"); } public class TestClass { [ReadOnly(true)] // ReSharper disable once UnusedAutoPropertyAccessor.Local public int Id { get; private set; } public string Name { get; set; } } } [TestFixture] public class When_asked_to_get_custom_Attributes_of_a_specific_type_for_a_PropertyInfo { [Test] public void Should_get_the_matching_Attributes() { // ReSharper disable once AssignNullToNotNullAttribute var attributes = typeof(TestClass).GetProperty("Id").CustomAttributesOfType<ReadOnlyAttribute>(); attributes.Count().ShouldBeEqualTo(1); } [Test] public void Should_return_an_empty_container_if_there_are_no_matching_Attributes() { // ReSharper disable once AssignNullToNotNullAttribute var attributes = typeof(TestClass).GetProperty("Id").CustomAttributesOfType<TestAttribute>().ToList(); attributes.ShouldNotBeNull(); attributes.Count.ShouldBeEqualTo(0); } public class TestClass { [ReadOnly(true)] // ReSharper disable once UnusedAutoPropertyAccessor.Local public int Id { get; private set; } } } [TestFixture] public class When_asked_to_get_the_custom_Attributes_for_a_PropertyInfo { [Test] public void Should_get_the_Attributes() { // ReSharper disable once AssignNullToNotNullAttribute var attributes = typeof(TestClass).GetProperty("Id").CustomAttributes().ToList(); attributes.Count.ShouldBeEqualTo(1); attributes.First().ShouldBeOfType<ReadOnlyAttribute>(); } public class TestClass { [ReadOnly(true)] // ReSharper disable once UnusedAutoPropertyAccessor.Local public int Id { get; private set; } } } } }