context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// <copyright file=ReflectionUtils company=Hydra> // Copyright (c) 2015 All Rights Reserved // </copyright> // <author>Christopher Cameron</author> using System; using System.Collections.Generic; using System.Reflection; namespace Hydra.HydraCommon.Utils { /// <summary> /// Reflection utility methods. /// </summary> public static class ReflectionUtils { /// <summary> /// Gets the subclasses of the given type. /// </summary> /// <param name="output">Output.</param> /// <param name="type">Type.</param> public static void GetSubclasses(List<Type> output, Type type) { Type[] assemblyTypes = Assembly.GetAssembly(type).GetTypes(); for (int index = 0; index < assemblyTypes.Length; index++) { Type subType = assemblyTypes[index]; if (subType != type && type.IsAssignableFrom(subType)) output.Add(subType); } } /// <summary> /// Gets all items flags. /// </summary> /// <returns>The all items flags.</returns> public static BindingFlags GetAllItemsFlags() { return BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly; } /// <summary> /// Gets all fields in a given type. /// </summary> /// <returns>The fields.</returns> /// <param name="type">Object type.</param> public static FieldInfo[] GetAllFields(Type type) { if (type == null) return new FieldInfo[0]; BindingFlags flags = GetAllItemsFlags(); FieldInfo[] fields = type.GetFields(flags); FieldInfo[] baseFields = GetAllFields(type.BaseType); ArrayUtils.AddRange(ref fields, baseFields); return fields; } /// <summary> /// Gets all properties in a given type. /// </summary> /// <returns>The properties.</returns> /// <param name="type">Object type.</param> public static PropertyInfo[] GetAllProperties(Type type) { if (type == null) return new PropertyInfo[0]; BindingFlags flags = GetAllItemsFlags(); PropertyInfo[] properties = type.GetProperties(flags); PropertyInfo[] baseProperties = GetAllProperties(type.BaseType); ArrayUtils.AddRange(ref properties, baseProperties); return properties; } /// <summary> /// Gets all methods in a given type. /// </summary> /// <returns>The methods.</returns> /// <param name="type">Type.</param> public static MethodInfo[] GetAllMethods(Type type) { if (type == null) return new MethodInfo[0]; BindingFlags flags = GetAllItemsFlags(); MethodInfo[] methods = type.GetMethods(flags); MethodInfo[] baseMethods = GetAllMethods(type.BaseType); ArrayUtils.AddRange(ref methods, baseMethods); return methods; } /// <summary> /// Gets all constructors. /// </summary> /// <returns>The constructors.</returns> /// <param name="type">Type.</param> public static ConstructorInfo[] GetAllConstructors(Type type) { if (type == null) return new ConstructorInfo[0]; BindingFlags flags = GetAllItemsFlags(); return type.GetConstructors(flags); } /// <summary> /// Gets the type with the given name. /// </summary> /// <returns>The type.</returns> /// <param name="assembly">Assembly.</param> /// <param name="name">Name.</param> public static Type GetTypeByName(Assembly assembly, string name) { Type[] types = assembly.GetTypes(); for (int index = 0; index < types.Length; index++) { Type type = types[index]; if (type.Name == name) return type; } return null; } /// <summary> /// Returns the field with the matching name. /// </summary> /// <returns>The field.</returns> /// <param name="objectType">Object type.</param> /// <param name="fieldName">Field name.</param> public static FieldInfo GetFieldByName(Type objectType, string fieldName) { FieldInfo[] fields = GetAllFields(objectType); for (int index = 0; index < fields.Length; index++) { FieldInfo field = fields[index]; if (field.Name == fieldName) return field; } return null; } /// <summary> /// Returns the property with the matching name. /// </summary> /// <returns>The property.</returns> /// <param name="objectType">Object type.</param> /// <param name="propertyName">Property name.</param> public static PropertyInfo GetPropertyByName(Type objectType, string propertyName) { PropertyInfo[] properties = GetAllProperties(objectType); for (int index = 0; index < properties.Length; index++) { PropertyInfo property = properties[index]; if (property.Name == propertyName) return property; } return null; } /// <summary> /// Returns the method with the matching name. /// </summary> /// <returns>The method.</returns> /// <param name="objectType">Object type.</param> /// <param name="methodName">Method name.</param> public static MethodInfo GetMethodByName(Type objectType, string methodName) { MethodInfo[] methods = GetAllMethods(objectType); for (int index = 0; index < methods.Length; index++) { MethodInfo method = methods[index]; if (method.Name == methodName) return method; } return null; } /// <summary> /// Gets the source field value. /// </summary> /// <returns>The source field value.</returns> /// <param name="source">Source.</param> /// <param name="fieldName">Field name.</param> public static object GetSourceFieldValue(object source, string fieldName) { if (source == null) return null; Type type = source.GetType(); FieldInfo f = GetFieldByName(type, fieldName); if (f == null) return null; return f.GetValue(source); } /// <summary> /// Gets the source field value. /// </summary> /// <returns>The source field value.</returns> /// <param name="source">Source.</param> /// <param name="fieldName">Field name.</param> /// <param name="index">Index.</param> public static object GetSourceFieldValue(object source, string fieldName, int index) { object sourceFieldValue = GetSourceFieldValue(source, fieldName); if (sourceFieldValue is Array) { object[] array = sourceFieldValue as object[]; return array[index]; } throw new FieldAccessException(); } /// <summary> /// Returns true if the toCheck type is a subclass of the generic type. /// </summary> /// <returns>Returns true if the toCheck type is a subclass of the generic type.</returns> /// <param name="generic">Generic.</param> /// <param name="toCheck">To check.</param> public static bool IsSubclassOfRawGeneric(Type generic, Type toCheck) { while (toCheck != null && toCheck != typeof(object)) { Type current = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck; if (generic == current) return true; toCheck = toCheck.BaseType; } return false; } } }
/* * Licensed to the Apache Software Foundation (ASF) Under one or more * contributor license agreements. See the NOTICE file distributed with * this work for Additional information regarding copyright ownership. * The ASF licenses this file to You Under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed Under the License is distributed on an "AS Is" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations Under the License. */ namespace NPOI.SS.Formula.Functions { using System; using NPOI.SS.Formula.Eval; using NPOI.SS.Formula.Functions; using NPOI.SS.Formula; public class SingleValueVector : ValueVector { private ValueEval _value; public SingleValueVector(ValueEval value) { _value = value; } public ValueEval GetItem(int index) { if (index != 0) { throw new ArgumentException("Invalid index (" + index + ") only zero is allowed"); } return _value; } public int Size { get { return 1; } } } /** * Implementation for the MATCH() Excel function.<p/> * * <b>Syntax:</b><br/> * <b>MATCH</b>(<b>lookup_value</b>, <b>lookup_array</b>, match_type)<p/> * * Returns a 1-based index specifying at what position in the <b>lookup_array</b> the specified * <b>lookup_value</b> Is found.<p/> * * Specific matching behaviour can be modified with the optional <b>match_type</b> parameter. * * <table border="0" cellpAdding="1" cellspacing="0" summary="match_type parameter description"> * <tr><th>Value</th><th>Matching Behaviour</th></tr> * <tr><td>1</td><td>(default) Find the largest value that Is less than or equal to lookup_value. * The lookup_array must be in ascending <i>order</i>*.</td></tr> * <tr><td>0</td><td>Find the first value that Is exactly equal to lookup_value. * The lookup_array can be in any order.</td></tr> * <tr><td>-1</td><td>Find the smallest value that Is greater than or equal to lookup_value. * The lookup_array must be in descending <i>order</i>*.</td></tr> * </table> * * * Note regarding <i>order</i> - For the <b>match_type</b> cases that require the lookup_array to * be ordered, MATCH() can produce incorrect results if this requirement Is not met. Observed * behaviour in Excel Is to return the lowest index value for which every item after that index * breaks the match rule.<br/> * The (ascending) sort order expected by MATCH() Is:<br/> * numbers (low to high), strings (A to Z), bool (FALSE to TRUE)<br/> * MATCH() ignores all elements in the lookup_array with a different type to the lookup_value. * Type conversion of the lookup_array elements Is never performed. * * * @author Josh Micich */ public class Match : Function { public ValueEval Evaluate(ValueEval[] args, int srcCellRow, int srcCellCol) { double match_type = 1; // default switch (args.Length) { case 3: try { match_type = EvaluateMatchTypeArg(args[2], srcCellRow, srcCellCol); } catch (EvaluationException) { // Excel/MATCH() seems to have slightly abnormal handling of errors with // the last parameter. Errors do not propagate up. Every error Gets // translated into #REF! return ErrorEval.REF_INVALID; } break; case 2: break; default: return ErrorEval.VALUE_INVALID; } bool matchExact = match_type == 0; // Note - Excel does not strictly require -1 and +1 bool FindLargestLessThanOrEqual = match_type > 0; try { ValueEval lookupValue = OperandResolver.GetSingleValue(args[0], srcCellRow, srcCellCol); ValueVector lookupRange = EvaluateLookupRange(args[1]); int index = FindIndexOfValue(lookupValue, lookupRange, matchExact, FindLargestLessThanOrEqual); return new NumberEval(index + 1); // +1 to Convert to 1-based } catch (EvaluationException e) { return e.GetErrorEval(); } } private static ValueVector EvaluateLookupRange(ValueEval eval) { if (eval is RefEval) { RefEval re = (RefEval)eval; return new SingleValueVector(re.InnerValueEval); } if (eval is TwoDEval) { ValueVector result = LookupUtils.CreateVector((TwoDEval)eval); if (result == null) { throw new EvaluationException(ErrorEval.NA); } return result; } // Error handling for lookup_range arg Is also Unusual if (eval is NumericValueEval) { throw new EvaluationException(ErrorEval.NA); } if (eval is StringEval) { StringEval se = (StringEval)eval; double d = OperandResolver.ParseDouble(se.StringValue); if (double.IsNaN(d)) { // plain string throw new EvaluationException(ErrorEval.VALUE_INVALID); } // else looks like a number throw new EvaluationException(ErrorEval.NA); } throw new Exception("Unexpected eval type (" + eval.GetType().Name + ")"); } private static double EvaluateMatchTypeArg(ValueEval arg, int srcCellRow, int srcCellCol) { ValueEval match_type = OperandResolver.GetSingleValue(arg, srcCellRow, srcCellCol); if (match_type is ErrorEval) { throw new EvaluationException((ErrorEval)match_type); } if (match_type is NumericValueEval) { NumericValueEval ne = (NumericValueEval)match_type; return ne.NumberValue; } if (match_type is StringEval) { StringEval se = (StringEval)match_type; double d = OperandResolver.ParseDouble(se.StringValue); if (double.IsNaN(d)) { // plain string throw new EvaluationException(ErrorEval.VALUE_INVALID); } // if the string Parses as a number, it Is OK return d; } throw new Exception("Unexpected match_type type (" + match_type.GetType().Name + ")"); } /** * @return zero based index */ private static int FindIndexOfValue(ValueEval lookupValue, ValueVector lookupRange, bool matchExact, bool FindLargestLessThanOrEqual) { LookupValueComparer lookupComparer = CreateLookupComparer(lookupValue, matchExact); if (matchExact) { for (int i = 0; i < lookupRange.Size; i++) { if (lookupComparer.CompareTo(lookupRange.GetItem(i)).IsEqual) { return i; } } throw new EvaluationException(ErrorEval.NA); } if (FindLargestLessThanOrEqual) { // Note - backward iteration for (int i = lookupRange.Size - 1; i >= 0; i--) { CompareResult cmp = lookupComparer.CompareTo(lookupRange.GetItem(i)); if (cmp.IsTypeMismatch) { continue; } if (!cmp.IsLessThan) { return i; } } throw new EvaluationException(ErrorEval.NA); } // else - Find smallest greater than or equal to // TODO - Is binary search used for (match_type==+1) ? for (int i = 0; i < lookupRange.Size; i++) { CompareResult cmp = lookupComparer.CompareTo(lookupRange.GetItem(i)); if (cmp.IsEqual) { return i; } if (cmp.IsGreaterThan) { if (i < 1) { throw new EvaluationException(ErrorEval.NA); } return i - 1; } } throw new EvaluationException(ErrorEval.NA); } private static LookupValueComparer CreateLookupComparer(ValueEval lookupValue, bool matchExact) { return LookupUtils.CreateLookupComparer(lookupValue, matchExact, true); } private static bool IsLookupValueWild(String stringValue) { if (stringValue.IndexOf('?') >= 0 || stringValue.IndexOf('*') >= 0) { return true; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; using TestLibrary; using System.Globalization; class StringBuilderAppend { static int Main() { StringBuilderAppend test = new StringBuilderAppend(); TestFramework.BeginTestCase("StringBuilder.Append"); if (test.RunTests()) { TestFramework.EndTestCase(); TestFramework.LogInformation("PASS"); return 100; } else { TestFramework.EndTestCase(); TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool ret = true; // Positive Tests ret &= Test001(); ret &= Test002(); ret &= Test003(); ret &= Test004(); ret &= Test005(); ret &= Test019(); ret &= Test021(); ret &= Test022(); ret &= Test023(); ret &= Test010(); ret &= Test011(); ret &= Test012(); ret &= Test013(); ret &= Test014(); ret &= Test020(); ret &= Test024(); ret &= Test025(); ret &= Test026(); ret &= Test027(); ret &= Test028(); ret &= Test029(); ret &= Test030(); ret &= Test031(); ret &= Test032(); ret &= Test033(); ret &= Test034(); ret &= Test035(); ret &= Test036(); ret &= Test037(); ret &= Test038(); ret &= Test039(); ret &= Test040(); ret &= Test041(); ret &= Test042(); // Negative Tests ret &= Test006(); ret &= Test007(); ret &= Test008(); ret &= Test009(); ret &= Test015(); ret &= Test016(); ret &= Test017(); ret &= Test018(); return ret; } public bool Test001() { return PositiveTest("Testing", 1, 6, "esting", "00A");} public bool Test002() { return PositiveTest(new string('a', 5000), 0, 5000, new string('a',5000), "00B");} public bool Test003() { return PositiveTest("Testing", 1, 0, string.Empty, "00C");} public bool Test004() { return PositiveTest(null, 0, 0, string.Empty, "00D");} public bool Test005() { return PositiveTest(string.Empty, 0, 0, string.Empty, "00E");} public bool Test019() { return NegativeTest("Testing", -5, 0, typeof(ArgumentOutOfRangeException), "00J"); } public bool Test006() { return NegativeTest(null, 0, 1, typeof(ArgumentNullException), "00F"); } public bool Test007() { return NegativeTest("a", -1, 1, typeof(ArgumentOutOfRangeException), "00G"); } public bool Test008() { return NegativeTest("a", 0, -1, typeof(ArgumentOutOfRangeException), "00H"); } public bool Test009() { return NegativeTest("a", 0, 3, typeof(ArgumentOutOfRangeException), "00I"); } public bool Test010() { return PositiveTest2(new char[] {'T', 'e', 's', 't', 'i', 'n', 'g'}, 1, 6, "esting", "00A1"); } public bool Test011() { char[] chars = new char[5000]; for (int i = 0; i < 5000; i++) chars[i] = 'a'; return PositiveTest2(chars, 0, 5000, new string('a', 5000), "00B1"); } public bool Test012() { return PositiveTest2(new char[] {'T', 'e', 's', 't', 'i', 'n', 'g'}, 1, 0, string.Empty, "00C1"); } public bool Test013() { return PositiveTest2(null, 0, 0, string.Empty, "00D1"); } public bool Test014() { return PositiveTest2(new char[] { }, 0, 0, string.Empty, "00E1"); } public bool Test020() { return NegativeTest2(new char[] { 'T', 'e', 's', 't', 'i', 'n', 'g' }, -5, 0, typeof(ArgumentOutOfRangeException), "00J1"); } public bool Test015() { return NegativeTest2(null, 0, 1, typeof(ArgumentNullException), "00F1"); } public bool Test016() { return NegativeTest2(new char[] { 'T', 'e', 's', 't', 'i', 'n', 'g' }, - 1, 1, typeof(ArgumentOutOfRangeException), "00G1"); } public bool Test017() { return NegativeTest2(new char[] { 'T', 'e', 's', 't', 'i', 'n', 'g' }, 0, -1, typeof(ArgumentOutOfRangeException), "00H1"); } public bool Test018() { return NegativeTest2(new char[] { 'T' }, 0, 3, typeof(ArgumentOutOfRangeException), "00I1"); } public bool Test021() { return PositiveTest3('T', 6, "TTTTTT", "00A2"); } public bool Test022() { return PositiveTest3('a', 5000, new string('a', 5000), "00B2"); } public bool Test023() { return PositiveTest3('a', 0, string.Empty, "00C2"); } public bool Test024() { return NegativeTest3('a', -1, typeof(ArgumentOutOfRangeException), "00G2"); } public bool Test025() { return PositiveTest4<byte>(1, "00K"); } public bool Test026() { return PositiveTest4<sbyte>(-1, "00L"); } public bool Test027() { return PositiveTest4<bool>(true, "00M"); } public bool Test028() { return PositiveTest4<char>('t', "00N"); } public bool Test029() { return PositiveTest4<short>(short.MaxValue, "00O"); } public bool Test030() { return PositiveTest4<int>(int.MaxValue, "00P"); } public bool Test031() { return PositiveTest4<long>(long.MaxValue, "00Q"); } public bool Test032() { return PositiveTest4<float>(3.14f, "00R"); } public bool Test033() { return PositiveTest4<double>(3.1415927, "00S"); } public bool Test034() { return PositiveTest4<ushort>(17, "00T"); } public bool Test035() { return PositiveTest4<uint>(uint.MaxValue, "00U"); } public bool Test036() { return PositiveTest4<ulong>(ulong.MaxValue, "00V"); } public bool Test037() { return PositiveTest4<object>(null, "00W"); } public bool Test038() { return PositiveTest4<object>(new StringBuilder("Testing"), "00X"); } public bool Test039() { return PositiveTest5(new char[] { 'T', 'e', 's', 't' }, "Test", "00Y"); } public bool Test040() { char[] chars = new char[5000]; for (int i = 0; i < 5000; i++) chars[i] = 'a'; return PositiveTest5(chars, new string('a', 5000), "00Z"); } public bool Test041() { return PositiveTest5(new char[] { }, String.Empty, "0AA"); } public bool Test042() { return PositiveTest5(null, String.Empty, "0AB"); } public bool PositiveTest(string str, int index, int count, string expected, string id) { bool result = true; TestFramework.BeginScenario(id + ": Append"); try { StringBuilder sb = new StringBuilder("Test"); sb.Append(str, index, count); string output = sb.ToString(); expected = "Test" + expected; if (output != expected) { result = false; TestFramework.LogError("001", "Error in " + id + ", unexpected append result. Actual string " + output + ", Expected: " + expected); } } catch (Exception exc) { result = false; TestFramework.LogError("002", "Unexpected exception in " + id + ", excpetion: " + exc.ToString()); } return result; } public bool PositiveTest2(char[] str, int index, int count, string expected, string id) { bool result = true; TestFramework.BeginScenario(id + ": Append"); try { StringBuilder sb = new StringBuilder("Test"); sb.Append(str, index, count); string output = sb.ToString(); expected = "Test" + expected; if (output != expected) { result = false; TestFramework.LogError("001a", "Error in " + id + ", unexpected append result. Actual string " + output + ", Expected: " + expected); } } catch (Exception exc) { result = false; TestFramework.LogError("002a", "Unexpected exception in " + id + ", excpetion: " + exc.ToString()); } return result; } public bool PositiveTest3(char str, int count, string expected, string id) { bool result = true; TestFramework.BeginScenario(id + ": Append"); try { StringBuilder sb = new StringBuilder("Test"); sb.Append(str, count); string output = sb.ToString(); expected = "Test" + expected; if (output != expected) { result = false; TestFramework.LogError("001b", "Error in " + id + ", unexpected append result. Actual string " + output + ", Expected: " + expected); } } catch (Exception exc) { result = false; TestFramework.LogError("002b", "Unexpected exception in " + id + ", excpetion: " + exc.ToString()); } return result; } public bool PositiveTest4<T>(T str, string id) { bool result = true; TestFramework.BeginScenario(id + ": Append"); try { StringBuilder sb = new StringBuilder("Test"); sb.Append(str); string output = sb.ToString(); string expected = ((str == null)?"Test":"Test" + str.ToString()); if (output != expected) { result = false; TestFramework.LogError("001c", "Error in " + id + ", unexpected append result. Actual string " + output + ", Expected: " + expected); } } catch (Exception exc) { result = false; TestFramework.LogError("002c", "Unexpected exception in " + id + ", excpetion: " + exc.ToString()); } return result; } public bool PositiveTest5(char[] str, string expected, string id) { bool result = true; TestFramework.BeginScenario(id + ": Append"); try { StringBuilder sb = new StringBuilder("Test"); sb.Append(str); string output = sb.ToString(); expected = "Test" + expected; if (output != expected) { result = false; TestFramework.LogError("001d", "Error in " + id + ", unexpected append result. Actual string " + output + ", Expected: " + expected); } } catch (Exception exc) { result = false; TestFramework.LogError("002d", "Unexpected exception in " + id + ", excpetion: " + exc.ToString()); } return result; } public bool NegativeTest(string str, int index, int count, Type expected, string id) { bool result = true; TestFramework.BeginScenario(id + ": Append"); try { StringBuilder sb = new StringBuilder("Test"); sb.Append(str, index, count); string output = sb.ToString(); result = false; TestFramework.LogError("003", "Error in " + id + ", Expected exception not thrown. No exception. Actual string " + output + ", Expected: " + expected.ToString()); } catch (Exception exc) { if (exc.GetType() != expected) { result = false; TestFramework.LogError("004", "Unexpected exception in " + id + ", expected type: " + expected.ToString() + ", Actual excpetion: " + exc.ToString()); } } return result; } public bool NegativeTest2(char[] str, int index, int count, Type expected, string id) { bool result = true; TestFramework.BeginScenario(id + ": Append"); try { StringBuilder sb = new StringBuilder("Test"); sb.Append(str, index, count); string output = sb.ToString(); result = false; TestFramework.LogError("003b", "Error in " + id + ", Expected exception not thrown. No exception. Actual string " + output + ", Expected: " + expected.ToString()); } catch (Exception exc) { if (exc.GetType() != expected) { result = false; TestFramework.LogError("004b", "Unexpected exception in " + id + ", expected type: " + expected.ToString() + ", Actual excpetion: " + exc.ToString()); } } return result; } public bool NegativeTest3(char str, int count, Type expected, string id) { bool result = true; TestFramework.BeginScenario(id + ": Append"); try { StringBuilder sb = new StringBuilder("Test"); sb.Append(str, count); string output = sb.ToString(); result = false; TestFramework.LogError("003c", "Error in " + id + ", Expected exception not thrown. No exception. Actual string " + output + ", Expected: " + expected.ToString()); } catch (Exception exc) { if (exc.GetType() != expected) { result = false; TestFramework.LogError("004c", "Unexpected exception in " + id + ", expected type: " + expected.ToString() + ", Actual excpetion: " + exc.ToString()); } } return result; } }
/* ==================================================================== */ using System; using Oranikle.Report.Engine; using System.IO; using System.Collections; using System.Drawing.Imaging; using System.Text; using System.Xml; using System.Globalization; using System.Drawing; namespace Oranikle.Report.Engine { ///<summary> /// Renders a report to HTML. This handles some page formating but does not do true page formatting. ///</summary> public class RenderHtml: IPresent { Report r; // report StringWriter tw; // temporary location where the output is going IStreamGen _sg; // stream generater Hashtable _styles; // hash table of styles we've generated int cssId=1; // ID for css when names are usable or available bool bScriptToggle=false; // need to generate toggle javascript in header bool bScriptTableSort=false; // need to generate table sort javascript in header Bitmap _bm=null; // bm and Graphics _g=null; // g are needed when calculating string heights bool _Asp=false; // denotes ASP.NET compatible HTML; e.g. no <html>, <body> // separate JavaScript and CSS string _Prefix=""; // prefix to generating all HTML names (e.g. css, ... string _CSS; // when ASP we put the CSS into a string string _JavaScript; // as well as any required javascript int _SkipMatrixCols=0; // # of matrix columns to skip public RenderHtml(Report rep, IStreamGen sg) { r = rep; _sg = sg; // We need this in future tw = new StringWriter(); // will hold the bulk of the HTML until we generate // final file _styles = new Hashtable(); } ~RenderHtml() { // These should already be cleaned up; but in case of an unexpected error // these still need to be disposed of if (_bm != null) _bm.Dispose(); if (_g != null) _g.Dispose(); } public Report Report() { return r; } public bool Asp { get {return _Asp;} set {_Asp = value;} } public string JavaScript { get {return _JavaScript;} } public string CSS { get {return _CSS;} } public string Prefix { get {return _Prefix;} set { _Prefix = value==null? "": value; if (_Prefix.Length > 0 && _Prefix[0] == '_') _Prefix = "a" + _Prefix; // not perfect but underscores as first letter don't work } } public bool IsPagingNeeded() { return false; } public void Start() { return; } string FixupRelativeName(string relativeName) { if (_sg is OneFileStreamGen) { if (relativeName[0] == Path.DirectorySeparatorChar || relativeName[0] == Path.AltDirectorySeparatorChar) relativeName = relativeName.Substring(1); } else if (!(relativeName[0] == Path.DirectorySeparatorChar || relativeName[0] == Path.AltDirectorySeparatorChar)) { if (_Asp) relativeName = "/" + relativeName; // Hack for Firefox else relativeName = Path.DirectorySeparatorChar + relativeName; } return relativeName; } // puts the JavaScript into the header private void ScriptGenerate(TextWriter ftw) { if (bScriptToggle || bScriptTableSort) { ftw.WriteLine("<script language=\"javascript\">"); } if (bScriptToggle) { ftw.WriteLine("var dname='';"); ftw.WriteLine(@"function hideShow(node, hideCount, showID) { if (navigator.appName.toLowerCase().indexOf('netscape') > -1) dname = 'table-row'; else dname = 'block'; var tNode; for (var ci=0;ci<node.childNodes.length;ci++) { if (node.childNodes[ci].tagName && node.childNodes[ci].tagName.toLowerCase() == 'img') tNode = node.childNodes[ci]; } var rows = findObject(showID); if (rows[0].style.display == dname) {hideRows(rows, hideCount); tNode.src='plus.gif';} else { tNode.src='minus.gif'; for (var i = 0; i < rows.length; i++) { rows[i].style.display = dname; } } } function hideRows(rows, count) { var row; if (navigator.appName.toLowerCase().indexOf('netscape') > -1) { for (var r=0; r < rows.length; r++) { row = rows[r]; row.style.display = 'none'; var imgs = row.getElementsByTagName('img'); for (var ci=0;ci<imgs.length;ci++) { if (imgs[ci].className == 'toggle') { imgs[ci].src='plus.gif'; } } } return; } if (rows.tagName == 'TR') row = rows; else row = rows[0]; while (count > 0) { row.style.display = 'none'; var imgs = row.getElementsByTagName('img'); for (var ci=0;ci<imgs.length;ci++) { if (imgs[ci].className == 'toggle') { imgs[ci].src='plus.gif'; } } row = row.nextSibling; count--; } } function findObject(id) { if (navigator.appName.toLowerCase().indexOf('netscape') > -1) { var a = new Array(); var count=0; for (var i=0; i < document.all.length; i++) { if (document.all[i].id == id) a[count++] = document.all[i]; } return a; } else { var o = document.all[id]; if (o.tagName == 'TR') { var a = new Array(); a[0] = o; return a; } return o; } } "); } if (bScriptTableSort) { ftw.WriteLine("var SORT_INDEX;"); ftw.WriteLine("var SORT_DIR;"); ftw.WriteLine("function sort_getInnerText(element) {"); ftw.WriteLine(" if (typeof element == 'string') return element;"); ftw.WriteLine(" if (typeof element == 'undefined') return element;"); ftw.WriteLine(" if (element.innerText) return element.innerText;"); ftw.WriteLine(" var s = '';"); ftw.WriteLine(" var cn = element.childNodes;"); ftw.WriteLine(" for (var i = 0; i < cn.length; i++) {"); ftw.WriteLine(" switch (cn[i].nodeType) {"); ftw.WriteLine(" case 1:"); // element node ftw.WriteLine(" s += sort_getInnerText(cn[i]);"); ftw.WriteLine(" break;"); ftw.WriteLine(" case 3:"); // text node ftw.WriteLine(" s += cn[i].nodeValue;"); ftw.WriteLine(" break;"); ftw.WriteLine(" }"); ftw.WriteLine(" }"); ftw.WriteLine(" return s;"); ftw.WriteLine("}"); ftw.WriteLine("function sort_table(node, sortfn, header_rows, footer_rows) {"); ftw.WriteLine(" var arrowNode;"); // arrow node ftw.WriteLine(" for (var ci=0;ci<node.childNodes.length;ci++) {"); ftw.WriteLine(" if (node.childNodes[ci].tagName && node.childNodes[ci].tagName.toLowerCase() == 'span') arrowNode = node.childNodes[ci];"); ftw.WriteLine(" }"); ftw.WriteLine(" var td = node.parentNode;"); ftw.WriteLine(" SORT_INDEX = td.cellIndex;"); // need to remember SORT_INDEX in compare function ftw.WriteLine(" var table = sort_getTable(td);"); ftw.WriteLine(" var sortnext;"); ftw.WriteLine(" if (arrowNode.getAttribute('sortdir') == 'down') {"); ftw.WriteLine(" arrow = '&nbsp;&nbsp;&uarr;';"); ftw.WriteLine(" SORT_DIR = -1;"); // descending SORT_DIR in compare function ftw.WriteLine(" sortnext = 'up';"); ftw.WriteLine(" } else {"); ftw.WriteLine(" arrow = '&nbsp;&nbsp;&darr;';"); ftw.WriteLine(" SORT_DIR = 1;"); // ascending SORT_DIR in compare function ftw.WriteLine(" sortnext = 'down';"); ftw.WriteLine(" }"); ftw.WriteLine(" var newRows = new Array();"); ftw.WriteLine(" for (j=header_rows;j<table.rows.length-footer_rows;j++) { newRows[j-header_rows] = table.rows[j]; }"); ftw.WriteLine(" newRows.sort(sortfn);"); // We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones ftw.WriteLine(" for (i=0;i<newRows.length;i++) {table.tBodies[0].appendChild(newRows[i]);}"); // Reset all arrows and directions for next time ftw.WriteLine(" var spans = document.getElementsByTagName('span');"); ftw.WriteLine(" for (var ci=0;ci<spans.length;ci++) {"); ftw.WriteLine(" if (spans[ci].className == 'sortarrow') {"); // in the same table as us? ftw.WriteLine(" if (sort_getTable(spans[ci]) == sort_getTable(node)) {"); ftw.WriteLine(" spans[ci].innerHTML = '&nbsp;&nbsp;&nbsp;';"); ftw.WriteLine(" spans[ci].setAttribute('sortdir','up');"); ftw.WriteLine(" }"); ftw.WriteLine(" }"); ftw.WriteLine(" }"); ftw.WriteLine(" arrowNode.innerHTML = arrow;"); ftw.WriteLine(" arrowNode.setAttribute('sortdir',sortnext);"); ftw.WriteLine("}"); ftw.WriteLine("function sort_getTable(el) {"); ftw.WriteLine(" if (el == null) return null;"); ftw.WriteLine(" else if (el.nodeType == 1 && el.tagName.toLowerCase() == 'table')"); ftw.WriteLine(" return el;"); ftw.WriteLine(" else"); ftw.WriteLine(" return sort_getTable(el.parentNode);"); ftw.WriteLine("}"); ftw.WriteLine("function sort_cmp_date(c1,c2) {"); ftw.WriteLine(" t1 = sort_getInnerText(c1.cells[SORT_INDEX]);"); ftw.WriteLine(" t2 = sort_getInnerText(c2.cells[SORT_INDEX]);"); ftw.WriteLine(" dt1 = new Date(t1);"); ftw.WriteLine(" dt2 = new Date(t2);"); ftw.WriteLine(" if (dt1==dt2) return 0;"); ftw.WriteLine(" if (dt1<dt2) return -SORT_DIR;"); ftw.WriteLine(" return SORT_DIR;"); ftw.WriteLine("}"); // numeric - removes any extraneous formating characters before parsing ftw.WriteLine("function sort_cmp_number(c1,c2) {"); ftw.WriteLine(" t1 = sort_getInnerText(c1.cells[SORT_INDEX]).replace(/[^0-9.]/g,'');"); ftw.WriteLine(" t2 = sort_getInnerText(c2.cells[SORT_INDEX]).replace(/[^0-9.]/g,'');"); ftw.WriteLine(" n1 = parseFloat(t1);"); ftw.WriteLine(" n2 = parseFloat(t2);"); ftw.WriteLine(" if (isNaN(n1)) n1 = Number.MAX_VALUE"); ftw.WriteLine(" if (isNaN(n2)) n2 = Number.MAX_VALUE"); ftw.WriteLine(" return (n1 - n2)*SORT_DIR;"); ftw.WriteLine("}"); // For string we first do a case insensitive comparison; // when equal we then do a case sensitive comparison ftw.WriteLine("function sort_cmp_string(c1,c2) {"); ftw.WriteLine(" t1 = sort_getInnerText(c1.cells[SORT_INDEX]).toLowerCase();"); ftw.WriteLine(" t2 = sort_getInnerText(c2.cells[SORT_INDEX]).toLowerCase();"); ftw.WriteLine(" if (t1==t2) return sort_cmp_casesensitive(c1,c2);"); ftw.WriteLine(" if (t1<t2) return -SORT_DIR;"); ftw.WriteLine(" return SORT_DIR;"); ftw.WriteLine("}"); ftw.WriteLine("function sort_cmp_casesensitive(c1,c2) {"); ftw.WriteLine(" t1 = sort_getInnerText(c1.cells[SORT_INDEX]);"); ftw.WriteLine(" t2 = sort_getInnerText(c2.cells[SORT_INDEX]);"); ftw.WriteLine(" if (t1==t2) return 0;"); ftw.WriteLine(" if (t2<t2) return -SORT_DIR;"); ftw.WriteLine(" return SORT_DIR;"); ftw.WriteLine("}"); } if (bScriptToggle || bScriptTableSort) { ftw.WriteLine("</script>"); } return; } // handle the Action tag private string Action(Action a, Row r, string t, string tooltip) { if (a == null) return t; string result = t; if (a.Hyperlink != null) { // Handle a hyperlink string url = a.HyperLinkValue(this.r, r); if (tooltip == null) result = String.Format("<a target=\"_top\" href=\"{0}\">{1}</a>", url, t); else result = String.Format("<a target=\"_top\" href=\"{0}\" title=\"{1}\">{2}</a>", url, tooltip, t); } else if (a.Drill != null) { // Handle a drill through StringBuilder args= new StringBuilder("<a target=\"_top\" href=\""); if (_Asp) // for ASP we go thru the default page and pass it as an argument args.Append("Default.aspx?rs:url="); args.Append(a.Drill.ReportName); args.Append(".rdlc"); if (a.Drill.DrillthroughParameters != null) { bool bFirst = !_Asp; // ASP already have an argument foreach (DrillthroughParameter dtp in a.Drill.DrillthroughParameters.Items) { if (!dtp.OmitValue(this.r, r)) { if (bFirst) { // First parameter - prefixed by '?' args.Append('?'); bFirst = false; } else { // Subsequant parameters - prefixed by '&' args.Append('&'); } args.Append(dtp.Name.Nm); args.Append('='); args.Append(dtp.ValueValue(this.r, r)); } } } args.Append('"'); if (tooltip != null) args.Append(String.Format(" title=\"{0}\"", tooltip)); args.Append(">"); args.Append(t); args.Append("</a>"); result = args.ToString(); } else if (a.BookmarkLink != null) { // Handle a bookmark string bm = a.BookmarkLinkValue(this.r, r); if (tooltip == null) result = String.Format("<a href=\"#{0}\">{1}</a>", bm, t); else result = String.Format("<a href=\"#{0}\" title=\"{1}\">{2}</a>", bm, tooltip, t); } return result; } private string Bookmark(string bm, string t) { if (bm == null) return t; return String.Format("<div id=\"{0}\">{1}</div>", bm, t); } // Generate the CSS styles and put them in the header private void CssGenerate(TextWriter ftw) { if (_styles.Count <= 0) return; if (!_Asp) ftw.WriteLine("<style type='text/css'>"); foreach (CssCacheEntry cce in _styles.Values) { int i = cce.Css.IndexOf('{'); if (cce.Name.IndexOf('#') >= 0) ftw.WriteLine("{0} {1}", cce.Name, cce.Css.Substring(i)); else ftw.WriteLine(".{0} {1}", cce.Name, cce.Css.Substring(i)); } if (!_Asp) ftw.WriteLine("</style>"); } private string CssAdd(Style s, ReportLink rl, Row row) { return CssAdd(s, rl, row, false, float.MinValue, float.MinValue); } private string CssAdd(Style s, ReportLink rl, Row row, bool bForceRelative) { return CssAdd(s, rl, row, bForceRelative, float.MinValue, float.MinValue); } private string CssAdd(Style s, ReportLink rl, Row row, bool bForceRelative, float h, float w) { string css; string prefix = CssPrefix(s, rl); if (_Asp && prefix == "table#") bForceRelative = true; if (s != null) css = prefix + "{" + CssPosition(rl, row, bForceRelative, h, w) + s.GetCSS(this.r, row, true) + "}"; else if (rl is Table || rl is Matrix) css = prefix + "{" + CssPosition(rl, row, bForceRelative, h, w) + "border-collapse:collapse;}"; else css = prefix + "{" + CssPosition(rl, row, bForceRelative, h, w) + "}"; CssCacheEntry cce = (CssCacheEntry) _styles[css]; if (cce == null) { string name = prefix + this.Prefix + "css" + cssId++.ToString(); cce = new CssCacheEntry(css, name); _styles.Add(cce.Css, cce); } int i = cce.Name.IndexOf('#'); if (i > 0) return cce.Name.Substring(i+1); else return cce.Name; } private string CssPosition(ReportLink rl,Row row, bool bForceRelative, float h, float w) { if (!(rl is ReportItem)) // if not a report item then no position return ""; // no positioning within a table for (ReportLink p=rl.Parent; p != null; p=p.Parent) { if (p is TableCell) return ""; if (p is RowGrouping || p is MatrixCell || p is ColumnGrouping || p is Corner) { StringBuilder sb2 = new StringBuilder(); if (h != float.MinValue) sb2.AppendFormat(NumberFormatInfo.InvariantInfo, "height: {0}pt; ", h); if (w != float.MinValue) sb2.AppendFormat(NumberFormatInfo.InvariantInfo, "width: {0}pt; ", w); return sb2.ToString(); } } // TODO: optimize by putting this into ReportItem and caching result??? ReportItem ri = (ReportItem) rl; StringBuilder sb = new StringBuilder(); if (ri.Left != null && ri.Left.Size > 0) { sb.AppendFormat(NumberFormatInfo.InvariantInfo, "left: {0}; ", ri.Left.CSS); } if (ri is Matrix || ri is Image || ri is Chart) { } else { if (ri.Width != null) sb.AppendFormat(NumberFormatInfo.InvariantInfo, "width: {0}; ", ri.Width.CSS); } if (ri.Top != null && ri.Top.Size > 0) { sb.AppendFormat(NumberFormatInfo.InvariantInfo, "top: {0}pt; ", ri.Gap(this.r)); } if (ri is List) { List l = ri as List; sb.AppendFormat(NumberFormatInfo.InvariantInfo, "height: {0}pt; ", l.HeightOfList(this.r, GetGraphics,row)); } else if (ri is Matrix || ri is Table || ri is Image || ri is Chart) {} else if (ri.Height != null) sb.AppendFormat(NumberFormatInfo.InvariantInfo, "height: {0}; ", ri.Height.CSS); if (sb.Length > 0) { if (bForceRelative || ri.YParents != null) sb.Insert(0, "position: relative; "); else sb.Insert(0, "position: absolute; "); } return sb.ToString(); } private Graphics GetGraphics { get { if (_g == null) { _bm = new Bitmap(10, 10); _g = Graphics.FromImage(_bm); } return _g; } } private string CssPrefix(Style s, ReportLink rl) { string cssPrefix=null; ReportLink p; if (rl is Table || rl is Matrix || rl is Rectangle) { cssPrefix = "table#"; } else if (rl is Body) { cssPrefix = "body#"; } else if (rl is Line) { cssPrefix = "table#"; } else if (rl is List) { cssPrefix = ""; } else if (rl is Subreport) { cssPrefix = ""; } else if (rl is Chart) { cssPrefix = ""; } if (cssPrefix != null) return cssPrefix; // now find what the style applies to for (p=rl.Parent; p != null; p=p.Parent) { if (p is TableCell) { bool bHead = false; ReportLink p2; for (p2=p.Parent; p2 != null; p2=p2.Parent) { Type t2 = p2.GetType(); if (t2 == typeof(Header)) { if (p2.Parent is Table) bHead=true; break; } } if (bHead) cssPrefix = "th#"; else cssPrefix = "td#"; break; } else if (p is RowGrouping || p is MatrixCell || p is ColumnGrouping || p is Corner) { cssPrefix = "td#"; break; } } return cssPrefix == null? "": cssPrefix; } public void End() { string bodyCssId; if (r.ReportDefinition.Body != null) bodyCssId = CssAdd(r.ReportDefinition.Body.Style, r.ReportDefinition.Body, null); // add the style for the body else bodyCssId = null; TextWriter ftw = _sg.GetTextWriter(); // the final text writer location if (_Asp) { // do any required JavaScript StringWriter sw = new StringWriter(); ScriptGenerate(sw); _JavaScript = sw.ToString(); sw.Close(); // do any required CSS sw = new StringWriter(); CssGenerate(sw); _CSS = sw.ToString(); sw.Close(); } else { ftw.WriteLine("<html>"); // handle the <head>: description, javascript and CSS goes here ftw.WriteLine("<head>"); ScriptGenerate(ftw); CssGenerate(ftw); if (r.Description != null) // Use description as title if provided ftw.WriteLine(string.Format(@"<title>{0}</title>", XmlUtil.XmlAnsi(r.Description))); ftw.WriteLine(@"</head>"); } // Always want an HTML body - even if report doesn't have a body stmt if (this._Asp) { ftw.WriteLine("<table style=\"position: relative;\">"); } else if (bodyCssId != null) ftw.WriteLine(@"<body id='{0}'><table>", bodyCssId); else ftw.WriteLine("<body><table>"); ftw.Write(tw.ToString()); if (this._Asp) ftw.WriteLine(@"</table>"); else ftw.WriteLine(@"</table></body></html>"); if (_g != null) { _g.Dispose(); _g = null; } if (_bm != null) { _bm.Dispose(); _bm = null; } return; } // Body: main container for the report public void BodyStart(Body b) { if (b.ReportItems != null && b.ReportItems.Items.Count > 0) tw.WriteLine("<tr><td><div style=\"POSITION: relative; \">"); } public void BodyEnd(Body b) { if (b.ReportItems != null && b.ReportItems.Items.Count > 0) tw.WriteLine("</div></td></tr>"); } public void PageHeaderStart(PageHeader ph) { if (ph.ReportItems != null && ph.ReportItems.Items.Count > 0) tw.WriteLine("<tr><td><div style=\"overflow: clip; POSITION: relative; HEIGHT: {0};\">", ph.Height.CSS); } public void PageHeaderEnd(PageHeader ph) { if (ph.ReportItems != null && ph.ReportItems.Items.Count > 0) tw.WriteLine("</div></td></tr>"); } public void PageFooterStart(PageFooter pf) { if (pf.ReportItems != null && pf.ReportItems.Items.Count > 0) tw.WriteLine("<tr><td><div style=\"overflow: clip; POSITION: relative; HEIGHT: {0};\">", pf.Height.CSS); } public void PageFooterEnd(PageFooter pf) { if (pf.ReportItems != null && pf.ReportItems.Items.Count > 0) tw.WriteLine("</div></td></tr>"); } public void Textbox(Textbox tb, string t, Row row) { if (tb.IsHtml(this.r, row)) // we leave the text as is (except to handle unicode) when request is to treat as html { // this can screw up the generated HTML if not properly formed HTML t = XmlUtil.HtmlAnsi(t); } else { // make all the characters browser readable t = XmlUtil.XmlAnsi(t); // handle any specified bookmark t = Bookmark(tb.BookmarkValue(this.r, row), t); // handle any specified actions t = Action(tb.Action, row, t, tb.ToolTipValue(this.r, row)); } // determine if we're in a tablecell Type tp = tb.Parent.Parent.GetType(); bool bCell; if (tp == typeof(TableCell) || tp == typeof(Corner) || tp == typeof(DynamicColumns) || tp == typeof(DynamicRows) || tp == typeof(StaticRow) || tp == typeof(StaticColumn) || tp == typeof(Subtotal) || tp == typeof(MatrixCell)) bCell = true; else bCell = false; if (tp == typeof(Rectangle)) tw.Write("<td>"); if (bCell) { // The cell has the formatting for this text if (t == "") tw.Write("<br />"); // must have something in cell for formating else tw.Write(t); } else { // Formatting must be specified string cssName = CssAdd(tb.Style, tb, row); // get the style name for this item tw.Write("<div class='{0}'>{1}</div>", cssName, t); } if (tp == typeof(Rectangle)) tw.Write("</td>"); } public void DataRegionNoRows(DataRegion d, string noRowsMsg) // no rows in table { if (noRowsMsg == null) noRowsMsg = ""; bool bTableCell = d.Parent.Parent.GetType() == typeof(TableCell); if (bTableCell) { if (noRowsMsg == "") tw.Write("<br />"); else tw.Write(noRowsMsg); } else { string cssName = CssAdd(d.Style, d, null); // get the style name for this item tw.Write("<div class='{0}'>{1}</div>", cssName, noRowsMsg); } } // Lists public bool ListStart(List l, Row r) { // identifiy reportitem it if necessary string bookmark = l.BookmarkValue(this.r, r); if (bookmark != null) // tw.WriteLine("<div id=\"{0}\">", bookmark); // can't use the table id since we're using for css style return true; } public void ListEnd(List l, Row r) { string bookmark = l.BookmarkValue(this.r, r); if (bookmark != null) tw.WriteLine("</div>"); } public void ListEntryBegin(List l, Row r) { string cssName = CssAdd(l.Style, l, r, true); // get the style name for this item; force to be relative tw.WriteLine(); tw.WriteLine("<div class={0}>", cssName); } public void ListEntryEnd(List l, Row r) { tw.WriteLine(); tw.WriteLine("</div>"); } // Tables // Report item table public bool TableStart(Table t, Row row) { string cssName = CssAdd(t.Style, t, row); // get the style name for this item // Determine if report custom defn want this table to be sortable if (IsTableSortable(t)) { this.bScriptTableSort = true; } string bookmark = t.BookmarkValue(this.r, row); if (bookmark != null) tw.WriteLine("<div id=\"{0}\">", bookmark); // can't use the table id since we're using for css style // Calculate the width of all the columns int width = t.WidthInPixels(this.r, row); if (width <= 0) tw.WriteLine("<table id='{0}'>", cssName); else tw.WriteLine("<table id='{0}' width={1}>", cssName, width); return true; } public bool IsTableSortable(Table t) { if (t.TableGroups != null || t.Details == null || t.Details.TableRows == null || t.Details.TableRows.Items.Count != 1) return false; // can't have tableGroups; must have 1 detail row // Determine if report custom defn want this table to be sortable bool bReturn = false; if (t.Custom != null) { // Loop thru all the child nodes foreach(XmlNode xNodeLoop in t.Custom.CustomXmlNode.ChildNodes) { if (xNodeLoop.Name == "HTML") { if (xNodeLoop.LastChild.InnerText.ToLower() == "true") { bReturn = true; } break; } } } return bReturn; } public void TableEnd(Table t, Row row) { string bookmark = t.BookmarkValue(this.r, row); if (bookmark != null) tw.WriteLine("</div>"); tw.WriteLine("</table>"); return; } public void TableBodyStart(Table t, Row row) { tw.WriteLine("<tbody>"); } public void TableBodyEnd(Table t, Row row) { tw.WriteLine("</tbody>"); } public void TableFooterStart(Footer f, Row row) { tw.WriteLine("<tfoot>"); } public void TableFooterEnd(Footer f, Row row) { tw.WriteLine("</tfoot>"); } public void TableHeaderStart(Header h, Row row) { tw.WriteLine("<thead>"); } public void TableHeaderEnd(Header h, Row row) { tw.WriteLine("</thead>"); } public void TableRowStart(TableRow tr, Row row) { tw.Write("\t<tr"); ReportLink rl = tr.Parent.Parent; Visibility v=null; Textbox togText=null; // holds the toggle text box if any if (rl is Details) { Details d = (Details) rl; v = d.Visibility; togText = d.ToggleTextbox; } else if (rl.Parent is TableGroup) { TableGroup tg = (TableGroup) rl.Parent; v = tg.Visibility; togText = tg.ToggleTextbox; } if (v != null && v.Hidden != null) { bool bHide = v.Hidden.EvaluateBoolean(this.r, row); if (bHide) tw.Write(" style=\"display:none;\""); } if (togText != null && togText.Name != null) { string name = togText.Name.Nm + "_" + togText.RunCount(this.r).ToString(); tw.Write(" id='{0}'", name); } tw.Write(">"); } public void TableRowEnd(TableRow tr, Row row) { tw.WriteLine("</tr>"); } public void TableCellStart(TableCell t, Row row) { string cellType = t.InTableHeader? "th": "td"; ReportItem r = t.ReportItems.Items[0]; string cssName = CssAdd(r.Style, r, row); // get the style name for this item tw.Write("<{0} id='{1}'", cellType, cssName); // calculate width of column if (t.InTableHeader && t.OwnerTable.TableColumns != null) { // Calculate the width across all the spanned columns int width = 0; for (int ci=t.ColIndex; ci < t.ColIndex + t.ColSpan; ci++) { TableColumn tc = t.OwnerTable.TableColumns.Items[ci] as TableColumn; if (tc != null && tc.Width != null) width += tc.Width.PixelsX; } if (width > 0) tw.Write(" width={0}", width); } if (t.ColSpan > 1) tw.Write(" colspan={0}", t.ColSpan); Textbox tb = r as Textbox; if (tb != null && // have textbox tb.IsToggle && // and its a toggle tb.Name != null) // and need name as well { int groupNestCount = t.OwnerTable.GetGroupNestCount(this.r); if (groupNestCount > 0) // anything to toggle? { string name = tb.Name.Nm + "_" + (tb.RunCount(this.r)+1).ToString(); bScriptToggle = true; // need both hand and pointer because IE and Firefox use different names tw.Write(" onClick=\"hideShow(this, {0}, '{1}')\" onMouseOver=\"style.cursor ='hand';style.cursor ='pointer'\">", groupNestCount, name); tw.Write("<img class='toggle' src=\"plus.gif\" align=\"top\"/>"); } else tw.Write("<img src=\"empty.gif\" align=\"top\"/>"); } else tw.Write(">"); if (t.InTableHeader) { // put the second half of the sort tags for the column; if needed // first half ---- <a href="#" onclick="sort_table(this,sort_cmp_string,1,0);return false;"> // next half follows text ---- <span class="sortarrow">&nbsp;&nbsp;&nbsp;</span></a></th> string sortcmp = SortType(t, tb); // obtain the sort type if (sortcmp != null) // null if sort not needed { int headerRows, footerRows; headerRows = t.OwnerTable.Header.TableRows.Items.Count; // since we're in header we know we have some rows if (t.OwnerTable.Footer != null && t.OwnerTable.Footer.TableRows != null) footerRows = t.OwnerTable.Footer.TableRows.Items.Count; else footerRows = 0; tw.Write("<a href=\"#\" title='Sort' onclick=\"sort_table(this,{0},{1},{2});return false;\">",sortcmp, headerRows, footerRows); } } return; } private string SortType(TableCell tc, Textbox tb) { // return of null means don't sort if (tb == null || !IsTableSortable(tc.OwnerTable)) return null; // default is true if table is sortable; // but user may place override on Textbox custom tag if (tb.Custom != null) { // Loop thru all the child nodes foreach(XmlNode xNodeLoop in tb.Custom.CustomXmlNode.ChildNodes) { if (xNodeLoop.Name == "HTML") { if (xNodeLoop.LastChild.InnerText.ToLower() == "false") { return null; } break; } } } // Must find out the type of the detail column Details d = tc.OwnerTable.Details; if (d == null) return null; TableRow tr = d.TableRows.Items[0] as TableRow; if (tr == null) return null; TableCell dtc = tr.TableCells.Items[tc.ColIndex] as TableCell; if (dtc == null) return null; Textbox dtb = dtc.ReportItems.Items[0] as Textbox; if (dtb == null) return null; string sortcmp; switch (dtb.Value.Type) { case TypeCode.DateTime: sortcmp = "sort_cmp_date"; break; case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Decimal: case TypeCode.Single: case TypeCode.Double: sortcmp = "sort_cmp_number"; break; case TypeCode.String: sortcmp = "sort_cmp_string"; break; case TypeCode.Empty: // Not a type we know how to sort default: sortcmp = null; break; } return sortcmp; } public void TableCellEnd(TableCell t, Row row) { string cellType = t.InTableHeader? "th": "td"; Textbox tb = t.ReportItems.Items[0] as Textbox; if (cellType == "th" && SortType(t, tb) != null) { // put the second half of the sort tags for the column // first half ---- <a href="#" onclick="sort_table(this,sort_cmp_string,1,0);return false;"> // next half follows text ---- <span class="sortarrow">&nbsp;&nbsp;&nbsp;</span></a></th> tw.Write("<span class=\"sortarrow\">&nbsp;&nbsp;&nbsp;</span></a>"); } tw.Write("</{0}>", cellType); return; } public bool MatrixStart(Matrix m, MatrixCellEntry[,] matrix, Row r, int headerRows, int maxRows, int maxCols) // called first { string bookmark = m.BookmarkValue(this.r, r); if (bookmark != null) tw.WriteLine("<div id=\"{0}\">", bookmark); // can't use the table id since we're using for css style // output some of the table styles string cssName = CssAdd(m.Style, m, r); // get the style name for this item tw.WriteLine("<table id='{0}'>", cssName); return true; } public void MatrixColumns(Matrix m, MatrixColumns mc) // called just after MatrixStart { } public void MatrixCellStart(Matrix m, ReportItem ri, int row, int column, Row r, float h, float w, int colSpan) { if (ri == null) // Empty cell? { if (_SkipMatrixCols == 0) tw.Write("<td>"); return; } string cssName = CssAdd(ri.Style, ri, r, false, h, w); // get the style name for this item tw.Write("<td id='{0}'", cssName); if (colSpan != 1) { tw.Write(" colspan={0}", colSpan); _SkipMatrixCols=-(colSpan-1); // start it as negative as indicator that we need this </td> } else _SkipMatrixCols=0; if (ri is Textbox) { Textbox tb = (Textbox) ri; if (tb.IsToggle && tb.Name != null) // name is required for this { string name = tb.Name.Nm + "_" + (tb.RunCount(this.r)+1).ToString(); bScriptToggle = true; // we need to generate JavaScript in header // TODO -- need to calculate the hide count correctly tw.Write(" onClick=\"hideShow(this, {0}, '{1}')\" onMouseOver=\"style.cursor ='hand'\"", 0, name); } } tw.Write(">"); } public void MatrixCellEnd(Matrix m, ReportItem ri, int row, int column, Row r) { if (_SkipMatrixCols == 0) tw.Write("</td>"); else if (_SkipMatrixCols < 0) { tw.Write("</td>"); _SkipMatrixCols = -_SkipMatrixCols; } else _SkipMatrixCols--; return; } public void MatrixRowStart(Matrix m, int row, Row r) { tw.Write("\t<tr"); tw.Write(">"); } public void MatrixRowEnd(Matrix m, int row, Row r) { tw.WriteLine("</tr>"); } public void MatrixEnd(Matrix m, Row r) // called last { tw.Write("</table>"); string bookmark = m.BookmarkValue(this.r, r); if (bookmark != null) tw.WriteLine("</div>"); return; } public void Chart(Chart c, Row r, ChartBase cb) { string relativeName; Stream io = _sg.GetIOStream(out relativeName, "png"); try { cb.Save(this.r, io, ImageFormat.Png); } finally { io.Flush(); io.Close(); } relativeName = FixupRelativeName(relativeName); // Create syntax in a string buffer StringWriter sw = new StringWriter(); string bookmark = c.BookmarkValue(this.r, r); if (bookmark != null) sw.WriteLine("<div id=\"{0}\">", bookmark); // can't use the table id since we're using for css style string cssName = CssAdd(c.Style, c, null); // get the style name for this item sw.Write("<img src=\"{0}\" class='{1}'", relativeName, cssName); string tooltip = c.ToolTipValue(this.r, r); if (tooltip != null) sw.Write(" alt=\"{0}\"", tooltip); if (c.Height != null) sw.Write(" height=\"{0}\"", c.Height.PixelsY.ToString()); if (c.Width != null) sw.Write(" width=\"{0}\"", c.Width.PixelsX.ToString()); sw.Write(">"); if (bookmark != null) sw.Write("</div>"); tw.Write(Action(c.Action, r, sw.ToString(), tooltip)); return; } public void Image(Image i, Row r, string mimeType, Stream ioin) { string relativeName; string suffix; switch (mimeType) { case "image/bmp": suffix = "bmp"; break; case "image/jpeg": suffix = "jpeg"; break; case "image/gif": suffix = "gif"; break; case "image/png": case "image/x-png": suffix = "png"; break; default: suffix = "unk"; break; } Stream io = _sg.GetIOStream(out relativeName, suffix); try { if (ioin.CanSeek) // ioin.Length requires Seek support { byte[] ba = new byte[ioin.Length]; ioin.Read(ba, 0, ba.Length); io.Write(ba, 0, ba.Length); } else { byte[] ba = new byte[1000]; // read a 1000 bytes at a time while (true) { int length = ioin.Read(ba, 0, ba.Length); if (length <= 0) break; io.Write(ba, 0, length); } } } finally { io.Flush(); io.Close(); } relativeName = FixupRelativeName(relativeName); // Create syntax in a string buffer StringWriter sw = new StringWriter(); string bookmark = i.BookmarkValue(this.r, r); if (bookmark != null) sw.WriteLine("<div id=\"{0}\">", bookmark); // we're using for css style string cssName = CssAdd(i.Style, i, null); // get the style name for this item sw.Write("<img src=\"{0}\" class='{1}'", relativeName, cssName); string tooltip = i.ToolTipValue(this.r, r); if (tooltip != null) sw.Write(" alt=\"{0}\"", tooltip); int h = i.Height == null? -1: i.Height.PixelsY; int w = i.Width == null ? -1 : i.Width.PixelsX; switch (i.Sizing) { case ImageSizingEnum.AutoSize: break; // this is right case ImageSizingEnum.Clip: break; // not sure how to clip it case ImageSizingEnum.Fit: if (h > 0) sw.Write(" height=\"{0}\"", h.ToString()); if (w > 0) sw.Write(" width=\"{0}\"", w.ToString()); break; case ImageSizingEnum.FitProportional: break; // would have to create an image to handle this } sw.Write("/>"); if (bookmark != null) sw.Write("</div>"); tw.Write(Action(i.Action, r, sw.ToString(), tooltip)); return; } public void Line(Line l, Row r) { bool bVertical; string t; if (l.Height == null || l.Height.PixelsY > 0) // only handle horizontal rule { if (l.Width == null || l.Width.PixelsX > 0) // and vertical rules return; bVertical = true; t = "<TABLE style=\"border-collapse:collapse;BORDER-STYLE: none;WIDTH: {0}; POSITION: absolute; LEFT: {1}; TOP: {2}; HEIGHT: {3}; BACKGROUND-COLOR:{4};\"><TBODY><TR style=\"WIDTH:{0}\"><TD style=\"WIDTH:{0}\"></TD></TR></TBODY></TABLE>"; } else { bVertical = false; t = "<TABLE style=\"border-collapse:collapse;BORDER-STYLE: none;WIDTH: {0}; POSITION: absolute; LEFT: {1}; TOP: {2}; HEIGHT: {3}; BACKGROUND-COLOR:{4};\"><TBODY><TR style=\"HEIGHT:{3}\"><TD style=\"HEIGHT:{3}\"></TD></TR></TBODY></TABLE>"; } string width, left, top, height, color; Style s = l.Style; left = l.Left == null? "0px": l.Left.CSS; top = l.Top == null? "0px": l.Top.CSS; if (bVertical) { height = l.Height == null? "0px": l.Height.CSS; // width comes from the BorderWidth if (s != null && s.BorderWidth != null && s.BorderWidth.Default != null) width = s.BorderWidth.Default.EvaluateString(this.r, r); else width = "1px"; } else { width = l.Width == null? "0px": l.Width.CSS; // height comes from the BorderWidth if (s != null && s.BorderWidth != null && s.BorderWidth.Default != null) height = s.BorderWidth.Default.EvaluateString(this.r, r); else height = "1px"; } if (s != null && s.BorderColor != null && s.BorderColor.Default != null) color = s.BorderColor.Default.EvaluateString(this.r, r); else color = "black"; tw.WriteLine(t, width, left, top, height, color); return; } public bool RectangleStart(Oranikle.Report.Engine.Rectangle rect, Row r) { string cssName = CssAdd(rect.Style, rect, r); // get the style name for this item string bookmark = rect.BookmarkValue(this.r, r); if (bookmark != null) tw.WriteLine("<div id=\"{0}\">", bookmark); // can't use the table id since we're using for css style // Calculate the width of all the columns int width = rect.Width == null? -1: rect.Width.PixelsX; if (width < 0) tw.WriteLine("<table id='{0}'><tr>", cssName); else tw.WriteLine("<table id='{0}' width={1}><tr>", cssName, width); return true; } public void RectangleEnd(Oranikle.Report.Engine.Rectangle rect, Row r) { tw.WriteLine("</tr></table>"); string bookmark = rect.BookmarkValue(this.r, r); if (bookmark != null) tw.WriteLine("</div>"); return; } // Subreport: public void Subreport(Subreport s, Row r) { string cssName = CssAdd(s.Style, s, r); // get the style name for this item tw.WriteLine("<div class='{0}'>", cssName); s.ReportDefn.Run(this); tw.WriteLine("</div>"); } public void GroupingStart(Grouping g) // called at start of grouping { } public void GroupingInstanceStart(Grouping g) // called at start for each grouping instance { } public void GroupingInstanceEnd(Grouping g) // called at start for each grouping instance { } public void GroupingEnd(Grouping g) // called at end of grouping { } public void RunPages(Pages pgs) // we don't have paging turned on for html { } } class CssCacheEntry { string _Css; // css string _Name; // name of entry public CssCacheEntry(string css, string name) { _Css = css; _Name = name; } public string Css { get { return _Css; } set { _Css = value; } } public string Name { get { return _Name; } set { _Name = value; } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osuTK; using osuTK.Graphics; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Graphics; using osu.Game.Graphics.UserInterface; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Overlays.SearchableList; using osu.Game.Overlays.Social; using osu.Game.Users; using osu.Framework.Threading; namespace osu.Game.Overlays { public class SocialOverlay : SearchableListOverlay<SocialTab, SocialSortCriteria, SortDirection>, IOnlineComponent { private APIAccess api; private readonly LoadingAnimation loading; private FillFlowContainer<SocialPanel> panels; protected override Color4 BackgroundColour => OsuColour.FromHex(@"60284b"); protected override Color4 TrianglesColourLight => OsuColour.FromHex(@"672b51"); protected override Color4 TrianglesColourDark => OsuColour.FromHex(@"5c2648"); protected override SearchableListHeader<SocialTab> CreateHeader() => new Header(); protected override SearchableListFilterControl<SocialSortCriteria, SortDirection> CreateFilterControl() => new FilterControl(); private IEnumerable<User> users; public IEnumerable<User> Users { get => users; set { if (users?.Equals(value) ?? false) return; users = value?.ToList(); } } public SocialOverlay() { Waves.FirstWaveColour = OsuColour.FromHex(@"cb5fa0"); Waves.SecondWaveColour = OsuColour.FromHex(@"b04384"); Waves.ThirdWaveColour = OsuColour.FromHex(@"9b2b6e"); Waves.FourthWaveColour = OsuColour.FromHex(@"6d214d"); Add(loading = new LoadingAnimation()); Filter.Search.Current.ValueChanged += text => { if (!string.IsNullOrEmpty(text.NewValue)) { // force searching in players until searching for friends is supported Header.Tabs.Current.Value = SocialTab.AllPlayers; if (Filter.Tabs.Current.Value != SocialSortCriteria.Rank) Filter.Tabs.Current.Value = SocialSortCriteria.Rank; } }; Header.Tabs.Current.ValueChanged += _ => Scheduler.AddOnce(updateSearch); Filter.Tabs.Current.ValueChanged += _ => Scheduler.AddOnce(updateSearch); Filter.DisplayStyleControl.DisplayStyle.ValueChanged += style => recreatePanels(style.NewValue); Filter.DisplayStyleControl.Dropdown.Current.ValueChanged += _ => Scheduler.AddOnce(updateSearch); currentQuery.ValueChanged += query => { queryChangedDebounce?.Cancel(); if (string.IsNullOrEmpty(query.NewValue)) Scheduler.AddOnce(updateSearch); else queryChangedDebounce = Scheduler.AddDelayed(updateSearch, 500); }; currentQuery.BindTo(Filter.Search.Current); } [BackgroundDependencyLoader] private void load(APIAccess api) { this.api = api; api.Register(this); } private void recreatePanels(PanelDisplayStyle displayStyle) { clearPanels(); if (Users == null) return; var newPanels = new FillFlowContainer<SocialPanel> { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Spacing = new Vector2(10f), Margin = new MarginPadding { Top = 10 }, ChildrenEnumerable = Users.Select(u => { SocialPanel panel; switch (displayStyle) { case PanelDisplayStyle.Grid: panel = new SocialGridPanel(u) { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre }; break; default: panel = new SocialListPanel(u); break; } panel.Status.BindTo(u.Status); return panel; }) }; LoadComponentAsync(newPanels, f => { if (panels != null) ScrollFlow.Remove(panels); ScrollFlow.Add(panels = newPanels); }); } private APIRequest getUsersRequest; private readonly Bindable<string> currentQuery = new Bindable<string>(); private ScheduledDelegate queryChangedDebounce; private void updateSearch() { queryChangedDebounce?.Cancel(); if (!IsLoaded) return; Users = null; clearPanels(); loading.Hide(); getUsersRequest?.Cancel(); if (api?.IsLoggedIn != true) return; switch (Header.Tabs.Current.Value) { case SocialTab.Friends: var friendRequest = new GetFriendsRequest(); // TODO filter arguments? friendRequest.Success += updateUsers; api.Queue(getUsersRequest = friendRequest); break; default: var userRequest = new GetUsersRequest(); // TODO filter arguments! userRequest.Success += response => updateUsers(response.Select(r => r.User)); api.Queue(getUsersRequest = userRequest); break; } loading.Show(); } private void updateUsers(IEnumerable<User> newUsers) { Users = newUsers; loading.Hide(); recreatePanels(Filter.DisplayStyleControl.DisplayStyle.Value); } private void clearPanels() { if (panels != null) { panels.Expire(); panels = null; } } public void APIStateChanged(APIAccess api, APIState state) { switch (state) { case APIState.Online: Scheduler.AddOnce(updateSearch); break; default: Users = null; clearPanels(); break; } } } public enum SortDirection { Ascending, Descending } }
// I dont take no real credit here, all i did is add the jeep and adminvehicles together and tweek it down to loading a model for basic usage // AdminVehicle // // for spawn purposes // /////////////////////// function servercmdPlant(%client,%mName,%mScale) { %raycast = containerRayCast(%client.player.getEyePoint(),vectorAdd(vectorScale(vectorNormalize(%client.player.getEyeVector()),10),%client.player.getEyePoint()),$TypeMasks::TerrainObjectType,%client.player); if(!isObject(firstWord(%raycast))) return; %pos = posFromRaycast(%raycast); if(%mScale $= "") %mScale = "0.1"; %DataBlock = "VFM_" @ strlwr(%mName); %client.ModelPlacement[%client.ModelCount++] = new WheeledVehicle() { datablock = %DataBlock; isAdminVehicle = true; creationTime = getSimTime(); }; %client.ModelPlacement[%client.ModelCount].setTransform(%pos); %client.ModelPlacement[%client.ModelCount].setScale(%mScale SPC %mScale SPC %mScale); %client.GrowCrops("1"); messageClient(%client,'',"\c6Model Request \c3" @ %client.ModelCount @ "\c6, has been \c2created"); } function servercmdplantsize(%client,%mNum, %mScale,%speed) { %client.ModelPlacement[%mNum].setscale(%mScale SPC %mScale SPC %mScale); messageClient(%client,'',"\c3" @ %client.ModelPlacement[%mNum].getDatablock().UIName @ " \c6scale changed to \c3" @ %mScale); } function servercmdGrowSpeed(%client,%speed) { %client.growCrops(%speed); } function GameConnection::growCrops(%this,%speed) { if(%speed>10 || %speed $= "") %speed = "10"; if(isObject(%this.stopWatch)) cancel(%this.stopWatch); // grow! for(%pl=0;%pl<%this.ModelCount;%pl++) { %XYZ = %this.ModelPlacement[%pl].getDatablock().fullSize; if(%this.ModelPlacement[%pl].scale !$= %XYZ SPC %XYZ SPC %XYZ) { %scale = %this.ModelPlacement[%pl].scale; %this.ModelPlacement[%pl].setScale(getWord(%scale,0)+0.1 SPC getWord(%scale,1)+0.1 SPC getWord(%scale,2)+0.1); } } if(isObject(%this.ModelPlacement[1])) %this.stopWatch = %this.schedule(1000/%speed,"growCrops",%speed); } // Vehicle Datablocks // /////////////////////// datablock WheeledVehicleData(VFM_Wheat) { category = "Vehicles"; displayName = " "; uiName = "Wheat"; shapeFile = "./shapes/wheat.dts"; // Poof emap = true; minMountDist = 1; fullSize = 1.5; numMountPoints = 0; maxDamage = 30.00; destroyedLevel = 30.00; // speedDamageScale = 1.04; collDamageThresholdVel = 20.0; collDamageMultiplier = 0.02; massCenter = "0 0 0"; useEyePoint = false; numWheels = 0; // Rigid Body mass = 0; density = 1; drag = 3; bodyFriction = 0.6; bodyRestitution = 0.6; minImpactSpeed = 10; // Impacts over this invoke the script callback softImpactSpeed = 10; // Play SoftImpact Sound hardImpactSpeed = 15; // Play HardImpact Sound groundImpactMinSpeed = 10.0; // Engine engineTorque = 12000; //4000; // Engine power engineBrake = 2000; // Braking when throttle is 0 brakeTorque = 50000; // When brakes are applied maxWheelSpeed = 30; // Engine scale by current speed / max speed rollForce = 900; yawForce = 600; pitchForce = 1000; rotationalDrag = 0.2; // Energy maxEnergy = 100; jetForce = 3000; minJetEnergy = 30; jetEnergyDrain = 2; // Sounds // jetSound = ScoutThrustSound; //engineSound = idleSound; //squealSound = skidSound; softImpactSound = slowImpactSound; hardImpactSound = fastImpactSound; //wheelImpactSound = slowImpactSound; justcollided = 0; lookUpLimit = 0.65; lookDownLimit = 0; paintable = true; }; datablock WheeledVehicleData(VFM_turnip) { category = "Vehicles"; displayName = " "; uiName = "Turnip"; shapeFile = "./shapes/turnip.dts"; // Poof emap = true; minMountDist = 1; fullSize = 1.1; numMountPoints = 0; maxDamage = 30.00; destroyedLevel = 30.00; // speedDamageScale = 1.04; collDamageThresholdVel = 20.0; collDamageMultiplier = 0.02; massCenter = "0 0 0"; useEyePoint = false; numWheels = 0; // Rigid Body mass = 0; density = 1; drag = 3; bodyFriction = 0.6; bodyRestitution = 0.6; minImpactSpeed = 10; // Impacts over this invoke the script callback softImpactSpeed = 10; // Play SoftImpact Sound hardImpactSpeed = 15; // Play HardImpact Sound groundImpactMinSpeed = 10.0; // Engine engineTorque = 12000; //4000; // Engine power engineBrake = 2000; // Braking when throttle is 0 brakeTorque = 50000; // When brakes are applied maxWheelSpeed = 30; // Engine scale by current speed / max speed rollForce = 900; yawForce = 600; pitchForce = 1000; rotationalDrag = 0.2; // Energy maxEnergy = 100; jetForce = 3000; minJetEnergy = 30; jetEnergyDrain = 2; // Sounds // jetSound = ScoutThrustSound; //engineSound = idleSound; //squealSound = skidSound; softImpactSound = slowImpactSound; hardImpactSound = fastImpactSound; //wheelImpactSound = slowImpactSound; justcollided = 0; lookUpLimit = 0.65; lookDownLimit = 0; paintable = true; }; datablock WheeledVehicleData(VFM_carrot) { category = "Vehicles"; displayName = " "; uiName = "Carrot"; shapeFile = "./shapes/carrot.dts"; // Poof emap = true; minMountDist = 1; fullSize = 0.8; numMountPoints = 0; maxDamage = 30.00; destroyedLevel = 30.00; // speedDamageScale = 1.04; collDamageThresholdVel = 20.0; collDamageMultiplier = 0.02; massCenter = "0 0 0"; useEyePoint = false; numWheels = 0; // Rigid Body mass = 0; density = 1; drag = 3; bodyFriction = 0.6; bodyRestitution = 0.6; minImpactSpeed = 10; // Impacts over this invoke the script callback softImpactSpeed = 10; // Play SoftImpact Sound hardImpactSpeed = 15; // Play HardImpact Sound groundImpactMinSpeed = 10.0; // Engine engineTorque = 12000; //4000; // Engine power engineBrake = 2000; // Braking when throttle is 0 brakeTorque = 50000; // When brakes are applied maxWheelSpeed = 30; // Engine scale by current speed / max speed rollForce = 900; yawForce = 600; pitchForce = 1000; rotationalDrag = 0.2; // Energy maxEnergy = 100; jetForce = 3000; minJetEnergy = 30; jetEnergyDrain = 2; // Sounds // jetSound = ScoutThrustSound; //engineSound = idleSound; //squealSound = skidSound; softImpactSound = slowImpactSound; hardImpactSound = fastImpactSound; //wheelImpactSound = slowImpactSound; justcollided = 0; lookUpLimit = 0.65; lookDownLimit = 0; paintable = true; }; datablock WheeledVehicleData(VFM_herb) { category = "Vehicles"; displayName = " "; uiName = "Herb"; shapeFile = "./shapes/herb.dts"; // Poof emap = true; minMountDist = 1; fullSize = 1; numMountPoints = 0; maxDamage = 30.00; destroyedLevel = 30.00; // speedDamageScale = 1.04; collDamageThresholdVel = 20.0; collDamageMultiplier = 0.02; massCenter = "0 0 0"; useEyePoint = false; numWheels = 0; // Rigid Body mass = 0; density = 1; drag = 3; bodyFriction = 0.6; bodyRestitution = 0.6; minImpactSpeed = 10; // Impacts over this invoke the script callback softImpactSpeed = 10; // Play SoftImpact Sound hardImpactSpeed = 15; // Play HardImpact Sound groundImpactMinSpeed = 10.0; // Engine engineTorque = 12000; //4000; // Engine power engineBrake = 2000; // Braking when throttle is 0 brakeTorque = 50000; // When brakes are applied maxWheelSpeed = 30; // Engine scale by current speed / max speed rollForce = 900; yawForce = 600; pitchForce = 1000; rotationalDrag = 0.2; // Energy maxEnergy = 100; jetForce = 3000; minJetEnergy = 30; jetEnergyDrain = 2; // Sounds // jetSound = ScoutThrustSound; //engineSound = idleSound; //squealSound = skidSound; softImpactSound = slowImpactSound; hardImpactSound = fastImpactSound; //wheelImpactSound = slowImpactSound; justcollided = 0; lookUpLimit = 0.65; lookDownLimit = 0; paintable = true; }; datablock WheeledVehicleData(VFM_tomato) { category = "Vehicles"; displayName = " "; uiName = "Tomato"; shapeFile = "./shapes/tomato.dts"; // Poof emap = true; minMountDist = 1; fullSize = 2; numMountPoints = 0; maxDamage = 30.00; destroyedLevel = 30.00; // speedDamageScale = 1.04; collDamageThresholdVel = 20.0; collDamageMultiplier = 0.02; massCenter = "0 0 0"; useEyePoint = false; numWheels = 0; // Rigid Body mass = 0; density = 1; drag = 3; bodyFriction = 0.6; bodyRestitution = 0.6; minImpactSpeed = 10; // Impacts over this invoke the script callback softImpactSpeed = 10; // Play SoftImpact Sound hardImpactSpeed = 15; // Play HardImpact Sound groundImpactMinSpeed = 10.0; // Engine engineTorque = 12000; //4000; // Engine power engineBrake = 2000; // Braking when throttle is 0 brakeTorque = 50000; // When brakes are applied maxWheelSpeed = 30; // Engine scale by current speed / max speed rollForce = 900; yawForce = 600; pitchForce = 1000; rotationalDrag = 0.2; // Energy maxEnergy = 100; jetForce = 3000; minJetEnergy = 30; jetEnergyDrain = 2; // Sounds // jetSound = ScoutThrustSound; //engineSound = idleSound; //squealSound = skidSound; softImpactSound = slowImpactSound; hardImpactSound = fastImpactSound; //wheelImpactSound = slowImpactSound; justcollided = 0; lookUpLimit = 0.65; lookDownLimit = 0; paintable = true; };
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using LibGit2Sharp.Core; using LibGit2Sharp.Core.Handles; namespace LibGit2Sharp { /// <summary> /// Provides methods to directly work against the Git object database /// without involving the index nor the working directory. /// </summary> public class ObjectDatabase : IEnumerable<GitObject> { private readonly Repository repo; private readonly ObjectDatabaseHandle handle; /// <summary> /// Needed for mocking purposes. /// </summary> protected ObjectDatabase() { } internal ObjectDatabase(Repository repo, bool isInMemory) { this.repo = repo; if (isInMemory) { handle = Proxy.git_odb_new(); Proxy.git_repository_set_odb(repo.Handle, handle.AsIntPtr()); } else { handle = Proxy.git_repository_odb(repo.Handle); } repo.RegisterForCleanup(handle); } #region Implementation of IEnumerable /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>An <see cref="IEnumerator{T}"/> object that can be used to iterate through the collection.</returns> public virtual IEnumerator<GitObject> GetEnumerator() { ICollection<ObjectId> oids = Proxy.git_odb_foreach(handle); return oids .Select(gitOid => repo.Lookup<GitObject>(gitOid)) .GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>An <see cref="IEnumerator"/> object that can be used to iterate through the collection.</returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion /// <summary> /// Determines if the given object can be found in the object database. /// </summary> /// <param name="objectId">Identifier of the object being searched for.</param> /// <returns>True if the object has been found; false otherwise.</returns> public virtual bool Contains(ObjectId objectId) { Ensure.ArgumentNotNull(objectId, "objectId"); return Proxy.git_odb_exists(handle, objectId); } /// <summary> /// Retrieves the header of a GitObject from the object database. The header contains the Size /// and Type of the object. Note that most backends do not support reading only the header /// of an object, so the whole object will be read and then size would be returned. /// </summary> /// <param name="objectId">Object Id of the queried object</param> /// <returns>GitObjectMetadata object instance containg object header information</returns> public virtual GitObjectMetadata RetrieveObjectMetadata(ObjectId objectId) { Ensure.ArgumentNotNull(objectId, "objectId"); return Proxy.git_odb_read_header(handle, objectId); } /// <summary> /// Inserts a <see cref="Blob"/> into the object database, created from the content of a file. /// </summary> /// <param name="path">Path to the file to create the blob from. A relative path is allowed to /// be passed if the <see cref="Repository"/> is a standard, non-bare, repository. The path /// will then be considered as a path relative to the root of the working directory.</param> /// <returns>The created <see cref="Blob"/>.</returns> public virtual Blob CreateBlob(string path) { Ensure.ArgumentNotNullOrEmptyString(path, "path"); if (repo.Info.IsBare && !Path.IsPathRooted(path)) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Cannot create a blob in a bare repository from a relative path ('{0}').", path)); } ObjectId id = Path.IsPathRooted(path) ? Proxy.git_blob_create_fromdisk(repo.Handle, path) : Proxy.git_blob_create_fromfile(repo.Handle, path); return repo.Lookup<Blob>(id); } /// <summary> /// Adds the provided backend to the object database with the specified priority. /// <para> /// If the provided backend implements <see cref="IDisposable"/>, the <see cref="IDisposable.Dispose"/> /// method will be honored and invoked upon the disposal of the repository. /// </para> /// </summary> /// <param name="backend">The backend to add</param> /// <param name="priority">The priority at which libgit2 should consult this backend (higher values are consulted first)</param> public virtual void AddBackend(OdbBackend backend, int priority) { Ensure.ArgumentNotNull(backend, "backend"); Ensure.ArgumentConformsTo(priority, s => s > 0, "priority"); Proxy.git_odb_add_backend(handle, backend.GitOdbBackendPointer, priority); } private class Processor { private readonly Stream stream; private readonly long? numberOfBytesToConsume; private int totalNumberOfReadBytes; public Processor(Stream stream, long? numberOfBytesToConsume) { this.stream = stream; this.numberOfBytesToConsume = numberOfBytesToConsume; } public int Provider(IntPtr content, int max_length, IntPtr data) { var local = new byte[max_length]; int bytesToRead = max_length; if (numberOfBytesToConsume.HasValue) { long totalRemainingBytesToRead = numberOfBytesToConsume.Value - totalNumberOfReadBytes; if (totalRemainingBytesToRead < max_length) { bytesToRead = totalRemainingBytesToRead > int.MaxValue ? int.MaxValue : (int)totalRemainingBytesToRead; } } if (bytesToRead == 0) { return 0; } int numberOfReadBytes = stream.Read(local, 0, bytesToRead); if (numberOfBytesToConsume.HasValue && numberOfReadBytes == 0) { return (int)GitErrorCode.User; } totalNumberOfReadBytes += numberOfReadBytes; Marshal.Copy(local, 0, content, numberOfReadBytes); return numberOfReadBytes; } } /// <summary> /// Writes an object to the object database. /// </summary> /// <param name="data">The contents of the object</param> /// <typeparam name="T">The type of object to write</typeparam> public virtual ObjectId Write<T>(byte[] data) where T : GitObject { return Proxy.git_odb_write(handle, data, GitObject.TypeToKindMap[typeof(T)]); } /// <summary> /// Writes an object to the object database. /// </summary> /// <param name="stream">The contents of the object</param> /// <param name="numberOfBytesToConsume">The number of bytes to consume from the stream</param> /// <typeparam name="T">The type of object to write</typeparam> public virtual ObjectId Write<T>(Stream stream, long numberOfBytesToConsume) where T : GitObject { Ensure.ArgumentNotNull(stream, "stream"); if (!stream.CanRead) { throw new ArgumentException("The stream cannot be read from.", "stream"); } using (var odbStream = Proxy.git_odb_open_wstream(handle, numberOfBytesToConsume, GitObjectType.Blob)) { var buffer = new byte[4 * 1024]; long totalRead = 0; while (totalRead < numberOfBytesToConsume) { long left = numberOfBytesToConsume - totalRead; int toRead = left < buffer.Length ? (int)left : buffer.Length; var read = stream.Read(buffer, 0, toRead); if (read == 0) { throw new EndOfStreamException("The stream ended unexpectedly"); } Proxy.git_odb_stream_write(odbStream, buffer, read); totalRead += read; } return Proxy.git_odb_stream_finalize_write(odbStream); } } /// <summary> /// Inserts a <see cref="Blob"/> into the object database, created from the content of a stream. /// <para>Optionally, git filters will be applied to the content before storing it.</para> /// </summary> /// <param name="stream">The stream from which will be read the content of the blob to be created.</param> /// <returns>The created <see cref="Blob"/>.</returns> public virtual Blob CreateBlob(Stream stream) { return CreateBlob(stream, null, null); } /// <summary> /// Inserts a <see cref="Blob"/> into the object database, created from the content of a stream. /// <para>Optionally, git filters will be applied to the content before storing it.</para> /// </summary> /// <param name="stream">The stream from which will be read the content of the blob to be created.</param> /// <param name="hintpath">The hintpath is used to determine what git filters should be applied to the object before it can be placed to the object database.</param> /// <returns>The created <see cref="Blob"/>.</returns> public virtual Blob CreateBlob(Stream stream, string hintpath) { return CreateBlob(stream, hintpath, null); } /// <summary> /// Inserts a <see cref="Blob"/> into the object database, created from the content of a stream. /// <para>Optionally, git filters will be applied to the content before storing it.</para> /// </summary> /// <param name="stream">The stream from which will be read the content of the blob to be created.</param> /// <param name="hintpath">The hintpath is used to determine what git filters should be applied to the object before it can be placed to the object database.</param> /// <param name="numberOfBytesToConsume">The number of bytes to consume from the stream.</param> /// <returns>The created <see cref="Blob"/>.</returns> public virtual Blob CreateBlob(Stream stream, string hintpath, long numberOfBytesToConsume) { return CreateBlob(stream, hintpath, (long?)numberOfBytesToConsume); } private unsafe Blob CreateBlob(Stream stream, string hintpath, long? numberOfBytesToConsume) { Ensure.ArgumentNotNull(stream, "stream"); // there's no need to buffer the file for filtering, so simply use a stream if (hintpath == null && numberOfBytesToConsume.HasValue) { return CreateBlob(stream, numberOfBytesToConsume.Value); } if (!stream.CanRead) { throw new ArgumentException("The stream cannot be read from.", "stream"); } IntPtr writestream_ptr = Proxy.git_blob_create_fromstream(repo.Handle, hintpath); GitWriteStream writestream = Marshal.PtrToStructure<GitWriteStream>(writestream_ptr); try { var buffer = new byte[4 * 1024]; long totalRead = 0; int read = 0; while (true) { int toRead = numberOfBytesToConsume.HasValue ? (int)Math.Min(numberOfBytesToConsume.Value - totalRead, (long)buffer.Length) : buffer.Length; if (toRead > 0) { read = (toRead > 0) ? stream.Read(buffer, 0, toRead) : 0; } if (read == 0) { break; } fixed (byte* buffer_ptr = buffer) { writestream.write(writestream_ptr, (IntPtr)buffer_ptr, (UIntPtr)read); } totalRead += read; } if (numberOfBytesToConsume.HasValue && totalRead < numberOfBytesToConsume.Value) { throw new EndOfStreamException("The stream ended unexpectedly"); } } catch(Exception e) { writestream.free(writestream_ptr); throw e; } ObjectId id = Proxy.git_blob_create_fromstream_commit(writestream_ptr); return repo.Lookup<Blob>(id); } /// <summary> /// Inserts a <see cref="Blob"/> into the object database created from the content of the stream. /// </summary> /// <param name="stream">The stream from which will be read the content of the blob to be created.</param> /// <param name="numberOfBytesToConsume">Number of bytes to consume from the stream.</param> /// <returns>The created <see cref="Blob"/>.</returns> public virtual Blob CreateBlob(Stream stream, long numberOfBytesToConsume) { var id = Write<Blob>(stream, numberOfBytesToConsume); return repo.Lookup<Blob>(id); } /// <summary> /// Inserts a <see cref="Tree"/> into the object database, created from a <see cref="TreeDefinition"/>. /// </summary> /// <param name="treeDefinition">The <see cref="TreeDefinition"/>.</param> /// <returns>The created <see cref="Tree"/>.</returns> public virtual Tree CreateTree(TreeDefinition treeDefinition) { Ensure.ArgumentNotNull(treeDefinition, "treeDefinition"); return treeDefinition.Build(repo); } /// <summary> /// Inserts a <see cref="Tree"/> into the object database, created from the <see cref="Index"/>. /// <para> /// It recursively creates tree objects for each of the subtrees stored in the index, but only returns the root tree. /// </para> /// <para> /// The index must be fully merged. /// </para> /// </summary> /// <param name="index">The <see cref="Index"/>.</param> /// <returns>The created <see cref="Tree"/>. This can be used e.g. to create a <see cref="Commit"/>.</returns> public virtual Tree CreateTree(Index index) { Ensure.ArgumentNotNull(index, "index"); var treeId = Proxy.git_index_write_tree(index.Handle); return this.repo.Lookup<Tree>(treeId); } /// <summary> /// Inserts a <see cref="Commit"/> into the object database, referencing an existing <see cref="Tree"/>. /// <para> /// Prettifing the message includes: /// * Removing empty lines from the beginning and end. /// * Removing trailing spaces from every line. /// * Turning multiple consecutive empty lines between paragraphs into just one empty line. /// * Ensuring the commit message ends with a newline. /// * Removing every line starting with "#". /// </para> /// </summary> /// <param name="author">The <see cref="Signature"/> of who made the change.</param> /// <param name="committer">The <see cref="Signature"/> of who added the change to the repository.</param> /// <param name="message">The description of why a change was made to the repository.</param> /// <param name="tree">The <see cref="Tree"/> of the <see cref="Commit"/> to be created.</param> /// <param name="parents">The parents of the <see cref="Commit"/> to be created.</param> /// <param name="prettifyMessage">True to prettify the message, or false to leave it as is.</param> /// <returns>The created <see cref="Commit"/>.</returns> public virtual Commit CreateCommit(Signature author, Signature committer, string message, Tree tree, IEnumerable<Commit> parents, bool prettifyMessage) { return CreateCommit(author, committer, message, tree, parents, prettifyMessage, null); } /// <summary> /// Inserts a <see cref="Commit"/> into the object database, referencing an existing <see cref="Tree"/>. /// <para> /// Prettifing the message includes: /// * Removing empty lines from the beginning and end. /// * Removing trailing spaces from every line. /// * Turning multiple consecutive empty lines between paragraphs into just one empty line. /// * Ensuring the commit message ends with a newline. /// * Removing every line starting with the <paramref name="commentChar"/>. /// </para> /// </summary> /// <param name="author">The <see cref="Signature"/> of who made the change.</param> /// <param name="committer">The <see cref="Signature"/> of who added the change to the repository.</param> /// <param name="message">The description of why a change was made to the repository.</param> /// <param name="tree">The <see cref="Tree"/> of the <see cref="Commit"/> to be created.</param> /// <param name="parents">The parents of the <see cref="Commit"/> to be created.</param> /// <param name="prettifyMessage">True to prettify the message, or false to leave it as is.</param> /// <param name="commentChar">When non null, lines starting with this character will be stripped if prettifyMessage is true.</param> /// <returns>The created <see cref="Commit"/>.</returns> public virtual Commit CreateCommit(Signature author, Signature committer, string message, Tree tree, IEnumerable<Commit> parents, bool prettifyMessage, char? commentChar) { Ensure.ArgumentNotNull(message, "message"); Ensure.ArgumentDoesNotContainZeroByte(message, "message"); Ensure.ArgumentNotNull(author, "author"); Ensure.ArgumentNotNull(committer, "committer"); Ensure.ArgumentNotNull(tree, "tree"); Ensure.ArgumentNotNull(parents, "parents"); if (prettifyMessage) { message = Proxy.git_message_prettify(message, commentChar); } GitOid[] parentIds = parents.Select(p => p.Id.Oid).ToArray(); ObjectId commitId = Proxy.git_commit_create(repo.Handle, null, author, committer, message, tree, parentIds); Commit commit = repo.Lookup<Commit>(commitId); Ensure.GitObjectIsNotNull(commit, commitId.Sha); return commit; } /// <summary> /// Inserts a <see cref="Commit"/> into the object database after attaching the given signature. /// </summary> /// <param name="commitContent">The raw unsigned commit</param> /// <param name="signature">The signature data </param> /// <param name="field">The header field in the commit in which to store the signature</param> /// <returns>The created <see cref="Commit"/>.</returns> public virtual ObjectId CreateCommitWithSignature(string commitContent, string signature, string field) { return Proxy.git_commit_create_with_signature(repo.Handle, commitContent, signature, field); } /// <summary> /// Inserts a <see cref="Commit"/> into the object database after attaching the given signature. /// <para> /// This overload uses the default header field of "gpgsig" /// </para> /// </summary> /// <param name="commitContent">The raw unsigned commit</param> /// <param name="signature">The signature data </param> /// <returns>The created <see cref="Commit"/>.</returns> public virtual ObjectId CreateCommitWithSignature(string commitContent, string signature) { return Proxy.git_commit_create_with_signature(repo.Handle, commitContent, signature, null); } /// <summary> /// Inserts a <see cref="TagAnnotation"/> into the object database, pointing to a specific <see cref="GitObject"/>. /// </summary> /// <param name="name">The name.</param> /// <param name="target">The <see cref="GitObject"/> being pointed at.</param> /// <param name="tagger">The tagger.</param> /// <param name="message">The message.</param> /// <returns>The created <see cref="TagAnnotation"/>.</returns> public virtual TagAnnotation CreateTagAnnotation(string name, GitObject target, Signature tagger, string message) { Ensure.ArgumentNotNullOrEmptyString(name, "name"); Ensure.ArgumentNotNull(message, "message"); Ensure.ArgumentNotNull(target, "target"); Ensure.ArgumentNotNull(tagger, "tagger"); Ensure.ArgumentDoesNotContainZeroByte(name, "name"); Ensure.ArgumentDoesNotContainZeroByte(message, "message"); string prettifiedMessage = Proxy.git_message_prettify(message, null); ObjectId tagId = Proxy.git_tag_annotation_create(repo.Handle, name, target, tagger, prettifiedMessage); return repo.Lookup<TagAnnotation>(tagId); } /// <summary> /// Create a TAR archive of the given tree. /// </summary> /// <param name="tree">The tree.</param> /// <param name="archivePath">The archive path.</param> public virtual void Archive(Tree tree, string archivePath) { using (var output = new FileStream(archivePath, FileMode.Create)) using (var archiver = new TarArchiver(output)) { Archive(tree, archiver); } } /// <summary> /// Create a TAR archive of the given commit. /// </summary> /// <param name="commit">commit.</param> /// <param name="archivePath">The archive path.</param> public virtual void Archive(Commit commit, string archivePath) { using (var output = new FileStream(archivePath, FileMode.Create)) using (var archiver = new TarArchiver(output)) { Archive(commit, archiver); } } /// <summary> /// Archive the given commit. /// </summary> /// <param name="commit">The commit.</param> /// <param name="archiver">The archiver to use.</param> public virtual void Archive(Commit commit, ArchiverBase archiver) { Ensure.ArgumentNotNull(commit, "commit"); Ensure.ArgumentNotNull(archiver, "archiver"); archiver.OrchestrateArchiving(commit.Tree, commit.Id, commit.Committer.When); } /// <summary> /// Archive the given tree. /// </summary> /// <param name="tree">The tree.</param> /// <param name="archiver">The archiver to use.</param> public virtual void Archive(Tree tree, ArchiverBase archiver) { Ensure.ArgumentNotNull(tree, "tree"); Ensure.ArgumentNotNull(archiver, "archiver"); archiver.OrchestrateArchiving(tree, null, DateTimeOffset.UtcNow); } /// <summary> /// Returns the merge base (best common ancestor) of the given commits /// and the distance between each of these commits and this base. /// </summary> /// <param name="one">The <see cref="Commit"/> being used as a reference.</param> /// <param name="another">The <see cref="Commit"/> being compared against <paramref name="one"/>.</param> /// <returns>A instance of <see cref="HistoryDivergence"/>.</returns> public virtual HistoryDivergence CalculateHistoryDivergence(Commit one, Commit another) { Ensure.ArgumentNotNull(one, "one"); Ensure.ArgumentNotNull(another, "another"); return new HistoryDivergence(repo, one, another); } /// <summary> /// Performs a cherry-pick of <paramref name="cherryPickCommit"/> onto <paramref name="cherryPickOnto"/> commit. /// </summary> /// <param name="cherryPickCommit">The commit to cherry-pick.</param> /// <param name="cherryPickOnto">The commit to cherry-pick onto.</param> /// <param name="mainline">Which commit to consider the parent for the diff when cherry-picking a merge commit.</param> /// <param name="options">The options for the merging in the cherry-pick operation.</param> /// <returns>A result containing a <see cref="Tree"/> if the cherry-pick was successful and a list of <see cref="Conflict"/>s if it is not.</returns> public virtual MergeTreeResult CherryPickCommit(Commit cherryPickCommit, Commit cherryPickOnto, int mainline, MergeTreeOptions options) { Ensure.ArgumentNotNull(cherryPickCommit, "cherryPickCommit"); Ensure.ArgumentNotNull(cherryPickOnto, "cherryPickOnto"); var modifiedOptions = new MergeTreeOptions(); // We throw away the index after looking at the conflicts, so we'll never need the REUC // entries to be there modifiedOptions.SkipReuc = true; if (options != null) { modifiedOptions.FailOnConflict = options.FailOnConflict; modifiedOptions.FindRenames = options.FindRenames; modifiedOptions.MergeFileFavor = options.MergeFileFavor; modifiedOptions.RenameThreshold = options.RenameThreshold; modifiedOptions.TargetLimit = options.TargetLimit; } bool earlyStop; using (var indexHandle = CherryPickCommit(cherryPickCommit, cherryPickOnto, mainline, modifiedOptions, out earlyStop)) { MergeTreeResult cherryPickResult; // Stopped due to FailOnConflict so there's no index or conflict list if (earlyStop) { return new MergeTreeResult(new Conflict[] { }); } if (Proxy.git_index_has_conflicts(indexHandle)) { List<Conflict> conflicts = new List<Conflict>(); Conflict conflict; using (ConflictIteratorHandle iterator = Proxy.git_index_conflict_iterator_new(indexHandle)) { while ((conflict = Proxy.git_index_conflict_next(iterator)) != null) { conflicts.Add(conflict); } } cherryPickResult = new MergeTreeResult(conflicts); } else { var treeId = Proxy.git_index_write_tree_to(indexHandle, repo.Handle); cherryPickResult = new MergeTreeResult(this.repo.Lookup<Tree>(treeId)); } return cherryPickResult; } } /// <summary> /// Calculates the current shortest abbreviated <see cref="ObjectId"/> /// string representation for a <see cref="GitObject"/>. /// </summary> /// <param name="gitObject">The <see cref="GitObject"/> which identifier should be shortened.</param> /// <returns>A short string representation of the <see cref="ObjectId"/>.</returns> public virtual string ShortenObjectId(GitObject gitObject) { var shortSha = Proxy.git_object_short_id(repo.Handle, gitObject.Id); return shortSha; } /// <summary> /// Calculates the current shortest abbreviated <see cref="ObjectId"/> /// string representation for a <see cref="GitObject"/>. /// </summary> /// <param name="gitObject">The <see cref="GitObject"/> which identifier should be shortened.</param> /// <param name="minLength">Minimum length of the shortened representation.</param> /// <returns>A short string representation of the <see cref="ObjectId"/>.</returns> public virtual string ShortenObjectId(GitObject gitObject, int minLength) { Ensure.ArgumentNotNull(gitObject, "gitObject"); if (minLength <= 0 || minLength > ObjectId.HexSize) { throw new ArgumentOutOfRangeException("minLength", minLength, string.Format("Expected value should be greater than zero and less than or equal to {0}.", ObjectId.HexSize)); } string shortSha = Proxy.git_object_short_id(repo.Handle, gitObject.Id); if (shortSha == null) { throw new LibGit2SharpException("Unable to abbreviate SHA-1 value for GitObject " + gitObject.Id); } if (minLength <= shortSha.Length) { return shortSha; } return gitObject.Sha.Substring(0, minLength); } /// <summary> /// Returns whether merging <paramref name="one"/> into <paramref name="another"/> /// would result in merge conflicts. /// </summary> /// <param name="one">The commit wrapping the base tree to merge into.</param> /// <param name="another">The commit wrapping the tree to merge into <paramref name="one"/>.</param> /// <returns>True if the merge does not result in a conflict, false otherwise.</returns> public virtual bool CanMergeWithoutConflict(Commit one, Commit another) { Ensure.ArgumentNotNull(one, "one"); Ensure.ArgumentNotNull(another, "another"); var opts = new MergeTreeOptions() { SkipReuc = true, FailOnConflict = true, }; var result = repo.ObjectDatabase.MergeCommits(one, another, opts); return (result.Status == MergeTreeStatus.Succeeded); } /// <summary> /// Find the best possible merge base given two <see cref="Commit"/>s. /// </summary> /// <param name="first">The first <see cref="Commit"/>.</param> /// <param name="second">The second <see cref="Commit"/>.</param> /// <returns>The merge base or null if none found.</returns> public virtual Commit FindMergeBase(Commit first, Commit second) { Ensure.ArgumentNotNull(first, "first"); Ensure.ArgumentNotNull(second, "second"); return FindMergeBase(new[] { first, second }, MergeBaseFindingStrategy.Standard); } /// <summary> /// Find the best possible merge base given two or more <see cref="Commit"/> according to the <see cref="MergeBaseFindingStrategy"/>. /// </summary> /// <param name="commits">The <see cref="Commit"/>s for which to find the merge base.</param> /// <param name="strategy">The strategy to leverage in order to find the merge base.</param> /// <returns>The merge base or null if none found.</returns> public virtual Commit FindMergeBase(IEnumerable<Commit> commits, MergeBaseFindingStrategy strategy) { Ensure.ArgumentNotNull(commits, "commits"); ObjectId id; List<GitOid> ids = new List<GitOid>(8); int count = 0; foreach (var commit in commits) { if (commit == null) { throw new ArgumentException("Enumerable contains null at position: " + count.ToString(CultureInfo.InvariantCulture), "commits"); } ids.Add(commit.Id.Oid); count++; } if (count < 2) { throw new ArgumentException("The enumerable must contains at least two commits.", "commits"); } switch (strategy) { case MergeBaseFindingStrategy.Standard: id = Proxy.git_merge_base_many(repo.Handle, ids.ToArray()); break; case MergeBaseFindingStrategy.Octopus: id = Proxy.git_merge_base_octopus(repo.Handle, ids.ToArray()); break; default: throw new ArgumentException("", "strategy"); } return id == null ? null : repo.Lookup<Commit>(id); } /// <summary> /// Perform a three-way merge of two commits, looking up their /// commit ancestor. The returned <see cref="MergeTreeResult"/> will contain the results /// of the merge and can be examined for conflicts. /// </summary> /// <param name="ours">The first commit</param> /// <param name="theirs">The second commit</param> /// <param name="options">The <see cref="MergeTreeOptions"/> controlling the merge</param> /// <returns>The <see cref="MergeTreeResult"/> containing the merged trees and any conflicts</returns> public virtual MergeTreeResult MergeCommits(Commit ours, Commit theirs, MergeTreeOptions options) { Ensure.ArgumentNotNull(ours, "ours"); Ensure.ArgumentNotNull(theirs, "theirs"); var modifiedOptions = new MergeTreeOptions(); // We throw away the index after looking at the conflicts, so we'll never need the REUC // entries to be there modifiedOptions.SkipReuc = true; if (options != null) { modifiedOptions.FailOnConflict = options.FailOnConflict; modifiedOptions.FindRenames = options.FindRenames; modifiedOptions.IgnoreWhitespaceChange = options.IgnoreWhitespaceChange; modifiedOptions.MergeFileFavor = options.MergeFileFavor; modifiedOptions.RenameThreshold = options.RenameThreshold; modifiedOptions.TargetLimit = options.TargetLimit; } bool earlyStop; using (var indexHandle = MergeCommits(ours, theirs, modifiedOptions, out earlyStop)) { MergeTreeResult mergeResult; // Stopped due to FailOnConflict so there's no index or conflict list if (earlyStop) { return new MergeTreeResult(new Conflict[] { }); } if (Proxy.git_index_has_conflicts(indexHandle)) { List<Conflict> conflicts = new List<Conflict>(); Conflict conflict; using (ConflictIteratorHandle iterator = Proxy.git_index_conflict_iterator_new(indexHandle)) { while ((conflict = Proxy.git_index_conflict_next(iterator)) != null) { conflicts.Add(conflict); } } mergeResult = new MergeTreeResult(conflicts); } else { var treeId = Proxy.git_index_write_tree_to(indexHandle, repo.Handle); mergeResult = new MergeTreeResult(this.repo.Lookup<Tree>(treeId)); } return mergeResult; } } /// <summary> /// Packs all the objects in the <see cref="ObjectDatabase"/> and write a pack (.pack) and index (.idx) files for them. /// </summary> /// <param name="options">Packing options</param> /// This method will invoke the default action of packing all objects in an arbitrary order. /// <returns>Packing results</returns> public virtual PackBuilderResults Pack(PackBuilderOptions options) { return InternalPack(options, builder => { foreach (GitObject obj in repo.ObjectDatabase) { builder.Add(obj.Id); } }); } /// <summary> /// Packs objects in the <see cref="ObjectDatabase"/> chosen by the packDelegate action /// and write a pack (.pack) and index (.idx) files for them /// </summary> /// <param name="options">Packing options</param> /// <param name="packDelegate">Packing action</param> /// <returns>Packing results</returns> public virtual PackBuilderResults Pack(PackBuilderOptions options, Action<PackBuilder> packDelegate) { return InternalPack(options, packDelegate); } /// <summary> /// Perform a three-way merge of two commits, looking up their /// commit ancestor. The returned index will contain the results /// of the merge and can be examined for conflicts. /// </summary> /// <param name="ours">The first tree</param> /// <param name="theirs">The second tree</param> /// <param name="options">The <see cref="MergeTreeOptions"/> controlling the merge</param> /// <returns>The <see cref="TransientIndex"/> containing the merged trees and any conflicts, or null if the merge stopped early due to conflicts. /// The index must be disposed by the caller.</returns> public virtual TransientIndex MergeCommitsIntoIndex(Commit ours, Commit theirs, MergeTreeOptions options) { Ensure.ArgumentNotNull(ours, "ours"); Ensure.ArgumentNotNull(theirs, "theirs"); options = options ?? new MergeTreeOptions(); bool earlyStop; var indexHandle = MergeCommits(ours, theirs, options, out earlyStop); if (earlyStop) { if (indexHandle != null) { indexHandle.Dispose(); } return null; } var result = new TransientIndex(indexHandle, repo); return result; } /// <summary> /// Performs a cherry-pick of <paramref name="cherryPickCommit"/> onto <paramref name="cherryPickOnto"/> commit. /// </summary> /// <param name="cherryPickCommit">The commit to cherry-pick.</param> /// <param name="cherryPickOnto">The commit to cherry-pick onto.</param> /// <param name="mainline">Which commit to consider the parent for the diff when cherry-picking a merge commit.</param> /// <param name="options">The options for the merging in the cherry-pick operation.</param> /// <returns>The <see cref="TransientIndex"/> containing the cherry-pick result tree and any conflicts, or null if the merge stopped early due to conflicts. /// The index must be disposed by the caller. </returns> public virtual TransientIndex CherryPickCommitIntoIndex(Commit cherryPickCommit, Commit cherryPickOnto, int mainline, MergeTreeOptions options) { Ensure.ArgumentNotNull(cherryPickCommit, "cherryPickCommit"); Ensure.ArgumentNotNull(cherryPickOnto, "cherryPickOnto"); options = options ?? new MergeTreeOptions(); bool earlyStop; var indexHandle = CherryPickCommit(cherryPickCommit, cherryPickOnto, mainline, options, out earlyStop); if (earlyStop) { if (indexHandle != null) { indexHandle.Dispose(); } return null; } var result = new TransientIndex(indexHandle, repo); return result; } /// <summary> /// Perform a three-way merge of two commits, looking up their /// commit ancestor. The returned index will contain the results /// of the merge and can be examined for conflicts. /// </summary> /// <param name="ours">The first tree</param> /// <param name="theirs">The second tree</param> /// <param name="options">The <see cref="MergeTreeOptions"/> controlling the merge</param> /// <param name="earlyStop">True if the merge stopped early due to conflicts</param> /// <returns>The <see cref="IndexHandle"/> containing the merged trees and any conflicts</returns> private IndexHandle MergeCommits(Commit ours, Commit theirs, MergeTreeOptions options, out bool earlyStop) { GitMergeFlag mergeFlags = GitMergeFlag.GIT_MERGE_NORMAL; if (options.SkipReuc) { mergeFlags |= GitMergeFlag.GIT_MERGE_SKIP_REUC; } if (options.FindRenames) { mergeFlags |= GitMergeFlag.GIT_MERGE_FIND_RENAMES; } if (options.FailOnConflict) { mergeFlags |= GitMergeFlag.GIT_MERGE_FAIL_ON_CONFLICT; } var mergeOptions = new GitMergeOpts { Version = 1, MergeFileFavorFlags = options.MergeFileFavor, MergeTreeFlags = mergeFlags, RenameThreshold = (uint)options.RenameThreshold, TargetLimit = (uint)options.TargetLimit, }; using (var oneHandle = Proxy.git_object_lookup(repo.Handle, ours.Id, GitObjectType.Commit)) using (var twoHandle = Proxy.git_object_lookup(repo.Handle, theirs.Id, GitObjectType.Commit)) { var indexHandle = Proxy.git_merge_commits(repo.Handle, oneHandle, twoHandle, mergeOptions, out earlyStop); return indexHandle; } } /// <summary> /// Performs a cherry-pick of <paramref name="cherryPickCommit"/> onto <paramref name="cherryPickOnto"/> commit. /// </summary> /// <param name="cherryPickCommit">The commit to cherry-pick.</param> /// <param name="cherryPickOnto">The commit to cherry-pick onto.</param> /// <param name="mainline">Which commit to consider the parent for the diff when cherry-picking a merge commit.</param> /// <param name="options">The options for the merging in the cherry-pick operation.</param> /// <param name="earlyStop">True if the cherry-pick stopped early due to conflicts</param> /// <returns>The <see cref="IndexHandle"/> containing the cherry-pick result tree and any conflicts</returns> private IndexHandle CherryPickCommit(Commit cherryPickCommit, Commit cherryPickOnto, int mainline, MergeTreeOptions options, out bool earlyStop) { GitMergeFlag mergeFlags = GitMergeFlag.GIT_MERGE_NORMAL; if (options.SkipReuc) { mergeFlags |= GitMergeFlag.GIT_MERGE_SKIP_REUC; } if (options.FindRenames) { mergeFlags |= GitMergeFlag.GIT_MERGE_FIND_RENAMES; } if (options.FailOnConflict) { mergeFlags |= GitMergeFlag.GIT_MERGE_FAIL_ON_CONFLICT; } var mergeOptions = new GitMergeOpts { Version = 1, MergeFileFavorFlags = options.MergeFileFavor, MergeTreeFlags = mergeFlags, RenameThreshold = (uint)options.RenameThreshold, TargetLimit = (uint)options.TargetLimit, }; using (var cherryPickOntoHandle = Proxy.git_object_lookup(repo.Handle, cherryPickOnto.Id, GitObjectType.Commit)) using (var cherryPickCommitHandle = Proxy.git_object_lookup(repo.Handle, cherryPickCommit.Id, GitObjectType.Commit)) { var indexHandle = Proxy.git_cherrypick_commit(repo.Handle, cherryPickCommitHandle, cherryPickOntoHandle, (uint)mainline, mergeOptions, out earlyStop); return indexHandle; } } /// <summary> /// Packs objects in the <see cref="ObjectDatabase"/> and write a pack (.pack) and index (.idx) files for them. /// For internal use only. /// </summary> /// <param name="options">Packing options</param> /// <param name="packDelegate">Packing action</param> /// <returns>Packing results</returns> private PackBuilderResults InternalPack(PackBuilderOptions options, Action<PackBuilder> packDelegate) { Ensure.ArgumentNotNull(options, "options"); Ensure.ArgumentNotNull(packDelegate, "packDelegate"); PackBuilderResults results = new PackBuilderResults(); using (PackBuilder builder = new PackBuilder(repo)) { // set pre-build options builder.SetMaximumNumberOfThreads(options.MaximumNumberOfThreads); // call the provided action packDelegate(builder); // writing the pack and index files builder.Write(options.PackDirectoryPath); // adding the results to the PackBuilderResults object results.WrittenObjectsCount = builder.WrittenObjectsCount; } return results; } /// <summary> /// Performs a revert of <paramref name="revertCommit"/> onto <paramref name="revertOnto"/> commit. /// </summary> /// <param name="revertCommit">The commit to revert.</param> /// <param name="revertOnto">The commit to revert onto.</param> /// <param name="mainline">Which commit to consider the parent for the diff when reverting a merge commit.</param> /// <param name="options">The options for the merging in the revert operation.</param> /// <returns>A result containing a <see cref="Tree"/> if the revert was successful and a list of <see cref="Conflict"/>s if it is not.</returns> public virtual MergeTreeResult RevertCommit(Commit revertCommit, Commit revertOnto, int mainline, MergeTreeOptions options) { Ensure.ArgumentNotNull(revertCommit, "revertCommit"); Ensure.ArgumentNotNull(revertOnto, "revertOnto"); options = options ?? new MergeTreeOptions(); // We throw away the index after looking at the conflicts, so we'll never need the REUC // entries to be there GitMergeFlag mergeFlags = GitMergeFlag.GIT_MERGE_NORMAL | GitMergeFlag.GIT_MERGE_SKIP_REUC; if (options.FindRenames) { mergeFlags |= GitMergeFlag.GIT_MERGE_FIND_RENAMES; } if (options.FailOnConflict) { mergeFlags |= GitMergeFlag.GIT_MERGE_FAIL_ON_CONFLICT; } var opts = new GitMergeOpts { Version = 1, MergeFileFavorFlags = options.MergeFileFavor, MergeTreeFlags = mergeFlags, RenameThreshold = (uint)options.RenameThreshold, TargetLimit = (uint)options.TargetLimit }; bool earlyStop; using (var revertOntoHandle = Proxy.git_object_lookup(repo.Handle, revertOnto.Id, GitObjectType.Commit)) using (var revertCommitHandle = Proxy.git_object_lookup(repo.Handle, revertCommit.Id, GitObjectType.Commit)) using (var indexHandle = Proxy.git_revert_commit(repo.Handle, revertCommitHandle, revertOntoHandle, (uint)mainline, opts, out earlyStop)) { MergeTreeResult revertTreeResult; // Stopped due to FailOnConflict so there's no index or conflict list if (earlyStop) { return new MergeTreeResult(new Conflict[] { }); } if (Proxy.git_index_has_conflicts(indexHandle)) { List<Conflict> conflicts = new List<Conflict>(); Conflict conflict; using (ConflictIteratorHandle iterator = Proxy.git_index_conflict_iterator_new(indexHandle)) { while ((conflict = Proxy.git_index_conflict_next(iterator)) != null) { conflicts.Add(conflict); } } revertTreeResult = new MergeTreeResult(conflicts); } else { var treeId = Proxy.git_index_write_tree_to(indexHandle, repo.Handle); revertTreeResult = new MergeTreeResult(this.repo.Lookup<Tree>(treeId)); } return revertTreeResult; } } } }
// The MIT License (MIT) // // Copyright (c) 2015 FPT Software // // 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 2012-2014 Jeremy Feinstein * Copyright 2013-2014 Tomasz Cielecki * * 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 Android.App; using Android.Content; using Android.Graphics; using Android.Graphics.Drawables; using Android.OS; using Android.Util; using Android.Views; using Android.Widget; using Java.Interop; namespace SlidingMenuSharp { public class SlidingMenu : RelativeLayout { private new const string Tag = "SlidingMenu"; private bool _mActionbarOverlay; private readonly CustomViewAbove _viewAbove; private readonly CustomViewBehind _viewBehind; public event EventHandler Open; public event EventHandler Close; public event EventHandler Opened; public event EventHandler Closed; public SlidingMenu(Context context) : this(context, null) { } public SlidingMenu(Context context, IAttributeSet attrs) : this(context, attrs, 0) { } public SlidingMenu(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle) { var behindParams = new LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); _viewBehind = new CustomViewBehind(context); AddView(_viewBehind, behindParams); var aboveParams = new LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); _viewAbove = new CustomViewAbove(context); AddView(_viewAbove, aboveParams); _viewAbove.CustomViewBehind = _viewBehind; _viewBehind.CustomViewAbove = _viewAbove; _viewAbove.PageSelected += (sender, args) => { if (args.Position == 0 && null != Open) //position open Open(this, EventArgs.Empty); else if (args.Position == 2 && null != Close) //position close Close(this, EventArgs.Empty); }; _viewAbove.Opened += (sender, args) => { if (null != Opened) Opened(sender, args); }; _viewAbove.Closed += (sender, args) => { if (null != Closed) Closed(sender, args); }; var a = context.ObtainStyledAttributes(attrs, Resource.Styleable.SlidingMenu); var mode = a.GetInt(Resource.Styleable.SlidingMenu_mode, (int) MenuMode.Left); Mode = (MenuMode) mode; var viewAbove = a.GetResourceId(Resource.Styleable.SlidingMenu_viewAbove, -1); if (viewAbove != -1) SetContent(viewAbove); else SetContent(new FrameLayout(context)); TouchModeAbove = (TouchMode)a.GetInt(Resource.Styleable.SlidingMenu_touchModeAbove, (int)TouchMode.Margin); TouchModeBehind = (TouchMode)a.GetInt(Resource.Styleable.SlidingMenu_touchModeBehind, (int)TouchMode.Margin); var offsetBehind = (int) a.GetDimension(Resource.Styleable.SlidingMenu_behindOffset, -1); var widthBehind = (int) a.GetDimension(Resource.Styleable.SlidingMenu_behindWidth, -1); if (offsetBehind != -1 && widthBehind != -1) throw new ArgumentException("Cannot set both behindOffset and behindWidth for SlidingMenu, check your XML"); if (offsetBehind != -1) BehindOffset = offsetBehind; else if (widthBehind != -1) BehindWidth = widthBehind; else BehindOffset = 0; var shadowRes = a.GetResourceId(Resource.Styleable.SlidingMenu_shadowDrawable, -1); if (shadowRes != -1) ShadowDrawableRes = shadowRes; BehindScrollScale = a.GetFloat(Resource.Styleable.SlidingMenu_behindScrollScale, 0.33f); ShadowWidth = ((int)a.GetDimension(Resource.Styleable.SlidingMenu_shadowWidth, 0)); FadeEnabled = a.GetBoolean(Resource.Styleable.SlidingMenu_fadeEnabled, true); FadeDegree = a.GetFloat(Resource.Styleable.SlidingMenu_fadeDegree, 0.33f); SelectorEnabled = a.GetBoolean(Resource.Styleable.SlidingMenu_selectorEnabled, false); var selectorRes = a.GetResourceId(Resource.Styleable.SlidingMenu_selectorDrawable, -1); if (selectorRes != -1) SelectorDrawable = selectorRes; a.Recycle(); } public void AttachToActivity(Activity activity, SlideStyle slideStyle) { AttachToActivity(activity, slideStyle, false); } public void AttachToActivity(Activity activity, SlideStyle slideStyle, bool actionbarOverlay) { if (Parent != null) throw new ArgumentException("This SlidingMenu appears to already be attached"); // get the window background var a = activity.Theme.ObtainStyledAttributes(new[] { Android.Resource.Attribute.WindowBackground }); var background = a.GetResourceId(0, 0); a.Recycle(); switch (slideStyle) { case SlideStyle.Window: _mActionbarOverlay = false; var decor = (ViewGroup)activity.Window.DecorView; var decorChild = (ViewGroup)decor.GetChildAt(0); // save ActionBar themes that have transparent assets decorChild.SetBackgroundResource(background); decor.RemoveView(decorChild); decor.AddView(this); SetContent(decorChild); break; case SlideStyle.Content: _mActionbarOverlay = actionbarOverlay; // take the above view out of var contentParent = (ViewGroup)activity.FindViewById(Android.Resource.Id.Content); var content = contentParent.GetChildAt(0); contentParent.RemoveView(content); contentParent.AddView(this); SetContent(content); // save people from having transparent backgrounds if (content.Background == null) content.SetBackgroundResource(background); break; } } public void SetContent(int res) { SetContent(LayoutInflater.From(Context).Inflate(res, null)); } public void SetContent(View view) { _viewAbove.Content = view; ShowContent(); } public View GetContent() { return _viewAbove.Content; } public void SetMenu(int res) { SetMenu(LayoutInflater.From(Context).Inflate(res, null)); } public void SetMenu(View v) { _viewBehind.Content = v; } public View GetMenu() { return _viewBehind.Content; } public void SetSecondaryMenu(int res) { SetSecondaryMenu(LayoutInflater.From(Context).Inflate(res, null)); } public void SetSecondaryMenu(View v) { _viewBehind.SecondaryContent = v; } public View GetSecondaryMenu() { return _viewBehind.SecondaryContent; } public bool IsSlidingEnabled { get { return _viewAbove.IsSlidingEnabled; } set { _viewAbove.IsSlidingEnabled = value; } } public MenuMode Mode { get { return _viewBehind.Mode; } set { if (value != MenuMode.Left && value != MenuMode.Right && value != MenuMode.LeftRight) { throw new ArgumentException("SlidingMenu mode must be LEFT, RIGHT, or LEFT_RIGHT", "value"); } _viewBehind.Mode = value; } } public bool Static { set { if (value) { IsSlidingEnabled = false; _viewAbove.CustomViewBehind = null; _viewAbove.SetCurrentItem(1); } else { _viewAbove.SetCurrentItem(1); _viewAbove.CustomViewBehind = _viewBehind; IsSlidingEnabled = true; } } } public void ShowMenu() { ShowMenu(true); } public void ShowMenu(bool animate) { _viewAbove.SetCurrentItem(0, animate); } public void ShowSecondaryMenu() { ShowSecondaryMenu(true); } public void ShowSecondaryMenu(bool animate) { _viewAbove.SetCurrentItem(2, animate); } public void ShowContent(bool animate = true) { _viewAbove.SetCurrentItem(1, animate); } public void Toggle() { Toggle(true); } public void Toggle(bool animate) { if (IsMenuShowing) { ShowContent(animate); } else { ShowMenu(animate); } } public bool IsMenuShowing { get { return _viewAbove.GetCurrentItem() == 0 || _viewAbove.GetCurrentItem() == 2; } } public bool IsSecondaryMenuShowing { get { return _viewAbove.GetCurrentItem() == 2; } } public int BehindOffset { get { return _viewBehind.WidthOffset; } set { _viewBehind.WidthOffset = value; } } public int BehindOffsetRes { set { var i = (int) Context.Resources.GetDimension(value); BehindOffset = i; } } public int AboveOffset { set { _viewAbove.AboveOffset = value; } } public int AboveOffsetRes { set { var i = (int) Context.Resources.GetDimension(value); AboveOffset = i; } } public int BehindWidth { set { var windowService = Context.GetSystemService(Context.WindowService); var windowManager = windowService.JavaCast<IWindowManager>(); var width = windowManager.DefaultDisplay.Width; BehindOffset = width - value; } } public int BehindWidthRes { set { var i = (int)Context.Resources.GetDimension(value); BehindWidth = i; } } public float BehindScrollScale { get { return _viewBehind.ScrollScale; } set { if (value < 0f && value > 1f) throw new ArgumentOutOfRangeException("value", "ScrollScale must be between 0f and 1f"); _viewBehind.ScrollScale = value; } } public int TouchmodeMarginThreshold { get { return _viewBehind.MarginThreshold; } set { _viewBehind.MarginThreshold = value; } } public TouchMode TouchModeAbove { get { return _viewAbove.TouchMode; } set { if (value != TouchMode.Fullscreen && value != TouchMode.Margin && value != TouchMode.None) { throw new ArgumentException("TouchMode must be set to either" + "TOUCHMODE_FULLSCREEN or TOUCHMODE_MARGIN or TOUCHMODE_NONE.", "value"); } _viewAbove.TouchMode = value; } } public TouchMode TouchModeBehind { set { if (value != TouchMode.Fullscreen && value != TouchMode.Margin && value != TouchMode.None) { throw new ArgumentException("TouchMode must be set to either" + "TOUCHMODE_FULLSCREEN or TOUCHMODE_MARGIN or TOUCHMODE_NONE.", "value"); } _viewBehind.TouchMode = value; } } public int ShadowDrawableRes { set { _viewBehind.ShadowDrawable = Context.Resources.GetDrawable(value); } } public Drawable ShadowDrawable { set { _viewBehind.ShadowDrawable = value; } } public int SecondaryShadowDrawableRes { set { _viewBehind.SecondaryShadowDrawable = Context.Resources.GetDrawable(value); } } public Drawable SecondaryShadowDrawable { set { _viewBehind.SecondaryShadowDrawable = value; } } public int ShadowWidthRes { set { ShadowWidth = (int)Context.Resources.GetDimension(value); } } public int ShadowWidth { set { _viewBehind.ShadowWidth = value; } } public bool FadeEnabled { set { _viewBehind.FadeEnabled = value; } } public float FadeDegree { set { _viewBehind.FadeDegree = value; } } public bool SelectorEnabled { set { _viewBehind.SelectorEnabled = value; } } public View SelectedView { set { _viewBehind.SelectedView = value; } } public int SelectorDrawable { set { SelectorBitmap = BitmapFactory.DecodeResource(Resources, value); } } public Bitmap SelectorBitmap { set { _viewBehind.SelectorBitmap = value; } } public void AddIgnoredView(View v) { _viewAbove.AddIgnoredView(v); } public void RemoveIgnoredView(View v) { _viewAbove.RemoveIgnoredView(v); } public void ClearIgnoredViews() { _viewAbove.ClearIgnoredViews(); } public ICanvasTransformer BehindCanvasTransformer { set { _viewBehind.CanvasTransformer = value; } } public class SavedState : BaseSavedState { public int Item { get; private set; } public SavedState(IParcelable superState) : base(superState) { } public SavedState(Parcel parcel) : base(parcel) { Item = parcel.ReadInt(); } public override void WriteToParcel(Parcel dest, ParcelableWriteFlags flags) { base.WriteToParcel(dest, flags); dest.WriteInt(Item); } [ExportField("CREATOR")] static SavedStateCreator InitializeCreator() { return new SavedStateCreator(); } class SavedStateCreator : Java.Lang.Object, IParcelableCreator { public Java.Lang.Object CreateFromParcel(Parcel source) { return new SavedState(source); } public Java.Lang.Object[] NewArray(int size) { return new SavedState[size]; } } } protected override void OnRestoreInstanceState(IParcelable state) { try { Bundle bundle = state as Bundle; if (bundle != null) { IParcelable superState = (IParcelable)bundle.GetParcelable("base"); if (superState != null) base.OnRestoreInstanceState(superState); _viewAbove.SetCurrentItem(bundle.GetInt("currentPosition", 0)); } } catch { base.OnRestoreInstanceState(state); // Ignore, this needs to support IParcelable... } } protected override IParcelable OnSaveInstanceState() { var superState = base.OnSaveInstanceState(); Bundle state = new Bundle(); state.PutParcelable("base", superState); state.PutInt("currentPosition", _viewAbove.GetCurrentItem()); return state; } protected override bool FitSystemWindows(Rect insets) { if (!_mActionbarOverlay) { Log.Verbose(Tag, "setting padding"); SetPadding(insets.Left, insets.Top, insets.Right, insets.Bottom); } return true; } #if __ANDROID_11__ public void ManageLayers(float percentOpen) { if ((int) Build.VERSION.SdkInt < 11) return; var layer = percentOpen > 0.0f && percentOpen < 1.0f; var layerType = layer ? LayerType.Hardware : LayerType.None; if (layerType != GetContent().LayerType) { Handler.Post(() => { Log.Verbose(Tag, "changing layerType, hardware? " + (layerType == LayerType.Hardware)); GetContent().SetLayerType(layerType, null); GetMenu().SetLayerType(layerType, null); if (GetSecondaryMenu() != null) GetSecondaryMenu().SetLayerType(layerType, null); }); } } #endif } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Globalization; using System.Runtime.CompilerServices; using System.Text; namespace System.Numerics { /// <summary> /// A structure encapsulating three single precision floating point values and provides hardware accelerated methods. /// </summary> public partial struct Vector3 : IEquatable<Vector3>, IFormattable { #region Public Static Properties /// <summary> /// Returns the vector (0,0,0). /// </summary> public static Vector3 Zero { get { return new Vector3(); } } /// <summary> /// Returns the vector (1,1,1). /// </summary> public static Vector3 One { get { return new Vector3(1.0f, 1.0f, 1.0f); } } /// <summary> /// Returns the vector (1,0,0). /// </summary> public static Vector3 UnitX { get { return new Vector3(1.0f, 0.0f, 0.0f); } } /// <summary> /// Returns the vector (0,1,0). /// </summary> public static Vector3 UnitY { get { return new Vector3(0.0f, 1.0f, 0.0f); } } /// <summary> /// Returns the vector (0,0,1). /// </summary> public static Vector3 UnitZ { get { return new Vector3(0.0f, 0.0f, 1.0f); } } #endregion Public Static Properties #region Public Instance Methods /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int hash = this.X.GetHashCode(); hash = HashCodeHelper.CombineHashCodes(hash, this.Y.GetHashCode()); hash = HashCodeHelper.CombineHashCodes(hash, this.Z.GetHashCode()); return hash; } /// <summary> /// Returns a boolean indicating whether the given Object is equal to this Vector3 instance. /// </summary> /// <param name="obj">The Object to compare against.</param> /// <returns>True if the Object is equal to this Vector3; False otherwise.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object obj) { if (!(obj is Vector3)) return false; return Equals((Vector3)obj); } /// <summary> /// Returns a String representing this Vector3 instance. /// </summary> /// <returns>The string representation.</returns> public override string ToString() { return ToString("G", CultureInfo.CurrentCulture); } /// <summary> /// Returns a String representing this Vector3 instance, using the specified format to format individual elements. /// </summary> /// <param name="format">The format of individual elements.</param> /// <returns>The string representation.</returns> public string ToString(string format) { return ToString(format, CultureInfo.CurrentCulture); } /// <summary> /// Returns a String representing this Vector3 instance, using the specified format to format individual elements /// and the given IFormatProvider. /// </summary> /// <param name="format">The format of individual elements.</param> /// <param name="formatProvider">The format provider to use when formatting elements.</param> /// <returns>The string representation.</returns> public string ToString(string format, IFormatProvider formatProvider) { StringBuilder sb = new StringBuilder(); string separator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator; sb.Append('<'); sb.Append(((IFormattable)this.X).ToString(format, formatProvider)); sb.Append(separator); sb.Append(' '); sb.Append(((IFormattable)this.Y).ToString(format, formatProvider)); sb.Append(separator); sb.Append(' '); sb.Append(((IFormattable)this.Z).ToString(format, formatProvider)); sb.Append('>'); return sb.ToString(); } /// <summary> /// Returns the length of the vector. /// </summary> /// <returns>The vector's length.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public float Length() { if (Vector.IsHardwareAccelerated) { float ls = Vector3.Dot(this, this); return (float)System.Math.Sqrt(ls); } else { float ls = X * X + Y * Y + Z * Z; return (float)System.Math.Sqrt(ls); } } /// <summary> /// Returns the length of the vector squared. This operation is cheaper than Length(). /// </summary> /// <returns>The vector's length squared.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public float LengthSquared() { if (Vector.IsHardwareAccelerated) { return Vector3.Dot(this, this); } else { return X * X + Y * Y + Z * Z; } } #endregion Public Instance Methods #region Public Static Methods /// <summary> /// Returns the Euclidean distance between the two given points. /// </summary> /// <param name="value1">The first point.</param> /// <param name="value2">The second point.</param> /// <returns>The distance.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Distance(Vector3 value1, Vector3 value2) { if (Vector.IsHardwareAccelerated) { Vector3 difference = value1 - value2; float ls = Vector3.Dot(difference, difference); return (float)System.Math.Sqrt(ls); } else { float dx = value1.X - value2.X; float dy = value1.Y - value2.Y; float dz = value1.Z - value2.Z; float ls = dx * dx + dy * dy + dz * dz; return (float)System.Math.Sqrt((double)ls); } } /// <summary> /// Returns the Euclidean distance squared between the two given points. /// </summary> /// <param name="value1">The first point.</param> /// <param name="value2">The second point.</param> /// <returns>The distance squared.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float DistanceSquared(Vector3 value1, Vector3 value2) { if (Vector.IsHardwareAccelerated) { Vector3 difference = value1 - value2; return Vector3.Dot(difference, difference); } else { float dx = value1.X - value2.X; float dy = value1.Y - value2.Y; float dz = value1.Z - value2.Z; return dx * dx + dy * dy + dz * dz; } } /// <summary> /// Returns a vector with the same direction as the given vector, but with a length of 1. /// </summary> /// <param name="value">The vector to normalize.</param> /// <returns>The normalized vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Normalize(Vector3 value) { if (Vector.IsHardwareAccelerated) { float length = value.Length(); return value / length; } else { float ls = value.X * value.X + value.Y * value.Y + value.Z * value.Z; float length = (float)System.Math.Sqrt(ls); return new Vector3(value.X / length, value.Y / length, value.Z / length); } } /// <summary> /// Computes the cross product of two vectors. /// </summary> /// <param name="vector1">The first vector.</param> /// <param name="vector2">The second vector.</param> /// <returns>The cross product.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Cross(Vector3 vector1, Vector3 vector2) { return new Vector3( vector1.Y * vector2.Z - vector1.Z * vector2.Y, vector1.Z * vector2.X - vector1.X * vector2.Z, vector1.X * vector2.Y - vector1.Y * vector2.X); } /// <summary> /// Returns the reflection of a vector off a surface that has the specified normal. /// </summary> /// <param name="vector">The source vector.</param> /// <param name="normal">The normal of the surface being reflected off.</param> /// <returns>The reflected vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Reflect(Vector3 vector, Vector3 normal) { if (Vector.IsHardwareAccelerated) { float dot = Vector3.Dot(vector, normal); Vector3 temp = normal * dot * 2f; return vector - temp; } else { float dot = vector.X * normal.X + vector.Y * normal.Y + vector.Z * normal.Z; float tempX = normal.X * dot * 2f; float tempY = normal.Y * dot * 2f; float tempZ = normal.Z * dot * 2f; return new Vector3(vector.X - tempX, vector.Y - tempY, vector.Z - tempZ); } } /// <summary> /// Restricts a vector between a min and max value. /// </summary> /// <param name="value1">The source vector.</param> /// <param name="min">The minimum value.</param> /// <param name="max">The maximum value.</param> /// <returns>The restricted vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Clamp(Vector3 value1, Vector3 min, Vector3 max) { // This compare order is very important!!! // We must follow HLSL behavior in the case user specified min value is bigger than max value. float x = value1.X; x = (x > max.X) ? max.X : x; x = (x < min.X) ? min.X : x; float y = value1.Y; y = (y > max.Y) ? max.Y : y; y = (y < min.Y) ? min.Y : y; float z = value1.Z; z = (z > max.Z) ? max.Z : z; z = (z < min.Z) ? min.Z : z; return new Vector3(x, y, z); } /// <summary> /// Linearly interpolates between two vectors based on the given weighting. /// </summary> /// <param name="value1">The first source vector.</param> /// <param name="value2">The second source vector.</param> /// <param name="amount">Value between 0 and 1 indicating the weight of the second source vector.</param> /// <returns>The interpolated vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Lerp(Vector3 value1, Vector3 value2, float amount) { if (Vector.IsHardwareAccelerated) { Vector3 firstInfluence = value1 * (1f - amount); Vector3 secondInfluence = value2 * amount; return firstInfluence + secondInfluence; } else { return new Vector3( value1.X + (value2.X - value1.X) * amount, value1.Y + (value2.Y - value1.Y) * amount, value1.Z + (value2.Z - value1.Z) * amount); } } /// <summary> /// Transforms a vector by the given matrix. /// </summary> /// <param name="position">The source vector.</param> /// <param name="matrix">The transformation matrix.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Transform(Vector3 position, Matrix4x4 matrix) { return new Vector3( position.X * matrix.M11 + position.Y * matrix.M21 + position.Z * matrix.M31 + matrix.M41, position.X * matrix.M12 + position.Y * matrix.M22 + position.Z * matrix.M32 + matrix.M42, position.X * matrix.M13 + position.Y * matrix.M23 + position.Z * matrix.M33 + matrix.M43); } /// <summary> /// Transforms a vector normal by the given matrix. /// </summary> /// <param name="normal">The source vector.</param> /// <param name="matrix">The transformation matrix.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 TransformNormal(Vector3 normal, Matrix4x4 matrix) { return new Vector3( normal.X * matrix.M11 + normal.Y * matrix.M21 + normal.Z * matrix.M31, normal.X * matrix.M12 + normal.Y * matrix.M22 + normal.Z * matrix.M32, normal.X * matrix.M13 + normal.Y * matrix.M23 + normal.Z * matrix.M33); } /// <summary> /// Transforms a vector by the given Quaternion rotation value. /// </summary> /// <param name="value">The source vector to be rotated.</param> /// <param name="rotation">The rotation to apply.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Transform(Vector3 value, Quaternion rotation) { float x2 = rotation.X + rotation.X; float y2 = rotation.Y + rotation.Y; float z2 = rotation.Z + rotation.Z; float wx2 = rotation.W * x2; float wy2 = rotation.W * y2; float wz2 = rotation.W * z2; float xx2 = rotation.X * x2; float xy2 = rotation.X * y2; float xz2 = rotation.X * z2; float yy2 = rotation.Y * y2; float yz2 = rotation.Y * z2; float zz2 = rotation.Z * z2; return new Vector3( value.X * (1.0f - yy2 - zz2) + value.Y * (xy2 - wz2) + value.Z * (xz2 + wy2), value.X * (xy2 + wz2) + value.Y * (1.0f - xx2 - zz2) + value.Z * (yz2 - wx2), value.X * (xz2 - wy2) + value.Y * (yz2 + wx2) + value.Z * (1.0f - xx2 - yy2)); } #endregion Public Static Methods #region Public operator methods // All these methods should be inlined as they are implemented // over JIT intrinsics /// <summary> /// Adds two vectors together. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The summed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Add(Vector3 left, Vector3 right) { return left + right; } /// <summary> /// Subtracts the second vector from the first. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The difference vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Subtract(Vector3 left, Vector3 right) { return left - right; } /// <summary> /// Multiplies two vectors together. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The product vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Multiply(Vector3 left, Vector3 right) { return left * right; } /// <summary> /// Multiplies a vector by the given scalar. /// </summary> /// <param name="left">The source vector.</param> /// <param name="right">The scalar value.</param> /// <returns>The scaled vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Multiply(Vector3 left, Single right) { return left * right; } /// <summary> /// Multiplies a vector by the given scalar. /// </summary> /// <param name="left">The scalar value.</param> /// <param name="right">The source vector.</param> /// <returns>The scaled vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Multiply(Single left, Vector3 right) { return left * right; } /// <summary> /// Divides the first vector by the second. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The vector resulting from the division.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Divide(Vector3 left, Vector3 right) { return left / right; } /// <summary> /// Divides the vector by the given scalar. /// </summary> /// <param name="left">The source vector.</param> /// <param name="divisor">The scalar value.</param> /// <returns>The result of the division.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Divide(Vector3 left, Single divisor) { return left / divisor; } /// <summary> /// Negates a given vector. /// </summary> /// <param name="value">The source vector.</param> /// <returns>The negated vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Negate(Vector3 value) { return -value; } #endregion Public operator methods } }
// 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: Provides a fast, AV free, cross-language way of ** accessing unmanaged memory in a random fashion. ** ** ===========================================================*/ using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Security.Permissions; using Microsoft.Win32.SafeHandles; using System.Diagnostics.Contracts; namespace System.IO { /// Perf notes: ReadXXX, WriteXXX (for basic types) acquire and release the /// SafeBuffer pointer rather than relying on generic Read(T) from SafeBuffer because /// this gives better throughput; benchmarks showed about 12-15% better. public class UnmanagedMemoryAccessor : IDisposable { [System.Security.SecurityCritical] // auto-generated private SafeBuffer _buffer; private Int64 _offset; [ContractPublicPropertyName("Capacity")] private Int64 _capacity; private FileAccess _access; private bool _isOpen; private bool _canRead; private bool _canWrite; protected UnmanagedMemoryAccessor() { _isOpen = false; } #region SafeBuffer ctors and initializers // <SecurityKernel Critical="True" Ring="1"> // <ReferencesCritical Name="Method: Initialize(SafeBuffer, Int64, Int64, FileAccess):Void" Ring="1" /> // </SecurityKernel> [System.Security.SecuritySafeCritical] public UnmanagedMemoryAccessor(SafeBuffer buffer, Int64 offset, Int64 capacity) { Initialize(buffer, offset, capacity, FileAccess.Read); } [System.Security.SecuritySafeCritical] // auto-generated public UnmanagedMemoryAccessor(SafeBuffer buffer, Int64 offset, Int64 capacity, FileAccess access) { Initialize(buffer, offset, capacity, access); } [System.Security.SecuritySafeCritical] // auto-generated #pragma warning disable 618 [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] #pragma warning restore 618 protected void Initialize(SafeBuffer buffer, Int64 offset, Int64 capacity, FileAccess access) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (capacity < 0) { throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (buffer.ByteLength < (UInt64)(offset + capacity)) { throw new ArgumentException(Environment.GetResourceString("Argument_OffsetAndCapacityOutOfBounds")); } if (access < FileAccess.Read || access > FileAccess.ReadWrite) { throw new ArgumentOutOfRangeException(nameof(access)); } Contract.EndContractBlock(); if (_isOpen) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CalledTwice")); } unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { buffer.AcquirePointer(ref pointer); if (((byte*)((Int64)pointer + offset + capacity)) < pointer) { throw new ArgumentException(Environment.GetResourceString("Argument_UnmanagedMemAccessorWrapAround")); } } finally { if (pointer != null) { buffer.ReleasePointer(); } } } _offset = offset; _buffer = buffer; _capacity = capacity; _access = access; _isOpen = true; _canRead = (_access & FileAccess.Read) != 0; _canWrite = (_access & FileAccess.Write) != 0; } #endregion public Int64 Capacity { get { return _capacity; } } public bool CanRead { get { return _isOpen && _canRead; } } public bool CanWrite { get { return _isOpen && _canWrite; } } protected virtual void Dispose(bool disposing) { _isOpen = false; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected bool IsOpen { get { return _isOpen; } } public bool ReadBoolean(Int64 position) { int sizeOfType = sizeof(bool); EnsureSafeToRead(position, sizeOfType); byte b = InternalReadByte(position); return b != 0; } public byte ReadByte(Int64 position) { int sizeOfType = sizeof(byte); EnsureSafeToRead(position, sizeOfType); return InternalReadByte(position); } [System.Security.SecuritySafeCritical] // auto-generated public char ReadChar(Int64 position) { int sizeOfType = sizeof(char); EnsureSafeToRead(position, sizeOfType); char result; unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif result = *((char*)(pointer)); #if ALIGN_ACCESS } else { result = (char)( *pointer | *(pointer + 1) << 8 ) ; } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } return result; } // See comment above. [System.Security.SecuritySafeCritical] public Int16 ReadInt16(Int64 position) { int sizeOfType = sizeof(Int16); EnsureSafeToRead(position, sizeOfType); Int16 result; unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif result = *((Int16*)(pointer)); #if ALIGN_ACCESS } else { result = (Int16)( *pointer | *(pointer + 1) << 8 ); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } return result; } [System.Security.SecuritySafeCritical] // auto-generated public Int32 ReadInt32(Int64 position) { int sizeOfType = sizeof(Int32); EnsureSafeToRead(position, sizeOfType); Int32 result; unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif result = *((Int32*)(pointer)); #if ALIGN_ACCESS } else { result = (Int32)( *pointer | *(pointer + 1) << 8 | *(pointer + 2) << 16 | *(pointer + 3) << 24 ); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } return result; } [System.Security.SecuritySafeCritical] // auto-generated public Int64 ReadInt64(Int64 position) { int sizeOfType = sizeof(Int64); EnsureSafeToRead(position, sizeOfType); Int64 result; unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif result = *((Int64*)(pointer)); #if ALIGN_ACCESS } else { int lo = *pointer | *(pointer + 1) << 8 | *(pointer + 2) << 16 | *(pointer + 3) << 24; int hi = *(pointer + 4) | *(pointer + 5) << 8 | *(pointer + 6) << 16 | *(pointer + 7) << 24; result = (Int64)(((Int64)hi << 32) | (UInt32)lo); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } return result; } [System.Security.SecurityCritical] [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe Int32 UnsafeReadInt32(byte* pointer) { Int32 result; // check if pointer is aligned if (((int)pointer & (sizeof(Int32) - 1)) == 0) { result = *((Int32*)pointer); } else { result = (Int32)(*(pointer) | *(pointer + 1) << 8 | *(pointer + 2) << 16 | *(pointer + 3) << 24); } return result; } [System.Security.SecuritySafeCritical] // auto-generated public Decimal ReadDecimal(Int64 position) { const int ScaleMask = 0x00FF0000; const int SignMask = unchecked((int)0x80000000); int sizeOfType = sizeof(Decimal); EnsureSafeToRead(position, sizeOfType); unsafe { byte* pointer = null; try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); int lo = UnsafeReadInt32(pointer); int mid = UnsafeReadInt32(pointer + 4); int hi = UnsafeReadInt32(pointer + 8); int flags = UnsafeReadInt32(pointer + 12); // Check for invalid Decimal values if (!((flags & ~(SignMask | ScaleMask)) == 0 && (flags & ScaleMask) <= (28 << 16))) { throw new ArgumentException(Environment.GetResourceString("Arg_BadDecimal")); // Throw same Exception type as Decimal(int[]) ctor for compat } bool isNegative = (flags & SignMask) != 0; byte scale = (byte)(flags >> 16); return new decimal(lo, mid, hi, isNegative, scale); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } [System.Security.SecuritySafeCritical] // auto-generated public Single ReadSingle(Int64 position) { int sizeOfType = sizeof(Single); EnsureSafeToRead(position, sizeOfType); Single result; unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif result = *((Single*)(pointer)); #if ALIGN_ACCESS } else { UInt32 tempResult = (UInt32)( *pointer | *(pointer + 1) << 8 | *(pointer + 2) << 16 | *(pointer + 3) << 24 ); result = *((float*)&tempResult); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } return result; } [System.Security.SecuritySafeCritical] // auto-generated public Double ReadDouble(Int64 position) { int sizeOfType = sizeof(Double); EnsureSafeToRead(position, sizeOfType); Double result; unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif result = *((Double*)(pointer)); #if ALIGN_ACCESS } else { UInt32 lo = (UInt32)( *pointer | *(pointer + 1) << 8 | *(pointer + 2) << 16 | *(pointer + 3) << 24 ); UInt32 hi = (UInt32)( *(pointer + 4) | *(pointer + 5) << 8 | *(pointer + 6) << 16 | *(pointer + 7) << 24 ); UInt64 tempResult = ((UInt64)hi) << 32 | lo; result = *((double*)&tempResult); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } return result; } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] public SByte ReadSByte(Int64 position) { int sizeOfType = sizeof(SByte); EnsureSafeToRead(position, sizeOfType); SByte result; unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); result = *((SByte*)pointer); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } return result; } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] public UInt16 ReadUInt16(Int64 position) { int sizeOfType = sizeof(UInt16); EnsureSafeToRead(position, sizeOfType); UInt16 result; unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif result = *((UInt16*)(pointer)); #if ALIGN_ACCESS } else { result = (UInt16)( *pointer | *(pointer + 1) << 8 ); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } return result; } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] public UInt32 ReadUInt32(Int64 position) { int sizeOfType = sizeof(UInt32); EnsureSafeToRead(position, sizeOfType); UInt32 result; unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif result = *((UInt32*)(pointer)); #if ALIGN_ACCESS } else { result = (UInt32)( *pointer | *(pointer + 1) << 8 | *(pointer + 2) << 16 | *(pointer + 3) << 24 ); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } return result; } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] public UInt64 ReadUInt64(Int64 position) { int sizeOfType = sizeof(UInt64); EnsureSafeToRead(position, sizeOfType); UInt64 result; unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif result = *((UInt64*)(pointer)); #if ALIGN_ACCESS } else { UInt32 lo = (UInt32)( *pointer | *(pointer + 1) << 8 | *(pointer + 2) << 16 | *(pointer + 3) << 24 ); UInt32 hi = (UInt32)( *(pointer + 4) | *(pointer + 5) << 8 | *(pointer + 6) << 16 | *(pointer + 7) << 24 ); result = (UInt64)(((UInt64)hi << 32) | lo ); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } return result; } // Reads a struct of type T from unmanaged memory, into the reference pointed to by ref value. // Note: this method is not safe, since it overwrites the contents of a structure, it can be // used to modify the private members of a struct. Furthermore, using this with a struct that // contains reference members will most likely cause the runtime to AV. Note, that despite // various checks made by the C++ code used by Marshal.PtrToStructure, Marshal.PtrToStructure // will still overwrite privates and will also crash the runtime when used with structs // containing reference members. For this reason, I am sticking an UnmanagedCode requirement // on this method to match Marshal.PtrToStructure. // Alos note that this method is most performant when used with medium to large sized structs // (larger than 8 bytes -- though this is number is JIT and architecture dependent). As // such, it is best to use the ReadXXX methods for small standard types such as ints, longs, // bools, etc. [System.Security.SecurityCritical] // auto-generated_required public void Read<T>(Int64 position, out T structure) where T : struct { if (position < 0) { throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); if (!_isOpen) { throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed")); } if (!CanRead) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_Reading")); } UInt32 sizeOfT = Marshal.SizeOfType(typeof(T)); if (position > _capacity - sizeOfT) { if (position >= _capacity) { throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired")); } else { throw new ArgumentException(Environment.GetResourceString("Argument_NotEnoughBytesToRead", typeof(T).FullName), nameof(position)); } } structure = _buffer.Read<T>((UInt64)(_offset + position)); } // Reads 'count' structs of type T from unmanaged memory, into 'array' starting at 'offset'. // Note: this method is not safe, since it overwrites the contents of structures, it can // be used to modify the private members of a struct. Furthermore, using this with a // struct that contains reference members will most likely cause the runtime to AV. This // is consistent with Marshal.PtrToStructure. [System.Security.SecurityCritical] // auto-generated_required public int ReadArray<T>(Int64 position, T[] array, Int32 offset, Int32 count) where T : struct { if (array == null) { throw new ArgumentNullException(nameof(array), "Buffer cannot be null."); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (array.Length - offset < count) { throw new ArgumentException(Environment.GetResourceString("Argument_OffsetAndLengthOutOfBounds")); } Contract.EndContractBlock(); if (!CanRead) { if (!_isOpen) { throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed")); } else { throw new NotSupportedException(Environment.GetResourceString("NotSupported_Reading")); } } if (position < 0) { throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } UInt32 sizeOfT = Marshal.AlignedSizeOf<T>(); // only check position and ask for fewer Ts if count is too big if (position >= _capacity) { throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired")); } int n = count; long spaceLeft = _capacity - position; if (spaceLeft < 0) { n = 0; } else { ulong spaceNeeded = (ulong)(sizeOfT * count); if ((ulong)spaceLeft < spaceNeeded) { n = (int)(spaceLeft / sizeOfT); } } _buffer.ReadArray<T>((UInt64)(_offset + position), array, offset, n); return n; } // ************** Write Methods ****************/ // The following 13 WriteXXX methods write a value of type XXX into unmanaged memory at 'positon'. // The bounds of the unmanaged memory are checked against to ensure that there is enough // space after 'position' to write a value of type XXX. XXX can be a bool, byte, char, decimal, // double, short, int, long, sbyte, float, ushort, uint, or ulong. public void Write(Int64 position, bool value) { int sizeOfType = sizeof(bool); EnsureSafeToWrite(position, sizeOfType); byte b = (byte)(value ? 1 : 0); InternalWrite(position, b); } public void Write(Int64 position, byte value) { int sizeOfType = sizeof(byte); EnsureSafeToWrite(position, sizeOfType); InternalWrite(position, value); } [System.Security.SecuritySafeCritical] // auto-generated public void Write(Int64 position, char value) { int sizeOfType = sizeof(char); EnsureSafeToWrite(position, sizeOfType); unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif *((char*)pointer) = value; #if ALIGN_ACCESS } else { *(pointer) = (byte)value; *(pointer+1) = (byte)(value >> 8); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } [System.Security.SecuritySafeCritical] // auto-generated public void Write(Int64 position, Int16 value) { int sizeOfType = sizeof(Int16); EnsureSafeToWrite(position, sizeOfType); unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif *((Int16*)pointer) = value; #if ALIGN_ACCESS } else { *(pointer) = (byte)value; *(pointer + 1) = (byte)(value >> 8); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } [System.Security.SecuritySafeCritical] // auto-generated public void Write(Int64 position, Int32 value) { int sizeOfType = sizeof(Int32); EnsureSafeToWrite(position, sizeOfType); unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif *((Int32*)pointer) = value; #if ALIGN_ACCESS } else { *(pointer) = (byte)value; *(pointer + 1) = (byte)(value >> 8); *(pointer + 2) = (byte)(value >> 16); *(pointer + 3) = (byte)(value >> 24); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } [System.Security.SecuritySafeCritical] // auto-generated public void Write(Int64 position, Int64 value) { int sizeOfType = sizeof(Int64); EnsureSafeToWrite(position, sizeOfType); unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif *((Int64*)pointer) = value; #if ALIGN_ACCESS } else { *(pointer) = (byte)value; *(pointer + 1) = (byte)(value >> 8); *(pointer + 2) = (byte)(value >> 16); *(pointer + 3) = (byte)(value >> 24); *(pointer + 4) = (byte)(value >> 32); *(pointer + 5) = (byte)(value >> 40); *(pointer + 6) = (byte)(value >> 48); *(pointer + 7) = (byte)(value >> 56); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } [System.Security.SecurityCritical] [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe void UnsafeWriteInt32(byte* pointer, Int32 value) { // check if pointer is aligned if (((int)pointer & (sizeof(Int32) - 1)) == 0) { *((Int32*)pointer) = value; } else { *(pointer) = (byte)value; *(pointer + 1) = (byte)(value >> 8); *(pointer + 2) = (byte)(value >> 16); *(pointer + 3) = (byte)(value >> 24); } } [System.Security.SecuritySafeCritical] // auto-generated public void Write(Int64 position, Decimal value) { int sizeOfType = sizeof(Decimal); EnsureSafeToWrite(position, sizeOfType); unsafe { byte* pointer = null; try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); int* valuePtr = (int*)(&value); int flags = *valuePtr; int hi = *(valuePtr + 1); int lo = *(valuePtr + 2); int mid = *(valuePtr + 3); UnsafeWriteInt32(pointer, lo); UnsafeWriteInt32(pointer + 4, mid); UnsafeWriteInt32(pointer + 8, hi); UnsafeWriteInt32(pointer + 12, flags); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } [System.Security.SecuritySafeCritical] // auto-generated public void Write(Int64 position, Single value) { int sizeOfType = sizeof(Single); EnsureSafeToWrite(position, sizeOfType); unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif *((Single*)pointer) = value; #if ALIGN_ACCESS } else { UInt32 tmpValue = *(UInt32*)&value; *(pointer) = (byte)tmpValue; *(pointer + 1) = (byte)(tmpValue >> 8); *(pointer + 2) = (byte)(tmpValue >> 16); *(pointer + 3) = (byte)(tmpValue >> 24); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } [System.Security.SecuritySafeCritical] // auto-generated public void Write(Int64 position, Double value) { int sizeOfType = sizeof(Double); EnsureSafeToWrite(position, sizeOfType); unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif *((Double*)pointer) = value; #if ALIGN_ACCESS } else { UInt64 tmpValue = *(UInt64 *)&value; *(pointer) = (byte) tmpValue; *(pointer + 1) = (byte) (tmpValue >> 8); *(pointer + 2) = (byte) (tmpValue >> 16); *(pointer + 3) = (byte) (tmpValue >> 24); *(pointer + 4) = (byte) (tmpValue >> 32); *(pointer + 5) = (byte) (tmpValue >> 40); *(pointer + 6) = (byte) (tmpValue >> 48); *(pointer + 7) = (byte) (tmpValue >> 56); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] public void Write(Int64 position, SByte value) { int sizeOfType = sizeof(SByte); EnsureSafeToWrite(position, sizeOfType); unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); *((SByte*)pointer) = value; } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] public void Write(Int64 position, UInt16 value) { int sizeOfType = sizeof(UInt16); EnsureSafeToWrite(position, sizeOfType); unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif *((UInt16*)pointer) = value; #if ALIGN_ACCESS } else { *(pointer) = (byte)value; *(pointer + 1) = (byte)(value >> 8); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] public void Write(Int64 position, UInt32 value) { int sizeOfType = sizeof(UInt32); EnsureSafeToWrite(position, sizeOfType); unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif *((UInt32*)pointer) = value; #if ALIGN_ACCESS } else { *(pointer) = (byte)value; *(pointer + 1) = (byte)(value >> 8); *(pointer + 2) = (byte)(value >> 16); *(pointer + 3) = (byte)(value >> 24); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] public void Write(Int64 position, UInt64 value) { int sizeOfType = sizeof(UInt64); EnsureSafeToWrite(position, sizeOfType); unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); pointer += (_offset + position); #if ALIGN_ACCESS // check if pointer is aligned if (((int)pointer & (sizeOfType - 1)) == 0) { #endif *((UInt64*)pointer) = value; #if ALIGN_ACCESS } else { *(pointer) = (byte)value; *(pointer + 1) = (byte)(value >> 8); *(pointer + 2) = (byte)(value >> 16); *(pointer + 3) = (byte)(value >> 24); *(pointer + 4) = (byte)(value >> 32); *(pointer + 5) = (byte)(value >> 40); *(pointer + 6) = (byte)(value >> 48); *(pointer + 7) = (byte)(value >> 56); } #endif } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } // Writes the struct pointed to by ref value into unmanaged memory. Note that this method // is most performant when used with medium to large sized structs (larger than 8 bytes // though this is number is JIT and architecture dependent). As such, it is best to use // the WriteX methods for small standard types such as ints, longs, bools, etc. [System.Security.SecurityCritical] // auto-generated_required public void Write<T>(Int64 position, ref T structure) where T : struct { if (position < 0) { throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); if (!_isOpen) { throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed")); } if (!CanWrite) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_Writing")); } UInt32 sizeOfT = Marshal.SizeOfType(typeof(T)); if (position > _capacity - sizeOfT) { if (position >= _capacity) { throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired")); } else { throw new ArgumentException(Environment.GetResourceString("Argument_NotEnoughBytesToWrite", typeof(T).FullName), nameof(position)); } } _buffer.Write<T>((UInt64)(_offset + position), structure); } // Writes 'count' structs of type T from 'array' (starting at 'offset') into unmanaged memory. [System.Security.SecurityCritical] // auto-generated_required public void WriteArray<T>(Int64 position, T[] array, Int32 offset, Int32 count) where T : struct { if (array == null) { throw new ArgumentNullException(nameof(array), "Buffer cannot be null."); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (array.Length - offset < count) { throw new ArgumentException(Environment.GetResourceString("Argument_OffsetAndLengthOutOfBounds")); } if (position < 0) { throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (position >= Capacity) { throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired")); } Contract.EndContractBlock(); if (!_isOpen) { throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed")); } if (!CanWrite) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_Writing")); } _buffer.WriteArray<T>((UInt64)(_offset + position), array, offset, count); } [System.Security.SecuritySafeCritical] // auto-generated private byte InternalReadByte(Int64 position) { Contract.Assert(CanRead, "UMA not readable"); Contract.Assert(position >= 0, "position less than 0"); Contract.Assert(position <= _capacity - sizeof(byte), "position is greater than capacity - sizeof(byte)"); byte result; unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); result = *((byte*)(pointer + _offset + position)); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } return result; } [System.Security.SecuritySafeCritical] // auto-generated private void InternalWrite(Int64 position, byte value) { Contract.Assert(CanWrite, "UMA not writable"); Contract.Assert(position >= 0, "position less than 0"); Contract.Assert(position <= _capacity - sizeof(byte), "position is greater than capacity - sizeof(byte)"); unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); *((byte*)(pointer + _offset + position)) = value; } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } private void EnsureSafeToRead(Int64 position, int sizeOfType) { if (!_isOpen) { throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed")); } if (!CanRead) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_Reading")); } if (position < 0) { throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); if (position > _capacity - sizeOfType) { if (position >= _capacity) { throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired")); } else { throw new ArgumentException(Environment.GetResourceString("Argument_NotEnoughBytesToRead"), nameof(position)); } } } private void EnsureSafeToWrite(Int64 position, int sizeOfType) { if (!_isOpen) { throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed")); } if (!CanWrite) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_Writing")); } if (position < 0) { throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); if (position > _capacity - sizeOfType) { if (position >= _capacity) { throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired")); } else { throw new ArgumentException(Environment.GetResourceString("Argument_NotEnoughBytesToWrite", nameof(Byte)), nameof(position)); } } } } }
// Copyright 2014 Jacob Trimble // // 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; using System.Text.RegularExpressions; using ModMaker.Lua.Runtime.LuaValues; namespace ModMaker.Lua.Runtime { static partial class LuaStaticLibraries { static class String { public static void Initialize(ILuaEnvironment env) { var str = new LuaTable(); Register(env, str, (Func<string, int, int?, IEnumerable<int>>)byte_, "byte"); Register(env, str, (Func<int[], string>)char_, "char"); Register(env, str, (Func<string, string, int, bool, object[]>)find); Register(env, str, (Func<string, object[], string>)format); Register(env, str, (Func<string, string, object>)gmatch); Register(env, str, (Func<string, string, ILuaValue, int, string>)gsub); Register(env, str, (Func<string, int>)len); Register(env, str, (Func<string, string>)lower); Register(env, str, (Func<string, string, int, IEnumerable<string>>)match); Register(env, str, (Func<string, int, string, string>)rep); Register(env, str, (Func<string, string>)reverse); Register(env, str, (Func<string, int, int, string>)sub); Register(env, str, (Func<string, string>)upper); env.GlobalsTable.SetItemRaw(new LuaString("string"), str); } [MultipleReturn] static IEnumerable<int> byte_(string source, int i = 1, int? j = null) { CheckNotNull("string.byte", source); return sub(source, i, j ?? i).Select(c => (int)c); } static string char_(params int[] chars) { StringBuilder ret = new StringBuilder(chars.Length); foreach (int c in chars) { if (c < 0) { throw new ArgumentException("Character out of range for 'string.char'."); } else if (c <= 0xFFFF) { // This may be a surrogate pair, assume they know what they are doing. ret.Append((char)c); } else { int mask = (1 << 10) - 1; int point = c - 0x10000; int high = point >> 10; int low = point & mask; ret.Append((char)(high + 0xD800)); ret.Append((char)(low + 0xDC00)); } } return ret.ToString(); } [MultipleReturn] static object[] find(string source, string pattern, int start = 1, bool plain = false) { CheckNotNull("string.find", source); CheckNotNull("string.find", pattern); if (start >= source.Length) { return new object[0]; } start = normalizeIndex_(source.Length, start); if (plain) { int i = source.IndexOf(pattern, start - 1, StringComparison.CurrentCulture); if (i == -1) { return new object[0]; } else { return new object[] { i + 1, (i + pattern.Length) }; } } Regex reg = new Regex(pattern); Match match = reg.Match(source, start - 1); if (match == null || !match.Success) { return new object[0]; } return new object[] { match.Index + 1, (match.Index + match.Length) } .Concat(match.Groups.Cast<Group>().Skip(1).Select(c => c.Value)) .ToArray(); } static string format(string format, params object[] args) { CheckNotNull("string.format", format); return string.Format(format, args); } static object gmatch(string source, string pattern) { CheckNotNull("string.gmatch", source); CheckNotNull("string.gmatch", pattern); var helper = new gmatchIter(Regex.Matches(source, pattern)); return (Func<object[], string[]>)helper.gmatch_iter; } static string gsub(string source, string pattern, ILuaValue repl, int n = int.MaxValue) { CheckNotNull("string.gsub", source); CheckNotNull("string.gsub", pattern); return Regex.Replace(source, pattern, new gsubHelper(repl, n).Match); } static int len(string str) { CheckNotNull("string.len", str); return str.Length; } static string lower(string str) { CheckNotNull("string.lower", str); return str.ToLower(CultureInfo.CurrentCulture); } [MultipleReturn] static IEnumerable<string> match(string source, string pattern, int start = 1) { CheckNotNull("string.match", source); CheckNotNull("string.match", pattern); start = normalizeIndex_(source.Length, start); Regex reg = new Regex(pattern); Match match = reg.Match(source, start - 1); if (match == null || !match.Success) { return new string[0]; } if (match.Groups.Count == 1) { return new[] { match.Value }; } else { return match.Groups.Cast<Group>().Skip(1).Select(c => c.Value); } } static string rep(string str, int rep, string sep = null) { CheckNotNull("string.rep", str); if (rep < 1) { return ""; } sep ??= ""; StringBuilder ret = new StringBuilder((str.Length + sep.Length) * rep); for (int i = 0; i < rep - 1; i++) { ret.Append(str); ret.Append(sep); } ret.Append(str); return ret.ToString(); } static string reverse(string str) { CheckNotNull("string.reverse", str); // Ensure the reverse does not break surrogate pairs. var matches = Regex.Matches(str, @"\p{IsHighSurrogates}\p{IsLowSurrogates}|."); return matches.Cast<Match>().Select(c => c.Value).Reverse().Aggregate("", (a, b) => a + b); } static string sub(string source, int i, int j = -1) { CheckNotNull("string.sub", source); if (i > source.Length) { return ""; } int start = normalizeIndex_(source.Length, i); int end = normalizeIndex_(source.Length, j); if (start > end) { return ""; } return source.Substring(start - 1, end - start + 1); } static string upper(string str) { CheckNotNull("string.upper", str); return str.ToUpper(CultureInfo.CurrentCulture); } class gmatchIter { public gmatchIter(MatchCollection matches) { _matches = matches; _index = 0; } [MultipleReturn] public string[] gmatch_iter(params object[] _) { if (_matches == null || _index >= _matches.Count) { return new string[0]; } Match cur = _matches[_index]; _index++; if (cur.Groups.Count == 1) { return new[] { cur.Groups[0].Value }; } else { return cur.Groups.Cast<Group>().Select(c => c.Value).Skip(1).ToArray(); } } readonly MatchCollection _matches; int _index; } class gsubHelper { public gsubHelper(ILuaValue value, int max) { _count = 0; _max = max; if (value.ValueType == LuaValueType.String) { _string = (string)value.GetValue(); } else if (value.ValueType == LuaValueType.Table) { _table = (ILuaTable)value; } else if (value.ValueType == LuaValueType.Function) { _method = value; } else { throw new ArgumentException( "Third argument to function 'string.gsub' must be a string, table, or function."); } } public string Match(Match match) { if (_count >= _max) { return match.Value; } _count++; if (_string != null) { return Regex.Replace(_string, @"%[0-9%]", m => { if (m.Value == "%%") { return "%"; } int i = int.Parse(m.Groups[0].Value.Substring(1)); return i == 0 ? match.Value : (match.Groups.Count > i ? match.Groups[i].Value : ""); }); } else if (_table != null) { string key = match.Groups.Count == 0 ? match.Value : match.Groups[1].Value; ILuaValue value = _table.GetItemRaw(new LuaString(key)); if (value != null && value.IsTrue) { return value.ToString(); } } else if (_method != null) { var groups = match.Groups.Cast<Group>().Skip(1).Select(c => c.Value).ToArray(); var args = LuaMultiValue.CreateMultiValueFromObj(groups); LuaMultiValue obj = _method.Invoke(LuaNil.Nil, false, args); if (obj != null && obj.Count > 0) { ILuaValue value = obj[0]; if (value != null && value.IsTrue) { return value.ToString(); } } } return match.Value; } int _count; readonly int _max; readonly string _string; readonly ILuaTable _table; readonly ILuaValue _method; } } } }
// 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.Diagnostics.Contracts; namespace System { public struct Char { [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static double GetNumericValue (string! s, int index) { CodeContract.Requires(s != null); CodeContract.Requires(index < s.Length); return default(double); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static double GetNumericValue (Char c) { return default(double); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static System.Globalization.UnicodeCategory GetUnicodeCategory (string! s, int index) { CodeContract.Requires(s != null); CodeContract.Requires(index < s.Length); return default(System.Globalization.UnicodeCategory); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static System.Globalization.UnicodeCategory GetUnicodeCategory (Char c) { return default(System.Globalization.UnicodeCategory); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool IsWhiteSpace (string! s, int index) { CodeContract.Requires(s != null); CodeContract.Requires(index < s.Length); return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool IsUpper (string! s, int index) { CodeContract.Requires(s != null); CodeContract.Requires(index < s.Length); return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool IsSymbol (string! s, int index) { CodeContract.Requires(s != null); CodeContract.Requires(index < s.Length); return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool IsSymbol (Char c) { return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool IsSurrogate (string! s, int index) { CodeContract.Requires(s != null); CodeContract.Requires(index < s.Length); return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool IsSurrogate (Char c) { return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool IsSeparator (string! s, int index) { CodeContract.Requires(s != null); CodeContract.Requires(index < s.Length); return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool IsSeparator (Char c) { return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool IsPunctuation (string! s, int index) { CodeContract.Requires(s != null); CodeContract.Requires(index < s.Length); return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool IsNumber (string! s, int index) { CodeContract.Requires(s != null); CodeContract.Requires(index < s.Length); return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool IsNumber (Char c) { return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool IsLower (string! s, int index) { CodeContract.Requires(s != null); CodeContract.Requires(index < s.Length); return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool IsLetterOrDigit (string! s, int index) { CodeContract.Requires(s != null); CodeContract.Requires(index < s.Length); return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool IsLetter (string! s, int index) { CodeContract.Requires(s != null); CodeContract.Requires(index < s.Length); return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool IsDigit (string! s, int index) { CodeContract.Requires(s != null); CodeContract.Requires(index < s.Length); return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool IsControl (string! s, int index) { CodeContract.Requires(s != null); CodeContract.Requires(index < s.Length); return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool IsControl (Char c) { return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public TypeCode GetTypeCode () { return default(TypeCode); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Char ToLower (Char c) { return default(Char); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Char ToLower (Char c, System.Globalization.CultureInfo! culture) { CodeContract.Requires(culture != null); return default(Char); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Char ToUpper (Char c) { return default(Char); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Char ToUpper (Char c, System.Globalization.CultureInfo! culture) { CodeContract.Requires(culture != null); return default(Char); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool IsLetterOrDigit (Char c) { return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool IsPunctuation (Char c) { return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool IsLower (Char c) { return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool IsUpper (Char c) { return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool IsWhiteSpace (Char c) { return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool IsLetter (Char c) { return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static bool IsDigit (Char c) { return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static Char Parse (string! s) { CodeContract.Requires(s != null); CodeContract.Requires(s.Length == 1); return default(Char); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public static string ToString (Char arg0) { CodeContract.Ensures(CodeContract.Result<string>() != null); return default(string); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public string ToString (IFormatProvider provider) { CodeContract.Ensures(CodeContract.Result<string>() != null); return default(string); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public string ToString () { CodeContract.Ensures(CodeContract.Result<string>() != null); return default(string); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public int CompareTo (object value) { return default(int); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public bool Equals (object obj) { return default(bool); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public int GetHashCode () { return default(int); } } }
using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; using UnityEngine.Networking; using UnityEngine.Networking.Types; using UnityEngine.Networking.Match; using System.Collections; namespace Prototype.NetworkLobby { public class LobbyManager : NetworkLobbyManager { static short MsgKicked = MsgType.Highest + 1; static public LobbyManager s_Singleton; [Header("Unity UI Lobby")] [Tooltip("Time in second between all players ready & match start")] public float prematchCountdown = 5.0f; [Space] [Header("UI Reference")] public LobbyTopPanel topPanel; public RectTransform mainMenuPanel; public RectTransform lobbyPanel; public LobbyInfoPanel infoPanel; public LobbyCountdownPanel countdownPanel; public GameObject addPlayerButton; protected RectTransform currentPanel; public Button backButton; public Text statusInfo; public Text hostInfo; //Client numPlayers from NetworkManager is always 0, so we count (throught connect/destroy in LobbyPlayer) the number //of players, so that even client know how many player there is. [HideInInspector] public int _playerNumber = 0; //used to disconnect a client properly when exiting the matchmaker [HideInInspector] public bool _isMatchmaking = false; protected bool _disconnectServer = false; protected ulong _currentMatchID; protected LobbyHook _lobbyHooks; void Start() { s_Singleton = this; _lobbyHooks = GetComponent<Prototype.NetworkLobby.LobbyHook>(); currentPanel = mainMenuPanel; backButton.gameObject.SetActive(false); GetComponent<Canvas>().enabled = true; DontDestroyOnLoad(gameObject); SetServerInfo("Offline", "None"); } public override void OnLobbyClientSceneChanged(NetworkConnection conn) { if (SceneManager.GetSceneAt(0).name == lobbyScene) { if (topPanel.isInGame) { ChangeTo(lobbyPanel); if (_isMatchmaking) { if (conn.playerControllers[0].unetView.isServer) { backDelegate = StopHostClbk; } else { backDelegate = StopClientClbk; } } else { if (conn.playerControllers[0].unetView.isClient) { backDelegate = StopHostClbk; } else { backDelegate = StopClientClbk; } } } else { ChangeTo(mainMenuPanel); } topPanel.ToggleVisibility(true); topPanel.isInGame = false; } else { ChangeTo(null); Destroy(GameObject.Find("MainMenuUI(Clone)")); //backDelegate = StopGameClbk; topPanel.isInGame = true; topPanel.ToggleVisibility(false); } } public void ChangeTo(RectTransform newPanel) { if (currentPanel != null) { currentPanel.gameObject.SetActive(false); } if (newPanel != null) { newPanel.gameObject.SetActive(true); } currentPanel = newPanel; if (currentPanel != mainMenuPanel) { backButton.gameObject.SetActive(true); } else { backButton.gameObject.SetActive(false); SetServerInfo("Offline", "None"); _isMatchmaking = false; } } public void DisplayIsConnecting() { var _this = this; infoPanel.Display("Connecting...", "Cancel", () => { _this.backDelegate(); }); } public void SetServerInfo(string status, string host) { statusInfo.text = status; hostInfo.text = host; } public delegate void BackButtonDelegate(); public BackButtonDelegate backDelegate; public void GoBackButton() { backDelegate(); topPanel.isInGame = false; } // ----------------- Server management public void AddLocalPlayer() { TryToAddPlayer(); } public void RemovePlayer(LobbyPlayer player) { player.RemovePlayer(); } public void SimpleBackClbk() { ChangeTo(mainMenuPanel); } public void StopHostClbk() { if (_isMatchmaking) { matchMaker.DestroyMatch((NetworkID)_currentMatchID, 0, OnDestroyMatch); _disconnectServer = true; } else { StopHost(); } ChangeTo(mainMenuPanel); } public void StopClientClbk() { StopClient(); if (_isMatchmaking) { StopMatchMaker(); } ChangeTo(mainMenuPanel); } public void StopServerClbk() { StopServer(); ChangeTo(mainMenuPanel); } class KickMsg : MessageBase { } public void KickPlayer(NetworkConnection conn) { conn.Send(MsgKicked, new KickMsg()); } public void KickedMessageHandler(NetworkMessage netMsg) { infoPanel.Display("Kicked by Server", "Close", null); netMsg.conn.Disconnect(); } //=================== public override void OnStartHost() { base.OnStartHost(); ChangeTo(lobbyPanel); backDelegate = StopHostClbk; SetServerInfo("Hosting", networkAddress); } public override void OnMatchCreate(bool success, string extendedInfo, MatchInfo matchInfo) { base.OnMatchCreate(success, extendedInfo, matchInfo); _currentMatchID = (System.UInt64)matchInfo.networkId; } public override void OnDestroyMatch(bool success, string extendedInfo) { base.OnDestroyMatch(success, extendedInfo); if (_disconnectServer) { StopMatchMaker(); StopHost(); } } //allow to handle the (+) button to add/remove player public void OnPlayersNumberModified(int count) { _playerNumber += count; int localPlayerCount = 0; //foreach (PlayerController p in ClientScene.localPlayers) // localPlayerCount += (p == null || p.playerControllerId == -1) ? 0 : 1; //addPlayerButton.SetActive(localPlayerCount < maxPlayersPerConnection && _playerNumber < maxPlayers); } // ----------------- Server callbacks ------------------ //we want to disable the button JOIN if we don't have enough player //But OnLobbyClientConnect isn't called on hosting player. So we override the lobbyPlayer creation public override GameObject OnLobbyServerCreateLobbyPlayer(NetworkConnection conn, short playerControllerId) { GameObject obj = Instantiate(lobbyPlayerPrefab.gameObject) as GameObject; LobbyPlayer newPlayer = obj.GetComponent<LobbyPlayer>(); newPlayer.ToggleJoinButton(numPlayers + 1 >= minPlayers); for (int i = 0; i < lobbySlots.Length; ++i) { LobbyPlayer p = lobbySlots[i] as LobbyPlayer; if (p != null) { p.RpcUpdateRemoveButton(); p.ToggleJoinButton(numPlayers + 1 >= minPlayers); } } return obj; } public override void OnLobbyServerPlayerRemoved(NetworkConnection conn, short playerControllerId) { for (int i = 0; i < lobbySlots.Length; ++i) { LobbyPlayer p = lobbySlots[i] as LobbyPlayer; if (p != null) { p.RpcUpdateRemoveButton(); p.ToggleJoinButton(numPlayers + 1 >= minPlayers); } } } public override void OnLobbyServerDisconnect(NetworkConnection conn) { for (int i = 0; i < lobbySlots.Length; ++i) { LobbyPlayer p = lobbySlots[i] as LobbyPlayer; if (p != null) { p.RpcUpdateRemoveButton(); p.ToggleJoinButton(numPlayers >= minPlayers); } } } public override bool OnLobbyServerSceneLoadedForPlayer(GameObject lobbyPlayer, GameObject gamePlayer) { //This hook allows you to apply state data from the lobby-player to the game-player //just subclass "LobbyHook" and add it to the lobby object. if (_lobbyHooks) _lobbyHooks.OnLobbyServerSceneLoadedForPlayer(this, lobbyPlayer, gamePlayer); return true; } // --- Countdown management public override void OnLobbyServerPlayersReady() { bool allready = true; for(int i = 0; i < lobbySlots.Length; ++i) { if(lobbySlots[i] != null) allready &= lobbySlots[i].readyToBegin; } if(allready) StartCoroutine(ServerCountdownCoroutine()); } public IEnumerator ServerCountdownCoroutine() { float remainingTime = prematchCountdown; int floorTime = Mathf.FloorToInt(remainingTime); while (remainingTime > 0) { yield return null; remainingTime -= Time.deltaTime; int newFloorTime = Mathf.FloorToInt(remainingTime); if (newFloorTime != floorTime) {//to avoid flooding the network of message, we only send a notice to client when the number of plain seconds change. floorTime = newFloorTime; for (int i = 0; i < lobbySlots.Length; ++i) { if (lobbySlots[i] != null) {//there is maxPlayer slots, so some could be == null, need to test it before accessing! (lobbySlots[i] as LobbyPlayer).RpcUpdateCountdown(floorTime); } } } } for (int i = 0; i < lobbySlots.Length; ++i) { if (lobbySlots[i] != null) { (lobbySlots[i] as LobbyPlayer).RpcUpdateCountdown(0); } } ServerChangeScene(playScene); } // ----------------- Client callbacks ------------------ public override void OnClientConnect(NetworkConnection conn) { base.OnClientConnect(conn); infoPanel.gameObject.SetActive(false); conn.RegisterHandler(MsgKicked, KickedMessageHandler); if (!NetworkServer.active) {//only to do on pure client (not self hosting client) ChangeTo(lobbyPanel); backDelegate = StopClientClbk; SetServerInfo("Client", networkAddress); } } public override void OnClientDisconnect(NetworkConnection conn) { base.OnClientDisconnect(conn); ChangeTo(mainMenuPanel); } public override void OnClientError(NetworkConnection conn, int errorCode) { ChangeTo(mainMenuPanel); infoPanel.Display("Cient error : " + (errorCode == 6 ? "timeout" : errorCode.ToString()), "Close", null); } } }
// // SlnFile.cs // // Author: // Lluis Sanchez Gual <lluis@xamarin.com> // // Copyright (c) 2016 Xamarin, Inc (http://www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.IO; using System.Collections; using System.Globalization; using System.Reflection; using Microsoft.DotNet.Cli.Sln.Internal.FileManipulation; using Microsoft.DotNet.Tools.Common; namespace Microsoft.DotNet.Cli.Sln.Internal { public class SlnFile { private SlnProjectCollection _projects = new SlnProjectCollection(); private SlnSectionCollection _sections = new SlnSectionCollection(); private SlnPropertySet _metadata = new SlnPropertySet(true); private int _prefixBlankLines = 1; private TextFormatInfo _format = new TextFormatInfo(); public string FormatVersion { get; set; } public string ProductDescription { get; set; } public string VisualStudioVersion { get { return _metadata.GetValue("VisualStudioVersion"); } set { _metadata.SetValue("VisualStudioVersion", value); } } public string MinimumVisualStudioVersion { get { return _metadata.GetValue("MinimumVisualStudioVersion"); } set { _metadata.SetValue("MinimumVisualStudioVersion", value); } } public string BaseDirectory { get { return Path.GetDirectoryName(FullPath); } } public string FullPath { get; set; } public SlnPropertySet SolutionConfigurationsSection { get { return _sections .GetOrCreateSection("SolutionConfigurationPlatforms", SlnSectionType.PreProcess) .Properties; } } public SlnPropertySetCollection ProjectConfigurationsSection { get { return _sections .GetOrCreateSection("ProjectConfigurationPlatforms", SlnSectionType.PostProcess) .NestedPropertySets; } } public SlnSectionCollection Sections { get { return _sections; } } public SlnProjectCollection Projects { get { return _projects; } } public SlnFile() { _projects.ParentFile = this; _sections.ParentFile = this; } public static SlnFile Read(string file) { SlnFile slnFile = new SlnFile(); slnFile.FullPath = Path.GetFullPath(file); slnFile._format = FileUtil.GetTextFormatInfo(file); using (var sr = new StreamReader(new FileStream(file, FileMode.Open))) { slnFile.Read(sr); } return slnFile; } private void Read(TextReader reader) { const string HeaderPrefix = "Microsoft Visual Studio Solution File, Format Version"; string line; int curLineNum = 0; bool globalFound = false; bool productRead = false; while ((line = reader.ReadLine()) != null) { curLineNum++; line = line.Trim(); if (line.StartsWith(HeaderPrefix, StringComparison.Ordinal)) { if (line.Length <= HeaderPrefix.Length) { throw new InvalidSolutionFormatException( curLineNum, LocalizableStrings.FileHeaderMissingVersionError); } FormatVersion = line.Substring(HeaderPrefix.Length).Trim(); _prefixBlankLines = curLineNum - 1; } if (line.StartsWith("# ", StringComparison.Ordinal)) { if (!productRead) { productRead = true; ProductDescription = line.Substring(2); } } else if (line.StartsWith("Project", StringComparison.Ordinal)) { SlnProject p = new SlnProject(); p.Read(reader, line, ref curLineNum); _projects.Add(p); } else if (line == "Global") { if (globalFound) { throw new InvalidSolutionFormatException( curLineNum, LocalizableStrings.GlobalSectionMoreThanOnceError); } globalFound = true; while ((line = reader.ReadLine()) != null) { curLineNum++; line = line.Trim(); if (line == "EndGlobal") { break; } else if (line.StartsWith("GlobalSection", StringComparison.Ordinal)) { var sec = new SlnSection(); sec.Read(reader, line, ref curLineNum); _sections.Add(sec); } else // Ignore text that's out of place { continue; } } if (line == null) { throw new InvalidSolutionFormatException( curLineNum, LocalizableStrings.GlobalSectionNotClosedError); } } else if (line.IndexOf('=') != -1) { _metadata.ReadLine(line, curLineNum); } } if (FormatVersion == null) { throw new InvalidSolutionFormatException(LocalizableStrings.FileHeaderMissingError); } } public void Write(string file = null) { if (!string.IsNullOrEmpty(file)) { FullPath = Path.GetFullPath(file); } var sw = new StringWriter(); Write(sw); File.WriteAllText(FullPath, sw.ToString()); } private void Write(TextWriter writer) { writer.NewLine = _format.NewLine; for (int n = 0; n < _prefixBlankLines; n++) { writer.WriteLine(); } writer.WriteLine("Microsoft Visual Studio Solution File, Format Version " + FormatVersion); writer.WriteLine("# " + ProductDescription); _metadata.Write(writer); foreach (var p in _projects) { p.Write(writer); } writer.WriteLine("Global"); foreach (SlnSection s in _sections) { s.Write(writer, "GlobalSection"); } writer.WriteLine("EndGlobal"); } } public class SlnProject { private SlnSectionCollection _sections = new SlnSectionCollection(); private SlnFile _parentFile; public SlnFile ParentFile { get { return _parentFile; } internal set { _parentFile = value; _sections.ParentFile = _parentFile; } } public string Id { get; set; } public string TypeGuid { get; set; } public string Name { get; set; } private string _filePath; public string FilePath { get { return _filePath; } set { _filePath = PathUtility.RemoveExtraPathSeparators( PathUtility.GetPathWithDirectorySeparator(value)); } } public int Line { get; private set; } internal bool Processed { get; set; } public SlnSectionCollection Sections { get { return _sections; } } internal void Read(TextReader reader, string line, ref int curLineNum) { Line = curLineNum; int n = 0; FindNext(curLineNum, line, ref n, '('); n++; FindNext(curLineNum, line, ref n, '"'); int n2 = n + 1; FindNext(curLineNum, line, ref n2, '"'); TypeGuid = line.Substring(n + 1, n2 - n - 1); n = n2 + 1; FindNext(curLineNum, line, ref n, ')'); FindNext(curLineNum, line, ref n, '='); FindNext(curLineNum, line, ref n, '"'); n2 = n + 1; FindNext(curLineNum, line, ref n2, '"'); Name = line.Substring(n + 1, n2 - n - 1); n = n2 + 1; FindNext(curLineNum, line, ref n, ','); FindNext(curLineNum, line, ref n, '"'); n2 = n + 1; FindNext(curLineNum, line, ref n2, '"'); FilePath = line.Substring(n + 1, n2 - n - 1); n = n2 + 1; FindNext(curLineNum, line, ref n, ','); FindNext(curLineNum, line, ref n, '"'); n2 = n + 1; FindNext(curLineNum, line, ref n2, '"'); Id = line.Substring(n + 1, n2 - n - 1); while ((line = reader.ReadLine()) != null) { curLineNum++; line = line.Trim(); if (line == "EndProject") { return; } if (line.StartsWith("ProjectSection", StringComparison.Ordinal)) { if (_sections == null) { _sections = new SlnSectionCollection(); } var sec = new SlnSection(); _sections.Add(sec); sec.Read(reader, line, ref curLineNum); } } throw new InvalidSolutionFormatException( curLineNum, LocalizableStrings.ProjectSectionNotClosedError); } private void FindNext(int ln, string line, ref int i, char c) { var inputIndex = i; i = line.IndexOf(c, i); if (i == -1) { throw new InvalidSolutionFormatException( ln, string.Format(LocalizableStrings.ProjectParsingErrorFormatString, c, inputIndex)); } } internal void Write(TextWriter writer) { writer.Write("Project(\""); writer.Write(TypeGuid); writer.Write("\") = \""); writer.Write(Name); writer.Write("\", \""); writer.Write(PathUtility.GetPathWithBackSlashes(FilePath)); writer.Write("\", \""); writer.Write(Id); writer.WriteLine("\""); if (_sections != null) { foreach (SlnSection s in _sections) { s.Write(writer, "ProjectSection"); } } writer.WriteLine("EndProject"); } } public class SlnSection { private SlnPropertySetCollection _nestedPropertySets; private SlnPropertySet _properties; private List<string> _sectionLines; private int _baseIndex; public string Id { get; set; } public int Line { get; private set; } internal bool Processed { get; set; } public SlnFile ParentFile { get; internal set; } public bool IsEmpty { get { return (_properties == null || _properties.Count == 0) && (_nestedPropertySets == null || _nestedPropertySets.All(t => t.IsEmpty)) && (_sectionLines == null || _sectionLines.Count == 0); } } /// <summary> /// If true, this section won't be written to the file if it is empty /// </summary> /// <value><c>true</c> if skip if empty; otherwise, <c>false</c>.</value> public bool SkipIfEmpty { get; set; } public void Clear() { _properties = null; _nestedPropertySets = null; _sectionLines = null; } public SlnPropertySet Properties { get { if (_properties == null) { _properties = new SlnPropertySet(); _properties.ParentSection = this; if (_sectionLines != null) { foreach (var line in _sectionLines) { _properties.ReadLine(line, Line); } _sectionLines = null; } } return _properties; } } public SlnPropertySetCollection NestedPropertySets { get { if (_nestedPropertySets == null) { _nestedPropertySets = new SlnPropertySetCollection(this); if (_sectionLines != null) { LoadPropertySets(); } } return _nestedPropertySets; } } public void SetContent(IEnumerable<KeyValuePair<string, string>> lines) { _sectionLines = new List<string>(lines.Select(p => p.Key + " = " + p.Value)); _properties = null; _nestedPropertySets = null; } public IEnumerable<KeyValuePair<string, string>> GetContent() { if (_sectionLines != null) { return _sectionLines.Select(li => { int i = li.IndexOf('='); if (i != -1) { return new KeyValuePair<string, string>(li.Substring(0, i).Trim(), li.Substring(i + 1).Trim()); } else { return new KeyValuePair<string, string>(li.Trim(), ""); } }); } else { return new KeyValuePair<string, string>[0]; } } public SlnSectionType SectionType { get; set; } private SlnSectionType ToSectionType(int curLineNum, string s) { if (s == "preSolution" || s == "preProject") { return SlnSectionType.PreProcess; } if (s == "postSolution" || s == "postProject") { return SlnSectionType.PostProcess; } throw new InvalidSolutionFormatException( curLineNum, String.Format(LocalizableStrings.InvalidSectionTypeError, s)); } private string FromSectionType(bool isProjectSection, SlnSectionType type) { if (type == SlnSectionType.PreProcess) { return isProjectSection ? "preProject" : "preSolution"; } else { return isProjectSection ? "postProject" : "postSolution"; } } internal void Read(TextReader reader, string line, ref int curLineNum) { Line = curLineNum; int k = line.IndexOf('('); if (k == -1) { throw new InvalidSolutionFormatException( curLineNum, LocalizableStrings.SectionIdMissingError); } var tag = line.Substring(0, k).Trim(); var k2 = line.IndexOf(')', k); if (k2 == -1) { throw new InvalidSolutionFormatException( curLineNum, LocalizableStrings.SectionIdMissingError); } Id = line.Substring(k + 1, k2 - k - 1); k = line.IndexOf('=', k2); SectionType = ToSectionType(curLineNum, line.Substring(k + 1).Trim()); var endTag = "End" + tag; _sectionLines = new List<string>(); _baseIndex = ++curLineNum; while ((line = reader.ReadLine()) != null) { curLineNum++; line = line.Trim(); if (line == endTag) { break; } _sectionLines.Add(line); } if (line == null) { throw new InvalidSolutionFormatException( curLineNum, LocalizableStrings.ClosingSectionTagNotFoundError); } } private void LoadPropertySets() { if (_sectionLines != null) { SlnPropertySet curSet = null; for (int n = 0; n < _sectionLines.Count; n++) { var line = _sectionLines[n]; if (string.IsNullOrEmpty(line.Trim())) { continue; } var i = line.IndexOf('.'); if (i == -1) { throw new InvalidSolutionFormatException( _baseIndex + n, string.Format(LocalizableStrings.InvalidPropertySetFormatString, '.')); } var id = line.Substring(0, i); if (curSet == null || id != curSet.Id) { curSet = new SlnPropertySet(id); _nestedPropertySets.Add(curSet); } curSet.ReadLine(line.Substring(i + 1), _baseIndex + n); } _sectionLines = null; } } internal void Write(TextWriter writer, string sectionTag) { if (SkipIfEmpty && IsEmpty) { return; } writer.Write("\t"); writer.Write(sectionTag); writer.Write('('); writer.Write(Id); writer.Write(") = "); writer.WriteLine(FromSectionType(sectionTag == "ProjectSection", SectionType)); if (_sectionLines != null) { foreach (var l in _sectionLines) { writer.WriteLine("\t\t" + l); } } else if (_properties != null) { _properties.Write(writer); } else if (_nestedPropertySets != null) { foreach (var ps in _nestedPropertySets) { ps.Write(writer); } } writer.WriteLine("\tEnd" + sectionTag); } } /// <summary> /// A collection of properties /// </summary> public class SlnPropertySet : IDictionary<string, string> { private OrderedDictionary _values = new OrderedDictionary(); private bool _isMetadata; internal bool Processed { get; set; } public SlnFile ParentFile { get { return ParentSection != null ? ParentSection.ParentFile : null; } } public SlnSection ParentSection { get; set; } /// <summary> /// Text file line of this section in the original file /// </summary> /// <value>The line.</value> public int Line { get; private set; } internal SlnPropertySet() { } /// <summary> /// Creates a new property set with the specified ID /// </summary> /// <param name="id">Identifier.</param> public SlnPropertySet(string id) { Id = id; } internal SlnPropertySet(bool isMetadata) { _isMetadata = isMetadata; } public bool IsEmpty { get { return _values.Count == 0; } } internal void ReadLine(string line, int currentLine) { if (Line == 0) { Line = currentLine; } int k = line.IndexOf('='); if (k != -1) { var name = line.Substring(0, k).Trim(); var val = line.Substring(k + 1).Trim(); _values[name] = val; } else { line = line.Trim(); if (!string.IsNullOrWhiteSpace(line)) { _values.Add(line, null); } } } internal void Write(TextWriter writer) { foreach (DictionaryEntry e in _values) { if (!_isMetadata) { writer.Write("\t\t"); } if (Id != null) { writer.Write(Id + "."); } writer.WriteLine(e.Key + " = " + e.Value); } } public string Id { get; private set; } public string GetValue(string name, string defaultValue = null) { string res; if (TryGetValue(name, out res)) { return res; } else { return defaultValue; } } public T GetValue<T>(string name) { return (T)GetValue(name, typeof(T), default(T)); } public T GetValue<T>(string name, T defaultValue) { return (T)GetValue(name, typeof(T), defaultValue); } public object GetValue(string name, Type t, object defaultValue) { string val; if (TryGetValue(name, out val)) { if (t == typeof(bool)) { return (object)val.Equals("true", StringComparison.OrdinalIgnoreCase); } if (t.GetTypeInfo().IsEnum) { return Enum.Parse(t, val, true); } if (t.GetTypeInfo().IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) { var at = t.GetTypeInfo().GetGenericArguments()[0]; if (string.IsNullOrEmpty(val)) { return null; } return Convert.ChangeType(val, at, CultureInfo.InvariantCulture); } return Convert.ChangeType(val, t, CultureInfo.InvariantCulture); } else { return defaultValue; } } public void SetValue(string name, string value, string defaultValue = null, bool preserveExistingCase = false) { if (value == null && defaultValue == "") { value = ""; } if (value == defaultValue) { // if the value is default, only remove the property if it was not already the default // to avoid unnecessary project file churn string res; if (TryGetValue(name, out res) && !string.Equals(defaultValue ?? "", res, preserveExistingCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) { Remove(name); } return; } string currentValue; if (preserveExistingCase && TryGetValue(name, out currentValue) && string.Equals(value, currentValue, StringComparison.OrdinalIgnoreCase)) { return; } _values[name] = value; } public void SetValue(string name, object value, object defaultValue = null) { var isDefault = object.Equals(value, defaultValue); if (isDefault) { // if the value is default, only remove the property if it was not already the default // to avoid unnecessary project file churn if (ContainsKey(name) && (defaultValue == null || !object.Equals(defaultValue, GetValue(name, defaultValue.GetType(), null)))) { Remove(name); } return; } if (value is bool) { _values[name] = (bool)value ? "TRUE" : "FALSE"; } else { _values[name] = Convert.ToString(value, CultureInfo.InvariantCulture); } } void IDictionary<string, string>.Add(string key, string value) { SetValue(key, value); } public bool ContainsKey(string key) { return _values.Contains(key); } public bool Remove(string key) { var wasThere = _values.Contains(key); _values.Remove(key); return wasThere; } public bool TryGetValue(string key, out string value) { value = (string)_values[key]; return value != null; } public string this[string index] { get { return (string)_values[index]; } set { _values[index] = value; } } public ICollection<string> Values { get { return _values.Values.Cast<string>().ToList(); } } public ICollection<string> Keys { get { return _values.Keys.Cast<string>().ToList(); } } void ICollection<KeyValuePair<string, string>>.Add(KeyValuePair<string, string> item) { SetValue(item.Key, item.Value); } public void Clear() { _values.Clear(); } internal void ClearExcept(HashSet<string> keys) { foreach (var k in _values.Keys.Cast<string>().Except(keys).ToArray()) { _values.Remove(k); } } bool ICollection<KeyValuePair<string, string>>.Contains(KeyValuePair<string, string> item) { var val = GetValue(item.Key); return val == item.Value; } public void CopyTo(KeyValuePair<string, string>[] array, int arrayIndex) { foreach (DictionaryEntry de in _values) { array[arrayIndex++] = new KeyValuePair<string, string>((string)de.Key, (string)de.Value); } } bool ICollection<KeyValuePair<string, string>>.Remove(KeyValuePair<string, string> item) { if (((ICollection<KeyValuePair<string, string>>)this).Contains(item)) { Remove(item.Key); return true; } else { return false; } } public int Count { get { return _values.Count; } } internal void SetLines(IEnumerable<KeyValuePair<string, string>> lines) { _values.Clear(); foreach (var line in lines) { _values[line.Key] = line.Value; } } bool ICollection<KeyValuePair<string, string>>.IsReadOnly { get { return false; } } public IEnumerator<KeyValuePair<string, string>> GetEnumerator() { foreach (DictionaryEntry de in _values) { yield return new KeyValuePair<string, string>((string)de.Key, (string)de.Value); } } IEnumerator IEnumerable.GetEnumerator() { foreach (DictionaryEntry de in _values) { yield return new KeyValuePair<string, string>((string)de.Key, (string)de.Value); } } } public class SlnProjectCollection : Collection<SlnProject> { private SlnFile _parentFile; internal SlnFile ParentFile { get { return _parentFile; } set { _parentFile = value; foreach (var it in this) { it.ParentFile = _parentFile; } } } public SlnProject GetProject(string id) { return this.FirstOrDefault(s => s.Id == id); } public SlnProject GetOrCreateProject(string id) { var p = this.FirstOrDefault(s => s.Id.Equals(id, StringComparison.OrdinalIgnoreCase)); if (p == null) { p = new SlnProject { Id = id }; Add(p); } return p; } protected override void InsertItem(int index, SlnProject item) { base.InsertItem(index, item); item.ParentFile = ParentFile; } protected override void SetItem(int index, SlnProject item) { base.SetItem(index, item); item.ParentFile = ParentFile; } protected override void RemoveItem(int index) { var it = this[index]; it.ParentFile = null; base.RemoveItem(index); } protected override void ClearItems() { foreach (var it in this) { it.ParentFile = null; } base.ClearItems(); } } public class SlnSectionCollection : Collection<SlnSection> { private SlnFile _parentFile; internal SlnFile ParentFile { get { return _parentFile; } set { _parentFile = value; foreach (var it in this) { it.ParentFile = _parentFile; } } } public SlnSection GetSection(string id) { return this.FirstOrDefault(s => s.Id == id); } public SlnSection GetSection(string id, SlnSectionType sectionType) { return this.FirstOrDefault(s => s.Id == id && s.SectionType == sectionType); } public SlnSection GetOrCreateSection(string id, SlnSectionType sectionType) { if (id == null) { throw new ArgumentNullException("id"); } var sec = this.FirstOrDefault(s => s.Id == id); if (sec == null) { sec = new SlnSection { Id = id }; sec.SectionType = sectionType; Add(sec); } return sec; } public void RemoveSection(string id) { if (id == null) { throw new ArgumentNullException("id"); } var s = GetSection(id); if (s != null) { Remove(s); } } protected override void InsertItem(int index, SlnSection item) { base.InsertItem(index, item); item.ParentFile = ParentFile; } protected override void SetItem(int index, SlnSection item) { base.SetItem(index, item); item.ParentFile = ParentFile; } protected override void RemoveItem(int index) { var it = this[index]; it.ParentFile = null; base.RemoveItem(index); } protected override void ClearItems() { foreach (var it in this) { it.ParentFile = null; } base.ClearItems(); } } public class SlnPropertySetCollection : Collection<SlnPropertySet> { private SlnSection _parentSection; internal SlnPropertySetCollection(SlnSection parentSection) { _parentSection = parentSection; } public SlnPropertySet GetPropertySet(string id, bool ignoreCase = false) { var sc = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; return this.FirstOrDefault(s => s.Id.Equals(id, sc)); } public SlnPropertySet GetOrCreatePropertySet(string id, bool ignoreCase = false) { var ps = GetPropertySet(id, ignoreCase); if (ps == null) { ps = new SlnPropertySet(id); Add(ps); } return ps; } protected override void InsertItem(int index, SlnPropertySet item) { base.InsertItem(index, item); item.ParentSection = _parentSection; } protected override void SetItem(int index, SlnPropertySet item) { base.SetItem(index, item); item.ParentSection = _parentSection; } protected override void RemoveItem(int index) { var it = this[index]; it.ParentSection = null; base.RemoveItem(index); } protected override void ClearItems() { foreach (var it in this) { it.ParentSection = null; } base.ClearItems(); } } public class InvalidSolutionFormatException : Exception { public InvalidSolutionFormatException(string details) : base(details) { } public InvalidSolutionFormatException(int line, string details) : base(string.Format(LocalizableStrings.ErrorMessageFormatString, line, details)) { } } public enum SlnSectionType { PreProcess, PostProcess } }
namespace SlimMessageBus.Host { using System; using System.Collections.Generic; using System.Text; using SlimMessageBus.Host.Serialization; public class MessageWithHeadersSerializer : IMessageSerializer { private readonly Encoding encoding; private const int StringLengthFieldSize = sizeof(short); public const int TypeIdNull = 0; public const int TypeIdString = 1; public const int TypeIdBool = 2; public const int TypeIdInt = 3; public const int TypeIdLong = 4; public const int TypeIdGuid = 5; public MessageWithHeadersSerializer() : this(Encoding.ASCII) { } public MessageWithHeadersSerializer(Encoding encoding) => this.encoding = encoding; protected byte[] Serialize(MessageWithHeaders message) { // calculate bytes needed // 1 byte header count var payloadLength = 1; foreach (var header in message.Headers) { // 2 byte for key length + string length payloadLength += StringLengthFieldSize + encoding.GetByteCount(header.Key); // TypeId discriminator + value length in bytes payloadLength += CalculateWriteObjectByteLength(header.Value); } payloadLength += message.Payload?.Length ?? 0; // allocate bytes var payload = new byte[payloadLength]; // write bytes var i = 0; payload[i++] = (byte)message.Headers.Count; foreach (var header in message.Headers) { i += WriteString(payload, i, header.Key); i += WriteObject(payload, i, header.Value); } message.Payload?.CopyTo(payload, i); return payload; } private int WriteObject(byte[] payload, int index, object v) { switch (v) { case null: payload[index] = TypeIdNull; return 1; case string s: payload[index] = TypeIdString; return 1 + WriteString(payload, index + 1, s); case bool b: payload[index] = TypeIdBool; return 1 + WriteBool(payload, index + 1, b); case int i: payload[index] = TypeIdInt; return 1 + WriteInt(payload, index + 1, i); case long l: payload[index] = TypeIdLong; return 1 + WriteLong(payload, index + 1, l); case Guid g: payload[index] = TypeIdGuid; return 1 + WriteGuid(payload, index + 1, g); default: throw new InvalidOperationException($"Not supported header value type {v?.GetType().FullName ?? "(null)"}"); } } private int CalculateWriteObjectByteLength(object v) { var byteLength = v switch { null => 0, string s => StringLengthFieldSize + encoding.GetByteCount(s), bool _ => sizeof(byte), int _ => sizeof(int), long _ => sizeof(long), Guid _ => 16, _ => throw new InvalidOperationException($"Not supported header value type {v?.GetType().FullName ?? "(null)"}"), }; return 1 + byteLength; } private int WriteString(byte[] payload, int index, string s) { var count = encoding.GetBytes(s, 0, s.Length, payload, index + StringLengthFieldSize); // Write string length (byte length) BitConverter.TryWriteBytes(payload.AsSpan(index), (short)count); return count + StringLengthFieldSize; } private static int WriteBool(byte[] payload, int index, bool v) { payload[index] = v ? (byte)1 : (byte)0; return sizeof(byte); } private static int WriteInt(byte[] payload, int index, int v) { BitConverter.TryWriteBytes(payload.AsSpan(index), v); return sizeof(int); } private static int WriteLong(byte[] payload, int index, long v) { BitConverter.TryWriteBytes(payload.AsSpan(index), v); return sizeof(long); } private static int WriteGuid(byte[] payload, int index, Guid v) { v.TryWriteBytes(payload.AsSpan(index)); return 16; } private int ReadObject(byte[] payload, int index, out object o) { int byteLength; var typeId = payload[index]; switch (typeId) { case TypeIdNull: byteLength = 0; o = null; break; case TypeIdString: byteLength = ReadString(payload, index + 1, out var s); o = s; break; case TypeIdBool: byteLength = ReadBool(payload, index + 1, out var b); o = b; break; case TypeIdInt: byteLength = ReadInt(payload, index + 1, out var i); o = i; break; case TypeIdLong: byteLength = ReadLong(payload, index + 1, out var l); o = l; break; case TypeIdGuid: byteLength = ReadGuid(payload, index + 1, out var g); o = g; break; default: throw new InvalidOperationException($"Unknown field type with discriminator {typeId}"); } // Type Discriminator length (1 byte) + value length return 1 + byteLength; } private int ReadString(byte[] payload, int index, out string v) { var count = BitConverter.ToInt16(payload, index); v = encoding.GetString(payload, index + StringLengthFieldSize, count); return count + StringLengthFieldSize; } private static int ReadBool(byte[] payload, int index, out bool v) { v = payload[index] == 1; return sizeof(byte); } private static int ReadInt(byte[] payload, int index, out int v) { v = BitConverter.ToInt32(payload, index); return sizeof(int); } private static int ReadLong(byte[] payload, int index, out long v) { v = BitConverter.ToInt64(payload, index); return sizeof(long); } private static int ReadGuid(byte[] payload, int index, out Guid v) { v = new Guid(payload.AsSpan(index, 16)); return 16; } protected MessageWithHeaders Deserialize(byte[] payload) { if (payload is null) throw new ArgumentNullException(nameof(payload)); var messageHeaders = new Dictionary<string, object>(); var i = 0; var headerCount = payload[i++]; for (var headerIndex = 0; headerIndex < headerCount; headerIndex++) { i += ReadString(payload, i, out var key); i += ReadObject(payload, i, out var value); messageHeaders.Add(key, value); } byte[] messagePayload = null; var payloadSize = payload.Length - i; if (payloadSize > 0) { messagePayload = new byte[payload.Length - i]; Array.Copy(payload, i, messagePayload, 0, messagePayload.Length); } return new MessageWithHeaders(messagePayload, messageHeaders); } #region Implementation of IMessageSerializer public byte[] Serialize(Type t, object message) => Serialize((MessageWithHeaders)message); public object Deserialize(Type t, byte[] payload) => Deserialize(payload); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Text; using System.Threading; using System.Runtime.InteropServices.ComTypes; using Internal.Runtime.CompilerHelpers; namespace System.Runtime.InteropServices { public static partial class Marshal { #if PLATFORM_WINDOWS private const long HIWORDMASK = unchecked((long)0xffffffffffff0000L); // Win32 has the concept of Atoms, where a pointer can either be a pointer // or an int. If it's less than 64K, this is guaranteed to NOT be a // pointer since the bottom 64K bytes are reserved in a process' page table. // We should be careful about deallocating this stuff. Extracted to // a function to avoid C# problems with lack of support for IntPtr. // We have 2 of these methods for slightly different semantics for NULL. private static bool IsWin32Atom(IntPtr ptr) { long lPtr = (long)ptr; return 0 == (lPtr & HIWORDMASK); } private static bool IsNotWin32Atom(IntPtr ptr) { long lPtr = (long)ptr; return 0 != (lPtr & HIWORDMASK); } #else // PLATFORM_WINDOWS private static bool IsWin32Atom(IntPtr ptr) => false; private static bool IsNotWin32Atom(IntPtr ptr) => true; #endif // PLATFORM_WINDOWS //==================================================================== // The default character size for the system. This is always 2 because // the framework only runs on UTF-16 systems. //==================================================================== public static readonly int SystemDefaultCharSize = 2; //==================================================================== // The max DBCS character size for the system. //==================================================================== public static readonly int SystemMaxDBCSCharSize = PInvokeMarshal.GetSystemMaxDBCSCharSize(); public static unsafe String PtrToStringAnsi(IntPtr ptr) { if (IntPtr.Zero == ptr) { return null; } else if (IsWin32Atom(ptr)) { return null; } else { int nb = lstrlenA(ptr); if (nb == 0) { return string.Empty; } else { return new string((sbyte*)ptr); } } } public static unsafe String PtrToStringAnsi(IntPtr ptr, int len) { if (ptr == IntPtr.Zero) throw new ArgumentNullException(nameof(ptr)); if (len < 0) throw new ArgumentException(nameof(len)); return ConvertToUnicode(ptr, len); } public static unsafe String PtrToStringUni(IntPtr ptr, int len) { return PInvokeMarshal.PtrToStringUni(ptr, len); } public static unsafe String PtrToStringUni(IntPtr ptr) { return PInvokeMarshal.PtrToStringUni(ptr); } public static String PtrToStringAuto(IntPtr ptr, int len) { // Ansi platforms are no longer supported return PtrToStringUni(ptr, len); } public static String PtrToStringAuto(IntPtr ptr) { // Ansi platforms are no longer supported return PtrToStringUni(ptr); } public static unsafe String PtrToStringUTF8(IntPtr ptr) { if (IntPtr.Zero == ptr) { return null; } else { int nbBytes = lstrlenA(ptr); return PtrToStringUTF8(ptr, nbBytes); } } public static unsafe String PtrToStringUTF8(IntPtr ptr, int byteLen) { if (byteLen < 0) { throw new ArgumentOutOfRangeException(nameof(byteLen), SR.ArgumentOutOfRange_NeedNonNegNum); } else if (IntPtr.Zero == ptr) { return null; } else if (IsWin32Atom(ptr)) { return null; } else if (byteLen == 0) { return string.Empty; } else { byte* pByte = (byte*)ptr.ToPointer(); return Encoding.UTF8.GetString(pByte, byteLen); } } //==================================================================== // SizeOf() //==================================================================== /// <summary> /// Returns the size of an instance of a value type. /// </summary> public static int SizeOf<T>() { return SizeOf(typeof(T)); } public static int SizeOf<T>(T structure) { return SizeOf((object)structure); } public static int SizeOf(object structure) { if (structure == null) throw new ArgumentNullException(nameof(structure)); // we never had a check for generics here return SizeOfHelper(structure.GetType()); } public static int SizeOf(Type t) { if (t == null) throw new ArgumentNullException(nameof(t)); if (t.TypeHandle.IsGenericType() || t.TypeHandle.IsGenericTypeDefinition()) throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t)); return SizeOfHelper(t); } private static int SizeOfHelper(Type t) { RuntimeTypeHandle typeHandle = t.TypeHandle; if (RuntimeInteropData.Instance.TryGetStructUnsafeStructSize(typeHandle, out int size)) { return size; } // IsBlittable() checks whether the type contains GC references. It is approximate check with false positives. // This fallback path will return incorrect answer for types that do not contain GC references, but that are // not actually blittable; e.g. for types with bool fields. if (typeHandle.IsBlittable() && typeHandle.IsValueType()) { return typeHandle.GetValueTypeSize(); } throw new MissingInteropDataException(SR.StructMarshalling_MissingInteropData, t); } //==================================================================== // OffsetOf() //==================================================================== public static IntPtr OffsetOf(Type t, String fieldName) { if (t == null) throw new ArgumentNullException(nameof(t)); if (String.IsNullOrEmpty(fieldName)) throw new ArgumentNullException(nameof(fieldName)); if (t.TypeHandle.IsGenericType() || t.TypeHandle.IsGenericTypeDefinition()) throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t)); if (RuntimeInteropData.Instance.TryGetStructFieldOffset(t.TypeHandle, fieldName, out bool structExists, out uint offset)) { return new IntPtr(offset); } // if we can find the struct but couldn't find its field, throw Argument Exception if (structExists) { throw new ArgumentException(SR.Format(SR.Argument_OffsetOfFieldNotFound, t.TypeHandle.GetDisplayName()), nameof(fieldName)); } throw new MissingInteropDataException(SR.StructMarshalling_MissingInteropData, t); } public static IntPtr OffsetOf<T>(String fieldName) { return OffsetOf(typeof(T), fieldName); } //==================================================================== // Copy blocks from CLR arrays to native memory. //==================================================================== public static void Copy(int[] source, int startIndex, IntPtr destination, int length) { PInvokeMarshal.CopyToNative(source, startIndex, destination, length); } public static void Copy(char[] source, int startIndex, IntPtr destination, int length) { PInvokeMarshal.CopyToNative(source, startIndex, destination, length); } public static void Copy(short[] source, int startIndex, IntPtr destination, int length) { PInvokeMarshal.CopyToNative(source, startIndex, destination, length); } public static void Copy(long[] source, int startIndex, IntPtr destination, int length) { PInvokeMarshal.CopyToNative(source, startIndex, destination, length); } public static void Copy(float[] source, int startIndex, IntPtr destination, int length) { PInvokeMarshal.CopyToNative(source, startIndex, destination, length); } public static void Copy(double[] source, int startIndex, IntPtr destination, int length) { PInvokeMarshal.CopyToNative(source, startIndex, destination, length); } public static void Copy(byte[] source, int startIndex, IntPtr destination, int length) { PInvokeMarshal.CopyToNative(source, startIndex, destination, length); } public static void Copy(IntPtr[] source, int startIndex, IntPtr destination, int length) { PInvokeMarshal.CopyToNative(source, startIndex, destination, length); } //==================================================================== // Copy blocks from native memory to CLR arrays //==================================================================== public static void Copy(IntPtr source, int[] destination, int startIndex, int length) { PInvokeMarshal.CopyToManaged(source, destination, startIndex, length); } public static void Copy(IntPtr source, char[] destination, int startIndex, int length) { PInvokeMarshal.CopyToManaged(source, destination, startIndex, length); } public static void Copy(IntPtr source, short[] destination, int startIndex, int length) { PInvokeMarshal.CopyToManaged(source, destination, startIndex, length); } public static void Copy(IntPtr source, long[] destination, int startIndex, int length) { PInvokeMarshal.CopyToManaged(source, destination, startIndex, length); } public static void Copy(IntPtr source, float[] destination, int startIndex, int length) { PInvokeMarshal.CopyToManaged(source, destination, startIndex, length); } public static void Copy(IntPtr source, double[] destination, int startIndex, int length) { PInvokeMarshal.CopyToManaged(source, destination, startIndex, length); } public static void Copy(IntPtr source, byte[] destination, int startIndex, int length) { PInvokeMarshal.CopyToManaged(source, destination, startIndex, length); } public static void Copy(IntPtr source, IntPtr[] destination, int startIndex, int length) { PInvokeMarshal.CopyToManaged(source, destination, startIndex, length); } //==================================================================== // Read from memory //==================================================================== public static unsafe byte ReadByte(IntPtr ptr, int ofs) { byte* addr = (byte*)ptr + ofs; return *addr; } public static byte ReadByte(IntPtr ptr) { return ReadByte(ptr, 0); } public static unsafe short ReadInt16(IntPtr ptr, int ofs) { byte* addr = (byte*)ptr + ofs; if ((unchecked((int)addr) & 0x1) == 0) { // aligned read return *((short*)addr); } else { // unaligned read short val; byte* valPtr = (byte*)&val; valPtr[0] = addr[0]; valPtr[1] = addr[1]; return val; } } public static short ReadInt16(IntPtr ptr) { return ReadInt16(ptr, 0); } public static unsafe int ReadInt32(IntPtr ptr, int ofs) { byte* addr = (byte*)ptr + ofs; if ((unchecked((int)addr) & 0x3) == 0) { // aligned read return *((int*)addr); } else { // unaligned read int val; byte* valPtr = (byte*)&val; valPtr[0] = addr[0]; valPtr[1] = addr[1]; valPtr[2] = addr[2]; valPtr[3] = addr[3]; return val; } } public static int ReadInt32(IntPtr ptr) { return ReadInt32(ptr, 0); } public static IntPtr ReadIntPtr([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs) { if (IntPtr.Size == 4) return (IntPtr)ReadInt32(ptr, ofs); else return (IntPtr)ReadInt64(ptr, ofs); } public static IntPtr ReadIntPtr(IntPtr ptr, int ofs) { if (IntPtr.Size == 4) return (IntPtr)ReadInt32(ptr, ofs); else return (IntPtr)ReadInt64(ptr, ofs); } public static IntPtr ReadIntPtr(IntPtr ptr) { return ReadIntPtr(ptr, 0); } public static unsafe long ReadInt64(IntPtr ptr, int ofs) { byte* addr = (byte*)ptr + ofs; if ((unchecked((int)addr) & 0x7) == 0) { // aligned read return *((long*)addr); } else { // unaligned read long val; byte* valPtr = (byte*)&val; valPtr[0] = addr[0]; valPtr[1] = addr[1]; valPtr[2] = addr[2]; valPtr[3] = addr[3]; valPtr[4] = addr[4]; valPtr[5] = addr[5]; valPtr[6] = addr[6]; valPtr[7] = addr[7]; return val; } } public static long ReadInt64(IntPtr ptr) { return ReadInt64(ptr, 0); } //==================================================================== // Write to memory //==================================================================== public static unsafe void WriteByte(IntPtr ptr, int ofs, byte val) { byte* addr = (byte*)ptr + ofs; *addr = val; } public static void WriteByte(IntPtr ptr, byte val) { WriteByte(ptr, 0, val); } public static unsafe void WriteInt16(IntPtr ptr, int ofs, short val) { byte* addr = (byte*)ptr + ofs; if ((unchecked((int)addr) & 0x1) == 0) { // aligned write *((short*)addr) = val; } else { // unaligned write byte* valPtr = (byte*)&val; addr[0] = valPtr[0]; addr[1] = valPtr[1]; } } public static void WriteInt16(IntPtr ptr, short val) { WriteInt16(ptr, 0, val); } public static void WriteInt16(IntPtr ptr, int ofs, char val) { WriteInt16(ptr, ofs, (short)val); } public static void WriteInt16([In, Out]Object ptr, int ofs, char val) { WriteInt16(ptr, ofs, (short)val); } public static void WriteInt16(IntPtr ptr, char val) { WriteInt16(ptr, 0, (short)val); } public static unsafe void WriteInt32(IntPtr ptr, int ofs, int val) { byte* addr = (byte*)ptr + ofs; if ((unchecked((int)addr) & 0x3) == 0) { // aligned write *((int*)addr) = val; } else { // unaligned write byte* valPtr = (byte*)&val; addr[0] = valPtr[0]; addr[1] = valPtr[1]; addr[2] = valPtr[2]; addr[3] = valPtr[3]; } } public static void WriteInt32(IntPtr ptr, int val) { WriteInt32(ptr, 0, val); } public static void WriteIntPtr(IntPtr ptr, int ofs, IntPtr val) { if (IntPtr.Size == 4) WriteInt32(ptr, ofs, (int)val); else WriteInt64(ptr, ofs, (long)val); } public static void WriteIntPtr([MarshalAs(UnmanagedType.AsAny), In, Out] Object ptr, int ofs, IntPtr val) { if (IntPtr.Size == 4) WriteInt32(ptr, ofs, (int)val); else WriteInt64(ptr, ofs, (long)val); } public static void WriteIntPtr(IntPtr ptr, IntPtr val) { WriteIntPtr(ptr, 0, val); } public static unsafe void WriteInt64(IntPtr ptr, int ofs, long val) { byte* addr = (byte*)ptr + ofs; if ((unchecked((int)addr) & 0x7) == 0) { // aligned write *((long*)addr) = val; } else { // unaligned write byte* valPtr = (byte*)&val; addr[0] = valPtr[0]; addr[1] = valPtr[1]; addr[2] = valPtr[2]; addr[3] = valPtr[3]; addr[4] = valPtr[4]; addr[5] = valPtr[5]; addr[6] = valPtr[6]; addr[7] = valPtr[7]; } } public static void WriteInt64(IntPtr ptr, long val) { WriteInt64(ptr, 0, val); } //==================================================================== // GetHRForLastWin32Error //==================================================================== public static int GetHRForLastWin32Error() { int dwLastError = GetLastWin32Error(); if ((dwLastError & 0x80000000) == 0x80000000) { return dwLastError; } else { return (dwLastError & 0x0000FFFF) | unchecked((int)0x80070000); } } public static Exception GetExceptionForHR(int errorCode, IntPtr errorInfo) { #if ENABLE_WINRT if (errorInfo != new IntPtr(-1)) { throw new PlatformNotSupportedException(); } return ExceptionHelpers.GetMappingExceptionForHR( errorCode, message: null, createCOMException: false, hasErrorInfo: false); #else return new COMException() { HResult = errorCode }; #endif // ENABLE_WINRT } //==================================================================== // Throws a CLR exception based on the HRESULT. //==================================================================== public static void ThrowExceptionForHR(int errorCode) { ThrowExceptionForHRInternal(errorCode, new IntPtr(-1)); } public static void ThrowExceptionForHR(int errorCode, IntPtr errorInfo) { ThrowExceptionForHRInternal(errorCode, errorInfo); } private static void ThrowExceptionForHRInternal(int errorCode, IntPtr errorInfo) { if (errorCode < 0) { throw GetExceptionForHR(errorCode, errorInfo); } } //==================================================================== // Memory allocation and deallocation. //==================================================================== public static unsafe IntPtr ReAllocHGlobal(IntPtr pv, IntPtr cb) { return PInvokeMarshal.MemReAlloc(pv, cb); } private static unsafe void ConvertToAnsi(string source, IntPtr pbNativeBuffer, int cbNativeBuffer) { Debug.Assert(source != null); Debug.Assert(pbNativeBuffer != IntPtr.Zero); Debug.Assert(cbNativeBuffer >= (source.Length + 1) * SystemMaxDBCSCharSize, "Insufficient buffer length passed to ConvertToAnsi"); fixed (char* pch = source) { int convertedBytes = PInvokeMarshal.ConvertWideCharToMultiByte(pch, source.Length, (byte*)pbNativeBuffer, cbNativeBuffer, false, false); ((byte*)pbNativeBuffer)[convertedBytes] = 0; } } private static unsafe string ConvertToUnicode(IntPtr sourceBuffer, int cbSourceBuffer) { if (IsWin32Atom(sourceBuffer)) { throw new ArgumentException(SR.Arg_MustBeStringPtrNotAtom); } if (sourceBuffer == IntPtr.Zero || cbSourceBuffer == 0) { return String.Empty; } // MB_PRECOMPOSED is the default. int charsRequired = PInvokeMarshal.GetCharCount((byte*)sourceBuffer, cbSourceBuffer); if (charsRequired == 0) { throw new ArgumentException(SR.Arg_InvalidANSIString); } char[] wideChars = new char[charsRequired + 1]; fixed (char* pWideChars = &wideChars[0]) { int converted = PInvokeMarshal.ConvertMultiByteToWideChar((byte*)sourceBuffer, cbSourceBuffer, pWideChars, wideChars.Length); if (converted == 0) { throw new ArgumentException(SR.Arg_InvalidANSIString); } wideChars[converted] = '\0'; return new String(pWideChars); } } private static unsafe int lstrlenA(IntPtr sz) { Debug.Assert(sz != IntPtr.Zero); byte* pb = (byte*)sz; byte* start = pb; while (*pb != 0) { ++pb; } return (int)(pb - start); } private static unsafe int lstrlenW(IntPtr wsz) { Debug.Assert(wsz != IntPtr.Zero); char* pc = (char*)wsz; char* start = pc; while (*pc != 0) { ++pc; } return (int)(pc - start); } // Zero out the buffer pointed to by ptr, making sure that the compiler cannot // replace the zeroing with a nop private static unsafe void SecureZeroMemory(IntPtr ptr, int bytes) { Debug.Assert(ptr != IntPtr.Zero); Debug.Assert(bytes >= 0); byte* pBuffer = (byte*)ptr; for (int i = 0; i < bytes; ++i) { Volatile.Write(ref pBuffer[i], 0); } } //==================================================================== // String convertions. //==================================================================== public static unsafe IntPtr StringToHGlobalAnsi(String s) { if (s == null) { return IntPtr.Zero; } else { int nb = (s.Length + 1) * SystemMaxDBCSCharSize; // Overflow checking if (nb < s.Length) throw new ArgumentOutOfRangeException(nameof(s)); IntPtr hglobal = PInvokeMarshal.MemAlloc(new IntPtr(nb)); ConvertToAnsi(s, hglobal, nb); return hglobal; } } public static unsafe IntPtr StringToHGlobalUni(String s) { if (s == null) { return IntPtr.Zero; } else { int nb = (s.Length + 1) * 2; // Overflow checking if (nb < s.Length) throw new ArgumentOutOfRangeException(nameof(s)); IntPtr hglobal = PInvokeMarshal.MemAlloc(new IntPtr(nb)); fixed (char* firstChar = s) { InteropExtensions.Memcpy(hglobal, new IntPtr(firstChar), nb); } return hglobal; } } public static IntPtr StringToHGlobalAuto(String s) { // Ansi platforms are no longer supported return StringToHGlobalUni(s); } //==================================================================== // return the IUnknown* for an Object if the current context // is the one where the RCW was first seen. Will return null // otherwise. //==================================================================== public static IntPtr /* IUnknown* */ GetIUnknownForObject(Object o) { if (o == null) { throw new ArgumentNullException(nameof(o)); } return McgMarshal.ObjectToComInterface(o, InternalTypes.IUnknown); } //==================================================================== // return an Object for IUnknown //==================================================================== public static Object GetObjectForIUnknown(IntPtr /* IUnknown* */ pUnk) { if (pUnk == default(IntPtr)) { throw new ArgumentNullException(nameof(pUnk)); } return McgMarshal.ComInterfaceToObject(pUnk, InternalTypes.IUnknown); } //==================================================================== // check if the object is classic COM component //==================================================================== public static bool IsComObject(Object o) { if (o == null) throw new ArgumentNullException(nameof(o), SR.Arg_InvalidHandle); return McgMarshal.IsComObject(o); } public static unsafe IntPtr StringToCoTaskMemUni(String s) { if (s == null) { return IntPtr.Zero; } else { int nb = (s.Length + 1) * 2; // Overflow checking if (nb < s.Length) throw new ArgumentOutOfRangeException(nameof(s)); IntPtr hglobal = PInvokeMarshal.CoTaskMemAlloc(new UIntPtr((uint)nb)); if (hglobal == IntPtr.Zero) { throw new OutOfMemoryException(); } else { fixed (char* firstChar = s) { InteropExtensions.Memcpy(hglobal, new IntPtr(firstChar), nb); } return hglobal; } } } public static unsafe IntPtr StringToCoTaskMemUTF8(String s) { if (s == null) { return IntPtr.Zero; } else { int nb = Encoding.UTF8.GetMaxByteCount(s.Length); IntPtr pMem = PInvokeMarshal.CoTaskMemAlloc(new UIntPtr((uint)nb + 1)); if (pMem == IntPtr.Zero) { throw new OutOfMemoryException(); } else { fixed (char* firstChar = s) { byte* pbMem = (byte*)pMem; int nbWritten = Encoding.UTF8.GetBytes(firstChar, s.Length, pbMem, nb); pbMem[nbWritten] = 0; } return pMem; } } } public static unsafe IntPtr StringToCoTaskMemAnsi(String s) { if (s == null) { return IntPtr.Zero; } else { int nb = (s.Length + 1) * SystemMaxDBCSCharSize; // Overflow checking if (nb < s.Length) throw new ArgumentOutOfRangeException(nameof(s)); IntPtr hglobal = PInvokeMarshal.CoTaskMemAlloc(new UIntPtr((uint)nb)); if (hglobal == IntPtr.Zero) { throw new OutOfMemoryException(); } else { ConvertToAnsi(s, hglobal, nb); return hglobal; } } } public static IntPtr StringToCoTaskMemAuto(String s) { // Ansi platforms are no longer supported return StringToCoTaskMemUni(s); } //==================================================================== // release the COM component and if the reference hits 0 zombie this object // further usage of this Object might throw an exception //==================================================================== public static int ReleaseComObject(Object o) { if (o == null) throw new ArgumentNullException(nameof(o)); __ComObject co = null; // Make sure the obj is an __ComObject. try { co = (__ComObject)o; } catch (InvalidCastException) { throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o)); } return McgMarshal.Release(co); } //==================================================================== // release the COM component and zombie this object // further usage of this Object might throw an exception //==================================================================== public static Int32 FinalReleaseComObject(Object o) { if (o == null) throw new ArgumentNullException(nameof(o)); __ComObject co = null; // Make sure the obj is an __ComObject. try { co = (__ComObject)o; } catch (InvalidCastException) { throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o)); } co.FinalReleaseSelf(); return 0; } //==================================================================== // IUnknown Helpers //==================================================================== public static int /* HRESULT */ QueryInterface(IntPtr /* IUnknown */ pUnk, ref Guid iid, out IntPtr ppv) { if (pUnk == IntPtr.Zero) throw new ArgumentNullException(nameof(pUnk)); return McgMarshal.ComQueryInterfaceWithHR(pUnk, ref iid, out ppv); } public static int /* ULONG */ AddRef(IntPtr /* IUnknown */ pUnk) { if (pUnk == IntPtr.Zero) throw new ArgumentNullException(nameof(pUnk)); return McgMarshal.ComAddRef(pUnk); } public static int /* ULONG */ Release(IntPtr /* IUnknown */ pUnk) { if (pUnk == IntPtr.Zero) throw new ArgumentNullException(nameof(pUnk)); // This is documented to have "undefined behavior" when the ref count is already zero, so // let's not AV if we can help it return McgMarshal.ComSafeRelease(pUnk); } public static IntPtr ReAllocCoTaskMem(IntPtr pv, int cb) { IntPtr pNewMem = PInvokeMarshal.CoTaskMemReAlloc(pv, new IntPtr(cb)); if (pNewMem == IntPtr.Zero && cb != 0) { throw new OutOfMemoryException(); } return pNewMem; } //==================================================================== // BSTR allocation and dealocation. //==================================================================== public static void FreeBSTR(IntPtr ptr) { if (IsNotWin32Atom(ptr)) { McgMarshal.SysFreeString(ptr); } } public static unsafe IntPtr StringToBSTR(String s) { if (s == null) return IntPtr.Zero; // Overflow checking if (s.Length + 1 < s.Length) throw new ArgumentOutOfRangeException(nameof(s)); fixed (char* pch = s) { IntPtr bstr = new IntPtr(ExternalInterop.SysAllocStringLen(pch, (uint)s.Length)); if (bstr == IntPtr.Zero) throw new OutOfMemoryException(); return bstr; } } public static String PtrToStringBSTR(IntPtr ptr) { return PtrToStringUni(ptr, (int)ExternalInterop.SysStringLen(ptr)); } public static void ZeroFreeBSTR(IntPtr s) { SecureZeroMemory(s, (int)ExternalInterop.SysStringLen(s) * 2); FreeBSTR(s); } public static void ZeroFreeCoTaskMemAnsi(IntPtr s) { SecureZeroMemory(s, lstrlenA(s)); FreeCoTaskMem(s); } public static void ZeroFreeCoTaskMemUnicode(IntPtr s) { SecureZeroMemory(s, lstrlenW(s)); FreeCoTaskMem(s); } public static unsafe void ZeroFreeCoTaskMemUTF8(IntPtr s) { SecureZeroMemory(s, lstrlenA(s)); FreeCoTaskMem(s); } public static void ZeroFreeGlobalAllocAnsi(IntPtr s) { SecureZeroMemory(s, lstrlenA(s)); FreeHGlobal(s); } public static void ZeroFreeGlobalAllocUnicode(IntPtr s) { SecureZeroMemory(s, lstrlenW(s)); FreeHGlobal(s); } /// <summary> /// Returns the unmanaged function pointer for this delegate /// </summary> public static IntPtr GetFunctionPointerForDelegate(Delegate d) { if (d == null) throw new ArgumentNullException(nameof(d)); return PInvokeMarshal.GetFunctionPointerForDelegate(d); } public static IntPtr GetFunctionPointerForDelegate<TDelegate>(TDelegate d) { return GetFunctionPointerForDelegate((Delegate)(object)d); } //==================================================================== // Marshals data from a native memory block to a preallocated structure class. //==================================================================== private static unsafe void PtrToStructureHelper(IntPtr ptr, Object structure) { RuntimeTypeHandle structureTypeHandle = structure.GetType().TypeHandle; // Boxed struct start at offset 1 (EEType* at offset 0) while class start at offset 0 int offset = structureTypeHandle.IsValueType() ? 1 : 0; bool useMemCpy = false; if (RuntimeInteropData.Instance.TryGetStructUnmarshalStub(structureTypeHandle, out IntPtr unmarshalStub)) { if (unmarshalStub != IntPtr.Zero) { InteropExtensions.PinObjectAndCall(structure, unboxedStructPtr => { CalliIntrinsics.Call<int>( unmarshalStub, (void*)ptr, // unsafe (no need to adjust as it is always struct) ((void*)((IntPtr*)unboxedStructPtr + offset)) // safe (need to adjust offset as it could be class) ); }); return; } useMemCpy = true; } if (useMemCpy || structureTypeHandle.IsBlittable()) { int structSize = Marshal.SizeOf(structure); InteropExtensions.PinObjectAndCall(structure, unboxedStructPtr => { InteropExtensions.Memcpy( (IntPtr)((IntPtr*)unboxedStructPtr + offset), // safe (need to adjust offset as it could be class) ptr, // unsafe (no need to adjust as it is always struct) structSize ); }); return; } throw new MissingInteropDataException(SR.StructMarshalling_MissingInteropData, structure.GetType()); } //==================================================================== // Creates a new instance of "structuretype" and marshals data from a // native memory block to it. //==================================================================== public static Object PtrToStructure(IntPtr ptr, Type structureType) { if (ptr == IntPtr.Zero) throw new ArgumentNullException(nameof(ptr)); if (structureType == null) throw new ArgumentNullException(nameof(structureType)); Object boxedStruct = InteropExtensions.RuntimeNewObject(structureType.TypeHandle); PtrToStructureHelper(ptr, boxedStruct); return boxedStruct; } public static T PtrToStructure<T>(IntPtr ptr) { return (T)PtrToStructure(ptr, typeof(T)); } public static void PtrToStructure(IntPtr ptr, Object structure) { if (ptr == IntPtr.Zero) throw new ArgumentNullException(nameof(ptr)); if (structure == null) throw new ArgumentNullException(nameof(structure)); RuntimeTypeHandle structureTypeHandle = structure.GetType().TypeHandle; if (structureTypeHandle.IsValueType()) { throw new ArgumentException(nameof(structure), SR.Argument_StructMustNotBeValueClass); } PtrToStructureHelper(ptr, structure); } public static void PtrToStructure<T>(IntPtr ptr, T structure) { PtrToStructure(ptr, (object)structure); } //==================================================================== // Marshals data from a structure class to a native memory block. // If the structure contains pointers to allocated blocks and // "fDeleteOld" is true, this routine will call DestroyStructure() first. //==================================================================== public static unsafe void StructureToPtr(Object structure, IntPtr ptr, bool fDeleteOld) { if (structure == null) throw new ArgumentNullException(nameof(structure)); if (ptr == IntPtr.Zero) throw new ArgumentNullException(nameof(ptr)); if (fDeleteOld) { DestroyStructure(ptr, structure.GetType()); } RuntimeTypeHandle structureTypeHandle = structure.GetType().TypeHandle; if (structureTypeHandle.IsGenericType() || structureTypeHandle.IsGenericTypeDefinition()) { throw new ArgumentException(nameof(structure), SR.Argument_NeedNonGenericObject); } // Boxed struct start at offset 1 (EEType* at offset 0) while class start at offset 0 int offset = structureTypeHandle.IsValueType() ? 1 : 0; bool useMemCpy = false; if (RuntimeInteropData.Instance.TryGetStructMarshalStub(structureTypeHandle, out IntPtr marshalStub)) { if (marshalStub != IntPtr.Zero) { InteropExtensions.PinObjectAndCall(structure, unboxedStructPtr => { CalliIntrinsics.Call<int>( marshalStub, ((void*)((IntPtr*)unboxedStructPtr + offset)), // safe (need to adjust offset as it could be class) (void*)ptr // unsafe (no need to adjust as it is always struct) ); }); return; } useMemCpy = true; } if (useMemCpy || structureTypeHandle.IsBlittable()) { int structSize = Marshal.SizeOf(structure); InteropExtensions.PinObjectAndCall(structure, unboxedStructPtr => { InteropExtensions.Memcpy( ptr, // unsafe (no need to adjust as it is always struct) (IntPtr)((IntPtr*)unboxedStructPtr + offset), // safe (need to adjust offset as it could be class) structSize ); }); return; } throw new MissingInteropDataException(SR.StructMarshalling_MissingInteropData, structure.GetType()); } public static void StructureToPtr<T>(T structure, IntPtr ptr, bool fDeleteOld) { StructureToPtr((object)structure, ptr, fDeleteOld); } //==================================================================== // DestroyStructure() // //==================================================================== public static unsafe void DestroyStructure(IntPtr ptr, Type structuretype) { if (ptr == IntPtr.Zero) throw new ArgumentNullException(nameof(ptr)); if (structuretype == null) throw new ArgumentNullException(nameof(structuretype)); RuntimeTypeHandle structureTypeHandle = structuretype.TypeHandle; if (structureTypeHandle.IsGenericType() || structureTypeHandle.IsGenericTypeDefinition()) throw new ArgumentException(SR.Argument_NeedNonGenericType, "t"); if (structureTypeHandle.IsEnum() || structureTypeHandle.IsInterface() || InteropExtensions.AreTypesAssignable(typeof(Delegate).TypeHandle, structureTypeHandle)) { throw new ArgumentException(SR.Argument_MustHaveLayoutOrBeBlittable, structureTypeHandle.GetDisplayName()); } // Boxed struct start at offset 1 (EEType* at offset 0) while class start at offset 0 int offset = structureTypeHandle.IsValueType() ? 1 : 0; if (structureTypeHandle.IsBlittable()) { // ok to call with blittable structure, but no work to do in this case. return; } if (RuntimeInteropData.Instance.TryGetDestroyStructureStub(structureTypeHandle, out IntPtr destroyStructureStub, out bool hasInvalidLayout)) { if (hasInvalidLayout) throw new ArgumentException(SR.Argument_MustHaveLayoutOrBeBlittable, structureTypeHandle.GetDisplayName()); // DestroyStructureStub == IntPtr.Zero means its fields don't need to be destroied if (destroyStructureStub != IntPtr.Zero) { CalliIntrinsics.Call<int>( destroyStructureStub, (void*)ptr // unsafe (no need to adjust as it is always struct) ); } return; } // Didn't find struct marshal data throw new MissingInteropDataException(SR.StructMarshalling_MissingInteropData, structuretype); } public static void DestroyStructure<T>(IntPtr ptr) { DestroyStructure(ptr, typeof(T)); } public static IntPtr GetComInterfaceForObject<T, TInterface>(T o) { return GetComInterfaceForObject(o, typeof(TInterface)); } public static IntPtr /* IUnknown* */ GetComInterfaceForObject(Object o, Type T) { if (o == null) throw new ArgumentNullException(nameof(o)); if (T == null) throw new ArgumentNullException(nameof(T)); return McgMarshal.ObjectToComInterface(o, T.TypeHandle); } public static TDelegate GetDelegateForFunctionPointer<TDelegate>(IntPtr ptr) { return (TDelegate)(object)GetDelegateForFunctionPointer(ptr, typeof(TDelegate)); } public static Delegate GetDelegateForFunctionPointer(IntPtr ptr, Type t) { // Validate the parameters if (ptr == IntPtr.Zero) throw new ArgumentNullException(nameof(ptr)); if (t == null) throw new ArgumentNullException(nameof(t)); if (t.TypeHandle.IsGenericType() || t.TypeHandle.IsGenericTypeDefinition()) throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t)); bool isDelegateType = InteropExtensions.AreTypesAssignable(t.TypeHandle, typeof(Delegate).TypeHandle); if (!isDelegateType) throw new ArgumentException(SR.Arg_MustBeDelegateType, nameof(t)); return McgMarshal.GetPInvokeDelegateForStub(ptr, t.TypeHandle); } //==================================================================== // GetNativeVariantForObject() // //==================================================================== public static void GetNativeVariantForObject<T>(T obj, IntPtr pDstNativeVariant) { GetNativeVariantForObject((object)obj, pDstNativeVariant); } public static unsafe void GetNativeVariantForObject(Object obj, /* VARIANT * */ IntPtr pDstNativeVariant) { // Obsolete if (pDstNativeVariant == IntPtr.Zero) throw new ArgumentNullException(nameof(pDstNativeVariant)); if (obj != null && (obj.GetType().TypeHandle.IsGenericType() || obj.GetType().TypeHandle.IsGenericTypeDefinition())) throw new ArgumentException(SR.Argument_NeedNonGenericObject, nameof(obj)); Variant* pVariant = (Variant*)pDstNativeVariant; *pVariant = new Variant(obj); } //==================================================================== // GetObjectForNativeVariant() // //==================================================================== public static unsafe T GetObjectForNativeVariant<T>(IntPtr pSrcNativeVariant) { return (T)GetObjectForNativeVariant(pSrcNativeVariant); } public static unsafe Object GetObjectForNativeVariant(/* VARIANT * */ IntPtr pSrcNativeVariant) { // Obsolete if (pSrcNativeVariant == IntPtr.Zero) throw new ArgumentNullException(nameof(pSrcNativeVariant)); Variant* pNativeVar = (Variant*)pSrcNativeVariant; return pNativeVar->ToObject(); } //==================================================================== // GetObjectsForNativeVariants() // //==================================================================== public static unsafe Object[] GetObjectsForNativeVariants(IntPtr aSrcNativeVariant, int cVars) { // Obsolete if (aSrcNativeVariant == IntPtr.Zero) throw new ArgumentNullException(nameof(aSrcNativeVariant)); if (cVars < 0) throw new ArgumentOutOfRangeException(nameof(cVars), SR.ArgumentOutOfRange_NeedNonNegNum); Object[] obj = new Object[cVars]; IntPtr aNativeVar = aSrcNativeVariant; for (int i = 0; i < cVars; i++) { obj[i] = GetObjectForNativeVariant(aNativeVar); aNativeVar = aNativeVar + sizeof(Variant); } return obj; } public static T[] GetObjectsForNativeVariants<T>(IntPtr aSrcNativeVariant, int cVars) { object[] objects = GetObjectsForNativeVariants(aSrcNativeVariant, cVars); T[] result = null; if (objects != null) { result = new T[objects.Length]; Array.Copy(objects, result, objects.Length); } return result; } //==================================================================== // UnsafeAddrOfPinnedArrayElement() // // IMPORTANT NOTICE: This method does not do any verification on the // array. It must be used with EXTREME CAUTION since passing in // an array that is not pinned or in the fixed heap can cause // unexpected results ! //==================================================================== public static IntPtr UnsafeAddrOfPinnedArrayElement(Array arr, int index) { return PInvokeMarshal.UnsafeAddrOfPinnedArrayElement(arr, index); } public static IntPtr UnsafeAddrOfPinnedArrayElement<T>(T[] arr, int index) { return PInvokeMarshal.UnsafeAddrOfPinnedArrayElement(arr, index); } //==================================================================== // This method binds to the specified moniker. //==================================================================== public static Object BindToMoniker(String monikerName) { #if TARGET_CORE_API_SET // BindMoniker not available in core API set throw new PlatformNotSupportedException(); #else Object obj = null; IBindCtx bindctx = null; ExternalInterop.CreateBindCtx(0, out bindctx); UInt32 cbEaten; IMoniker pmoniker = null; ExternalInterop.MkParseDisplayName(bindctx, monikerName, out cbEaten, out pmoniker); ExternalInterop.BindMoniker(pmoniker, 0, ref Interop.COM.IID_IUnknown, out obj); return obj; #endif } #if ENABLE_WINRT public static Type GetTypeFromCLSID(Guid clsid) { return Type.GetTypeFromCLSID(clsid); } //==================================================================== // Return a unique Object given an IUnknown. This ensures that you // receive a fresh object (we will not look in the cache to match up this // IUnknown to an already existing object). This is useful in cases // where you want to be able to call ReleaseComObject on a RCW // and not worry about other active uses of said RCW. //==================================================================== public static Object GetUniqueObjectForIUnknown(IntPtr unknown) { throw new PlatformNotSupportedException(); } public static bool AreComObjectsAvailableForCleanup() { throw new PlatformNotSupportedException(); } public static IntPtr CreateAggregatedObject(IntPtr pOuter, Object o) { throw new PlatformNotSupportedException(); } public static IntPtr CreateAggregatedObject<T>(IntPtr pOuter, T o) { return CreateAggregatedObject(pOuter, (object)o); } public static Object CreateWrapperOfType(Object o, Type t) { throw new PlatformNotSupportedException(); } public static TWrapper CreateWrapperOfType<T, TWrapper>(T o) { return (TWrapper)CreateWrapperOfType(o, typeof(TWrapper)); } public static IntPtr /* IUnknown* */ GetComInterfaceForObject(Object o, Type T, CustomQueryInterfaceMode mode) { // Obsolete throw new PlatformNotSupportedException(); } public static int GetExceptionCode() { // Obsolete throw new PlatformNotSupportedException(); } /// <summary> /// <para>Returns the first valid COM slot that GetMethodInfoForSlot will work on /// This will be 3 for IUnknown based interfaces and 7 for IDispatch based interfaces. </para> /// </summary> public static int GetStartComSlot(Type t) { throw new PlatformNotSupportedException(); } //==================================================================== // Given a managed object that wraps an ITypeInfo, return its name //==================================================================== public static String GetTypeInfoName(ITypeInfo typeInfo) { throw new PlatformNotSupportedException(); } #endif //ENABLE_WINRT public static byte ReadByte(Object ptr, int ofs) { // Obsolete throw new PlatformNotSupportedException("ReadByte"); } public static short ReadInt16(Object ptr, int ofs) { // Obsolete throw new PlatformNotSupportedException("ReadInt16"); } public static int ReadInt32(Object ptr, int ofs) { // Obsolete throw new PlatformNotSupportedException("ReadInt32"); } public static long ReadInt64(Object ptr, int ofs) { // Obsolete throw new PlatformNotSupportedException("ReadInt64"); } public static void WriteByte(Object ptr, int ofs, byte val) { // Obsolete throw new PlatformNotSupportedException("WriteByte"); } public static void WriteInt16(Object ptr, int ofs, short val) { // Obsolete throw new PlatformNotSupportedException("WriteInt16"); } public static void WriteInt32(Object ptr, int ofs, int val) { // Obsolete throw new PlatformNotSupportedException("WriteInt32"); } public static void WriteInt64(Object ptr, int ofs, long val) { // Obsolete throw new PlatformNotSupportedException("WriteInt64"); } public static void ChangeWrapperHandleStrength(Object otp, bool fIsWeak) { throw new PlatformNotSupportedException("ChangeWrapperHandleStrength"); } public static void CleanupUnusedObjectsInCurrentContext() { // RCW cleanup implemented in native code in CoreCLR, and uses a global list to indicate which objects need to be collected. In // CoreRT, RCWs are implemented in managed code and their cleanup is normally accomplished using finalizers. Implementing // this method in a more complicated way (without calling WaitForPendingFinalizers) is non-trivial because it possible for timing // problems to occur when competing with finalizers. GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } public static void Prelink(MethodInfo m) { if (m == null) throw new ArgumentNullException(nameof(m)); // Note: This method is effectively a no-op in ahead-of-time compilation scenarios. In CoreCLR and Desktop, this will pre-generate // the P/Invoke, but everything is pre-generated in CoreRT. } public static void PrelinkAll(Type c) { if (c == null) throw new ArgumentNullException(nameof(c)); MethodInfo[] mi = c.GetMethods(); if (mi != null) { for (int i = 0; i < mi.Length; i++) { Prelink(mi[i]); } } } } }
///////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2006, Frank Blumenberg // // See License.txt for complete licensing and attribution information. // 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. // ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// // // This code is adapted from code in the Endogine sprite engine by Jonas Beckeman. // http://www.endogine.com/CS/ // ///////////////////////////////////////////////////////////////////////////////// using System; using System.IO; using System.Text; namespace PhotoshopFile { /// <summary> /// Reads primitive data types as binary values in in big-endian format /// </summary> public class BinaryReverseReader : BinaryReader { public BinaryReverseReader(Stream a_stream) : base(a_stream, Encoding.GetEncoding("ISO-8859-1")) { } public override short ReadInt16() { short val = base.ReadInt16(); unsafe { this.SwapBytes((byte*)&val, 2); } return val; } public override double ReadDouble() { double val = base.ReadDouble(); unsafe { SwapBytes((byte*)&val, 8); } return val; } public override int ReadInt32() { int val = base.ReadInt32(); unsafe { this.SwapBytes((byte*)&val, 4); } return val; } public override long ReadInt64() { long val = base.ReadInt64(); unsafe { this.SwapBytes((byte*)&val, 8); } return val; } public override ushort ReadUInt16() { ushort val = base.ReadUInt16(); unsafe { this.SwapBytes((byte*)&val, 2); } return val; } public override uint ReadUInt32() { uint val = base.ReadUInt32(); unsafe { this.SwapBytes((byte*)&val, 4); } return val; } public override ulong ReadUInt64() { ulong val = base.ReadUInt64(); unsafe { this.SwapBytes((byte*)&val, 8); } return val; } ////////////////////////////////////////////////////////////////// public string ReadPascalString() { byte stringLength = base.ReadByte(); char[] c = base.ReadChars(stringLength); if ((stringLength % 2) == 0) base.ReadByte(); return new string(c); } /// <summary> /// Does not support code points past 255 /// </summary> /// <returns></returns> public string ReadPSDUnicodeString() { string s = ""; int nLength = (int)this.ReadUInt32(); //ndj's version: //return System.Text.UTF32Encoding.BigEndianUnicode.GetString(base.ReadBytes(nLength)); for (int i = 0; i < nLength * 2; i++) { char c = base.ReadChar(); if (i % 2 == 1 && c != 0) s += c; } if (s.Length == 1 && s[0] == 0) { //String of a single null character, return null; } return s; } public string ReadTdTaString() { StringBuilder sb = new StringBuilder(4096); //int nLength = (int)this.ReadUInt32(); char c; while (BytesToEnd > 0) { c = base.ReadChar(); if (c != 0x0) sb.Append(c); if (c == '>' && sb[sb.Length - 2] == '>' && sb[sb.Length - 3] == '\n') { //we hit the end. break; } } return sb.ToString(); } public long BytesToEnd { get { return (this.BaseStream.Length - this.BaseStream.Position); } } public System.Drawing.Color ReadPSDColor(int bits, bool alpha) { if (bits == 8) { int a = (int)base.ReadByte(); if (!alpha) a = 255; return System.Drawing.Color.FromArgb(a, this.ReadByte(), this.ReadByte(), this.ReadByte()); } else { this.BaseStream.Position += 2; //Always? ushort a = ushort.MaxValue; if (alpha) a = this.ReadUInt16(); ushort r = this.ReadUInt16(); ushort g = this.ReadUInt16(); ushort b = this.ReadUInt16(); return System.Drawing.Color.FromArgb((int)a >> 8, (int)r >> 8, (int)g >> 8, (int)b >> 8); } } /// <summary> /// Standard ReadPSDChars() keeps reading until it has numBytes chars that are != 0. This one doesn't care /// </summary> /// <param name="numBytes"></param> /// <returns></returns> public char[] ReadPSDChars(int numBytes) { char[] chars = new char[numBytes]; for (int i = 0; i < numBytes; i++) chars[i] = (char)this.ReadByte(); return chars; } ////////////////////////////////////////////////////////////////// unsafe protected void SwapBytes(byte* ptr, int nLength) { for (long i = 0; i < nLength / 2; ++i) { byte t = *(ptr + i); *(ptr + i) = *(ptr + nLength - i - 1); *(ptr + nLength - i - 1) = t; } } public bool CanReadByte() { return BytesToEnd > 0; } } ////////////////////////////////////////////////////////////////// /// <summary> /// Writes primitive data types as binary values in in big-endian format /// </summary> public class BinaryReverseWriter : BinaryWriter { public BinaryReverseWriter(Stream a_stream) : base(a_stream) { } public bool AutoFlush; public void WritePascalString(string s) { char[] c; if (s.Length > 255) c = s.Substring(0, 255).ToCharArray(); else c = s.ToCharArray(); base.Write((byte)c.Length); base.Write(c); int realLength = c.Length + 1; if ((realLength % 2) == 0) return; for (int i = 0; i < (2 - (realLength % 2)); i++) base.Write((byte)0); if (AutoFlush) Flush(); } public override void Write(short val) { unsafe { this.SwapBytes((byte*)&val, 2); } base.Write(val); if (AutoFlush) Flush(); } public override void Write(int val) { unsafe { this.SwapBytes((byte*)&val, 4); } base.Write(val); if (AutoFlush) Flush(); } public override void Write(long val) { unsafe { this.SwapBytes((byte*)&val, 8); } base.Write(val); if (AutoFlush) Flush(); } public override void Write(ushort val) { unsafe { this.SwapBytes((byte*)&val, 2); } base.Write(val); if (AutoFlush) Flush(); } public override void Write(uint val) { unsafe { this.SwapBytes((byte*)&val, 4); } base.Write(val); if (AutoFlush) Flush(); } public override void Write(ulong val) { unsafe { this.SwapBytes((byte*)&val, 8); } base.Write(val); if (AutoFlush) Flush(); } ////////////////////////////////////////////////////////////////// unsafe protected void SwapBytes(byte* ptr, int nLength) { for (long i = 0; i < nLength / 2; ++i) { byte t = *(ptr + i); *(ptr + i) = *(ptr + nLength - i - 1); *(ptr + nLength - i - 1) = t; } } } class LengthWriter : IDisposable { long m_lengthPosition = long.MinValue; long m_startPosition; BinaryReverseWriter m_writer; public LengthWriter(BinaryReverseWriter writer) { m_writer = writer; // we will write the correct length later, so remember // the position m_lengthPosition = m_writer.BaseStream.Position; m_writer.Write((uint)0xFEEDFEED); // remember the start position for calculation Image // resources length m_startPosition = m_writer.BaseStream.Position; } public void Write() { if (m_lengthPosition != long.MinValue) { long endPosition = m_writer.BaseStream.Position; m_writer.BaseStream.Position = m_lengthPosition; long length=endPosition - m_startPosition; m_writer.Write((uint)length); m_writer.BaseStream.Position = endPosition; m_lengthPosition = long.MinValue; } } public void Dispose() { Write(); } } }
// =========================================================== // Copyright (C) 2014-2015 Kendar.org // // 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 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 CoroutinesLib.Shared; using CoroutinesLib.Shared.Logging; using Http.Contexts; using Http.Shared; using Http.Shared.Contexts; using Http.Shared.PathProviders; using NodeCs.Shared; using NodeCs.Shared.Caching; using System; using System.Collections.Generic; using System.IO; namespace Http.PathProvider.StaticContent { public class StaticContentPathProvider : IPathProvider, ILoggable { private const string STATIC_PATH_PROVIDER_CACHE_ID = "StaticContentPathProvider"; private readonly string _root; private string _virtualDir; private ICacheEngine _cacheEngine; private FileSystemWatcher _watcher; private bool _showDirectoryContent; public StaticContentPathProvider(string root) { Log = ServiceLocator.Locator.Resolve<ILogger>(); _showDirectoryContent = true; _root = root; } public bool Exists(string relativePath, out bool isDir) { isDir = false; relativePath = relativePath.Replace('/', Path.DirectorySeparatorChar).TrimStart(Path.DirectorySeparatorChar); relativePath = Path.Combine(_root, relativePath); if (File.Exists(relativePath)) { return true; } if (Directory.Exists(relativePath)) { isDir = true; return true; } return false; } public IEnumerable<ICoroutineResult> GetStream(string relativePath, IHttpContext context) { string requestPath; if (context.Request.Url.IsAbsoluteUri) { requestPath = context.Request.Url.LocalPath.Trim(); } else { requestPath = context.Request.Url.ToString().Trim(); } var parentPath = UrlUtils.GetDirectoryName(requestPath); relativePath = relativePath.Replace('/', Path.DirectorySeparatorChar); var parent = UrlUtils.Combine(requestPath); relativePath = Path.Combine(_root, relativePath.TrimStart(Path.DirectorySeparatorChar)); StreamResult result = null; if (_cacheEngine == null) { if (File.Exists(relativePath)) { foreach (var item in LoadStreamContent(relativePath, true)) { yield return item; } } } else { yield return _cacheEngine.AddAndGet(new CacheDefinition { Id = requestPath, LoadData = () => LoadStreamContent(relativePath), ExpireAfter = TimeSpan.FromSeconds(60) }, (a) => { result = (StreamResult)a; }, STATIC_PATH_PROVIDER_CACHE_ID); if (result != null) { //context.Response.ContentType = MimeHelper.GetMime(relativePath); yield return CoroutineResult.Return(result); } } if (!Directory.Exists(relativePath) || _showDirectoryContent == false) { throw new HttpException(404, "File not found"); } context.Response.ContentType = MimeHelper.GetMime("directory.html"); var responseString = "<HTML><BODY>"; responseString += "<table>"; if (!string.IsNullOrEmpty(parentPath)) { responseString += string.Format("<tr><td>&nbsp;</td><td><a href='{0}'>..</a></td></tr>", parentPath); } foreach (var dir in Directory.EnumerateDirectories(relativePath)) { var dirName = Path.GetFileName(dir); responseString += string.Format("<tr><td>Dir</td><td><a href='{0}'>{0}</a></td></tr>", parent + "/" + dirName); } foreach (var dir in Directory.EnumerateFiles(relativePath)) { var dirName = Path.GetFileName(dir); responseString += string.Format("<tr><td>File</td><td><a href='{0}'>{0}</a></td></tr>", parent + "/" + dirName); } responseString += "</table>"; responseString += "</BODY></HTML>"; yield return CoroutineResult.Return( new StreamResult(DateTime.UtcNow, System.Text.Encoding.UTF8.GetBytes(responseString))); } public void ShowDirectoryContent(bool showDirectoryContent) { _showDirectoryContent = showDirectoryContent; } private IEnumerable<ICoroutineResult> LoadStreamContent(string relativePath, bool fileExistsAlready = false) { if (fileExistsAlready || File.Exists(relativePath)) { var resultMs = new MemoryStream(); using (var sourceStream = new FileStream(relativePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.Asynchronous)) { var lastModification = File.GetLastWriteTimeUtc(relativePath); yield return CoroutineResult.RunTask(sourceStream.CopyToAsync(resultMs)) .AndWait(); sourceStream.Close(); resultMs.Seek(0, SeekOrigin.Begin); var result = resultMs.ToArray(); resultMs.Close(); yield return CoroutineResult.Return( new StreamResult(lastModification, File.ReadAllBytes(relativePath))); } } else { Log.Debug("LoadStreamContent failed for {0}", Path.GetFileName(relativePath)); yield return CoroutineResult.Return(null); } } public void SetVirtualDir(string virtualDir) { _virtualDir = virtualDir; } public void SetCachingEngine(ICacheEngine cacheEngine) { _cacheEngine = cacheEngine; _cacheEngine.AddGroup(new CacheGroupDefinition { ExpireAfter = TimeSpan.FromDays(1), Id = STATIC_PATH_PROVIDER_CACHE_ID, RollingExpiration = true }); } public ILogger Log { get; set; } public void InitializeFileWatcher() { _watcher = new FileSystemWatcher(_root); _watcher.IncludeSubdirectories = true; _watcher.Changed += OnFileChanged; _watcher.EnableRaisingEvents = true; } private void OnFileChanged(object sender, FileSystemEventArgs e) { if (e.ChangeType == WatcherChangeTypes.Changed) { if (_cacheEngine == null) return; if (File.Exists(e.FullPath)) { var fullPath = e.FullPath; var realPath = "/" + _virtualDir + "/" + fullPath.Substring(_root.Length).Replace(Path.DirectorySeparatorChar, '/').Trim('/'); _cacheEngine.InvalidateItem(realPath, STATIC_PATH_PROVIDER_CACHE_ID); } } } public IEnumerable<string> FindFiles(string dir) { var oriDir = dir.Replace('/', Path.DirectorySeparatorChar).TrimStart(Path.DirectorySeparatorChar); dir = Path.Combine(_root, oriDir); if(!Directory.Exists(dir)) yield break; foreach (var file in Directory.GetFiles(dir)) { var res = "/" + oriDir.Trim('/') + "/" + Path.GetFileName(file); yield return res; ; } } public IEnumerable<string> FindDirs(string dir) { dir = dir.Replace('/', Path.DirectorySeparatorChar).TrimStart(Path.DirectorySeparatorChar); dir = Path.Combine(_root, dir); if (!Directory.Exists(dir)) yield break; foreach (var file in Directory.GetFiles(dir)) yield return file; } } }
// Copyright (c) 2015-present, LeanCloud, LLC. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. using System; using System.Collections.Generic; using System.Linq; using System.Text; using LeanCloud.Storage.Internal; using LeanCloud.Core.Internal; namespace LeanCloud.Core.Internal { public class AVPlugins : IAVCorePlugins { private static readonly object instanceMutex = new object(); private static IAVCorePlugins instance; public static IAVCorePlugins Instance { get { lock (instanceMutex) { instance = instance ?? new AVPlugins(); return instance; } } set { lock (instanceMutex) { instance = value; } } } private readonly object mutex = new object(); #region Server Controllers private IHttpClient httpClient; private IAVCommandRunner commandRunner; private IStorageController storageController; private IAVCloudCodeController cloudCodeController; private IAVConfigController configController; private IAVFileController fileController; private IAVObjectController objectController; private IAVQueryController queryController; private IAVSessionController sessionController; private IAVUserController userController; private IObjectSubclassingController subclassingController; #endregion #region Current Instance Controller private IAVCurrentUserController currentUserController; private IInstallationIdController installationIdController; #endregion public void Reset() { lock (mutex) { HttpClient = null; CommandRunner = null; StorageController = null; CloudCodeController = null; FileController = null; ObjectController = null; SessionController = null; UserController = null; SubclassingController = null; CurrentUserController = null; InstallationIdController = null; } } public IHttpClient HttpClient { get { lock (mutex) { httpClient = httpClient ?? new HttpClient(); return httpClient; } } set { lock (mutex) { httpClient = value; } } } public IAVCommandRunner CommandRunner { get { lock (mutex) { commandRunner = commandRunner ?? new AVCommandRunner(HttpClient, InstallationIdController); return commandRunner; } } set { lock (mutex) { commandRunner = value; } } } public IStorageController StorageController { get { lock (mutex) { storageController = storageController ?? new StorageController(); return storageController; } } set { lock (mutex) { storageController = value; } } } public IAVCloudCodeController CloudCodeController { get { lock (mutex) { cloudCodeController = cloudCodeController ?? new AVCloudCodeController(CommandRunner); return cloudCodeController; } } set { lock (mutex) { cloudCodeController = value; } } } public IAVFileController FileController { get { lock (mutex) { fileController = fileController ?? new AVFileController(CommandRunner); return fileController; } } set { lock (mutex) { fileController = value; } } } public IAVConfigController ConfigController { get { lock (mutex) { if (configController == null) { configController = new AVConfigController(CommandRunner, StorageController); } return configController; } } set { lock (mutex) { configController = value; } } } public IAVObjectController ObjectController { get { lock (mutex) { objectController = objectController ?? new AVObjectController(CommandRunner); return objectController; } } set { lock (mutex) { objectController = value; } } } public IAVQueryController QueryController { get { lock (mutex) { if (queryController == null) { queryController = new AVQueryController(CommandRunner); } return queryController; } } set { lock (mutex) { queryController = value; } } } public IAVSessionController SessionController { get { lock (mutex) { sessionController = sessionController ?? new AVSessionController(CommandRunner); return sessionController; } } set { lock (mutex) { sessionController = value; } } } public IAVUserController UserController { get { lock (mutex) { userController = userController ?? new AVUserController(CommandRunner); return userController; } } set { lock (mutex) { userController = value; } } } public IAVCurrentUserController CurrentUserController { get { lock (mutex) { currentUserController = currentUserController ?? new AVCurrentUserController(StorageController); return currentUserController; } } set { lock (mutex) { currentUserController = value; } } } public IObjectSubclassingController SubclassingController { get { lock (mutex) { if (subclassingController == null) { subclassingController = new ObjectSubclassingController(); subclassingController.AddRegisterHook(typeof(AVUser), () => CurrentUserController.ClearFromMemory()); } return subclassingController; } } set { lock (mutex) { subclassingController = value; } } } public IInstallationIdController InstallationIdController { get { lock (mutex) { installationIdController = installationIdController ?? new InstallationIdController(StorageController); return installationIdController; } } set { lock (mutex) { installationIdController = value; } } } } }
// Copyright (C) 2014 dot42 // // Original filename: Dalvik.System.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 Dalvik.System { /// <summary> /// <para>A class loader that loads classes from <c> .jar </c> and <c> .apk </c> files containing a <c> classes.dex </c> entry. This can be used to execute code not installed as part of an application.</para><para>This class loader requires an application-private, writable directory to cache optimized classes. Use <c> Context.getDir(String, int) </c> to create such a directory: <pre> File dexOutputDir = context.getDir("dex", 0); /// /// </pre></para><para><b>Do not cache optimized classes on external storage.</b> External storage does not provide access controls necessary to protect your application from code injection attacks. </para> /// </summary> /// <java-name> /// dalvik/system/DexClassLoader /// </java-name> [Dot42.DexImport("dalvik/system/DexClassLoader", AccessFlags = 33)] public partial class DexClassLoader : global::Java.Lang.ClassLoader /* scope: __dot42__ */ { /// <summary> /// <para>Creates a <c> DexClassLoader </c> that finds interpreted and native code. Interpreted classes are found in a set of DEX files contained in Jar or APK files.</para><para>The path lists are separated using the character specified by the <c> path.separator </c> system property, which defaults to <c> : </c> .</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/ClassLoader;)V", AccessFlags = 1)] public DexClassLoader(string dexPath, string optimizedDirectory, string libraryPath, global::Java.Lang.ClassLoader parent) /* MethodBuilder.Create */ { } /// <java-name> /// findClass /// </java-name> [Dot42.DexImport("findClass", "(Ljava/lang/String;)Ljava/lang/Class;", AccessFlags = 4, Signature = "(Ljava/lang/String;)Ljava/lang/Class<*>;")] protected internal override global::System.Type FindClass(string @string) /* MethodBuilder.Create */ { return default(global::System.Type); } /// <java-name> /// findResource /// </java-name> [Dot42.DexImport("findResource", "(Ljava/lang/String;)Ljava/net/URL;", AccessFlags = 4)] protected internal override global::Java.Net.URL FindResource(string @string) /* MethodBuilder.Create */ { return default(global::Java.Net.URL); } /// <java-name> /// findLibrary /// </java-name> [Dot42.DexImport("findLibrary", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 4)] protected internal override string FindLibrary(string @string) /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getPackage /// </java-name> [Dot42.DexImport("getPackage", "(Ljava/lang/String;)Ljava/lang/Package;", AccessFlags = 4)] protected internal override global::Java.Lang.Package GetPackage(string @string) /* MethodBuilder.Create */ { return default(global::Java.Lang.Package); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal DexClassLoader() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>Manipulates DEX files. The class is similar in principle to java.util.zip.ZipFile. It is used primarily by class loaders. </para><para>Note we don't directly open and read the DEX file here. They're memory-mapped read-only by the VM. </para> /// </summary> /// <java-name> /// dalvik/system/DexFile /// </java-name> [Dot42.DexImport("dalvik/system/DexFile", AccessFlags = 49)] public sealed partial class DexFile /* scope: __dot42__ */ { /// <summary> /// <para>Opens a DEX file from a given File object. This will usually be a ZIP/JAR file with a "classes.dex" inside.</para><para>The VM will generate the name of the corresponding file in /data/dalvik-cache and open it, possibly creating or updating it first if system permissions allow. Don't pass in the name of a file in /data/dalvik-cache, as the named file is expected to be in its original (pre-dexopt) state.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/io/File;)V", AccessFlags = 1)] public DexFile(global::Java.Io.File file) /* MethodBuilder.Create */ { } /// <summary> /// <para>Opens a DEX file from a given File object. This will usually be a ZIP/JAR file with a "classes.dex" inside.</para><para>The VM will generate the name of the corresponding file in /data/dalvik-cache and open it, possibly creating or updating it first if system permissions allow. Don't pass in the name of a file in /data/dalvik-cache, as the named file is expected to be in its original (pre-dexopt) state.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public DexFile(string file) /* MethodBuilder.Create */ { } /// <summary> /// <para>Open a DEX file, specifying the file in which the optimized DEX data should be written. If the optimized form exists and appears to be current, it will be used; if not, the VM will attempt to regenerate it.</para><para>This is intended for use by applications that wish to download and execute DEX files outside the usual application installation mechanism. This function should not be called directly by an application; instead, use a class loader such as dalvik.system.DexClassLoader.</para><para></para> /// </summary> /// <returns> /// <para>A new or previously-opened DexFile. </para> /// </returns> /// <java-name> /// loadDex /// </java-name> [Dot42.DexImport("loadDex", "(Ljava/lang/String;Ljava/lang/String;I)Ldalvik/system/DexFile;", AccessFlags = 9)] public static global::Dalvik.System.DexFile LoadDex(string sourcePathName, string outputPathName, int flags) /* MethodBuilder.Create */ { return default(global::Dalvik.System.DexFile); } /// <summary> /// <para>Gets the name of the (already opened) DEX file.</para><para></para> /// </summary> /// <returns> /// <para>the file name </para> /// </returns> /// <java-name> /// getName /// </java-name> [Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1)] public string GetName() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Closes the DEX file. </para><para>This may not be able to release any resources. If classes from this DEX file are still resident, the DEX file can't be unmapped.</para><para></para> /// </summary> /// <java-name> /// close /// </java-name> [Dot42.DexImport("close", "()V", AccessFlags = 1)] public void Close() /* MethodBuilder.Create */ { } /// <summary> /// <para>Loads a class. Returns the class on success, or a <c> null </c> reference on failure. </para><para>If you are not calling this from a class loader, this is most likely not going to do what you want. Use Class#forName(String) instead. </para><para>The method does not throw ClassNotFoundException if the class isn't found because it isn't reasonable to throw exceptions wildly every time a class is not found in the first DEX file we look at.</para><para></para> /// </summary> /// <returns> /// <para>the Class object representing the class, or <c> null </c> if the class cannot be loaded </para> /// </returns> /// <java-name> /// loadClass /// </java-name> [Dot42.DexImport("loadClass", "(Ljava/lang/String;Ljava/lang/ClassLoader;)Ljava/lang/Class;", AccessFlags = 1)] public global::System.Type LoadClass(string name, global::Java.Lang.ClassLoader loader) /* MethodBuilder.Create */ { return default(global::System.Type); } /// <summary> /// <para>Enumerate the names of the classes in this DEX file.</para><para></para> /// </summary> /// <returns> /// <para>an enumeration of names of classes contained in the DEX file, in the usual internal form (like "java/lang/String"). </para> /// </returns> /// <java-name> /// entries /// </java-name> [Dot42.DexImport("entries", "()Ljava/util/Enumeration;", AccessFlags = 1, Signature = "()Ljava/util/Enumeration<Ljava/lang/String;>;")] public global::Java.Util.IEnumeration<string> Entries() /* MethodBuilder.Create */ { return default(global::Java.Util.IEnumeration<string>); } /// <summary> /// <para>Called when the class is finalized. Makes sure the DEX file is closed.</para><para></para> /// </summary> /// <java-name> /// finalize /// </java-name> [Dot42.DexImport("finalize", "()V", AccessFlags = 4)] extern ~DexFile() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns true if the VM believes that the apk/jar file is out of date and should be passed through "dexopt" again.</para><para></para> /// </summary> /// <returns> /// <para>true if dexopt should be called on the file, false otherwise. </para> /// </returns> /// <java-name> /// isDexOptNeeded /// </java-name> [Dot42.DexImport("isDexOptNeeded", "(Ljava/lang/String;)Z", AccessFlags = 265)] public static bool IsDexOptNeeded(string fileName) /* MethodBuilder.Create */ { return default(bool); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal DexFile() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Gets the name of the (already opened) DEX file.</para><para></para> /// </summary> /// <returns> /// <para>the file name </para> /// </returns> /// <java-name> /// getName /// </java-name> public string Name { [Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetName(); } } } /// <summary> /// <para>Provides a simple ClassLoader implementation that operates on a list of files and directories in the local file system, but does not attempt to load classes from the network. Android uses this class for its system class loader and for its application class loader(s). </para> /// </summary> /// <java-name> /// dalvik/system/PathClassLoader /// </java-name> [Dot42.DexImport("dalvik/system/PathClassLoader", AccessFlags = 33)] public partial class PathClassLoader : global::Java.Lang.ClassLoader /* scope: __dot42__ */ { /// <summary> /// <para>Creates a <c> PathClassLoader </c> that operates on a given list of files and directories. This method is equivalent to calling PathClassLoader(String, String, ClassLoader) with a <c> null </c> value for the second argument (see description there).</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/ClassLoader;)V", AccessFlags = 1)] public PathClassLoader(string dexPath, global::Java.Lang.ClassLoader parent) /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a <c> PathClassLoader </c> that operates on two given lists of files and directories. The entries of the first list should be one of the following:</para><para><ul><li><para>JAR/ZIP/APK files, possibly containing a "classes.dex" file as well as arbitrary resources. </para></li><li><para>Raw ".dex" files (not inside a zip file). </para></li></ul></para><para>The entries of the second list should be directories containing native library files.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/ClassLoader;)V", AccessFlags = 1)] public PathClassLoader(string dexPath, string libraryPath, global::Java.Lang.ClassLoader parent) /* MethodBuilder.Create */ { } /// <java-name> /// findClass /// </java-name> [Dot42.DexImport("findClass", "(Ljava/lang/String;)Ljava/lang/Class;", AccessFlags = 4, Signature = "(Ljava/lang/String;)Ljava/lang/Class<*>;")] protected internal override global::System.Type FindClass(string @string) /* MethodBuilder.Create */ { return default(global::System.Type); } /// <java-name> /// findResource /// </java-name> [Dot42.DexImport("findResource", "(Ljava/lang/String;)Ljava/net/URL;", AccessFlags = 4)] protected internal override global::Java.Net.URL FindResource(string @string) /* MethodBuilder.Create */ { return default(global::Java.Net.URL); } /// <java-name> /// findResources /// </java-name> [Dot42.DexImport("findResources", "(Ljava/lang/String;)Ljava/util/Enumeration;", AccessFlags = 4, Signature = "(Ljava/lang/String;)Ljava/util/Enumeration<Ljava/net/URL;>;")] protected internal override global::Java.Util.IEnumeration<global::Java.Net.URL> FindResources(string @string) /* MethodBuilder.Create */ { return default(global::Java.Util.IEnumeration<global::Java.Net.URL>); } /// <java-name> /// findLibrary /// </java-name> [Dot42.DexImport("findLibrary", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 1)] public new virtual string FindLibrary(string @string) /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getPackage /// </java-name> [Dot42.DexImport("getPackage", "(Ljava/lang/String;)Ljava/lang/Package;", AccessFlags = 4)] protected internal override global::Java.Lang.Package GetPackage(string @string) /* MethodBuilder.Create */ { return default(global::Java.Lang.Package); } /// <java-name> /// toString /// </java-name> [Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)] public override string ToString() /* MethodBuilder.Create */ { return default(string); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal PathClassLoader() /* TypeBuilder.AddDefaultConstructor */ { } } }
// Copyright (C) 2017 Alaa Masoud // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Moq; using Sejil.Configuration.Internal; using Sejil.Data.Internal; using Sejil.Models.Internal; using Xunit; namespace Sejil.Test.Data { public class SejilSqlProviderTests { [Fact] public void GetSavedQueriesSql_returns_correct_sql() { // Arrange var provider = new SejilSqlProvider(Mock.Of<ISejilSettings>()); // Act var sql = provider.GetSavedQueriesSql(); // Assert Assert.Equal("SELECT * FROM log_query", sql); } [Fact] public void InsertLogQuerySql_returns_correct_sql() { // Arrange var provider = new SejilSqlProvider(Mock.Of<ISejilSettings>()); // Act var sql = provider.InsertLogQuerySql(); // Assert Assert.Equal("INSERT INTO log_query (name, query) VALUES (@name, @query)", sql); } [Fact] public void DeleteQuerySql_returns_correct_sql() { // Arrange var provider = new SejilSqlProvider(Mock.Of<ISejilSettings>()); // Act var sql = provider.DeleteQuerySql(); // Assert Assert.Equal("DELETE FROM log_query WHERE name = @name", sql); } [Fact] public void GetPagedLogEntriesSql_throws_when_page_arg_is_zero() { // Arrange var provider = new SejilSqlProvider(Mock.Of<ISejilSettings>()); // Act & assert var ex = Assert.Throws<ArgumentOutOfRangeException>("page", () => provider.GetPagedLogEntriesSql(0, 1, null, null)); Assert.Equal($"Argument must be greater than zero. (Parameter 'page')", ex.Message); } [Fact] public void GetPagedLogEntriesSql_throws_when_page_arg_is_less_than_zero() { // Arrange var provider = new SejilSqlProvider(Mock.Of<ISejilSettings>()); // Act & assert var ex = Assert.Throws<ArgumentOutOfRangeException>("page", () => provider.GetPagedLogEntriesSql(-1, 1, null, null)); Assert.Equal($"Argument must be greater than zero. (Parameter 'page')", ex.Message); } [Fact] public void GetPagedLogEntriesSql_throws_when_pageSize_arg_is_zero() { // Arrange var provider = new SejilSqlProvider(Mock.Of<ISejilSettings>()); // Act & assert var ex = Assert.Throws<ArgumentOutOfRangeException>("pageSize", () => provider.GetPagedLogEntriesSql(1, 0, null, null)); Assert.Equal($"Argument must be greater than zero. (Parameter 'pageSize')", ex.Message); } [Fact] public void GetPagedLogEntriesSql_throws_when_pageSize_arg_is_less_than_zero() { // Arrange var provider = new SejilSqlProvider(Mock.Of<ISejilSettings>()); // Act & assert var ex = Assert.Throws<ArgumentOutOfRangeException>("pageSize", () => provider.GetPagedLogEntriesSql(1, -1, null, null)); Assert.Equal($"Argument must be greater than zero. (Parameter 'pageSize')", ex.Message); } [Fact] public void GetPagedLogEntriesSql_returns_correct_sql_for_page() { // Arrange var page = 2; var pageSize = 100; var provider = new SejilSqlProvider(Mock.Of<ISejilSettings>()); // Act var sql = provider.GetPagedLogEntriesSql(page, pageSize, null, null); // Assert Assert.Equal( $@"SELECT l.*, p.* from ( SELECT * FROM log ORDER BY timestamp DESC LIMIT {pageSize} OFFSET {(page - 1) * pageSize} ) l LEFT JOIN log_property p ON l.id = p.logId ORDER BY l.timestamp DESC, p.name", sql); } [Fact] public void GetPagedLogEntriesSql_ignores_timestamp_arg_when_null() { // Arrange DateTime? timestamp = null; var provider = new SejilSqlProvider(Mock.Of<ISejilSettings>()); // Act var sql = provider.GetPagedLogEntriesSql(2, 100, timestamp, null); // Assert Assert.Equal( @"SELECT l.*, p.* from ( SELECT * FROM log ORDER BY timestamp DESC LIMIT 100 OFFSET 100 ) l LEFT JOIN log_property p ON l.id = p.logId ORDER BY l.timestamp DESC, p.name", sql); } [Fact] public void GetPagedLogEntriesSql_returns_correct_sql_for_events_before_specified_timestamp() { // Arrange var timestamp = new DateTime(2017, 8, 3, 14, 56, 33, 876); var provider = new SejilSqlProvider(Mock.Of<ISejilSettings>()); // Act var sql = provider.GetPagedLogEntriesSql(2, 100, timestamp, null); // Assert Assert.Equal( @"SELECT l.*, p.* from ( SELECT * FROM log WHERE (timestamp <= '2017-08-03 14:56:33.876') ORDER BY timestamp DESC LIMIT 100 OFFSET 100 ) l LEFT JOIN log_property p ON l.id = p.logId ORDER BY l.timestamp DESC, p.name", sql); } [Fact] public void GetPagedLogEntriesSql_returns_correct_sql_for_events_before_specified_timestamp_and_with_dateFilter() { // Arrange var timestamp = new DateTime(2017, 8, 3, 14, 56, 33, 876); var provider = new SejilSqlProvider(Mock.Of<ISejilSettings>()); // Act var sql = provider.GetPagedLogEntriesSql(2, 100, timestamp, new LogQueryFilter { DateFilter = "5m" }); // Assert Assert.Equal( @"SELECT l.*, p.* from ( SELECT * FROM log WHERE (timestamp <= '2017-08-03 14:56:33.876' AND timestamp >= datetime('now', '-5 Minute')) ORDER BY timestamp DESC LIMIT 100 OFFSET 100 ) l LEFT JOIN log_property p ON l.id = p.logId ORDER BY l.timestamp DESC, p.name", sql); } [Fact] public void GetPagedLogEntriesSql_returns_correct_sql_for_events_before_specified_timestamp_with_specified_query() { // Arrange var timestamp = new DateTime(2017, 8, 3, 14, 56, 33, 876); var query = "p='v'"; var provider = new SejilSqlProvider(Mock.Of<ISejilSettings>()); // Act var sql = provider.GetPagedLogEntriesSql(2, 100, timestamp, new LogQueryFilter { QueryText = query }); // Assert Assert.Equal( @"SELECT l.*, p.* from ( SELECT * FROM log WHERE (timestamp <= '2017-08-03 14:56:33.876') AND (id IN (SELECT logId FROM log_property GROUP BY logId HAVING SUM(name = 'p' AND value = 'v') > 0)) ORDER BY timestamp DESC LIMIT 100 OFFSET 100 ) l LEFT JOIN log_property p ON l.id = p.logId ORDER BY l.timestamp DESC, p.name", sql); } [Fact] public void GetPagedLogEntriesSql_returns_correct_sql_for_events_before_specified_timestamp_with_specified_filter() { // Arrange var timestamp = new DateTime(2017, 8, 3, 14, 56, 33, 876); var levelFilter = "info"; var provider = new SejilSqlProvider(Mock.Of<ISejilSettings>()); // Act var sql = provider.GetPagedLogEntriesSql(2, 100, timestamp, new LogQueryFilter { LevelFilter = levelFilter }); // Assert Assert.Equal( @"SELECT l.*, p.* from ( SELECT * FROM log WHERE (timestamp <= '2017-08-03 14:56:33.876') AND (level = 'info') ORDER BY timestamp DESC LIMIT 100 OFFSET 100 ) l LEFT JOIN log_property p ON l.id = p.logId ORDER BY l.timestamp DESC, p.name", sql); } [Fact] public void GetPagedLogEntriesSql_returns_correct_sql_for_events_with_specified_query_with_specified_filter() { // Arrange var query = "p='v'"; var levelFilter = "info"; var provider = new SejilSqlProvider(Mock.Of<ISejilSettings>()); // Act var sql = provider.GetPagedLogEntriesSql(2, 100, null, new LogQueryFilter { QueryText = query, LevelFilter = levelFilter }); // Assert Assert.Equal( @"SELECT l.*, p.* from ( SELECT * FROM log WHERE (id IN (SELECT logId FROM log_property GROUP BY logId HAVING SUM(name = 'p' AND value = 'v') > 0)) AND (level = 'info') ORDER BY timestamp DESC LIMIT 100 OFFSET 100 ) l LEFT JOIN log_property p ON l.id = p.logId ORDER BY l.timestamp DESC, p.name", sql); } [Theory] [MemberData(nameof(GetPagedLogEntriesSql_TestData))] public void GetPagedLogEntriesSql_returns_correct_sql_for_events_with_specified_query(string query, string expectedSql, params string[] nonPropertyColumns) { // Arrange var settingsMoq = new Mock<ISejilSettings>(); settingsMoq.SetupGet(p => p.NonPropertyColumns).Returns(nonPropertyColumns); var provider = new SejilSqlProvider(settingsMoq.Object); // Act var sql = provider.GetPagedLogEntriesSql(2, 100, null, new LogQueryFilter { QueryText = query }); // Assert Assert.Equal(expectedSql, GetInnerPredicate(sql)); } [Theory] [MemberData(nameof(GetPagedLogEntriesSql_returns_correct_sql_for_events_with_specified_dateFilter_TestData))] public void GetPagedLogEntriesSql_returns_correct_sql_for_events_with_specified_dateFilter(string dateFilter, string expectedSql) { // Arrange var settingsMoq = new Mock<ISejilSettings>(); var provider = new SejilSqlProvider(settingsMoq.Object); // Act var sql = provider.GetPagedLogEntriesSql(2, 100, null, new LogQueryFilter { DateFilter = dateFilter }); // Assert Assert.Equal(expectedSql, GetInnerPredicate_ts(sql)); } [Theory] [MemberData(nameof(GetPagedLogEntriesSql_returns_correct_sql_for_events_with_specified_filter_TestData))] public void GetPagedLogEntriesSql_returns_correct_sql_for_events_with_specified_filter(string levelFilter, bool exceptionsOnly, string expectedSql) { // Arrange var settingsMoq = new Mock<ISejilSettings>(); var provider = new SejilSqlProvider(settingsMoq.Object); // Act var sql = provider.GetPagedLogEntriesSql(2, 100, null, new LogQueryFilter { LevelFilter = levelFilter, ExceptionsOnly = exceptionsOnly }); // Assert Assert.Equal(expectedSql, GetInnerPredicate(sql)); } [Fact] public void GetPagedLogEntriesSql_returns_correct_sql_for_events_with_specified_dateRangeFilter() { // Arrange var d1 = new DateTime(2017, 8, 1); var d2 = new DateTime(2017, 8, 10); var settingsMoq = new Mock<ISejilSettings>(); var provider = new SejilSqlProvider(settingsMoq.Object); // Act var sql = provider.GetPagedLogEntriesSql(2, 100, null, new LogQueryFilter { DateRangeFilter = new List<DateTime> { d1, d2 } }); // Assert Assert.Equal("timestamp >= '2017-08-01' and timestamp < '2017-08-10'", GetInnerPredicate_ts(sql)); } public static IEnumerable<object[]> GetPagedLogEntriesSql_TestData() { // ... =|!=|like|not like ... yield return new object[] { "prob1 = 'value1'", "id IN (SELECT logId FROM log_property GROUP BY logId HAVING SUM(name = 'prob1' AND value = 'value1') > 0)" }; yield return new object[] { "prob1 != 'value1'", "id IN (SELECT logId FROM log_property GROUP BY logId HAVING SUM(name = 'prob1' AND value = 'value1') = 0)" }; yield return new object[] { "prob1 like '%value1'", "id IN (SELECT logId FROM log_property GROUP BY logId HAVING SUM(name = 'prob1' AND value LIKE '%value1') > 0)" }; yield return new object[] { "prob1 not like '%value1'", "id IN (SELECT logId FROM log_property GROUP BY logId HAVING SUM(name = 'prob1' AND value LIKE '%value1') = 0)" }; // ... and|or ... yield return new object[] { "prob1 = 'value1' and prob2 = 'value2'", "id IN (SELECT logId FROM log_property GROUP BY logId HAVING " + "SUM(name = 'prob1' AND value = 'value1') > 0 " + "AND SUM(name = 'prob2' AND value = 'value2') > 0)" }; yield return new object[] { "prob1 = 'value1' and prob2 != 'value2'", "id IN (SELECT logId FROM log_property GROUP BY logId HAVING " + "SUM(name = 'prob1' AND value = 'value1') > 0 " + "AND SUM(name = 'prob2' AND value = 'value2') = 0)" }; yield return new object[] { "prob1 not like '%value1' or prob2 like '%value2'", "id IN (SELECT logId FROM log_property GROUP BY logId HAVING " + "SUM(name = 'prob1' AND value LIKE '%value1') = 0 " + "OR SUM(name = 'prob2' AND value LIKE '%value2') > 0)" }; yield return new object[] { "prob1 not like '%value1' or prob2 not like '%value2'", "id IN (SELECT logId FROM log_property GROUP BY logId HAVING " + "SUM(name = 'prob1' AND value LIKE '%value1') = 0 " + "OR SUM(name = 'prob2' AND value LIKE '%value2') = 0)" }; // (...) and|or ... yield return new object[] { "(prob1 = 'value1' or prob1 = 'value2') and prob3 like '%value3'", "id IN (SELECT logId FROM log_property GROUP BY logId HAVING " + "(SUM(name = 'prob1' AND value = 'value1') > 0 " + "OR SUM(name = 'prob1' AND value = 'value2') > 0) " + "AND SUM(name = 'prob3' AND value LIKE '%value3') > 0)" }; yield return new object[] { "(prob1 = 'value1' and prob2 = 'value2') or prob3 not like '%value3'", "id IN (SELECT logId FROM log_property GROUP BY logId HAVING " + "(SUM(name = 'prob1' AND value = 'value1') > 0 " + "AND SUM(name = 'prob2' AND value = 'value2') > 0) " + "OR SUM(name = 'prob3' AND value LIKE '%value3') = 0)" }; // ... and|or (...) yield return new object[] { "prob1 = 'value1' or (prob1 = 'value2' and prob3 like '%value3')", "id IN (SELECT logId FROM log_property GROUP BY logId HAVING " + "SUM(name = 'prob1' AND value = 'value1') > 0 " + "OR (SUM(name = 'prob1' AND value = 'value2') > 0 " + "AND SUM(name = 'prob3' AND value LIKE '%value3') > 0))" }; yield return new object[] { "prob1 = 'value1' and (prob2 = 'value2' or prob3 not like '%value3')", "id IN (SELECT logId FROM log_property GROUP BY logId HAVING " + "SUM(name = 'prob1' AND value = 'value1') > 0 " + "AND (SUM(name = 'prob2' AND value = 'value2') > 0 " + "OR SUM(name = 'prob3' AND value LIKE '%value3') = 0))" }; // (...) and|or (...) yield return new object[] { "(prob1 = 'value1' or prob1 = 'value2') and (prob3 like '%value3' and prob4 != 5)", "id IN (SELECT logId FROM log_property GROUP BY logId HAVING " + "(SUM(name = 'prob1' AND value = 'value1') > 0 " + "OR SUM(name = 'prob1' AND value = 'value2') > 0) " + "AND (SUM(name = 'prob3' AND value LIKE '%value3') > 0 " + "AND SUM(name = 'prob4' AND value = '5') = 0))" }; yield return new object[] { "(prob1 = 'value1' or prob1 = 'value2') or (prob3 like '%value3' and prob4 != 55.55)", "id IN (SELECT logId FROM log_property GROUP BY logId HAVING " + "(SUM(name = 'prob1' AND value = 'value1') > 0 " + "OR SUM(name = 'prob1' AND value = 'value2') > 0) " + "OR (SUM(name = 'prob3' AND value LIKE '%value3') > 0 " + "AND SUM(name = 'prob4' AND value = '55.55') = 0))" }; // mixed yield return new object[] { "(p1 = 'v' and message = 'v') or level='dbg'", "(id IN (SELECT logId FROM log_property GROUP BY logId HAVING SUM(name = 'p1' AND value = 'v') > 0) AND message = 'v') OR level = 'dbg'", new [] { "message", "level" } }; yield return new object[] { "(message = 'v' and p1 = 'v') or level='dbg'", "(message = 'v' AND id IN (SELECT logId FROM log_property GROUP BY logId HAVING SUM(name = 'p1' AND value = 'v') > 0)) OR level = 'dbg'", new [] { "message", "level" } }; yield return new object[] { "(p1 = 'v')", "id IN (SELECT logId FROM log_property GROUP BY logId HAVING (SUM(name = 'p1' AND value = 'v') > 0))", }; yield return new object[] { "(message = 'v')", "(message = 'v')", "message" }; // Non property columns yield return new object[] { "message like '%search%'", "message LIKE '%search%'", "message" }; yield return new object[] { "prob1 = 'value1' or message like '%search%' and prob2 != 'value2'", "id IN (SELECT logId FROM log_property GROUP BY logId HAVING SUM(name = 'prob1' AND value = 'value1') > 0) " + "OR message LIKE '%search%' " + "AND id IN (SELECT logId FROM log_property GROUP BY logId HAVING SUM(name = 'prob2' AND value = 'value2') = 0)", "message" }; // General text yield return new object[] { "search", "(message LIKE '%search%' OR exception LIKE '%search%' OR " + "id in (SELECT logId FROM log_property WHERE value LIKE '%search%'))" }; // General text yield return new object[] { "\"search=;()\"", "(message LIKE '%search=;()%' OR exception LIKE '%search=;()%' OR " + "id in (SELECT logId FROM log_property WHERE value LIKE '%search=;()%'))" }; // Quote escaping for a search string yield return new object[] { @"'searchstr'", "(message LIKE '%''searchstr''%' OR exception LIKE '%''searchstr''%' OR " + "id in (SELECT logId FROM log_property WHERE value LIKE '%''searchstr''%'))" }; // Quote escaping for a parsed query yield return new object[] { @"message = 'This is a \'quote\''", "message = 'This is a ''quote'''", "message" }; // Booleans yield return new object[] { @"loggedIn = true or loggedIn = false", "loggedIn = 'True' OR loggedIn = 'False'", "loggedIn" }; } public static IEnumerable<object[]> GetPagedLogEntriesSql_returns_correct_sql_for_events_with_specified_dateFilter_TestData() { yield return new object[] { "5m", "timestamp >= datetime('now', '-5 Minute')" }; yield return new object[] { "15m", "timestamp >= datetime('now', '-15 Minute')" }; yield return new object[] { "1h", "timestamp >= datetime('now', '-1 Hour')" }; yield return new object[] { "6h", "timestamp >= datetime('now', '-6 Hour')" }; yield return new object[] { "12h", "timestamp >= datetime('now', '-12 Hour')" }; yield return new object[] { "24h", "timestamp >= datetime('now', '-24 Hour')" }; yield return new object[] { "2d", "timestamp >= datetime('now', '-2 Day')" }; yield return new object[] { "5d", "timestamp >= datetime('now', '-5 Day')" }; } public static IEnumerable<object[]> GetPagedLogEntriesSql_returns_correct_sql_for_events_with_specified_filter_TestData() { yield return new object[] { "info", false, "level = 'info'" }; yield return new object[] { null, true, "exception is not null" }; yield return new object[] { "info", true, "level = 'info' AND exception is not null" }; } private static string GetInnerPredicate(string sql) => sql.Replace( @"SELECT l.*, p.* from ( SELECT * FROM log WHERE (", "").Replace( @") ORDER BY timestamp DESC LIMIT 100 OFFSET 100 ) l LEFT JOIN log_property p ON l.id = p.logId ORDER BY l.timestamp DESC, p.name", ""); private static string GetInnerPredicate_ts(string sql) => sql.Replace( @"SELECT l.*, p.* from ( SELECT * FROM log WHERE (", "").Replace( @") ORDER BY timestamp DESC LIMIT 100 OFFSET 100 ) l LEFT JOIN log_property p ON l.id = p.logId ORDER BY l.timestamp DESC, p.name", ""); } }
// // SourceView.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2005-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Linq; using System.Collections.Generic; using Gtk; using Cairo; using Mono.Unix; using Hyena; using Hyena.Gui; using Hyena.Gui.Theming; using Hyena.Gui.Theatrics; using Banshee.Configuration; using Banshee.ServiceStack; using Banshee.Sources; using Banshee.Playlist; using Banshee.Gui; namespace Banshee.Sources.Gui { // Note: This is a partial class - the drag and drop code is split // out into a separate file to make this class more manageable. // See SourceView_DragAndDrop.cs for the DnD code. public partial class SourceView : TreeView { private TreeViewColumn source_column; private SourceRowRenderer source_renderer; private CellRendererText header_renderer; private Theme theme; private Cairo.Context cr; private Stage<TreeIter> notify_stage = new Stage<TreeIter> (2000); private TreeIter highlight_iter = TreeIter.Zero; private SourceModel store; private int current_timeout = -1; private bool editing_row = false; private bool need_resort = false; protected SourceView (IntPtr ptr) : base (ptr) {} public SourceView () { FixedHeightMode = false; BuildColumns (); store = new SourceModel (); store.SourceRowInserted += OnSourceRowInserted; store.SourceRowRemoved += OnSourceRowRemoved; store.RowChanged += OnRowChanged; Model = store; EnableSearch = false; ShowExpanders = false; LevelIndentation = 6; ConfigureDragAndDrop (); store.Refresh (); ConnectEvents (); Selection.SelectFunction = (selection, model, path, selected) => { Source source = store.GetSource (path); if (source == null || source is SourceManager.GroupSource) { return false; } return true; }; ResetSelection (); } #region Setup Methods private void BuildColumns () { // Hidden expander column TreeViewColumn col = new TreeViewColumn (); col.Visible = false; AppendColumn (col); ExpanderColumn = col; source_column = new TreeViewColumn (); source_column.Sizing = TreeViewColumnSizing.Autosize; uint xpad = 2; // Special renderer for header rows; hidden for normal source rows header_renderer = new CellRendererText () { Xpad = xpad, Ypad = 4, Ellipsize = Pango.EllipsizeMode.End, Weight = (int)Pango.Weight.Bold, Variant = Pango.Variant.SmallCaps }; // Renderer for source rows; hidden for header rows source_renderer = new SourceRowRenderer (); source_renderer.Xpad = xpad; source_column.PackStart (header_renderer, true); source_column.SetCellDataFunc (header_renderer, new Gtk.CellLayoutDataFunc ((layout, cell, model, iter) => { if (model == null) { throw new ArgumentNullException ("model"); } // be paranoid about the values returned from model.GetValue(), they may be null or have unexpected types, see bgo#683359 var obj_type = model.GetValue (iter, (int)SourceModel.Columns.Type); if (obj_type == null || !(obj_type is SourceModel.EntryType)) { var source = model.GetValue (iter, (int)SourceModel.Columns.Source) as Source; var source_name = source == null ? "some source" : String.Format ("source {0}", source.Name); Log.ErrorFormat ( "SourceView of {0} could not render its source column because its type value returned {1} from the iter", source_name, obj_type == null ? "null" : String.Format ("an instance of {0}", obj_type.GetType ().FullName)); header_renderer.Visible = false; source_renderer.Visible = false; return; } var type = (SourceModel.EntryType) obj_type; header_renderer.Visible = type == SourceModel.EntryType.Group; source_renderer.Visible = type == SourceModel.EntryType.Source; if (type == SourceModel.EntryType.Group) { var source = (Source) model.GetValue (iter, (int)SourceModel.Columns.Source); header_renderer.Visible = true; header_renderer.Text = source.Name; } else { header_renderer.Visible = false; } })); int width, height; Gtk.Icon.SizeLookup (IconSize.Menu, out width, out height); source_renderer.RowHeight = RowHeight.Get (); source_renderer.RowHeight = height; source_renderer.Ypad = (uint)RowPadding.Get (); source_renderer.Ypad = 2; source_column.PackStart (source_renderer, true); source_column.SetCellDataFunc (source_renderer, new CellLayoutDataFunc (SourceRowRenderer.CellDataHandler)); AppendColumn (source_column); HeadersVisible = false; } private void ConnectEvents () { ServiceManager.SourceManager.ActiveSourceChanged += delegate (SourceEventArgs args) { ThreadAssist.ProxyToMain (ResetSelection); }; ServiceManager.SourceManager.SourceUpdated += delegate (SourceEventArgs args) { ThreadAssist.ProxyToMain (delegate { lock (args.Source) { TreeIter iter = store.FindSource (args.Source); if (!TreeIter.Zero.Equals (iter)) { if (args.Source.Expanded) { Expand (args.Source); } need_resort = true; QueueDraw (); } } }); }; ServiceManager.PlaybackController.NextSourceChanged += delegate { ThreadAssist.ProxyToMain (QueueDraw); }; notify_stage.ActorStep += delegate (Actor<TreeIter> actor) { ThreadAssist.AssertInMainThread (); if (!store.IterIsValid (actor.Target)) { return false; } using (var path = store.GetPath (actor.Target) ) { Gdk.Rectangle rect = GetBackgroundArea (path, source_column); QueueDrawArea (rect.X, rect.Y, rect.Width, rect.Height); } return true; }; ServiceManager.Get<InterfaceActionService> ().SourceActions["OpenSourceSwitcher"].Activated += delegate { new SourceSwitcherEntry (this); }; } #endregion #region Gtk.Widget Overrides protected override void OnStyleSet (Style old_style) { base.OnStyleSet (old_style); theme = Hyena.Gui.Theming.ThemeEngine.CreateTheme (this); var light_text = Hyena.Gui.Theming.GtkTheme.GetCairoTextMidColor (this); header_renderer.Foreground = CairoExtensions.ColorGetHex (light_text, false); } // While scrolling the source view with the keyboard, we want to // just skip group sources and jump to the next source in the view. protected override bool OnKeyPressEvent (Gdk.EventKey press) { TreeIter iter; bool movedCursor = false; Selection.GetSelected (out iter); TreePath path = store.GetPath (iter); // Move the path to the next source in line as we need to check if it's a group IncrementPathForKeyPress (press, path); Source source = store.GetSource (path); while (source is SourceManager.GroupSource && IncrementPathForKeyPress (press, path)) { source = store.GetSource (path); SetCursor (path, source_column, false); movedCursor = true; } return movedCursor ? true : base.OnKeyPressEvent (press); } protected override bool OnButtonPressEvent (Gdk.EventButton press) { TreePath path; TreeViewColumn column; if (press.Button == 1) { ResetHighlight (); } // If there is not a row at the click position let the base handler take care of the press if (!GetPathAtPos ((int)press.X, (int)press.Y, out path, out column)) { return base.OnButtonPressEvent (press); } Source source = store.GetSource (path); if (source == null || source is SourceManager.GroupSource) { return false; } // From F-Spot's SaneTreeView class if (source_renderer.InExpander ((int)press.X)) { if (!source.Expanded) { ExpandRow (path, false); } else { CollapseRow (path); } // If the active source is a child of this source, and we are about to collapse it, switch // the active source to the parent. if (source == ServiceManager.SourceManager.ActiveSource.Parent && GetRowExpanded (path)) { ServiceManager.SourceManager.SetActiveSource (source); } return true; } // For Sources that can't be activated, when they're clicked just // expand or collapse them and return. if (press.Button == 1 && !source.CanActivate) { if (!source.Expanded) { ExpandRow (path, false); } else { CollapseRow (path); } return false; } if (press.Button == 3) { TreeIter iter; if (Model.GetIter (out iter, path)) { HighlightIter (iter); OnPopupMenu (); return true; } } if (!source.CanActivate) { return false; } if (press.Button == 1) { if (ServiceManager.SourceManager.ActiveSource != source) { ServiceManager.SourceManager.SetActiveSource (source); } } if ((press.State & Gdk.ModifierType.ControlMask) != 0) { if (press.Type == Gdk.EventType.TwoButtonPress && press.Button == 1) { ActivateRow (path, null); } return true; } return base.OnButtonPressEvent (press); } protected override bool OnPopupMenu () { ServiceManager.Get<InterfaceActionService> ().SourceActions["SourceContextMenuAction"].Activate (); return true; } protected override bool OnExposeEvent (Gdk.EventExpose evnt) { if (need_resort) { need_resort = false; // Resort the tree store. This is performed in an event handler // known not to conflict with gtk_tree_view_bin_expose() to prevent // errors about corrupting the TreeView's internal state. foreach (Source dsource in ServiceManager.SourceManager.Sources) { TreeIter iter = store.FindSource (dsource); if (!TreeIter.Zero.Equals (iter) && (int)store.GetValue (iter, (int)SourceModel.Columns.Order) != dsource.Order) { store.SetValue (iter, (int)SourceModel.Columns.Order, dsource.Order); } } QueueDraw (); } try { cr = Gdk.CairoHelper.Create (evnt.Window); base.OnExposeEvent (evnt); if (Hyena.PlatformDetection.IsMeeGo) { theme.DrawFrameBorder (cr, new Gdk.Rectangle (0, 0, Allocation.Width, Allocation.Height)); } return true; } finally { CairoExtensions.DisposeContext (cr); cr = null; } } private bool IncrementPathForKeyPress (Gdk.EventKey press, TreePath path) { switch (press.Key) { case Gdk.Key.Up: case Gdk.Key.KP_Up: return path.Prev (); case Gdk.Key.Down: case Gdk.Key.KP_Down: path.Next (); return true; } return false; } #endregion #region Gtk.TreeView Overrides protected override void OnRowExpanded (TreeIter iter, TreePath path) { base.OnRowExpanded (iter, path); store.GetSource (iter).Expanded = true; } protected override void OnRowCollapsed (TreeIter iter, TreePath path) { base.OnRowCollapsed (iter, path); store.GetSource (iter).Expanded = false; } protected override void OnCursorChanged () { if (current_timeout < 0) { current_timeout = (int)GLib.Timeout.Add (200, OnCursorChangedTimeout); } } private bool OnCursorChangedTimeout () { TreeIter iter; TreeModel model; current_timeout = -1; if (!Selection.GetSelected (out model, out iter)) { return false; } Source new_source = store.GetValue (iter, (int)SourceModel.Columns.Source) as Source; if (ServiceManager.SourceManager.ActiveSource == new_source) { return false; } ServiceManager.SourceManager.SetActiveSource (new_source); QueueDraw (); return false; } #endregion #region Add/Remove Sources / SourceManager interaction private void OnSourceRowInserted (object o, SourceRowEventArgs args) { args.Source.UserNotifyUpdated += OnSourceUserNotifyUpdated; if (args.Source.Parent != null && args.Source.Parent.AutoExpand == true) { Expand (args.ParentIter); } if (args.Source.Expanded || args.Source.AutoExpand == true) { Expand (args.Iter); } UpdateView (); if (args.Source.Properties.Get<bool> ("NotifyWhenAdded")) { args.Source.NotifyUser (); } } private void OnSourceRowRemoved (object o, SourceRowEventArgs args) { args.Source.UserNotifyUpdated -= OnSourceUserNotifyUpdated; UpdateView (); } private void OnRowChanged (object o, RowChangedArgs args) { QueueDraw (); } internal void Expand (Source src) { Expand (store.FindSource (src)); src.Expanded = true; } private void Expand (TreeIter iter) { using (var path = store.GetPath (iter)) { ExpandRow (path, true); } } private void OnSourceUserNotifyUpdated (object o, EventArgs args) { ThreadAssist.ProxyToMain (delegate { TreeIter iter = store.FindSource ((Source)o); if (iter.Equals (TreeIter.Zero)) { return; } notify_stage.AddOrReset (iter); }); } #endregion #region List/View Utility Methods private bool UpdateView () { for (int i = 0, m = store.IterNChildren (); i < m; i++) { TreeIter iter = TreeIter.Zero; if (!store.IterNthChild (out iter, i)) { continue; } if (store.IterNChildren (iter) > 0) { ExpanderColumn = source_column; return true; } } ExpanderColumn = Columns[0]; return false; } internal void UpdateRow (TreePath path, string text) { TreeIter iter; if (!store.GetIter (out iter, path)) { return; } Source source = store.GetValue (iter, (int)SourceModel.Columns.Source) as Source; source.Rename (text); } public void BeginRenameSource (Source source) { TreeIter iter = store.FindSource (source); if (iter.Equals (TreeIter.Zero)) { return; } source_renderer.Editable = true; using (var path = store.GetPath (iter)) { SetCursor (path, source_column, true); } source_renderer.Editable = false; } private void ResetSelection () { TreeIter iter = store.FindSource (ServiceManager.SourceManager.ActiveSource); if (!iter.Equals (TreeIter.Zero)){ Selection.SelectIter (iter); } } public void HighlightIter (TreeIter iter) { highlight_iter = iter; QueueDraw (); } public void ResetHighlight () { highlight_iter = TreeIter.Zero; QueueDraw (); } #endregion #region Public Properties public Source HighlightedSource { get { if (TreeIter.Zero.Equals (highlight_iter)) { return null; } return store.GetValue (highlight_iter, (int)SourceModel.Columns.Source) as Source; } } public bool EditingRow { get { return editing_row; } set { editing_row = value; QueueDraw (); } } #endregion #region Internal Properties internal TreeIter HighlightedIter { get { return highlight_iter; } } internal Cairo.Context Cr { get { return cr; } } internal Theme Theme { get { return theme; } } internal Stage<TreeIter> NotifyStage { get { return notify_stage; } } internal Source NewPlaylistSource { get { return new_playlist_source ?? (new_playlist_source = new PlaylistSource (Catalog.GetString ("New Playlist"), ServiceManager.SourceManager.MusicLibrary)); } } #endregion #region Property Schemas private static SchemaEntry<int> RowHeight = new SchemaEntry<int> ( "player_window", "source_view_row_height", 22, "The height of each source row in the SourceView. 22 is the default.", ""); private static SchemaEntry<int> RowPadding = new SchemaEntry<int> ( "player_window", "source_view_row_padding", 5, "The padding between sources in the SourceView. 5 is the default.", ""); #endregion } }
using UnityEngine; using System.Collections; /// <summary> /// Provides functionality to use sprites in your scenes that display a multi-coloured gradient /// </summary> public class OTGradientSprite : OTSprite { /// <summary> /// Gradient orientation enumeration /// </summary> public enum GradientOrientation { /// <summary> /// Vertical gradient orientation /// </summary> Vertical, /// <summary> /// Horizontal gradient orientation /// </summary> Horizontal } //----------------------------------------------------------------------------- // Editor settings //----------------------------------------------------------------------------- public GradientOrientation _gradientOrientation = GradientOrientation.Vertical; public OTGradientSpriteColor[] _gradientColors; //----------------------------------------------------------------------------- // public attributes (get/set) //----------------------------------------------------------------------------- /// <summary> /// Gets or sets the gradient orientation. /// </summary> /// <value> /// The gradient orientation. /// </value> public GradientOrientation gradientOrientation { get { return _gradientOrientation; } set { if (value!=_gradientOrientation) { _gradientOrientation = value; meshDirty = true; isDirty = true; } } } /// <summary> /// Gets or sets the gradient colors. /// </summary> /// <value> /// An array with OTGradientSpriteColor elements /// </value> public OTGradientSpriteColor[] gradientColors { get { return _gradientColors; } set { _gradientColors = value; meshDirty = true; isDirty = true; } } private OTGradientSpriteColor[] _gradientColors_; private GradientOrientation _gradientOrientation_ = GradientOrientation.Vertical; void GradientVerts(int vr, int vp, int pos) { if (_gradientOrientation == GradientOrientation.Horizontal) { float dd = (_meshsize_.x/100) * (_gradientColors[vr].position + pos); verts[vp * 2] = new Vector3(mLeft + dd, mTop , 0); // top verts[(vp * 2) +1] = new Vector3(mLeft + dd, mBottom , 0); // bottom } else { float dd = (_meshsize_.y/100) * (_gradientColors[vr].position + pos); verts[vp * 2] = new Vector3(mLeft, mTop - dd , 0); // left verts[(vp * 2) +1] = new Vector3(mRight, mTop - dd , 0); // right } } Vector3[] verts = new Vector3[]{}; /// <exclude/> protected override Mesh GetMesh() { Mesh mesh = InitMesh(); int count = _gradientColors.Length; for (int vr=0; vr<_gradientColors.Length; vr++) if (_gradientColors[vr].size>0) count++; verts = new Vector3[count * 2]; int vp = 0; for (int vr=0; vr<_gradientColors.Length; vr++) { GradientVerts(vr,vp++,0); if (_gradientColors[vr].size>0) GradientVerts(vr,vp++,_gradientColors[vr].size); } mesh.vertices = verts; int[] tris = new int[(count-1) * 6]; for (int vr=0; vr<count-1; vr++) { int vv = vr*2; if (_gradientOrientation == GradientOrientation.Horizontal) { int[] _tris = new int[] { vv,vv+2,vv+3,vv+3,vv+1,vv }; _tris.CopyTo(tris, vr * 6); } else { int[] _tris = new int[] { vv,vv+1,vv+3,vv+3,vv+2,vv }; _tris.CopyTo(tris, vr * 6); } } mesh.triangles = tris; float[] gradientPositions = new float[count]; vp = 0; for(int g = 0; g<gradientColors.Length; g++) { gradientPositions[vp] = gradientColors[g].position; vp++; if (gradientColors[g].size>0) { gradientPositions[vp] = gradientColors[g].position + gradientColors[g].size; vp++; } } mesh.uv = SpliceUV( new Vector2[] { new Vector2(0,1), new Vector2(1,1), new Vector2(1,0), new Vector2(0,0) },gradientPositions, _gradientOrientation == GradientOrientation.Horizontal); return mesh; } void CloneGradientColors() { _gradientColors_ = new OTGradientSpriteColor[_gradientColors.Length]; for (int c=0; c<_gradientColors.Length; c++) { _gradientColors_[c] = new OTGradientSpriteColor(); _gradientColors_[c].position = _gradientColors[c].position; _gradientColors_[c].size = _gradientColors[c].size; _gradientColors_[c].color = _gradientColors[c].color; } } //----------------------------------------------------------------------------- // overridden subclass methods //----------------------------------------------------------------------------- protected override void CheckDirty() { base.CheckDirty(); if (_gradientColors.Length!=_gradientColors_.Length || GradientMeshChanged() || _gradientOrientation_ != _gradientOrientation) meshDirty = true; else if (GradientColorChanged()) isDirty = true; } protected override void CheckSettings() { base.CheckSettings(); if (_gradientColors.Length<2) System.Array.Resize(ref _gradientColors,2); } protected override string GetTypeName() { return "Gradient"; } /// <exclude/> protected override void HandleUV() { if (spriteContainer != null && spriteContainer.isReady) { OTContainer.Frame frame = spriteContainer.GetFrame(frameIndex); // adjust this sprites UV coords if (frame.uv != null && mesh != null) { int count = _gradientColors.Length; for (int vr=0; vr<_gradientColors.Length; vr++) if (_gradientColors[vr].size>0) count++; // get positions for UV splicing float[] gradientPositions = new float[count]; int vp = 0; for(int g = 0; g<gradientColors.Length; g++) { gradientPositions[vp] = gradientColors[g].position; vp++; if (gradientColors[g].size>0) { gradientPositions[vp] = gradientColors[g].position + gradientColors[g].size; vp++; } } // splice UV that we got from the container. mesh.uv = SpliceUV(frame.uv.Clone() as Vector2[],gradientPositions,gradientOrientation == GradientOrientation.Horizontal); } } } /// <exclude/> protected override void Clean() { base.Clean(); if (mesh == null) return; _gradientColors[0].position = 0; _gradientColors[_gradientColors.Length-1].position = 100-_gradientColors[_gradientColors.Length-1].size; CloneGradientColors(); _gradientOrientation_ = _gradientOrientation; var colors = new Color[mesh.vertexCount]; int vp = 0; for (int c=0; c<_gradientColors.Length; c++) { Color col = _gradientColors[c].color; col.a = (col.a * alpha); col.r = (col.r * tintColor.r); col.g = (col.g * tintColor.g); col.b = (col.b * tintColor.b); if (vp < mesh.vertexCount/2) { colors[(vp*2)] = col; colors[(vp*2)+1] = col; } vp++; if (_gradientColors[c].size>0 && vp < mesh.vertexCount/2) { colors[(vp*2)] = col; colors[(vp*2)+1] = col; vp++; } } mesh.colors = colors; } //----------------------------------------------------------------------------- // class methods //----------------------------------------------------------------------------- bool GradientMeshChanged() { bool res = false; for (int c = 0; c < _gradientColors.Length; c++) { if (_gradientColors[c].position < 0) _gradientColors[c].position = 0; if (_gradientColors[c].position > 100) _gradientColors[c].position = 100; if (_gradientColors[c].size < 0) _gradientColors[c].size = 0; if (_gradientColors[c].size > 100) _gradientColors[c].size = 100; if (_gradientColors[c].position+_gradientColors[c].size > 100) _gradientColors[c].position = 100-_gradientColors[c].size; if (_gradientColors[c].position!=_gradientColors_[c].position || _gradientColors[c].size!=_gradientColors_[c].size) res = true; } return res; } bool GradientColorChanged() { for (int c = 0; c < _gradientColors.Length; c++) { if (!_gradientColors[c].color.Equals(_gradientColors_[c].color)) { return true; } } return false; } protected override void Awake() { CloneGradientColors(); _gradientOrientation_ = _gradientOrientation; base.Awake(); } new void Start() { base.Start(); } // Update is called once per frame new void Update() { base.Update(); } } /// <summary> /// OT gradient sprite color element /// </summary> [System.Serializable] public class OTGradientSpriteColor { /// <summary> /// The position of the color (0-100) /// </summary> public int position = 0; /// <summary> /// The size of solid color area (0-100) /// </summary> public int size = 0; /// <summary> /// The color of this element /// </summary> public Color color = Color.white; }
#region License // // The Open Toolkit Library License // // Copyright (c) 2006 - 2009 the Open Toolkit library. // // 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.Text; namespace OpenTK.Input { /// <summary> /// Encapsulates the state of a mouse device. /// </summary> public struct MouseState : IEquatable<MouseState> { #region Fields // Allocate enough ints to store all mouse buttons const int IntSize = sizeof(int); const int NumInts = ((int)MouseButton.LastButton + IntSize - 1) / IntSize; // The following line triggers bogus CS0214 in gmcs 2.0.1, sigh... unsafe fixed int Buttons[NumInts]; int x, y; float wheel; bool is_connected; #endregion #region Public Members /// <summary> /// Gets a <see cref="System.Boolean"/> indicating whether the specified /// <see cref="OpenTK.Input.MouseButton"/> is pressed. /// </summary> /// <param name="button">The <see cref="OpenTK.Input.MouseButton"/> to check.</param> /// <returns>True if key is pressed; false otherwise.</returns> public bool this[MouseButton button] { get { return IsButtonDown(button); } internal set { if (value) EnableBit((int)button); else DisableBit((int)button); } } /// <summary> /// Gets a <see cref="System.Boolean"/> indicating whether this button is down. /// </summary> /// <param name="button">The <see cref="OpenTK.Input.MouseButton"/> to check.</param> public bool IsButtonDown(MouseButton button) { return ReadBit((int)button); } /// <summary> /// Gets a <see cref="System.Boolean"/> indicating whether this button is up. /// </summary> /// <param name="button">The <see cref="OpenTK.Input.MouseButton"/> to check.</param> public bool IsButtonUp(MouseButton button) { return !ReadBit((int)button); } /// <summary> /// Gets the absolute wheel position in integer units. /// To support high-precision mice, it is recommended to use <see cref="WheelPrecise"/> instead. /// </summary> public int Wheel { get { return (int)Math.Round(wheel, MidpointRounding.AwayFromZero); } } /// <summary> /// Gets the absolute wheel position in floating-point units. /// </summary> public float WheelPrecise { get { return wheel; } internal set { wheel = value; } } /// <summary> /// Gets an integer representing the absolute x position of the pointer, in window pixel coordinates. /// </summary> public int X { get { return x; } internal set { x = value; } } /// <summary> /// Gets an integer representing the absolute y position of the pointer, in window pixel coordinates. /// </summary> public int Y { get { return y; } internal set { y = value; } } /// <summary> /// Gets a <see cref="System.Boolean"/> indicating whether the left mouse button is pressed. /// This property is intended for XNA compatibility. /// </summary> public ButtonState LeftButton { get { return IsButtonDown(MouseButton.Left) ? ButtonState.Pressed : ButtonState.Released; } } /// <summary> /// Gets a <see cref="System.Boolean"/> indicating whether the middle mouse button is pressed. /// This property is intended for XNA compatibility. /// </summary> public ButtonState MiddleButton { get { return IsButtonDown(MouseButton.Middle) ? ButtonState.Pressed : ButtonState.Released; } } /// <summary> /// Gets a <see cref="System.Boolean"/> indicating whether the right mouse button is pressed. /// This property is intended for XNA compatibility. /// </summary> public ButtonState RightButton { get { return IsButtonDown(MouseButton.Right) ? ButtonState.Pressed : ButtonState.Released; } } /// <summary> /// Gets a <see cref="System.Boolean"/> indicating whether the first extra mouse button is pressed. /// This property is intended for XNA compatibility. /// </summary> public ButtonState XButton1 { get { return IsButtonDown(MouseButton.Button1) ? ButtonState.Pressed : ButtonState.Released; } } /// <summary> /// Gets a <see cref="System.Boolean"/> indicating whether the second extra mouse button is pressed. /// This property is intended for XNA compatibility. /// </summary> public ButtonState XButton2 { get { return IsButtonDown(MouseButton.Button2) ? ButtonState.Pressed : ButtonState.Released; } } /// <summary> /// Gets the absolute wheel position in integer units. This property is intended for XNA compatibility. /// To support high-precision mice, it is recommended to use <see cref="WheelPrecise"/> instead. /// </summary> public int ScrollWheelValue { get { return Wheel; } } public bool IsConnected { get { return is_connected; } internal set { is_connected = value; } } /// <summary> /// Checks whether two <see cref="MouseState" /> instances are equal. /// </summary> /// <param name="left"> /// A <see cref="MouseState"/> instance. /// </param> /// <param name="right"> /// A <see cref="MouseState"/> instance. /// </param> /// <returns> /// True if both left is equal to right; false otherwise. /// </returns> public static bool operator ==(MouseState left, MouseState right) { return left.Equals(right); } /// <summary> /// Checks whether two <see cref="MouseState" /> instances are not equal. /// </summary> /// <param name="left"> /// A <see cref="MouseState"/> instance. /// </param> /// <param name="right"> /// A <see cref="MouseState"/> instance. /// </param> /// <returns> /// True if both left is not equal to right; false otherwise. /// </returns> public static bool operator !=(MouseState left, MouseState right) { return !left.Equals(right); } /// <summary> /// Compares to an object instance for equality. /// </summary> /// <param name="obj"> /// The <see cref="System.Object"/> to compare to. /// </param> /// <returns> /// True if this instance is equal to obj; false otherwise. /// </returns> public override bool Equals(object obj) { if (obj is MouseState) { return this == (MouseState)obj; } else { return false; } } /// <summary> /// Generates a hashcode for the current instance. /// </summary> /// <returns> /// A <see cref="System.Int32"/> represting the hashcode for this instance. /// </returns> public override int GetHashCode() { unsafe { fixed (int* b = Buttons) { return b->GetHashCode() ^ X.GetHashCode() ^ Y.GetHashCode() ^ WheelPrecise.GetHashCode(); } } } #endregion #region Internal Members internal bool ReadBit(int offset) { ValidateOffset(offset); int int_offset = offset / 32; int bit_offset = offset % 32; unsafe { fixed (int* b = Buttons) { return (*(b + int_offset) & (1 << bit_offset)) != 0u; } } } internal void EnableBit(int offset) { ValidateOffset(offset); int int_offset = offset / 32; int bit_offset = offset % 32; unsafe { fixed (int* b = Buttons) { *(b + int_offset) |= 1 << bit_offset; } } } internal void DisableBit(int offset) { ValidateOffset(offset); int int_offset = offset / 32; int bit_offset = offset % 32; unsafe { fixed (int* b = Buttons) { *(b + int_offset) &= ~(1 << bit_offset); } } } internal void MergeBits(MouseState other) { unsafe { int* b2 = other.Buttons; fixed (int* b1 = Buttons) { for (int i = 0; i < NumInts; i++) *(b1 + i) |= *(b2 + i); } WheelPrecise += other.WheelPrecise; X += other.X; Y += other.Y; IsConnected |= other.IsConnected; } } #endregion #region Private Members static void ValidateOffset(int offset) { if (offset < 0 || offset >= NumInts * IntSize) throw new ArgumentOutOfRangeException("offset"); } #endregion #region IEquatable<MouseState> Members /// <summary> /// Compares two MouseState instances. /// </summary> /// <param name="other">The instance to compare two.</param> /// <returns>True, if both instances are equal; false otherwise.</returns> public bool Equals(MouseState other) { bool equal = true; unsafe { int* b2 = other.Buttons; fixed (int* b1 = Buttons) { for (int i = 0; equal && i < NumInts; i++) equal &= *(b1 + i) == *(b2 + i); } equal &= X == other.X && Y == other.Y && WheelPrecise == other.WheelPrecise; } return equal; } #endregion } }
//----------------------------------------------------------------------- // <copyright file="InnerList.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <summary> // Implements the InnerList control. //</summary> //----------------------------------------------------------------------- namespace Microsoft.Management.UI.Internal { using System; using System.Collections.Generic; using System.Text; using System.Globalization; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Collections; using System.ComponentModel; using System.Windows.Markup; using System.Windows.Automation; using System.Windows.Threading; using System.Diagnostics; using System.Collections.ObjectModel; using System.Collections.Specialized; /// <content> /// Partial class implementation for InnerList control. /// </content> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] public partial class InnerList : System.Windows.Controls.ListView { #region internal fields #region StyleCop Suppression - generated code /// <summary> /// The current ICollectionView being displayed /// </summary> internal ICollectionView CollectionView; #endregion StyleCop Suppression - generated code #endregion internal fields #region private fields /// <summary> /// The current GridView. /// </summary> private InnerListGridView innerGrid; private InnerListColumn sortedColumn; /// <summary> /// ContextMenu for InnerList columns. /// </summary> private ContextMenu contextMenu; /// <summary> /// Private setter for <see cref="Columns"/>. /// </summary> private ObservableCollection<InnerListColumn> columns = new ObservableCollection<InnerListColumn>(); /// <summary> /// Gets or sets whether the current items source is non-null and has items. /// </summary> private bool itemsSourceIsEmpty = false; #endregion private fields #region constructors /// <summary> /// Initializes a new instance of this control. /// </summary> public InnerList() : base() { // This flag is needed to dramatically increase performance of scrolling \\ VirtualizingStackPanel.SetVirtualizationMode(this, VirtualizationMode.Recycling); AutomationProperties.SetAutomationId(this, "InnerList"); // No localization needed } #endregion constructors #region Events /// <summary> /// Register PropertyChangedEventHandler ItemSourcesPropertyChanged . /// </summary> public event PropertyChangedEventHandler ItemSourcesPropertyChanged; #endregion Events #region public properties /// <summary> /// Gets ItemsSource instead. /// <seealso cref="InnerList"/> Does not support adding to Items. /// </summary> [Browsable(false)] public new ItemCollection Items { get { return base.Items; } } /// <summary> /// Gets the column that is sorted, or <c>null</c> if no column is sorted. /// </summary> public InnerListColumn SortedColumn { get { return this.sortedColumn; } } /// <summary> /// Gets InnerListGridView. /// </summary> public InnerListGridView InnerGrid { get { return this.innerGrid; } protected set { this.innerGrid = value; } } /// <summary> /// Gets the collection of columns that this list should display. /// </summary> public ObservableCollection<InnerListColumn> Columns { get { return this.columns; } } #endregion public properties #region public methods /// <summary> /// Causes the object to scroll into view. /// </summary> /// <param name="item">Object to scroll.</param> /// <remarks>This method overrides ListBox.ScrollIntoView(), which throws NullReferenceException when VirtualizationMode is set to Recycling. /// This implementation uses a workaround recommended by the WPF team.</remarks> public new void ScrollIntoView(object item) { Dispatcher.BeginInvoke( DispatcherPriority.Background, (DispatcherOperationCallback)delegate(object arg) { if (this.IsLoaded) { base.ScrollIntoView(arg); } return null; }, item); } /// <summary> /// Causes the object to scroll into view from the top, so that it tends to appear at the bottom of the scroll area. /// </summary> /// <param name="item">Object to scroll.</param> public void ScrollIntoViewFromTop(object item) { if (this.Items.Count > 0) { this.ScrollIntoView(this.Items[0]); this.ScrollIntoView(item); } } /// <summary> /// Updates the InnerGrid based upon the columns collection. /// </summary> public void RefreshColumns() { this.UpdateView(this.ItemsSource); } /// <summary> /// Sorts the list by the specified column. This has no effect if the list does not have a data source. /// </summary> /// <param name="column"> /// The column to sort /// </param> /// <param name="shouldScrollIntoView"> /// Indicates whether the SelectedItem should be scrolled into view. /// </param> /// <exception cref="ArgumentNullException">The specified value is a null reference.</exception> public void ApplySort(InnerListColumn column, bool shouldScrollIntoView) { if (column == null) { throw new ArgumentNullException("column"); } // NOTE : By setting the column here, it will be used // later to set the sorted column when the UI state // is ready. this.sortedColumn = column; // If the list hasn't been populated, don't do anything \\ if (this.CollectionView == null) { return; } this.UpdatePrimarySortColumn(); using (this.CollectionView.DeferRefresh()) { ListCollectionView lcv = (ListCollectionView)this.CollectionView; lcv.CustomSort = new PropertyValueComparer(this.GetDescriptionsForSorting(), true, FilterRuleCustomizationFactory.FactoryInstance.PropertyValueGetter); } if (shouldScrollIntoView && this.SelectedIndex > 0) { this.ScrollIntoView(this.SelectedItem); } } private void UpdatePrimarySortColumn() { foreach (InnerListColumn column in this.InnerGrid.AvailableColumns) { bool isPrimarySortColumn = Object.ReferenceEquals(this.sortedColumn, column); InnerList.SetIsPrimarySortColumn(column, isPrimarySortColumn); InnerList.SetIsPrimarySortColumn((GridViewColumnHeader)column.Header, isPrimarySortColumn); } } /// <summary> /// Gets a list of data descriptions for the columns that are not the primary sort column. /// </summary> /// <returns>A list of data descriptions for the columns that are not the primary sort column.</returns> private List<UIPropertyGroupDescription> GetDescriptionsForSorting() { List<UIPropertyGroupDescription> dataDescriptions = new List<UIPropertyGroupDescription>(); dataDescriptions.Add(this.SortedColumn.DataDescription); foreach (InnerListColumn column in this.InnerGrid.Columns) { if (!Object.ReferenceEquals(this.SortedColumn, column)) { dataDescriptions.Add(column.DataDescription); } } return dataDescriptions; } /// <summary> /// Clears the sort order from the list. /// </summary> public void ClearSort() { if (null == this.CollectionView) { return; } using (this.CollectionView.DeferRefresh()) { this.sortedColumn = null; ListCollectionView lcv = (ListCollectionView)this.CollectionView; lcv.CustomSort = null; } // If columns are shown, update them to show none are sorted \\ if (this.InnerGrid != null) { this.UpdatePrimarySortColumn(); } } #endregion public methods #region internal methods #endregion internal methods #region protected methods /// <summary> /// Called when the ItemsSource changes to set internal fields, subscribe to the view change /// and possibly autopopulate columns. /// </summary> /// <param name="oldValue">Previous ItemsSource.</param> /// <param name="newValue">Current ItemsSource.</param> protected override void OnItemsSourceChanged(System.Collections.IEnumerable oldValue, System.Collections.IEnumerable newValue) { base.OnItemsSourceChanged(oldValue, newValue); this.itemsSourceIsEmpty = (null != this.ItemsSource && false == this.ItemsSource.GetEnumerator().MoveNext()); // A view can be created if there is data to auto-generate columns, or columns are added programmatically \\ bool canCreateView = (null != this.ItemsSource) && (false == this.itemsSourceIsEmpty || false == this.AutoGenerateColumns); if (canCreateView) { this.UpdateViewAndCollectionView(this.ItemsSource); // If there are items, select the first item now \\ this.SelectedIndex = this.itemsSourceIsEmpty ? -1 : 0; } else { // Release the current inner grid \\ this.ReleaseInnerGridReferences(); // clean up old state if can not set the state. this.SetCollectionView(null); this.innerGrid = null; this.View = null; } } /// <summary> /// Called when ItemsChange to throw an exception indicating we don't support /// changing Items directly. /// </summary> /// <param name="e">Event parameters.</param> protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e) { base.OnItemsChanged(e); if (e.NewItems != null) { // If the items source now has items, select the first item \\ if (this.itemsSourceIsEmpty && this.Items.Count > 0) { this.SelectedIndex = 0; this.itemsSourceIsEmpty = false; } if (e.Action == NotifyCollectionChangedAction.Add) { if (this.InnerGrid == null) { this.UpdateViewAndCollectionView(this.ItemsSource); } } } } /// <summary> /// Called when a key is pressed while within the InnerList scope. /// </summary> /// <param name="e">The event args.</param> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if ((Key.Left == e.Key || Key.Right == e.Key) && Keyboard.Modifiers == ModifierKeys.None) { // If pressing Left or Right on a column header, move the focus \\ GridViewColumnHeader header = e.OriginalSource as GridViewColumnHeader; if (null != header) { header.MoveFocus(new TraversalRequest(KeyboardHelp.GetNavigationDirection(this, e.Key))); e.Handled = true; } } } #endregion protected methods #region static private methods /// <summary> /// Called when the View property is changed. /// </summary> /// <param name="obj">InnerList whose property is being changed.</param> /// <param name="e">Event arguments.</param> private static void InnerList_OnViewChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) { InnerList thisList = (InnerList)obj; GridView newGrid = e.NewValue as GridView; InnerListGridView innerGrid = e.NewValue as InnerListGridView; if (newGrid != null && innerGrid == null) { throw new NotSupportedException(String.Format( CultureInfo.InvariantCulture, InvariantResources.ViewSetWithType, typeof(GridView).Name, typeof(InnerListGridView).Name)); } ((InnerList)obj).innerGrid = innerGrid; } /// <summary> /// Gets the exception to be thrown when using Items. /// </summary> /// <returns>The exception to be thrown when using Items.</returns> private static NotSupportedException GetItemsException() { return new NotSupportedException( String.Format( CultureInfo.InvariantCulture, InvariantResources.NotSupportAddingToItems, typeof(InnerList).Name, ItemsControl.ItemsSourceProperty.Name)); } #endregion static private methods #region instance private methods /// <summary> /// Called from OnItemsSourceChanged to set the collectionView field and /// subscribe to the collectionView changed event. /// </summary> /// <param name="newValue">ITemsSource passed to OnItemsSourceChanged.</param> private void SetCollectionView(System.Collections.IEnumerable newValue) { if (newValue == null) { this.CollectionView = null; } else { CollectionViewSource newValueViewSource = newValue as CollectionViewSource; if (newValueViewSource != null && newValueViewSource.View != null) { this.CollectionView = newValueViewSource.View; } else { this.CollectionView = CollectionViewSource.GetDefaultView(newValue); } } } /// <summary> /// Update View And CollectionView. /// </summary> /// <param name="value">InnerList object.</param> private void UpdateViewAndCollectionView(IEnumerable value) { Debug.Assert(value != null, "value should be non-null"); // SetCollectionView deals with a null newEnumerable this.SetCollectionView(value); this.UpdateView(value); // Generate property changed event. if (this.ItemSourcesPropertyChanged != null) { this.ItemSourcesPropertyChanged(this, new PropertyChangedEventArgs("ItemsSource")); } } private void UpdateView(IEnumerable value) { // NOTE : We need to clear the SortDescription before // clearing the InnerGrid.Columns so that the Adorners // are appropriately cleared. InnerListColumn sortedColumn = this.SortedColumn; this.ClearSort(); // Release the current inner grid \\ this.ReleaseInnerGridReferences(); if (this.AutoGenerateColumns) { this.innerGrid = new InnerListGridView(); // PopulateColumns deals with a null newEnumerable this.innerGrid.PopulateColumns(value); } else { this.innerGrid = new InnerListGridView(this.Columns); } this.View = this.innerGrid; this.SetColumnHeaderActions(); if (null != sortedColumn && this.Columns.Contains(sortedColumn)) { this.ApplySort(sortedColumn, false); } } /// <summary> /// Releases all references to the current inner grid, if one exists. /// </summary> private void ReleaseInnerGridReferences() { if (this.innerGrid != null) { // Tell the inner grid to release its references \\ this.innerGrid.ReleaseReferences(); // Release the column headers \\ foreach (InnerListColumn column in this.innerGrid.AvailableColumns) { GridViewColumnHeader header = column.Header as GridViewColumnHeader; if (header != null) { header.Click -= this.Header_Click; header.PreviewKeyDown -= this.Header_KeyDown; } } } } /// <summary> /// Called when the ItemsSource changes, after SetGridview to add event handlers /// to the column header. /// </summary> internal void SetColumnHeaderActions() { if (this.innerGrid == null) { return; } // set context menu this.innerGrid.ColumnHeaderContextMenu = this.GetListColumnsContextMenu(); foreach (GridViewColumn column in this.innerGrid.AvailableColumns) { // A string header needs an explicit GridViewColumnHeader // so we can hook up our events string headerString = column.Header as string; if (headerString != null) { GridViewColumnHeader columnHeader = new GridViewColumnHeader(); columnHeader.Content = headerString; column.Header = columnHeader; } GridViewColumnHeader header = column.Header as GridViewColumnHeader; if (header != null) { // header Click header.Click += new RoutedEventHandler(this.Header_Click); header.PreviewKeyDown += new KeyEventHandler(this.Header_KeyDown); } // If it is a GridViewColumnHeader we will not have the same nice sorting and grouping // capabilities } } #region ApplicationCommands.Copy partial void OnCopyCanExecuteImplementation(CanExecuteRoutedEventArgs e) { e.CanExecute = this.SelectedItems.Count > 0; } partial void OnCopyExecutedImplementation(ExecutedRoutedEventArgs e) { string text = this.GetClipboardTextForSelectedItems(); this.SetClipboardWithSelectedItemsText(text); } #region Copy Helpers /// <summary> /// Gets a tab-delimited string representing the data of the selected rows. /// </summary> /// <returns>A tab-delimited string representing the data of the selected rows.</returns> protected internal string GetClipboardTextForSelectedItems() { StringBuilder text = new StringBuilder(); foreach (object value in this.Items) { if (this.SelectedItems.Contains(value)) { string entry = this.GetClipboardTextLineForSelectedItem(value); text.AppendLine(entry); } } return text.ToString(); } private string GetClipboardTextLineForSelectedItem(object value) { StringBuilder entryText = new StringBuilder(); foreach (InnerListColumn column in this.InnerGrid.Columns) { object propertyValue; if (!FilterRuleCustomizationFactory.FactoryInstance.PropertyValueGetter.TryGetPropertyValue(column.DataDescription.PropertyName, value, out propertyValue)) { propertyValue = String.Empty; } entryText.AppendFormat(CultureInfo.CurrentCulture, "{0}\t", propertyValue); } return entryText.ToString(); } private void SetClipboardWithSelectedItemsText(string text) { if (String.IsNullOrEmpty(text)) { return; } DataObject data = new DataObject(DataFormats.UnicodeText, text); Clipboard.SetDataObject(data); } #endregion Copy Helpers #endregion ApplicationCommands.Copy /// <summary> /// Called to implement sorting functionality on column header pressed by space or enter key. /// </summary> /// <param name="sender">Typically a GridViewColumnHeader.</param> /// <param name="e">The event information.</param> private void Header_KeyDown(object sender, KeyEventArgs e) { if (e.Key != Key.Space && e.Key != Key.Enter) { return; } // Call HeaderActionProcess when space or enter key pressed this.HeaderActionProcess(sender); e.Handled = true; } /// <summary> /// Called to implement sorting functionality on column header click. /// </summary> /// <param name="sender">Typically a GridViewColumnHeader.</param> /// <param name="e">The event information.</param> private void Header_Click(object sender, RoutedEventArgs e) { // Call HeaderActionProcess when mouse clicked on the header this.HeaderActionProcess(sender); } /// <summary> /// Called to implement sorting functionality. /// </summary> /// <param name="sender">Typically a GridViewColumnHeader.</param> private void HeaderActionProcess(object sender) { GridViewColumnHeader header = (GridViewColumnHeader)sender; InnerListColumn column = (InnerListColumn)header.Column; UIPropertyGroupDescription dataDescription = column.DataDescription; if (dataDescription == null) { return; } // If the sorted column is sorted again, reverse the sort \\ if (Object.ReferenceEquals(column, this.sortedColumn)) { dataDescription.ReverseSortDirection(); } this.ApplySort(column, true); } /// <summary> /// Create default Context Menu. /// </summary> /// <returns>ContextMenu of List Columns.</returns> private ContextMenu GetListColumnsContextMenu() { this.contextMenu = new ContextMenu(); // Add Context Menu item. this.SetColumnPickerContextMenuItem(); return this.contextMenu; } /// <summary> /// Set up context menu item for Column Picker feature. /// </summary> /// <returns>True if it is successfully set up.</returns> private bool SetColumnPickerContextMenuItem() { MenuItem columnPicker = new MenuItem(); AutomationProperties.SetAutomationId(columnPicker, "ChooseColumns"); columnPicker.Header = UICultureResources.ColumnPicker; columnPicker.Click += new RoutedEventHandler(this.innerGrid.OnColumnPicker); this.contextMenu.Items.Add(columnPicker); return true; } static partial void StaticConstructorImplementation() { // Adds notification for the View changing ListView.ViewProperty.OverrideMetadata( typeof(InnerList), new PropertyMetadata(new PropertyChangedCallback(InnerList_OnViewChanged))); } #endregion instance private methods } }
using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.Threading; using System.Linq; using System.Reflection; namespace Shielded { /// <summary> /// Central class of the Shielded library. Contains, among other things, methods /// for directly running transactions, and creating conditional transactions. /// </summary> public static class Shield { [ThreadStatic] private static TransactionContextInternal _context; internal static TransactionContext Context { get { return _context; } } internal static bool CommitCheckDone { get { return _context.CommitCheckDone; } } /// <summary> /// Current transaction's read stamp, i.e. the latest version it can read. /// Thread-static. Throws if called out of transaction. /// </summary> public static long ReadStamp { get { AssertInTransaction(); return _context.ReadTicket.Stamp; } } /// <summary> /// Gets a value indicating whether the current thread is in a transaction. /// </summary> public static bool IsInTransaction { get { return _context != null; } } /// <summary> /// Throws <see cref="InvalidOperationException"/> if called out of a transaction. /// </summary> public static void AssertInTransaction() { if (_context == null) throw new InvalidOperationException("Operation needs to be in a transaction."); } [ThreadStatic] private static IShielded _blockEnlist; [ThreadStatic] private static bool _enforceTracking; [ThreadStatic] private static int? _commuteTime; /// <summary> /// Enlist the specified item in the transaction. Returns true if this is the /// first time in this transaction that this item is enlisted. hasLocals indicates /// if this item already has local storage prepared. If true, it means it must have /// enlisted already. However, in IsolatedRun you may have locals, even though you /// have not yet enlisted in the isolated items! This param dictates the response /// if it is set to true, adding to the isolated items is not revealed by the retval. /// </summary> internal static bool Enlist(IShielded item, bool hasLocals, bool write) { AssertInTransaction(); var ctx = _context; if (write && ctx.CommitCheckDone && !item.HasChanges) throw new InvalidOperationException("New writes not allowed here."); if (_blockEnlist != null && _blockEnlist != item) throw new InvalidOperationException("Accessing other shielded fields in this context is forbidden."); var items = ctx.Items; if (hasLocals) { if (_enforceTracking) items.Enlisted.Add(item); items.HasChanges = items.HasChanges || write; return false; } items.HasChanges = items.HasChanges || write; if (!items.Enlisted.Contains(item)) { if (ctx.CommitCheckDone) throw new InvalidOperationException("Cannot access new fields here."); // must not add into Enlisted before we run commutes, otherwise commutes' calls // to Enlist would return false, and the commutes, although running first, would // not actually check the lock! this also means that CheckCommutes must tolerate // being reentered with the same item. CheckCommutes(item); return items.Enlisted.Add(item); } return false; } /// <summary> /// When an item is enlisted for which we have defined commutes, it causes those /// commutes to be executed immediately. This happens before the field is read or /// written into. The algorithm here allows for one commute to trigger others, /// guaranteeing that they will all execute in correct order provided that each /// commute correctly defined the fields which, if accessed, must cause it to /// degenerate. /// </summary> private static void CheckCommutes(IShielded item) { var commutes = _context.Items.Commutes; if (commutes == null || commutes.Count == 0) return; // in case one commute triggers others, we mark where we are in _comuteTime, // and no recursive call will execute commutes beyond that point. // so, clean "dependency resolution" - we trigger only those before us. those // after us just get marked, and then we execute them (or, someone lower in the stack). var oldTime = _commuteTime; var oldBlock = _blockCommute; int execLimit = oldTime ?? commutes.Count; try { if (!oldTime.HasValue) _blockCommute = true; for (int i = 0; i < commutes.Count; i++) { var comm = commutes[i]; if (comm.State == CommuteState.Ok && comm.Affecting.Contains(item)) comm.State = CommuteState.Broken; if (comm.State == CommuteState.Broken && i < execLimit) { _commuteTime = i; comm.State = CommuteState.Executed; comm.Perform(); } } } catch { // not sure if this matters, but i like it. please note that this and the Remove in finally // do not necessarily affect the same commutes. commutes.RemoveAll(c => c.Affecting.Contains(item)); throw; } finally { _commuteTime = oldTime; if (!oldTime.HasValue) { _blockCommute = oldBlock; commutes.RemoveAll(c => c.State != CommuteState.Ok); } } } [ThreadStatic] private static bool _blockCommute; /// <summary> /// The strict version of EnlistCommute, which will monitor that the code in /// perform does not enlist anything except the one item, affecting. /// </summary> internal static void EnlistStrictCommute(Action perform, IShielded affecting) { EnlistCommute(() => { // if a strict commute is enlisted from within another strict commute... // if != null, this definitely equals our affecting. even if not so, // perform trying to access anything else will be prevented in Enlist(). if (_blockEnlist != null) { perform(); return; } try { _blockEnlist = affecting; perform(); } finally { _blockEnlist = null; } }, affecting); } /// <summary> /// The action is performed just before commit, and reads the latest /// data. If it conflicts, only it is retried. If it succeeds, /// we (try to) commit with the same write stamp along with it. /// The affecting param determines the IShieldeds that this transaction must /// not access, otherwise this commute must degenerate - it gets executed /// now, or at the moment when any of these IShieldeds enlists. /// </summary> internal static void EnlistCommute(Action perform, params IShielded[] affecting) { if (affecting == null) throw new ArgumentException(); if (_blockCommute) perform(); // Enlist will check for any access violations AssertInTransaction(); var items = _context.Items; if (items.Enlisted.Overlaps(affecting)) perform(); else { items.HasChanges = true; if (items.Commutes == null) items.Commutes = new List<Commute>(); items.Commutes.Add(new Commute(perform, affecting)); } } /// <summary> /// Conditional transaction, which executes after some fields are committed into. /// Does not execute immediately! Test is executed once just to get a read pattern, /// result is ignored. It will later be re-executed when any of the accessed /// IShieldeds commits. /// When test passes, executes trans. Test is executed in a normal transaction. If it /// changes access patterns between calls, the subscription changes as well! /// Test and trans are executed in single transaction, and if the commit fails, test /// is also retried! /// </summary> /// <returns>An IDisposable which can be used to cancel the conditional by calling /// Dispose on it. Dispose can be called from trans.</returns> public static IDisposable Conditional(Func<bool> test, Action trans) { if (test == null || trans == null) throw new ArgumentNullException(); return new CommitSubscription(CommitSubscriptionContext.PostCommit, test, trans); } /// <summary> /// Pre-commit check, which executes just before commit of a transaction involving /// certain fields. Can be used to ensure certain invariants hold, for example. /// Does not execute immediately! Test is executed once just to get a read pattern, /// result is ignored. It will later be re-executed just before commit of any transaction /// that changes one of the fields it accessed. /// If test passes, executes trans as well. They will execute within the transaction /// that triggers them. If they access a commuted field, the commute will degenerate. /// </summary> /// <returns>An IDisposable which can be used to cancel the pre-commit by calling /// Dispose on it. Dispose can be called from trans.</returns> public static IDisposable PreCommit(Func<bool> test, Action trans) { if (test == null || trans == null) throw new ArgumentNullException(); return new CommitSubscription(CommitSubscriptionContext.PreCommit, test, trans); } /// <summary> /// Execute an action during every commit which changes fields of a type. /// The action will be immediately enlisted, and get called after any commit is /// checked, but before anything is written. Any exceptions bubble out to the thread /// running the transaction (or, on calling <see cref="CommitContinuation.Commit"/>). /// Calls to <see cref="Rollback"/> are not allowed. /// The action may not access any fields that the transaction did not already access, /// and it may only write into fields which were already written to by the transaction. /// This method throws when called within a transaction. /// </summary> /// <returns>An IDisposable for unsubscribing.</returns> public static IDisposable WhenCommitting<T>(Action<IEnumerable<T>> act) where T : class { if (act == null) throw new ArgumentNullException(); if (IsInTransaction) throw new InvalidOperationException("Operation not allowed in transaction."); return new CommittingSubscription( fields => { List<T> interesting = null; for (int i = 0; i < fields.Length; i++) { var field = fields[i]; T obj; if (field.HasChanges && (obj = field.Field as T) != null) { if (interesting == null) interesting = new List<T>(); interesting.Add(obj); } } if (interesting != null) act(interesting); }); } /// <summary> /// Execute an action during every writing commit which reads or changes a given field. /// The lambda receives a bool indicating whether the field has changes. /// The action will be immediately enlisted, and get called after any commit is /// checked, but before anything is written. Any exceptions bubble out to the thread /// running the transaction (or, on calling <see cref="CommitContinuation.Commit"/>). /// Calls to <see cref="Rollback"/> are not allowed. /// The action may not access any fields that the transaction did not already access, /// and it may only write into fields which were already written to by the transaction. /// This method throws when called within a transaction. /// </summary> /// <returns>An IDisposable for unsubscribing.</returns> public static IDisposable WhenCommitting(object field, Action<bool> act) { if (field == null || act == null) throw new ArgumentNullException(); return WhenCommitting(fields => { var tf = fields.FirstOrDefault(f => f.Field == field); if (tf.Field != null) act(tf.HasChanges); }); } /// <summary> /// Execute an action during every writing commit. /// The action will be immediately enlisted, and get called after any commit is /// checked, but before anything is written. Any exceptions bubble out to the thread /// running the transaction (or, on calling <see cref="CommitContinuation.Commit"/>). /// Calls to <see cref="Rollback"/> are not allowed. /// The action may not access any fields that the transaction did not already access, /// and it may only write into fields which were already written to by the transaction. /// This version receives a full list of enlisted items, even those without changes. /// This method throws when called within a transaction. /// </summary> /// <returns>An IDisposable for unsubscribing.</returns> public static IDisposable WhenCommitting(Action<IEnumerable<TransactionField>> act) { if (act == null) throw new ArgumentNullException(); if (IsInTransaction) throw new InvalidOperationException("Operation not allowed in transaction."); return new CommittingSubscription(act); } /// <summary> /// Enlists a side-effect - an operation to be performed only if the transaction /// commits. Optionally receives an action to perform in case of a rollback. /// If the transaction is rolled back, all enlisted side-effects are (also) cleared. /// Should be used to perform all IO and such operations (except maybe logging). /// /// If this is called out of transaction, the fx action (if one was provided) /// will be directly executed. This preserves correct behavior if the call finds /// itself sometimes in, sometimes out of transaction, because of some crazy /// nesting differences. /// </summary> public static void SideEffect(Action fx, Action rollbackFx = null) { if (fx == null && rollbackFx == null) throw new ArgumentNullException(null, "At least one arg must be != null."); if (!IsInTransaction) { if (fx != null) fx(); return; } if (_context.Items.Fx == null) _context.Items.Fx = new List<SideEffect>(); _context.Items.Fx.Add(new SideEffect(fx, rollbackFx)); } /// <summary> /// Enlists a synchronized side effect. Such side effects are executed during a /// commit, when individual transactional fields are still locked. They run just /// before any triggered <see cref="WhenCommitting"/> subscriptions, under the /// same conditions as they do. This can only be called within transactions. /// If the transaction is read-only, this will still work, but it will not be in /// sync with anything - please note that a read-only transaction locks nothing. /// </summary> public static void SyncSideEffect(Action fx) { if (fx == null) throw new ArgumentNullException(); AssertInTransaction(); if (_context.Items.SyncFx == null) _context.Items.SyncFx = new List<Action>(); _context.Items.SyncFx.Add(fx); } /// <summary> /// Executes the function in a transaction, and returns its final result. /// Transactions may, in case of conflicts, get repeated from beginning. Your /// delegate should be ready for this. If you wish to do IO or similar /// operations, which should not be repeated, pass them to /// <see cref="Shield.SideEffect"/>. Nesting InTransaction calls is allowed, /// the nested transactions are treated as normal parts of the outer transaction. /// </summary> public static T InTransaction<T>(Func<T> act) { T retVal = default(T); Shield.InTransaction(() => { retVal = act(); }); return retVal; } /// <summary> /// Executes the action in a transaction. /// Transactions may, in case of conflicts, get repeated from beginning. Your /// delegate should be ready for this. If you wish to do IO or similar /// operations, which should not be repeated, pass them to /// <see cref="Shield.SideEffect"/>. Nesting InTransaction calls is allowed, /// the nested transactions are treated as normal parts of the outer transaction. /// </summary> public static void InTransaction(Action act) { if (IsInTransaction) act(); else TransactionLoop(act, () => { _context.DoCommit(); }); } /// <summary> /// Runs a transaction, with repetitions if needed, until it passes the commit check, /// and then stops. The fields that will be written into, remain locked! It returns /// an object which can be used to later commit the transaction, roll it back, or run /// code inside of its scope, restricted to fields touched by the original transaction. /// Receives a timeout in milliseconds, and the returned continuation will, if not /// completed by then, automatically roll back by this time. /// </summary> public static CommitContinuation RunToCommit(int timeoutMs, Action act) { if (IsInTransaction) throw new InvalidOperationException("Operation not allowed in transaction."); CommitContinuation res = null; try { TransactionLoop(act, () => { res = _context; _context = null; }); return res; } finally { if (res != null && !res.Completed) res.StartTimer(timeoutMs); } } static void TransactionLoop(Action act, Action onChecked) { while (true) { try { _context = new TransactionContextInternal(); _context.Open(); act(); if (_rollback.HasValue) continue; if (CommitCheck()) { onChecked(); return; } _context.DoCheckFailed(); } catch (Exception ex) when (IsTransException(ex)) { } finally { if (_context != null) _context.DoRollback(); } } } /// <summary> /// Helper for checking if an exception is <see cref="TransException"/>, or an /// aggregate or target invocation exception which contain a TransException. Checks /// them recursively. Such an exception causes a retry of the current transaction. /// </summary> /// <param name="ex">Exception to check.</param> /// <returns>True if the exception is or contains a <see cref="TransException"/>.</returns> public static bool IsTransException(Exception ex) { return ex is TransException || ex is TargetInvocationException ti && IsTransException(ti.InnerException) || ex is AggregateException aggr && aggr.InnerExceptions.Any(IsTransException); } private static readonly ShieldedLocal<bool> _rollback = new ShieldedLocal<bool>(); /// <summary> /// Rolls the transaction back and retries it from the beginning. If you don't /// want the transaction to repeat, throw and catch an exception yourself. /// </summary> public static void Rollback() { AssertInTransaction(); if (_context.CommitCheckDone) throw new InvalidOperationException("Rollback not allowed for checked transactions."); _rollback.Value = true; throw new TransException("Requested rollback and retry."); } [ThreadStatic] private static bool _readOld; /// <summary> /// Indicates whether we're inside a <see cref="ReadOldState"/> lambda right now. Outside of transactions /// just returns false. /// </summary> public static bool ReadingOldState { get { return _readOld; } } /// <summary> /// Executes the delegate in a context where every read returns the value as /// it was at transaction opening. Writes still work! <see cref="Shielded&lt;T&gt;.Modify"/> /// ignores this and will expose the last written value. <see cref="ShieldedLocal{T}"/> /// ignores this. /// </summary> public static void ReadOldState(Action act) { if (_readOld) { act(); return; } AssertInTransaction(); try { _readOld = true; act(); } finally { _readOld = false; } } /// <summary> /// Executes the delegate in a context where every read returns the value as /// it was at transaction opening. Writes still work, even though their /// effects cannot be seen in this context. And please note that /// <see cref="Shielded&lt;T&gt;.Modify"/> will not be affected and will expose /// the last written value. /// </summary> public static T ReadOldState<T>(Func<T> act) { T retVal = default(T); Shield.ReadOldState(() => { retVal = act(); }); return retVal; } /// <summary> /// Runs the action, and returns a set of IShieldeds that the action enlisted. /// It will make sure to restore original enlisted items, merged with the ones /// that the action enlisted, before returning. This is important to make sure /// all thread-local state is cleared on transaction exit. The isolated action /// may still cause outer transaction's commutes to degenerate. /// </summary> internal static SimpleHashSet IsolatedRun(Action act) { var isolated = new SimpleHashSet(); var originalItems = _context.Items.Enlisted; var oldEnforce = _enforceTracking; var oldBlock = _blockCommute; try { Shield._context.Items.Enlisted = isolated; Shield._blockCommute = true; Shield._enforceTracking = true; act(); } finally { originalItems.UnionWith(isolated); Shield._context.Items.Enlisted = originalItems; Shield._blockCommute = oldBlock; Shield._enforceTracking = oldEnforce; } return isolated; } #region Commit & rollback /// <summary> /// Executes the commutes, returning through the out param the set of items that the /// commutes had accessed. /// Increases the current start stamp, and leaves the commuted items unmerged with the /// main transaction items! /// </summary> static void RunCommutes(out TransItems commutedItems) { var ctx = _context; var oldItems = ctx.Items; var commutes = oldItems.Commutes; Shield._blockCommute = true; try { while (true) { ctx.ReadTicket = VersionList.GetUntrackedReadStamp(); ctx.Items = commutedItems = new TransItems(); try { commutes.ForEach(comm => comm.Perform()); return; } catch (TransException) { commutedItems.Enlisted.Rollback(); commutedItems = null; } } } finally { ctx.Items = oldItems; Shield._blockCommute = false; } } private static bool HasChanges(IShielded item) { return item.HasChanges; } private static readonly object _checkLock = new object(); /// <summary> /// Performs the commit check, returning the outcome. Prepares the write ticket in the context. /// The ticket is obtained before leaving the lock here, so that any thread which /// later conflicts with us will surely (in its retry) read the version we are now /// writing. The idea is to avoid senseless repetitions, retries after which a /// thread would again read old data and be doomed to fail again. /// It is critical that this ticket be marked when complete (i.e. Changes set to /// something non-null), because trimming will not go past it until this happens. /// </summary> static bool CommitCheck() { var ctx = _context; var items = ctx.Items; if (!items.HasChanges) return true; TransItems commutedItems = null; var oldReadTicket = ctx.ReadTicket; bool commit = false; bool brokeInCommutes = items.Commutes != null && items.Commutes.Count > 0; if (CommitSubscriptionContext.PreCommit.Count > 0) { // if any commute would trigger a pre-commit check, this check could, if executed // in the commute sub-transaction, see newer values in fields which // were read (but not written to) by the main transaction. commutes are normally // very isolated to prevent this, but pre-commits we cannot isolate. // so, commutes trigger them now, and they cause the commutes to degenerate. CommitSubscriptionContext.PreCommit .Trigger(brokeInCommutes ? items.Enlisted.Where(HasChanges).Concat( items.Commutes.SelectMany(c => c.Affecting)) : items.Enlisted.Where(HasChanges)) .Run(); // in case a new commute sub was made brokeInCommutes = items.Commutes != null && items.Commutes.Count > 0; } try { repeatCommutes: if (brokeInCommutes) { RunCommutes(out commutedItems); #if DEBUG if (items.Enlisted.Overlaps(commutedItems.Enlisted)) throw new InvalidOperationException("Invalid commute - conflict with transaction."); #endif } var writeStamp = ctx.WriteStamp = new WriteStamp(ctx); lock (_checkLock) { try { if (brokeInCommutes) if (!commutedItems.Enlisted.CanCommit(writeStamp)) goto repeatCommutes; ctx.ReadTicket = oldReadTicket; brokeInCommutes = false; if (!items.Enlisted.CanCommit(writeStamp)) return false; commit = true; } finally { if (!commit) { if (commutedItems != null) commutedItems.Enlisted.Rollback(); if (!brokeInCommutes) items.Enlisted.Rollback(); } else VersionList.NewVersion(writeStamp, out ctx.WriteTicket); } } return true; } finally { ctx.ReadTicket = oldReadTicket; ctx.CommitCheckDone = true; // note that this changes the _localItems.Enlisted hashset to contain the // commute-enlists as well, regardless of the check outcome. if (commutedItems != null) items.UnionWith(commutedItems); } } private class TransactionContextInternal : TransactionContext { public ReadTicket ReadTicket; public WriteTicket WriteTicket; public WriteStamp WriteStamp; public TransItems Items = new TransItems(); public bool CommitCheckDone; public void Open() { VersionList.GetReaderTicket(out ReadTicket); } public override TransactionField[] Fields { get { if (Completed) throw new ContinuationCompletedException(); if (_fields == null) InContext(() => _fields = Items.GetFields()); return _fields; } } private TransactionField[] _fields; public override bool TryInContext(Action act) { return Sync(act); } private static readonly IShielded[] EmptyChanges = new IShielded[0]; private void Complete(bool committed) { try { } finally { if (WriteTicket != null && WriteTicket.Changes == null) WriteTicket.Changes = EmptyChanges; if (ReadTicket != null) VersionList.ReleaseReaderTicket(ref ReadTicket); if (WriteStamp != null && WriteStamp.Locked) WriteStamp.Release(); Committed = committed; Completed = true; Shield._context = null; } } private object _lock; internal override void StartTimer(int ms) { _lock = new object(); base.StartTimer(ms); } private bool Sync(Action act) { if (Completed) return false; var oldContext = Shield._context; try { Shield._context = this; lock (_lock) { if (Completed) return false; act(); return true; } } finally { Shield._context = oldContext; } } public override bool TryCommit() { if (Shield._context != null) throw new InvalidOperationException("Operation not allowed in a transaction."); return Sync(() => { using (this) try { DoCommit(); } finally { if (Shield._context != null) DoRollback(); } }); } public void DoCommit() { Items.SyncFx.SafeRun(); if (Items.HasChanges) { CommittingSubscription.Fire(Items); CommitWChanges(); } else CommitWoChanges(); VersionList.TrimCopies(); } private void CommitWoChanges() { Items.Enlisted.CommitWoChanges(); Complete(true); if (Items.Fx != null) Items.Fx.Select(f => f.OnCommit).SafeRun(); } private void CommitWChanges() { List<IShielded> trigger; // this must not be interrupted by a Thread.Abort! try { } finally { trigger = Items.Enlisted.Commit(); WriteTicket.Changes = trigger; } Complete(true); (Items.Fx != null ? Items.Fx.Select(f => f.OnCommit) : null) .SafeConcat(CommitSubscriptionContext.PostCommit.Trigger(trigger)) .SafeRun(); } public override bool TryRollback() { if (Shield._context != null) throw new InvalidOperationException("Operation not allowed in a transaction."); return Sync(() => { using (this) try { } finally { DoRollback(); } }); } public void DoRollback() { Items.Enlisted.Rollback(); DoCheckFailed(); } public void DoCheckFailed() { Complete(false); if (Items.Fx != null) Items.Fx.Select(f => f.OnRollback).SafeRun(); } } private static IEnumerable<T> SafeConcat<T>(this IEnumerable<T> first, IEnumerable<T> second) { if (first != null && second != null) return first.Concat(second); else if (first != null) return first; else return second; } #endregion } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public sealed class ObjectPool : MonoBehaviour { public enum StartupPoolMode { Awake, Start, CallManually }; [System.Serializable] public class StartupPool { public int size; public GameObject prefab; } static ObjectPool _instance; static List<GameObject> tempList = new List<GameObject>(); Dictionary<GameObject, List<GameObject>> pooledObjects = new Dictionary<GameObject, List<GameObject>>(); Dictionary<GameObject, GameObject> spawnedObjects = new Dictionary<GameObject, GameObject>(); public StartupPoolMode startupPoolMode; public StartupPool[] startupPools; bool startupPoolsCreated; void Awake() { _instance = this; if (startupPoolMode == StartupPoolMode.Awake) CreateStartupPools(); } void Start() { if (startupPoolMode == StartupPoolMode.Start) CreateStartupPools(); } public static void CreateStartupPools() { if (!instance.startupPoolsCreated) { instance.startupPoolsCreated = true; var pools = instance.startupPools; if (pools != null && pools.Length > 0) for (int i = 0; i < pools.Length; ++i) CreatePool(pools[i].prefab, pools[i].size); } } public static void CreatePool<T>(T prefab, int initialPoolSize) where T : Component { CreatePool(prefab.gameObject, initialPoolSize); } public static void CreatePool(GameObject prefab, int initialPoolSize) { if (prefab != null && !instance.pooledObjects.ContainsKey(prefab)) { var list = new List<GameObject>(); instance.pooledObjects.Add(prefab, list); if (initialPoolSize > 0) { bool active = prefab.activeSelf; prefab.SetActive(false); Transform parent = instance.transform; while (list.Count < initialPoolSize) { var obj = (GameObject)Object.Instantiate(prefab); obj.transform.parent = parent; list.Add(obj); } prefab.SetActive(active); } } } public static T Spawn<T>(T prefab, Transform parent, Vector3 position, Quaternion rotation) where T : Component { return Spawn(prefab.gameObject, parent, position, rotation).GetComponent<T>(); } public static T Spawn<T>(T prefab, Vector3 position, Quaternion rotation) where T : Component { return Spawn(prefab.gameObject, null, position, rotation).GetComponent<T>(); } public static T Spawn<T>(T prefab, Transform parent, Vector3 position) where T : Component { return Spawn(prefab.gameObject, parent, position, Quaternion.identity).GetComponent<T>(); } public static T Spawn<T>(T prefab, Vector3 position) where T : Component { return Spawn(prefab.gameObject, null, position, Quaternion.identity).GetComponent<T>(); } public static T Spawn<T>(T prefab, Transform parent) where T : Component { return Spawn(prefab.gameObject, parent, Vector3.zero, Quaternion.identity).GetComponent<T>(); } public static T Spawn<T>(T prefab) where T : Component { return Spawn(prefab.gameObject, null, Vector3.zero, Quaternion.identity).GetComponent<T>(); } public static GameObject Spawn(GameObject prefab, Transform parent, Vector3 position, Quaternion rotation) { List<GameObject> list; Transform trans; GameObject obj; if (instance.pooledObjects.TryGetValue(prefab, out list)) { obj = null; if (list.Count > 0) { while (obj == null && list.Count > 0) { obj = list[0]; list.RemoveAt(0); } if (obj != null) { trans = obj.transform; trans.parent = parent; trans.localPosition = position; trans.localRotation = rotation; obj.SetActive(true); instance.spawnedObjects.Add(obj, prefab); return obj; } } obj = (GameObject)Object.Instantiate(prefab); trans = obj.transform; trans.parent = parent; trans.localPosition = position; trans.localRotation = rotation; instance.spawnedObjects.Add(obj, prefab); return obj; } else { obj = (GameObject)Object.Instantiate(prefab); trans = obj.GetComponent<Transform>(); trans.parent = parent; trans.localPosition = position; trans.localRotation = rotation; return obj; } } public static GameObject Spawn(GameObject prefab, Transform parent, Vector3 position) { return Spawn(prefab, parent, position, Quaternion.identity); } public static GameObject Spawn(GameObject prefab, Vector3 position, Quaternion rotation) { return Spawn(prefab, null, position, rotation); } public static GameObject Spawn(GameObject prefab, Transform parent) { return Spawn(prefab, parent, Vector3.zero, Quaternion.identity); } public static GameObject Spawn(GameObject prefab, Vector3 position) { return Spawn(prefab, null, position, Quaternion.identity); } public static GameObject Spawn(GameObject prefab) { return Spawn(prefab, null, Vector3.zero, Quaternion.identity); } public static void Recycle<T>(T obj) where T : Component { Recycle(obj.gameObject); } public static void Recycle(GameObject obj) { GameObject prefab; if (instance.spawnedObjects.TryGetValue(obj, out prefab)) Recycle(obj, prefab); else Object.Destroy(obj); } static void Recycle(GameObject obj, GameObject prefab) { instance.pooledObjects[prefab].Add(obj); instance.spawnedObjects.Remove(obj); obj.transform.parent = instance.transform; obj.SetActive(false); } public static void RecycleAll<T>(T prefab) where T : Component { RecycleAll(prefab.gameObject); } public static void RecycleAll(GameObject prefab) { foreach (var item in instance.spawnedObjects) if (item.Value == prefab) tempList.Add(item.Key); for (int i = 0; i < tempList.Count; ++i) Recycle(tempList[i]); tempList.Clear(); } public static void RecycleAll() { tempList.AddRange(instance.spawnedObjects.Keys); for (int i = 0; i < tempList.Count; ++i) Recycle(tempList[i]); tempList.Clear(); } public static bool IsSpawned(GameObject obj) { return instance.spawnedObjects.ContainsKey(obj); } public static int CountPooled<T>(T prefab) where T : Component { return CountPooled(prefab.gameObject); } public static int CountPooled(GameObject prefab) { List<GameObject> list; if (instance.pooledObjects.TryGetValue(prefab, out list)) return list.Count; return 0; } public static int CountSpawned<T>(T prefab) where T : Component { return CountSpawned(prefab.gameObject); } public static int CountSpawned(GameObject prefab) { int count = 0 ; foreach (var instancePrefab in instance.spawnedObjects.Values) if (prefab == instancePrefab) ++count; return count; } public static int CountAllPooled() { int count = 0; foreach (var list in instance.pooledObjects.Values) count += list.Count; return count; } public static List<GameObject> GetPooled(GameObject prefab, List<GameObject> list, bool appendList) { if (list == null) list = new List<GameObject>(); if (!appendList) list.Clear(); List<GameObject> pooled; if (instance.pooledObjects.TryGetValue(prefab, out pooled)) list.AddRange(pooled); return list; } public static List<T> GetPooled<T>(T prefab, List<T> list, bool appendList) where T : Component { if (list == null) list = new List<T>(); if (!appendList) list.Clear(); List<GameObject> pooled; if (instance.pooledObjects.TryGetValue(prefab.gameObject, out pooled)) for (int i = 0; i < pooled.Count; ++i) list.Add(pooled[i].GetComponent<T>()); return list; } public static List<GameObject> GetSpawned(GameObject prefab, List<GameObject> list, bool appendList) { if (list == null) list = new List<GameObject>(); if (!appendList) list.Clear(); foreach (var item in instance.spawnedObjects) if (item.Value == prefab) list.Add(item.Key); return list; } public static List<T> GetSpawned<T>(T prefab, List<T> list, bool appendList) where T : Component { if (list == null) list = new List<T>(); if (!appendList) list.Clear(); var prefabObj = prefab.gameObject; foreach (var item in instance.spawnedObjects) if (item.Value == prefabObj) list.Add(item.Key.GetComponent<T>()); return list; } public static ObjectPool instance { get { if (_instance != null) return _instance; _instance = Object.FindObjectOfType<ObjectPool>(); if (_instance != null) return _instance; var obj = new GameObject("ObjectPool"); obj.transform.localPosition = Vector3.zero; obj.transform.localRotation = Quaternion.identity; obj.transform.localScale = Vector3.one; _instance = obj.AddComponent<ObjectPool>(); return _instance; } } } public static class ObjectPoolExtensions { public static void CreatePool<T>(this T prefab) where T : Component { ObjectPool.CreatePool(prefab, 0); } public static void CreatePool<T>(this T prefab, int initialPoolSize) where T : Component { ObjectPool.CreatePool(prefab, initialPoolSize); } public static void CreatePool(this GameObject prefab) { ObjectPool.CreatePool(prefab, 0); } public static void CreatePool(this GameObject prefab, int initialPoolSize) { ObjectPool.CreatePool(prefab, initialPoolSize); } public static T Spawn<T>(this T prefab, Transform parent, Vector3 position, Quaternion rotation) where T : Component { return ObjectPool.Spawn(prefab, parent, position, rotation); } public static T Spawn<T>(this T prefab, Vector3 position, Quaternion rotation) where T : Component { return ObjectPool.Spawn(prefab, null, position, rotation); } public static T Spawn<T>(this T prefab, Transform parent, Vector3 position) where T : Component { return ObjectPool.Spawn(prefab, parent, position, Quaternion.identity); } public static T Spawn<T>(this T prefab, Vector3 position) where T : Component { return ObjectPool.Spawn(prefab, null, position, Quaternion.identity); } public static T Spawn<T>(this T prefab, Transform parent) where T : Component { return ObjectPool.Spawn(prefab, parent, Vector3.zero, Quaternion.identity); } public static T Spawn<T>(this T prefab) where T : Component { return ObjectPool.Spawn(prefab, null, Vector3.zero, Quaternion.identity); } public static GameObject Spawn(this GameObject prefab, Transform parent, Vector3 position, Quaternion rotation) { return ObjectPool.Spawn(prefab, parent, position, rotation); } public static GameObject Spawn(this GameObject prefab, Vector3 position, Quaternion rotation) { return ObjectPool.Spawn(prefab, null, position, rotation); } public static GameObject Spawn(this GameObject prefab, Transform parent, Vector3 position) { return ObjectPool.Spawn(prefab, parent, position, Quaternion.identity); } public static GameObject Spawn(this GameObject prefab, Vector3 position) { return ObjectPool.Spawn(prefab, null, position, Quaternion.identity); } public static GameObject Spawn(this GameObject prefab, Transform parent) { return ObjectPool.Spawn(prefab, parent, Vector3.zero, Quaternion.identity); } public static GameObject Spawn(this GameObject prefab) { return ObjectPool.Spawn(prefab, null, Vector3.zero, Quaternion.identity); } public static void Recycle<T>(this T obj) where T : Component { ObjectPool.Recycle(obj); } public static void Recycle(this GameObject obj) { ObjectPool.Recycle(obj); } public static void RecycleAll<T>(this T prefab) where T : Component { ObjectPool.RecycleAll(prefab); } public static void RecycleAll(this GameObject prefab) { ObjectPool.RecycleAll(prefab); } public static int CountPooled<T>(this T prefab) where T : Component { return ObjectPool.CountPooled(prefab); } public static int CountPooled(this GameObject prefab) { return ObjectPool.CountPooled(prefab); } public static int CountSpawned<T>(this T prefab) where T : Component { return ObjectPool.CountSpawned(prefab); } public static int CountSpawned(this GameObject prefab) { return ObjectPool.CountSpawned(prefab); } public static List<GameObject> GetSpawned(this GameObject prefab, List<GameObject> list, bool appendList) { return ObjectPool.GetSpawned(prefab, list, appendList); } public static List<GameObject> GetSpawned(this GameObject prefab, List<GameObject> list) { return ObjectPool.GetSpawned(prefab, list, false); } public static List<GameObject> GetSpawned(this GameObject prefab) { return ObjectPool.GetSpawned(prefab, null, false); } public static List<T> GetSpawned<T>(this T prefab, List<T> list, bool appendList) where T : Component { return ObjectPool.GetSpawned(prefab, list, appendList); } public static List<T> GetSpawned<T>(this T prefab, List<T> list) where T : Component { return ObjectPool.GetSpawned(prefab, list, false); } public static List<T> GetSpawned<T>(this T prefab) where T : Component { return ObjectPool.GetSpawned(prefab, null, false); } public static List<GameObject> GetPooled(this GameObject prefab, List<GameObject> list, bool appendList) { return ObjectPool.GetPooled(prefab, list, appendList); } public static List<GameObject> GetPooled(this GameObject prefab, List<GameObject> list) { return ObjectPool.GetPooled(prefab, list, false); } public static List<GameObject> GetPooled(this GameObject prefab) { return ObjectPool.GetPooled(prefab, null, false); } public static List<T> GetPooled<T>(this T prefab, List<T> list, bool appendList) where T : Component { return ObjectPool.GetPooled(prefab, list, appendList); } public static List<T> GetPooled<T>(this T prefab, List<T> list) where T : Component { return ObjectPool.GetPooled(prefab, list, false); } public static List<T> GetPooled<T>(this T prefab) where T : Component { return ObjectPool.GetPooled(prefab, null, false); } }
// 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.Azure.AcceptanceTestsSubscriptionIdApiVersion { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; 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> /// Some cool documentation. /// </summary> public partial class MicrosoftAzureTestUrl : ServiceClient<MicrosoftAzureTestUrl>, IMicrosoftAzureTestUrl, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Subscription Id. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// API Version with value '2014-04-01-preview'. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IGroupOperations. /// </summary> public virtual IGroupOperations Group { get; private set; } /// <summary> /// Initializes a new instance of the MicrosoftAzureTestUrl class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected MicrosoftAzureTestUrl(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the MicrosoftAzureTestUrl class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected MicrosoftAzureTestUrl(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the MicrosoftAzureTestUrl class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected MicrosoftAzureTestUrl(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the MicrosoftAzureTestUrl class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected MicrosoftAzureTestUrl(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the MicrosoftAzureTestUrl class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public MicrosoftAzureTestUrl(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the MicrosoftAzureTestUrl class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public MicrosoftAzureTestUrl(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the MicrosoftAzureTestUrl class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public MicrosoftAzureTestUrl(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the MicrosoftAzureTestUrl class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public MicrosoftAzureTestUrl(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.Group = new GroupOperations(this); this.BaseUri = new Uri("https://management.azure.com/"); this.ApiVersion = "2014-04-01-preview"; this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
/* * SonarLint for Visual Studio * Copyright (C) 2016-2021 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ using System; using EnvDTE; using EnvDTE80; namespace SonarLint.VisualStudio.Integration.UnitTests { public class DTEMock : DTE, DTE2 { public DTEMock() { this.ToolWindows = new ToolWindowsMock(this); this.Commands = new CommandsMock(this); } public string Version { get; set; } #region DTE Document _DTE.ActiveDocument { get { throw new NotImplementedException(); } } object _DTE.ActiveSolutionProjects { get { return this.ActiveSolutionProjects; } } Window _DTE.ActiveWindow { get { throw new NotImplementedException(); } } AddIns _DTE.AddIns { get { throw new NotImplementedException(); } } DTE _DTE.Application { get { throw new NotImplementedException(); } } object _DTE.CommandBars { get { throw new NotImplementedException(); } } string _DTE.CommandLineArguments { get { throw new NotImplementedException(); } } Commands _DTE.Commands { get { return this.Commands; } } ContextAttributes _DTE.ContextAttributes { get { throw new NotImplementedException(); } } Debugger _DTE.Debugger { get { throw new NotImplementedException(); } } vsDisplay _DTE.DisplayMode { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } Documents _DTE.Documents { get { throw new NotImplementedException(); } } DTE _DTE.DTE { get { throw new NotImplementedException(); } } string _DTE.Edition { get { throw new NotImplementedException(); } } Events _DTE.Events { get { throw new NotImplementedException(); } } string _DTE.FileName { get { throw new NotImplementedException(); } } Find _DTE.Find { get { throw new NotImplementedException(); } } string _DTE.FullName { get { throw new NotImplementedException(); } } Globals _DTE.Globals { get { throw new NotImplementedException(); } } ItemOperations _DTE.ItemOperations { get { throw new NotImplementedException(); } } int _DTE.LocaleID { get { throw new NotImplementedException(); } } Macros _DTE.Macros { get { throw new NotImplementedException(); } } DTE _DTE.MacrosIDE { get { throw new NotImplementedException(); } } Window _DTE.MainWindow { get { throw new NotImplementedException(); } } vsIDEMode _DTE.Mode { get { throw new NotImplementedException(); } } string _DTE.Name { get { throw new NotImplementedException(); } } ObjectExtenders _DTE.ObjectExtenders { get { throw new NotImplementedException(); } } string _DTE.RegistryRoot { get { throw new NotImplementedException(); } } SelectedItems _DTE.SelectedItems { get { throw new NotImplementedException(); } } Solution _DTE.Solution { get { return this.Solution; } } SourceControl _DTE.SourceControl { get { throw new NotImplementedException(); } } StatusBar _DTE.StatusBar { get { throw new NotImplementedException(); } } bool _DTE.SuppressUI { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } UndoContext _DTE.UndoContext { get { throw new NotImplementedException(); } } bool _DTE.UserControl { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } string _DTE.Version { get { return Version; } } WindowConfigurations _DTE.WindowConfigurations { get { throw new NotImplementedException(); } } EnvDTE.Windows _DTE.Windows { get { throw new NotImplementedException(); } } void _DTE.ExecuteCommand(string CommandName, string CommandArgs) { throw new NotImplementedException(); } object _DTE.GetObject(string Name) { throw new NotImplementedException(); } bool _DTE.get_IsOpenFile(string ViewKind, string FileName) { throw new NotImplementedException(); } Properties _DTE.get_Properties(string Category, string Page) { throw new NotImplementedException(); } wizardResult _DTE.LaunchWizard(string VSZFile, ref object[] ContextParams) { throw new NotImplementedException(); } Window _DTE.OpenFile(string ViewKind, string FileName) { throw new NotImplementedException(); } void _DTE.Quit() { throw new NotImplementedException(); } string _DTE.SatelliteDllPath(string Path, string Name) { throw new NotImplementedException(); } void DTE2.Quit() { throw new NotImplementedException(); } object DTE2.GetObject(string Name) { throw new NotImplementedException(); } Window DTE2.OpenFile(string ViewKind, string FileName) { throw new NotImplementedException(); } void DTE2.ExecuteCommand(string CommandName, string CommandArgs) { throw new NotImplementedException(); } wizardResult DTE2.LaunchWizard(string VSZFile, ref object[] ContextParams) { throw new NotImplementedException(); } string DTE2.SatelliteDllPath(string Path, string Name) { throw new NotImplementedException(); } uint DTE2.GetThemeColor(vsThemeColors Element) { throw new NotImplementedException(); } Properties DTE2.get_Properties(string Category, string Page) { throw new NotImplementedException(); } bool DTE2.get_IsOpenFile(string ViewKind, string FileName) { throw new NotImplementedException(); } #endregion DTE #region DTE2 string DTE2.Name { get { return ((DTE)this).Name; } } string DTE2.FileName { get { return ((DTE)this).FileName; } } string DTE2.Version { get { return ((DTE)this).Version; } } object DTE2.CommandBars { get { return ((DTE)this).CommandBars; } } EnvDTE.Windows DTE2.Windows { get { return ((DTE)this).Windows; } } Events DTE2.Events { get { return ((DTE)this).Events; } } AddIns DTE2.AddIns { get { return ((DTE)this).AddIns; } } Window DTE2.MainWindow { get { return ((DTE)this).MainWindow; } } Window DTE2.ActiveWindow { get { return ((DTE)this).ActiveWindow; } } vsDisplay DTE2.DisplayMode { get { return ((DTE)this).DisplayMode; } set { ((DTE)this).DisplayMode = value; } } Solution DTE2.Solution { get { return ((DTE)this).Solution; } } Commands DTE2.Commands { get { return ((DTE)this).Commands; } } SelectedItems DTE2.SelectedItems { get { return ((DTE)this).SelectedItems; } } string DTE2.CommandLineArguments { get { return ((DTE)this).CommandLineArguments; } } DTE DTE2.DTE { get { return this; } } int DTE2.LocaleID { get { return ((DTE)this).LocaleID; } } WindowConfigurations DTE2.WindowConfigurations { get { return ((DTE)this).WindowConfigurations; } } Documents DTE2.Documents { get { return ((DTE)this).Documents; } } Document DTE2.ActiveDocument { get { return ((DTE)this).ActiveDocument; } } Globals DTE2.Globals { get { return ((DTE)this).Globals; } } StatusBar DTE2.StatusBar { get { return ((DTE)this).StatusBar; } } string DTE2.FullName { get { return ((DTE)this).FullName; } } bool DTE2.UserControl { get { return ((DTE)this).UserControl; } set { ((DTE)this).UserControl = value; } } ObjectExtenders DTE2.ObjectExtenders { get { return ((DTE)this).ObjectExtenders; } } Find DTE2.Find { get { return ((DTE)this).Find; } } vsIDEMode DTE2.Mode { get { return ((DTE)this).Mode; } } ItemOperations DTE2.ItemOperations { get { return ((DTE)this).ItemOperations; } } UndoContext DTE2.UndoContext { get { return ((DTE)this).UndoContext; } } Macros DTE2.Macros { get { return ((DTE)this).Macros; } } object DTE2.ActiveSolutionProjects { get { return ((DTE)this).ActiveSolutionProjects; } } DTE DTE2.MacrosIDE { get { return ((DTE)this).MacrosIDE; } } string DTE2.RegistryRoot { get { return ((DTE)this).RegistryRoot; } } DTE DTE2.Application { get { return ((DTE)this).Application; } } ContextAttributes DTE2.ContextAttributes { get { return ((DTE)this).ContextAttributes; } } SourceControl DTE2.SourceControl { get { return ((DTE)this).SourceControl; } } bool DTE2.SuppressUI { get { return ((DTE)this).SuppressUI; } set { ((DTE)this).SuppressUI = value; } } Debugger DTE2.Debugger { get { return ((DTE)this).Debugger; } } string DTE2.Edition { get { return ((DTE)this).Edition; } } ToolWindows DTE2.ToolWindows { get { return this.ToolWindows; } } #endregion DTE2 #region Test helpers public SolutionMock Solution { get; set; } public ToolWindowsMock ToolWindows { get; set; } public CommandsMock Commands { get; set; } public Project[] ActiveSolutionProjects { get; set; } = new Project[0]; #endregion Test helpers } }
// 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.Runtime.InteropServices; namespace System.Management { //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// /// <summary> /// <para> Contains information about a WMI method.</para> /// </summary> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// /// // This example shows how to obtain meta data /// // about a WMI method with a given name in a given WMI class /// /// class Sample_MethodData /// { /// public static int Main(string[] args) { /// /// // Get the "SetPowerState" method in the Win32_LogicalDisk class /// ManagementClass diskClass = new ManagementClass("win32_logicaldisk"); /// MethodData m = diskClass.Methods["SetPowerState"]; /// /// // Get method name (albeit we already know it) /// Console.WriteLine("Name: " + m.Name); /// /// // Get the name of the top-most class where this specific method was defined /// Console.WriteLine("Origin: " + m.Origin); /// /// // List names and types of input parameters /// ManagementBaseObject inParams = m.InParameters; /// foreach(PropertyData pdata in inParams.Properties) { /// Console.WriteLine(); /// Console.WriteLine("InParam_Name: " + pdata.Name); /// Console.WriteLine("InParam_Type: " + pdata.Type); /// } /// /// // List names and types of output parameters /// ManagementBaseObject outParams = m.OutParameters; /// foreach(PropertyData pdata in outParams.Properties) { /// Console.WriteLine(); /// Console.WriteLine("OutParam_Name: " + pdata.Name); /// Console.WriteLine("OutParam_Type: " + pdata.Type); /// } /// /// return 0; /// } /// } /// </code> /// <code lang='VB'>Imports System /// Imports System.Management /// /// ' This example shows how to obtain meta data /// ' about a WMI method with a given name in a given WMI class /// /// Class Sample_ManagementClass /// Overloads Public Shared Function Main(args() As String) As Integer /// /// ' Get the "SetPowerState" method in the Win32_LogicalDisk class /// Dim diskClass As New ManagementClass("Win32_LogicalDisk") /// Dim m As MethodData = diskClass.Methods("SetPowerState") /// /// ' Get method name (albeit we already know it) /// Console.WriteLine("Name: " &amp; m.Name) /// /// ' Get the name of the top-most class where /// ' this specific method was defined /// Console.WriteLine("Origin: " &amp; m.Origin) /// /// ' List names and types of input parameters /// Dim inParams As ManagementBaseObject /// inParams = m.InParameters /// Dim pdata As PropertyData /// For Each pdata In inParams.Properties /// Console.WriteLine() /// Console.WriteLine("InParam_Name: " &amp; pdata.Name) /// Console.WriteLine("InParam_Type: " &amp; pdata.Type) /// Next pdata /// /// ' List names and types of output parameters /// Dim outParams As ManagementBaseObject /// outParams = m.OutParameters /// For Each pdata in outParams.Properties /// Console.WriteLine() /// Console.WriteLine("OutParam_Name: " &amp; pdata.Name) /// Console.WriteLine("OutParam_Type: " &amp; pdata.Type) /// Next pdata /// /// Return 0 /// End Function /// End Class /// </code> /// </example> //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// public class MethodData { private ManagementObject parent; //needed to be able to get method qualifiers private string methodName; private IWbemClassObjectFreeThreaded wmiInParams; private IWbemClassObjectFreeThreaded wmiOutParams; private QualifierDataCollection qualifiers; internal MethodData(ManagementObject parent, string methodName) { this.parent = parent; this.methodName = methodName; RefreshMethodInfo(); qualifiers = null; } //This private function is used to refresh the information from the Wmi object before returning the requested data private void RefreshMethodInfo() { int status = (int)ManagementStatus.Failed; try { status = parent.wbemObject.GetMethod_(methodName, 0, out wmiInParams, out wmiOutParams); } catch (COMException e) { ManagementException.ThrowWithExtendedInfo(e); } if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else if ((status & 0x80000000) != 0) { Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } /// <summary> /// <para>Gets or sets the name of the method.</para> /// </summary> /// <value> /// <para>The name of the method.</para> /// </value> public string Name { get { return methodName != null ? methodName : ""; } } /// <summary> /// <para> Gets or sets the input parameters to the method. Each /// parameter is described as a property in the object. If a parameter is both in /// and out, it appears in both the <see cref='System.Management.MethodData.InParameters'/> and <see cref='System.Management.MethodData.OutParameters'/> /// properties.</para> /// </summary> /// <value> /// <para> /// A <see cref='System.Management.ManagementBaseObject'/> /// containing all the input parameters to the /// method.</para> /// </value> /// <remarks> /// <para>Each parameter in the object should have an /// <see langword='ID'/> /// qualifier, identifying the order of the parameters in the method call.</para> /// </remarks> public ManagementBaseObject InParameters { get { RefreshMethodInfo(); return (null == wmiInParams) ? null : new ManagementBaseObject(wmiInParams); } } /// <summary> /// <para> Gets or sets the output parameters to the method. Each /// parameter is described as a property in the object. If a parameter is both in /// and out, it will appear in both the <see cref='System.Management.MethodData.InParameters'/> and <see cref='System.Management.MethodData.OutParameters'/> /// properties.</para> /// </summary> /// <value> /// <para>A <see cref='System.Management.ManagementBaseObject'/> containing all the output parameters to the method. </para> /// </value> /// <remarks> /// <para>Each parameter in this object should have an /// <see langword='ID'/> qualifier to identify the /// order of the parameters in the method call.</para> /// <para>The ReturnValue property is a special property of /// the <see cref='System.Management.MethodData.OutParameters'/> /// object and /// holds the return value of the method.</para> /// </remarks> public ManagementBaseObject OutParameters { get { RefreshMethodInfo(); return (null == wmiOutParams) ? null : new ManagementBaseObject(wmiOutParams); } } /// <summary> /// <para>Gets the name of the management class in which the method was first /// introduced in the class inheritance hierarchy.</para> /// </summary> /// <value> /// A string representing the originating /// management class name. /// </value> public string Origin { get { string className = null; int status = parent.wbemObject.GetMethodOrigin_(methodName, out className); if (status < 0) { if (status == (int)tag_WBEMSTATUS.WBEM_E_INVALID_OBJECT) className = String.Empty; // Interpret as an unspecified property - return "" else if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } return className; } } /// <summary> /// <para>Gets a collection of qualifiers defined in the /// method. Each element is of type <see cref='System.Management.QualifierData'/> /// and contains information such as the qualifier name, value, and /// flavor.</para> /// </summary> /// <value> /// A <see cref='System.Management.QualifierDataCollection'/> containing the /// qualifiers for this method. /// </value> /// <seealso cref='System.Management.QualifierData'/> public QualifierDataCollection Qualifiers { get { if (qualifiers == null) qualifiers = new QualifierDataCollection(parent, methodName, QualifierType.MethodQualifier); return qualifiers; } } }//MethodData }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Contoso.Apps.PaymentGateway.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// // Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets.Wrappers { using System; using System.Collections.Generic; using System.Threading; using NLog.Common; using NLog.Targets; using NLog.Targets.Wrappers; using Xunit; public class RoundRobinGroupTargetTests : NLogTestBase { [Fact] public void RoundRobinGroupTargetSyncTest1() { var myTarget1 = new MyTarget(); var myTarget2 = new MyTarget(); var myTarget3 = new MyTarget(); var wrapper = new RoundRobinGroupTarget() { Targets = { myTarget1, myTarget2, myTarget3 }, }; myTarget1.Initialize(null); myTarget2.Initialize(null); myTarget3.Initialize(null); wrapper.Initialize(null); List<Exception> exceptions = new List<Exception>(); // no exceptions for (int i = 0; i < 10; ++i) { wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); } Assert.Equal(10, exceptions.Count); foreach (var e in exceptions) { Assert.Null(e); } Assert.Equal(4, myTarget1.WriteCount); Assert.Equal(3, myTarget2.WriteCount); Assert.Equal(3, myTarget3.WriteCount); Exception flushException = null; var flushHit = new ManualResetEvent(false); wrapper.Flush(ex => { flushException = ex; flushHit.Set(); }); flushHit.WaitOne(); if (flushException != null) { Assert.True(false, flushException.ToString()); } Assert.Equal(1, myTarget1.FlushCount); Assert.Equal(1, myTarget2.FlushCount); Assert.Equal(1, myTarget3.FlushCount); } [Fact] public void RoundRobinGroupTargetSyncTest2() { var wrapper = new RoundRobinGroupTarget() { // empty target list }; wrapper.Initialize(null); List<Exception> exceptions = new List<Exception>(); // no exceptions for (int i = 0; i < 10; ++i) { wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); } Assert.Equal(10, exceptions.Count); foreach (var e in exceptions) { Assert.Null(e); } Exception flushException = null; var flushHit = new ManualResetEvent(false); wrapper.Flush(ex => { flushException = ex; flushHit.Set(); }); flushHit.WaitOne(); if (flushException != null) { Assert.True(false, flushException.ToString()); } } public class MyAsyncTarget : Target { public int FlushCount { get; private set; } public int WriteCount { get; private set; } public MyAsyncTarget() : base() { } public MyAsyncTarget(string name) : this() { Name = name; } protected override void Write(LogEventInfo logEvent) { throw new NotSupportedException(); } protected override void Write(AsyncLogEventInfo logEvent) { Assert.True(FlushCount <= WriteCount); WriteCount++; ThreadPool.QueueUserWorkItem( s => { if (ThrowExceptions) { logEvent.Continuation(new InvalidOperationException("Some problem!")); logEvent.Continuation(new InvalidOperationException("Some problem!")); } else { logEvent.Continuation(null); logEvent.Continuation(null); } }); } protected override void FlushAsync(AsyncContinuation asyncContinuation) { FlushCount++; ThreadPool.QueueUserWorkItem( s => asyncContinuation(null)); } public bool ThrowExceptions { get; set; } } class MyTarget : Target { public int FlushCount { get; set; } public int WriteCount { get; set; } public int FailCounter { get; set; } public MyTarget() : base() { } public MyTarget(string name) : this() { Name = name; } protected override void Write(LogEventInfo logEvent) { Assert.True(FlushCount <= WriteCount); WriteCount++; if (FailCounter > 0) { FailCounter--; throw new InvalidOperationException("Some failure."); } } protected override void FlushAsync(AsyncContinuation asyncContinuation) { FlushCount++; asyncContinuation(null); } } } }
//------------------------------------------------------------------------------ // <copyright file="XmlDiffPathForView.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System; using System.Xml; using System.Diagnostics; using System.Collections; namespace Microsoft.XmlDiffPatch { internal class XmlDiffPath { static char[] Delimites = new char[] {'|','-','/'}; static char[] MultiNodesDelimiters = new char[] {'|','-'}; internal static XmlDiffPathNodeList SelectNodes( XmlDiffViewParentNode rootNode, XmlDiffViewParentNode currentParentNode, string xmlDiffPathExpr ) { switch ( xmlDiffPathExpr[0] ) { case '/': return SelectAbsoluteNodes( rootNode, xmlDiffPathExpr ); case '@': if ( xmlDiffPathExpr.Length < 2 ) OnInvalidExpression( xmlDiffPathExpr ); if ( xmlDiffPathExpr[1] == '*' ) return SelectAllAttributes( (XmlDiffViewElement)currentParentNode ); else return SelectAttributes( (XmlDiffViewElement)currentParentNode, xmlDiffPathExpr ); case '*': if ( xmlDiffPathExpr.Length == 1 ) return SelectAllChildren( currentParentNode ); else { OnInvalidExpression( xmlDiffPathExpr ); return null; } default: return SelectChildNodes( currentParentNode, xmlDiffPathExpr, 0 ); } } static XmlDiffPathNodeList SelectAbsoluteNodes( XmlDiffViewParentNode rootNode, string path ) { Debug.Assert( path[0] == '/' ); int pos = 1; XmlDiffViewNode node = rootNode; for (;;) { int startPos = pos; int nodePos = ReadPosition( path, ref pos ); if ( pos == path.Length || path[pos] == '/' ) { if ( node.FirstChildNode == null ) { OnNoMatchingNode( path ); } XmlDiffViewParentNode parentNode = (XmlDiffViewParentNode) node; if ( nodePos <= 0 || nodePos > parentNode._sourceChildNodesCount ) { OnNoMatchingNode( path ); } node = parentNode.GetSourceChildNode( nodePos - 1 ); if ( pos == path.Length ) { XmlDiffPathNodeList list = new XmlDiffPathSingleNodeList(); list.AddNode( node ); return list; } pos++; } else { if ( path[pos] == '-' || path[pos] == '|' ) { if ( node.FirstChildNode == null ) { OnNoMatchingNode( path ); } return SelectChildNodes( ((XmlDiffViewParentNode)node), path, startPos ); } OnInvalidExpression( path ); } } } static XmlDiffPathNodeList SelectAllAttributes( XmlDiffViewElement parentElement ) { if ( parentElement._attributes == null ) { OnNoMatchingNode( "@*" ); return null; } else if ( parentElement._attributes._nextSibbling == null ) { XmlDiffPathNodeList nodeList = new XmlDiffPathSingleNodeList(); nodeList.AddNode( parentElement._attributes ); return nodeList; } else { XmlDiffPathNodeList nodeList = new XmlDiffPathMultiNodeList(); XmlDiffViewAttribute curAttr = parentElement._attributes; while ( curAttr != null ) nodeList.AddNode( curAttr ); return nodeList; } } static XmlDiffPathNodeList SelectAttributes( XmlDiffViewElement parentElement, string path ) { Debug.Assert( path[0] == '@' ); int pos = 1; XmlDiffPathNodeList nodeList = null; for (;;) { string name = ReadAttrName( path, ref pos ); if ( nodeList == null ) { if ( pos == path.Length ) nodeList = new XmlDiffPathSingleNodeList(); else nodeList = new XmlDiffPathMultiNodeList(); } XmlDiffViewAttribute attr = parentElement.GetAttribute( name ); if ( attr == null ) OnNoMatchingNode( path ); nodeList.AddNode( attr ); if ( pos == path.Length ) break; else if ( path[pos] == '|' ) { pos++; if ( path[pos] != '@' ) OnInvalidExpression( path ); pos++; } else OnInvalidExpression( path ); } return nodeList; } static XmlDiffPathNodeList SelectAllChildren( XmlDiffViewParentNode parentNode ) { if ( parentNode._childNodes == null ) { OnNoMatchingNode( "*" ); return null; } else if ( parentNode._childNodes._nextSibbling == null ) { XmlDiffPathNodeList nodeList = new XmlDiffPathSingleNodeList(); nodeList.AddNode( parentNode._childNodes ); return nodeList; } else { XmlDiffPathNodeList nodeList = new XmlDiffPathMultiNodeList(); XmlDiffViewNode childNode = parentNode._childNodes; while ( childNode != null ) { nodeList.AddNode( childNode ); childNode = childNode._nextSibbling; } return nodeList; } } static XmlDiffPathNodeList SelectChildNodes( XmlDiffViewParentNode parentNode, string path, int startPos ) { int pos = startPos; XmlDiffPathNodeList nodeList = null; for (;;) { int nodePos = ReadPosition( path, ref pos ); if ( pos == path.Length ) nodeList = new XmlDiffPathSingleNodeList(); else nodeList = new XmlDiffPathMultiNodeList(); if ( nodePos <= 0 || nodePos > parentNode._sourceChildNodesCount ) OnNoMatchingNode( path ); nodeList.AddNode( parentNode.GetSourceChildNode( nodePos-1 ) ); if ( pos == path.Length ) break; else if ( path[pos] == '|' ) pos++; else if ( path[pos] == '-' ) { pos++; int endNodePos = ReadPosition( path, ref pos ); if ( endNodePos <= 0 || endNodePos > parentNode._sourceChildNodesCount ) OnNoMatchingNode( path ); while ( nodePos < endNodePos ) { nodePos++; nodeList.AddNode( parentNode.GetSourceChildNode( nodePos-1 ) ); } if ( pos == path.Length ) break; else if ( path[pos] == '|' ) pos++; else OnInvalidExpression( path ); } } return nodeList; } static int ReadPosition( string str, ref int pos ) { int end = str.IndexOfAny( Delimites, pos ); if ( end < 0 ) end = str.Length; // TODO: better error handling if this should be shipped int nodePos = int.Parse( str.Substring( pos, end - pos ) ); pos = end; return nodePos; } static string ReadAttrName( string str, ref int pos ) { int end = str.IndexOf( '|', pos ); if ( end < 0 ) end = str.Length; // TODO: better error handling if this should be shipped string name = str.Substring( pos, end - pos ); pos = end; return name; } static void OnInvalidExpression( string path ) { throw new Exception( "Invalid XmlDiffPath expression: " + path ); } static void OnNoMatchingNode( string path ) { throw new Exception( "No matching node:" + path ); } } ////////////////////////////////////////////////////////////////// // XmlDiffPathNodeList // internal abstract class XmlDiffPathNodeList { internal abstract void AddNode( XmlDiffViewNode node ); internal abstract void Reset(); internal abstract XmlDiffViewNode Current { get; } internal abstract bool MoveNext(); internal abstract int Count { get; } } ////////////////////////////////////////////////////////////////// // XmlDiffPathNodeList // internal class XmlDiffPathMultiNodeList : XmlDiffPathNodeList { internal class ListChunk { internal const int ChunkSize = 10; internal XmlDiffViewNode[] _nodes = new XmlDiffViewNode[ ChunkSize ]; internal int _count = 0; internal ListChunk _next = null; internal XmlDiffViewNode this[int i] { get { return _nodes[i]; } } internal void AddNode( XmlDiffViewNode node ) { Debug.Assert( _count < ChunkSize ); _nodes[ _count++ ] = node; } } // Fields int _count = 0; ListChunk _chunks = null; ListChunk _lastChunk = null; ListChunk _currentChunk = null; int _currentChunkIndex = -1; // Constructor internal XmlDiffPathMultiNodeList() { } internal override XmlDiffViewNode Current { get { if ( _currentChunk == null || _currentChunkIndex < 0) return null; else return _currentChunk[ _currentChunkIndex ]; } } internal override int Count { get { return _count; } } // Methods internal override bool MoveNext() { if ( _currentChunk == null ) return false; if ( _currentChunkIndex >= _currentChunk._count - 1 ) { if ( _currentChunk._next == null ) return false; else { _currentChunk = _currentChunk._next; _currentChunkIndex = 0; Debug.Assert( _currentChunk._count > 0 ); return true; } } else { _currentChunkIndex++; return true; } } internal override void Reset() { _currentChunk = _chunks; _currentChunkIndex = -1; } internal override void AddNode( XmlDiffViewNode node ) { if ( _lastChunk == null ) { _chunks = new ListChunk(); _lastChunk = _chunks; _currentChunk = _chunks; } else if ( _lastChunk._count == ListChunk.ChunkSize ) { _lastChunk._next = new ListChunk(); _lastChunk = _lastChunk._next; } _lastChunk.AddNode( node ); _count++; } } ////////////////////////////////////////////////////////////////// // XmlDiffPathSingleNodeList // internal class XmlDiffPathSingleNodeList : XmlDiffPathNodeList { enum State { BeforeNode = 0, OnNode = 1, AfterNode = 2 } XmlDiffViewNode _node; State _state = State.BeforeNode; internal XmlDiffPathSingleNodeList () { } internal override int Count { get { return 1; } } internal override XmlDiffViewNode Current { get { return ( _state == State.OnNode ) ? _node : null; } } internal override bool MoveNext() { switch ( _state ) { case State.BeforeNode: _state = State.OnNode; return true; case State.OnNode: _state = State.AfterNode; return false; case State.AfterNode: return false; default: return false; } } internal override void Reset() { _state = State.BeforeNode; } internal override void AddNode( XmlDiffViewNode node ) { if ( _node != null ) throw new Exception( "XmlDiffPathSingleNodeList can contain one node only." ); _node = node; } } }
#region Licence... /* The MIT License (MIT) Copyright (c) 2014 Oleg Shilo 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 Licence... namespace WixSharp { /// <summary> /// Defines WiX InstalledFileAction for executing installed file. /// </summary> /// /// <example>The following is an example of using <c>InstalledFileAction</c> to run /// installed executable <c>Registrator.exe</c> with different arguments depending /// in installation type (install/uninstall): /// <code> /// var project = /// new Project("My Product", /// /// new Dir(@"%ProgramFiles%\My Company\My Product", /// /// new File(binaries, @"AppFiles\MyApp.exe", /// new WixSharp.Shortcut("MyApp", @"%ProgramMenu%\My Company\My Product"), /// new WixSharp.Shortcut("MyApp", @"%Desktop%")), /// /// new File(binaries, @"AppFiles\Registrator.exe"), /// /// new InstalledFileAction("Registrator.exe", "", /// Return.check, /// When.After, /// Step.InstallFinalize, /// Condition.NOT_Installed), /// /// new InstalledFileAction("Registrator.exe", "/u", /// Return.check, /// When.Before, /// Step.InstallFinalize, /// Condition.Installed), /// ... /// /// Compiler.BuildMsi(project); /// </code> /// </example> public class InstalledFileAction : Action { /// <summary> /// Initializes a new instance of the <see cref="InstalledFileAction"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="key">The key (file name) of the installed file to be executed.</param> /// <param name="args">The arguments to be passed to the file during the execution.</param> public InstalledFileAction(string key, string args) : base() { Key = key; Args = args; Name = key; Step = Step.InstallExecute; } /// <summary> /// Initializes a new instance of the <see cref="InstalledFileAction"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="key">The key (file name) of the installed file to be executed.</param> /// <param name="args">The arguments to be passed to the file during the execution.</param> /// <param name="rollback">The key (file name) of the installed file that must be executed on rollback.</param> /// <param name="rollbackArg">The arguments to be passed to the file during the execution on rollback.</param> public InstalledFileAction(string key, string args, string rollback, string rollbackArg) : base() { Key = key; Args = args; Name = key; Rollback = rollback; RollbackArg = rollbackArg; Step = Step.InstallExecute; } /// <summary> /// Initializes a new instance of the <see cref="InstalledFileAction"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="id">The explicit <see cref="Id"></see> to be associated with <see cref="InstalledFileAction"/> instance.</param> /// <param name="key">The key (file name) of the installed file to be executed.</param> /// <param name="args">The arguments to be passed to the file during the execution.</param> public InstalledFileAction(Id id, string key, string args) : base(id) { Key = key; Args = args; Name = key; Step = Step.InstallExecute; } /// <summary> /// Initializes a new instance of the <see cref="InstalledFileAction"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="id">The explicit <see cref="Id"></see> to be associated with <see cref="InstalledFileAction"/> instance.</param> /// <param name="key">The key (file name) of the installed file to be executed.</param> /// <param name="args">The arguments to be passed to the file during the execution.</param> /// <param name="rollback">The key (file name) of the installed file that must be executed on rollback.</param> /// <param name="rollbackArg">The arguments to be passed to the file during the execution on rollback.</param> public InstalledFileAction(Id id, string key, string args, string rollback, string rollbackArg) : base(id) { Key = key; Args = args; Name = key; Rollback = rollback; RollbackArg = rollbackArg; Step = Step.InstallExecute; } /// <summary> /// Initializes a new instance of the <see cref="InstalledFileAction"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="key">The key (file ID) of the installed file to be executed.</param> /// <param name="args">The arguments to be passed to the file during the execution.</param> /// <param name="returnType">The return type of the action.</param> /// <param name="when"><see cref="T:WixSharp.When"/> the action should be executed with respect to the <paramref name="step"/> parameter.</param> /// <param name="step"><see cref="T:WixSharp.Step"/> the action should be executed before/after during the installation.</param> /// <param name="condition">The launch condition for the <see cref="InstalledFileAction"/>.</param> public InstalledFileAction(string key, string args, Return returnType, When when, Step step, Condition condition) : base(returnType, when, step, condition) { Key = key; Args = args; Name = key; } /// <summary> /// Initializes a new instance of the <see cref="InstalledFileAction"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="key">The key (file name) of the installed file to be executed.</param> /// <param name="args">The arguments to be passed to the file during the execution.</param> /// <param name="returnType">The return type of the action.</param> /// <param name="when"><see cref="T:WixSharp.When"/> the action should be executed with respect to the <paramref name="step"/> parameter.</param> /// <param name="step"><see cref="T:WixSharp.Step"/> the action should be executed before/after during the installation.</param> /// <param name="condition">The launch condition for the <see cref="InstalledFileAction"/>.</param> /// <param name="rollback">The key (file name) of the installed file that must be executed on rollback.</param> /// <param name="rollbackArg">The arguments to be passed to the file during the execution on rollback.</param> public InstalledFileAction(string key, string args, Return returnType, When when, Step step, Condition condition, string rollback, string rollbackArg) : base(returnType, when, step, condition) { Key = key; Args = args; Name = key; Rollback = rollback; RollbackArg = rollbackArg; } /// <summary> /// Initializes a new instance of the <see cref="InstalledFileAction"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="id">The explicit <see cref="Id"></see> to be associated with <see cref="InstalledFileAction"/> instance.</param> /// <param name="key">The key (file name) of the installed file to be executed.</param> /// <param name="args">The arguments to be passed to the file during the execution.</param> /// <param name="returnType">The return type of the action.</param> /// <param name="when"><see cref="T:WixSharp.When"/> the action should be executed with respect to the <paramref name="step"/> parameter.</param> /// <param name="step"><see cref="T:WixSharp.Step"/> the action should be executed before/after during the installation.</param> /// <param name="condition">The launch condition for the <see cref="InstalledFileAction"/>.</param> public InstalledFileAction(Id id, string key, string args, Return returnType, When when, Step step, Condition condition) : base(id, returnType, when, step, condition) { Key = key; Args = args; Name = key; } /// <summary> /// Initializes a new instance of the <see cref="InstalledFileAction"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="id">The explicit <see cref="Id"></see> to be associated with <see cref="InstalledFileAction"/> instance.</param> /// <param name="key">The key (file name) of the installed file to be executed.</param> /// <param name="args">The arguments to be passed to the file during the execution.</param> /// <param name="returnType">The return type of the action.</param> /// <param name="when"><see cref="T:WixSharp.When"/> the action should be executed with respect to the <paramref name="step"/> parameter.</param> /// <param name="step"><see cref="T:WixSharp.Step"/> the action should be executed before/after during the installation.</param> /// <param name="condition">The launch condition for the <see cref="InstalledFileAction"/>.</param> /// <param name="rollback">The key (file name) of the installed file that must be executed on rollback.</param> /// <param name="rollbackArg">The arguments to be passed to the file during the execution on rollback.</param> public InstalledFileAction(Id id, string key, string args, Return returnType, When when, Step step, Condition condition, string rollback, string rollbackArg) : base(id, returnType, when, step, condition) { Key = key; Args = args; Name = key; Rollback = rollback; RollbackArg = rollbackArg; } /// <summary> /// Initializes a new instance of the <see cref="InstalledFileAction"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="key">The key (file name) of the installed file to be executed.</param> /// <param name="args">The arguments to be passed to the file during the execution.</param> /// <param name="returnType">The return type of the action.</param> /// <param name="when"><see cref="T:WixSharp.When"/> the action should be executed with respect to the <paramref name="step"/> parameter.</param> /// <param name="step"><see cref="T:WixSharp.Step"/> the action should be executed before/after during the installation.</param> /// <param name="condition">The launch condition for the <see cref="InstalledFileAction"/>.</param> /// <param name="sequence">The MSI sequence the action belongs to.</param> public InstalledFileAction(string key, string args, Return returnType, When when, Step step, Condition condition, Sequence sequence) : base(returnType, when, step, condition, sequence) { Key = key; Args = args; Name = key; } /// <summary> /// Initializes a new instance of the <see cref="InstalledFileAction"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="key">The key (file name) of the installed file to be executed.</param> /// <param name="args">The arguments to be passed to the file during the execution.</param> /// <param name="returnType">The return type of the action.</param> /// <param name="when"><see cref="T:WixSharp.When"/> the action should be executed with respect to the <paramref name="step"/> parameter.</param> /// <param name="step"><see cref="T:WixSharp.Step"/> the action should be executed before/after during the installation.</param> /// <param name="condition">The launch condition for the <see cref="InstalledFileAction"/>.</param> /// <param name="sequence">The MSI sequence the action belongs to.</param> /// <param name="rollback">The key (file name) of the installed file that must be executed on rollback.</param> /// <param name="rollbackArg">The arguments to be passed to the file during the execution on rollback.</param> public InstalledFileAction(string key, string args, Return returnType, When when, Step step, Condition condition, Sequence sequence, string rollback, string rollbackArg) : base(returnType, when, step, condition, sequence) { Key = key; Args = args; Name = key; Rollback = rollback; RollbackArg = rollbackArg; } /// <summary> /// Initializes a new instance of the <see cref="InstalledFileAction"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="id">The explicit <see cref="Id"></see> to be associated with <see cref="InstalledFileAction"/> instance.</param> /// <param name="key">The key (file name) of the installed file to be executed.</param> /// <param name="args">The arguments to be passed to the file during the execution.</param> /// <param name="returnType">The return type of the action.</param> /// <param name="when"><see cref="T:WixSharp.When"/> the action should be executed with respect to the <paramref name="step"/> parameter.</param> /// <param name="step"><see cref="T:WixSharp.Step"/> the action should be executed before/after during the installation.</param> /// <param name="condition">The launch condition for the <see cref="InstalledFileAction"/>.</param> /// <param name="sequence">The MSI sequence the action belongs to.</param> public InstalledFileAction(Id id, string key, string args, Return returnType, When when, Step step, Condition condition, Sequence sequence) : base(id, returnType, when, step, condition, sequence) { Key = key; Args = args; Name = key; } /// <summary> /// Initializes a new instance of the <see cref="InstalledFileAction"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="id">The explicit <see cref="Id"></see> to be associated with <see cref="InstalledFileAction"/> instance.</param> /// <param name="key">The key (file name) of the installed file to be executed.</param> /// <param name="args">The arguments to be passed to the file during the execution.</param> /// <param name="returnType">The return type of the action.</param> /// <param name="when"><see cref="T:WixSharp.When"/> the action should be executed with respect to the <paramref name="step"/> parameter.</param> /// <param name="step"><see cref="T:WixSharp.Step"/> the action should be executed before/after during the installation.</param> /// <param name="condition">The launch condition for the <see cref="InstalledFileAction"/>.</param> /// <param name="sequence">The MSI sequence the action belongs to.</param> /// <param name="rollback">The key (file name) of the installed file that must be executed on rollback.</param> /// <param name="rollbackArg">The arguments to be passed to the file during the execution on rollback.</param> public InstalledFileAction(Id id, string key, string args, Return returnType, When when, Step step, Condition condition, Sequence sequence, string rollback, string rollbackArg) : base(id, returnType, when, step, condition, sequence) { Key = key; Args = args; Name = key; Rollback = rollback; RollbackArg = rollbackArg; } /// <summary> /// The key (file name) of the installed file to be executed. /// </summary> public string Key = ""; /// <summary> /// The arguments to be passed to the file during the execution. /// </summary> public string Args = ""; } }
//----------------------------------------------------------------------- // <copyright file="MethodCaller.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>Provides methods to dynamically find and call methods.</summary> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; using System.Globalization; using System.Threading.Tasks; using System.Runtime.Loader; using Csla.Properties; #if NET5_0_OR_GREATER using Csla.Runtime; #endif namespace Csla.Reflection { /// <summary> /// Provides methods to dynamically find and call methods. /// </summary> public static class MethodCaller { private const BindingFlags allLevelFlags = BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ; private const BindingFlags oneLevelFlags = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ; private const BindingFlags ctorFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ; private const BindingFlags factoryFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy; private const BindingFlags privateMethodFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy; #region Dynamic Method Cache #if NET5_0_OR_GREATER private static readonly Dictionary<MethodCacheKey, Tuple<string, DynamicMethodHandle>> _methodCache = new Dictionary<MethodCacheKey, Tuple<string, DynamicMethodHandle>>(); #else private readonly static Dictionary<MethodCacheKey, DynamicMethodHandle> _methodCache = new Dictionary<MethodCacheKey, DynamicMethodHandle>(); #endif private static DynamicMethodHandle GetCachedMethod(object obj, System.Reflection.MethodInfo info, params object[] parameters) { var objectType = obj.GetType(); var found = false; DynamicMethodHandle mh = null; #if NET5_0_OR_GREATER var key = new MethodCacheKey(objectType.FullName, info.Name, GetParameterTypes(parameters)); try { found = _methodCache.TryGetValue(key, out var methodHandleInfo); mh = methodHandleInfo?.Item2; } catch { /* failure will drop into !found block */ } if (!found) { lock (_methodCache) { found = _methodCache.TryGetValue(key, out var methodHandleInfo); mh = methodHandleInfo?.Item2; if (!found) { mh = new DynamicMethodHandle(info, parameters); var cacheInstance = AssemblyLoadContextManager.CreateCacheInstance(objectType, mh, OnMethodAssemblyLoadContextUnload); _methodCache.Add(key, cacheInstance); } } } #else var key = new MethodCacheKey(objectType.FullName, info.Name, GetParameterTypes(parameters)); try { found = _methodCache.TryGetValue(key, out mh); } catch { /* failure will drop into !found block */ } if (!found) { lock (_methodCache) { if (!_methodCache.TryGetValue(key, out mh)) { mh = new DynamicMethodHandle(info, parameters); _methodCache.Add(key, mh); } } } #endif return mh; } private static DynamicMethodHandle GetCachedMethod(object obj, string method, params object[] parameters) { return GetCachedMethod(obj, method, true, parameters); } private static DynamicMethodHandle GetCachedMethod(object obj, string method, bool hasParameters, params object[] parameters) { #if NET5_0_OR_GREATER var objectType = obj.GetType(); var key = new MethodCacheKey(objectType.FullName, method, GetParameterTypes(hasParameters, parameters)); DynamicMethodHandle mh; var found = _methodCache.TryGetValue(key, out var methodHandleInfo); mh = methodHandleInfo?.Item2; if (!found) { lock (_methodCache) { found = _methodCache.TryGetValue(key, out methodHandleInfo); mh = methodHandleInfo?.Item2; if (!found) { var info = GetMethod(obj.GetType(), method, hasParameters, parameters); mh = new DynamicMethodHandle(info, parameters); var cacheInstance = AssemblyLoadContextManager.CreateCacheInstance(objectType, mh, OnMethodAssemblyLoadContextUnload); _methodCache.Add(key, cacheInstance); } } } #else var key = new MethodCacheKey(obj.GetType().FullName, method, GetParameterTypes(hasParameters, parameters)); if (!_methodCache.TryGetValue(key, out DynamicMethodHandle mh)) { lock (_methodCache) { if (!_methodCache.TryGetValue(key, out mh)) { var info = GetMethod(obj.GetType(), method, hasParameters, parameters); mh = new DynamicMethodHandle(info, parameters); _methodCache.Add(key, mh); } } } #endif return mh; } #endregion #region Dynamic Constructor Cache private readonly static Dictionary<Type, DynamicCtorDelegate> _ctorCache = new Dictionary<Type, DynamicCtorDelegate>(); private static DynamicCtorDelegate GetCachedConstructor(Type objectType) { if (objectType == null) throw new ArgumentNullException(nameof(objectType)); DynamicCtorDelegate result = null; var found = false; try { found = _ctorCache.TryGetValue(objectType, out result); } catch { /* failure will drop into !found block */ } if (!found) { lock (_ctorCache) { if (!_ctorCache.TryGetValue(objectType, out result)) { ConstructorInfo info = objectType.GetConstructor(ctorFlags, null, Type.EmptyTypes, null); if (info == null) throw new NotSupportedException(string.Format( CultureInfo.CurrentCulture, "Cannot create instance of Type '{0}'. No public parameterless constructor found.", objectType)); result = DynamicMethodHandlerFactory.CreateConstructor(info); _ctorCache.Add(objectType, result); } } } return result; } #endregion #region GetType /// <summary> /// Gets a Type object based on the type name. /// </summary> /// <param name="typeName">Type name including assembly name.</param> /// <param name="throwOnError">true to throw an exception if the type can't be found.</param> /// <param name="ignoreCase">true for a case-insensitive comparison of the type name.</param> public static Type GetType(string typeName, bool throwOnError, bool ignoreCase) { try { return Type.GetType(typeName, throwOnError, ignoreCase); } catch { string[] splitName = typeName.Split(','); if (splitName.Length > 2) { var asm = AssemblyLoadContext.Default.LoadFromAssemblyPath(AppContext.BaseDirectory + splitName[1].Trim() + ".dll"); return asm.GetType(splitName[0].Trim()); } else { throw; } } } /// <summary> /// Gets a Type object based on the type name. /// </summary> /// <param name="typeName">Type name including assembly name.</param> /// <param name="throwOnError">true to throw an exception if the type can't be found.</param> public static Type GetType(string typeName, bool throwOnError) { return GetType(typeName, throwOnError, false); } /// <summary> /// Gets a Type object based on the type name. /// </summary> /// <param name="typeName">Type name including assembly name.</param> public static Type GetType(string typeName) { return GetType(typeName, true, false); } #endregion private const BindingFlags propertyFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy; private const BindingFlags fieldFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; #if NET5_0_OR_GREATER private static readonly Dictionary<MethodCacheKey, Tuple<string, DynamicMemberHandle>> _memberCache = new Dictionary<MethodCacheKey, Tuple<string, DynamicMemberHandle>>(); #else private static readonly Dictionary<MethodCacheKey, DynamicMemberHandle> _memberCache = new Dictionary<MethodCacheKey, DynamicMemberHandle>(); #endif internal static DynamicMemberHandle GetCachedProperty(Type objectType, string propertyName) { var key = new MethodCacheKey(objectType.FullName, propertyName, GetParameterTypes(null)); #if NET5_0_OR_GREATER var found = _memberCache.TryGetValue(key, out var memberHandleInfo); var mh = memberHandleInfo?.Item2; if (!found) { lock (_memberCache) { found = _memberCache.TryGetValue(key, out memberHandleInfo); mh = memberHandleInfo?.Item2; if (!found) { var info = objectType.GetProperty(propertyName, propertyFlags); if (info == null) throw new InvalidOperationException(string.Format(Resources.MemberNotFoundException, propertyName)); mh = new DynamicMemberHandle(info); var cacheInstance = AssemblyLoadContextManager.CreateCacheInstance(objectType, mh, OnMemberAssemblyLoadContextUnload); _memberCache.Add(key, cacheInstance); } } } #else if (!_memberCache.TryGetValue(key, out DynamicMemberHandle mh)) { lock (_memberCache) { if (!_memberCache.TryGetValue(key, out mh)) { var info = objectType.GetProperty(propertyName, propertyFlags); if (info == null) throw new InvalidOperationException(string.Format(Resources.MemberNotFoundException, propertyName)); mh = new DynamicMemberHandle(info); _memberCache.Add(key, mh); } } } #endif return mh; } internal static DynamicMemberHandle GetCachedField(Type objectType, string fieldName) { var key = new MethodCacheKey(objectType.FullName, fieldName, GetParameterTypes(null)); #if NET5_0_OR_GREATER var found = _memberCache.TryGetValue(key, out var memberHandleInfo); var mh = memberHandleInfo?.Item2; if (!found) { lock (_memberCache) { found = _memberCache.TryGetValue(key, out memberHandleInfo); mh = memberHandleInfo?.Item2; if (!found) { var info = objectType.GetField(fieldName, fieldFlags); if (info == null) throw new InvalidOperationException(string.Format(Resources.MemberNotFoundException, fieldName)); mh = new DynamicMemberHandle(info); var cacheInstance = AssemblyLoadContextManager.CreateCacheInstance(objectType, mh, OnMemberAssemblyLoadContextUnload); _memberCache.Add(key, cacheInstance); } } } #else if (!_memberCache.TryGetValue(key, out DynamicMemberHandle mh)) { lock (_memberCache) { if (!_memberCache.TryGetValue(key, out mh)) { var info = objectType.GetField(fieldName, fieldFlags); if (info == null) throw new InvalidOperationException(string.Format(Resources.MemberNotFoundException, fieldName)); mh = new DynamicMemberHandle(info); _memberCache.Add(key, mh); } } } #endif return mh; } /// <summary> /// Invokes a property getter using dynamic /// method invocation. /// </summary> /// <param name="obj">Target object.</param> /// <param name="property">Property to invoke.</param> /// <returns></returns> public static object CallPropertyGetter(object obj, string property) { if (ApplicationContext.UseReflectionFallback) { var propertyInfo = obj.GetType().GetProperty(property); return propertyInfo.GetValue(obj); } else { if (obj == null) throw new ArgumentNullException("obj"); if (string.IsNullOrEmpty(property)) throw new ArgumentException("Argument is null or empty.", "property"); var mh = GetCachedProperty(obj.GetType(), property); if (mh.DynamicMemberGet == null) { throw new NotSupportedException(string.Format( CultureInfo.CurrentCulture, "The property '{0}' on Type '{1}' does not have a public getter.", property, obj.GetType())); } return mh.DynamicMemberGet(obj); } } /// <summary> /// Invokes a property setter using dynamic /// method invocation. /// </summary> /// <param name="obj">Target object.</param> /// <param name="property">Property to invoke.</param> /// <param name="value">New value for property.</param> public static void CallPropertySetter(object obj, string property, object value) { if (obj == null) throw new ArgumentNullException("obj"); if (string.IsNullOrEmpty(property)) throw new ArgumentException("Argument is null or empty.", "property"); if (ApplicationContext.UseReflectionFallback) { var propertyInfo = obj.GetType().GetProperty(property); propertyInfo.SetValue(obj, value); } else { var mh = GetCachedProperty(obj.GetType(), property); if (mh.DynamicMemberSet == null) { throw new NotSupportedException(string.Format( CultureInfo.CurrentCulture, "The property '{0}' on Type '{1}' does not have a public setter.", property, obj.GetType())); } mh.DynamicMemberSet(obj, value); } } #region Call Method /// <summary> /// Uses reflection to dynamically invoke a method /// if that method is implemented on the target object. /// </summary> /// <param name="obj"> /// Object containing method. /// </param> /// <param name="method"> /// Name of the method. /// </param> public static object CallMethodIfImplemented(object obj, string method) { return CallMethodIfImplemented(obj, method, false, null); } /// <summary> /// Uses reflection to dynamically invoke a method /// if that method is implemented on the target object. /// </summary> /// <param name="obj"> /// Object containing method. /// </param> /// <param name="method"> /// Name of the method. /// </param> /// <param name="parameters"> /// Parameters to pass to method. /// </param> public static object CallMethodIfImplemented(object obj, string method, params object[] parameters) { return CallMethodIfImplemented(obj, method, true, parameters); } private static object CallMethodIfImplemented(object obj, string method, bool hasParameters, params object[] parameters) { if (ApplicationContext.UseReflectionFallback) { var found = (FindMethod(obj.GetType(), method, GetParameterTypes(hasParameters, parameters)) != null); if (found) return CallMethod(obj, method, parameters); else return null; } else { var mh = GetCachedMethod(obj, method, parameters); if (mh == null || mh.DynamicMethod == null) return null; return CallMethod(obj, mh, hasParameters, parameters); } } /// <summary> /// Detects if a method matching the name and parameters is implemented on the provided object. /// </summary> /// <param name="obj">The object implementing the method.</param> /// <param name="method">The name of the method to find.</param> /// <param name="parameters">The parameters matching the parameters types of the method to match.</param> /// <returns>True obj implements a matching method.</returns> public static bool IsMethodImplemented(object obj, string method, params object[] parameters) { var mh = GetCachedMethod(obj, method, parameters); return mh != null && mh.DynamicMethod != null; } /// <summary> /// Uses reflection to dynamically invoke a method, /// throwing an exception if it is not /// implemented on the target object. /// </summary> /// <param name="obj"> /// Object containing method. /// </param> /// <param name="method"> /// Name of the method. /// </param> public static object CallMethod(object obj, string method) { return CallMethod(obj, method, false, null); } /// <summary> /// Uses reflection to dynamically invoke a method, /// throwing an exception if it is not /// implemented on the target object. /// </summary> /// <param name="obj"> /// Object containing method. /// </param> /// <param name="method"> /// Name of the method. /// </param> /// <param name="parameters"> /// Parameters to pass to method. /// </param> public static object CallMethod(object obj, string method, params object[] parameters) { return CallMethod(obj, method, true, parameters); } private static object CallMethod(object obj, string method, bool hasParameters, params object[] parameters) { if (ApplicationContext.UseReflectionFallback) { System.Reflection.MethodInfo info = GetMethod(obj.GetType(), method, hasParameters, parameters); if (info == null) throw new NotImplementedException(obj.GetType().Name + "." + method + " " + Resources.MethodNotImplemented); return CallMethod(obj, info, hasParameters, parameters); } else { var mh = GetCachedMethod(obj, method, hasParameters, parameters); if (mh == null || mh.DynamicMethod == null) throw new NotImplementedException(obj.GetType().Name + "." + method + " " + Resources.MethodNotImplemented); return CallMethod(obj, mh, hasParameters, parameters); } } /// <summary> /// Uses reflection to dynamically invoke a method, /// throwing an exception if it is not /// implemented on the target object. /// </summary> /// <param name="obj"> /// Object containing method. /// </param> /// <param name="info"> /// System.Reflection.MethodInfo for the method. /// </param> /// <param name="parameters"> /// Parameters to pass to method. /// </param> public static object CallMethod(object obj, System.Reflection.MethodInfo info, params object[] parameters) { return CallMethod(obj, info, true, parameters); } private static object CallMethod(object obj, System.Reflection.MethodInfo info, bool hasParameters, params object[] parameters) { if (ApplicationContext.UseReflectionFallback) { var infoParams = info.GetParameters(); var infoParamsCount = infoParams.Length; bool hasParamArray = infoParamsCount > 0 && infoParams[infoParamsCount - 1].GetCustomAttributes(typeof(ParamArrayAttribute), true).Length > 0; bool specialParamArray = false; if (hasParamArray && infoParams[infoParamsCount - 1].ParameterType.Equals(typeof(string[]))) specialParamArray = true; if (hasParamArray && infoParams[infoParamsCount - 1].ParameterType.Equals(typeof(object[]))) specialParamArray = true; object[] par; if (infoParamsCount == 1 && specialParamArray) { par = new object[] { parameters }; } else if (infoParamsCount > 1 && hasParamArray && specialParamArray) { par = new object[infoParamsCount]; for (int i = 0; i < infoParamsCount - 1; i++) par[i] = parameters[i]; par[infoParamsCount - 1] = parameters[infoParamsCount - 1]; } else { par = parameters; } object result; try { result = info.Invoke(obj, par); } catch (Exception e) { Exception inner; if (e.InnerException == null) inner = e; else inner = e.InnerException; throw new CallMethodException(obj.GetType().Name + "." + info.Name + " " + Resources.MethodCallFailed, inner); } return result; } else { var mh = GetCachedMethod(obj, info, parameters); if (mh == null || mh.DynamicMethod == null) throw new NotImplementedException(obj.GetType().Name + "." + info.Name + " " + Resources.MethodNotImplemented); return CallMethod(obj, mh, hasParameters, parameters); } } private static object CallMethod(object obj, DynamicMethodHandle methodHandle, bool hasParameters, params object[] parameters) { object result = null; var method = methodHandle.DynamicMethod; object[] inParams; if (parameters == null) inParams = new object[] { null }; else inParams = parameters; if (methodHandle.HasFinalArrayParam) { // last param is a param array or only param is an array var pCount = methodHandle.MethodParamsLength; var inCount = inParams.Length; if (inCount == pCount - 1) { // no paramter was supplied for the param array // copy items into new array with last entry null object[] paramList = new object[pCount]; for (var pos = 0; pos <= pCount - 2; pos++) paramList[pos] = parameters[pos]; paramList[paramList.Length - 1] = hasParameters && inParams.Length == 0 ? inParams : null; // use new array inParams = paramList; } else if ((inCount == pCount && inParams[inCount - 1] != null && !inParams[inCount - 1].GetType().IsArray) || inCount > pCount) { // 1 or more params go in the param array // copy extras into an array var extras = inParams.Length - (pCount - 1); object[] extraArray = GetExtrasArray(extras, methodHandle.FinalArrayElementType); Array.Copy(inParams, pCount - 1, extraArray, 0, extras); // copy items into new array object[] paramList = new object[pCount]; for (var pos = 0; pos <= pCount - 2; pos++) paramList[pos] = parameters[pos]; paramList[paramList.Length - 1] = extraArray; // use new array inParams = paramList; } } try { result = methodHandle.DynamicMethod(obj, inParams); } catch (Exception ex) { throw new CallMethodException(obj.GetType().Name + "." + methodHandle.MethodName + " " + Resources.MethodCallFailed, ex); } return result; } private static object[] GetExtrasArray(int count, Type arrayType) { return (object[])(System.Array.CreateInstance(arrayType.GetElementType(), count)); } #endregion #region Get/Find Method /// <summary> /// Uses reflection to locate a matching method /// on the target object. /// </summary> /// <param name="objectType"> /// Type of object containing method. /// </param> /// <param name="method"> /// Name of the method. /// </param> public static System.Reflection.MethodInfo GetMethod(Type objectType, string method) { return GetMethod(objectType, method, true, false, null); } /// <summary> /// Uses reflection to locate a matching method /// on the target object. /// </summary> /// <param name="objectType"> /// Type of object containing method. /// </param> /// <param name="method"> /// Name of the method. /// </param> /// <param name="parameters"> /// Parameters to pass to method. /// </param> public static System.Reflection.MethodInfo GetMethod(Type objectType, string method, params object[] parameters) { return GetMethod(objectType, method, true, parameters); } private static System.Reflection.MethodInfo GetMethod(Type objectType, string method, bool hasParameters, params object[] parameters) { System.Reflection.MethodInfo result; object[] inParams; if (!hasParameters) inParams = new object[] { }; else if (parameters == null) inParams = new object[] { null }; else inParams = parameters; // try to find a strongly typed match // first see if there's a matching method // where all params match types result = FindMethod(objectType, method, GetParameterTypes(hasParameters, inParams)); if (result == null) { // no match found - so look for any method // with the right number of parameters try { result = FindMethod(objectType, method, inParams.Length); } catch (AmbiguousMatchException) { // we have multiple methods matching by name and parameter count result = FindMethodUsingFuzzyMatching(objectType, method, inParams); } } // no strongly typed match found, get default based on name only if (result == null) { result = objectType.GetMethod(method, allLevelFlags); } return result; } private static System.Reflection.MethodInfo FindMethodUsingFuzzyMatching(Type objectType, string method, object[] parameters) { System.Reflection.MethodInfo result = null; Type currentType = objectType; do { System.Reflection.MethodInfo[] methods = currentType.GetMethods(oneLevelFlags); int parameterCount = parameters.Length; // Match based on name and parameter types and parameter arrays foreach (System.Reflection.MethodInfo m in methods) { if (m.Name == method) { var infoParams = m.GetParameters(); var pCount = infoParams.Length; if (pCount > 0) { if (pCount == 1 && infoParams[0].ParameterType.IsArray) { // only param is an array if (parameters.GetType().Equals(infoParams[0].ParameterType)) { // got a match so use it result = m; break; } } if (infoParams[pCount - 1].GetCustomAttributes(typeof(ParamArrayAttribute), true).Length > 0) { // last param is a param array if (parameterCount == pCount && parameters[pCount - 1].GetType().Equals(infoParams[pCount - 1].ParameterType)) { // got a match so use it result = m; break; } } } } } if (result == null) { // match based on parameter name and number of parameters foreach (System.Reflection.MethodInfo m in methods) { if (m.Name == method && m.GetParameters().Length == parameterCount) { result = m; break; } } } if (result != null) break; currentType = currentType.BaseType; } while (currentType != null); return result; } /// <summary> /// Returns information about the specified /// method, even if the parameter types are /// generic and are located in an abstract /// generic base class. /// </summary> /// <param name="objectType"> /// Type of object containing method. /// </param> /// <param name="method"> /// Name of the method. /// </param> /// <param name="types"> /// Parameter types to pass to method. /// </param> public static System.Reflection.MethodInfo FindMethod(Type objectType, string method, Type[] types) { System.Reflection.MethodInfo info; do { // find for a strongly typed match info = objectType.GetMethod(method, oneLevelFlags, null, types, null); if (info != null) { break; // match found } objectType = objectType.BaseType; } while (objectType != null); return info; } /// <summary> /// Returns information about the specified /// method, finding the method based purely /// on the method name and number of parameters. /// </summary> /// <param name="objectType"> /// Type of object containing method. /// </param> /// <param name="method"> /// Name of the method. /// </param> /// <param name="parameterCount"> /// Number of parameters to pass to method. /// </param> public static System.Reflection.MethodInfo FindMethod(Type objectType, string method, int parameterCount) { // walk up the inheritance hierarchy looking // for a method with the right number of // parameters System.Reflection.MethodInfo result = null; Type currentType = objectType; do { System.Reflection.MethodInfo info = currentType.GetMethod(method, oneLevelFlags); if (info != null) { var infoParams = info.GetParameters(); var pCount = infoParams.Length; if (pCount > 0 && ((pCount == 1 && infoParams[0].ParameterType.IsArray) || (infoParams[pCount - 1].GetCustomAttributes(typeof(ParamArrayAttribute), true).Length > 0))) { // last param is a param array or only param is an array if (parameterCount >= pCount - 1) { // got a match so use it result = info; break; } } else if (pCount == parameterCount) { // got a match so use it result = info; break; } } currentType = currentType.BaseType; } while (currentType != null); return result; } #endregion /// <summary> /// Returns an array of Type objects corresponding /// to the type of parameters provided. /// </summary> public static Type[] GetParameterTypes() { return GetParameterTypes(false, null); } /// <summary> /// Returns an array of Type objects corresponding /// to the type of parameters provided. /// </summary> /// <param name="parameters"> /// Parameter values. /// </param> public static Type[] GetParameterTypes(object[] parameters) { return GetParameterTypes(true, parameters); } private static Type[] GetParameterTypes(bool hasParameters, object[] parameters) { if (!hasParameters) return new Type[] { }; List<Type> result = new List<Type>(); if (parameters == null) { result.Add(typeof(object)); } else { foreach (object item in parameters) { if (item == null) { result.Add(typeof(object)); } else { result.Add(item.GetType()); } } } return result.ToArray(); } /// <summary> /// Gets a property type descriptor by name. /// </summary> /// <param name="t">Type of object containing the property.</param> /// <param name="propertyName">Name of the property.</param> public static PropertyDescriptor GetPropertyDescriptor(Type t, string propertyName) { var propertyDescriptors = TypeDescriptor.GetProperties(t); PropertyDescriptor result = null; foreach (PropertyDescriptor desc in propertyDescriptors) if (desc.Name == propertyName) { result = desc; break; } return result; } /// <summary> /// Gets information about a property. /// </summary> /// <param name="objectType">Object containing the property.</param> /// <param name="propertyName">Name of the property.</param> public static PropertyInfo GetProperty(Type objectType, string propertyName) { return objectType.GetProperty(propertyName, propertyFlags); } /// <summary> /// Gets a property value. /// </summary> /// <param name="obj">Object containing the property.</param> /// <param name="info">Property info object for the property.</param> /// <returns>The value of the property.</returns> public static object GetPropertyValue(object obj, PropertyInfo info) { object result; try { result = info.GetValue(obj, null); } catch (Exception e) { Exception inner; if (e.InnerException == null) inner = e; else inner = e.InnerException; throw new CallMethodException(obj.GetType().Name + "." + info.Name + " " + Resources.MethodCallFailed, inner); } return result; } /// <summary> /// Invokes an instance method on an object. /// </summary> /// <param name="obj">Object containing method.</param> /// <param name="info">Method info object.</param> /// <returns>Any value returned from the method.</returns> public static object CallMethod(object obj, System.Reflection.MethodInfo info) { object result; try { result = info.Invoke(obj, null); } catch (Exception e) { Exception inner; if (e.InnerException == null) inner = e; else inner = e.InnerException; throw new CallMethodException(obj.GetType().Name + "." + info.Name + " " + Resources.MethodCallFailed, inner); } return result; } /// <summary> /// Uses reflection to dynamically invoke a method, /// throwing an exception if it is not /// implemented on the target object. /// </summary> /// <param name="obj"> /// Object containing method. /// </param> /// <param name="method"> /// Name of the method. /// </param> /// <param name="parameters"> /// Parameters to pass to method. /// </param> public async static Task<object> CallMethodTryAsync(object obj, string method, params object[] parameters) { return await CallMethodTryAsync(obj, method, true, parameters); } /// <summary> /// Invokes an instance method on an object. If the method /// is async returning Task of object it will be invoked using an await statement. /// </summary> /// <param name="obj">Object containing method.</param> /// <param name="method"> /// Name of the method. /// </param> public async static Task<object> CallMethodTryAsync(object obj, string method) { return await CallMethodTryAsync(obj, method, false, null); } private async static Task<object> CallMethodTryAsync(object obj, string method, bool hasParameters, params object[] parameters) { try { if (ApplicationContext.UseReflectionFallback) { var info = FindMethod(obj.GetType(), method, GetParameterTypes(hasParameters, parameters)); if (info == null) throw new NotImplementedException(obj.GetType().Name + "." + method + " " + Resources.MethodNotImplemented); var isAsyncTask = (info.ReturnType == typeof(Task)); var isAsyncTaskObject = (info.ReturnType.IsGenericType && (info.ReturnType.GetGenericTypeDefinition() == typeof(Task<>))); if (isAsyncTask) { await (Task)CallMethod(obj, method, hasParameters, parameters); return null; } else if (isAsyncTaskObject) { return await (Task<object>)CallMethod(obj, method, hasParameters, parameters); } else { return CallMethod(obj, method, hasParameters, parameters); } } else { var mh = GetCachedMethod(obj, method, hasParameters, parameters); if (mh == null || mh.DynamicMethod == null) throw new NotImplementedException(obj.GetType().Name + "." + method + " " + Resources.MethodNotImplemented); if (mh.IsAsyncTask) { await (Task)CallMethod(obj, mh, hasParameters, parameters); return null; } else if (mh.IsAsyncTaskObject) { return await (Task<object>)CallMethod(obj, mh, hasParameters, parameters); } else { return CallMethod(obj, mh, hasParameters, parameters); } } } catch (InvalidCastException ex) { throw new NotSupportedException( string.Format(Resources.TaskOfObjectException, obj.GetType().Name + "." + method), ex); } } /// <summary> /// Returns true if the method provided is an async method returning a Task object. /// </summary> /// <param name="obj">Object containing method.</param> /// <param name="method">Name of the method.</param> public static bool IsAsyncMethod(object obj, string method) { return IsAsyncMethod(obj, method, false, null); } /// <summary> /// Returns true if the method provided is an async method returning a Task object. /// </summary> /// <param name="obj">Object containing method.</param> /// <param name="method">Name of the method.</param> /// <param name="parameters"> /// Parameters to pass to method. /// </param> public static bool IsAsyncMethod(object obj, string method, params object[] parameters) { return IsAsyncMethod(obj, method, true, parameters); } internal static bool IsAsyncMethod(System.Reflection.MethodInfo info) { var isAsyncTask = (info.ReturnType == typeof(Task)); var isAsyncTaskObject = (info.ReturnType.IsGenericType && (info.ReturnType.GetGenericTypeDefinition() == typeof(Task<>))); return isAsyncTask || isAsyncTaskObject; } private static bool IsAsyncMethod(object obj, string method, bool hasParameters, params object[] parameters) { if (ApplicationContext.UseReflectionFallback) { var info = FindMethod(obj.GetType(), method, GetParameterTypes(hasParameters, parameters)); if (info == null) throw new NotImplementedException(obj.GetType().Name + "." + method + " " + Resources.MethodNotImplemented); return IsAsyncMethod(info); } else { var mh = GetCachedMethod(obj, method, hasParameters, parameters); if (mh == null || mh.DynamicMethod == null) throw new NotImplementedException(obj.GetType().Name + "." + method + " " + Resources.MethodNotImplemented); return mh.IsAsyncTask || mh.IsAsyncTaskObject; } } /// <summary> /// Invokes a generic async static method by name /// </summary> /// <param name="objectType">Class containing static method</param> /// <param name="method">Method to invoke</param> /// <param name="typeParams">Type parameters for method</param> /// <param name="hasParameters">Flag indicating whether method accepts parameters</param> /// <param name="parameters">Parameters for method</param> /// <returns></returns> public static Task<object> CallGenericStaticMethodAsync(Type objectType, string method, Type[] typeParams, bool hasParameters, params object[] parameters) { var tcs = new TaskCompletionSource<object>(); try { Task task = null; if (hasParameters) { var pTypes = GetParameterTypes(parameters); var methodReference = objectType.GetMethod(method, BindingFlags.Static | BindingFlags.Public, null, CallingConventions.Any, pTypes, null); if (methodReference == null) methodReference = objectType.GetMethod(method, BindingFlags.Static | BindingFlags.Public); if (methodReference == null) throw new InvalidOperationException(objectType.Name + "." + method); var gr = methodReference.MakeGenericMethod(typeParams); task = (Task)gr.Invoke(null, parameters); } else { var methodReference = objectType.GetMethod(method, BindingFlags.Static | BindingFlags.Public, null, CallingConventions.Any, System.Type.EmptyTypes, null); var gr = methodReference.MakeGenericMethod(typeParams); task = (Task)gr.Invoke(null, null); } task.Wait(); if (task.Exception != null) tcs.SetException(task.Exception); else tcs.SetResult(Csla.Reflection.MethodCaller.CallPropertyGetter(task, "Result")); } catch (Exception ex) { tcs.SetException(ex); } return tcs.Task; } /// <summary> /// Invokes a generic method by name /// </summary> /// <param name="target">Object containing method to invoke</param> /// <param name="method">Method to invoke</param> /// <param name="typeParams">Type parameters for method</param> /// <param name="hasParameters">Flag indicating whether method accepts parameters</param> /// <param name="parameters">Parameters for method</param> /// <returns></returns> public static object CallGenericMethod(object target, string method, Type[] typeParams, bool hasParameters, params object[] parameters) { var objectType = target.GetType(); object result; if (hasParameters) { var pTypes = GetParameterTypes(parameters); var methodReference = objectType.GetMethod(method, BindingFlags.Instance | BindingFlags.Public, null, CallingConventions.Any, pTypes, null); if (methodReference == null) methodReference = objectType.GetMethod(method, BindingFlags.Instance | BindingFlags.Public); if (methodReference == null) throw new InvalidOperationException(objectType.Name + "." + method); var gr = methodReference.MakeGenericMethod(typeParams); result = gr.Invoke(target, parameters); } else { var methodReference = objectType.GetMethod(method, BindingFlags.Static | BindingFlags.Public, null, CallingConventions.Any, System.Type.EmptyTypes, null); if (methodReference == null) throw new InvalidOperationException(objectType.Name + "." + method); var gr = methodReference.MakeGenericMethod(typeParams); result = gr.Invoke(target, null); } return result; } /// <summary> /// Invokes a static factory method. /// </summary> /// <param name="objectType">Business class where the factory is defined.</param> /// <param name="method">Name of the factory method</param> /// <param name="parameters">Parameters passed to factory method.</param> /// <returns>Result of the factory method invocation.</returns> public static object CallFactoryMethod(Type objectType, string method, params object[] parameters) { object returnValue; System.Reflection.MethodInfo factory = objectType.GetMethod( method, factoryFlags, null, MethodCaller.GetParameterTypes(parameters), null); if (factory == null) { // strongly typed factory couldn't be found // so find one with the correct number of // parameters int parameterCount = parameters.Length; System.Reflection.MethodInfo[] methods = objectType.GetMethods(factoryFlags); foreach (System.Reflection.MethodInfo oneMethod in methods) if (oneMethod.Name == method && oneMethod.GetParameters().Length == parameterCount) { factory = oneMethod; break; } } if (factory == null) { // no matching factory could be found // so throw exception throw new InvalidOperationException( string.Format(Resources.NoSuchFactoryMethod, method)); } try { returnValue = factory.Invoke(null, parameters); } catch (Exception ex) { Exception inner; if (ex.InnerException == null) inner = ex; else inner = ex.InnerException; throw new CallMethodException(objectType.Name + "." + factory.Name + " " + Resources.MethodCallFailed, inner); } return returnValue; } /// <summary> /// Gets a System.Reflection.MethodInfo object corresponding to a /// non-public method. /// </summary> /// <param name="objectType">Object containing the method.</param> /// <param name="method">Name of the method.</param> public static System.Reflection.MethodInfo GetNonPublicMethod(Type objectType, string method) { var result = FindMethod(objectType, method, privateMethodFlags); return result; } /// <summary> /// Returns information about the specified /// method. /// </summary> /// <param name="objType">Type of object.</param> /// <param name="method">Name of the method.</param> /// <param name="flags">Flag values.</param> public static System.Reflection.MethodInfo FindMethod(Type objType, string method, BindingFlags flags) { System.Reflection.MethodInfo info; do { // find for a strongly typed match info = objType.GetMethod(method, flags); if (info != null) break; // match found objType = objType.BaseType; } while (objType != null); return info; } #if NET5_0_OR_GREATER private static void OnMethodAssemblyLoadContextUnload(AssemblyLoadContext context) { lock (_methodCache) AssemblyLoadContextManager.RemoveFromCache(_methodCache, context); } private static void OnMemberAssemblyLoadContextUnload(AssemblyLoadContext context) { lock (_memberCache) AssemblyLoadContextManager.RemoveFromCache(_memberCache, context); } #endif } }
/* * Deed API * * Land Registry Deed API * * OpenAPI spec version: 2.3.1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using RestSharp; using IO.Swagger.Client; using IO.Swagger.Model; namespace IO.Swagger.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IDefaultApi : IApiAccessor { #region Synchronous Operations /// <summary> /// Deed /// </summary> /// <remarks> /// The post Deed endpoint creates a new deed based on the JSON provided. The reponse will return a URL that can retrieve the created deed. &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>string</returns> string AddDeed (DeedApplication body); /// <summary> /// Deed /// </summary> /// <remarks> /// The post Deed endpoint creates a new deed based on the JSON provided. The reponse will return a URL that can retrieve the created deed. &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>ApiResponse of string</returns> ApiResponse<string> AddDeedWithHttpInfo (DeedApplication body); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Deed /// </summary> /// <remarks> /// The post Deed endpoint creates a new deed based on the JSON provided. The reponse will return a URL that can retrieve the created deed. &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>Task of string</returns> System.Threading.Tasks.Task<string> AddDeedAsync (DeedApplication body); /// <summary> /// Deed /// </summary> /// <remarks> /// The post Deed endpoint creates a new deed based on the JSON provided. The reponse will return a URL that can retrieve the created deed. &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>Task of ApiResponse (string)</returns> System.Threading.Tasks.Task<ApiResponse<string>> AddDeedAsyncWithHttpInfo (DeedApplication body); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class DefaultApi : IDefaultApi { private IO.Swagger.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="DefaultApi"/> class. /// </summary> /// <returns></returns> public DefaultApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Initializes a new instance of the <see cref="DefaultApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public DefaultApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public IO.Swagger.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public Dictionary<String, String> DefaultHeader() { return this.Configuration.DefaultHeader; } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Deed The post Deed endpoint creates a new deed based on the JSON provided. The reponse will return a URL that can retrieve the created deed. &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>string</returns> public string AddDeed (DeedApplication body) { ApiResponse<string> localVarResponse = AddDeedWithHttpInfo(body); return localVarResponse.Data; } /// <summary> /// Deed The post Deed endpoint creates a new deed based on the JSON provided. The reponse will return a URL that can retrieve the created deed. &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>ApiResponse of string</returns> public ApiResponse< string > AddDeedWithHttpInfo (DeedApplication body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling DefaultApi->AddDeed"); var localVarPath = "/deed/"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("AddDeed", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<string>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (string) Configuration.ApiClient.Deserialize(localVarResponse, typeof(string))); } /// <summary> /// Deed The post Deed endpoint creates a new deed based on the JSON provided. The reponse will return a URL that can retrieve the created deed. &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>Task of string</returns> public async System.Threading.Tasks.Task<string> AddDeedAsync (DeedApplication body) { ApiResponse<string> localVarResponse = await AddDeedAsyncWithHttpInfo(body); return localVarResponse.Data; } /// <summary> /// Deed The post Deed endpoint creates a new deed based on the JSON provided. The reponse will return a URL that can retrieve the created deed. &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>Task of ApiResponse (string)</returns> public async System.Threading.Tasks.Task<ApiResponse<string>> AddDeedAsyncWithHttpInfo (DeedApplication body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling DefaultApi->AddDeed"); var localVarPath = "/deed/"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("AddDeed", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<string>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (string) Configuration.ApiClient.Deserialize(localVarResponse, typeof(string))); } } }
using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using NUnit.Framework; using Assert = Lucene.Net.TestFramework.Assert; namespace Lucene.Net.Search { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Directory = Lucene.Net.Store.Directory; using DirectoryReader = Lucene.Net.Index.DirectoryReader; using DocsAndPositionsEnum = Lucene.Net.Index.DocsAndPositionsEnum; using Document = Documents.Document; using English = Lucene.Net.Util.English; using Field = Field; using Fields = Lucene.Net.Index.Fields; using FieldType = FieldType; using IndexReader = Lucene.Net.Index.IndexReader; using IndexWriter = Lucene.Net.Index.IndexWriter; using IOUtils = Lucene.Net.Util.IOUtils; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using MockTokenizer = Lucene.Net.Analysis.MockTokenizer; using OpenMode = Lucene.Net.Index.OpenMode; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using Term = Lucene.Net.Index.Term; using Terms = Lucene.Net.Index.Terms; using TermsEnum = Lucene.Net.Index.TermsEnum; using TextField = TextField; public class TestTermVectors : LuceneTestCase { private static IndexReader reader; private static Directory directory; /// <summary> /// LUCENENET specific /// Is non-static because NewIndexWriterConfig is no longer static. /// </summary> [OneTimeSetUp] public override void BeforeClass() { base.BeforeClass(); directory = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random, directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random, MockTokenizer.SIMPLE, true)).SetMergePolicy(NewLogMergePolicy())); //writer.setNoCFSRatio(1.0); //writer.infoStream = System.out; for (int i = 0; i < 1000; i++) { Document doc = new Document(); FieldType ft = new FieldType(TextField.TYPE_STORED); int mod3 = i % 3; int mod2 = i % 2; if (mod2 == 0 && mod3 == 0) { ft.StoreTermVectors = true; ft.StoreTermVectorOffsets = true; ft.StoreTermVectorPositions = true; } else if (mod2 == 0) { ft.StoreTermVectors = true; ft.StoreTermVectorPositions = true; } else if (mod3 == 0) { ft.StoreTermVectors = true; ft.StoreTermVectorOffsets = true; } else { ft.StoreTermVectors = true; } doc.Add(new Field("field", English.Int32ToEnglish(i), ft)); //test no term vectors too doc.Add(new TextField("noTV", English.Int32ToEnglish(i), Field.Store.YES)); writer.AddDocument(doc); } reader = writer.GetReader(); writer.Dispose(); } [OneTimeTearDown] public override void AfterClass() { reader.Dispose(); directory.Dispose(); reader = null; directory = null; base.AfterClass(); } // In a single doc, for the same field, mix the term // vectors up [Test] public virtual void TestMixedVectrosVectors() { RandomIndexWriter writer = new RandomIndexWriter(Random, directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random, MockTokenizer.SIMPLE, true)).SetOpenMode(OpenMode.CREATE)); Document doc = new Document(); FieldType ft2 = new FieldType(TextField.TYPE_STORED); ft2.StoreTermVectors = true; FieldType ft3 = new FieldType(TextField.TYPE_STORED); ft3.StoreTermVectors = true; ft3.StoreTermVectorPositions = true; FieldType ft4 = new FieldType(TextField.TYPE_STORED); ft4.StoreTermVectors = true; ft4.StoreTermVectorOffsets = true; FieldType ft5 = new FieldType(TextField.TYPE_STORED); ft5.StoreTermVectors = true; ft5.StoreTermVectorOffsets = true; ft5.StoreTermVectorPositions = true; doc.Add(NewTextField("field", "one", Field.Store.YES)); doc.Add(NewField("field", "one", ft2)); doc.Add(NewField("field", "one", ft3)); doc.Add(NewField("field", "one", ft4)); doc.Add(NewField("field", "one", ft5)); writer.AddDocument(doc); IndexReader reader = writer.GetReader(); writer.Dispose(); IndexSearcher searcher = NewSearcher(reader); Query query = new TermQuery(new Term("field", "one")); ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); Fields vectors = searcher.IndexReader.GetTermVectors(hits[0].Doc); Assert.IsNotNull(vectors); Assert.AreEqual(1, vectors.Count); Terms vector = vectors.GetTerms("field"); Assert.IsNotNull(vector); Assert.AreEqual(1, vector.Count); TermsEnum termsEnum = vector.GetEnumerator(); Assert.IsTrue(termsEnum.MoveNext()); Assert.AreEqual("one", termsEnum.Term.Utf8ToString()); Assert.AreEqual(5, termsEnum.TotalTermFreq); DocsAndPositionsEnum dpEnum = termsEnum.DocsAndPositions(null, null); Assert.IsNotNull(dpEnum); Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS); Assert.AreEqual(5, dpEnum.Freq); for (int i = 0; i < 5; i++) { Assert.AreEqual(i, dpEnum.NextPosition()); } dpEnum = termsEnum.DocsAndPositions(null, dpEnum); Assert.IsNotNull(dpEnum); Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS); Assert.AreEqual(5, dpEnum.Freq); for (int i = 0; i < 5; i++) { dpEnum.NextPosition(); Assert.AreEqual(4 * i, dpEnum.StartOffset); Assert.AreEqual(4 * i + 3, dpEnum.EndOffset); } reader.Dispose(); } private IndexWriter CreateWriter(Directory dir) { return new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMaxBufferedDocs(2)); } private void CreateDir(Directory dir) { IndexWriter writer = CreateWriter(dir); writer.AddDocument(CreateDoc()); writer.Dispose(); } private Document CreateDoc() { Document doc = new Document(); FieldType ft = new FieldType(TextField.TYPE_STORED); ft.StoreTermVectors = true; ft.StoreTermVectorOffsets = true; ft.StoreTermVectorPositions = true; doc.Add(NewField("c", "aaa", ft)); return doc; } private void VerifyIndex(Directory dir) { IndexReader r = DirectoryReader.Open(dir); int numDocs = r.NumDocs; for (int i = 0; i < numDocs; i++) { Assert.IsNotNull(r.GetTermVectors(i).GetTerms("c"), "term vectors should not have been null for document " + i); } r.Dispose(); } [Test] public virtual void TestFullMergeAddDocs() { Directory target = NewDirectory(); IndexWriter writer = CreateWriter(target); // with maxBufferedDocs=2, this results in two segments, so that forceMerge // actually does something. for (int i = 0; i < 4; i++) { writer.AddDocument(CreateDoc()); } writer.ForceMerge(1); writer.Dispose(); VerifyIndex(target); target.Dispose(); } [Test] public virtual void TestFullMergeAddIndexesDir() { Directory[] input = new Directory[] { NewDirectory(), NewDirectory() }; Directory target = NewDirectory(); foreach (Directory dir in input) { CreateDir(dir); } IndexWriter writer = CreateWriter(target); writer.AddIndexes(input); writer.ForceMerge(1); writer.Dispose(); VerifyIndex(target); IOUtils.Dispose(target, input[0], input[1]); } [Test] public virtual void TestFullMergeAddIndexesReader() { Directory[] input = new Directory[] { NewDirectory(), NewDirectory() }; Directory target = NewDirectory(); foreach (Directory dir in input) { CreateDir(dir); } IndexWriter writer = CreateWriter(target); foreach (Directory dir in input) { IndexReader r = DirectoryReader.Open(dir); writer.AddIndexes(r); r.Dispose(); } writer.ForceMerge(1); writer.Dispose(); VerifyIndex(target); IOUtils.Dispose(target, input[0], input[1]); } } }
//--------------------------------------------------------------------------- // // <copyright file="BitmapEffectInput.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.Collections; using MS.Internal.KnownBoxes; 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.Media3D; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using System.Windows.Media.Imaging; using System.Windows.Markup; 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.Effects { sealed partial class BitmapEffectInput : Animatable { //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Shadows inherited Clone() with a strongly typed /// version for convenience. /// </summary> public new BitmapEffectInput Clone() { return (BitmapEffectInput)base.Clone(); } /// <summary> /// Shadows inherited CloneCurrentValue() with a strongly typed /// version for convenience. /// </summary> public new BitmapEffectInput CloneCurrentValue() { return (BitmapEffectInput)base.CloneCurrentValue(); } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ private static void AreaToApplyEffectPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { BitmapEffectInput target = ((BitmapEffectInput) d); target.PropertyChanged(AreaToApplyEffectProperty); } #region Public Properties /// <summary> /// Input - BitmapSource. Default value is BitmapEffectInput.ContextInputSource. /// </summary> public BitmapSource Input { get { return (BitmapSource) GetValue(InputProperty); } set { SetValueInternal(InputProperty, value); } } /// <summary> /// AreaToApplyEffectUnits - BrushMappingMode. Default value is BrushMappingMode.RelativeToBoundingBox. /// </summary> public BrushMappingMode AreaToApplyEffectUnits { get { return (BrushMappingMode) GetValue(AreaToApplyEffectUnitsProperty); } set { SetValueInternal(AreaToApplyEffectUnitsProperty, value); } } /// <summary> /// AreaToApplyEffect - Rect. Default value is Rect.Empty. /// </summary> public Rect AreaToApplyEffect { get { return (Rect) GetValue(AreaToApplyEffectProperty); } set { SetValueInternal(AreaToApplyEffectProperty, 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 BitmapEffectInput(); } #endregion ProtectedMethods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties #endregion Internal Properties //------------------------------------------------------ // // Dependency Properties // //------------------------------------------------------ #region Dependency Properties /// <summary> /// The DependencyProperty for the BitmapEffectInput.Input property. /// </summary> public static readonly DependencyProperty InputProperty; /// <summary> /// The DependencyProperty for the BitmapEffectInput.AreaToApplyEffectUnits property. /// </summary> public static readonly DependencyProperty AreaToApplyEffectUnitsProperty; /// <summary> /// The DependencyProperty for the BitmapEffectInput.AreaToApplyEffect property. /// </summary> public static readonly DependencyProperty AreaToApplyEffectProperty; #endregion Dependency Properties //------------------------------------------------------ // // Internal Fields // //------------------------------------------------------ #region Internal Fields internal static BitmapSource s_Input = BitmapEffectInput.ContextInputSource; internal const BrushMappingMode c_AreaToApplyEffectUnits = BrushMappingMode.RelativeToBoundingBox; internal static Rect s_AreaToApplyEffect = Rect.Empty; #endregion Internal Fields #region Constructors //------------------------------------------------------ // // Constructors // //------------------------------------------------------ static BitmapEffectInput() { // 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) // Debug.Assert(s_Input == null || s_Input.IsFrozen, "Detected context bound default value BitmapEffectInput.s_Input (See OS Bug #947272)."); // Initializations Type typeofThis = typeof(BitmapEffectInput); InputProperty = RegisterProperty("Input", typeof(BitmapSource), typeofThis, BitmapEffectInput.ContextInputSource, null, null, /* isIndependentlyAnimated = */ false, /* coerceValueCallback */ null); AreaToApplyEffectUnitsProperty = RegisterProperty("AreaToApplyEffectUnits", typeof(BrushMappingMode), typeofThis, BrushMappingMode.RelativeToBoundingBox, null, new ValidateValueCallback(System.Windows.Media.ValidateEnums.IsBrushMappingModeValid), /* isIndependentlyAnimated = */ false, /* coerceValueCallback */ null); AreaToApplyEffectProperty = RegisterProperty("AreaToApplyEffect", typeof(Rect), typeofThis, Rect.Empty, new PropertyChangedCallback(AreaToApplyEffectPropertyChanged), null, /* isIndependentlyAnimated = */ true, /* coerceValueCallback */ null); } #endregion Constructors } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using JetBrains.Annotations; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Graphics; using osu.Game.Online.Multiplayer; using osu.Game.Online.Spectator; using osu.Game.Screens.Play; using osu.Game.Screens.Play.HUD; using osu.Game.Screens.Spectate; namespace osu.Game.Screens.OnlinePlay.Multiplayer.Spectate { /// <summary> /// A <see cref="SpectatorScreen"/> that spectates multiple users in a match. /// </summary> public class MultiSpectatorScreen : SpectatorScreen { // Isolates beatmap/ruleset to this screen. public override bool DisallowExternalBeatmapRulesetChanges => true; // We are managing our own adjustments. For now, this happens inside the Player instances themselves. public override bool? AllowTrackAdjustments => false; /// <summary> /// Whether all spectating players have finished loading. /// </summary> public bool AllPlayersLoaded => instances.All(p => p?.PlayerLoaded == true); [Resolved] private OsuColour colours { get; set; } [Resolved] private SpectatorClient spectatorClient { get; set; } [Resolved] private MultiplayerClient multiplayerClient { get; set; } private readonly PlayerArea[] instances; private MasterGameplayClockContainer masterClockContainer; private ISyncManager syncManager; private PlayerGrid grid; private MultiSpectatorLeaderboard leaderboard; private PlayerArea currentAudioSource; private bool canStartMasterClock; private readonly MultiplayerRoomUser[] users; /// <summary> /// Creates a new <see cref="MultiSpectatorScreen"/>. /// </summary> /// <param name="users">The players to spectate.</param> public MultiSpectatorScreen(MultiplayerRoomUser[] users) : base(users.Select(u => u.UserID).ToArray()) { this.users = users; instances = new PlayerArea[Users.Count]; } [BackgroundDependencyLoader] private void load() { Container leaderboardContainer; Container scoreDisplayContainer; masterClockContainer = new MasterGameplayClockContainer(Beatmap.Value, 0); InternalChildren = new[] { (Drawable)(syncManager = new CatchUpSyncManager(masterClockContainer)), masterClockContainer.WithChild(new GridContainer { RelativeSizeAxes = Axes.Both, RowDimensions = new[] { new Dimension(GridSizeMode.AutoSize) }, Content = new[] { new Drawable[] { scoreDisplayContainer = new Container { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y }, }, new Drawable[] { new GridContainer { RelativeSizeAxes = Axes.Both, ColumnDimensions = new[] { new Dimension(GridSizeMode.AutoSize) }, Content = new[] { new Drawable[] { leaderboardContainer = new Container { RelativeSizeAxes = Axes.Y, AutoSizeAxes = Axes.X }, grid = new PlayerGrid { RelativeSizeAxes = Axes.Both } } } } } } }) }; for (int i = 0; i < Users.Count; i++) { grid.Add(instances[i] = new PlayerArea(Users[i], masterClockContainer.GameplayClock)); syncManager.AddPlayerClock(instances[i].GameplayClock); } // Todo: This is not quite correct - it should be per-user to adjust for other mod combinations. var playableBeatmap = Beatmap.Value.GetPlayableBeatmap(Ruleset.Value); var scoreProcessor = Ruleset.Value.CreateInstance().CreateScoreProcessor(); scoreProcessor.ApplyBeatmap(playableBeatmap); LoadComponentAsync(leaderboard = new MultiSpectatorLeaderboard(scoreProcessor, users) { Expanded = { Value = true }, Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, }, l => { foreach (var instance in instances) leaderboard.AddClock(instance.UserId, instance.GameplayClock); leaderboardContainer.Add(leaderboard); if (leaderboard.TeamScores.Count == 2) { LoadComponentAsync(new MatchScoreDisplay { Team1Score = { BindTarget = leaderboard.TeamScores.First().Value }, Team2Score = { BindTarget = leaderboard.TeamScores.Last().Value }, }, scoreDisplayContainer.Add); } }); } protected override void LoadComplete() { base.LoadComplete(); masterClockContainer.Reset(); masterClockContainer.Stop(); syncManager.ReadyToStart += onReadyToStart; syncManager.MasterState.BindValueChanged(onMasterStateChanged, true); } protected override void Update() { base.Update(); if (!isCandidateAudioSource(currentAudioSource?.GameplayClock)) { currentAudioSource = instances.Where(i => isCandidateAudioSource(i.GameplayClock)) .OrderBy(i => Math.Abs(i.GameplayClock.CurrentTime - syncManager.MasterClock.CurrentTime)) .FirstOrDefault(); foreach (var instance in instances) instance.Mute = instance != currentAudioSource; } } private bool isCandidateAudioSource([CanBeNull] ISpectatorPlayerClock clock) => clock?.IsRunning == true && !clock.IsCatchingUp && !clock.WaitingOnFrames.Value; private void onReadyToStart() { // Seek the master clock to the gameplay time. // This is chosen as the first available frame in the players' replays, which matches the seek by each individual SpectatorPlayer. double startTime = instances.Where(i => i.Score != null) .SelectMany(i => i.Score.Replay.Frames) .Select(f => f.Time) .DefaultIfEmpty(0) .Min(); masterClockContainer.Seek(startTime); masterClockContainer.Start(); // Although the clock has been started, this flag is set to allow for later synchronisation state changes to also be able to start it. canStartMasterClock = true; } private void onMasterStateChanged(ValueChangedEvent<MasterClockState> state) { switch (state.NewValue) { case MasterClockState.Synchronised: if (canStartMasterClock) masterClockContainer.Start(); break; case MasterClockState.TooFarAhead: masterClockContainer.Stop(); break; } } protected override void OnUserStateChanged(int userId, SpectatorState spectatorState) { } protected override void StartGameplay(int userId, SpectatorGameplayState spectatorGameplayState) => instances.Single(i => i.UserId == userId).LoadScore(spectatorGameplayState.Score); protected override void EndGameplay(int userId) { RemoveUser(userId); var instance = instances.Single(i => i.UserId == userId); instance.FadeColour(colours.Gray4, 400, Easing.OutQuint); syncManager.RemovePlayerClock(instance.GameplayClock); leaderboard.RemoveClock(userId); } public override bool OnBackButton() { // On a manual exit, set the player state back to idle. multiplayerClient.ChangeState(MultiplayerUserState.Idle); return base.OnBackButton(); } } }
using ClosedXML.Excel; using NUnit.Framework; using System; using System.IO; using System.Linq; namespace ClosedXML.Tests { /// <summary> /// This is a test class for XLRichStringTests and is intended /// to contain all XLRichStringTests Unit Tests /// </summary> [TestFixture] public class XLRichStringTests { [Test] public void AccessRichTextTest1() { IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet1"); IXLCell cell = ws.Cell(1, 1); cell.CreateRichText().AddText("12"); cell.DataType = XLDataType.Number; Assert.AreEqual(12.0, cell.GetDouble()); IXLRichText richText = cell.GetRichText(); Assert.AreEqual("12", richText.ToString()); richText.AddText("34"); Assert.AreEqual("1234", cell.GetString()); Assert.AreEqual(XLDataType.Number, cell.DataType); Assert.AreEqual(1234.0, cell.GetDouble()); } /// <summary> /// A test for AddText /// </summary> [Test] public void AddTextTest1() { IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet1"); IXLCell cell = ws.Cell(1, 1); IXLRichText richString = cell.CreateRichText(); string text = "Hello"; richString.AddText(text).SetBold().SetFontColor(XLColor.Red); Assert.AreEqual(cell.GetString(), text); Assert.AreEqual(cell.GetRichText().First().Bold, true); Assert.AreEqual(cell.GetRichText().First().FontColor, XLColor.Red); Assert.AreEqual(1, richString.Count); richString.AddText("World"); Assert.AreEqual(richString.First().Text, text, "Item in collection is not the same as the one returned"); } [Test] public void AddTextTest2() { IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet1"); IXLCell cell = ws.Cell(1, 1); Int32 number = 123; cell.SetValue(number).Style .Font.SetBold() .Font.SetFontColor(XLColor.Red); string text = number.ToString(); Assert.AreEqual(cell.GetRichText().ToString(), text); Assert.AreEqual(cell.GetRichText().First().Bold, true); Assert.AreEqual(cell.GetRichText().First().FontColor, XLColor.Red); Assert.AreEqual(1, cell.GetRichText().Count); cell.GetRichText().AddText("World"); Assert.AreEqual(cell.GetRichText().First().Text, text, "Item in collection is not the same as the one returned"); } [Test] public void AddTextTest3() { IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet1"); IXLCell cell = ws.Cell(1, 1); Int32 number = 123; cell.Value = number; cell.Style .Font.SetBold() .Font.SetFontColor(XLColor.Red); string text = number.ToString(); Assert.AreEqual(cell.GetRichText().ToString(), text); Assert.AreEqual(cell.GetRichText().First().Bold, true); Assert.AreEqual(cell.GetRichText().First().FontColor, XLColor.Red); Assert.AreEqual(1, cell.GetRichText().Count); cell.GetRichText().AddText("World"); Assert.AreEqual(cell.GetRichText().First().Text, text, "Item in collection is not the same as the one returned"); } /// <summary> /// A test for Clear /// </summary> [Test] public void ClearTest() { IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet1"); IXLRichText richString = ws.Cell(1, 1).GetRichText(); richString.AddText("Hello"); richString.AddText(" "); richString.AddText("World!"); richString.ClearText(); String expected = String.Empty; String actual = richString.ToString(); Assert.AreEqual(expected, actual); Assert.AreEqual(0, richString.Count); } [Test] public void CountTest() { IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet1"); IXLRichText richString = ws.Cell(1, 1).GetRichText(); richString.AddText("Hello"); richString.AddText(" "); richString.AddText("World!"); Assert.AreEqual(3, richString.Count); } [Test] public void HasRichTextTest1() { IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet1"); IXLCell cell = ws.Cell(1, 1); cell.GetRichText().AddText("123"); Assert.AreEqual(true, cell.HasRichText); cell.DataType = XLDataType.Text; Assert.AreEqual(true, cell.HasRichText); cell.DataType = XLDataType.Number; Assert.AreEqual(false, cell.HasRichText); cell.GetRichText().AddText("123"); Assert.AreEqual(true, cell.HasRichText); cell.Value = 123; Assert.AreEqual(false, cell.HasRichText); cell.GetRichText().AddText("123"); Assert.AreEqual(true, cell.HasRichText); cell.SetValue("123"); Assert.AreEqual(false, cell.HasRichText); } /// <summary> /// A test for Characters /// </summary> [Test] public void Substring_All_From_OneString() { IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet1"); IXLRichText richString = ws.Cell(1, 1).GetRichText(); richString.AddText("Hello"); IXLFormattedText<IXLRichText> actual = richString.Substring(0); Assert.AreEqual(richString.First(), actual.First()); Assert.AreEqual(1, actual.Count); actual.First().SetBold(); Assert.AreEqual(true, ws.Cell(1, 1).GetRichText().First().Bold); } [Test] public void Substring_All_From_ThreeStrings() { IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet1"); IXLRichText richString = ws.Cell(1, 1).GetRichText(); richString.AddText("Good Morning"); richString.AddText(" my "); richString.AddText("neighbors!"); IXLFormattedText<IXLRichText> actual = richString.Substring(0); Assert.AreEqual(richString.ElementAt(0), actual.ElementAt(0)); Assert.AreEqual(richString.ElementAt(1), actual.ElementAt(1)); Assert.AreEqual(richString.ElementAt(2), actual.ElementAt(2)); Assert.AreEqual(3, actual.Count); Assert.AreEqual(3, richString.Count); actual.First().SetBold(); Assert.AreEqual(true, ws.Cell(1, 1).GetRichText().First().Bold); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().ElementAt(1).Bold); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().Last().Bold); } [Test] public void Substring_From_OneString_End() { IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet1"); IXLRichText richString = ws.Cell(1, 1).GetRichText(); richString.AddText("Hello"); IXLFormattedText<IXLRichText> actual = richString.Substring(2); Assert.AreEqual(1, actual.Count); // substring was in one piece Assert.AreEqual(2, richString.Count); // The text was split because of the substring Assert.AreEqual("llo", actual.First().Text); Assert.AreEqual("He", richString.First().Text); Assert.AreEqual("llo", richString.Last().Text); actual.First().SetBold(); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().First().Bold); Assert.AreEqual(true, ws.Cell(1, 1).GetRichText().Last().Bold); richString.Last().SetItalic(); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().First().Italic); Assert.AreEqual(true, ws.Cell(1, 1).GetRichText().Last().Italic); Assert.AreEqual(true, actual.First().Italic); richString.SetFontSize(20); Assert.AreEqual(20, ws.Cell(1, 1).GetRichText().First().FontSize); Assert.AreEqual(20, ws.Cell(1, 1).GetRichText().Last().FontSize); Assert.AreEqual(20, actual.First().FontSize); } [Test] public void Substring_From_OneString_Middle() { IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet1"); IXLRichText richString = ws.Cell(1, 1).GetRichText(); richString.AddText("Hello"); IXLFormattedText<IXLRichText> actual = richString.Substring(2, 2); Assert.AreEqual(1, actual.Count); // substring was in one piece Assert.AreEqual(3, richString.Count); // The text was split because of the substring Assert.AreEqual("ll", actual.First().Text); Assert.AreEqual("He", richString.First().Text); Assert.AreEqual("ll", richString.ElementAt(1).Text); Assert.AreEqual("o", richString.Last().Text); actual.First().SetBold(); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().First().Bold); Assert.AreEqual(true, ws.Cell(1, 1).GetRichText().ElementAt(1).Bold); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().Last().Bold); richString.Last().SetItalic(); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().First().Italic); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().ElementAt(1).Italic); Assert.AreEqual(true, ws.Cell(1, 1).GetRichText().Last().Italic); Assert.AreEqual(false, actual.First().Italic); richString.SetFontSize(20); Assert.AreEqual(20, ws.Cell(1, 1).GetRichText().First().FontSize); Assert.AreEqual(20, ws.Cell(1, 1).GetRichText().ElementAt(1).FontSize); Assert.AreEqual(20, ws.Cell(1, 1).GetRichText().Last().FontSize); Assert.AreEqual(20, actual.First().FontSize); } [Test] public void Substring_From_OneString_Start() { IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet1"); IXLRichText richString = ws.Cell(1, 1).GetRichText(); richString.AddText("Hello"); IXLFormattedText<IXLRichText> actual = richString.Substring(0, 2); Assert.AreEqual(1, actual.Count); // substring was in one piece Assert.AreEqual(2, richString.Count); // The text was split because of the substring Assert.AreEqual("He", actual.First().Text); Assert.AreEqual("He", richString.First().Text); Assert.AreEqual("llo", richString.Last().Text); actual.First().SetBold(); Assert.AreEqual(true, ws.Cell(1, 1).GetRichText().First().Bold); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().Last().Bold); richString.Last().SetItalic(); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().First().Italic); Assert.AreEqual(true, ws.Cell(1, 1).GetRichText().Last().Italic); Assert.AreEqual(false, actual.First().Italic); richString.SetFontSize(20); Assert.AreEqual(20, ws.Cell(1, 1).GetRichText().First().FontSize); Assert.AreEqual(20, ws.Cell(1, 1).GetRichText().Last().FontSize); Assert.AreEqual(20, actual.First().FontSize); } [Test] public void Substring_From_ThreeStrings_End1() { IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet1"); IXLRichText richString = ws.Cell(1, 1).GetRichText(); richString.AddText("Good Morning"); richString.AddText(" my "); richString.AddText("neighbors!"); IXLFormattedText<IXLRichText> actual = richString.Substring(21); Assert.AreEqual(1, actual.Count); // substring was in one piece Assert.AreEqual(4, richString.Count); // The text was split because of the substring Assert.AreEqual("bors!", actual.First().Text); Assert.AreEqual("Good Morning", richString.ElementAt(0).Text); Assert.AreEqual(" my ", richString.ElementAt(1).Text); Assert.AreEqual("neigh", richString.ElementAt(2).Text); Assert.AreEqual("bors!", richString.ElementAt(3).Text); actual.First().SetBold(); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().ElementAt(0).Bold); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().ElementAt(1).Bold); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().ElementAt(2).Bold); Assert.AreEqual(true, ws.Cell(1, 1).GetRichText().ElementAt(3).Bold); richString.Last().SetItalic(); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().ElementAt(0).Italic); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().ElementAt(1).Italic); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().ElementAt(2).Italic); Assert.AreEqual(true, ws.Cell(1, 1).GetRichText().ElementAt(3).Italic); Assert.AreEqual(true, actual.First().Italic); richString.SetFontSize(20); Assert.AreEqual(20, ws.Cell(1, 1).GetRichText().ElementAt(0).FontSize); Assert.AreEqual(20, ws.Cell(1, 1).GetRichText().ElementAt(1).FontSize); Assert.AreEqual(20, ws.Cell(1, 1).GetRichText().ElementAt(2).FontSize); Assert.AreEqual(20, ws.Cell(1, 1).GetRichText().ElementAt(3).FontSize); Assert.AreEqual(20, actual.First().FontSize); } [Test] public void Substring_From_ThreeStrings_End2() { IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet1"); IXLRichText richString = ws.Cell(1, 1).GetRichText(); richString.AddText("Good Morning"); richString.AddText(" my "); richString.AddText("neighbors!"); IXLFormattedText<IXLRichText> actual = richString.Substring(13); Assert.AreEqual(2, actual.Count); Assert.AreEqual(4, richString.Count); // The text was split because of the substring Assert.AreEqual("my ", actual.ElementAt(0).Text); Assert.AreEqual("neighbors!", actual.ElementAt(1).Text); Assert.AreEqual("Good Morning", richString.ElementAt(0).Text); Assert.AreEqual(" ", richString.ElementAt(1).Text); Assert.AreEqual("my ", richString.ElementAt(2).Text); Assert.AreEqual("neighbors!", richString.ElementAt(3).Text); actual.ElementAt(1).SetBold(); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().ElementAt(0).Bold); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().ElementAt(1).Bold); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().ElementAt(2).Bold); Assert.AreEqual(true, ws.Cell(1, 1).GetRichText().ElementAt(3).Bold); richString.Last().SetItalic(); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().ElementAt(0).Italic); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().ElementAt(1).Italic); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().ElementAt(2).Italic); Assert.AreEqual(true, ws.Cell(1, 1).GetRichText().ElementAt(3).Italic); Assert.AreEqual(false, actual.ElementAt(0).Italic); Assert.AreEqual(true, actual.ElementAt(1).Italic); richString.SetFontSize(20); Assert.AreEqual(20, ws.Cell(1, 1).GetRichText().ElementAt(0).FontSize); Assert.AreEqual(20, ws.Cell(1, 1).GetRichText().ElementAt(1).FontSize); Assert.AreEqual(20, ws.Cell(1, 1).GetRichText().ElementAt(2).FontSize); Assert.AreEqual(20, ws.Cell(1, 1).GetRichText().ElementAt(3).FontSize); Assert.AreEqual(20, actual.ElementAt(0).FontSize); Assert.AreEqual(20, actual.ElementAt(1).FontSize); } [Test] public void Substring_From_ThreeStrings_Mid1() { IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet1"); IXLRichText richString = ws.Cell(1, 1).GetRichText(); richString.AddText("Good Morning"); richString.AddText(" my "); richString.AddText("neighbors!"); IXLFormattedText<IXLRichText> actual = richString.Substring(5, 10); Assert.AreEqual(2, actual.Count); Assert.AreEqual(5, richString.Count); // The text was split because of the substring Assert.AreEqual("Morning", actual.ElementAt(0).Text); Assert.AreEqual(" my", actual.ElementAt(1).Text); Assert.AreEqual("Good ", richString.ElementAt(0).Text); Assert.AreEqual("Morning", richString.ElementAt(1).Text); Assert.AreEqual(" my", richString.ElementAt(2).Text); Assert.AreEqual(" ", richString.ElementAt(3).Text); Assert.AreEqual("neighbors!", richString.ElementAt(4).Text); } [Test] public void Substring_From_ThreeStrings_Mid2() { IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet1"); IXLRichText richString = ws.Cell(1, 1).GetRichText(); richString.AddText("Good Morning"); richString.AddText(" my "); richString.AddText("neighbors!"); IXLFormattedText<IXLRichText> actual = richString.Substring(5, 15); Assert.AreEqual(3, actual.Count); Assert.AreEqual(5, richString.Count); // The text was split because of the substring Assert.AreEqual("Morning", actual.ElementAt(0).Text); Assert.AreEqual(" my ", actual.ElementAt(1).Text); Assert.AreEqual("neig", actual.ElementAt(2).Text); Assert.AreEqual("Good ", richString.ElementAt(0).Text); Assert.AreEqual("Morning", richString.ElementAt(1).Text); Assert.AreEqual(" my ", richString.ElementAt(2).Text); Assert.AreEqual("neig", richString.ElementAt(3).Text); Assert.AreEqual("hbors!", richString.ElementAt(4).Text); } [Test] public void Substring_From_ThreeStrings_Start1() { IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet1"); IXLRichText richString = ws.Cell(1, 1).GetRichText(); richString.AddText("Good Morning"); richString.AddText(" my "); richString.AddText("neighbors!"); IXLFormattedText<IXLRichText> actual = richString.Substring(0, 4); Assert.AreEqual(1, actual.Count); // substring was in one piece Assert.AreEqual(4, richString.Count); // The text was split because of the substring Assert.AreEqual("Good", actual.First().Text); Assert.AreEqual("Good", richString.ElementAt(0).Text); Assert.AreEqual(" Morning", richString.ElementAt(1).Text); Assert.AreEqual(" my ", richString.ElementAt(2).Text); Assert.AreEqual("neighbors!", richString.ElementAt(3).Text); actual.First().SetBold(); Assert.AreEqual(true, ws.Cell(1, 1).GetRichText().ElementAt(0).Bold); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().ElementAt(1).Bold); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().ElementAt(2).Bold); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().ElementAt(3).Bold); richString.First().SetItalic(); Assert.AreEqual(true, ws.Cell(1, 1).GetRichText().ElementAt(0).Italic); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().ElementAt(1).Italic); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().ElementAt(2).Italic); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().ElementAt(3).Italic); Assert.AreEqual(true, actual.First().Italic); richString.SetFontSize(20); Assert.AreEqual(20, ws.Cell(1, 1).GetRichText().ElementAt(0).FontSize); Assert.AreEqual(20, ws.Cell(1, 1).GetRichText().ElementAt(1).FontSize); Assert.AreEqual(20, ws.Cell(1, 1).GetRichText().ElementAt(2).FontSize); Assert.AreEqual(20, ws.Cell(1, 1).GetRichText().ElementAt(3).FontSize); Assert.AreEqual(20, actual.First().FontSize); } [Test] public void Substring_From_ThreeStrings_Start2() { IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet1"); IXLRichText richString = ws.Cell(1, 1).GetRichText(); richString.AddText("Good Morning"); richString.AddText(" my "); richString.AddText("neighbors!"); IXLFormattedText<IXLRichText> actual = richString.Substring(0, 15); Assert.AreEqual(2, actual.Count); Assert.AreEqual(4, richString.Count); // The text was split because of the substring Assert.AreEqual("Good Morning", actual.ElementAt(0).Text); Assert.AreEqual(" my", actual.ElementAt(1).Text); Assert.AreEqual("Good Morning", richString.ElementAt(0).Text); Assert.AreEqual(" my", richString.ElementAt(1).Text); Assert.AreEqual(" ", richString.ElementAt(2).Text); Assert.AreEqual("neighbors!", richString.ElementAt(3).Text); actual.ElementAt(1).SetBold(); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().ElementAt(0).Bold); Assert.AreEqual(true, ws.Cell(1, 1).GetRichText().ElementAt(1).Bold); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().ElementAt(2).Bold); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().ElementAt(3).Bold); richString.First().SetItalic(); Assert.AreEqual(true, ws.Cell(1, 1).GetRichText().ElementAt(0).Italic); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().ElementAt(1).Italic); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().ElementAt(2).Italic); Assert.AreEqual(false, ws.Cell(1, 1).GetRichText().ElementAt(3).Italic); Assert.AreEqual(true, actual.ElementAt(0).Italic); Assert.AreEqual(false, actual.ElementAt(1).Italic); richString.SetFontSize(20); Assert.AreEqual(20, ws.Cell(1, 1).GetRichText().ElementAt(0).FontSize); Assert.AreEqual(20, ws.Cell(1, 1).GetRichText().ElementAt(1).FontSize); Assert.AreEqual(20, ws.Cell(1, 1).GetRichText().ElementAt(2).FontSize); Assert.AreEqual(20, ws.Cell(1, 1).GetRichText().ElementAt(3).FontSize); Assert.AreEqual(20, actual.ElementAt(0).FontSize); Assert.AreEqual(20, actual.ElementAt(1).FontSize); } [Test] public void Substring_IndexOutsideRange1() { IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet1"); IXLRichText richString = ws.Cell(1, 1).GetRichText(); richString.AddText("Hello"); Assert.That(() => richString.Substring(50), Throws.TypeOf<IndexOutOfRangeException>()); } [Test] public void Substring_IndexOutsideRange2() { IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet1"); IXLRichText richString = ws.Cell(1, 1).GetRichText(); richString.AddText("Hello"); richString.AddText("World"); Assert.That(() => richString.Substring(50), Throws.TypeOf<IndexOutOfRangeException>()); } [Test] public void Substring_IndexOutsideRange3() { IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet1"); IXLRichText richString = ws.Cell(1, 1).GetRichText(); richString.AddText("Hello"); Assert.That(() => richString.Substring(1, 10), Throws.TypeOf<IndexOutOfRangeException>()); } [Test] public void Substring_IndexOutsideRange4() { IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet1"); IXLRichText richString = ws.Cell(1, 1).GetRichText(); richString.AddText("Hello"); richString.AddText("World"); Assert.That(() => richString.Substring(5, 20), Throws.TypeOf<IndexOutOfRangeException>()); } /// <summary> /// A test for ToString /// </summary> [Test] public void ToStringTest() { IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet1"); IXLRichText richString = ws.Cell(1, 1).GetRichText(); richString.AddText("Hello"); richString.AddText(" "); richString.AddText("World"); string expected = "Hello World"; string actual = richString.ToString(); Assert.AreEqual(expected, actual); richString.AddText("!"); expected = "Hello World!"; actual = richString.ToString(); Assert.AreEqual(expected, actual); richString.ClearText(); expected = String.Empty; actual = richString.ToString(); Assert.AreEqual(expected, actual); } [Test(Description = "See #1361")] public void CanClearInlinedRichText() { using (var outputStream = new MemoryStream()) { using (var inputStream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Other\InlinedRichText\ChangeRichText\inputfile.xlsx"))) using (var workbook = new XLWorkbook(inputStream)) { workbook.Worksheets.First().Cell("A1").Value = ""; workbook.SaveAs(outputStream); } using (var wb = new XLWorkbook(outputStream)) { Assert.AreEqual("", wb.Worksheets.First().Cell("A1").Value); } } } [Test] public void CanChangeInlinedRichText() { void testRichText(IXLRichText richText) { Assert.IsNotNull(richText); Assert.IsTrue(richText.Any()); Assert.AreEqual("3", richText.ElementAt(2).Text); Assert.AreEqual(XLColor.Red, richText.ElementAt(2).FontColor); } using (var outputStream = new MemoryStream()) { using (var inputStream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Other\InlinedRichText\ChangeRichText\inputfile.xlsx"))) using (var workbook = new XLWorkbook(inputStream)) { var richText = workbook.Worksheets.First().Cell("A1").GetRichText(); testRichText(richText); richText.AddText(" - changed"); workbook.SaveAs(outputStream); } using (var wb = new XLWorkbook(outputStream)) { var cell = wb.Worksheets.First().Cell("A1"); Assert.IsFalse(cell.ShareString); Assert.IsTrue(cell.HasRichText); var rt = cell.GetRichText(); Assert.AreEqual("Year (range: 3 yrs) - changed", rt.ToString()); testRichText(rt); } } } [Test] public void ClearInlineRichTextWhenRelevant() { using (var ms = new MemoryStream()) { TestHelper.CreateAndCompare(() => { using (var wb = new XLWorkbook()) { var ws = wb.AddWorksheet(); var cell = ws.FirstCell(); cell.GetRichText().AddText("Bold").SetBold().AddText(" and red").SetBold().SetFontColor(XLColor.Red); cell.ShareString = false; //wb.SaveAs(ms); wb.SaveAs(ms); } ms.Seek(0, SeekOrigin.Begin); var wb2 = new XLWorkbook(ms); { var ws = wb2.Worksheets.First(); var cell = ws.FirstCell(); cell.FormulaA1 = "=1 + 2"; wb2.SaveAs(ms); } ms.Seek(0, SeekOrigin.Begin); return wb2; }, @"Other\InlinedRichText\ChangeRichTextToFormula\output.xlsx"); } } } }
//----------------------------------------------------------------------- // <copyright file="TcpSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using Akka.Actor; using Akka.IO; using Akka.Pattern; using Akka.Streams.Dsl; using Akka.Streams.TestKit; using Akka.Streams.TestKit.Tests; using FluentAssertions; using Xunit; using Xunit.Abstractions; using Tcp = Akka.Streams.Dsl.Tcp; namespace Akka.Streams.Tests.IO { public class TcpSpec : TcpHelper { public TcpSpec(ITestOutputHelper helper) : base("akka.stream.materializer.subscription-timeout.timeout = 2s", helper) { } [Fact(Skip="Fix me")] public void Outgoing_TCP_stream_must_work_in_the_happy_case() { this.AssertAllStagesStopped(() => { var testData = ByteString.Create(new byte[] {1, 2, 3, 4, 5}); var server = new Server(this); var tcpReadProbe = new TcpReadProbe(this); var tcpWriteProbe = new TcpWriteProbe(this); Source.FromPublisher(tcpWriteProbe.PublisherProbe) .Via(Sys.TcpStream().OutgoingConnection(server.Address)) .To(Sink.FromSubscriber(tcpReadProbe.SubscriberProbe)) .Run(Materializer); var serverConnection = server.WaitAccept(); ValidateServerClientCommunication(testData, serverConnection, tcpReadProbe, tcpWriteProbe); tcpWriteProbe.Close(); tcpReadProbe.Close(); server.Close(); }, Materializer); } [Fact(Skip = "Fix me")] public void Outgoing_TCP_stream_must_be_able_to_write_a_sequence_of_ByteStrings() { var server = new Server(this); var testInput = Enumerable.Range(0, 256).Select(i => ByteString.Create(new[] {Convert.ToByte(i)})); var expectedOutput = ByteString.Create(Enumerable.Range(0, 256).Select(Convert.ToByte).ToArray()); Source.From(testInput) .Via(Sys.TcpStream().OutgoingConnection(server.Address)) .To(Sink.Ignore<ByteString>()) .Run(Materializer); var serverConnection = server.WaitAccept(); serverConnection.Read(256); serverConnection.WaitRead().ShouldBeEquivalentTo(expectedOutput); } [Fact(Skip = "Fix me")] public void Outgoing_TCP_stream_must_be_able_to_read_a_sequence_of_ByteStrings() { var server = new Server(this); var testInput = Enumerable.Range(0, 255).Select(i => ByteString.Create(new[] { Convert.ToByte(i) })); var expectedOutput = ByteString.Create(Enumerable.Range(0, 255).Select(Convert.ToByte).ToArray()); var idle = new TcpWriteProbe(this); //Just register an idle upstream var resultFuture = Source.FromPublisher(idle.PublisherProbe) .Via(Sys.TcpStream().OutgoingConnection(server.Address)) .RunAggregate(ByteString.Empty, (acc, input) => acc + input, Materializer); var serverConnection = server.WaitAccept(); foreach (var input in testInput) serverConnection.Write(input); serverConnection.ConfirmedClose(); resultFuture.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); resultFuture.Result.ShouldBeEquivalentTo(expectedOutput); } [Fact] public void Outgoing_TCP_stream_must_fail_the_materialized_task_when_the_connection_fails() { this.AssertAllStagesStopped(() => { var tcpWriteProbe = new TcpWriteProbe(this); var task = Source.FromPublisher(tcpWriteProbe.PublisherProbe) .ViaMaterialized( Sys.TcpStream() .OutgoingConnection(new DnsEndPoint("example.com", 666), connectionTimeout: TimeSpan.FromSeconds(1)), Keep.Right) .ToMaterialized(Sink.Ignore<ByteString>(), Keep.Left) .Run(Materializer); task.Invoking(t => t.Wait(TimeSpan.FromSeconds(3))) .ShouldThrow<Exception>() .And.Message.Should() .Contain("Connection failed"); }, Materializer); } [Fact(Skip = "Fix me")] public void Outgoing_TCP_stream_must_work_when_client_closes_write_then_remote_closes_write() { this.AssertAllStagesStopped(() => { var testData = ByteString.Create(new byte[] { 1, 2, 3, 4, 5 }); var server = new Server(this); var tcpWriteProbe = new TcpWriteProbe(this); var tcpReadProbe = new TcpReadProbe(this); Source.FromPublisher(tcpWriteProbe.PublisherProbe) .Via(Sys.TcpStream().OutgoingConnection(server.Address)) .To(Sink.FromSubscriber(tcpReadProbe.SubscriberProbe)) .Run(Materializer); var serverConnection = server.WaitAccept(); // Client can still write tcpWriteProbe.Write(testData); serverConnection.Read(5); serverConnection.WaitRead().ShouldBeEquivalentTo(testData); // Close client side write tcpWriteProbe.Close(); serverConnection.ExpectClosed(Akka.IO.Tcp.PeerClosed.Instance); // Server can still write serverConnection.Write(testData); tcpReadProbe.Read(5).ShouldBeEquivalentTo(testData); // Close server side write serverConnection.ConfirmedClose(); tcpReadProbe.SubscriberProbe.ExpectComplete(); serverConnection.ExpectClosed(Akka.IO.Tcp.ConfirmedClosed.Instance); serverConnection.ExpectTerminated(); }, Materializer); } [Fact(Skip = "Fix me")] public void Outgoing_TCP_stream_must_work_when_remote_closes_write_then_client_closes_write() { this.AssertAllStagesStopped(() => { var testData = ByteString.Create(new byte[] {1, 2, 3, 4, 5}); var server = new Server(this); var tcpWriteProbe = new TcpWriteProbe(this); var tcpReadProbe = new TcpReadProbe(this); Source.FromPublisher(tcpWriteProbe.PublisherProbe) .Via(Sys.TcpStream().OutgoingConnection(server.Address)) .To(Sink.FromSubscriber(tcpReadProbe.SubscriberProbe)) .Run(Materializer); var serverConnection = server.WaitAccept(); // Server can still write serverConnection.Write(testData); tcpReadProbe.Read(5).ShouldBeEquivalentTo(testData); // Close server side write serverConnection.ConfirmedClose(); tcpReadProbe.SubscriberProbe.ExpectComplete(); // Client can still write tcpWriteProbe.Write(testData); serverConnection.Read(5); serverConnection.WaitRead().ShouldBeEquivalentTo(testData); // Close clint side write tcpWriteProbe.Close(); serverConnection.ExpectClosed(Akka.IO.Tcp.ConfirmedClosed.Instance); serverConnection.ExpectTerminated(); }, Materializer); } [Fact(Skip = "Fix me")] public void Outgoing_TCP_stream_must_work_when_client_closes_read_then_client_closes_write() { this.AssertAllStagesStopped(() => { var testData = ByteString.Create(new byte[] { 1, 2, 3, 4, 5 }); var server = new Server(this); var tcpWriteProbe = new TcpWriteProbe(this); var tcpReadProbe = new TcpReadProbe(this); Source.FromPublisher(tcpWriteProbe.PublisherProbe) .Via(Sys.TcpStream().OutgoingConnection(server.Address)) .To(Sink.FromSubscriber(tcpReadProbe.SubscriberProbe)) .Run(Materializer); var serverConnection = server.WaitAccept(); // Server can still write serverConnection.Write(testData); tcpReadProbe.Read(5).ShouldBeEquivalentTo(testData); // Close client side read tcpReadProbe.TcpReadSubscription.Value.Cancel(); // Client can still write tcpWriteProbe.Write(testData); serverConnection.Read(5); serverConnection.WaitRead().ShouldBeEquivalentTo(testData); // Close client side write tcpWriteProbe.Close(); // Need a write on the server side to detect the close event AwaitAssert(() => { serverConnection.Write(testData); serverConnection.ExpectClosed(c=>c.IsErrorClosed, TimeSpan.FromMilliseconds(500)); }, TimeSpan.FromSeconds(5)); serverConnection.ExpectTerminated(); }, Materializer); } [Fact(Skip = "Fix me")] public void Outgoing_TCP_stream_must_work_when_client_closes_read_then_server_closes_write_then_client_closes_write() { this.AssertAllStagesStopped(() => { var testData = ByteString.Create(new byte[] { 1, 2, 3, 4, 5 }); var server = new Server(this); var tcpWriteProbe = new TcpWriteProbe(this); var tcpReadProbe = new TcpReadProbe(this); Source.FromPublisher(tcpWriteProbe.PublisherProbe) .Via(Sys.TcpStream().OutgoingConnection(server.Address)) .To(Sink.FromSubscriber(tcpReadProbe.SubscriberProbe)) .Run(Materializer); var serverConnection = server.WaitAccept(); // Server can still write serverConnection.Write(testData); tcpReadProbe.Read(5).ShouldBeEquivalentTo(testData); // Close client side read tcpReadProbe.TcpReadSubscription.Value.Cancel(); // Client can still write tcpWriteProbe.Write(testData); serverConnection.Read(5); serverConnection.WaitRead().ShouldBeEquivalentTo(testData); serverConnection.ConfirmedClose(); // Close clint side write tcpWriteProbe.Close(); serverConnection.ExpectClosed(Akka.IO.Tcp.ConfirmedClosed.Instance); serverConnection.ExpectTerminated(); }, Materializer); } [Fact(Skip = "Fix me")] public void Outgoing_TCP_stream_must_shut_everything_down_if_client_signals_error() { this.AssertAllStagesStopped(() => { var testData = ByteString.Create(new byte[] { 1, 2, 3, 4, 5 }); var server = new Server(this); var tcpWriteProbe = new TcpWriteProbe(this); var tcpReadProbe = new TcpReadProbe(this); Source.FromPublisher(tcpWriteProbe.PublisherProbe) .Via(Sys.TcpStream().OutgoingConnection(server.Address)) .To(Sink.FromSubscriber(tcpReadProbe.SubscriberProbe)) .Run(Materializer); var serverConnection = server.WaitAccept(); // Server can still write serverConnection.Write(testData); tcpReadProbe.Read(5).ShouldBeEquivalentTo(testData); // Client can still write tcpWriteProbe.Write(testData); serverConnection.Read(5); serverConnection.WaitRead().ShouldBeEquivalentTo(testData); // Cause error tcpWriteProbe.TcpWriteSubscription.Value.SendError(new IllegalStateException("test")); tcpReadProbe.SubscriberProbe.ExpectError(); serverConnection.ExpectClosed(c=>c.IsErrorClosed); serverConnection.ExpectTerminated(); }, Materializer); } [Fact(Skip = "Fix me")] public void Outgoing_TCP_stream_must_shut_everything_down_if_client_signals_error_after_remote_has_closed_write() { this.AssertAllStagesStopped(() => { var testData = ByteString.Create(new byte[] { 1, 2, 3, 4, 5 }); var server = new Server(this); var tcpWriteProbe = new TcpWriteProbe(this); var tcpReadProbe = new TcpReadProbe(this); Source.FromPublisher(tcpWriteProbe.PublisherProbe) .Via(Sys.TcpStream().OutgoingConnection(server.Address)) .To(Sink.FromSubscriber(tcpReadProbe.SubscriberProbe)) .Run(Materializer); var serverConnection = server.WaitAccept(); // Server can still write serverConnection.Write(testData); tcpReadProbe.Read(5).ShouldBeEquivalentTo(testData); // Close remote side write serverConnection.ConfirmedClose(); tcpReadProbe.SubscriberProbe.ExpectComplete(); // Client can still write tcpWriteProbe.Write(testData); serverConnection.Read(5); serverConnection.WaitRead().ShouldBeEquivalentTo(testData); tcpWriteProbe.TcpWriteSubscription.Value.SendError(new IllegalStateException("test")); serverConnection.ExpectClosed(c => c.IsErrorClosed); serverConnection.ExpectTerminated(); }, Materializer); } [Fact(Skip = "Fix me")] public void Outgoing_TCP_stream_must_shut_down_both_streams_when_connection_is_aborted_remotely() { this.AssertAllStagesStopped(() => { // Client gets a PeerClosed event and does not know that the write side is also closed var server = new Server(this); var tcpWriteProbe = new TcpWriteProbe(this); var tcpReadProbe = new TcpReadProbe(this); Source.FromPublisher(tcpWriteProbe.PublisherProbe) .Via(Sys.TcpStream().OutgoingConnection(server.Address)) .To(Sink.FromSubscriber(tcpReadProbe.SubscriberProbe)) .Run(Materializer); var serverConnection = server.WaitAccept(); serverConnection.Abort(); tcpReadProbe.SubscriberProbe.ExpectSubscriptionAndError(); tcpWriteProbe.TcpWriteSubscription.Value.ExpectCancellation(); serverConnection.ExpectTerminated(); }, Materializer); } [Fact(Skip = "Fix me")] public void Outgoing_TCP_stream_must_materialize_correctly_when_used_in_multiple_flows() { var testData = ByteString.Create(new byte[] { 1, 2, 3, 4, 5 }); var server = new Server(this); var tcpWriteProbe1 = new TcpWriteProbe(this); var tcpReadProbe1 = new TcpReadProbe(this); var tcpWriteProbe2 = new TcpWriteProbe(this); var tcpReadProbe2 = new TcpReadProbe(this); var outgoingConnection = new Tcp().CreateExtension(Sys as ExtendedActorSystem).OutgoingConnection(server.Address); var conn1F = Source.FromPublisher(tcpWriteProbe1.PublisherProbe) .ViaMaterialized(outgoingConnection, Keep.Both) .To(Sink.FromSubscriber(tcpReadProbe1.SubscriberProbe)) .Run(Materializer).Item2; var serverConnection1 = server.WaitAccept(); var conn2F = Source.FromPublisher(tcpWriteProbe2.PublisherProbe) .ViaMaterialized(outgoingConnection, Keep.Both) .To(Sink.FromSubscriber(tcpReadProbe2.SubscriberProbe)) .Run(Materializer).Item2; var serverConnection2 = server.WaitAccept(); ValidateServerClientCommunication(testData, serverConnection1, tcpReadProbe1, tcpWriteProbe1); ValidateServerClientCommunication(testData, serverConnection2, tcpReadProbe2, tcpWriteProbe2); conn1F.Wait(TimeSpan.FromSeconds(1)).Should().BeTrue(); conn2F.Wait(TimeSpan.FromSeconds(1)).Should().BeTrue(); var conn1 = conn1F.Result; var conn2 = conn2F.Result; // Since we have already communicated over the connections we can have short timeouts for the tasks ((IPEndPoint) conn1.RemoteAddress).Port.Should().Be(((IPEndPoint) server.Address).Port); ((IPEndPoint) conn2.RemoteAddress).Port.Should().Be(((IPEndPoint) server.Address).Port); ((IPEndPoint) conn1.LocalAddress).Port.Should().NotBe(((IPEndPoint) conn2.LocalAddress).Port); tcpWriteProbe1.Close(); tcpReadProbe1.Close(); server.Close(); } [Fact(Skip = "Fix me")] public void Outgoing_TCP_stream_must_properly_full_close_if_requested() { this.AssertAllStagesStopped(() => { var serverAddress = TestUtils.TemporaryServerAddress(); var writeButIgnoreRead = Flow.FromSinkAndSource(Sink.Ignore<ByteString>(), Source.Single(ByteString.FromString("Early response")), Keep.Right); var task = Sys.TcpStream() .Bind(serverAddress.Address.ToString(), serverAddress.Port) .ToMaterialized( Sink.ForEach<Tcp.IncomingConnection>(conn => conn.Flow.Join(writeButIgnoreRead).Run(Materializer)), Keep.Left) .Run(Materializer); task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); var binding = task.Result; var t = Source.Maybe<ByteString>() .Via(Sys.TcpStream().OutgoingConnection(serverAddress.Address.ToString(), serverAddress.Port)) .ToMaterialized(Sink.Aggregate<ByteString, ByteString>(ByteString.Empty, (s, s1) => s + s1), Keep.Both) .Run(Materializer); var promise = t.Item1; var result = t.Item2; result.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); result.Result.ShouldBeEquivalentTo(ByteString.FromString("Early response")); promise.SetResult(null); // close client upstream, no more data binding.Unbind(); }, Materializer); } [Fact(Skip = "Fix me")] public void Outgoing_TCP_stream_must_Echo_should_work_even_if_server_is_in_full_close_mode() { var serverAddress = TestUtils.TemporaryServerAddress(); var task = Sys.TcpStream() .Bind(serverAddress.Address.ToString(), serverAddress.Port) .ToMaterialized( Sink.ForEach<Tcp.IncomingConnection>(conn => conn.Flow.Join(Flow.Create<ByteString>())), Keep.Left) .Run(Materializer); task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); var binding = task.Result; var result = Source.From(Enumerable.Repeat(0, 1000) .Select(i => ByteString.Create(new[] {Convert.ToByte(i)}))) .Via(Sys.TcpStream().OutgoingConnection(serverAddress)) .RunAggregate(0, (i, s) => i + s.Count, Materializer); result.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); result.Result.Should().Be(1000); binding.Unbind(); } [Fact(Skip = "Fix me")] public void Outgoing_TCP_stream_must_handle_when_connection_actor_terminates_unexpectedly() { var system2 = ActorSystem.Create("system2"); var mat2 = ActorMaterializer.Create(system2); var serverAddress = TestUtils.TemporaryServerAddress(); var binding = system2.TcpStream() .BindAndHandle(Flow.Create<ByteString>(), mat2, serverAddress.Address.ToString(), serverAddress.Port); var result = Source.Maybe<ByteString>() .Via(system2.TcpStream().OutgoingConnection(serverAddress)) .RunAggregate(0, (i, s) => i + s.Count, mat2); // Getting rid of existing connection actors by using a blunt instrument system2.ActorSelection(system2.Tcp().Path/"selectors"/"$b"/"*").Tell(Kill.Instance); result.Invoking(r => r.Wait(TimeSpan.FromSeconds(3))).ShouldThrow<StreamTcpException>(); binding.Result.Unbind().Wait(); system2.Terminate().Wait(); } [Fact(Skip = "Fix me")] public void Outgoing_TCP_stream_must_not_thrown_on_unbind_after_system_has_been_shut_down() { var sys2 = ActorSystem.Create("shutdown-test-system"); var mat2 = sys2.Materializer(); try { var address = TestUtils.TemporaryServerAddress(); var bindingTask = sys2.TcpStream() .BindAndHandle(Flow.Create<ByteString>(), mat2, address.Address.ToString(), address.Port); // Ensure server is running bindingTask.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); // and is possible to communicate with var t = Source.Single(ByteString.FromString("")) .Via(sys2.TcpStream().OutgoingConnection(address)) .RunWith(Sink.Ignore<ByteString>(), mat2); t.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); sys2.Terminate().Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); var binding = bindingTask.Result; binding.Unbind().Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); } finally { sys2.Terminate().Wait(TimeSpan.FromSeconds(5)); } } private void ValidateServerClientCommunication(ByteString testData, ServerConnection serverConnection, TcpReadProbe readProbe, TcpWriteProbe writeProbe) { serverConnection.Write(testData); serverConnection.Read(5); readProbe.Read(5).ShouldBeEquivalentTo(testData); writeProbe.Write(testData); serverConnection.WaitRead().ShouldBeEquivalentTo(testData); } private Sink<Tcp.IncomingConnection, Task> EchoHandler() => Sink.ForEach<Tcp.IncomingConnection>(c => c.Flow.Join(Flow.Create<ByteString>()).Run(Materializer)); [Fact(Skip = "Fix me")] public void Tcp_listen_stream_must_be_able_to_implement_echo() { var serverAddress = TestUtils.TemporaryServerAddress(); var t = Sys.TcpStream() .Bind(serverAddress.Address.ToString(), serverAddress.Port) .ToMaterialized(EchoHandler(), Keep.Both) .Run(Materializer); var bindingFuture = t.Item1; var echoServerFinish = t.Item2; // make sure that the server has bound to the socket bindingFuture.Wait(100).Should().BeTrue(); var binding = bindingFuture.Result; var testInput = Enumerable.Range(0, 255).Select(i => ByteString.Create(new[] {Convert.ToByte(i)})).ToList(); var expectedOutput = testInput.Aggregate(ByteString.Empty, (agg, b) => agg.Concat(b)); var resultFuture = Source.From(testInput) .Via(Sys.TcpStream().OutgoingConnection(serverAddress)) .RunAggregate(ByteString.Empty, (agg, b) => agg.Concat(b), Materializer); resultFuture.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); resultFuture.Result.ShouldBeEquivalentTo(expectedOutput); binding.Unbind().Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); echoServerFinish.Wait(TimeSpan.FromSeconds(1)).Should().BeTrue(); } [Fact(Skip = "Fix me")] public void Tcp_listen_stream_must_work_with_a_chain_of_echoes() { var serverAddress = TestUtils.TemporaryServerAddress(); var t = Sys.TcpStream() .Bind(serverAddress.Address.ToString(), serverAddress.Port) .ToMaterialized(EchoHandler(), Keep.Both) .Run(Materializer); var bindingFuture = t.Item1; var echoServerFinish = t.Item2; // make sure that the server has bound to the socket bindingFuture.Wait(100).Should().BeTrue(); var binding = bindingFuture.Result; var echoConnection = Sys.TcpStream().OutgoingConnection(serverAddress); var testInput = Enumerable.Range(0, 255).Select(i => ByteString.Create(new[] { Convert.ToByte(i) })).ToList(); var expectedOutput = testInput.Aggregate(ByteString.Empty, (agg, b) => agg.Concat(b)); var resultFuture = Source.From(testInput) .Via(echoConnection) // The echoConnection is reusable .Via(echoConnection) .Via(echoConnection) .Via(echoConnection) .RunAggregate(ByteString.Empty, (agg, b) => agg.Concat(b), Materializer); resultFuture.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); resultFuture.Result.ShouldBeEquivalentTo(expectedOutput); binding.Unbind().Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); echoServerFinish.Wait(TimeSpan.FromSeconds(1)).Should().BeTrue(); } [Fact(Skip = "On Windows unbinding is not immediate")] public void Tcp_listen_stream_must_bind_and_unbind_correctly() { EventFilter.Exception<BindFailedException>().Expect(2, () => { // if (Helpers.isWindows) { // info("On Windows unbinding is not immediate") // pending //} //val address = temporaryServerAddress() //val probe1 = TestSubscriber.manualProbe[Tcp.IncomingConnection]() //val bind = Tcp(system).bind(address.getHostName, address.getPort) // TODO getHostString in Java7 //// Bind succeeded, we have a local address //val binding1 = Await.result(bind.to(Sink.fromSubscriber(probe1)).run(), 3.second) //probe1.expectSubscription() //val probe2 = TestSubscriber.manualProbe[Tcp.IncomingConnection]() //val binding2F = bind.to(Sink.fromSubscriber(probe2)).run() //probe2.expectSubscriptionAndError(BindFailedException) //val probe3 = TestSubscriber.manualProbe[Tcp.IncomingConnection]() //val binding3F = bind.to(Sink.fromSubscriber(probe3)).run() //probe3.expectSubscriptionAndError() //a[BindFailedException] shouldBe thrownBy { Await.result(binding2F, 1.second) } //a[BindFailedException] shouldBe thrownBy { Await.result(binding3F, 1.second) } //// Now unbind first //Await.result(binding1.unbind(), 1.second) //probe1.expectComplete() //val probe4 = TestSubscriber.manualProbe[Tcp.IncomingConnection]() //// Bind succeeded, we have a local address //val binding4 = Await.result(bind.to(Sink.fromSubscriber(probe4)).run(), 3.second) //probe4.expectSubscription() //// clean up //Await.result(binding4.unbind(), 1.second) }); } [Fact(Skip = "Fix me")] public void Tcp_listen_stream_must_not_shut_down_connections_after_the_connection_stream_cacelled() { this.AssertAllStagesStopped(() => { var serverAddress = TestUtils.TemporaryServerAddress(); Sys.TcpStream() .Bind(serverAddress.Address.ToString(), serverAddress.Port) .Take(1).RunForeach(c => { Thread.Sleep(1000); c.Flow.Join(Flow.Create<ByteString>()).Run(Materializer); }, Materializer); var total = Source.From( Enumerable.Range(0, 1000).Select(_ => ByteString.Create(new byte[] {0}))) .Via(Sys.TcpStream().OutgoingConnection(serverAddress)) .RunAggregate(0, (i, s) => i + s.Count, Materializer); total.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); total.Result.Should().Be(1000); }, Materializer); } [Fact(Skip = "Fix me")] public void Tcp_listen_stream_must_shut_down_properly_even_if_some_accepted_connection_Flows_have_not_been_subscribed_to () { this.AssertAllStagesStopped(() => { var serverAddress = TestUtils.TemporaryServerAddress(); var firstClientConnected = new TaskCompletionSource<NotUsed>(); var takeTwoAndDropSecond = Flow.Create<Tcp.IncomingConnection>().Select(c => { firstClientConnected.TrySetResult(NotUsed.Instance); return c; }).Grouped(2).Take(1).Select(e => e.First()); Sys.TcpStream() .Bind(serverAddress.Address.ToString(), serverAddress.Port) .Via(takeTwoAndDropSecond) .RunForeach(c => c.Flow.Join(Flow.Create<ByteString>()).Run(Materializer), Materializer); var folder = Source.From(Enumerable.Range(0, 100).Select(_ => ByteString.Create(new byte[] {0}))) .Via(Sys.TcpStream().OutgoingConnection(serverAddress)) .Aggregate(0, (i, s) => i + s.Count) .ToMaterialized(Sink.First<int>(), Keep.Right); var total = folder.Run(Materializer); firstClientConnected.Task.Wait(TimeSpan.FromSeconds(2)).Should().BeTrue(); var rejected = folder.Run(Materializer); total.Wait(TimeSpan.FromSeconds(10)).Should().BeTrue(); total.Result.Should().Be(100); rejected.Wait(TimeSpan.FromSeconds(5)).Should().BeTrue(); rejected.Exception.Flatten().InnerExceptions.Any(e => e is StreamTcpException).Should().BeTrue(); }, Materializer); } } }
////////////////////////////////////////////////////////////////////////////////////// // // // This file was generated by a tool. It would be a bad idea to make changes to it. // // // ////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; namespace Rock.Rock.StaticDependencyInjection { internal sealed partial class CompositionRoot : CompositionRootBase { internal CompositionRoot() { } } internal abstract class CompositionRootBase { private readonly ConcurrentDictionary<Tuple<string, bool>, ICollection<Type>> _candidateTypesCache; private readonly ConcurrentDictionary<string, ConcurrentDictionary<Tuple<string, string, bool, bool>, IEnumerable<string>>> _candidateTypeNamesByTargetTypeNameCache; protected CompositionRootBase() { _candidateTypesCache = new ConcurrentDictionary<Tuple<string, bool>, ICollection<Type>>(); _candidateTypeNamesByTargetTypeNameCache = new ConcurrentDictionary<string, ConcurrentDictionary<Tuple<string, string, bool, bool>, IEnumerable<string>>>(); } /// <summary> /// Import the types for this library by calling one of the import methods: /// <see cref="ImportSingle{TTargetType}"/>, <see cref="ImportSingle{TTargetType,TFactoryType}"/>, /// <see cref="ImportFirst{TTargetType}"/>, <see cref="ImportFirst{TTargetType,TFactoryType}"/>, /// <see cref="ImportMultiple{TTargetType}"/>, or <see cref="ImportMultiple{TTargetType, TFactoryType}"/>. /// </summary> public abstract void Bootstrap(); /// <summary> /// Gets a value indicating whether static dependency injection is enabled. /// </summary> public virtual bool IsEnabled { get { return true; } } /// <summary> /// Called when an error condition occurrs. /// </summary> /// <param name="message">A message describing the error condition.</param> /// <param name="exception">The <see cref="Exception"/> that caused the error condition. Can be null.</param> /// <param name="import">An <see cref="ImportInfo"/> object that describes the import operation that failed.</param> protected virtual void OnError(string message, Exception exception, ImportInfo import) { var sb = new StringBuilder(); if (message != null) { sb.AppendLine("Message: " + message).AppendLine(); } if (import != null) { sb.AppendLine("Import: " + import.ToString()).AppendLine(); } if (exception != null) { sb.AppendLine(exception.ToString()).AppendLine(); } var debugMessage = sb.ToString(); Debug.WriteLine(debugMessage); } /// <summary> /// Return a collection of metadata objects that describe the export operations for a type. /// </summary> /// <param name="type">The type to get export metadata.</param> /// <returns>A collection of metadata objects that describe export operations.</returns> protected virtual IEnumerable<ExportInfo> GetExportInfos(Type type) { yield return new ExportInfo(type); } /// <summary> /// Return an object that defines various options. /// </summary> protected virtual ImportOptions GetDefaultImportOptions() { return new ImportOptions(); } /// <summary> /// Imports the type specified by <typeparamref name="TTargetType"/>. When a single /// class with a public parameterless constructor is found that implements or /// inherits from <typeparamref name="TTargetType"/>, then an instance of that class /// will be created and passed to the <paramref name="importAction"/> parameter callback. /// </summary> /// <typeparam name="TTargetType"> /// The type to import. An object of this type will be passed to the /// <paramref name="importAction"/> parameter callback. /// </typeparam> /// <param name="importAction"> /// A callback function to invoke when an implementation of /// <typeparamref name="TTargetType"/> is created. /// </param> /// <param name="importName"> /// The name of this import operation. If not null, exported classes without /// a matching name are excluded. /// </param> /// <param name="options"> /// The import options to use. If null or not provided, the value returned by /// <see cref="GetDefaultImportOptions"/> is returned. /// </param> protected void ImportSingle<TTargetType>( Action<TTargetType> importAction, string importName = null, ImportOptions options = null) where TTargetType : class { var import = GetImportInfo<TTargetType>(importName, options); try { ImportSingleType( importAction, import, type => CreateInstance<TTargetType>(type, import)); } catch (Exception ex) { var message = string.Format("Unexpected error in ImportSingle<{0}>.", typeof(TTargetType)); OnError(message, ex, import); } } /// <summary> /// Imports the type specified by <typeparamref name="TTargetType"/>. When a single /// class with a public parameterless constructor is found that implements or /// inherits from either <typeparamref name="TTargetType"/> or /// <typeparamref name="TFactoryType"/>, then an instance of that class is created. /// If that instance is a <typeparamref name="TTargetType"/>, than that instance will be /// passed to the <paramref name="importAction"/> callback. If the instance is a /// <typeparamref name="TFactoryType"/>, then an instance of /// <typeparamref name="TTargetType"/> is obtained by using the /// <paramref name="getTarget"/> function and passed to the /// <paramref name="importAction"/> callback. /// </summary> /// <typeparam name="TTargetType"> /// The type to import. An object of this type will be passed to the /// <paramref name="importAction"/> parameter callback. /// </typeparam> /// <typeparam name="TFactoryType"> /// A type that exposes a method or property that can be invoked to obtain an instance /// of <typeparamref name="TTargetType"/>. /// </typeparam> /// <param name="importAction"> /// A callback function to invoke when an implementation of <typeparamref name="TTargetType"/> is created. /// </param> /// <param name="getTarget"> /// A function used to obtain an instance of <typeparamref name="TTargetType"/> /// by using an instance of <typeparamref name="TFactoryType"/>. /// </param> /// <param name="importName"> /// The name of this import operation. If not null, exported classes without a matching name are excluded. /// </param> /// <param name="options"> /// The import options to use. If null or not provided, the value returned by /// <see cref="GetDefaultImportOptions"/> is returned. /// </param> protected void ImportSingle<TTargetType, TFactoryType>( Action<TTargetType> importAction, Func<TFactoryType, TTargetType> getTarget, string importName = null, ImportOptions options = null) where TTargetType : class where TFactoryType : class { var import = GetImportInfo<TTargetType>(importName, options, typeof(TFactoryType)); try { ImportSingleType( importAction, import, type => CreateInstance(type, getTarget, import)); } catch (Exception ex) { var message = string.Format("Unexpected error in ImportSingle<{0}, {1}>.", typeof(TTargetType), typeof(TFactoryType)); OnError(message, ex, import); } } /// <summary> /// Imports the type specified by <typeparamref name="TTargetType"/>. When any class /// with a public parameterless constructor is found that implements or inherits from /// <typeparamref name="TTargetType"/>, then the one with the highest priority will be /// created and passed to the <paramref name="importAction"/> parameter callback. /// </summary> /// <typeparam name="TTargetType"> /// The type to import. An object of this type will be passed to the /// <paramref name="importAction"/> parameter callback. /// </typeparam> /// <param name="importAction"> /// A callback function to invoke when an implementation of <typeparamref name="TTargetType"/> is created. /// </param> /// <param name="importName"> /// The name of this import operation. If not null, exported classes without a matching name are excluded. /// </param> /// <param name="options"> /// The import options to use. If null or not provided, the value returned by /// <see cref="GetDefaultImportOptions"/> is returned. /// </param> protected void ImportFirst<TTargetType>( Action<TTargetType> importAction, string importName = null, ImportOptions options = null) where TTargetType : class { var import = GetImportInfo<TTargetType>(importName, options); try { ImportFirstType(importAction, GetInstances<TTargetType>(import), import); } catch (Exception ex) { var message = string.Format("Unexpected error in ImportFirst<{0}>.", typeof(TTargetType)); OnError(message, ex, import); } } /// <summary> /// Imports the type specified by <typeparamref name="TTargetType"/>. When any /// class with a public parameterless constructor is found that implements or /// inherits from either <typeparamref name="TTargetType"/> or /// <typeparamref name="TFactoryType"/>, then an instance of the highest priority /// class is created. If that instance is a <typeparamref name="TTargetType"/>, than that /// instance will be passed to the <paramref name="importAction"/> callback. If the /// instance is a <typeparamref name="TFactoryType"/>, then an instance of /// <typeparamref name="TTargetType"/> is obtained by using the /// <paramref name="getTarget"/> function and passed to the /// <paramref name="importAction"/> callback. /// </summary> /// <typeparam name="TTargetType"> /// The type to import. An object of this type will be passed to the /// <paramref name="importAction"/> parameter callback. /// </typeparam> /// <typeparam name="TFactoryType"> /// A type that exposes a method or property that can be invoked to obtain an instance /// of <typeparamref name="TTargetType"/>. /// </typeparam> /// <param name="importAction"> /// A callback function to invoke when an implementation of <typeparamref name="TTargetType"/> is created. /// </param> /// <param name="getTarget"> /// A function used to obtain an instance of <typeparamref name="TTargetType"/> /// by using an instance of <typeparamref name="TFactoryType"/>. /// </param> /// <param name="importName"> /// The name of this import operation. If not null, exported classes without a matching name are excluded. /// </param> /// <param name="options"> /// The import options to use. If null or not provided, the value returned by /// <see cref="GetDefaultImportOptions"/> is returned. /// </param> protected void ImportFirst<TTargetType, TFactoryType>( Action<TTargetType> importAction, Func<TFactoryType, TTargetType> getTarget, string importName = null, ImportOptions options = null) where TTargetType : class where TFactoryType : class { var import = GetImportInfo<TTargetType>(importName, options, typeof(TFactoryType)); try { ImportFirstType(importAction, GetInstances(getTarget, import), import); } catch (Exception ex) { var message = string.Format("Unexpected error in ImportFirst<{0}, {1}>.", typeof(TTargetType), typeof(TFactoryType)); OnError(message, ex, import); } } /// <summary> /// Imports the type specified by <typeparamref name="TTargetType"/> for many /// implementations. When zero to many classes with a public parameterless /// constructor are found that implements or inherits from /// <typeparamref name="TTargetType"/>, then an instances of those class will be /// created and passed to the <paramref name="importAction"/> parameter callback. /// </summary> /// <typeparam name="TTargetType"> /// The type to import. Objects of this type will be passed to the /// <paramref name="importAction"/> parameter callback. /// </typeparam> /// <param name="importAction"> /// A callback function to invoke when a implementations of /// <typeparamref name="TTargetType"/> are created. /// </param> /// <param name="importName"> /// The name of this import operation. If not null, exported classes without a matching name are excluded. /// </param> /// <param name="options"> /// The import options to use. If null or not provided, the value returned by /// <see cref="GetDefaultImportOptions"/> is returned. /// </param> protected void ImportMultiple<TTargetType>( Action<IEnumerable<TTargetType>> importAction, string importName = null, ImportOptions options = null) where TTargetType : class { var import = GetImportInfo<TTargetType>(importName, options); List<TTargetType> instances; try { instances = GetInstances<TTargetType>(import).ToList(); } catch (Exception ex) { var message = string.Format("Unexpected error in ImportMultiple<{0}>.", typeof(TTargetType)); OnError(message, ex, import); return; } try { importAction(instances); } catch (Exception ex) { OnError("An error occurred in the 'importAction' callback.", ex, import); } } /// <summary> /// Imports the type specified by <typeparamref name="TTargetType"/> for many /// implementations. When zero to many classes with a public parameterless /// constructor are found that implements or inherits from either /// <typeparamref name="TTargetType"/> or <typeparamref name="TFactoryType"/>, /// then instances of those classes are created. If an instance is a /// <typeparamref name="TTargetType"/>, than that instance will be passed as part of a /// collection to the <paramref name="importAction"/> callback. If an instance is a /// <typeparamref name="TFactoryType"/>, then an instance of /// <typeparamref name="TTargetType"/> is obtained by using the /// <paramref name="getTarget"/> function and passed to the /// <paramref name="importAction"/> callback. /// </summary> /// <typeparam name="TTargetType"> /// The type to import. Objects of this type will be passed to the /// <paramref name="importAction"/> parameter callback. /// </typeparam> /// <typeparam name="TFactoryType"> /// A type that exposes a method or property that can be invoked to obtain an instance /// of <typeparamref name="TTargetType"/>. /// </typeparam> /// <param name="importAction"> /// A callback function to invoke when a implementations of /// <typeparamref name="TTargetType"/> are created. /// </param> /// <param name="getTarget"> /// A function used to obtain an instance of <typeparamref name="TTargetType"/> /// by using an instance of <typeparamref name="TFactoryType"/>. /// </param> /// <param name="importName"> /// The name of this import operation. If not null, exported classes without a matching name are excluded. /// </param> /// <param name="options"> /// The import options to use. If null or not provided, the value returned by /// <see cref="GetDefaultImportOptions"/> is returned. /// </param> protected void ImportMultiple<TTargetType, TFactoryType>( Action<IEnumerable<TTargetType>> importAction, Func<TFactoryType, TTargetType> getTarget, string importName = null, ImportOptions options = null) where TTargetType : class where TFactoryType : class { var import = GetImportInfo<TTargetType>(importName, options, typeof(TFactoryType)); List<TTargetType> instances; try { instances = GetInstances(getTarget, import).ToList(); } catch (Exception ex) { var message = string.Format("Unexpected error in ImportMultiple<{0}, {1}>.", typeof(TTargetType), typeof(TFactoryType)); OnError(message, ex, import); return; } try { importAction(instances); } catch (Exception ex) { OnError("An error occurred in the 'importAction' callback.", ex, import); } } private IEnumerable<TTargetType> GetInstances<TTargetType>(ImportInfo import) where TTargetType : class { return GetInstances(import, type => CreateInstance<TTargetType>(type, import)); } private IEnumerable<TTargetType> GetInstances<TTargetType, TFactoryType>( Func<TFactoryType, TTargetType> getTarget, ImportInfo import) where TTargetType : class where TFactoryType : class { return GetInstances(import, type => CreateInstance(type, getTarget, import)); } private ImportInfo GetImportInfo<TTargetType>( string importName, ImportOptions options, Type factoryType = null) where TTargetType : class { return new ImportInfo( importName, typeof(TTargetType), factoryType, options ?? GetDefaultImportOptions()); } private void ImportSingleType<TTargetType>( Action<TTargetType> importAction, ImportInfo import, Func<Type, TTargetType> createInstance) where TTargetType : class { var candidateTypeNames = GetCandidateTypeNames(import); var prioritizedGroupsOfCandidateTypes = GetPrioritizedGroupsOfCandidateTypes(candidateTypeNames, import).GetEnumerator(); // If any candidate types were found, the enumerator will advance. if (prioritizedGroupsOfCandidateTypes.MoveNext()) { var highestPriorityCandidateTypes = prioritizedGroupsOfCandidateTypes.Current; var bestCandidateType = ChooseCandidateType(highestPriorityCandidateTypes, import); if (bestCandidateType == null) { var message = string.Format( "Unable to import a single instance of type '{0}' - more than one export " + "with the same highest priority was discovered: {1}.", typeof(TTargetType), string.Join(", ", highestPriorityCandidateTypes.Select(t => "'" + t + "'"))); OnError(message, null, import); } else { var instance = createInstance(bestCandidateType); try { importAction(instance); } catch (Exception ex) { OnError("An error occurred in the 'importAction' callback.", ex, import); } } } } private void ImportFirstType<TTargetType>( Action<TTargetType> importAction, IEnumerable<TTargetType> instances, ImportInfo import) where TTargetType : class { var instance = instances.FirstOrDefault(); if (instance != null) { try { importAction(instance); } catch (Exception ex) { OnError("An error occurred in the 'importAction' callback.", ex, import); } } } private IEnumerable<TTargetType> GetInstances<TTargetType>( ImportInfo import, Func<Type, TTargetType> createInstance) where TTargetType : class { var candidateTypeNames = GetCandidateTypeNames(import); var prioritizedGroupsOfCandidateTypes = GetPrioritizedGroupsOfCandidateTypes( candidateTypeNames, import); return ( from candidateTypes in prioritizedGroupsOfCandidateTypes from candidateType in candidateTypes select createInstance(candidateType)) .Where(instance => instance != null); } private TTargetType CreateInstance<TTargetType>(Type candidateType, ImportInfo import) where TTargetType : class { object instance; try { instance = Instantiate(candidateType); } catch (Exception ex) { OnError(string.Format( "An error occurred while creating an instance of the '{0}' type.", candidateType), ex, import); return null; } var target = instance as TTargetType; if (target != null) { return target; } OnError(string.Format( "The type of the created instance, '{0}', is not assignable to the target type, '{1}'.", instance.GetType(), typeof(TTargetType)), null, import); return null; } private TTargetType CreateInstance<TTargetType, TFactoryType>( Type candidateType, Func<TFactoryType, TTargetType> getTarget, ImportInfo import) where TTargetType : class where TFactoryType : class { object instance; try { instance = Instantiate(candidateType); } catch (Exception ex) { OnError(string.Format( "An error occurred while creating an instance of the '{0}' type.", candidateType), ex, import); return null; } var factory = instance as TFactoryType; if (factory != null) { try { return getTarget(factory); } catch (Exception ex) { OnError("An error occurred in the 'getTarget' callback.", ex, import); return null; } } var target = instance as TTargetType; if (target != null) { return target; } OnError(string.Format( "The type of the created instance, '{0}', is not assignable to the target type, '{1}'.", instance.GetType(), typeof(TTargetType)), null, import); return null; } private static object Instantiate(Type candidateType) { if (candidateType.GetConstructor(Type.EmptyTypes) != null) { return Activator.CreateInstance(candidateType); } var ctor = candidateType.GetConstructors() .OrderByDescending(c => c.GetParameters().Length) .First(c => c.GetParameters().All(HasDefaultValue)); var args = ctor.GetParameters().Select(p => p.DefaultValue).ToArray(); return Activator.CreateInstance(candidateType, args); } private IEnumerable<IList<Type>> GetPrioritizedGroupsOfCandidateTypes( IEnumerable<string> candidateTypeNames, ImportInfo import) { Func<Type, bool> isPreferredType; if (import.FactoryType == null) { isPreferredType = type => false; } else { if (import.Options.PreferTTargetType) { isPreferredType = GetIsTargetTypeFunc(import.TargetType, import.Options.AllowNonPublicClasses); } else { isPreferredType = GetIsTargetTypeFunc(import.FactoryType, import.Options.AllowNonPublicClasses); } } var prioritizedGroupsOfCandidateTypes = candidateTypeNames.SelectMany(GetExportInfos) .Where(export => export != null && !export.Disabled && AreCompatible(import, export)) .GroupBy(x => x.Priority) .OrderByDescending(g => g.Key) .Select(g => g.OrderByDescending(export => isPreferredType(export.TargetClass)) .ThenBy(export => export, import.Options.ExportComparer) .ToList()) .ToList(); var uniqueExports = new List<ExportInfo>(); var groupsToRemove = new List<List<ExportInfo>>(); foreach (var group in prioritizedGroupsOfCandidateTypes) { var exportsToRemove = new List<ExportInfo>(); foreach (var export in group) { if (uniqueExports.Any(uniqueExport => export.TargetClass == uniqueExport.TargetClass && export.Name == uniqueExport.Name)) { exportsToRemove.Add(export); } else { uniqueExports.Add(export); } } foreach (var export in exportsToRemove) { group.Remove(export); } if (group.Count == 0) { groupsToRemove.Add(group); } } foreach (var group in groupsToRemove) { prioritizedGroupsOfCandidateTypes.Remove(group); } return prioritizedGroupsOfCandidateTypes .Select(group => group.Select(g => g.TargetClass).ToList()).ToList(); } private static bool AreCompatible(ImportInfo import, ExportInfo export) { if (!import.Options.IncludeNamedExportsFromUnnamedImports && export.Name != null && import.Name == null) { return false; } return export.Name == import.Name || import.Name == null; } private static Type ChooseCandidateType( IList<Type> candidateTypes, ImportInfo import) { if (candidateTypes.Count == 1) { return candidateTypes[0]; } if (import.FactoryType != null) { var data = candidateTypes.Select(type => { var interfaces = type.GetInterfaces(); return new { Type = type, IsTarget = interfaces.Any(i => i.AssemblyQualifiedName == import.TargetTypeName), IsFactory = interfaces.Any(i => i.AssemblyQualifiedName == import.FactoryTypeName) }; }).ToList(); if (import.Options.PreferTTargetType) { if ((data.Count(x => x.IsTarget) == 1) && (data.Count(x => x.IsFactory && !x.IsTarget) == (data.Count - 1))) { return data.Single(x => x.IsTarget).Type; } } else { if ((data.Count(x => x.IsFactory) == 1) && (data.Count(x => x.IsTarget && !x.IsFactory) == (data.Count - 1))) { return data.Single(x => x.IsFactory).Type; } } } return null; } private IEnumerable<ExportInfo> GetExportInfos(string assemblyQualifiedName) { try { var type = Type.GetType(assemblyQualifiedName); if (type == null) { return null; } return GetExportInfos(type); } catch { return null; } } private IEnumerable<string> GetCandidateTypeNames(ImportInfo import) { var candidateTypeNamesCache = _candidateTypeNamesByTargetTypeNameCache.GetOrAdd( import.TargetTypeName, _ => new ConcurrentDictionary<Tuple<string, string, bool, bool>, IEnumerable<string>>()); var key = Tuple.Create( import.TargetTypeName, import.FactoryTypeName, import.Options.AllowNonPublicClasses, import.Options.IncludeTypesFromThisAssembly); var candidateTypeNames = candidateTypeNamesCache.GetOrAdd( key, _ => { var isTargetType = GetIsTargetTypeFunc(import.TargetType, import.Options.AllowNonPublicClasses); if (import.FactoryType != null) { var isFactoryType = GetIsTargetTypeFunc(import.FactoryType, import.Options.AllowNonPublicClasses); var isTargetTypeLocal = isTargetType; isTargetType = type => isTargetTypeLocal(type) || isFactoryType(type); } var candidateTypes = _candidateTypesCache.GetOrAdd( Tuple.Create(string.Join("|", import.Options.DirectoryPaths), import.Options.IncludeTypesFromThisAssembly), __ => GetCandidateTypes(import.Options.DirectoryPaths, import.Options.IncludeTypesFromThisAssembly)); return candidateTypes .Where(isTargetType) .Select(t => t.AssemblyQualifiedName) .ToList(); }); return candidateTypeNames; } private static Func<Type, bool> GetIsTargetTypeFunc(Type targetType, bool allowNonPublicClasses) { var targetTypeName = targetType.AssemblyQualifiedName; if (targetTypeName == null) { return typeInQuestion => false; } if (targetType.IsInterface) { return typeInQuestion => (typeInQuestion.IsPublic || allowNonPublicClasses) && typeInQuestion.GetInterfaces().Any(i => i.AssemblyQualifiedName == targetTypeName); } if (targetType.IsClass && !targetType.IsSealed) { return typeInQuestion => { var type = typeInQuestion; while (type != null) { if (type.AssemblyQualifiedName == targetTypeName) { return true; } type = type.BaseType; } return false; }; } return typeInQuestion => false; } private ICollection<Type> GetCandidateTypes(IEnumerable<string> directoryPaths, bool includeTypesFromThisAssembly) { try { AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += AppDomainOnReflectionOnlyAssemblyResolve; return GetAssemblyFiles(directoryPaths, includeTypesFromThisAssembly).SelectMany(x => LoadCandidateTypes(x, includeTypesFromThisAssembly)).ToList(); } finally { AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= AppDomainOnReflectionOnlyAssemblyResolve; } } private static Assembly AppDomainOnReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args) { return Assembly.ReflectionOnlyLoad(args.Name); } private static IEnumerable<string> GetAssemblyFiles(IEnumerable<string> directoryPaths, bool includeTypesFromThisAssembly) { foreach (var directoryPath in directoryPaths) { if (!Directory.Exists(directoryPath)) { continue; } IEnumerable<string> dllFiles; try { dllFiles = Directory.EnumerateFiles(directoryPath, "*.dll"); } catch { dllFiles = Enumerable.Empty<string>(); } IEnumerable<string> exeFiles; try { exeFiles = Directory.EnumerateFiles(directoryPath, "*.exe"); } catch { exeFiles = Enumerable.Empty<string>(); } foreach (var file in dllFiles.Concat(exeFiles)) { yield return file; } } } private static IEnumerable<Type> LoadCandidateTypes(string assemblyFile, bool includeTypesFromThisAssembly) { try { var assembly = Assembly.ReflectionOnlyLoadFrom(assemblyFile); if (!includeTypesFromThisAssembly && assembly.FullName == typeof(CompositionRootBase).Assembly.FullName) { return Enumerable.Empty<Type>(); } return GetTypesSafely(assembly) .Where(t => t.IsClass && !t.IsAbstract && t.AssemblyQualifiedName != null && HasDefaultishConstructor(t)); } catch { return Enumerable.Empty<Type>(); } } private static IEnumerable<Type> GetTypesSafely(Assembly assembly) { try { return assembly.GetTypes(); } catch (ReflectionTypeLoadException ex) { return ex.Types.Where(t => t != null); } } private static bool HasDefaultishConstructor(Type type) { try { var constructors = GetConstructors(type); return constructors.Any( ctor => { var parameters = ctor.GetParameters(); return parameters.Length == 0 || parameters.All(HasDefaultValue); }); } catch { return false; } } private static IEnumerable<ConstructorInfo> GetConstructors(Type type) { // Retreiving constructors via TypeInfo.DeclaredConstructors is less likely to throw an // an exception, but TypeInfo doesn't exist in .NET 4.0. So use reflection to attempt // to try to get a TypeInfo. If we're unable to get it, just return type.GetConstructors() var introspectionExtensionsType = Type.GetType("System.Reflection.IntrospectionExtensions, mscorlib"); if (introspectionExtensionsType == null) { return type.GetConstructors(); } var getTypeInfo = introspectionExtensionsType.GetMethod("GetTypeInfo"); if (getTypeInfo == null) { return type.GetConstructors(); } dynamic typeInfo = getTypeInfo.Invoke(null, new object[] { type }); IEnumerable<ConstructorInfo> constructors = typeInfo.DeclaredConstructors; return constructors.Where(ctor => ctor.IsPublic); } private static bool HasDefaultValue(ParameterInfo parameter) { const ParameterAttributes hasDefaultValue = ParameterAttributes.HasDefault | ParameterAttributes.Optional; return (parameter.Attributes & hasDefaultValue) == hasDefaultValue; } } /// <summary> /// An internal helper class that makes it easier for your library to implement /// the static default pattern that Rock.StaticDependencyInjection is meant to /// support. /// </summary> /// <typeparam name="T">A type that requires a default instance.</typeparam> internal sealed class Default<T> { private readonly Lazy<T> _defaultInstance; private Lazy<T> _currentInstance; /// <summary> /// Initializes a new instance of the <see cref="Default{T}"/> class. /// </summary> /// <param name="createDefaultInstance"> /// A function that describes how to create the the object returned by the /// <see cref="DefaultInstance"/> property. /// </param> public Default(Func<T> createDefaultInstance) { _defaultInstance = new Lazy<T>(createDefaultInstance); _currentInstance = _defaultInstance; } /// <summary> /// Gets the default instance of <typeparamref name="T"/>. This value is /// returned by the <see cref="Current"/> property when neither the /// <see cref="SetCurrent(System.Func{T})"/> nor <see cref="SetCurrent(T)"/> /// has been called. /// </summary> public T DefaultInstance { get { return _defaultInstance.Value; } } /// <summary> /// Gets the current value for an instance of type <typeparamref name="T"/>. /// </summary> public T Current { get { return _currentInstance.Value; } } /// <summary> /// Restores the value of the <see cref="Current"/> property to the value of /// the <see cref="DefaultInstance"/> property. /// </summary> public void RestoreDefault() { SetCurrent(null); } /// <summary> /// Sets the value of the <see cref="Current"/> property. If the /// <paramref name="getInstance"/> parameter is null, sets the value of the /// <see cref="Current"/> to the value of the <see cref="DefaultInstance"/> /// property. /// </summary> /// <param name="getInstance"> /// A function that returns the value for the <see cref="Current"/> property. /// </param> public void SetCurrent(Func<T> getInstance) { _currentInstance = getInstance == null ? _defaultInstance : new Lazy<T>(getInstance); } /// <summary> /// Sets the value of the <see cref="Current"/> property. If the /// <paramref name="instance"/> parameter is null, sets the value of the /// <see cref="Current"/> to the value of the <see cref="DefaultInstance"/> /// property. /// </summary> /// <param name="instance"> /// The value for the <see cref="Current"/> property. /// </param> public void SetCurrent(T instance) { _currentInstance = instance == null ? _defaultInstance : new Lazy<T>(() => instance); } } /// <summary> /// Provides information about an export. /// </summary> internal class ExportInfo { /// <summary> /// The default priority for an instance of <see cref="ExportInfo"/> if not specified. /// </summary> public const int DefaultPriority = -1; private readonly Type _targetClass; private readonly int _priority; /// <summary> /// Initializes a new instance of the <see cref="ExportInfo"/> class with /// a priority with the value of <see cref="DefaultPriority"/>. /// </summary> /// <param name="targetClass">The class to be exported.</param> public ExportInfo(Type targetClass) : this(targetClass, DefaultPriority) { } /// <summary> /// Initializes a new instance of the <see cref="ExportInfo"/> class. /// </summary> /// <param name="targetClass">The class to be exported.</param> /// <param name="priority"> /// The priority of the export, relative to the priority of other exports. /// </param> public ExportInfo(Type targetClass, int priority) { if (targetClass == null) { throw new ArgumentNullException("targetClass"); } if (targetClass.Assembly.ReflectionOnly) { targetClass = Type.GetType(targetClass.AssemblyQualifiedName); } _targetClass = targetClass; _priority = priority; } /// <summary> /// Gets the class to be exported. /// </summary> public Type TargetClass { get { return _targetClass; } } /// <summary> /// Gets the priority of the export, relative to the priority of other exports. /// The default value, if not specified in the constructor is negative one. /// This value is used during import operations to sort the discovered classes. /// </summary> public int Priority { get { return _priority; } } /// <summary> /// Gets or sets the name of the export. This value is compared against the /// name parameter in various import operations. /// </summary> public string Name { get; set; } /// <summary> /// Gets or sets a value indicating whether the type indicated by /// <see cref="TargetClass"/> should be excluded from consideration during an /// import operation. /// </summary> public bool Disabled { get; set; } } internal class ImportInfo { private readonly string _name; private readonly Type _targetType; private readonly Type _factoryType; private readonly ImportOptions _options; public ImportInfo( string name, Type targetType, Type factoryType, ImportOptions options) { _name = name; _targetType = targetType; _factoryType = factoryType; _options = options; } public string Name { get { return _name; } } public Type TargetType { get { return _targetType; } } public Type FactoryType { get { return _factoryType; } } public ImportOptions Options { get { return _options; } } public override string ToString() { var sb = new StringBuilder(); sb.AppendFormat(@"{{ ""Name"": {0}, ""TargetType"": {1}, ""FactoryType"": {2}, ""Options"": {3} }}", Name, TargetType, FactoryType, Options.ToString(" ")); return sb.ToString(); } internal string TargetTypeName { get { return TargetType.AssemblyQualifiedName; } } internal string FactoryTypeName { get { return _factoryType == null ? null : _factoryType.AssemblyQualifiedName; } } } /// <summary> /// Defines various options for an import operation. /// </summary> internal class ImportOptions { private string[] _directoryPaths = GetDefaultDirectoryPaths(); private IComparer<ExportInfo> _exportComparer = GetDefaultExportComparer(); /// <summary> /// Gets or sets a value indicating whether to allow non-public classes to be imported. /// Default value is false, indicating that only public classes will be included in an /// import operation. /// </summary> public bool AllowNonPublicClasses { get; set; } /// <summary> /// Gets or sets a value indicating whether a named export will be included from an /// unnamed import operation. Default value is false, indicating that named exports /// will not be used given an unnamed import. /// </summary> public bool IncludeNamedExportsFromUnnamedImports { get; set; } /// <summary> /// Gets or sets a value indicating whether, given equal priorities, an implementation /// of TTargetType will be chosen over an implementation of TFactoryType. Default /// value is false, indicating that TFactoryType will be preferred. /// </summary> public bool PreferTTargetType { get; set; } /// <summary> /// Gets or sets a value indicating whether types that are defined in this assembly /// should be considered from an import operation. Default value is false, indicating /// that types defined in this assembly will be excluded. /// </summary> public bool IncludeTypesFromThisAssembly { get; set; } /// <summary> /// Gets or sets the directory paths that are searched for an import operation. /// If not set, or set to null, the value returned will contain a single element: /// the value returned by AppDomain.CurrentDomain.BaseDirectory. /// </summary> public IEnumerable<string> DirectoryPaths { get { return _directoryPaths; } set { _directoryPaths = value != null ? value.OrderBy(x => x).ToArray() : GetDefaultDirectoryPaths(); } } /// <summary> /// Gets or sets a comparer to be used to differentiate between multiple /// exports with the same priority. If not set, or set to null, the value /// returned will be a comparer that sorts based on the assembly qualified /// name of the target class. /// </summary> public IComparer<ExportInfo> ExportComparer { get { return _exportComparer; } set { _exportComparer = value ?? GetDefaultExportComparer(); } } public override string ToString() { return ToString(""); } internal string ToString(string indent) { var sb = new StringBuilder(); sb.AppendFormat(@"{{ {6} ""AllowNonPublicClasses"": {0}, {6} ""IncludeNamedExportsFromUnnamedImports"": {1}, {6} ""PreferTTargetType"": {2}, {6} ""IncludeTypesFromThisAssembly"": {3}, {6} ""DirectoryPaths"": [{4}], {6} ""ExportComparer"": ""{5}"" {6}}}", AllowNonPublicClasses, IncludeNamedExportsFromUnnamedImports, PreferTTargetType, IncludeTypesFromThisAssembly, string.Join(",", DirectoryPaths), ExportComparer.GetType(), indent); return sb.ToString(); } /// <summary> /// Returns an array containing a single element: the value returned by /// AppDomain.CurrentDomain.BaseDirectory. /// </summary> private static string[] GetDefaultDirectoryPaths() { return new[] { AppDomain.CurrentDomain.BaseDirectory, Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin") }; } /// <summary> /// Gets a new instance of <see cref="TargetClassAssemblyQualifiedNameComparer"/>. /// </summary> private static IComparer<ExportInfo> GetDefaultExportComparer() { return new TargetClassAssemblyQualifiedNameComparer(); } private class TargetClassAssemblyQualifiedNameComparer : IComparer<ExportInfo> { public int Compare(ExportInfo lhs, ExportInfo rhs) { var lhsString = lhs.TargetClass.AssemblyQualifiedName ?? lhs.TargetClass.ToString(); var rhsString = rhs.TargetClass.AssemblyQualifiedName ?? rhs.TargetClass.ToString(); return lhsString.CompareTo(rhsString); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Numerics; using GraphQL.Conversion; using GraphQL.Instrumentation; using GraphQL.Introspection; using GraphQL.Resolvers; using GraphQL.Types.Relay; using GraphQL.Utilities; namespace GraphQL.Types { /// <summary> /// A class that represents a list of all the graph types utilized by a schema. /// Also provides lookup for all schema types and has algorithms for discovering them. /// <br/> /// NOTE: After creating an instance of this class, its contents cannot be changed. /// </summary> public class SchemaTypes : IEnumerable<IGraphType> { internal static readonly Dictionary<Type, Type> BuiltInScalarMappings = new Dictionary<Type, Type> { [typeof(int)] = typeof(IntGraphType), [typeof(long)] = typeof(LongGraphType), [typeof(BigInteger)] = typeof(BigIntGraphType), [typeof(double)] = typeof(FloatGraphType), [typeof(float)] = typeof(FloatGraphType), [typeof(decimal)] = typeof(DecimalGraphType), [typeof(string)] = typeof(StringGraphType), [typeof(bool)] = typeof(BooleanGraphType), [typeof(DateTime)] = typeof(DateTimeGraphType), #if NET6_0_OR_GREATER [typeof(DateOnly)] = typeof(DateOnlyGraphType), [typeof(TimeOnly)] = typeof(TimeOnlyGraphType), #endif [typeof(DateTimeOffset)] = typeof(DateTimeOffsetGraphType), [typeof(TimeSpan)] = typeof(TimeSpanSecondsGraphType), [typeof(Guid)] = typeof(IdGraphType), [typeof(short)] = typeof(ShortGraphType), [typeof(ushort)] = typeof(UShortGraphType), [typeof(ulong)] = typeof(ULongGraphType), [typeof(uint)] = typeof(UIntGraphType), [typeof(byte)] = typeof(ByteGraphType), [typeof(sbyte)] = typeof(SByteGraphType), [typeof(Uri)] = typeof(UriGraphType), }; // Introspection types http://spec.graphql.org/June2018/#sec-Schema-Introspection private Dictionary<Type, IGraphType> _introspectionTypes; // Standard scalars https://graphql.github.io/graphql-spec/June2018/#sec-Scalars private readonly Dictionary<Type, IGraphType> _builtInScalars = new IGraphType[] { new StringGraphType(), new BooleanGraphType(), new FloatGraphType(), new IntGraphType(), new IdGraphType(), } .ToDictionary(t => t.GetType()); // .NET custom scalars private readonly Dictionary<Type, IGraphType> _builtInCustomScalars = new IGraphType[] { new DateGraphType(), #if NET6_0_OR_GREATER new DateOnlyGraphType(), new TimeOnlyGraphType(), #endif new DateTimeGraphType(), new DateTimeOffsetGraphType(), new TimeSpanSecondsGraphType(), new TimeSpanMillisecondsGraphType(), new DecimalGraphType(), new UriGraphType(), new GuidGraphType(), new ShortGraphType(), new UShortGraphType(), new UIntGraphType(), new LongGraphType(), new BigIntGraphType(), new ULongGraphType(), new ByteGraphType(), new SByteGraphType(), } .ToDictionary(t => t.GetType()); private TypeCollectionContext _context; private INameConverter _nameConverter; /// <summary> /// Initializes a new instance with no types registered. /// </summary> #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. protected SchemaTypes() #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. { } /// <summary> /// Initializes a new instance for the specified schema, and with the specified type resolver. /// </summary> /// <param name="schema">A schema for which this instance is created.</param> /// <param name="serviceProvider">A service provider used to resolve graph types.</param> #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. public SchemaTypes(ISchema schema, IServiceProvider serviceProvider) #pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. { Initialize(schema, serviceProvider); } private bool _initialized = false; /// <summary> /// Initializes the instance for the specified schema, and with the specified type resolver. /// </summary> /// <param name="schema">A schema for which this instance is created.</param> /// <param name="serviceProvider">A service provider used to resolve graph types.</param> protected void Initialize(ISchema schema, IServiceProvider serviceProvider) { if (schema == null) throw new ArgumentNullException(nameof(schema)); if (serviceProvider == null) throw new ArgumentNullException(nameof(serviceProvider)); if (_initialized) throw new InvalidOperationException("SchemaTypes has already been initialized."); _initialized = true; var types = GetSchemaTypes(schema, serviceProvider); var typeMappingsEnumerable = schema.TypeMappings ?? throw new ArgumentNullException(nameof(schema) + "." + nameof(ISchema.TypeMappings)); var typeMappings = typeMappingsEnumerable is List<(Type, Type)> typeMappingsList ? typeMappingsList : typeMappingsEnumerable.ToList(); var directives = schema.Directives ?? throw new ArgumentNullException(nameof(schema) + "." + nameof(ISchema.Directives)); _typeDictionary = new Dictionary<Type, IGraphType>(); _introspectionTypes = CreateIntrospectionTypes(schema.Features.AppliedDirectives, schema.Features.RepeatableDirectives); _context = new TypeCollectionContext( type => BuildNamedType(type, t => _builtInScalars.TryGetValue(t, out var graphType) ? graphType : _introspectionTypes.TryGetValue(t, out graphType) ? graphType : (IGraphType)Activator.CreateInstance(t)!), (name, type, ctx) => { SetGraphType(name, type); ctx.AddType(name, type, null!); }, typeMappings); // Add manually-added scalar types. To allow overriding of built-in scalars, these must be added // prior to adding any other types (including introspection types). foreach (var type in types) { if (type is ScalarGraphType) AddType(type, _context); } // Add introspection types. Note that introspection types rely on the // CamelCaseNameConverter, as some fields are defined in pascal case - e.g. Field(x => x.Name) _nameConverter = CamelCaseNameConverter.Instance; foreach (var introspectionType in _introspectionTypes.Values) AddType(introspectionType, _context); // set the name converter properly _nameConverter = schema.NameConverter ?? CamelCaseNameConverter.Instance; var ctx = new TypeCollectionContext( t => _builtInScalars.TryGetValue(t, out var graphType) ? graphType : (IGraphType)serviceProvider.GetRequiredService(t), (name, graphType, context) => { if (this[name] == null) { AddType(graphType, context); } }, typeMappings); foreach (var type in types) { if (type is not ScalarGraphType) AddType(type, ctx); } // these fields must not have their field names translated by INameConverter; see HandleField HandleField(null, SchemaMetaFieldType, ctx, false); HandleField(null, TypeMetaFieldType, ctx, false); HandleField(null, TypeNameMetaFieldType, ctx, false); foreach (var directive in directives) { HandleDirective(directive, ctx); } ApplyTypeReferences(); Debug.Assert(ctx.InFlightRegisteredTypes.Count == 0); _typeDictionary = null!; // not needed once initialization is complete } private static IEnumerable<IGraphType> GetSchemaTypes(ISchema schema, IServiceProvider serviceProvider) { // Manually registered AdditionalTypeInstances and AdditionalTypes should be handled first. // This is necessary for the correct processing of overridden built-in scalars. foreach (var instance in schema.AdditionalTypeInstances) yield return instance; foreach (var type in schema.AdditionalTypes) yield return (IGraphType)serviceProvider.GetRequiredService(type.GetNamedType()); //TODO: According to the specification, Query is a required type. But if you uncomment these lines, then the mass of tests begin to fail, because they do not set Query. // if (Query == null) // throw new InvalidOperationException("Query root type must be provided. See https://graphql.github.io/graphql-spec/June2018/#sec-Schema-Introspection"); if (schema.Query != null) yield return schema.Query; if (schema.Mutation != null) yield return schema.Mutation; if (schema.Subscription != null) yield return schema.Subscription; } private static Dictionary<Type, IGraphType> CreateIntrospectionTypes(bool allowAppliedDirectives, bool allowRepeatable) { return (allowAppliedDirectives ? new IGraphType[] { new __DirectiveLocation(), new __DirectiveArgument(), new __AppliedDirective(), new __TypeKind(), new __EnumValue(true), new __Directive(true, allowRepeatable), new __Field(true), new __InputValue(true), new __Type(true), new __Schema(true) } : new IGraphType[] { new __DirectiveLocation(), //new __DirectiveArgument(), forbidden //new __AppliedDirective(), forbidden new __TypeKind(), new __EnumValue(false), new __Directive(false, allowRepeatable), new __Field(false), new __InputValue(false), new __Type(false), new __Schema(false) }) .ToDictionary(t => t.GetType()); } /// <summary> /// Returns a dictionary that relates type names to graph types. /// </summary> protected internal virtual Dictionary<string, IGraphType> Dictionary { get; } = new Dictionary<string, IGraphType>(); private Dictionary<Type, IGraphType> _typeDictionary; /// <inheritdoc cref="IEnumerable.GetEnumerator"/> public IEnumerator<IGraphType> GetEnumerator() => Dictionary.Values.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); /// <summary> /// Gets the count of all the graph types utilized by the schema. /// </summary> public int Count => Dictionary.Count; private IGraphType BuildNamedType(Type type, Func<Type, IGraphType> resolver) => type.BuildNamedType(t => FindGraphType(t) ?? resolver(t)); /// <summary> /// Applies all delegates specified by the middleware builder to the schema. /// <br/><br/> /// When applying to the schema, modifies the resolver of each field of each graph type adding required behavior. /// Therefore, as a rule, this method should be called only once - during schema initialization. /// </summary> public void ApplyMiddleware(IFieldMiddlewareBuilder fieldMiddlewareBuilder) { var transform = (fieldMiddlewareBuilder ?? throw new ArgumentNullException(nameof(fieldMiddlewareBuilder))).Build(); // allocation free optimization if no middlewares are defined if (transform != null) { ApplyMiddleware(transform); } } /// <summary> /// Applies the specified middleware transform delegate to the schema. /// <br/><br/> /// When applying to the schema, modifies the resolver of each field of each graph type adding required behavior. /// Therefore, as a rule, this method should be called only once - during schema initialization. /// </summary> public void ApplyMiddleware(Func<FieldMiddlewareDelegate, FieldMiddlewareDelegate> transform) { if (transform == null) throw new ArgumentNullException(nameof(transform)); foreach (var item in Dictionary) { if (item.Value is IComplexGraphType complex) { foreach (var field in complex.Fields.List) { var inner = field.Resolver ?? NameFieldResolver.Instance; var fieldMiddlewareDelegate = transform(context => inner.ResolveAsync(context)); field.Resolver = new FuncFieldResolver<object>(fieldMiddlewareDelegate.Invoke); } } } } /// <summary> /// Returns a graph type instance from the lookup table by its GraphQL type name. /// </summary> public IGraphType? this[string typeName] { get { if (string.IsNullOrWhiteSpace(typeName)) { throw new ArgumentOutOfRangeException(nameof(typeName), "A type name is required to lookup."); } return Dictionary.TryGetValue(typeName, out var type) ? type : null; } } /// <summary> /// Returns a graph type instance from the lookup table by its .NET type. /// </summary> /// <param name="type">The .NET type of the graph type.</param> private IGraphType? FindGraphType(Type type) => _typeDictionary.TryGetValue(type, out var value) ? value : null; private void AddType(IGraphType type, TypeCollectionContext context) { if (type == null || type is GraphQLTypeReference) { return; } if (type is NonNullGraphType || type is ListGraphType) { throw new ArgumentOutOfRangeException(nameof(type), "Only add root types."); } SetGraphType(type.Name, type); if (type is IComplexGraphType complexType) { foreach (var field in complexType.Fields) { HandleField(complexType, field, context, true); } } if (type is IObjectGraphType obj) { foreach (var objectInterface in obj.Interfaces.List) { AddTypeIfNotRegistered(objectInterface, context); if (FindGraphType(objectInterface) is IInterfaceGraphType interfaceInstance) { obj.AddResolvedInterface(interfaceInstance); interfaceInstance.AddPossibleType(obj); if (interfaceInstance.ResolveType == null && obj.IsTypeOf == null) { throw new InvalidOperationException( $"Interface type '{interfaceInstance.Name}' does not provide a 'resolveType' function " + $"and possible Type '{obj.Name}' does not provide a 'isTypeOf' function. " + "There is no way to resolve this possible type during execution."); } } } } if (type is UnionGraphType union) { if (!union.Types.Any() && !union.PossibleTypes.Any()) { throw new InvalidOperationException($"Must provide types for Union '{union}'."); } foreach (var unionedType in union.PossibleTypes) { // skip references if (unionedType is GraphQLTypeReference) continue; AddTypeIfNotRegistered(unionedType, context); if (union.ResolveType == null && unionedType.IsTypeOf == null) { throw new InvalidOperationException( $"Union type '{union.Name}' does not provide a 'resolveType' function " + $"and possible Type '{unionedType.Name}' does not provide a 'isTypeOf' function. " + "There is no way to resolve this possible type during execution."); } } foreach (var unionedType in union.Types) { AddTypeIfNotRegistered(unionedType, context); var objType = FindGraphType(unionedType) as IObjectGraphType; if (union.ResolveType == null && objType != null && objType.IsTypeOf == null) { throw new InvalidOperationException( $"Union type '{union.Name}' does not provide a 'resolveType' function " + $"and possible Type '{objType.Name}' does not provide a 'isTypeOf' function. " + "There is no way to resolve this possible type during execution."); } union.AddPossibleType(objType!); } } } private void HandleField(IComplexGraphType? parentType, FieldType field, TypeCollectionContext context, bool applyNameConverter) { // applyNameConverter will be false while processing the three root introspection query fields: __schema, __type, and __typename // // During processing of those three root fields, the NameConverter will be set to the schema's selected NameConverter, // and the field names must not be processed by the NameConverter // // For other introspection types and fields, the NameConverter will be set to CamelCaseNameConverter at the time this // code executes, and applyNameConverter will be true // // For any other fields, the NameConverter will be set to the schema's selected NameConverter at the time this code // executes, and applyNameConverter will be true if (applyNameConverter) { field.Name = _nameConverter.NameForField(field.Name, parentType!); NameValidator.ValidateNameOnSchemaInitialize(field.Name, NamedElement.Field); } if (field.ResolvedType == null) { if (field.Type == null) throw new InvalidOperationException($"Both ResolvedType and Type properties on field '{parentType?.Name}.{field.Name}' are null."); object typeOrError = RebuildType(field.Type, parentType is IInputObjectGraphType, context.TypeMappings); if (typeOrError is string error) throw new InvalidOperationException($"The GraphQL type for field '{parentType?.Name}.{field.Name}' could not be derived implicitly. " + error); field.Type = (Type)typeOrError; AddTypeIfNotRegistered(field.Type, context); field.ResolvedType = BuildNamedType(field.Type, context.ResolveType); } else { AddTypeIfNotRegistered(field.ResolvedType, context); } if (field.Arguments?.Count > 0) { foreach (var arg in field.Arguments.List!) { if (applyNameConverter) { arg.Name = _nameConverter.NameForArgument(arg.Name, parentType!, field); NameValidator.ValidateNameOnSchemaInitialize(arg.Name, NamedElement.Argument); } if (arg.ResolvedType == null) { if (arg.Type == null) throw new InvalidOperationException($"Both ResolvedType and Type properties on argument '{parentType?.Name}.{field.Name}.{arg.Name}' are null."); object typeOrError = RebuildType(arg.Type, true, context.TypeMappings); if (typeOrError is string error) throw new InvalidOperationException($"The GraphQL type for argument '{parentType?.Name}.{field.Name}.{arg.Name}' could not be derived implicitly. " + error); arg.Type = (Type)typeOrError; AddTypeIfNotRegistered(arg.Type, context); arg.ResolvedType = BuildNamedType(arg.Type, context.ResolveType); } else { AddTypeIfNotRegistered(arg.ResolvedType, context); } } } } private void HandleDirective(DirectiveGraphType directive, TypeCollectionContext context) { if (directive.Arguments?.Count > 0) { foreach (var arg in directive.Arguments.List!) { if (arg.ResolvedType == null) { if (arg.Type == null) throw new InvalidOperationException($"Both ResolvedType and Type properties on argument '{directive.Name}.{arg.Name}' are null."); object typeOrError = RebuildType(arg.Type, true, context.TypeMappings); if (typeOrError is string error) throw new InvalidOperationException($"The GraphQL type for argument '{directive.Name}.{arg.Name}' could not be derived implicitly. " + error); arg.Type = (Type)typeOrError; AddTypeIfNotRegistered(arg.Type, context); arg.ResolvedType = BuildNamedType(arg.Type, context.ResolveType); } else { AddTypeIfNotRegistered(arg.ResolvedType, context); arg.ResolvedType = ConvertTypeReference(directive, arg.ResolvedType); } } } } // https://github.com/graphql-dotnet/graphql-dotnet/pull/1010 private void AddTypeWithLoopCheck(IGraphType resolvedType, TypeCollectionContext context, Type namedType) { if (context.InFlightRegisteredTypes.Any(t => t == namedType)) { throw new InvalidOperationException($@"A loop has been detected while registering schema types. There was an attempt to re-register '{namedType.FullName}' with instance of '{resolvedType.GetType().FullName}'. Make sure that your ServiceProvider is configured correctly."); } context.InFlightRegisteredTypes.Push(namedType); try { AddType(resolvedType, context); } finally { context.InFlightRegisteredTypes.Pop(); } } private void AddTypeIfNotRegistered(Type type, TypeCollectionContext context) { var namedType = type.GetNamedType(); var foundType = FindGraphType(namedType); if (foundType == null) { if (namedType == typeof(PageInfoType)) { AddType(new PageInfoType(), context); } else if (namedType.IsGenericType && (namedType.ImplementsGenericType(typeof(EdgeType<>)) || namedType.ImplementsGenericType(typeof(ConnectionType<,>)))) { AddType((IGraphType)Activator.CreateInstance(namedType), context); } else if (_builtInCustomScalars.TryGetValue(namedType, out var builtInCustomScalar)) { AddType(builtInCustomScalar, _context); } else { AddTypeWithLoopCheck(context.ResolveType(namedType), context, namedType); } } } private void AddTypeIfNotRegistered(IGraphType type, TypeCollectionContext context) { var (namedType, namedType2) = type.GetNamedTypes(); namedType ??= context.ResolveType(namedType2!); var foundType = this[namedType.Name]; if (foundType == null) { AddType(namedType, context); } } private object RebuildType(Type type, bool input, List<(Type, Type)> typeMappings) { if (!type.IsGenericType) return type; var genericDef = type.GetGenericTypeDefinition(); if (genericDef == typeof(GraphQLClrOutputTypeReference<>) || genericDef == typeof(GraphQLClrInputTypeReference<>)) { return GetGraphType(type.GetGenericArguments()[0], input, typeMappings); } else { var typeList = type.GetGenericArguments(); var changed = false; for (var i = 0; i < typeList.Length; i++) { object typeOrError = RebuildType(typeList[i], input, typeMappings); if (typeOrError is string) return typeOrError; var changedType = (Type)typeOrError; changed |= changedType != typeList[i]; typeList[i] = changedType; } return changed ? genericDef.MakeGenericType(typeList) : type; } } private object GetGraphType(Type clrType, bool input, List<(Type clr, Type graph)> typeMappings) { var ret = GetGraphTypeFromClrType(clrType, input, typeMappings); if (ret == null) return $"Could not find type mapping from CLR type '{clrType.FullName}' to GraphType. Did you forget to register the type mapping with the '{nameof(ISchema)}.{nameof(ISchema.RegisterTypeMapping)}'?"; return ret; } /// <summary> /// Returns a graph type for a specified input or output CLR type. /// This method is called when a graph type is specified as a <see cref="GraphQLClrInputTypeReference{T}"/> or <see cref="GraphQLClrOutputTypeReference{T}"/>. /// </summary> /// <param name="clrType">The CLR type to be mapped.</param> /// <param name="isInputType">Indicates if the CLR type should be mapped to an input or output graph type.</param> /// <param name="typeMappings">The list of registered type mappings on the schema.</param> /// <returns>The graph type to be used, or <see langword="null"/> if no match can be found.</returns> /// <remarks> /// This method should not return wrapped types such as <see cref="ListGraphType"/> or <see cref="NonNullGraphType"/>. /// These are handled within <see cref="GraphQL.TypeExtensions.GetGraphTypeFromType(Type, bool, TypeMappingMode)"/>, /// and should already have been wrapped around the type reference. /// </remarks> protected virtual Type? GetGraphTypeFromClrType(Type clrType, bool isInputType, List<(Type ClrType, Type GraphType)> typeMappings) { // check custom mappings first if (typeMappings != null) { foreach (var mapping in typeMappings) { if (mapping.ClrType == clrType) { if (isInputType && mapping.GraphType.IsInputType() || !isInputType && mapping.GraphType.IsOutputType()) return mapping.GraphType; } } } // then built-in mappings if (BuiltInScalarMappings.TryGetValue(clrType, out var graphType)) return graphType; // create an enumeration graph type if applicable if (clrType.IsEnum) return typeof(EnumerationGraphType<>).MakeGenericType(clrType); return null; } private void ApplyTypeReferences() { // ToList() is a necessary measure here since otherwise we get System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute.' foreach (var type in Dictionary.Values.ToList()) { ApplyTypeReference(type); } } private void ApplyTypeReference(IGraphType type) { if (type is IComplexGraphType complexType) { foreach (var field in complexType.Fields) { field.ResolvedType = ConvertTypeReference(type, field.ResolvedType!); if (field.Arguments?.Count > 0) { foreach (var arg in field.Arguments.List!) { arg.ResolvedType = ConvertTypeReference(type, arg.ResolvedType!); } } } } if (type is IObjectGraphType objectType) { var list = objectType.ResolvedInterfaces.List; for (int i = 0; i < list.Count; ++i) { var interfaceType = (IInterfaceGraphType)ConvertTypeReference(objectType, list[i]); if (objectType.IsTypeOf == null && interfaceType.ResolveType == null) { throw new InvalidOperationException( $"Interface type '{interfaceType.Name}' does not provide a 'resolveType' function " + $"and possible Type '{objectType.Name}' does not provide a 'isTypeOf' function. " + "There is no way to resolve this possible type during execution."); } interfaceType.AddPossibleType(objectType); list[i] = interfaceType; } } if (type is UnionGraphType union) { var list = union.PossibleTypes.List; for (int i = 0; i < list.Count; ++i) { var unionType = ConvertTypeReference(union, list[i]) as IObjectGraphType; if (union.ResolveType == null && unionType != null && unionType.IsTypeOf == null) { throw new InvalidOperationException( $"Union type '{union.Name}' does not provide a 'resolveType' function " + $"and possible Type '{union.Name}' does not provide a 'isTypeOf' function. " + "There is no way to resolve this possible type during execution."); } list[i] = unionType!; } } } private IGraphType ConvertTypeReference(INamedType parentType, IGraphType type) { if (type is NonNullGraphType nonNull) { nonNull.ResolvedType = ConvertTypeReference(parentType, nonNull.ResolvedType!); return nonNull; } if (type is ListGraphType list) { list.ResolvedType = ConvertTypeReference(parentType, list.ResolvedType!); return list; } if (type is GraphQLTypeReference reference) { var type2 = this[reference.TypeName]; if (type2 == null) { type2 = _builtInScalars.Values.FirstOrDefault(t => t.Name == reference.TypeName) ?? _builtInCustomScalars.Values.FirstOrDefault(t => t.Name == reference.TypeName); if (type2 != null) SetGraphType(type2.Name, type2); } if (type2 == null) { throw new InvalidOperationException($"Unable to resolve reference to type '{reference.TypeName}' on '{parentType.Name}'"); } type = type2; } return type; } private void SetGraphType(string typeName, IGraphType graphType) { if (string.IsNullOrWhiteSpace(typeName)) { throw new ArgumentOutOfRangeException(nameof(typeName), "A type name is required to lookup."); } var type = graphType.GetType(); if (Dictionary.TryGetValue(typeName, out var existingGraphType)) { if (ReferenceEquals(existingGraphType, graphType) || existingGraphType.GetType() == type) { // Soft schema configuration error. // Intentionally or inadvertently, a situation may arise when the same GraphType is registered more that one time. // This may be due to the simultaneous registration of GraphType instances and the GraphType types. In this case // the duplicate MUST be ignored, otherwise errors will occur. } else if (type.IsAssignableFrom(existingGraphType.GetType()) && typeof(ScalarGraphType).IsAssignableFrom(type)) { // This can occur when a built-in scalar graph type is overridden by preregistering a replacement graph type that // has the same name and inherits from it. if (!_typeDictionary.ContainsKey(type)) _typeDictionary.Add(type, existingGraphType); } else { // Fatal schema configuration error. throw new InvalidOperationException($@"Unable to register GraphType '{type.FullName}' with the name '{typeName}'. The name '{typeName}' is already registered to '{existingGraphType.GetType().FullName}'. Check your schema configuration."); } } else { Dictionary.Add(typeName, graphType); // if building a schema from code, the .NET types will not be unique, which should be ignored if (!_typeDictionary.ContainsKey(type)) _typeDictionary.Add(type, graphType); } } /// <summary> /// Returns the <see cref="FieldType"/> instance for the <c>__schema</c> meta-field. /// </summary> protected internal virtual FieldType SchemaMetaFieldType { get; } = new SchemaMetaFieldType(); /// <summary> /// Returns the <see cref="FieldType"/> instance for the <c>__type</c> meta-field. /// </summary> protected internal virtual FieldType TypeMetaFieldType { get; } = new TypeMetaFieldType(); /// <summary> /// Returns the <see cref="FieldType"/> instance for the <c>__typename</c> meta-field. /// </summary> protected internal virtual FieldType TypeNameMetaFieldType { get; } = new TypeNameMetaFieldType(); } }
/* Copyright (c) 2010 Daniel Mueller <daniel@danm.de> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. Changes to this license can be made only by the copyright author with explicit written consent. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.Threading; namespace PCSC { public delegate void StatusChangeEvent(object sender, StatusChangeEventArgs e); public delegate void CardInsertedEvent(object sender, CardStatusEventArgs e); public delegate void CardRemovedEvent(object sender, CardStatusEventArgs e); public delegate void CardInitializedEvent(object sender, CardStatusEventArgs e); public delegate void MonitorExceptionEvent(object sender, PCSCException ex); public class StatusChangeEventArgs : EventArgs { public string ReaderName; public SCRState LastState; public SCRState NewState; public byte[] ATR; public StatusChangeEventArgs() { } public StatusChangeEventArgs(string ReaderName, SCRState LastState, SCRState NewState, byte[] Atr) { this.ReaderName = ReaderName; this.LastState = LastState; this.NewState = NewState; this.ATR = Atr; } } public class CardStatusEventArgs : EventArgs { public string ReaderName; public SCRState State; public byte[] Atr; public CardStatusEventArgs() { } public CardStatusEventArgs(string ReaderName, SCRState State, byte[] Atr) { this.ReaderName = ReaderName; this.State = State; this.Atr = Atr; } } public class SCardMonitor : IDisposable { public event StatusChangeEvent StatusChanged; public event CardInsertedEvent CardInserted; public event CardRemovedEvent CardRemoved; public event CardInitializedEvent Initialized; public event MonitorExceptionEvent MonitorException; internal SCardContext context; internal SCRState[] previousState; internal IntPtr[] previousStateValue; internal Thread monitorthread; internal string[] readernames; public string[] ReaderNames { get { if (readernames == null) return null; string[] tmp = new string[readernames.Length]; Array.Copy(readernames, tmp, readernames.Length); return tmp; } } internal bool monitoring; public bool Monitoring { get { return monitoring; } } public IntPtr GetCurrentStateValue(int index) { if (previousStateValue == null) throw new InvalidOperationException("Monitor object is not initialized."); lock (previousStateValue) { // actually "previousStateValue" contains the last known value. if (index < 0 || index > previousStateValue.Length) throw new ArgumentOutOfRangeException("index"); return previousStateValue[index]; } } public SCRState GetCurrentState(int index) { if (previousState == null) throw new InvalidOperationException("Monitor object is not initialized."); lock (previousState) { // "previousState" contains the last known value. if (index < 0 || index > previousState.Length) throw new ArgumentOutOfRangeException("index"); return previousState[index]; } } public string GetReaderName(int index) { if (readernames == null) throw new InvalidOperationException("Monitor object is not initialized."); lock (readernames) { if (index < 0 || index > readernames.Length) throw new ArgumentOutOfRangeException("index"); return readernames[index]; } } public int ReaderCount { get { lock (readernames) { if (readernames == null) return 0; return readernames.Length; } } } public SCardMonitor(SCardContext hContext) { if (hContext == null) throw new ArgumentNullException("hContext"); this.context = hContext; } public SCardMonitor(SCardContext hContext, SCardScope scope) : this(hContext) { hContext.Establish(scope); } ~SCardMonitor() { Dispose(); } public void Dispose() { Cancel(); } public void Cancel() { if (monitoring) { context.Cancel(); readernames = null; previousStateValue = null; previousState = null; monitoring = false; } } public void Start(string readername) { if (readername == null || readername.Equals("")) throw new ArgumentNullException("readername"); Start(new string[] { readername }); } public void Start(string[] readernames) { if (monitoring) Cancel(); lock (this) { if (!monitoring) { if (readernames == null || readernames.Length == 0) throw new ArgumentNullException("readernames"); if (context == null || !context.IsValid()) throw new InvalidContextException(SCardError.InvalidHandle, "No connection context object specified."); this.readernames = readernames; previousState = new SCRState[readernames.Length]; previousStateValue = new IntPtr[readernames.Length]; monitorthread = new Thread(new ThreadStart(StartMonitor)); monitorthread.IsBackground = true; monitorthread.Start(); } } } private void StartMonitor() { monitoring = true; SCardReaderState[] state = new SCardReaderState[readernames.Length]; for (int i = 0; i < readernames.Length; i++) { state[i] = new SCardReaderState(); state[i].ReaderName = readernames[i]; state[i].CurrentState = SCRState.Unaware; /* force SCardGetStatusChange to return immediately with the current reader state */ } SCardError rc = context.GetStatusChange(IntPtr.Zero, state); if (rc == SCardError.Success) { // initialize event if (Initialized != null) { for (int i = 0; i < state.Length; i++) { Initialized(this, new CardStatusEventArgs(readernames[i], (state[i].EventState & (~(SCRState.Changed))), state[i].ATR)); previousState[i] = state[i].EventState & (~(SCRState.Changed)); // remove "Changed" previousStateValue[i] = state[i].EventStateValue; } } while (true) { for (int i = 0; i < state.Length; i++) { state[i].CurrentStateValue = previousStateValue[i]; } // block until status change occurs rc = context.GetStatusChange(SCardReader.Infinite, state); // Cancel? if (rc != SCardError.Success) break; for (int i = 0; i < state.Length; i++) { SCRState newState = state[i].EventState; newState &= (~(SCRState.Changed)); // remove "Changed" byte[] Atr = state[i].ATR; // Status change if (StatusChanged != null && (previousState[i] != newState)) StatusChanged(this, new StatusChangeEventArgs(readernames[i], previousState[i], newState, Atr)); // Card inserted if (((newState & SCRState.Present) == SCRState.Present) && ((previousState[i] & SCRState.Empty) == SCRState.Empty)) if (CardInserted != null) CardInserted(this, new CardStatusEventArgs(readernames[i], newState, Atr)); // Card removed if (((newState & SCRState.Empty) == SCRState.Empty) && ((previousState[i] & SCRState.Present) == SCRState.Present)) if (CardRemoved != null) CardRemoved(this, new CardStatusEventArgs(readernames[i], newState, Atr)); previousState[i] = newState; previousStateValue[i] = state[i].EventStateValue; } } } monitoring = false; if (rc != SCardError.Cancelled) if (MonitorException != null) MonitorException(this, new PCSCException(rc, "An error occured during SCardGetStatusChange(..).")); } } }
// Some copyright should be here... using System; using System.IO; using System.Text.RegularExpressions; using UnrealBuildTool; using System.Diagnostics; using System.Collections.Generic; namespace UnrealBuildTool.Rules { struct SetupInfo { public string _DownloadPath; public string _Version; public string _FileName; public string _InstallPath; public string _TempPath; public SetupInfo(string DownloadPath, string Version, string FileName, string InstallPath, string tempPath) { _DownloadPath = DownloadPath; _Version = Version; _FileName = FileName; _InstallPath = InstallPath; _TempPath = tempPath; } } public class UEStormancerPlugin : ModuleRules { Dictionary<string, SetupInfo> SetupInfoMap = new Dictionary<string, SetupInfo>(); private string VS_TOOLSET = "140"; private string TEMP_PATH = "D:\\Temp"; private string SDK_LIB_PATH = ""; private string SDK_HEADER_PATH = ""; private string SDK_DOWNLOAD_PATH = "https://github.com/Stormancer/stormancer-sdk-cpp/releases/download"; private string SDK_VERSION = "v1.2"; private string SDK_FILENAME = "Stormancer-cpp-1.2.zip"; private string SDK_INSTALL_PATH = ""; private string DCS_LIB_PATH = ""; private string DCS_HEADER_PATH = ""; private string DCS_DOWNLOAD_PATH = "https://github.com/Stormancer/Sample_DedicatedClientServer/releases/download"; private string DCS_VERSION = "1.02"; private string DCS_FILENAME = "Stormancer_DCS_1.02.zip"; private string DCS_INSTALL_PATH = ""; public UEStormancerPlugin(ReadOnlyTargetRules Target) : base(Target) { SDK_LIB_PATH = ModuleDirectory + "/../../Resources/Stormancer/libs/"; SDK_HEADER_PATH = ModuleDirectory + "/../../Resources/Stormancer/include/"; SDK_INSTALL_PATH = ModuleDirectory + "/../../Resources/Stormancer"; SetupInfoMap.Add("Stormancer", new SetupInfo(SDK_DOWNLOAD_PATH, SDK_VERSION, SDK_FILENAME, SDK_INSTALL_PATH, TEMP_PATH)); DCS_LIB_PATH = ModuleDirectory + "/../../Resources/DCS/Libs/"; DCS_HEADER_PATH = ModuleDirectory + "/../../Resources/DCS/Includes/"; DCS_INSTALL_PATH = ModuleDirectory + "/../../Resources/DCS"; SetupInfoMap.Add("DCS_OnlineModule", new SetupInfo(DCS_DOWNLOAD_PATH, DCS_VERSION, DCS_FILENAME, DCS_INSTALL_PATH, TEMP_PATH)); LoadLibrary(Target, DCS_HEADER_PATH, DCS_LIB_PATH, "DCS_OnlineModule"); LoadLibrary(Target, SDK_HEADER_PATH, SDK_LIB_PATH, "Stormancer"); SetupLocal(Target); } /// <summary> /// Setup file in this plugin /// </summary> /// <param name="target">ReadOnlyTargetRules</param> private void SetupLocal(ReadOnlyTargetRules target) { PCHUsage = ModuleRules.PCHUsageMode.UseExplicitOrSharedPCHs; PublicIncludePaths.AddRange( new string[] { "Source/UEStormancerPlugin/Public", } ); PrivateIncludePaths.AddRange( new string[] { "Source/UEStormancerPlugin/Private", } ); PublicDependencyModuleNames.AddRange( new string[] { "Core", } ); PrivateDependencyModuleNames.AddRange( new string[] { "CoreUObject", "Engine", "Slate", "SlateCore" } ); DynamicallyLoadedModuleNames.AddRange(new string[]{}); } /// <summary> /// Helper to setup an arbitrary library in the given library folder /// </summary> /// <param name="target">ReadOnlyTargetRules object</param> /// <param name="include_path">include_path Relative include path, eg. 3rdparty/mylib/include</param> /// <param name="build_path">build_path Relative build path, eg. 3rdparty/mylib/build</param> /// <param name="library_name">library_name Short library name, eg. mylib. Automatically expands to libmylib.a, mylib.lib, etc.</param> private void LoadLibrary(ReadOnlyTargetRules target, string include_path, string build_path, string library_name) { // Add the include path var full_include_path = Path.Combine(PluginPath, include_path); if (!Directory.Exists(full_include_path)) { //Fail("Invalid include path: " + full_include_path); Trace("Missing include files at : {0}", full_include_path); DownloadResources(SetupInfoMap[library_name]); } else { SetupInfo info = SetupInfoMap[library_name]; string versionFile = info._InstallPath + "\\" + info._FileName.Substring(0, info._FileName.Length-4); if (!File.Exists(versionFile)) { //File exists but it's not up-to-date DownloadResources(SetupInfoMap[library_name]); } PublicIncludePaths.Add(full_include_path); Trace("Added include path: {0}", full_include_path); } // Get the build path var full_build_path = Path.Combine(PluginPath, build_path); if (!Directory.Exists(full_build_path)) { Fail("Invalid build path: " + full_build_path + " (Did you build the 3rdparty module already?)"); } string platform = ""; string extension = "lib"; switch (target.Platform) { case UnrealTargetPlatform.Win64: platform = "x64"; break; case UnrealTargetPlatform.Win32: platform = "x86"; break; } string configuration = "_Release_"; //switch (target.Configuration) //{ // case UnrealTargetConfiguration.Debug: // configuration = "_Debug_"; // break; // case UnrealTargetConfiguration.DebugGame: // //DebugUE4 is only needed on Windows // if (target.Platform == UnrealTargetPlatform.Win64 || target.Platform == UnrealTargetPlatform.Win32) // { // configuration = "_DebugUE4_"; // } // else // { // configuration = "_Debug_"; // } // break; // default: // configuration = "_Release_"; // break; //} // Look at all the files in the build path; we need to smartly locate // the static library based on the current platform. For dynamic libraries // this is more difficult, but for static libraries, it's just .lib or .a string[] fileEntries = Directory.GetFiles(full_build_path); var pattern = ".*" + library_name + VS_TOOLSET + configuration + platform + "." + extension; Regex r = new Regex(pattern, RegexOptions.IgnoreCase); string full_library_path = null; foreach (var file in fileEntries) { if (r.Match(file).Success) { full_library_path = Path.Combine(full_build_path, file); break; } } if (full_library_path == null) { Fail("Unable to locate any build libraries in: " + full_build_path); } // Found a library; add it to the dependencies list PublicAdditionalLibraries.Add(full_library_path); Trace("Added static library: {0}", full_library_path); } /** * Print out a build message * Why error? Well, the UE masks all other errors. *shrug* */ private void Trace(string msg) { Log.TraceError(Plugin + ": " + msg); } /// <summary> /// Trace helper /// </summary> /// <param name="format"></param> /// <param name="args"></param> private void Trace(string format, params object[] args) { Trace(string.Format(format, args)); } /// <summary> /// Raise an error /// </summary> /// <param name="message"></param> private void Fail(string message) { Trace(message); throw new Exception(message); } /// <summary> /// Get the absolute root to the plugin folder /// </summary> private string PluginPath { get { return Path.GetFullPath(Path.Combine(ModuleDirectory, "../..")); } } /// <summary> /// Get the name of this plugin's folder /// </summary> private string Plugin { get { return new DirectoryInfo(PluginPath).Name; } } void DownloadResources(SetupInfo info) { ProcessStartInfo startInfo = new ProcessStartInfo(); // Maybe wrong I Think this is not launching a right powershell exe as I an launch it correctly with the arguments startInfo.FileName = "Powershell.exe"; string scriptPath = ModuleDirectory + "/../../SetupResources.ps1"; startInfo.Arguments = "Unblock-File -Path "+ scriptPath+"; " + scriptPath+" -DownloadPath " + info._DownloadPath + " -Version " + info._Version + " -FileName " + info._FileName + " -InstallPath " + info._InstallPath + " -TempPath " + info._TempPath; Trace(startInfo.Arguments); startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; startInfo.UseShellExecute = false; startInfo.CreateNoWindow = true; Process process = new Process(); process.StartInfo = startInfo; process.OutputDataReceived += (s, e) => Trace(e.Data); process.ErrorDataReceived += (s, e) => Trace(e.Data); process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); } } }
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: blah@cliffano.com * Generated by: https://openapi-generator.tech */ using System; using System.Linq; using System.Text; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; using Newtonsoft.Json; using Org.OpenAPITools.Converters; namespace Org.OpenAPITools.Models { /// <summary> /// /// </summary> [DataContract] public partial class MultibranchPipeline : IEquatable<MultibranchPipeline> { /// <summary> /// Gets or Sets DisplayName /// </summary> [DataMember(Name="displayName", EmitDefaultValue=false)] public string DisplayName { get; set; } /// <summary> /// Gets or Sets EstimatedDurationInMillis /// </summary> [DataMember(Name="estimatedDurationInMillis", EmitDefaultValue=false)] public int EstimatedDurationInMillis { get; set; } /// <summary> /// Gets or Sets LatestRun /// </summary> [DataMember(Name="latestRun", EmitDefaultValue=false)] public string LatestRun { get; set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Gets or Sets Organization /// </summary> [DataMember(Name="organization", EmitDefaultValue=false)] public string Organization { get; set; } /// <summary> /// Gets or Sets WeatherScore /// </summary> [DataMember(Name="weatherScore", EmitDefaultValue=false)] public int WeatherScore { get; set; } /// <summary> /// Gets or Sets BranchNames /// </summary> [DataMember(Name="branchNames", EmitDefaultValue=false)] public List<string> BranchNames { get; set; } /// <summary> /// Gets or Sets NumberOfFailingBranches /// </summary> [DataMember(Name="numberOfFailingBranches", EmitDefaultValue=false)] public int NumberOfFailingBranches { get; set; } /// <summary> /// Gets or Sets NumberOfFailingPullRequests /// </summary> [DataMember(Name="numberOfFailingPullRequests", EmitDefaultValue=false)] public int NumberOfFailingPullRequests { get; set; } /// <summary> /// Gets or Sets NumberOfSuccessfulBranches /// </summary> [DataMember(Name="numberOfSuccessfulBranches", EmitDefaultValue=false)] public int NumberOfSuccessfulBranches { get; set; } /// <summary> /// Gets or Sets NumberOfSuccessfulPullRequests /// </summary> [DataMember(Name="numberOfSuccessfulPullRequests", EmitDefaultValue=false)] public int NumberOfSuccessfulPullRequests { get; set; } /// <summary> /// Gets or Sets TotalNumberOfBranches /// </summary> [DataMember(Name="totalNumberOfBranches", EmitDefaultValue=false)] public int TotalNumberOfBranches { get; set; } /// <summary> /// Gets or Sets TotalNumberOfPullRequests /// </summary> [DataMember(Name="totalNumberOfPullRequests", EmitDefaultValue=false)] public int TotalNumberOfPullRequests { get; set; } /// <summary> /// Gets or Sets Class /// </summary> [DataMember(Name="_class", EmitDefaultValue=false)] public string Class { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class MultibranchPipeline {\n"); sb.Append(" DisplayName: ").Append(DisplayName).Append("\n"); sb.Append(" EstimatedDurationInMillis: ").Append(EstimatedDurationInMillis).Append("\n"); sb.Append(" LatestRun: ").Append(LatestRun).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Organization: ").Append(Organization).Append("\n"); sb.Append(" WeatherScore: ").Append(WeatherScore).Append("\n"); sb.Append(" BranchNames: ").Append(BranchNames).Append("\n"); sb.Append(" NumberOfFailingBranches: ").Append(NumberOfFailingBranches).Append("\n"); sb.Append(" NumberOfFailingPullRequests: ").Append(NumberOfFailingPullRequests).Append("\n"); sb.Append(" NumberOfSuccessfulBranches: ").Append(NumberOfSuccessfulBranches).Append("\n"); sb.Append(" NumberOfSuccessfulPullRequests: ").Append(NumberOfSuccessfulPullRequests).Append("\n"); sb.Append(" TotalNumberOfBranches: ").Append(TotalNumberOfBranches).Append("\n"); sb.Append(" TotalNumberOfPullRequests: ").Append(TotalNumberOfPullRequests).Append("\n"); sb.Append(" Class: ").Append(Class).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { if (obj is null) return false; if (ReferenceEquals(this, obj)) return true; return obj.GetType() == GetType() && Equals((MultibranchPipeline)obj); } /// <summary> /// Returns true if MultibranchPipeline instances are equal /// </summary> /// <param name="other">Instance of MultibranchPipeline to be compared</param> /// <returns>Boolean</returns> public bool Equals(MultibranchPipeline other) { if (other is null) return false; if (ReferenceEquals(this, other)) return true; return ( DisplayName == other.DisplayName || DisplayName != null && DisplayName.Equals(other.DisplayName) ) && ( EstimatedDurationInMillis == other.EstimatedDurationInMillis || EstimatedDurationInMillis.Equals(other.EstimatedDurationInMillis) ) && ( LatestRun == other.LatestRun || LatestRun != null && LatestRun.Equals(other.LatestRun) ) && ( Name == other.Name || Name != null && Name.Equals(other.Name) ) && ( Organization == other.Organization || Organization != null && Organization.Equals(other.Organization) ) && ( WeatherScore == other.WeatherScore || WeatherScore.Equals(other.WeatherScore) ) && ( BranchNames == other.BranchNames || BranchNames != null && other.BranchNames != null && BranchNames.SequenceEqual(other.BranchNames) ) && ( NumberOfFailingBranches == other.NumberOfFailingBranches || NumberOfFailingBranches.Equals(other.NumberOfFailingBranches) ) && ( NumberOfFailingPullRequests == other.NumberOfFailingPullRequests || NumberOfFailingPullRequests.Equals(other.NumberOfFailingPullRequests) ) && ( NumberOfSuccessfulBranches == other.NumberOfSuccessfulBranches || NumberOfSuccessfulBranches.Equals(other.NumberOfSuccessfulBranches) ) && ( NumberOfSuccessfulPullRequests == other.NumberOfSuccessfulPullRequests || NumberOfSuccessfulPullRequests.Equals(other.NumberOfSuccessfulPullRequests) ) && ( TotalNumberOfBranches == other.TotalNumberOfBranches || TotalNumberOfBranches.Equals(other.TotalNumberOfBranches) ) && ( TotalNumberOfPullRequests == other.TotalNumberOfPullRequests || TotalNumberOfPullRequests.Equals(other.TotalNumberOfPullRequests) ) && ( Class == other.Class || Class != null && Class.Equals(other.Class) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; // Suitable nullity checks etc, of course :) if (DisplayName != null) hashCode = hashCode * 59 + DisplayName.GetHashCode(); hashCode = hashCode * 59 + EstimatedDurationInMillis.GetHashCode(); if (LatestRun != null) hashCode = hashCode * 59 + LatestRun.GetHashCode(); if (Name != null) hashCode = hashCode * 59 + Name.GetHashCode(); if (Organization != null) hashCode = hashCode * 59 + Organization.GetHashCode(); hashCode = hashCode * 59 + WeatherScore.GetHashCode(); if (BranchNames != null) hashCode = hashCode * 59 + BranchNames.GetHashCode(); hashCode = hashCode * 59 + NumberOfFailingBranches.GetHashCode(); hashCode = hashCode * 59 + NumberOfFailingPullRequests.GetHashCode(); hashCode = hashCode * 59 + NumberOfSuccessfulBranches.GetHashCode(); hashCode = hashCode * 59 + NumberOfSuccessfulPullRequests.GetHashCode(); hashCode = hashCode * 59 + TotalNumberOfBranches.GetHashCode(); hashCode = hashCode * 59 + TotalNumberOfPullRequests.GetHashCode(); if (Class != null) hashCode = hashCode * 59 + Class.GetHashCode(); return hashCode; } } #region Operators #pragma warning disable 1591 public static bool operator ==(MultibranchPipeline left, MultibranchPipeline right) { return Equals(left, right); } public static bool operator !=(MultibranchPipeline left, MultibranchPipeline right) { return !Equals(left, right); } #pragma warning restore 1591 #endregion Operators } }
using Google.GData.Extensions.Apps; namespace Google.GData.Apps.AdminSettings { /// <summary> /// A Google Apps Google Admin Settings entry. /// </summary> public class AdminSettingsEntry : AppsExtendedEntry { /// <summary> /// DefaultLanguage Property accessor /// </summary> public string DefaultLanguage { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.DefaultLanguage); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.DefaultLanguage).Value = value; } } /// <summary> /// OrganizationName Property accessor /// </summary> public string OrganizationName { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.OrganizationName); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.OrganizationName).Value = value; } } /// <summary> /// MaximumNumberOfUsers Property accessor /// </summary> public string MaximumNumberOfUsers { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.MaximumNumberOfUsers); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.MaximumNumberOfUsers).Value = value; } } /// <summary> /// MaximumNumberOfUsers Property accessor /// </summary> public string CurrentNumberOfUsers { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.CurrentNumberOfUsers); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.CurrentNumberOfUsers).Value = value; } } /// <summary> /// IsVerified Property accessor /// </summary> public string IsVerified { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.IsVerified); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.IsVerified).Value = value; } } /// <summary> /// SupportPIN Property accessor /// </summary> public string SupportPIN { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.SupportPIN); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.SupportPIN).Value = value; } } /// <summary> /// Edition Property accessor /// </summary> public string Edition { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.Edition); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.Edition).Value = value; } } /// <summary> /// CustomerPIN Property accessor /// </summary> public string CustomerPIN { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.CustomerPIN); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.CustomerPIN).Value = value; } } /// <summary> /// CreationTime Property accessor /// </summary> public string CreationTime { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.CreationTime); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.CreationTime).Value = value; } } /// <summary> /// CountryCode Property accessor /// </summary> public string CountryCode { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.CountryCode); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.CountryCode).Value = value; } } /// <summary> /// AdminSecondaryEmail Property accessor /// </summary> public string AdminSecondaryEmail { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.AdminSecondaryEmail); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.AdminSecondaryEmail).Value = value; } } /// <summary> /// LogoImage Property accessor /// </summary> public string LogoImage { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.LogoImage); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.LogoImage).Value = value; } } /// <summary> /// RecordName Property accessor /// </summary> public string RecordName { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.RecordName); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.RecordName).Value = value; } } /// <summary> /// Verified Property accessor /// </summary> public string Verified { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.Verified); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.Verified).Value = value; } } /// <summary> /// VerifiedMethod Property accessor /// </summary> public string VerifiedMethod { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.VerifiedMethod); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.VerifiedMethod).Value = value; } } /// <summary> /// MaximumNumberOfUsers Property accessor /// </summary> public string SamlSignonUri { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.SamlSignonUri); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.SamlSignonUri).Value = value; } } /// <summary> /// SamlLogoutUri Property accessor /// </summary> public string SamlLogoutUri { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.SamlLogoutUri); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.SamlLogoutUri).Value = value; } } /// <summary> /// ChangePasswordUri Property accessor /// </summary> public string ChangePasswordUri { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.ChangePasswordUri); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.ChangePasswordUri).Value = value; } } /// <summary> /// EnableSSO Property accessor /// </summary> public string EnableSSO { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.EnableSSO); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.EnableSSO).Value = value; } } /// <summary> /// SsoWhitelist Property accessor /// </summary> public string SsoWhitelist { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.SsoWhitelist); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.SsoWhitelist).Value = value; } } /// <summary> /// UseDomainSpecificIssuer Property accessor /// </summary> public string UseDomainSpecificIssuer { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.UseDomainSpecificIssuer); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.UseDomainSpecificIssuer).Value = value; } } /// <summary> /// SigningKey Property accessor /// </summary> public string SigningKey { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.SigningKey); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.SigningKey).Value = value; } } /// <summary> /// EnableUserMigration Property accessor /// </summary> public string EnableUserMigration { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.EnableUserMigration); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.EnableUserMigration).Value = value; } } /// <summary> /// SmartHost Property accessor /// </summary> public string SmartHost { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.SmartHost); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.SmartHost).Value = value; } } /// <summary> /// SmtpMode Property accessor /// </summary> public string SmtpMode { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.SmtpMode); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.SmtpMode).Value = value; } } /// <summary> /// RouteDestination Property accessor /// </summary> public string RouteDestination { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.RouteDestination); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.RouteDestination).Value = value; } } /// <summary> /// RouteRewriteTo Property accessor /// </summary> public string RouteRewriteTo { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.RouteRewriteTo); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.RouteRewriteTo).Value = value; } } /// <summary> /// RouteEnabled Property accessor /// </summary> public string RouteEnabled { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.RouteEnabled); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.RouteEnabled).Value = value; } } /// <summary> /// BounceNotifications Property accessor /// </summary> public string BounceNotifications { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.BounceNotifications); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.BounceNotifications).Value = value; } } /// <summary> /// AccountHandling Property accessor /// </summary> public string AccountHandling { get { PropertyElement property = getPropertyByName(AppsDomainSettingsNameTable.AccountHandling); return property != null ? property.Value : null; } set { getPropertyByName(AppsDomainSettingsNameTable.AccountHandling).Value = value; } } /// <summary> /// typed override of the Update method /// </summary> /// <returns>AdminSettingsEntry</returns> public new AdminSettingsEntry Update() { return base.Update() as AdminSettingsEntry; } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation; using System.Management.Automation.Internal; namespace Microsoft.PowerShell.Commands.Internal.Format { /// <summary> /// base class for the various types of formatting shapes /// </summary> internal abstract class ViewGenerator { internal virtual void Initialize(TerminatingErrorContext terminatingErrorContext, MshExpressionFactory mshExpressionFactory, TypeInfoDataBase db, ViewDefinition view, FormattingCommandLineParameters formatParameters) { Diagnostics.Assert(mshExpressionFactory != null, "mshExpressionFactory cannot be null"); Diagnostics.Assert(db != null, "db cannot be null"); Diagnostics.Assert(view != null, "view cannot be null"); errorContext = terminatingErrorContext; expressionFactory = mshExpressionFactory; parameters = formatParameters; dataBaseInfo.db = db; dataBaseInfo.view = view; dataBaseInfo.applicableTypes = DisplayDataQuery.GetAllApplicableTypes(db, view.appliesTo); InitializeHelper(); } internal virtual void Initialize(TerminatingErrorContext terminatingErrorContext, MshExpressionFactory mshExpressionFactory, PSObject so, TypeInfoDataBase db, FormattingCommandLineParameters formatParameters) { errorContext = terminatingErrorContext; expressionFactory = mshExpressionFactory; parameters = formatParameters; dataBaseInfo.db = db; InitializeHelper(); } /// <summary> /// Let the view prepare itself for RemoteObjects. Specific view generators can /// use this call to customize display for remote objects like showing/hiding /// computername property etc. /// </summary> /// <param name="so"></param> internal virtual void PrepareForRemoteObjects(PSObject so) { } private void InitializeHelper() { InitializeFormatErrorManager(); InitializeGroupBy(); InitializeAutoSize(); } private void InitializeFormatErrorManager() { FormatErrorPolicy formatErrorPolicy = new FormatErrorPolicy(); if (parameters != null && parameters.showErrorsAsMessages.HasValue) { formatErrorPolicy.ShowErrorsAsMessages = parameters.showErrorsAsMessages.Value; } else { formatErrorPolicy.ShowErrorsAsMessages = this.dataBaseInfo.db.defaultSettingsSection.formatErrorPolicy.ShowErrorsAsMessages; } if (parameters != null && parameters.showErrorsInFormattedOutput.HasValue) { formatErrorPolicy.ShowErrorsInFormattedOutput = parameters.showErrorsInFormattedOutput.Value; } else { formatErrorPolicy.ShowErrorsInFormattedOutput = this.dataBaseInfo.db.defaultSettingsSection.formatErrorPolicy.ShowErrorsInFormattedOutput; } _errorManager = new FormatErrorManager(formatErrorPolicy); } private void InitializeGroupBy() { // first check if there is an override from the command line if (parameters != null && parameters.groupByParameter != null) { // get the expression to use MshExpression groupingKeyExpression = parameters.groupByParameter.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as MshExpression; // set the label string label = null; object labelKey = parameters.groupByParameter.GetEntry(FormatParameterDefinitionKeys.LabelEntryKey); if (labelKey != AutomationNull.Value) { label = labelKey as string; } _groupingManager = new GroupingInfoManager(); _groupingManager.Initialize(groupingKeyExpression, label); return; } // check if we have a view to initialize from if (this.dataBaseInfo.view != null) { GroupBy gb = this.dataBaseInfo.view.groupBy; if (gb == null) { return; } if (gb.startGroup == null || gb.startGroup.expression == null) { return; } MshExpression ex = this.expressionFactory.CreateFromExpressionToken(gb.startGroup.expression, this.dataBaseInfo.view.loadingInfo); _groupingManager = new GroupingInfoManager(); _groupingManager.Initialize(ex, null); } } private void InitializeAutoSize() { // check the autosize flag first if (parameters != null && parameters.autosize.HasValue) { _autosize = parameters.autosize.Value; return; } // check if we have a view with autosize checked if (this.dataBaseInfo.view != null && this.dataBaseInfo.view.mainControl != null) { ControlBody controlBody = this.dataBaseInfo.view.mainControl as ControlBody; if (controlBody != null && controlBody.autosize.HasValue) { _autosize = controlBody.autosize.Value; } } } internal virtual FormatStartData GenerateStartData(PSObject so) { FormatStartData startFormat = new FormatStartData(); if (_autosize) { startFormat.autosizeInfo = new AutosizeInfo(); } return startFormat; } internal abstract FormatEntryData GeneratePayload(PSObject so, int enumerationLimit); internal GroupStartData GenerateGroupStartData(PSObject firstObjectInGroup, int enumerationLimit) { GroupStartData startGroup = new GroupStartData(); if (_groupingManager == null) return startGroup; object currentGroupingValue = _groupingManager.CurrentGroupingKeyPropertyValue; if (currentGroupingValue == AutomationNull.Value) return startGroup; PSObject so = PSObjectHelper.AsPSObject(currentGroupingValue); // we need to determine how to display the group header ControlBase control = null; TextToken labelTextToken = null; if (this.dataBaseInfo.view != null && this.dataBaseInfo.view.groupBy != null) { if (this.dataBaseInfo.view.groupBy.startGroup != null) { // NOTE: from the database constraints, only one of the // two will be non null control = this.dataBaseInfo.view.groupBy.startGroup.control; labelTextToken = this.dataBaseInfo.view.groupBy.startGroup.labelTextToken; } } startGroup.groupingEntry = new GroupingEntry(); if (control == null) { // we do not have a control, we auto generate a // snippet of complex display using a label StringFormatError formatErrorObject = null; if (_errorManager.DisplayFormatErrorString) { // we send a format error object down to the formatting calls // only if we want to show the formatting error strings formatErrorObject = new StringFormatError(); } string currentGroupingValueDisplay = PSObjectHelper.SmartToString(so, this.expressionFactory, enumerationLimit, formatErrorObject); if (formatErrorObject != null && formatErrorObject.exception != null) { // if we did no thave any errors in the expression evaluation // we might have errors in the formatting, if present _errorManager.LogStringFormatError(formatErrorObject); if (_errorManager.DisplayFormatErrorString) { currentGroupingValueDisplay = _errorManager.FormatErrorString; } } FormatEntry fe = new FormatEntry(); startGroup.groupingEntry.formatValueList.Add(fe); FormatTextField ftf = new FormatTextField(); // determine what the label should be. If we have a label from the // database, let's use it, else fall back to the string provided // by the grouping manager string label; if (labelTextToken != null) label = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(labelTextToken); else label = _groupingManager.GroupingKeyDisplayName; ftf.text = StringUtil.Format(FormatAndOut_format_xxx.GroupStartDataIndentedAutoGeneratedLabel, label); fe.formatValueList.Add(ftf); FormatPropertyField fpf = new FormatPropertyField(); fpf.propertyValue = currentGroupingValueDisplay; fe.formatValueList.Add(fpf); } else { // NOTE: we set a max depth to protect ourselves from infinite loops const int maxTreeDepth = 50; ComplexControlGenerator controlGenerator = new ComplexControlGenerator(this.dataBaseInfo.db, this.dataBaseInfo.view.loadingInfo, this.expressionFactory, this.dataBaseInfo.view.formatControlDefinitionHolder.controlDefinitionList, this.ErrorManager, enumerationLimit, this.errorContext); controlGenerator.GenerateFormatEntries(maxTreeDepth, control, firstObjectInGroup, startGroup.groupingEntry.formatValueList); } return startGroup; } /// <summary> /// update the current value of the grouping key /// </summary> /// <param name="so">object to use for the update</param> /// <returns>true if the value of the key changed</returns> internal bool UpdateGroupingKeyValue(PSObject so) { if (_groupingManager == null) return false; return _groupingManager.UpdateGroupingKeyValue(so); } internal GroupEndData GenerateGroupEndData() { return new GroupEndData(); } internal bool IsObjectApplicable(Collection<string> typeNames) { if (dataBaseInfo.view == null) return true; if (typeNames.Count == 0) return false; TypeMatch match = new TypeMatch(expressionFactory, dataBaseInfo.db, typeNames); if (match.PerfectMatch(new TypeMatchItem(this, dataBaseInfo.applicableTypes))) { return true; } bool result = match.BestMatch != null; // we were unable to find a best match so far..try // to get rid of Deserialization prefix and see if a // match can be found. if (false == result) { Collection<string> typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); if (null != typesWithoutPrefix) { result = IsObjectApplicable(typesWithoutPrefix); } } return result; } private GroupingInfoManager _groupingManager = null; protected bool AutoSize { get { return _autosize; } } private bool _autosize = false; protected class DataBaseInfo { internal TypeInfoDataBase db = null; internal ViewDefinition view = null; internal AppliesTo applicableTypes = null; } protected TerminatingErrorContext errorContext; protected FormattingCommandLineParameters parameters; protected MshExpressionFactory expressionFactory; protected DataBaseInfo dataBaseInfo = new DataBaseInfo(); protected List<MshResolvedExpressionParameterAssociation> activeAssociationList = null; protected FormattingCommandLineParameters inputParameters = null; protected string GetExpressionDisplayValue(PSObject so, int enumerationLimit, MshExpression ex, FieldFormattingDirective directive) { MshExpressionResult resolvedExpression; return GetExpressionDisplayValue(so, enumerationLimit, ex, directive, out resolvedExpression); } protected string GetExpressionDisplayValue(PSObject so, int enumerationLimit, MshExpression ex, FieldFormattingDirective directive, out MshExpressionResult expressionResult) { StringFormatError formatErrorObject = null; if (_errorManager.DisplayFormatErrorString) { // we send a format error object down to the formatting calls // only if we want to show the formatting error strings formatErrorObject = new StringFormatError(); } string retVal = PSObjectHelper.GetExpressionDisplayValue(so, enumerationLimit, ex, directive, formatErrorObject, expressionFactory, out expressionResult); if (expressionResult != null) { // we obtained a result, check if there is an error if (expressionResult.Exception != null) { _errorManager.LogMshExpressionFailedResult(expressionResult, so); if (_errorManager.DisplayErrorStrings) { retVal = _errorManager.ErrorString; } } else if (formatErrorObject != null && formatErrorObject.exception != null) { // if we did no thave any errors in the expression evaluation // we might have errors in the formatting, if present _errorManager.LogStringFormatError(formatErrorObject); if (_errorManager.DisplayErrorStrings) { retVal = _errorManager.FormatErrorString; } } } return retVal; } protected bool EvaluateDisplayCondition(PSObject so, ExpressionToken conditionToken) { if (conditionToken == null) return true; MshExpression ex = this.expressionFactory.CreateFromExpressionToken(conditionToken, this.dataBaseInfo.view.loadingInfo); MshExpressionResult expressionResult; bool retVal = DisplayCondition.Evaluate(so, ex, out expressionResult); if (expressionResult != null && expressionResult.Exception != null) { _errorManager.LogMshExpressionFailedResult(expressionResult, so); } return retVal; } internal FormatErrorManager ErrorManager { get { return _errorManager; } } private FormatErrorManager _errorManager; #region helpers protected FormatPropertyField GenerateFormatPropertyField(List<FormatToken> formatTokenList, PSObject so, int enumerationLimit) { MshExpressionResult result; return GenerateFormatPropertyField(formatTokenList, so, enumerationLimit, out result); } protected FormatPropertyField GenerateFormatPropertyField(List<FormatToken> formatTokenList, PSObject so, int enumerationLimit, out MshExpressionResult result) { result = null; FormatPropertyField fpf = new FormatPropertyField(); if (formatTokenList.Count != 0) { FormatToken token = formatTokenList[0]; FieldPropertyToken fpt = token as FieldPropertyToken; if (fpt != null) { MshExpression ex = this.expressionFactory.CreateFromExpressionToken(fpt.expression, this.dataBaseInfo.view.loadingInfo); fpf.propertyValue = this.GetExpressionDisplayValue(so, enumerationLimit, ex, fpt.fieldFormattingDirective, out result); } else { TextToken tt = token as TextToken; if (tt != null) fpf.propertyValue = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(tt); } } else { fpf.propertyValue = ""; } return fpf; } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Windows.Input; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using NuGet.VisualStudio; namespace NuGetConsole.Implementation.Console { internal class WpfConsoleKeyProcessor : OleCommandFilter { private readonly Lazy<IntPtr> _pKeybLayout = new Lazy<IntPtr>(() => NativeMethods.GetKeyboardLayout(0)); private WpfConsole WpfConsole { get; set; } private IWpfTextView WpfTextView { get; set; } private ICommandExpansion CommandExpansion { get; set; } public WpfConsoleKeyProcessor(WpfConsole wpfConsole) : base(wpfConsole.VsTextView) { WpfConsole = wpfConsole; WpfTextView = wpfConsole.WpfTextView; CommandExpansion = wpfConsole.Factory.GetCommandExpansion(wpfConsole); } /// <summary> /// Check if Caret is in read only region. This is true if the console is currently not /// in input mode, or the caret is before current prompt. /// </summary> private bool IsCaretInReadOnlyRegion { get { return WpfConsole.InputLineStart == null || // shortcut -- no inut allowed WpfTextView.TextBuffer.IsReadOnly(WpfTextView.Caret.Position.BufferPosition.Position); } } /// <summary> /// Check if Caret is on InputLine, including before or after Prompt. /// </summary> private bool IsCaretOnInputLine { get { SnapshotPoint? inputStart = WpfConsole.InputLineStart; if (inputStart != null) { SnapshotSpan inputExtent = inputStart.Value.GetContainingLine().ExtentIncludingLineBreak; SnapshotPoint caretPos = CaretPosition; return inputExtent.Contains(caretPos) || inputExtent.End == caretPos; } return false; } } /// <summary> /// Check if Caret is exactly on InputLineStart. Do nothing when HOME/Left keys are pressed here. /// When caret is right to this position, HOME/Left moves caret to this position. /// </summary> private bool IsCaretAtInputLineStart { get { return WpfConsole.InputLineStart == WpfTextView.Caret.Position.BufferPosition; } } private SnapshotPoint CaretPosition { get { return WpfTextView.Caret.Position.BufferPosition; } } private bool IsSelectionReadonly { get { if (!WpfTextView.Selection.IsEmpty) { ITextBuffer buffer = WpfTextView.TextBuffer; return WpfTextView.Selection.SelectedSpans.Any(span => buffer.IsReadOnly(span)); } return false; } } /// <summary> /// Manually execute a command on the OldChain (so this filter won't participate in the command filtering). /// </summary> private void ExecuteCommand(VSConstants.VSStd2KCmdID idCommand, object args = null) { OldChain.Execute(idCommand, args); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] protected override int InternalExec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { int hr = OLECMDERR_E_NOTSUPPORTED; if (WpfConsole == null || WpfConsole.Host == null || WpfConsole.Dispatcher == null) { return hr; } if (!WpfConsole.Host.IsCommandEnabled) { return hr; } if (!WpfConsole.Dispatcher.IsExecutingReadKey) { // if the console has not been successfully started, do not accept any key inputs, unless // we are in the middle of a ReadKey call. This happens when the execution group policy setting // is set to AllSigned, and PS is asking user to trust the certificate. if (!WpfConsole.Dispatcher.IsStartCompleted) { return hr; } // if the console is in the middle of executing a command, do not accept any key inputs unless // we are in the middle of a ReadKey call. if (WpfConsole.Dispatcher.IsExecutingCommand) { return hr; } } if (pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97) { //Debug.Print("Exec: GUID_VSStandardCommandSet97: {0}", (VSConstants.VSStd97CmdID)nCmdID); switch ((VSConstants.VSStd97CmdID)nCmdID) { case VSConstants.VSStd97CmdID.Paste: if (IsCaretInReadOnlyRegion || IsSelectionReadonly) { hr = VSConstants.S_OK; // eat it } else { PasteText(ref hr); } break; } } else if (pguidCmdGroup == VSConstants.VSStd2K) { //Debug.Print("Exec: VSStd2K: {0}", (VSConstants.VSStd2KCmdID)nCmdID); var commandID = (VSConstants.VSStd2KCmdID)nCmdID; if (WpfConsole.Dispatcher.IsExecutingReadKey) { switch (commandID) { case VSConstants.VSStd2KCmdID.TYPECHAR: case VSConstants.VSStd2KCmdID.BACKSPACE: case VSConstants.VSStd2KCmdID.RETURN: var keyInfo = GetVsKeyInfo(pvaIn, commandID); WpfConsole.Dispatcher.PostKey(keyInfo); break; case VSConstants.VSStd2KCmdID.CANCEL: // Handle ESC WpfConsole.Dispatcher.CancelWaitKey(); break; default: // ignore everything else break; } hr = VSConstants.S_OK; // eat everything } else { switch (commandID) { case VSConstants.VSStd2KCmdID.TYPECHAR: if (IsCompletionSessionActive) { char ch = (char)(ushort)Marshal.GetObjectForNativeVariant(pvaIn); if (IsCommitChar(ch)) { if (_completionSession.SelectedCompletionSet.SelectionStatus.IsSelected) { _completionSession.Commit(); } else { _completionSession.Dismiss(); } } } else { if (IsSelectionReadonly) { WpfTextView.Selection.Clear(); } if (IsCaretInReadOnlyRegion) { WpfTextView.Caret.MoveTo(WpfConsole.InputLineExtent.End); } } break; case VSConstants.VSStd2KCmdID.LEFT: case VSConstants.VSStd2KCmdID.LEFT_EXT: case VSConstants.VSStd2KCmdID.LEFT_EXT_COL: case VSConstants.VSStd2KCmdID.WORDPREV: case VSConstants.VSStd2KCmdID.WORDPREV_EXT: case VSConstants.VSStd2KCmdID.WORDPREV_EXT_COL: if (IsCaretAtInputLineStart) { // // Note: This simple implementation depends on Prompt containing a trailing space. // When caret is on the right of InputLineStart, editor will handle it correctly, // and caret won't move left to InputLineStart because of the trailing space. // hr = VSConstants.S_OK; // eat it } break; case VSConstants.VSStd2KCmdID.BOL: case VSConstants.VSStd2KCmdID.BOL_EXT: case VSConstants.VSStd2KCmdID.BOL_EXT_COL: if (IsCaretOnInputLine) { VirtualSnapshotPoint oldCaretPoint = WpfTextView.Caret.Position.VirtualBufferPosition; WpfTextView.Caret.MoveTo(WpfConsole.InputLineStart.Value); WpfTextView.Caret.EnsureVisible(); if ((VSConstants.VSStd2KCmdID)nCmdID == VSConstants.VSStd2KCmdID.BOL) { WpfTextView.Selection.Clear(); } else if ((VSConstants.VSStd2KCmdID)nCmdID != VSConstants.VSStd2KCmdID.BOL) // extend selection { VirtualSnapshotPoint anchorPoint = WpfTextView.Selection.IsEmpty ? oldCaretPoint.TranslateTo( WpfTextView.TextSnapshot) : WpfTextView.Selection.AnchorPoint; WpfTextView.Selection.Select(anchorPoint, WpfTextView.Caret.Position.VirtualBufferPosition); } hr = VSConstants.S_OK; } break; case VSConstants.VSStd2KCmdID.UP: if (!IsCompletionSessionActive) { if (IsCaretInReadOnlyRegion) { ExecuteCommand(VSConstants.VSStd2KCmdID.END); } WpfConsole.NavigateHistory(-1); hr = VSConstants.S_OK; } break; case VSConstants.VSStd2KCmdID.DOWN: if (!IsCompletionSessionActive) { if (IsCaretInReadOnlyRegion) { ExecuteCommand(VSConstants.VSStd2KCmdID.END); } WpfConsole.NavigateHistory(+1); hr = VSConstants.S_OK; } break; case VSConstants.VSStd2KCmdID.RETURN: if (IsCompletionSessionActive) { if (_completionSession.SelectedCompletionSet.SelectionStatus.IsSelected) { _completionSession.Commit(); } else { _completionSession.Dismiss(); } } else if (IsCaretOnInputLine || !IsCaretInReadOnlyRegion) { ExecuteCommand(VSConstants.VSStd2KCmdID.END); ExecuteCommand(VSConstants.VSStd2KCmdID.RETURN); WpfConsole.EndInputLine(); } hr = VSConstants.S_OK; break; case VSConstants.VSStd2KCmdID.TAB: if (!IsCaretInReadOnlyRegion) { if (IsCompletionSessionActive) { _completionSession.Commit(); } else { TriggerCompletion(); } } hr = VSConstants.S_OK; break; case VSConstants.VSStd2KCmdID.CANCEL: if (IsCompletionSessionActive) { _completionSession.Dismiss(); hr = VSConstants.S_OK; } else if (!IsCaretInReadOnlyRegion) { // Delete all text after InputLineStart WpfTextView.TextBuffer.Delete(WpfConsole.AllInputExtent); hr = VSConstants.S_OK; } break; case VSConstants.VSStd2KCmdID.CUTLINE: // clears the console when CutLine shortcut key is pressed, // usually it is Ctrl + L WpfConsole.ClearConsole(); hr = VSConstants.S_OK; break; } } } return hr; } private VsKeyInfo GetVsKeyInfo(IntPtr pvaIn, VSConstants.VSStd2KCmdID commandID) { // catch current modifiers as early as possible bool capsLockToggled = Keyboard.IsKeyToggled(Key.CapsLock); bool numLockToggled = Keyboard.IsKeyToggled(Key.NumLock); char keyChar; if ((commandID == VSConstants.VSStd2KCmdID.RETURN) && pvaIn == IntPtr.Zero) { // <enter> pressed keyChar = Environment.NewLine[0]; // [CR]LF } else if ((commandID == VSConstants.VSStd2KCmdID.BACKSPACE) && pvaIn == IntPtr.Zero) { keyChar = '\b'; // backspace control character } else { Debug.Assert(pvaIn != IntPtr.Zero, "pvaIn != IntPtr.Zero"); // 1) deref pointer to char keyChar = (char)(ushort)Marshal.GetObjectForNativeVariant(pvaIn); } // 2) convert from char to virtual key, using current thread's input locale short keyScan = NativeMethods.VkKeyScanEx(keyChar, _pKeybLayout.Value); // 3) virtual key is in LSB, shiftstate in MSB. byte virtualKey = (byte)(keyScan & 0x00ff); keyScan = (short)(keyScan >> 8); byte shiftState = (byte)(keyScan & 0x00ff); // 4) convert from virtual key to wpf key. Key key = KeyInterop.KeyFromVirtualKey(virtualKey); // 5) create nugetconsole.vskeyinfo to marshal info to var keyInfo = VsKeyInfo.Create( key, keyChar, virtualKey, keyStates: KeyStates.Down, capsLockToggled: capsLockToggled, numLockToggled: numLockToggled, shiftPressed: ((shiftState & 1) == 1), controlPressed: ((shiftState & 2) == 4), altPressed: ((shiftState & 4) == 2)); return keyInfo; } private static readonly char[] NEWLINE_CHARS = new char[] { '\n', '\r' }; private void PasteText(ref int hr) { string text = System.Windows.Clipboard.GetText(); int iLineStart = 0; int iNewLine = -1; char c; if (!string.IsNullOrEmpty(text) && (iNewLine = text.IndexOfAny(NEWLINE_CHARS)) >= 0) { ITextBuffer textBuffer = WpfTextView.TextBuffer; while (iLineStart < text.Length) { string pasteLine = (iNewLine >= 0 ? text.Substring(iLineStart, iNewLine - iLineStart) : text.Substring(iLineStart)); if (iLineStart == 0) { if (!WpfTextView.Selection.IsEmpty) { textBuffer.Replace(WpfTextView.Selection.SelectedSpans[0], pasteLine); } else { textBuffer.Insert(WpfTextView.Caret.Position.BufferPosition.Position, pasteLine); } this.Execute(VSConstants.VSStd2KCmdID.RETURN); } else { WpfConsole.Dispatcher.PostInputLine( new InputLine(pasteLine, iNewLine >= 0)); } if (iNewLine < 0) { break; } iLineStart = iNewLine + 1; if (iLineStart < text.Length && (c = text[iLineStart]) != text[iNewLine] && (c == '\n' || c == '\r')) { iLineStart++; } iNewLine = (iLineStart < text.Length ? text.IndexOfAny(NEWLINE_CHARS, iLineStart) : -1); } hr = VSConstants.S_OK; // completed, eat it } } #region completion static bool IsCommitChar(char c) { // TODO: CommandExpansion determines this return (char.IsPunctuation(c) && c != '-' && c != '_') || char.IsWhiteSpace(c); } ICompletionBroker CompletionBroker { get { return WpfConsole.Factory.CompletionBroker; } } ICompletionSession _completionSession; bool IsCompletionSessionActive { get { return _completionSession != null && !_completionSession.IsDismissed; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] void TriggerCompletion() { if (CommandExpansion == null) { return; // Host CommandExpansion service not available } if (IsCompletionSessionActive) { _completionSession.Dismiss(); _completionSession = null; } string line = WpfConsole.InputLineText; int caretIndex = CaretPosition - WpfConsole.InputLineStart.Value; Debug.Assert(caretIndex >= 0); SimpleExpansion simpleExpansion = null; try { simpleExpansion = CommandExpansion.GetExpansions(line, caretIndex); } catch (Exception x) { // Ignore exception from expansion, but write it to the activity log ExceptionHelper.WriteToActivityLog(x); } if (simpleExpansion != null && simpleExpansion.Expansions != null) { IList<string> expansions = simpleExpansion.Expansions; if (expansions.Count == 1) // Shortcut for 1 TabExpansion candidate { ReplaceTabExpansion(simpleExpansion.Start, simpleExpansion.Length, expansions[0]); } else if (expansions.Count > 1) // Only start intellisense session for multiple expansion candidates { _completionSession = CompletionBroker.CreateCompletionSession( WpfTextView, WpfTextView.TextSnapshot.CreateTrackingPoint(CaretPosition.Position, PointTrackingMode.Positive), true); _completionSession.Properties.AddProperty("TabExpansion", simpleExpansion); _completionSession.Dismissed += CompletionSession_Dismissed; _completionSession.Start(); } } } void ReplaceTabExpansion(int lastWordIndex, int length, string expansion) { if (!string.IsNullOrEmpty(expansion)) { SnapshotSpan extent = WpfConsole.GetInputLineExtent(lastWordIndex, length); WpfTextView.TextBuffer.Replace(extent, expansion); } } void CompletionSession_Dismissed(object sender, EventArgs e) { Debug.Assert(this._completionSession == sender); this._completionSession.Dismissed -= CompletionSession_Dismissed; this._completionSession = null; } #endregion } }
/* * Naiad ver. 0.5 * Copyright (c) Microsoft Corporation * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT * LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR * A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Research.Naiad.Serialization; using Microsoft.Research.Naiad.DataStructures; using Microsoft.Research.Naiad.Dataflow.Channels; using Microsoft.Research.Naiad.Scheduling; using Microsoft.Research.Naiad.Frameworks.DifferentialDataflow.CollectionTrace; using System.Linq.Expressions; using System.Diagnostics; using Microsoft.Research.Naiad.Runtime.Progress; using Microsoft.Research.Naiad; using Microsoft.Research.Naiad.Dataflow; using Microsoft.Research.Naiad.Dataflow.StandardVertices; namespace Microsoft.Research.Naiad.Frameworks.DifferentialDataflow.OperatorImplementations { internal class UnaryStatefulIntKeyedOperator<V, S, T, R> : UnaryBufferingVertex<Weighted<S>, Weighted<R>, T> where V : IEquatable<V> where S : IEquatable<S> where T : Time<T> where R : IEquatable<R> { bool inputImmutable = false; public override void OnReceive(Message<Weighted<S>, T> message) { if (this.inputImmutable) { this.NotifyAt(message.time); for (int i = 0; i < message.length; i++) this.OnInput(message.payload[i], message.time); } else base.OnReceive(message); } protected CollectionTraceWithHeap<R> createOutputTrace() { return new CollectionTraceWithHeap<R>((x, y) => internTable.LessThan(x, y), x => internTable.UpdateTime(x), this.Stage.Placement.Count); } protected virtual CollectionTraceCheckpointable<V> createInputTrace() { if (Microsoft.Research.Naiad.Utilities.ExpressionComparer.Instance.Equals(keyExpression, valueExpression)) { if (this.inputImmutable) return new CollectionTraceImmutableNoHeap<V>(); else return new CollectionTraceWithoutHeap<V>((x, y) => internTable.LessThan(x, y), x => internTable.UpdateTime(x)); } else { if (this.inputImmutable) return new CollectionTraceImmutable<V>(); else return new CollectionTraceWithHeap<V>((x, y) => internTable.LessThan(x, y), x => internTable.UpdateTime(x), this.Stage.Placement.Count); } } protected override void OnShutdown() { base.OnShutdown(); if (inputTrace != null) inputTrace.Release(); inputTrace = null; if (outputTrace != null) outputTrace.Release(); outputTrace = null; internTable = null; keyIndices = null; keysToProcess = null; } protected override void UpdateReachability(List<Pointstamp> causalTimes) { base.UpdateReachability(causalTimes); if (causalTimes != null && internTable != null) internTable.UpdateReachability(causalTimes); } public readonly Func<S, int> key; // extracts the key from the input record public readonly Func<S, V> value; // reduces input record to relevant value public readonly Expression<Func<S, int>> keyExpression; public readonly Expression<Func<S, V>> valueExpression; readonly bool MaintainOutputTrace; public override void OnNotify(T workTime) { if (!this.inputImmutable) foreach (var item in this.Input.GetRecordsAt(workTime)) OnInput(item, workTime); Compute(); Flush(); //if (this.inputImmutable) // this.ShutDown(); } protected LatticeInternTable<T> internTable; protected CollectionTraceCheckpointable<V> inputTrace; // collects all differences that have processed. protected CollectionTraceCheckpointable<R> outputTrace; // collects outputs protected UnaryKeyIndices[][] keyIndices; protected NaiadList<int> keysToProcess = new NaiadList<int>(1); public virtual void OnInput(Weighted<S> entry, T time) { var k = key(entry.record); var index = (int)(k / this.Stage.Placement.Count); if (keyIndices[index / 65536] == null) keyIndices[index / 65536] = new UnaryKeyIndices[65536]; keysToProcess.Add(index); inputTrace.Introduce(ref keyIndices[index / 65536][index % 65536].unprocessed, value(entry.record), entry.weight, internTable.Intern(time)); } public virtual void Compute() { for (int i = 0; i < keysToProcess.Count; i++) Update(keysToProcess.Array[i]); inputTrace.Compact(); outputTrace.Compact(); keysToProcess.Clear(); } protected NaiadList<Weighted<V>> collection = new NaiadList<Weighted<V>>(1); protected NaiadList<Weighted<V>> difference = new NaiadList<Weighted<V>>(1); // Moves from unprocessed[key] to processed[key], updating output[key] and Send()ing. protected int outputWorkspace; protected virtual void Update(int index) { var traceIndices = keyIndices[index / 65536][index % 65536]; if (traceIndices.unprocessed != 0) { inputTrace.EnsureStateIsCurrentWRTAdvancedTimes(ref traceIndices.processed); //inputTrace.EnsureStateIsCurrentWRTAdvancedTimes(ref traceIndices.unprocessed); if (MaintainOutputTrace) outputTrace.EnsureStateIsCurrentWRTAdvancedTimes(ref traceIndices.output); // iterate through the times that may require updates. var interestingTimes = InterestingTimes(traceIndices); // incorporate the updates, so we can compare old and new outputs. inputTrace.IntroduceFrom(ref traceIndices.processed, ref traceIndices.unprocessed, false); for (int i = 0; i < interestingTimes.Count; i++) UpdateTime(index, traceIndices, interestingTimes.Array[i]); // clean out the state we just processed inputTrace.ZeroState(ref traceIndices.unprocessed); // move the differences we produced from local to persistent storage. if (MaintainOutputTrace) outputTrace.IntroduceFrom(ref traceIndices.output, ref outputWorkspace); else outputTrace.ZeroState(ref outputWorkspace); keyIndices[index / 65536][index % 65536] = traceIndices; } } protected NaiadList<int> timeList = new NaiadList<int>(1); protected NaiadList<int> truthList = new NaiadList<int>(1); protected NaiadList<int> deltaList = new NaiadList<int>(1); protected virtual NaiadList<int> InterestingTimes(UnaryKeyIndices keyIndices) { deltaList.Clear(); inputTrace.EnumerateTimes(keyIndices.unprocessed, deltaList); truthList.Clear(); inputTrace.EnumerateTimes(keyIndices.processed, truthList); timeList.Clear(); this.internTable.InterestingTimes(timeList, truthList, deltaList); return timeList; } protected virtual void UpdateTime(int index, UnaryKeyIndices keyIndices, int timeIndex) { // subtract out prior output updates before adding new ones outputTrace.SubtractStrictlyPriorDifferences(ref outputWorkspace, timeIndex); NewOutputMinusOldOutput(index, keyIndices, timeIndex); var outputTime = this.internTable.times[timeIndex]; toSend.Clear(); outputTrace.EnumerateDifferenceAt(outputWorkspace, timeIndex, toSend); var output = this.Output.GetBufferForTime(outputTime); for (int i = 0; i < toSend.Count; i++) output.Send(toSend.Array[i]); } protected NaiadList<Weighted<R>> toSend = new NaiadList<Weighted<R>>(1); protected virtual void NewOutputMinusOldOutput(int index, UnaryKeyIndices keyIndices, int timeIndex) { if (!MaintainOutputTrace) throw new Exception("Override NewOutputMinusOldOutput or set MaintainOutputTrace"); if (keyIndices.processed != 0) Reduce(index, keyIndices, timeIndex); toSend.Clear(); outputTrace.EnumerateCollectionAt(keyIndices.output, timeIndex, toSend); for (int i = 0; i < toSend.Count; i++) outputTrace.Introduce(ref outputWorkspace, toSend.Array[i].record, -toSend.Array[i].weight, timeIndex); } // expected to populate resultList to match reduction(collection.source) protected virtual void Reduce(int index, UnaryKeyIndices keyIndices, int time) { //var key = index * this.Stage.Placement.Count + this.VertexId; } /* Checkpoint format: * bool terminated * if !terminated: * LatticeInternTable<T> internTable * CollectionTrace<> inputTrace * CollectionTrace<> outputTrace * int keyIndicesCount * (K,KeyIndices)*keyIndicesCount keyIndices * int recordsToProcessCount * (T,NaiadList<Weighted<S>>)*recordsToProcessCount recordsToProcess */ // keyIndices is spined list protected override void Checkpoint(NaiadWriter writer) { base.Checkpoint(writer); writer.Write(this.isShutdown); if (!this.isShutdown) { this.internTable.Checkpoint(writer); this.inputTrace.Checkpoint(writer); this.outputTrace.Checkpoint(writer); for (int i = 0; i < this.keyIndices.Length; ++i) { if (this.keyIndices[i] == null) writer.Write(0); else { writer.Write(this.keyIndices[i].Length); for (int j = 0; j < this.keyIndices[i].Length; ++j) writer.Write(this.keyIndices[i][j]); } } this.keysToProcess.Checkpoint(writer); this.Input.Checkpoint(writer); } } protected override void Restore(NaiadReader reader) { base.Restore(reader); this.isShutdown = reader.Read<bool>(); if (!this.isShutdown) { this.internTable.Restore(reader); this.inputTrace.Restore(reader); this.outputTrace.Restore(reader); for (int i = 0; i < this.keyIndices.Length; ++i) { int length = reader.Read<int>(); if (length == 0) this.keyIndices[i] = null; else { Debug.Assert(length == 65536); this.keyIndices[i] = new UnaryKeyIndices[length]; for (int j = 0; j < this.keyIndices[i].Length; ++j) this.keyIndices[i][j] = reader.Read<UnaryKeyIndices>(); } } this.keysToProcess.Restore(reader); this.Input.Restore(reader); } } public UnaryStatefulIntKeyedOperator(int index, Stage<T> collection, bool immutableInput, Expression<Func<S, int>> k, Expression<Func<S, V>> v, bool maintainOutputTrace = true) : base(index, collection, null) { key = k.Compile(); value = v.Compile(); keyExpression = k; valueExpression = v; MaintainOutputTrace = maintainOutputTrace; if (immutableInput) this.inputImmutable = true; internTable = new LatticeInternTable<T>(); keyIndices = new UnaryKeyIndices[65536][]; inputTrace = createInputTrace(); outputTrace = createOutputTrace(); //this.Input = new Naiad.Frameworks.RecvFiberBank<Weighted<S>, T>(this, collection.Input); //if (inputImmutable) // collection.Input.Register(new ActionReceiver<Weighted<S>, T>(this, x => { this.OnInput(x.s, x.t); this.ScheduleAt(x.t); })); #if false if (this.inputImmutable) this.input = new ActionReceiver<Weighted<S>, T>(this, x => { this.OnInput(x.s, x.t); this.ScheduleAt(x.t); }); else { this.RecvInput = new Naiad.Frameworks.RecvFiberBank<Weighted<S>, T>(this); this.input = this.RecvInput; } #endif } } }
using System; namespace ICSharpCode.SharpZipLib.Zip.Compression { /// <summary> /// This is the DeflaterHuffman class. /// /// This class is <i>not</i> thread safe. This is inherent in the API, due /// to the split of Deflate and SetInput. /// /// author of the original java version : Jochen Hoenicke /// </summary> public class DeflaterHuffman { private const int BUFSIZE = 1 << (DeflaterConstants.DEFAULT_MEM_LEVEL + 6); private const int LITERAL_NUM = 286; // Number of distance codes private const int DIST_NUM = 30; // Number of codes used to transfer bit lengths private const int BITLEN_NUM = 19; // repeat previous bit length 3-6 times (2 bits of repeat count) private const int REP_3_6 = 16; // repeat a zero length 3-10 times (3 bits of repeat count) private const int REP_3_10 = 17; // repeat a zero length 11-138 times (7 bits of repeat count) private const int REP_11_138 = 18; private const int EOF_SYMBOL = 256; // The lengths of the bit length codes are sent in order of decreasing // probability, to avoid transmitting the lengths for unused bit length codes. private static readonly int[] BL_ORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; private static readonly byte[] bit4Reverse = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 }; private static short[] staticLCodes; private static byte[] staticLLength; private static short[] staticDCodes; private static byte[] staticDLength; private class Tree { #region Instance Fields public short[] freqs; public byte[] length; public int minNumCodes; public int numCodes; private short[] codes; private readonly int[] bl_counts; private readonly int maxLength; private DeflaterHuffman dh; #endregion Instance Fields #region Constructors public Tree(DeflaterHuffman dh, int elems, int minCodes, int maxLength) { this.dh = dh; this.minNumCodes = minCodes; this.maxLength = maxLength; freqs = new short[elems]; bl_counts = new int[maxLength]; } #endregion Constructors /// <summary> /// Resets the internal state of the tree /// </summary> public void Reset() { for (int i = 0; i < freqs.Length; i++) { freqs[i] = 0; } codes = null; length = null; } public void WriteSymbol(int code) { // if (DeflaterConstants.DEBUGGING) { // freqs[code]--; // // Console.Write("writeSymbol("+freqs.length+","+code+"): "); // } dh.pending.WriteBits(codes[code] & 0xffff, length[code]); } /// <summary> /// Check that all frequencies are zero /// </summary> /// <exception cref="SharpZipBaseException"> /// At least one frequency is non-zero /// </exception> public void CheckEmpty() { bool empty = true; for (int i = 0; i < freqs.Length; i++) { empty &= freqs[i] == 0; } if (!empty) { throw new SharpZipBaseException("!Empty"); } } /// <summary> /// Set static codes and length /// </summary> /// <param name="staticCodes">new codes</param> /// <param name="staticLengths">length for new codes</param> public void SetStaticCodes(short[] staticCodes, byte[] staticLengths) { codes = staticCodes; length = staticLengths; } /// <summary> /// Build dynamic codes and lengths /// </summary> public void BuildCodes() { int numSymbols = freqs.Length; int[] nextCode = new int[maxLength]; int code = 0; codes = new short[freqs.Length]; // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("buildCodes: "+freqs.Length); // } for (int bits = 0; bits < maxLength; bits++) { nextCode[bits] = code; code += bl_counts[bits] << (15 - bits); // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("bits: " + ( bits + 1) + " count: " + bl_counts[bits] // +" nextCode: "+code); // } } #if DebugDeflation if ( DeflaterConstants.DEBUGGING && (code != 65536) ) { throw new SharpZipBaseException("Inconsistent bl_counts!"); } #endif for (int i = 0; i < numCodes; i++) { int bits = length[i]; if (bits > 0) { // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("codes["+i+"] = rev(" + nextCode[bits-1]+"), // +bits); // } codes[i] = BitReverse(nextCode[bits - 1]); nextCode[bits - 1] += 1 << (16 - bits); } } } public void BuildTree() { int numSymbols = freqs.Length; /* heap is a priority queue, sorted by frequency, least frequent * nodes first. The heap is a binary tree, with the property, that * the parent node is smaller than both child nodes. This assures * that the smallest node is the first parent. * * The binary tree is encoded in an array: 0 is root node and * the nodes 2*n+1, 2*n+2 are the child nodes of node n. */ int[] heap = new int[numSymbols]; int heapLen = 0; int maxCode = 0; for (int n = 0; n < numSymbols; n++) { int freq = freqs[n]; if (freq != 0) { // Insert n into heap int pos = heapLen++; int ppos; while (pos > 0 && freqs[heap[ppos = (pos - 1) / 2]] > freq) { heap[pos] = heap[ppos]; pos = ppos; } heap[pos] = n; maxCode = n; } } /* We could encode a single literal with 0 bits but then we * don't see the literals. Therefore we force at least two * literals to avoid this case. We don't care about order in * this case, both literals get a 1 bit code. */ while (heapLen < 2) { int node = maxCode < 2 ? ++maxCode : 0; heap[heapLen++] = node; } numCodes = Math.Max(maxCode + 1, minNumCodes); int numLeafs = heapLen; int[] childs = new int[4 * heapLen - 2]; int[] values = new int[2 * heapLen - 1]; int numNodes = numLeafs; for (int i = 0; i < heapLen; i++) { int node = heap[i]; childs[2 * i] = node; childs[2 * i + 1] = -1; values[i] = freqs[node] << 8; heap[i] = i; } /* Construct the Huffman tree by repeatedly combining the least two * frequent nodes. */ do { int first = heap[0]; int last = heap[--heapLen]; // Propagate the hole to the leafs of the heap int ppos = 0; int path = 1; while (path < heapLen) { if (path + 1 < heapLen && values[heap[path]] > values[heap[path + 1]]) { path++; } heap[ppos] = heap[path]; ppos = path; path = path * 2 + 1; } /* Now propagate the last element down along path. Normally * it shouldn't go too deep. */ int lastVal = values[last]; while ((path = ppos) > 0 && values[heap[ppos = (path - 1) / 2]] > lastVal) { heap[path] = heap[ppos]; } heap[path] = last; int second = heap[0]; // Create a new node father of first and second last = numNodes++; childs[2 * last] = first; childs[2 * last + 1] = second; int mindepth = Math.Min(values[first] & 0xff, values[second] & 0xff); values[last] = lastVal = values[first] + values[second] - mindepth + 1; // Again, propagate the hole to the leafs ppos = 0; path = 1; while (path < heapLen) { if (path + 1 < heapLen && values[heap[path]] > values[heap[path + 1]]) { path++; } heap[ppos] = heap[path]; ppos = path; path = ppos * 2 + 1; } // Now propagate the new element down along path while ((path = ppos) > 0 && values[heap[ppos = (path - 1) / 2]] > lastVal) { heap[path] = heap[ppos]; } heap[path] = last; } while (heapLen > 1); if (heap[0] != childs.Length / 2 - 1) { throw new SharpZipBaseException("Heap invariant violated"); } BuildLength(childs); } /// <summary> /// Get encoded length /// </summary> /// <returns>Encoded length, the sum of frequencies * lengths</returns> public int GetEncodedLength() { int len = 0; for (int i = 0; i < freqs.Length; i++) { len += freqs[i] * length[i]; } return len; } /// <summary> /// Scan a literal or distance tree to determine the frequencies of the codes /// in the bit length tree. /// </summary> public void CalcBLFreq(Tree blTree) { int max_count; /* max repeat count */ int min_count; /* min repeat count */ int count; /* repeat count of the current code */ int curlen = -1; /* length of current code */ int i = 0; while (i < numCodes) { count = 1; int nextlen = length[i]; if (nextlen == 0) { max_count = 138; min_count = 3; } else { max_count = 6; min_count = 3; if (curlen != nextlen) { blTree.freqs[nextlen]++; count = 0; } } curlen = nextlen; i++; while (i < numCodes && curlen == length[i]) { i++; if (++count >= max_count) { break; } } if (count < min_count) { blTree.freqs[curlen] += (short)count; } else if (curlen != 0) { blTree.freqs[REP_3_6]++; } else if (count <= 10) { blTree.freqs[REP_3_10]++; } else { blTree.freqs[REP_11_138]++; } } } /// <summary> /// Write tree values /// </summary> /// <param name="blTree">Tree to write</param> public void WriteTree(Tree blTree) { int max_count; // max repeat count int min_count; // min repeat count int count; // repeat count of the current code int curlen = -1; // length of current code int i = 0; while (i < numCodes) { count = 1; int nextlen = length[i]; if (nextlen == 0) { max_count = 138; min_count = 3; } else { max_count = 6; min_count = 3; if (curlen != nextlen) { blTree.WriteSymbol(nextlen); count = 0; } } curlen = nextlen; i++; while (i < numCodes && curlen == length[i]) { i++; if (++count >= max_count) { break; } } if (count < min_count) { while (count-- > 0) { blTree.WriteSymbol(curlen); } } else if (curlen != 0) { blTree.WriteSymbol(REP_3_6); dh.pending.WriteBits(count - 3, 2); } else if (count <= 10) { blTree.WriteSymbol(REP_3_10); dh.pending.WriteBits(count - 3, 3); } else { blTree.WriteSymbol(REP_11_138); dh.pending.WriteBits(count - 11, 7); } } } private void BuildLength(int[] childs) { this.length = new byte[freqs.Length]; int numNodes = childs.Length / 2; int numLeafs = (numNodes + 1) / 2; int overflow = 0; for (int i = 0; i < maxLength; i++) { bl_counts[i] = 0; } // First calculate optimal bit lengths int[] lengths = new int[numNodes]; lengths[numNodes - 1] = 0; for (int i = numNodes - 1; i >= 0; i--) { if (childs[2 * i + 1] != -1) { int bitLength = lengths[i] + 1; if (bitLength > maxLength) { bitLength = maxLength; overflow++; } lengths[childs[2 * i]] = lengths[childs[2 * i + 1]] = bitLength; } else { // A leaf node int bitLength = lengths[i]; bl_counts[bitLength - 1]++; this.length[childs[2 * i]] = (byte)lengths[i]; } } // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("Tree "+freqs.Length+" lengths:"); // for (int i=0; i < numLeafs; i++) { // //Console.WriteLine("Node "+childs[2*i]+" freq: "+freqs[childs[2*i]] // + " len: "+length[childs[2*i]]); // } // } if (overflow == 0) { return; } int incrBitLen = maxLength - 1; do { // Find the first bit length which could increase: while (bl_counts[--incrBitLen] == 0) { } // Move this node one down and remove a corresponding // number of overflow nodes. do { bl_counts[incrBitLen]--; bl_counts[++incrBitLen]++; overflow -= 1 << (maxLength - 1 - incrBitLen); } while (overflow > 0 && incrBitLen < maxLength - 1); } while (overflow > 0); /* We may have overshot above. Move some nodes from maxLength to * maxLength-1 in that case. */ bl_counts[maxLength - 1] += overflow; bl_counts[maxLength - 2] -= overflow; /* Now recompute all bit lengths, scanning in increasing * frequency. It is simpler to reconstruct all lengths instead of * fixing only the wrong ones. This idea is taken from 'ar' * written by Haruhiko Okumura. * * The nodes were inserted with decreasing frequency into the childs * array. */ int nodePtr = 2 * numLeafs; for (int bits = maxLength; bits != 0; bits--) { int n = bl_counts[bits - 1]; while (n > 0) { int childPtr = 2 * childs[nodePtr++]; if (childs[childPtr + 1] == -1) { // We found another leaf length[childs[childPtr]] = (byte)bits; n--; } } } // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("*** After overflow elimination. ***"); // for (int i=0; i < numLeafs; i++) { // //Console.WriteLine("Node "+childs[2*i]+" freq: "+freqs[childs[2*i]] // + " len: "+length[childs[2*i]]); // } // } } } #region Instance Fields /// <summary> /// Pending buffer to use /// </summary> public DeflaterPending pending; private Tree literalTree; private Tree distTree; private Tree blTree; // Buffer for distances private short[] d_buf; private byte[] l_buf; private int last_lit; private int extra_bits; #endregion Instance Fields static DeflaterHuffman() { // See RFC 1951 3.2.6 // Literal codes staticLCodes = new short[LITERAL_NUM]; staticLLength = new byte[LITERAL_NUM]; int i = 0; while (i < 144) { staticLCodes[i] = BitReverse((0x030 + i) << 8); staticLLength[i++] = 8; } while (i < 256) { staticLCodes[i] = BitReverse((0x190 - 144 + i) << 7); staticLLength[i++] = 9; } while (i < 280) { staticLCodes[i] = BitReverse((0x000 - 256 + i) << 9); staticLLength[i++] = 7; } while (i < LITERAL_NUM) { staticLCodes[i] = BitReverse((0x0c0 - 280 + i) << 8); staticLLength[i++] = 8; } // Distance codes staticDCodes = new short[DIST_NUM]; staticDLength = new byte[DIST_NUM]; for (i = 0; i < DIST_NUM; i++) { staticDCodes[i] = BitReverse(i << 11); staticDLength[i] = 5; } } /// <summary> /// Construct instance with pending buffer /// </summary> /// <param name="pending">Pending buffer to use</param> public DeflaterHuffman(DeflaterPending pending) { this.pending = pending; literalTree = new Tree(this, LITERAL_NUM, 257, 15); distTree = new Tree(this, DIST_NUM, 1, 15); blTree = new Tree(this, BITLEN_NUM, 4, 7); d_buf = new short[BUFSIZE]; l_buf = new byte[BUFSIZE]; } /// <summary> /// Reset internal state /// </summary> public void Reset() { last_lit = 0; extra_bits = 0; literalTree.Reset(); distTree.Reset(); blTree.Reset(); } /// <summary> /// Write all trees to pending buffer /// </summary> /// <param name="blTreeCodes">The number/rank of treecodes to send.</param> public void SendAllTrees(int blTreeCodes) { blTree.BuildCodes(); literalTree.BuildCodes(); distTree.BuildCodes(); pending.WriteBits(literalTree.numCodes - 257, 5); pending.WriteBits(distTree.numCodes - 1, 5); pending.WriteBits(blTreeCodes - 4, 4); for (int rank = 0; rank < blTreeCodes; rank++) { pending.WriteBits(blTree.length[BL_ORDER[rank]], 3); } literalTree.WriteTree(blTree); distTree.WriteTree(blTree); #if DebugDeflation if (DeflaterConstants.DEBUGGING) { blTree.CheckEmpty(); } #endif } /// <summary> /// Compress current buffer writing data to pending buffer /// </summary> public void CompressBlock() { for (int i = 0; i < last_lit; i++) { int litlen = l_buf[i] & 0xff; int dist = d_buf[i]; if (dist-- != 0) { // if (DeflaterConstants.DEBUGGING) { // Console.Write("["+(dist+1)+","+(litlen+3)+"]: "); // } int lc = Lcode(litlen); literalTree.WriteSymbol(lc); int bits = (lc - 261) / 4; if (bits > 0 && bits <= 5) { pending.WriteBits(litlen & ((1 << bits) - 1), bits); } int dc = Dcode(dist); distTree.WriteSymbol(dc); bits = dc / 2 - 1; if (bits > 0) { pending.WriteBits(dist & ((1 << bits) - 1), bits); } } else { // if (DeflaterConstants.DEBUGGING) { // if (litlen > 32 && litlen < 127) { // Console.Write("("+(char)litlen+"): "); // } else { // Console.Write("{"+litlen+"}: "); // } // } literalTree.WriteSymbol(litlen); } } #if DebugDeflation if (DeflaterConstants.DEBUGGING) { Console.Write("EOF: "); } #endif literalTree.WriteSymbol(EOF_SYMBOL); #if DebugDeflation if (DeflaterConstants.DEBUGGING) { literalTree.CheckEmpty(); distTree.CheckEmpty(); } #endif } /// <summary> /// Flush block to output with no compression /// </summary> /// <param name="stored">Data to write</param> /// <param name="storedOffset">Index of first byte to write</param> /// <param name="storedLength">Count of bytes to write</param> /// <param name="lastBlock">True if this is the last block</param> public void FlushStoredBlock(byte[] stored, int storedOffset, int storedLength, bool lastBlock) { #if DebugDeflation // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("Flushing stored block "+ storedLength); // } #endif pending.WriteBits((DeflaterConstants.STORED_BLOCK << 1) + (lastBlock ? 1 : 0), 3); pending.AlignToByte(); pending.WriteShort(storedLength); pending.WriteShort(~storedLength); pending.WriteBlock(stored, storedOffset, storedLength); Reset(); } /// <summary> /// Flush block to output with compression /// </summary> /// <param name="stored">Data to flush</param> /// <param name="storedOffset">Index of first byte to flush</param> /// <param name="storedLength">Count of bytes to flush</param> /// <param name="lastBlock">True if this is the last block</param> public void FlushBlock(byte[] stored, int storedOffset, int storedLength, bool lastBlock) { literalTree.freqs[EOF_SYMBOL]++; // Build trees literalTree.BuildTree(); distTree.BuildTree(); // Calculate bitlen frequency literalTree.CalcBLFreq(blTree); distTree.CalcBLFreq(blTree); // Build bitlen tree blTree.BuildTree(); int blTreeCodes = 4; for (int i = 18; i > blTreeCodes; i--) { if (blTree.length[BL_ORDER[i]] > 0) { blTreeCodes = i + 1; } } int opt_len = 14 + blTreeCodes * 3 + blTree.GetEncodedLength() + literalTree.GetEncodedLength() + distTree.GetEncodedLength() + extra_bits; int static_len = extra_bits; for (int i = 0; i < LITERAL_NUM; i++) { static_len += literalTree.freqs[i] * staticLLength[i]; } for (int i = 0; i < DIST_NUM; i++) { static_len += distTree.freqs[i] * staticDLength[i]; } if (opt_len >= static_len) { // Force static trees opt_len = static_len; } if (storedOffset >= 0 && storedLength + 4 < opt_len >> 3) { // Store Block // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("Storing, since " + storedLength + " < " + opt_len // + " <= " + static_len); // } FlushStoredBlock(stored, storedOffset, storedLength, lastBlock); } else if (opt_len == static_len) { // Encode with static tree pending.WriteBits((DeflaterConstants.STATIC_TREES << 1) + (lastBlock ? 1 : 0), 3); literalTree.SetStaticCodes(staticLCodes, staticLLength); distTree.SetStaticCodes(staticDCodes, staticDLength); CompressBlock(); Reset(); } else { // Encode with dynamic tree pending.WriteBits((DeflaterConstants.DYN_TREES << 1) + (lastBlock ? 1 : 0), 3); SendAllTrees(blTreeCodes); CompressBlock(); Reset(); } } /// <summary> /// Get value indicating if internal buffer is full /// </summary> /// <returns>true if buffer is full</returns> public bool IsFull() { return last_lit >= BUFSIZE; } /// <summary> /// Add literal to buffer /// </summary> /// <param name="literal">Literal value to add to buffer.</param> /// <returns>Value indicating internal buffer is full</returns> public bool TallyLit(int literal) { // if (DeflaterConstants.DEBUGGING) { // if (lit > 32 && lit < 127) { // //Console.WriteLine("("+(char)lit+")"); // } else { // //Console.WriteLine("{"+lit+"}"); // } // } d_buf[last_lit] = 0; l_buf[last_lit++] = (byte)literal; literalTree.freqs[literal]++; return IsFull(); } /// <summary> /// Add distance code and length to literal and distance trees /// </summary> /// <param name="distance">Distance code</param> /// <param name="length">Length</param> /// <returns>Value indicating if internal buffer is full</returns> public bool TallyDist(int distance, int length) { // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("[" + distance + "," + length + "]"); // } d_buf[last_lit] = (short)distance; l_buf[last_lit++] = (byte)(length - 3); int lc = Lcode(length - 3); literalTree.freqs[lc]++; if (lc >= 265 && lc < 285) { extra_bits += (lc - 261) / 4; } int dc = Dcode(distance - 1); distTree.freqs[dc]++; if (dc >= 4) { extra_bits += dc / 2 - 1; } return IsFull(); } /// <summary> /// Reverse the bits of a 16 bit value. /// </summary> /// <param name="toReverse">Value to reverse bits</param> /// <returns>Value with bits reversed</returns> public static short BitReverse(int toReverse) { return (short)(bit4Reverse[toReverse & 0xF] << 12 | bit4Reverse[(toReverse >> 4) & 0xF] << 8 | bit4Reverse[(toReverse >> 8) & 0xF] << 4 | bit4Reverse[toReverse >> 12]); } private static int Lcode(int length) { if (length == 255) { return 285; } int code = 257; while (length >= 8) { code += 4; length >>= 1; } return code + length; } private static int Dcode(int distance) { int code = 0; while (distance >= 4) { code += 2; distance >>= 1; } return code + distance; } } }
using System; using IBatisNet.Common.Test.Domain; using IBatisNet.Common.Utilities; using IBatisNet.Common.Utilities.Objects.Members; using NUnit.Framework; namespace IBatisNet.Common.Test.NUnit.CommonTests.Utilities { [TestFixture] public class PropertyAccessorTest : BaseMemberTest { #region SetUp & TearDown /// <summary> /// SetUp /// </summary> [SetUp] public void SetUp() { intSetAccessor = factorySet.CreateSetAccessor(typeof(Property), "Int"); intGetAccessor = factoryGet.CreateGetAccessor(typeof(Property), "Int"); longSetAccessor = factorySet.CreateSetAccessor(typeof(Property), "Long"); longGetAccessor = factoryGet.CreateGetAccessor(typeof(Property), "Long"); sbyteSetAccessor = factorySet.CreateSetAccessor(typeof(Property), "SByte"); sbyteGetAccessor = factoryGet.CreateGetAccessor(typeof(Property), "SByte"); stringSetAccessor = factorySet.CreateSetAccessor(typeof(Property), "String"); stringGetAccessor = factoryGet.CreateGetAccessor(typeof(Property), "String"); datetimeSetAccessor = factorySet.CreateSetAccessor(typeof(Property), "DateTime"); datetimeGetAccessor = factoryGet.CreateGetAccessor(typeof(Property), "DateTime"); decimalSetAccessor = factorySet.CreateSetAccessor(typeof(Property), "Decimal"); decimalGetAccessor = factoryGet.CreateGetAccessor(typeof(Property), "Decimal"); byteSetAccessor = factorySet.CreateSetAccessor(typeof(Property), "Byte"); byteGetAccessor = factoryGet.CreateGetAccessor(typeof(Property), "Byte"); charSetAccessor = factorySet.CreateSetAccessor(typeof(Property), "Char"); charGetAccessor = factoryGet.CreateGetAccessor(typeof(Property), "Char"); shortSetAccessor = factorySet.CreateSetAccessor(typeof(Property), "Short"); shortGetAccessor = factoryGet.CreateGetAccessor(typeof(Property), "Short"); ushortSetAccessor = factorySet.CreateSetAccessor(typeof(Property), "UShort"); ushortGetAccessor = factoryGet.CreateGetAccessor(typeof(Property), "UShort"); uintSetAccessor = factorySet.CreateSetAccessor(typeof(Property), "UInt"); uintGetAccessor = factoryGet.CreateGetAccessor(typeof(Property), "UInt"); ulongSetAccessor = factorySet.CreateSetAccessor(typeof(Property), "ULong"); ulongGetAccessor = factoryGet.CreateGetAccessor(typeof(Property), "ULong"); boolSetAccessor = factorySet.CreateSetAccessor(typeof(Property), "Bool"); boolGetAccessor = factoryGet.CreateGetAccessor(typeof(Property), "Bool"); doubleSetAccessor = factorySet.CreateSetAccessor(typeof(Property), "Double"); doubleGetAccessor = factoryGet.CreateGetAccessor(typeof(Property), "Double"); floatSetAccessor = factorySet.CreateSetAccessor(typeof(Property), "Float"); floatGetAccessor = factoryGet.CreateGetAccessor(typeof(Property), "Float"); guidSetAccessor = factorySet.CreateSetAccessor(typeof(Property), "Guid"); guidGetAccessor = factoryGet.CreateGetAccessor(typeof(Property), "Guid"); timespanSetAccessor = factorySet.CreateSetAccessor(typeof(Property), "TimeSpan"); timespanGetAccessor = factoryGet.CreateGetAccessor(typeof(Property), "TimeSpan"); accountSetAccessor = factorySet.CreateSetAccessor(typeof(Property), "Account"); accountGetAccessor = factoryGet.CreateGetAccessor(typeof(Property), "Account"); enumSetAccessor = factorySet.CreateSetAccessor(typeof(Property), "Day"); enumGetAccessor = factoryGet.CreateGetAccessor(typeof(Property), "Day"); #if dotnet2 nullableSetAccessor = factorySet.CreateSetAccessor(typeof(Property), "IntNullable"); nullableGetAccessor = factoryGet.CreateGetAccessor(typeof(Property), "IntNullable"); #endif } /// <summary> /// TearDown /// </summary> [TearDown] public void Dispose() { } #endregion /// <summary> /// Test Finding properties on interfaces which "inherites" other interfaces /// </summary> [Test] public void TestJIRA210OnGet() { //---------------------------- IGetAccessor addressGet = factoryGet.CreateGetAccessor(typeof(User), "Address"); User user = new User(); user.Address = new Address(); Guid newGuid = Guid.NewGuid(); user.Address.Id = newGuid; IAddress address = (IAddress)addressGet.Get(user); Assert.IsNotNull(address); Assert.AreEqual(newGuid, address.Id); IGetAccessor domainGet = factoryGet.CreateGetAccessor(typeof(IAddress), "Id"); Guid guid = (Guid)domainGet.Get(address); Assert.AreEqual(newGuid, guid); } /// <summary> /// Test Finding properties on interfaces which "inherites" other interfaces /// </summary> [Test] public void TestJIRA210OnSet() { Address adr = new Address(); Guid newGuid = Guid.NewGuid(); ISetAccessor domainSet = factorySet.CreateSetAccessor(typeof(IAddress), "Id"); domainSet.Set(adr, newGuid); Assert.AreEqual(newGuid, adr.Id ); } /// <summary> /// Test multiple call to factory /// </summary> [Test] public void TestMemberAccessorFactory() { IGetAccessor accessor11 = factoryGet.CreateGetAccessor(typeof(Property), "Int"); IGetAccessor accessor12 = factoryGet.CreateGetAccessor(typeof(Property), "Int"); Assert.AreEqual(HashCodeProvider.GetIdentityHashCode(accessor11), HashCodeProvider.GetIdentityHashCode(accessor12)); ISetAccessor accessor21 = factorySet.CreateSetAccessor(typeof(Property), "Int"); ISetAccessor accessor22 = factorySet.CreateSetAccessor(typeof(Property), "Int"); Assert.AreEqual(HashCodeProvider.GetIdentityHashCode(accessor21), HashCodeProvider.GetIdentityHashCode(accessor22)); } /// <summary> /// Test multiple IGetAccessor /// </summary> [Test] public void TestMultipleMemberAccessorFactory() { Property prop = new Property(); IGetAccessor accessor1 = factoryGet.CreateGetAccessor(typeof(Property), "Int"); IGetAccessorFactory factory2 = new GetAccessorFactory(true); IGetAccessor accessor2 = factory2.CreateGetAccessor(typeof(Property), "Int"); Assert.AreEqual(int.MinValue, accessor1.Get(prop)); Assert.AreEqual(int.MinValue, accessor2.Get(prop)); } /// <summary> /// Test accessor on virtual property /// </summary> [Test] [ExpectedException(typeof(InvalidOperationException), "Test virtual")] public void TestVirtualIMemberAccessor1() { IGetAccessor accessorGet = factoryGet.CreateGetAccessor(typeof(PropertySon), "Account"); ISetAccessor accessorSet = factorySet.CreateSetAccessor(typeof(PropertySon), "Account"); PropertySon son = new PropertySon(); Account account = (Account)accessorGet.Get(son); Assert.IsTrue(account.Days == Days.Wed); accessorSet.Set(son, new Account()); } /// <summary> /// Test accessor on virtual property /// </summary> [Test] [ExpectedException(typeof(InvalidOperationException), "Test virtual")] public void TestVirtualIMemberAccessor2() { IGetAccessor accessorGet = factoryGet.CreateGetAccessor(typeof(PropertySon), "Int"); ISetAccessor accessorSet = factorySet.CreateSetAccessor(typeof(PropertySon), "Int"); PropertySon son = new PropertySon(); Int32 i = (Int32)accessorGet.Get(son); Assert.IsTrue(i == -88); accessorSet.Set(son, 9); } /// <summary> /// Test IMemberAccessor on virtual property /// </summary> [Test] [ExpectedException(typeof(InvalidOperationException), "Test virtual")] public void TestVirtualIMemberAccessor3() { IGetAccessor accessorGet = factoryGet.CreateGetAccessor(typeof(PropertySon), "DateTime"); ISetAccessor accessorSet = factorySet.CreateSetAccessor(typeof(PropertySon), "DateTime"); PropertySon son = new PropertySon(); DateTime date = (DateTime)accessorGet.Get(son); Assert.AreEqual(new DateTime(2000,1,1), date); accessorSet.Set(son, DateTime.Now); } /// <summary> /// Test IMemberAccessor on private set property /// </summary> [Test] public void TestPrivateSetAccessor() { ISetAccessor accessorSet = factorySet.CreateSetAccessor(typeof(PropertySon), "PrivateIndex"); PropertySon son = new PropertySon(); accessorSet.Set(son, -99); Assert.AreEqual(-99, son.Index); } /// <summary> /// Test IMemberAccessor on protected set property /// </summary> [Test] public void TestProtectedSetAccessor() { ISetAccessor accessorSet = factorySet.CreateSetAccessor(typeof(PropertySon), "Index"); PropertySon son = new PropertySon(); accessorSet.Set(son, -99); Assert.AreEqual(-99, son.Index); } /// <summary> /// Test set IMemberAccessor on a property override by new /// </summary> [Test] public void TestSetPropertyOverrideByNew() { ISetAccessor accessorSet = factorySet.CreateSetAccessor(typeof(PropertySon), "Float"); PropertySon son = new PropertySon(); accessorSet.Set(son, -99); Assert.AreEqual(-99*2, son.Float); } /// <summary> /// Test get IMemberAccessor on a property override by new /// </summary> [Test] public void TestGetPropertyOverrideByNew() { IGetAccessor accessorGet = factoryGet.CreateGetAccessor(typeof(PropertySon), "Float"); PropertySon son = new PropertySon(); son.Float = -99; Assert.AreEqual(-99 * 2, accessorGet.Get(son)); } #if dotnet2 /// <summary> /// Test getter access to Public Generic Property /// </summary> [Test] public void TestPublicGetterOnGenericProperty2() { IGetAccessor accessorGet = factoryGet.CreateGetAccessor(typeof(SpecialReference<Account>), "Value"); SpecialReference<Account> referenceAccount = new SpecialReference<Account>(); Account account = new Account(5); referenceAccount.Value = account; Account acc = accessorGet.Get(referenceAccount) as Account; Assert.AreEqual(referenceAccount.Value, acc); Assert.AreEqual(referenceAccount.Value.Id, acc.Id); } /// <summary> /// Test getter access to Public Generic Property /// </summary> [Test] public void TestPublicGetterOnGenericProperty() { IGetAccessor accessorGet = factoryGet.CreateGetAccessor(typeof(PropertySon), "ReferenceAccount"); PropertySon son = new PropertySon(); son.ReferenceAccount = new SpecialReference<Account>(); Account account = new Account(5); son.ReferenceAccount.Value = account; SpecialReference<Account> acc = accessorGet.Get(son) as SpecialReference<Account>; Assert.AreEqual(account, acc.Value); Assert.AreEqual(account.Id, acc.Value.Id); } /// <summary> /// Test setter access to Public Generic Property /// </summary> [Test] public void TestPublicSetterOnGenericVariable() { ISetAccessor accessorSet = factorySet.CreateSetAccessor(typeof(PropertySon), "ReferenceAccount"); PropertySon son = new PropertySon(); SpecialReference<Account> referenceAccount = new SpecialReference<Account>(); Account account = new Account(5); referenceAccount.Value = account; accessorSet.Set(son, referenceAccount); Assert.AreEqual(son.ReferenceAccount, referenceAccount); Assert.AreEqual(son.ReferenceAccount.Value.Id, referenceAccount.Value.Id); } /// <summary> /// Test setter access to Public Generic Property /// </summary> [Test] public void TestPublicSetterOnGenericVariable2() { ISetAccessor accessorSet = factorySet.CreateSetAccessor(typeof(SpecialReference<Account>), "Value"); SpecialReference<Account> referenceAccount = new SpecialReference<Account>(); Account account = new Account(5); accessorSet.Set(referenceAccount, account); Assert.AreEqual(account, referenceAccount.Value); Assert.AreEqual(account.Id, referenceAccount.Value.Id); } /// <summary> /// Test getter access to private Generic Property /// </summary> [Test] public void TestPrivateGetterOnGenericProperty() { IGetAccessor accessorGet = factoryGet.CreateGetAccessor(typeof(PropertySon), "_referenceAccount"); PropertySon son = new PropertySon(); son.ReferenceAccount = new SpecialReference<Account>(); Account account = new Account(5); son.ReferenceAccount.Value = account; SpecialReference<Account> acc = accessorGet.Get(son) as SpecialReference<Account>; Assert.AreEqual(account, acc.Value); Assert.AreEqual(account.Id, acc.Value.Id); } /// <summary> /// Test getter access to private Generic Property /// </summary> [Test] public void TestPrivateGetterOnGenericProperty2() { IGetAccessor accessorGet = factoryGet.CreateGetAccessor(typeof(SpecialReference<Account>), "_value"); SpecialReference<Account> referenceAccount = new SpecialReference<Account>(); Account account = new Account(5); referenceAccount.Value = account; Account acc = accessorGet.Get(referenceAccount) as Account; Assert.AreEqual(referenceAccount.Value, acc); Assert.AreEqual(referenceAccount.Value.Id, acc.Id); } /// <summary> /// Test setter access to Public Generic Property /// </summary> [Test] public void TestPrivateSetterOnGenericVariable() { ISetAccessor accessorSet = factorySet.CreateSetAccessor(typeof(PropertySon), "_referenceAccount"); PropertySon son = new PropertySon(); SpecialReference<Account> referenceAccount = new SpecialReference<Account>(); Account account = new Account(5); referenceAccount.Value = account; accessorSet.Set(son, referenceAccount); Assert.AreEqual(son.ReferenceAccount, referenceAccount); Assert.AreEqual(son.ReferenceAccount.Value.Id, referenceAccount.Value.Id); } /// <summary> /// Test setter access to Public Generic Property /// </summary> [Test] public void TestPrivateSetterOnGenericVariable2() { ISetAccessor accessorSet = factorySet.CreateSetAccessor(typeof(SpecialReference<Account>), "_value"); SpecialReference<Account> referenceAccount = new SpecialReference<Account>(); Account account = new Account(5); accessorSet.Set(referenceAccount, account); Assert.AreEqual(account, referenceAccount.Value); Assert.AreEqual(account.Id, referenceAccount.Value.Id); } #endif } }
#region CopyrightHeader // // Copyright by Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0.txt // // 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.Generic; using System.Collections.Specialized; using System.Collections; using System.Text; using System.IO; using gov.va.medora.mdo.dao; using gov.va.medora.mdo.dao.vista; using gov.va.medora.utils; using gov.va.medora.mdo.exceptions; using gov.va.medora.mdo.src.mdo; namespace gov.va.medora.mdo.dao.vista { public class VistaVitalsDao : IVitalsDao { AbstractConnection cxn = null; public VistaVitalsDao(AbstractConnection cxn) { this.cxn = cxn; } // Get all vital signs for currently selected patient (RDV call) public VitalSignSet[] getVitalSigns() { return getVitalSigns(cxn.Pid); } // Get all vital signs for given patient (RDV call) public VitalSignSet[] getVitalSigns(string dfn) { MdoQuery request = buildGetVitalSignsRdvRequest(dfn); string response = (string)cxn.query(request); return toVitalSignsFromRdv(response); } // Get vital signs within time frame for currently selected patient (RDV call) public VitalSignSet[] getVitalSigns(string fromDate, string toDate, int maxRex) { return getVitalSigns(cxn.Pid,fromDate,toDate,maxRex); } // Get vital signs within time frame for given patient (RDV call) public VitalSignSet[] getVitalSigns(string dfn, string fromDate, string toDate, int maxRex) { MdoQuery request = buildGetVitalSignsRdvRequest(dfn, fromDate, toDate, maxRex); string response = (string)cxn.query(request); return toVitalSignsFromRdv(response); } internal MdoQuery buildGetVitalSignsRdvRequest(string dfn) { VistaUtils.CheckRpcParams(dfn); return VistaUtils.buildReportTextRequest_AllResults(dfn, "OR_VS:VITAL SIGNS~VS;ORDV04;47;"); } internal MdoQuery buildGetVitalSignsRdvRequest(string dfn, string fromDate, string toDate, int maxRex) { VistaUtils.CheckRpcParams(dfn); return VistaUtils.buildReportTextRequest(dfn, fromDate, toDate, maxRex, "OR_VS:VITAL SIGNS~VS;ORDV04;47;"); } internal VitalSignSet[] toVitalSignsFromRdv(string response) { if (response == "") { return null; } string[] lines = StringUtils.split(response, StringUtils.CRLF); lines = StringUtils.trimArray(lines); ArrayList lst = new ArrayList(); VitalSignSet rec = null; VitalSign s = null; for (int i = 0; i < lines.Length; i++) { string[] flds = StringUtils.split(lines[i], StringUtils.CARET); int fldnum = Convert.ToInt16(flds[0]); switch (fldnum) { case 1: if (rec != null) { lst.Add(rec); } rec = new VitalSignSet(); string[] subflds = StringUtils.split(flds[1], StringUtils.SEMICOLON); if (subflds.Length == 1) { rec.Facility = new SiteId("200", subflds[0]); } else { rec.Facility = new SiteId(subflds[1], subflds[0]); } break; case 2: if (flds.Length == 2) { rec.Timestamp = VistaTimestamp.toUtcFromRdv(flds[1]); } break; case 3: s = new VitalSign(); s.Type = new ObservationType("", VitalSign.VITAL_SIGN, VitalSign.TEMPERATURE); if (flds.Length == 2) { s.Value1 = flds[1]; } rec.addVitalSign(VitalSign.TEMPERATURE, s); break; case 4: s = new VitalSign(); s.Type = new ObservationType("", VitalSign.VITAL_SIGN, VitalSign.PULSE); if (flds.Length == 2) { s.Value1 = flds[1]; } rec.addVitalSign(VitalSign.PULSE, s); break; case 5: s = new VitalSign(); s.Type = new ObservationType("", VitalSign.VITAL_SIGN, VitalSign.RESPIRATION); if (flds.Length == 2) { s.Value1 = flds[1]; } rec.addVitalSign(VitalSign.RESPIRATION, s); break; case 6: s = new VitalSign(); s.Type = new ObservationType("", VitalSign.VITAL_SIGN, VitalSign.BLOOD_PRESSURE); if (flds.Length == 2) { s.Value1 = flds[1]; } rec.addVitalSign(VitalSign.BLOOD_PRESSURE, s); break; case 7: s = new VitalSign(); s.Type = new ObservationType("", VitalSign.VITAL_SIGN, VitalSign.HEIGHT); if (flds.Length == 2) { s.Value1 = flds[1]; } rec.addVitalSign(VitalSign.HEIGHT, s); break; case 8: s = new VitalSign(); s.Type = new ObservationType("", VitalSign.VITAL_SIGN, VitalSign.WEIGHT); if (flds.Length == 2) { s.Value1 = flds[1]; } rec.addVitalSign(VitalSign.WEIGHT, s); break; case 9: s = new VitalSign(); s.Type = new ObservationType("", VitalSign.VITAL_SIGN, VitalSign.PAIN); if (flds.Length == 2) { s.Value1 = flds[1]; } rec.addVitalSign(VitalSign.PAIN, s); break; case 10: s = new VitalSign(); s.Type = new ObservationType("", VitalSign.VITAL_SIGN, VitalSign.PULSE_OXYMETRY); if (flds.Length == 2) { s.Value1 = flds[1]; } rec.addVitalSign(VitalSign.PULSE_OXYMETRY, s); break; case 11: s = new VitalSign(); s.Type = new ObservationType("", VitalSign.VITAL_SIGN, VitalSign.CENTRAL_VENOUS_PRESSURE); if (flds.Length == 2) { s.Value1 = flds[1]; } rec.addVitalSign(VitalSign.CENTRAL_VENOUS_PRESSURE, s); break; case 12: s = new VitalSign(); s.Type = new ObservationType("", VitalSign.VITAL_SIGN, VitalSign.CIRCUMFERENCE_GIRTH); if (flds.Length == 2) { s.Value1 = flds[1]; } rec.addVitalSign(VitalSign.CIRCUMFERENCE_GIRTH, s); break; case 15: if (flds.Length == 2) { setVitalSignQualifierStrings(rec, flds[1], "Qualifiers"); rec.Qualifiers = flds[1]; } break; case 16: s = new VitalSign(); s.Type = new ObservationType("", VitalSign.VITAL_SIGN, VitalSign.BODY_MASS_INDEX); if (flds.Length == 2) { s.Value1 = flds[1]; } rec.addVitalSign(VitalSign.BODY_MASS_INDEX, s); break; case 17: if (flds.Length == 2) { setVitalSignQualifierStrings(rec, flds[1], "Units"); rec.Units = flds[1]; } break; default: break; } } lst.Add(rec); return (VitalSignSet[])lst.ToArray(typeof(VitalSignSet)); } public VitalSign[] getLatestVitalSigns() { return getLatestVitalSigns(cxn.Pid); } public VitalSign[] getLatestVitalSigns(string dfn) { MdoQuery request = buildGetLatestVitalSignsRequest(dfn); string response = (string)cxn.query(request); return toLatestVitalSigns(response); } internal MdoQuery buildGetLatestVitalSignsRequest(string dfn) { VistaUtils.CheckRpcParams(dfn); VistaQuery vq = new VistaQuery("ORQQVI VITALS"); vq.addParameter(vq.LITERAL, dfn); return vq; } internal VitalSign[] toLatestVitalSigns(string response) { if (!cxn.IsConnected) { throw new NotConnectedException(); } if (response == "") { return null; } string[] lines = StringUtils.split(response, StringUtils.CRLF); ArrayList lst = new ArrayList(lines.Length); string category = "Vital Signs"; for (int i = 0; i < lines.Length; i++) { if (lines[i] == "") { continue; } string[] flds = StringUtils.split(lines[i], StringUtils.CARET); ObservationType observationType = null; if (flds[1] == "T") { observationType = new ObservationType(flds[0], category, "Temperature"); } else if (flds[1] == "P") { observationType = new ObservationType(flds[0], category, "Pulse"); } else if (flds[1] == "R") { observationType = new ObservationType(flds[0], category, "Respiration"); } else if (flds[1] == "BP") { observationType = new ObservationType(flds[0], category, "Blood Pressure"); } else if (flds[1] == "HT") { observationType = new ObservationType(flds[0], category, "Height"); } else if (flds[1] == "WT") { observationType = new ObservationType(flds[0], category, "Weight"); } else if (flds[1] == "PN") { observationType = new ObservationType(flds[0], category, "Pain"); } if (observationType == null) { continue; } VitalSign observation = new VitalSign(); observation.Type = observationType; observation.Value1 = flds[4]; if (flds.Length == 6) { observation.Value2 = flds[5]; } observation.Timestamp = VistaTimestamp.toUtcString(flds[3]); lst.Add(observation); } return (VitalSign[])lst.ToArray(typeof(VitalSign)); } internal string getVitalSignQualifierItem(string qualifiers, string key) { int p1 = qualifiers.IndexOf(key + ':'); if (p1 == -1) { return ""; } p1 += key.Length + 1; int p2 = p1; while (p2 < qualifiers.Length && qualifiers[p2] != ':') { p2++; } if (p2 < qualifiers.Length) { while (qualifiers[p2] != ',') { p2--; } } return qualifiers.Substring(p1, p2 - p1).Trim(); } internal void setVitalSignQualifierStrings(VitalSignSet set, string s, string qualifier) { string[] keys = new string[] { "TEMP","PULSE","BP","RESP","WT","HT","PAIN","O2","CG","CVP","BMI" }; for (int i = 0; i < keys.Length; i++) { string value = getVitalSignQualifierItem(s, keys[i]); if (!String.IsNullOrEmpty(value)) { VitalSign theSign = getSignFromSet(set, keys[i]); if (theSign == null) { continue; } if (String.Equals(qualifier, "Units", StringComparison.CurrentCultureIgnoreCase)) { theSign.Units = value; if (keys[i] == "BP") { theSign = set.getVitalSign(VitalSign.SYSTOLIC_BP); if (theSign != null) { theSign.Units = value; } theSign = set.getVitalSign(VitalSign.DIASTOLIC_BP); if (theSign != null) { theSign.Units = value; } } } else if (String.Equals(qualifier, "Qualifiers", StringComparison.CurrentCultureIgnoreCase)) { theSign.Qualifiers = value; if (keys[i] == "BP") { theSign = set.getVitalSign(VitalSign.SYSTOLIC_BP); if (theSign != null) { theSign.Qualifiers = value; } theSign = set.getVitalSign(VitalSign.DIASTOLIC_BP); if (theSign != null) { theSign.Qualifiers = value; } } } else { throw new Exception("Invalid qualifier: " + qualifier); } } } } internal VitalSign getSignFromSet(VitalSignSet set, string key) { if (key == "TEMP") { return set.getVitalSign(VitalSign.TEMPERATURE); } if (key == "PULSE") { return set.getVitalSign(VitalSign.PULSE); } if (key == "RESP") { return set.getVitalSign(VitalSign.RESPIRATION); } if (key == "BP") { return set.getVitalSign(VitalSign.BLOOD_PRESSURE); } if (key == "WT") { return set.getVitalSign(VitalSign.WEIGHT); } if (key == "HT") { return set.getVitalSign(VitalSign.HEIGHT); } if (key == "PAIN") { return set.getVitalSign(VitalSign.PAIN); } if (key == "O2") { return set.getVitalSign(VitalSign.PULSE_OXYMETRY); } if (key == "CG") { return set.getVitalSign(VitalSign.CIRCUMFERENCE_GIRTH); } if (key == "CVP") { return set.getVitalSign(VitalSign.CENTRAL_VENOUS_PRESSURE); } if (key == "BMI") { return set.getVitalSign(VitalSign.BODY_MASS_INDEX); } return null; } } }
/* Copyright (c) 2012 - 2015 Antmicro <www.antmicro.com> Authors: * Konrad Kruczynski (kkruczynski@antmicro.com) * Piotr Zierhoffer (pzierhoffer@antmicro.com) * Mateusz Holenko (mholenko@antmicro.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.IO; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Collections; using Antmicro.Migrant.Hooks; using Antmicro.Migrant.Generators; using System.Reflection.Emit; using System.Threading; using System.Diagnostics; using Antmicro.Migrant.VersionTolerance; using Antmicro.Migrant.Utilities; using Antmicro.Migrant.Customization; using System.Runtime.CompilerServices; namespace Antmicro.Migrant { /// <summary> /// Writes the object in a format that can be later read by <see cref="Antmicro.Migrant.ObjectReader"/>. /// </summary> public class ObjectWriter : IDisposable { /// <summary> /// Initializes a new instance of the <see cref="Antmicro.Migrant.ObjectWriter" /> class. /// </summary> /// <param name='stream'> /// Stream to which data will be written. /// </param> /// <param name='preSerializationCallback'> /// Callback which is called once on every unique object before its serialization. Contains this object in its only parameter. /// </param> /// <param name='postSerializationCallback'> /// Callback which is called once on every unique object after its serialization. Contains this object in its only parameter. /// </param> /// <param name='writeMethodCache'> /// Cache in which generated write methods are stored and reused between instances of <see cref="Antmicro.Migrant.ObjectWriter" />. /// Can be null if one does not want to use the cache. Note for the life of the cache you always have to provide the same /// <paramref name="surrogatesForObjects"/>. /// </param> /// <param name='surrogatesForObjects'> /// Dictionary, containing callbacks that provide surrogate for given type. Callbacks have to be of type Func&lt;T, object&gt; where /// typeof(T) is given type. Note that the list always have to be in sync with <paramref name="writeMethodCache"/>. /// </param> /// <param name='isGenerating'> /// True if write methods are to be generated, false if one wants to use reflection. /// </param> /// <param name = "treatCollectionAsUserObject"> /// True if collection objects are to be serialized without optimization (treated as normal user objects). /// </param> /// <param name="useBuffering"> /// True if buffering is used. False if all writes should directly go to the stream and no padding should be used. /// </param> /// <param name="referencePreservation"> /// Tells serializer how to treat object identity between the calls to <see cref="Antmicro.Migrant.ObjectWriter.WriteObject" />. /// </param> public ObjectWriter(Stream stream, Action<object> preSerializationCallback = null, Action<object> postSerializationCallback = null, IDictionary<Type, DynamicMethod> writeMethodCache = null, InheritanceAwareList<Delegate> surrogatesForObjects = null, bool isGenerating = true, bool treatCollectionAsUserObject = false, bool useBuffering = true, ReferencePreservation referencePreservation = ReferencePreservation.Preserve) { if(surrogatesForObjects == null) { surrogatesForObjects = new InheritanceAwareList<Delegate>(); } currentlyWrittenTypes = new Stack<Type>(); transientTypeCache = new Dictionary<Type, bool>(); writeMethods = new Dictionary<Type, Action<PrimitiveWriter, object>>(); postSerializationHooks = new List<Action>(); this.writeMethodCache = writeMethodCache; this.isGenerating = isGenerating; this.treatCollectionAsUserObject = treatCollectionAsUserObject; this.surrogatesForObjects = surrogatesForObjects; typeIndices = new Dictionary<TypeDescriptor, int>(); methodIndices = new Dictionary<MethodInfo, int>(); assemblyIndices = new Dictionary<AssemblyDescriptor, int>(); this.preSerializationCallback = preSerializationCallback; this.postSerializationCallback = postSerializationCallback; writer = new PrimitiveWriter(stream, useBuffering); inlineWritten = new HashSet<int>(); this.referencePreservation = referencePreservation; if(referencePreservation == ReferencePreservation.Preserve) { identifier = new ObjectIdentifier(); } } /// <summary> /// Writes the given object along with the ones referenced by it. /// </summary> /// <param name='o'> /// The object to write. /// </param> public void WriteObject(object o) { if(o == null || Helpers.CheckTransientNoCache(o.GetType())) { throw new ArgumentException("Cannot write a null object or a transient object."); } objectsWrittenThisSession = 0; if(referencePreservation != ReferencePreservation.Preserve) { identifier = identifierContext == null ? new ObjectIdentifier() : new ObjectIdentifier(identifierContext); identifierContext = null; } var identifiersCount = identifier.Count; identifier.GetId(o); var firstObjectIsNew = identifiersCount != identifier.Count; try { // first object is always written InvokeCallbacksAndWriteObject(o); if(firstObjectIsNew) { objectsWrittenThisSession++; } while(identifier.Count - identifierCountPreviousSession > objectsWrittenThisSession) { if(!inlineWritten.Contains(identifierCountPreviousSession + objectsWrittenThisSession)) { InvokeCallbacksAndWriteObject(identifier[identifierCountPreviousSession + objectsWrittenThisSession]); } objectsWrittenThisSession++; } } finally { foreach(var postHook in postSerializationHooks) { postHook(); } PrepareForNextWrite(); } } /// <summary> /// Releases all resource used by the <see cref="Antmicro.Migrant.ObjectWriter"/> object. Note that this is not necessary /// if buffering is not used. /// </summary> /// <remarks>Call <see cref="Dispose"/> when you are finished using the <see cref="Antmicro.Migrant.ObjectWriter"/>. The /// <see cref="Dispose"/> method leaves the <see cref="Antmicro.Migrant.ObjectWriter"/> in an unusable state. /// After calling <see cref="Dispose"/>, you must release all references to the /// <see cref="Antmicro.Migrant.ObjectWriter"/> so the garbage collector can reclaim the memory that the /// <see cref="Antmicro.Migrant.ObjectWriter"/> was occupying.</remarks> public void Dispose() { writer.Dispose(); writer = null; } internal void WriteObjectIdPossiblyInline(object o) { var refId = identifier.GetId(o); writer.Write(refId); if(WasNotWrittenYet(refId)) { inlineWritten.Add(refId); InvokeCallbacksAndWriteObject(o); } } internal Delegate[] GetDelegatesWithNonTransientTargets(MulticastDelegate mDelegate) { return mDelegate.GetInvocationList().Where(x => x.Target == null || !CheckTransient(x.Target)).ToArray(); } internal bool CheckTransient(object o) { return CheckTransient(o.GetType()); } internal bool CheckTransient(Type type) { bool result; if(transientTypeCache.TryGetValue(type, out result)) { return result; } var isTransient = Helpers.CheckTransientNoCache(type); transientTypeCache.Add(type, isTransient); return isTransient; } internal static void CheckLegality(Type type, Type containingType = null, IEnumerable<Type> writtenTypes = null) { // containing type is a hint in case of if(type.IsPointer || type == typeof(IntPtr) || (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ThreadLocal<>)) || type == typeof(SpinLock)) { IEnumerable<string> typeNames; if(writtenTypes == null) { var stackTrace = new StackTrace(); var methods = stackTrace.GetFrames().Select(x => x.GetMethod()).ToArray(); var topType = containingType != null ? new [] { containingType.Name } : (new string[0]); typeNames = topType.Union( methods .Where(x => (x.Name.StartsWith("Write_") || x.Name.StartsWith("WriteArray")) && x.GetParameters()[0].ParameterType == typeof(ObjectWriter)) .Select(x => x.Name.Substring(x.Name.IndexOf('_') + 1))); } else { typeNames = writtenTypes.Select(x => x.Name); } var path = typeNames.Reverse().Aggregate((x, y) => x + " => " + y); throw new InvalidOperationException("Pointer or ThreadLocal or SpinLock encountered during serialization. The classes path that lead to it was: " + path); } } internal int TouchAndWriteMethodId(MethodInfo info) { int methodId; if(methodIndices.ContainsKey(info)) { methodId = methodIndices[info]; writer.Write(methodId); return methodId; } AddMissingMethod(info); methodId = methodIndices[info]; writer.Write(methodId); TouchAndWriteTypeId(info.ReflectedType); var methodParameters = info.GetParameters(); if(info.IsGenericMethod) { var genericDefinition = info.GetGenericMethodDefinition(); var genericArguments = info.GetGenericArguments(); var genericMethodParamters = genericDefinition.GetParameters(); writer.Write(genericDefinition.Name); writer.Write(genericArguments.Length); for(int i = 0; i < genericArguments.Length; i++) { TouchAndWriteTypeId(genericArguments[i]); } writer.Write(genericMethodParamters.Length); for(int i = 0; i < genericMethodParamters.Length; i++) { writer.Write(genericMethodParamters[i].ParameterType.IsGenericParameter); if(genericMethodParamters[i].ParameterType.IsGenericParameter) { writer.Write(genericMethodParamters[i].ParameterType.GenericParameterPosition); } else { TouchAndWriteTypeId(methodParameters[i].ParameterType); } } } else { writer.Write(info.Name); writer.Write(0); // no generic arguments writer.Write(methodParameters.Length); foreach(var p in methodParameters) { TouchAndWriteTypeId(p.ParameterType); } } return methodId; } internal static bool HasSpecialWriteMethod(Type type) { return type == typeof(string) || typeof(ISpeciallySerializable).IsAssignableFrom(type) || Helpers.CheckTransientNoCache(type); } internal int TouchAndWriteTypeId(Type type) { var typeDescriptor = TypeDescriptor.CreateFromType(type); int typeId; if(typeIndices.ContainsKey(typeDescriptor)) { typeId = typeIndices[typeDescriptor]; writer.Write(typeId); return typeId; } typeId = nextTypeId++; typeIndices.Add(typeDescriptor, typeId); writer.Write(typeId); typeDescriptor.WriteTypeStamp(this); typeDescriptor.WriteStructureStampIfNeeded(this); return typeId; } internal int TouchAndWriteAssemblyId(AssemblyDescriptor assembly) { int assemblyId; if(assemblyIndices.ContainsKey(assembly)) { assemblyId = assemblyIndices[assembly]; writer.Write(assemblyId); return assemblyId; } assemblyId = nextAssemblyId++; assemblyIndices.Add(assembly, assemblyId); writer.Write(assemblyId); assembly.WriteTo(this); return assemblyId; } internal bool TreatCollectionAsUserObject { get { return treatCollectionAsUserObject; } } internal PrimitiveWriter PrimitiveWriter { get { return writer; } } private void PrepareForNextWrite() { if(referencePreservation != ReferencePreservation.DoNotPreserve) { identifierCountPreviousSession = identifier.Count; } else { inlineWritten.Clear(); } currentlyWrittenTypes.Clear(); if(referencePreservation == ReferencePreservation.UseWeakReference) { identifierContext = identifier.GetContext(); } if(referencePreservation != ReferencePreservation.Preserve) { identifier = null; } } private void InvokeCallbacksAndWriteObject(object o) { if(preSerializationCallback != null) { preSerializationCallback(o); } WriteObjectInner(o); if(postSerializationCallback != null) { postSerializationCallback(o); } } private void WriteObjectInner(object o) { var type = o.GetType(); if(writeMethods.ContainsKey(type)) { writeMethods[type](writer, o); return; } Action<PrimitiveWriter, object> writeMethod; if(writeMethodCache != null && writeMethodCache.ContainsKey(type)) { writeMethod = (Action<PrimitiveWriter, object>)writeMethodCache[type].CreateDelegate(typeof(Action<PrimitiveWriter, object>), this); } else { var surrogateId = Helpers.GetSurrogateFactoryIdForType(type, surrogatesForObjects); writeMethod = PrepareWriteMethod(type, surrogateId); } writeMethods.Add(type, writeMethod); writeMethod(writer, o); } private void WriteObjectUsingReflection(PrimitiveWriter primitiveWriter, object o) { TouchAndWriteTypeId(o.GetType()); // the primitiveWriter and parameter is not used here in fact, it is only to have // signature compatible with the generated method Helpers.InvokeAttribute(typeof(PreSerializationAttribute), o); try { var type = o.GetType(); currentlyWrittenTypes.Push(type); if(!WriteSpecialObject(o)) { WriteObjectsFields(o, type); } currentlyWrittenTypes.Pop(); } finally { Helpers.InvokeAttribute(typeof(PostSerializationAttribute), o); var postHook = Helpers.GetDelegateWithAttribute(typeof(LatePostSerializationAttribute), o); if(postHook != null) { postSerializationHooks.Add(postHook); } } } private void WriteObjectsFields(object o, Type type) { // fields in the alphabetical order var fields = StampHelpers.GetFieldsInSerializationOrder(type); foreach(var field in fields) { var fieldType = field.FieldType; var value = field.GetValue(o); WriteField(fieldType, value); } } private bool WriteSpecialObject(object o) { // if the object here is value type, it is in fact boxed // value type - the reference layout is fine, we should // write it using WriteField var type = o.GetType(); if(type.IsValueType) { WriteField(type, o); return true; } var speciallySerializable = o as ISpeciallySerializable; if(speciallySerializable != null) { var startingPosition = writer.Position; speciallySerializable.Save(writer); writer.Write(writer.Position - startingPosition); return true; } if(type.IsArray) { var elementType = type.GetElementType(); var array = o as Array; var rank = array.Rank; writer.Write(rank); WriteArray(elementType, array); return true; } var mDelegate = o as MulticastDelegate; if(mDelegate != null) { // if the target is trasient, we omit associated delegate entry var invocationList = GetDelegatesWithNonTransientTargets(mDelegate); writer.Write(invocationList.Length); foreach(var del in invocationList) { WriteField(typeof(object), del.Target); TouchAndWriteMethodId(del.Method); } return true; } var str = o as string; if(str != null) { writer.Write(str); return true; } if(!treatCollectionAsUserObject) { CollectionMetaToken collectionToken; if (CollectionMetaToken.TryGetCollectionMetaToken(o.GetType(), out collectionToken)) { // here we can have normal or extension method that needs to be treated differently int count = collectionToken.CountMethod.IsStatic ? (int)collectionToken.CountMethod.Invoke(null, new[] { o }) : (int)collectionToken.CountMethod.Invoke(o, null); if(collectionToken.IsDictionary) { WriteDictionary(collectionToken, count, o); } else { WriteEnumerable(collectionToken.FormalElementType, count, (IEnumerable)o); } return true; } } return false; } private void WriteEnumerable(Type elementFormalType, int count, IEnumerable collection) { writer.Write(count); foreach(var element in collection) { WriteField(elementFormalType, element); } } private void WriteDictionary(CollectionMetaToken collectionToken, int count, object dictionary) { writer.Write(count); if(collectionToken.IsGeneric) { var enumeratorMethod = typeof(IEnumerable<>).MakeGenericType(typeof(KeyValuePair<,>).MakeGenericType(collectionToken.FormalKeyType, collectionToken.FormalValueType)).GetMethod("GetEnumerator"); var enumerator = enumeratorMethod.Invoke(dictionary, null); var enumeratorType = enumeratorMethod.ReturnType; var moveNext = Helpers.GetMethodInfo<IEnumerator>(x => x.MoveNext()); var currentField = enumeratorType.GetProperty("Current"); var current = currentField.GetGetMethod(); var currentType = current.ReturnType; var key = currentType.GetProperty("Key").GetGetMethod(); var value = currentType.GetProperty("Value").GetGetMethod(); while((bool)moveNext.Invoke(enumerator, null)) { var currentValue = current.Invoke(enumerator, null); var keyValue = key.Invoke(currentValue, null); var valueValue = value.Invoke(currentValue, null); WriteField(collectionToken.FormalKeyType, keyValue); WriteField(collectionToken.FormalValueType, valueValue); } } else { var castDictionary = (IDictionary)dictionary; foreach(DictionaryEntry element in castDictionary) { WriteField(typeof(object), element.Key); WriteField(typeof(object), element.Value); } } } private void WriteArray(Type elementFormalType, Array array) { var rank = array.Rank; for(var i = 0; i < rank; i++) { writer.Write(array.GetLength(i)); } var position = new int[rank]; WriteArrayRowRecursive(array, 0, elementFormalType, position); } private void WriteArrayRowRecursive(Array array, int currentDimension, Type elementFormalType, int[] position) { var length = array.GetLength(currentDimension); for(var i = 0; i < length; i++) { if(currentDimension == array.Rank - 1) { // the final row WriteField(elementFormalType, array.GetValue(position)); } else { WriteArrayRowRecursive(array, currentDimension + 1, elementFormalType, position); } position[currentDimension]++; for(var j = currentDimension + 1; j < array.Rank; j++) { position[j] = 0; } } } private void WriteField(Type formalType, object value) { var serializationType = Helpers.GetSerializationType(formalType); switch(serializationType) { case SerializationType.Transient: return; case SerializationType.Value: WriteValueType(formalType, value); return; case SerializationType.Reference: break; } // OK, so we should write a reference // a null reference maybe? if(value == null || CheckTransient(value)) { writer.Write(Consts.NullObjectId); return; } var actualType = value.GetType(); if(CheckTransient(actualType)) { return; } CheckLegality(actualType, writtenTypes: currentlyWrittenTypes); var refId = identifier.GetId(value); // if this is a future reference, just after the reference id, // we should write inline data writer.Write(refId); if(WasNotWrittenYet(refId)) { inlineWritten.Add(refId); InvokeCallbacksAndWriteObject(value); } } private bool WasNotWrittenYet(int referenceId) { return referenceId > (identifierCountPreviousSession + objectsWrittenThisSession) && !inlineWritten.Contains(referenceId); } private void WriteValueType(Type formalType, object value) { CheckLegality(formalType, writtenTypes: currentlyWrittenTypes); // value type -> actual type is the formal type if(formalType.IsEnum) { var underlyingType = Enum.GetUnderlyingType(formalType); var convertedValue = Convert.ChangeType(value, underlyingType); var method = writer.GetType().GetMethod("Write", new [] { underlyingType }); method.Invoke(writer, new[] { convertedValue }); return; } var nullableActualType = Nullable.GetUnderlyingType(formalType); if(nullableActualType != null) { if(value != null) { writer.Write(true); WriteValueType(nullableActualType, value); } else { writer.Write(false); } return; } if(Helpers.IsWriteableByPrimitiveWriter(formalType)) { writer.Write((dynamic)value); return; } // so we guess it is struct WriteObjectsFields(value, formalType); } private void AddMissingMethod(MethodInfo info) { methodIndices.Add(info, nextMethodId++); } private Action<PrimitiveWriter, object> PrepareWriteMethod(Type actualType, int surrogateId) { if(surrogateId == -1) { var specialWrite = LinkSpecialWrite(actualType); if(specialWrite != null) { // linked methods are not added to writeMethodCache, there's no point return specialWrite; } } if(!isGenerating) { if(surrogateId != -1) { return (pw, o) => InvokeCallbacksAndWriteObject(surrogatesForObjects.GetByIndex(surrogateId).DynamicInvoke(new [] { o })); } return WriteObjectUsingReflection; } var method = new WriteMethodGenerator(actualType, treatCollectionAsUserObject, surrogateId, Helpers.GetFieldInfo<ObjectWriter, InheritanceAwareList<Delegate>>(x => x.surrogatesForObjects), Helpers.GetMethodInfo<ObjectWriter>(x => x.InvokeCallbacksAndWriteObject(null))).Method; var result = (Action<PrimitiveWriter, object>)method.CreateDelegate(typeof(Action<PrimitiveWriter, object>), this); if(writeMethodCache != null) { writeMethodCache.Add(actualType, method); } return result; } private Action<PrimitiveWriter, object> LinkSpecialWrite(Type actualType) { if(actualType == typeof(string)) { return (y, obj) => { TouchAndWriteTypeId(actualType); y.Write((string)obj); }; } if(typeof(ISpeciallySerializable).IsAssignableFrom(actualType)) { return (writer, obj) => { TouchAndWriteTypeId(actualType); var startingPosition = writer.Position; ((ISpeciallySerializable)obj).Save(writer); writer.Write(writer.Position - startingPosition); }; } if(actualType == typeof(byte[])) { return (writer, objToWrite) => { TouchAndWriteTypeId(actualType); writer.Write(1); // rank of the array var array = (byte[])objToWrite; writer.Write(array.Length); writer.Write(array); }; } return null; } private ObjectIdentifier identifier; private ObjectIdentifierContext identifierContext; private int objectsWrittenThisSession; private int identifierCountPreviousSession; private int nextTypeId; private int nextMethodId; private int nextAssemblyId; private PrimitiveWriter writer; private readonly HashSet<int> inlineWritten; private readonly bool isGenerating; private readonly bool treatCollectionAsUserObject; private readonly ReferencePreservation referencePreservation; private readonly Action<object> preSerializationCallback; private readonly Action<object> postSerializationCallback; private readonly List<Action> postSerializationHooks; private readonly Dictionary<TypeDescriptor, int> typeIndices; private readonly Dictionary<MethodInfo, int> methodIndices; private readonly Dictionary<AssemblyDescriptor, int> assemblyIndices; private readonly Dictionary<Type, bool> transientTypeCache; private readonly IDictionary<Type, DynamicMethod> writeMethodCache; private readonly InheritanceAwareList<Delegate> surrogatesForObjects; private readonly Dictionary<Type, Action<PrimitiveWriter, object>> writeMethods; private readonly Stack<Type> currentlyWrittenTypes; } }
#pragma warning disable #if NETSTANDARD2_0 || NET45 || NET461|| NET472 || NETCOREAPP2_0 || NETCOREAPP2_1 // https://github.com/dotnet/corefx/blob/1597b894a2e9cac668ce6e484506eca778a85197/src/Common/src/CoreLib/System/Index.cs // https://github.com/dotnet/corefx/blob/1597b894a2e9cac668ce6e484506eca778a85197/src/Common/src/CoreLib/System/Range.cs using System.Runtime.CompilerServices; namespace System { /// <summary>Represent a type can be used to index a collection either from the start or the end.</summary> /// <remarks> /// Index is used by the C# compiler to support the new index syntax /// <code> /// int[] someArray = new int[5] { 1, 2, 3, 4, 5 } ; /// int lastElement = someArray[^1]; // lastElement = 5 /// </code> /// </remarks> [Runtime.InteropServices.StructLayout(Runtime.InteropServices.LayoutKind.Auto)] internal readonly struct Index : IEquatable<Index> { private readonly int _value; /// <summary>Construct an Index using a value and indicating if the index is from the start or from the end.</summary> /// <param name="value">The index value. it has to be zero or positive number.</param> /// <param name="fromEnd">Indicating if the index is from the start or from the end.</param> /// <remarks> /// If the Index constructed from the end, index value 1 means pointing at the last element and index value 0 means pointing at beyond last element. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Index(int value, bool fromEnd = false) { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value), "value must be non-negative"); } if (fromEnd) _value = ~value; else _value = value; } // The following private constructors mainly created for perf reason to avoid the checks private Index(int value) { _value = value; } /// <summary>Create an Index pointing at first element.</summary> public static Index Start => new Index(0); /// <summary>Create an Index pointing at beyond last element.</summary> public static Index End => new Index(~0); /// <summary>Create an Index from the start at the position indicated by the value.</summary> /// <param name="value">The index value from the start.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Index FromStart(int value) { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value), "value must be non-negative"); } return new Index(value); } /// <summary>Create an Index from the end at the position indicated by the value.</summary> /// <param name="value">The index value from the end.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Index FromEnd(int value) { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value), "value must be non-negative"); } return new Index(~value); } /// <summary>Returns the index value.</summary> public int Value { get { if (_value < 0) { return ~_value; } else { return _value; } } } /// <summary>Indicates whether the index is from the start or the end.</summary> public bool IsFromEnd => _value < 0; /// <summary>Calculate the offset from the start using the giving collection length.</summary> /// <param name="length">The length of the collection that the Index will be used with. length has to be a positive value</param> /// <remarks> /// For performance reason, we don't validate the input length parameter and the returned offset value against negative values. /// we don't validate either the returned offset is greater than the input length. /// It is expected Index will be used with collections which always have non negative length/count. If the returned offset is negative and /// then used to index a collection will get out of range exception which will be same affect as the validation. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public int GetOffset(int length) { var offset = _value; if (IsFromEnd) { // offset = length - (~value) // offset = length + (~(~value) + 1) // offset = length + value + 1 offset += length + 1; } return offset; } /// <summary>Indicates whether the current Index object is equal to another object of the same type.</summary> /// <param name="value">An object to compare with this object</param> public override bool Equals(object? value) => value is Index && _value == ((Index)value)._value; /// <summary>Indicates whether the current Index object is equal to another Index object.</summary> /// <param name="other">An object to compare with this object</param> public bool Equals(Index other) => _value == other._value; /// <summary>Returns the hash code for this instance.</summary> public override int GetHashCode() => _value; /// <summary>Converts integer number to an Index.</summary> public static implicit operator Index(int value) => FromStart(value); /// <summary>Converts the value of the current Index object to its equivalent string representation.</summary> public override string ToString() { if (IsFromEnd) return "^" + ((uint)Value).ToString(); return ((uint)Value).ToString(); } } /// <summary>Represent a range has start and end indexes.</summary> /// <remarks> /// Range is used by the C# compiler to support the range syntax. /// <code> /// int[] someArray = new int[5] { 1, 2, 3, 4, 5 }; /// int[] subArray1 = someArray[0..2]; // { 1, 2 } /// int[] subArray2 = someArray[1..^0]; // { 2, 3, 4, 5 } /// </code> /// </remarks> [Runtime.InteropServices.StructLayout(Runtime.InteropServices.LayoutKind.Auto)] internal readonly struct Range : IEquatable<Range> { /// <summary>Represent the inclusive start index of the Range.</summary> public Index Start { get; } /// <summary>Represent the exclusive end index of the Range.</summary> public Index End { get; } /// <summary>Construct a Range object using the start and end indexes.</summary> /// <param name="start">Represent the inclusive start index of the range.</param> /// <param name="end">Represent the exclusive end index of the range.</param> public Range(Index start, Index end) { Start = start; End = end; } /// <summary>Indicates whether the current Range object is equal to another object of the same type.</summary> /// <param name="value">An object to compare with this object</param> public override bool Equals(object? value) => value is Range r && r.Start.Equals(Start) && r.End.Equals(End); /// <summary>Indicates whether the current Range object is equal to another Range object.</summary> /// <param name="other">An object to compare with this object</param> public bool Equals(Range other) => other.Start.Equals(Start) && other.End.Equals(End); /// <summary>Returns the hash code for this instance.</summary> public override int GetHashCode() { return Start.GetHashCode() * 31 + End.GetHashCode(); } /// <summary>Converts the value of the current Range object to its equivalent string representation.</summary> public override string ToString() { return Start + ".." + End; } /// <summary>Create a Range object starting from start index to the end of the collection.</summary> public static Range StartAt(Index start) => new Range(start, Index.End); /// <summary>Create a Range object starting from first element in the collection to the end Index.</summary> public static Range EndAt(Index end) => new Range(Index.Start, end); /// <summary>Create a Range object starting from first element to the end.</summary> public static Range All => new Range(Index.Start, Index.End); /// <summary>Calculate the start offset and length of range object using a collection length.</summary> /// <param name="length">The length of the collection that the range will be used with. length has to be a positive value.</param> /// <remarks> /// For performance reason, we don't validate the input length parameter against negative values. /// It is expected Range will be used with collections which always have non negative length/count. /// We validate the range is inside the length scope though. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public (int Offset, int Length) GetOffsetAndLength(int length) { int start; var startIndex = Start; if (startIndex.IsFromEnd) start = length - startIndex.Value; else start = startIndex.Value; int end; var endIndex = End; if (endIndex.IsFromEnd) end = length - endIndex.Value; else end = endIndex.Value; if ((uint)end > (uint)length || (uint)start > (uint)end) { throw new ArgumentOutOfRangeException(nameof(length)); } return (start, end - start); } } } namespace System.Runtime.CompilerServices { internal static class RuntimeHelpers { /// <summary> /// Slices the specified array using the specified range. /// </summary> public static T[] GetSubArray<T>(T[] array, Range range) { if (array == null) { throw new ArgumentNullException(nameof(array)); } (int offset, int length) = range.GetOffsetAndLength(array.Length); if (default(T)! != null || typeof(T[]) == array.GetType()) { // We know the type of the array to be exactly T[]. if (length == 0) { return Array.Empty<T>(); } var dest = new T[length]; Array.Copy(array, offset, dest, 0, length); return dest; } else { // The array is actually a U[] where U:T. var dest = (T[])Array.CreateInstance(array.GetType().GetElementType(), length); Array.Copy(array, offset, dest, 0, length); return dest; } } } } #elif NETSTANDARD2_1 || NETCOREAPP3_0_OR_GREATER #else #error Platform not supported #endif
// // CropEditor.cs // // Author: // Ruben Vermeersch <ruben@savanne.be> // // Copyright (C) 2008-2010 Novell, Inc. // Copyright (C) 2008, 2010 Ruben Vermeersch // // 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 FSpot; using FSpot.UI.Dialog; using FSpot.Utils; using Hyena; using Gdk; using Gtk; using Mono.Unix; using System; using System.Collections.Generic; using System.IO; using System.Xml.Serialization; namespace FSpot.Editors { class CropEditor : Editor { private TreeStore constraints_store; private ComboBox constraints_combo; public enum ConstraintType { Normal, AddCustom, SameAsPhoto } private List<SelectionRatioDialog.SelectionConstraint> custom_constraints; private static SelectionRatioDialog.SelectionConstraint [] default_constraints = { new SelectionRatioDialog.SelectionConstraint (Catalog.GetString ("4 x 3 (Book)"), 4.0 / 3.0), new SelectionRatioDialog.SelectionConstraint (Catalog.GetString ("4 x 6 (Postcard)"), 6.0 / 4.0), new SelectionRatioDialog.SelectionConstraint (Catalog.GetString ("5 x 7 (L, 2L)"), 7.0 / 5.0), new SelectionRatioDialog.SelectionConstraint (Catalog.GetString ("8 x 10"), 10.0 / 8.0), new SelectionRatioDialog.SelectionConstraint (Catalog.GetString ("Square"), 1.0) }; public CropEditor () : base (Catalog.GetString ("Crop"), "crop") { NeedsSelection = true; Preferences.SettingChanged += OnPreferencesChanged; Initialized += delegate { State.PhotoImageView.PhotoChanged += delegate { UpdateSelectionCombo (); }; }; } private void OnPreferencesChanged (object sender, NotifyEventArgs args) { LoadPreference (args.Key); } private void LoadPreference (String key) { switch (key) { case Preferences.CUSTOM_CROP_RATIOS: custom_constraints = new List<SelectionRatioDialog.SelectionConstraint> (); if (Preferences.Get<string[]> (key) != null) { XmlSerializer serializer = new XmlSerializer (typeof(SelectionRatioDialog.SelectionConstraint)); foreach (string xml in Preferences.Get<string[]> (key)) custom_constraints.Add ((SelectionRatioDialog.SelectionConstraint)serializer.Deserialize (new StringReader (xml))); } PopulateConstraints (); break; } } public override Widget ConfigurationWidget () { VBox vbox = new VBox (); Label info = new Label (Catalog.GetString ("Select the area that needs cropping.")); constraints_combo = new ComboBox (); CellRendererText constraint_name_cell = new CellRendererText (); CellRendererPixbuf constraint_pix_cell = new CellRendererPixbuf (); constraints_combo.PackStart (constraint_name_cell, true); constraints_combo.PackStart (constraint_pix_cell, false); constraints_combo.SetCellDataFunc (constraint_name_cell, new CellLayoutDataFunc (ConstraintNameCellFunc)); constraints_combo.SetCellDataFunc (constraint_pix_cell, new CellLayoutDataFunc (ConstraintPixCellFunc)); constraints_combo.Changed += HandleConstraintsComboChanged; // FIXME: need tooltip Catalog.GetString ("Constrain the aspect ratio of the selection") LoadPreference (Preferences.CUSTOM_CROP_RATIOS); vbox.Add (info); vbox.Add (constraints_combo); return vbox; } private void PopulateConstraints() { constraints_store = new TreeStore (typeof (string), typeof (string), typeof (double), typeof (ConstraintType)); constraints_combo.Model = constraints_store; constraints_store.AppendValues (null, Catalog.GetString ("No Constraint"), 0.0, ConstraintType.Normal); constraints_store.AppendValues (null, Catalog.GetString ("Same as photo"), 0.0, ConstraintType.SameAsPhoto); foreach (SelectionRatioDialog.SelectionConstraint constraint in custom_constraints) constraints_store.AppendValues (null, constraint.Label, constraint.XyRatio, ConstraintType.Normal); foreach (SelectionRatioDialog.SelectionConstraint constraint in default_constraints) constraints_store.AppendValues (null, constraint.Label, constraint.XyRatio, ConstraintType.Normal); constraints_store.AppendValues (Stock.Edit, Catalog.GetString ("Custom Ratios..."), 0.0, ConstraintType.AddCustom); constraints_combo.Active = 0; } public void UpdateSelectionCombo () { if (!StateInitialized || constraints_combo == null) // Don't bomb out on instant-apply. return; //constraints_combo.Active = 0; TreeIter iter; if (constraints_combo.GetActiveIter (out iter)) { if (((ConstraintType)constraints_store.GetValue (iter, 3)) == ConstraintType.SameAsPhoto) constraints_combo.Active = 0; } } private void HandleConstraintsComboChanged (object o, EventArgs e) { if (State.PhotoImageView == null) { Log.Debug ("PhotoImageView is null"); return; } TreeIter iter; if (constraints_combo.GetActiveIter (out iter)) { double ratio = ((double)constraints_store.GetValue (iter, 2)); ConstraintType type = ((ConstraintType)constraints_store.GetValue (iter, 3)); switch (type) { case ConstraintType.Normal: State.PhotoImageView.SelectionXyRatio = ratio; break; case ConstraintType.AddCustom: SelectionRatioDialog dialog = new SelectionRatioDialog (); dialog.Run (); break; case ConstraintType.SameAsPhoto: try { Pixbuf pb = State.PhotoImageView.CompletePixbuf (); State.PhotoImageView.SelectionXyRatio = (double)pb.Width / (double)pb.Height; } catch (System.Exception ex) { Log.WarningFormat ("Exception in selection ratio's: {0}", ex); State.PhotoImageView.SelectionXyRatio = 0; } break; default: State.PhotoImageView.SelectionXyRatio = 0; break; } } } void ConstraintNameCellFunc (CellLayout cell_layout, CellRenderer cell, TreeModel tree_model, TreeIter iter) { string name = (string)tree_model.GetValue (iter, 1); (cell as CellRendererText).Text = name; } void ConstraintPixCellFunc (CellLayout cell_layout, CellRenderer cell, TreeModel tree_model, TreeIter iter) { string stockname = (string)tree_model.GetValue (iter, 0); if (stockname != null) (cell as CellRendererPixbuf).Pixbuf = GtkUtil.TryLoadIcon (FSpot.Core.Global.IconTheme, stockname, 16, (Gtk.IconLookupFlags)0); else (cell as CellRendererPixbuf).Pixbuf = null; } protected override Pixbuf Process (Pixbuf input, Cms.Profile input_profile) { Rectangle selection = FSpot.Utils.PixbufUtils.TransformOrientation ((int)State.PhotoImageView.PixbufOrientation <= 4 ? input.Width : input.Height, (int)State.PhotoImageView.PixbufOrientation <= 4 ? input.Height : input.Width, State.Selection, State.PhotoImageView.PixbufOrientation); Pixbuf edited = new Pixbuf (input.Colorspace, input.HasAlpha, input.BitsPerSample, selection.Width, selection.Height); input.CopyArea (selection.X, selection.Y, selection.Width, selection.Height, edited, 0, 0); return edited; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ApiManagement { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// ApiOperationPolicyOperations operations. /// </summary> internal partial class ApiOperationPolicyOperations : IServiceOperations<ApiManagementClient>, IApiOperationPolicyOperations { /// <summary> /// Initializes a new instance of the ApiOperationPolicyOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ApiOperationPolicyOperations(ApiManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the ApiManagementClient /// </summary> public ApiManagementClient Client { get; private set; } /// <summary> /// Get the policy configuration at the API Operation level. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='apiId'> /// API identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='operationId'> /// Operation identifier within an API. Must be unique in the current API /// Management service instance. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// 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<PolicyContract,ApiOperationPolicyGetHeaders>> GetWithHttpMessagesAsync(string resourceGroupName, string serviceName, string apiId, string operationId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serviceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serviceName"); } if (serviceName != null) { if (serviceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50); } if (serviceName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "serviceName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$")) { throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"); } } if (apiId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "apiId"); } if (apiId != null) { if (apiId.Length > 256) { throw new ValidationException(ValidationRules.MaxLength, "apiId", 256); } if (apiId.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "apiId", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(apiId, "^[^*#&+:<>?]+$")) { throw new ValidationException(ValidationRules.Pattern, "apiId", "^[^*#&+:<>?]+$"); } } if (operationId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "operationId"); } if (operationId != null) { if (operationId.Length > 256) { throw new ValidationException(ValidationRules.MaxLength, "operationId", 256); } if (operationId.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "operationId", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(operationId, "^[^*#&+:<>?]+$")) { throw new ValidationException(ValidationRules.Pattern, "operationId", "^[^*#&+:<>?]+$"); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string policyId = "policy"; // 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("serviceName", serviceName); tracingParameters.Add("apiId", apiId); tracingParameters.Add("operationId", operationId); tracingParameters.Add("policyId", policyId); 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.ApiManagement/service/{serviceName}/apis/{apiId}/operations/{operationId}/policies/{policyId}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName)); _url = _url.Replace("{apiId}", System.Uri.EscapeDataString(apiId)); _url = _url.Replace("{operationId}", System.Uri.EscapeDataString(operationId)); _url = _url.Replace("{policyId}", System.Uri.EscapeDataString(policyId)); _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 HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<PolicyContract,ApiOperationPolicyGetHeaders>(); _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<PolicyContract>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<ApiOperationPolicyGetHeaders>(JsonSerializer.Create(Client.DeserializationSettings)); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates policy configuration for the API Operation level. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='apiId'> /// API identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='operationId'> /// Operation identifier within an API. Must be unique in the current API /// Management service instance. /// </param> /// <param name='parameters'> /// The policy contents to apply. /// </param> /// <param name='ifMatch'> /// The entity state (Etag) version of the Api Operation policy to update. A /// value of "*" can be used for If-Match to unconditionally apply the /// operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// 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<PolicyContract>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, string apiId, string operationId, PolicyContract parameters, string ifMatch, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serviceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serviceName"); } if (serviceName != null) { if (serviceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50); } if (serviceName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "serviceName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$")) { throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"); } } if (apiId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "apiId"); } if (apiId != null) { if (apiId.Length > 256) { throw new ValidationException(ValidationRules.MaxLength, "apiId", 256); } if (apiId.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "apiId", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(apiId, "^[^*#&+:<>?]+$")) { throw new ValidationException(ValidationRules.Pattern, "apiId", "^[^*#&+:<>?]+$"); } } if (operationId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "operationId"); } if (operationId != null) { if (operationId.Length > 256) { throw new ValidationException(ValidationRules.MaxLength, "operationId", 256); } if (operationId.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "operationId", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(operationId, "^[^*#&+:<>?]+$")) { throw new ValidationException(ValidationRules.Pattern, "operationId", "^[^*#&+:<>?]+$"); } } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (ifMatch == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ifMatch"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string policyId = "policy"; // 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("serviceName", serviceName); tracingParameters.Add("apiId", apiId); tracingParameters.Add("operationId", operationId); tracingParameters.Add("policyId", policyId); tracingParameters.Add("parameters", parameters); tracingParameters.Add("ifMatch", ifMatch); 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.ApiManagement/service/{serviceName}/apis/{apiId}/operations/{operationId}/policies/{policyId}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName)); _url = _url.Replace("{apiId}", System.Uri.EscapeDataString(apiId)); _url = _url.Replace("{operationId}", System.Uri.EscapeDataString(operationId)); _url = _url.Replace("{policyId}", System.Uri.EscapeDataString(policyId)); _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 HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (ifMatch != null) { if (_httpRequest.Headers.Contains("If-Match")) { _httpRequest.Headers.Remove("If-Match"); } _httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch); } 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 StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201 && (int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<PolicyContract>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PolicyContract>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PolicyContract>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the policy configuration at the Api Operation. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='apiId'> /// API identifier. Must be unique in the current API Management service /// instance. /// </param> /// <param name='operationId'> /// Operation identifier within an API. Must be unique in the current API /// Management service instance. /// </param> /// <param name='ifMatch'> /// The entity state (Etag) version of the Api Operation Policy to delete. A /// value of "*" can be used for If-Match to unconditionally apply the /// operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// 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 serviceName, string apiId, string operationId, string ifMatch, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serviceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serviceName"); } if (serviceName != null) { if (serviceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50); } if (serviceName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "serviceName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$")) { throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"); } } if (apiId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "apiId"); } if (apiId != null) { if (apiId.Length > 256) { throw new ValidationException(ValidationRules.MaxLength, "apiId", 256); } if (apiId.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "apiId", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(apiId, "^[^*#&+:<>?]+$")) { throw new ValidationException(ValidationRules.Pattern, "apiId", "^[^*#&+:<>?]+$"); } } if (operationId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "operationId"); } if (operationId != null) { if (operationId.Length > 256) { throw new ValidationException(ValidationRules.MaxLength, "operationId", 256); } if (operationId.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "operationId", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(operationId, "^[^*#&+:<>?]+$")) { throw new ValidationException(ValidationRules.Pattern, "operationId", "^[^*#&+:<>?]+$"); } } if (ifMatch == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ifMatch"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string policyId = "policy"; // 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("serviceName", serviceName); tracingParameters.Add("apiId", apiId); tracingParameters.Add("operationId", operationId); tracingParameters.Add("ifMatch", ifMatch); tracingParameters.Add("policyId", policyId); 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.ApiManagement/service/{serviceName}/apis/{apiId}/operations/{operationId}/policies/{policyId}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName)); _url = _url.Replace("{apiId}", System.Uri.EscapeDataString(apiId)); _url = _url.Replace("{operationId}", System.Uri.EscapeDataString(operationId)); _url = _url.Replace("{policyId}", System.Uri.EscapeDataString(policyId)); _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 HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (ifMatch != null) { if (_httpRequest.Headers.Contains("If-Match")) { _httpRequest.Headers.Remove("If-Match"); } _httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Copyright Bastian Eicher // Licensed under the MIT License #pragma warning disable 0618 using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; namespace NanoByte.Common.Native; static partial class WindowsTaskbar { [StructLayout(LayoutKind.Sequential, Pack = 4)] [SuppressMessage("ReSharper", "FieldCanBeMadeReadOnly.Local"), SuppressMessage("ReSharper", "PrivateFieldCanBeConvertedToLocalVariable")] private struct PropertyKey { private Guid formatID; private int propertyID; public PropertyKey(Guid formatID, int propertyID) { this.formatID = formatID; this.propertyID = propertyID; } } [StructLayout(LayoutKind.Sequential)] private struct PropertyVariant : IDisposable { private ushort valueType; private ushort wReserved1, wReserved2, wReserved3; private IntPtr valueData; private int valueDataExt; public PropertyVariant(string value) { valueType = (ushort)VarEnum.VT_LPWSTR; wReserved1 = 0; wReserved2 = 0; wReserved3 = 0; valueData = Marshal.StringToCoTaskMemUni(value); valueDataExt = 0; } public void Dispose() { PropertyVariant var = this; NativeMethods.PropVariantClear(ref var); valueType = (ushort)VarEnum.VT_EMPTY; wReserved1 = wReserved2 = wReserved3 = 0; valueData = IntPtr.Zero; valueDataExt = 0; } } private const string PropertyStoreGuid = "886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99"; [ComImport, Guid(PropertyStoreGuid), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IPropertyStore { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetCount([Out] out uint cProps); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetAt([In] uint iProp, out PropertyKey pkey); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetValue([In] ref PropertyKey key, out PropertyVariant pv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), PreserveSig] [return: MarshalAs(UnmanagedType.I4)] int SetValue([In] ref PropertyKey key, [In] ref PropertyVariant pv); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] uint Commit(); } [ComImport, Guid("c43dc798-95d1-4bea-9030-bb99e2983a1a"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface ITaskbarList4 { // ITaskbarList [PreserveSig] void HrInit(); [PreserveSig] void AddTab(IntPtr hwnd); [PreserveSig] void DeleteTab(IntPtr hwnd); [PreserveSig] void ActivateTab(IntPtr hwnd); [PreserveSig] void SetActiveAlt(IntPtr hwnd); // ITaskbarList2 [PreserveSig] void MarkFullscreenWindow(IntPtr hwnd, [MarshalAs(UnmanagedType.Bool)] bool fFullscreen); // ITaskbarList3 [PreserveSig] void SetProgressValue(IntPtr hwnd, UInt64 ullCompleted, UInt64 ullTotal); [PreserveSig] void SetProgressState(IntPtr hwnd, ProgressBarState tbpFlags); [PreserveSig] void RegisterTab(IntPtr hwndTab, IntPtr hwndMDI); [PreserveSig] void UnregisterTab(IntPtr hwndTab); [PreserveSig] void SetTabOrder(IntPtr hwndTab, IntPtr hwndInsertBefore); [PreserveSig] void SetTabActive(IntPtr hwndTab, IntPtr hwndInsertBefore, uint dwReserved); [PreserveSig] uint ThumbBarAddButtons(IntPtr hwnd, uint cButtons, [MarshalAs(UnmanagedType.LPArray)] ThumbnailButton[] pButtons); [PreserveSig] uint ThumbBarUpdateButtons(IntPtr hwnd, uint cButtons, [MarshalAs(UnmanagedType.LPArray)] ThumbnailButton[] pButtons); [PreserveSig] void ThumbBarSetImageList(IntPtr hwnd, IntPtr himl); [PreserveSig] void SetOverlayIcon(IntPtr hwnd, IntPtr hIcon, [MarshalAs(UnmanagedType.LPWStr)] string pszDescription); [PreserveSig] void SetThumbnailTooltip(IntPtr hwnd, [MarshalAs(UnmanagedType.LPWStr)] string pszTip); [PreserveSig] void SetThumbnailClip(IntPtr hwnd, IntPtr prcClip); // ITaskbarList4 void SetTabProperties(IntPtr hwndTab, StpFlag stpFlags); } [StructLayout(LayoutKind.Sequential)] [SuppressMessage("ReSharper", "FieldCanBeMadeReadOnly.Local")] private struct ThumbnailButton { [MarshalAs(UnmanagedType.U4)] private ThumbnailMask dwMask; private uint iId; private uint iBitmap; private IntPtr hIcon; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] private string szTip; [MarshalAs(UnmanagedType.U4)] private ThumbnailFlags dwFlags; } [ComImport, Guid("56FDF344-FD6D-11d0-958A-006097C9A090"), ClassInterface(ClassInterfaceType.None)] private class CTaskbarList {} [ComImport, Guid("6332DEBF-87B5-4670-90C0-5E57B408A49E"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface ICustomDestinationList { void SetAppID([MarshalAs(UnmanagedType.LPWStr)] string pszAppID); [PreserveSig] uint BeginList(out uint cMaxSlots, ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppvObject); [PreserveSig] uint AppendCategory([MarshalAs(UnmanagedType.LPWStr)] string pszCategory, [MarshalAs(UnmanagedType.Interface)] IObjectArray poa); void AppendKnownCategory([MarshalAs(UnmanagedType.I4)] KnownDestinationCategory category); [PreserveSig] uint AddUserTasks([MarshalAs(UnmanagedType.Interface)] IObjectArray poa); void CommitList(); void GetRemovedDestinations(ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppvObject); void DeleteList([MarshalAs(UnmanagedType.LPWStr)] string pszAppID); void AbortList(); } private enum ThumbnailMask { Bitmap = 0x1, Icon = 0x2, Tooltip = 0x4, Flags = 0x8 } [Flags] private enum ThumbnailFlags { Enabled = 0x0, ThbfDisabled = 0x1, ThbfDismissonclick = 0x2, ThbfNobackground = 0x4, ThbfHidden = 0x8, ThbfNoninteractive = 0x10 } [Flags] private enum StpFlag { None = 0x0, UseThumbnailalways = 0x1, UseThumbnailWhenActive = 0x2, UsePeekAlways = 0x4, UsePeekWhenActive = 0x8 } private enum KnownDestinationCategory { Frequent = 1, Recent } [ComImport, Guid("77F10CF0-3DB5-4966-B520-B7C54FD35ED6"), ClassInterface(ClassInterfaceType.None)] private class CDestinationList {} [ComImport, Guid("92CA9DCD-5622-4BBA-A805-5E9F541BD8C9"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IObjectArray { void GetCount(out uint cObjects); void GetAt(uint iIndex, ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppvObject); } [ComImport, Guid("5632B1A4-E38A-400A-928A-D4CD63230295"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IObjectCollection { // IObjectArray [PreserveSig] void GetCount(out uint cObjects); [PreserveSig] void GetAt(uint iIndex, ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppvObject); // IObjectCollection void AddObject([MarshalAs(UnmanagedType.Interface)] object pvObject); void AddFromArray([MarshalAs(UnmanagedType.Interface)] IObjectArray poaSource); void RemoveObject(uint uiIndex); void Clear(); } [ComImport, Guid("2D3468C1-36A7-43B6-AC24-D3F02FD9607A"), ClassInterface(ClassInterfaceType.None)] private class CEnumerableObjectCollection {} [ComImport, Guid("000214F9-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IShellLinkW { void GetPath([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, int cchMaxPath, IntPtr pfd, uint fFlags); void GetIDList(out IntPtr ppidl); void SetIDList(IntPtr pidl); void GetDescription([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, int cchMaxName); void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName); void GetWorkingDirectory([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir, int cchMaxPath); void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string pszDir); void GetArguments([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs, int cchMaxPath); void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string pszArgs); void GetHotKey(out short wHotKey); void SetHotKey(short wHotKey); void GetShowCmd(out uint iShowCmd); void SetShowCmd(uint iShowCmd); void GetIconLocation([Out, MarshalAs(UnmanagedType.LPWStr)] out StringBuilder pszIconPath, int cchIconPath, out int iIcon); void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon); void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, uint dwReserved); void Resolve(IntPtr hwnd, uint fFlags); void SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile); } [ComImport, Guid("00021401-0000-0000-C000-000000000046"), ClassInterface(ClassInterfaceType.None)] private class CShellLink {} private static readonly ITaskbarList4? _taskbarList; [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Must perform COM call during init")] [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "COM calls throw unpredictable exceptions and this methods successful execution is not critical.")] static WindowsTaskbar() { if (WindowsUtils.IsWindows7) { try { _taskbarList = (ITaskbarList4)new CTaskbarList(); _taskbarList.HrInit(); } #region Error handling catch (Exception ex) { Log.Warn(ex); } #endregion } } private static class NativeMethods { [DllImport("shell32", SetLastError = true)] public static extern int SHGetPropertyStoreForWindow(IntPtr hwnd, ref Guid iid, [Out, MarshalAs(UnmanagedType.Interface)] out IPropertyStore propertyStore); [DllImport("ole32", PreserveSig = false)] public static extern void PropVariantClear([In, Out] ref PropertyVariant pvar); } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.IO; using System.Runtime.InteropServices; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Controls; using ESRI.ArcGIS.ADF; using ESRI.ArcGIS.SystemUI; using ESRI.ArcGIS.SchematicControls; using ESRI.ArcGIS.Schematic; namespace SchematicApplication { public sealed partial class MainForm : Form { #region class private members private ITOCControl2 m_tocControl; private IMapControl3 m_mapControl = null; private string m_mapDocumentName = string.Empty; private IToolbarMenu m_menuSchematicLayer; private IToolbarMenu m_menuLayer; private IToolbarMenu m_CreateMenu = new ToolbarMenuClass(); private Boolean m_blnExistingMap = false; private ESRI.ArcGIS.esriSystem.IArray m_arrMaps = new ESRI.ArcGIS.esriSystem.Array(); private Boolean m_blnToolbarItemClick = false; private Boolean m_blnOpenDoc = false; #endregion #region class constructor public MainForm() { InitializeComponent(); } #endregion private void MainForm_Load(object sender, EventArgs e) { //get the MapControl and tocControl m_tocControl = (ITOCControl2)axTOCControl1.Object; m_mapControl = (IMapControl3)axMapControl1.Object; //Set buddy control for tocControl m_tocControl.SetBuddyControl(m_mapControl); axToolbarControl2.SetBuddyControl(m_mapControl); //disable the Save menu (since there is no document yet) menuSaveDoc.Enabled = false; axToolbarControl2.Select(); //Create a SchematicEditor's MenuDef object IMenuDef menuDefSchematicEditor = new CreateMenuSchematicEditor(); //Add SchematicEditor on the ToolBarMenu m_CreateMenu.AddItem(menuDefSchematicEditor, 0, -1, false, esriCommandStyles.esriCommandStyleIconAndText); //Set the ToolbarMenu's hook m_CreateMenu.SetHook(axToolbarControl2.Object); //Set the ToolbarMenu's caption m_CreateMenu.Caption = "SchematicEditor"; /// Add ToolbarMenu on the ToolBarControl axToolbarControl2.AddItem(m_CreateMenu, -1, -1, false, 0, esriCommandStyles.esriCommandStyleMenuBar); ///Create a other ToolbarMenu for layer m_menuSchematicLayer = new ToolbarMenuClass(); m_menuLayer = new ToolbarMenuClass(); ///Add 3 items on the SchematicLayer properties menu m_menuSchematicLayer.AddItem(new RemoveLayer(), -1, 0, false, esriCommandStyles.esriCommandStyleTextOnly); m_menuSchematicLayer.AddItem("esriControls.ControlsSchematicSaveEditsCommand", -1, 1, true, esriCommandStyles.esriCommandStyleIconAndText); m_menuSchematicLayer.AddItem("esriControls.ControlsSchematicUpdateDiagramCommand", -1, 2, false, esriCommandStyles.esriCommandStyleIconAndText); IMenuDef subMenuDef = new CreateSubMenuSchematic(); m_menuSchematicLayer.AddSubMenu(subMenuDef, 3, true); ////Add the sub-menu as the third item on the Layer properties menu, making it start a new group m_menuSchematicLayer.AddItem(new ZoomToLayer(), -1, 4, true, esriCommandStyles.esriCommandStyleTextOnly); m_menuLayer.AddItem(new RemoveLayer(), -1, 0, false, esriCommandStyles.esriCommandStyleTextOnly); m_menuLayer.AddItem(new ZoomToLayer(), -1, 1, true, esriCommandStyles.esriCommandStyleTextOnly); ////Set the hook of each menu m_menuSchematicLayer.SetHook(m_mapControl); m_menuLayer.SetHook(m_mapControl); } private void axTOCControl1_OnMouseDown(object sender, ITOCControlEvents_OnMouseDownEvent e) { if (e.button != 2) return; esriTOCControlItem item = esriTOCControlItem.esriTOCControlItemNone; IBasicMap map = null; ILayer layer = null; object other = null; object index = null; //Determine what kind of item is selected m_tocControl.HitTest(e.x, e.y, ref item, ref map, ref layer, ref other, ref index); //Ensure the item gets selected if (item == esriTOCControlItem.esriTOCControlItemMap) m_tocControl.SelectItem(map, null); else m_tocControl.SelectItem(layer, null); //Set the layer into the CustomProperty (this is used by the custom layer commands) m_mapControl.CustomProperty = layer; ISchematicLayer schLayer = layer as ISchematicLayer; if (schLayer != null) /// attach menu for SchematicLayer { ISchematicTarget schematicTarget = new ESRI.ArcGIS.SchematicControls.EngineSchematicEnvironmentClass() as ISchematicTarget; if (schematicTarget != null) schematicTarget.SchematicTarget = schLayer; //Popup the correct context menu if (item == esriTOCControlItem.esriTOCControlItemLayer) m_menuSchematicLayer.PopupMenu(e.x, e.y, m_tocControl.hWnd); } else /// attach menu for Layer { //Popup the correct context menu if (item == esriTOCControlItem.esriTOCControlItemLayer) m_menuLayer.PopupMenu(e.x, e.y, m_tocControl.hWnd); } } #region Main Menu event handlers private void menuNewDoc_Click(object sender, EventArgs e) { //execute New Document command ICommand command = new CreateNewDocument(); command.OnCreate(m_mapControl.Object); command.OnClick(); } private void menuOpenDoc_Click(object sender, EventArgs e) { //execute Open Document command ICommand command = new ControlsOpenDocCommandClass(); command.OnCreate(m_mapControl.Object); command.OnClick(); m_blnOpenDoc = true; m_blnExistingMap = false; cboFrame.Items.Clear(); } private void menuSaveDoc_Click(object sender, EventArgs e) { //execute Save Document command if (m_mapControl.CheckMxFile(m_mapDocumentName)) { //create a new instance of a MapDocument IMapDocument mapDoc = new MapDocumentClass(); mapDoc.Open(m_mapDocumentName, string.Empty); //Make sure that the MapDocument is not read only if (mapDoc.get_IsReadOnly(m_mapDocumentName)) { MessageBox.Show("Map document is read only!"); mapDoc.Close(); return; } //Replace its contents with the current map mapDoc.ReplaceContents((IMxdContents)m_mapControl.Map); //save the MapDocument in order to persist it mapDoc.Save(mapDoc.UsesRelativePaths, false); //close the MapDocument mapDoc.Close(); } } private void menuSaveAs_Click(object sender, EventArgs e) { //execute SaveAs Document command ICommand command = new ControlsSaveAsDocCommandClass(); command.OnCreate(m_mapControl.Object); command.OnClick(); } private void menuExitApp_Click(object sender, EventArgs e) { //exit the application Application.Exit(); } #endregion //listen to MapReplaced event in order to update the status bar and the Save menu private void axMapControl1_OnMapReplaced(object sender, IMapControlEvents2_OnMapReplacedEvent e) { //get the current document name from the MapControl m_mapDocumentName = m_mapControl.DocumentFilename; if (m_blnToolbarItemClick == true) { m_blnToolbarItemClick = false; m_blnExistingMap = true; //need to add the new diagram to the combobox IMap p = (IMap)e.newMap; if (!cboFrame.Items.Contains(p.Name)) cboFrame.Items.Add(p.Name.ToString()); m_arrMaps.Add(p); } if (m_blnExistingMap == false) { IMap m; m_arrMaps = axMapControl1.ReadMxMaps(m_mapDocumentName); Int16 i; for (i = 0; i < m_arrMaps.Count; i++) { m = (IMap)m_arrMaps.Element[i]; if (!cboFrame.Items.Contains(m.Name.ToString())) cboFrame.Items.Add(m.Name.ToString()); } cboFrame.Text = this.axMapControl1.ActiveView.FocusMap.Name; } //if there is no MapDocument, disable the Save menu and clear the status bar if (m_mapDocumentName == string.Empty) { menuSaveDoc.Enabled = false; statusBarXY.Text = string.Empty; } else { //enable the Save menu and write the doc name to the status bar menuSaveDoc.Enabled = true; statusBarXY.Text = Path.GetFileName(m_mapDocumentName); } m_blnExistingMap = true; cboFrame.Text = axMapControl1.Map.Name.ToString(); } private void axMapControl1_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e) { statusBarXY.Text = string.Format("{0}, {1} {2}", e.mapX.ToString("#######.##"), e.mapY.ToString("#######.##"), axMapControl1.MapUnits.ToString().Substring(4)); } private void onSelectedValueChanged(object sender, EventArgs e) { IMap m; Int16 i; for (i = 0; i < m_arrMaps.Count; i++) { m = (IMap)m_arrMaps.Element[i]; if (m.Name == cboFrame.Text) { m_blnExistingMap = true; m_mapControl.Map = (IMap)m_arrMaps.Element[i]; m_mapControl.Refresh(); m_blnExistingMap = false; return; } } } //specific for toolbar2 private void onToolbarItemClick(object sender, IToolbarControlEvents_OnItemClickEvent e) { if (e.index == 0) { //clicked generate new diagram m_blnToolbarItemClick = true; } //if (m_blnOpenDoc == false) //{ // m_blnToolbarItemClick = true; //} //else //{ // m_blnOpenDoc = false; //} } } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // namespace Revit.SDK.Samples.CreateSimpleAreaRein.CS { using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using Autodesk.Revit; using Autodesk.Revit.DB; using Autodesk.Revit.DB.Structure; using GeoElement = Autodesk.Revit.DB.GeometryElement; using GeoSolid = Autodesk.Revit.DB.Solid; using Element = Autodesk.Revit.DB.Element; /// <summary> /// provide some common geometry judgement and calculate method /// </summary> class GeomUtil { const double PRECISION = 0.00001; //precision when judge whether two doubles are equal /// <summary> /// get all faces that compose the geometry solid of given element /// </summary> /// <param name="elem">element to be calculated</param> /// <returns>all faces</returns> public static FaceArray GetFaces(Element elem) { List<Face> faces = new List<Face>(); Autodesk.Revit.DB.Options geoOptions = Command.CommandData.Application.Application.Create.NewGeometryOptions(); geoOptions.ComputeReferences = true; GeoElement geoElem = elem.get_Geometry(geoOptions); GeometryObjectArray geoElems = geoElem.Objects; foreach (object o in geoElems) { GeoSolid geoSolid = o as GeoSolid; if (null == geoSolid) { continue; } return geoSolid.Faces; } return null; } /// <summary> /// get all points proximate to the given face /// </summary> /// <param name="face">face to be calculated</param> /// <returns></returns> public static List<Autodesk.Revit.DB.XYZ > GetPoints(Face face) { List<Autodesk.Revit.DB.XYZ > points = new List<Autodesk.Revit.DB.XYZ >(); List<Autodesk.Revit.DB.XYZ> XYZs = face.Triangulate().Vertices as List<Autodesk.Revit.DB.XYZ>; foreach (Autodesk.Revit.DB.XYZ point in XYZs) { points.Add(point); } return points; } /// <summary> /// judge whether the given face is horizontal /// </summary> /// <param name="face">face to be judged</param> /// <returns>is horizontal</returns> public static bool IsHorizontalFace(Face face) { List<Autodesk.Revit.DB.XYZ > points = GetPoints(face); double z1 = points[0].Z; double z2 = points[1].Z; double z3 = points[2].Z; double z4 = points[3].Z; bool flag = IsEqual(z1, z2); flag = flag && IsEqual(z2, z3); flag = flag && IsEqual(z3, z4); flag = flag && IsEqual(z4, z1); return flag; } /// <summary> /// judge whether a face and a line are parallel /// </summary> /// <param name="face"></param> /// <param name="line"></param> /// <returns></returns> public static bool IsParallel(Face face, Line line) { List<Autodesk.Revit.DB.XYZ > points = GetPoints(face); Autodesk.Revit.DB.XYZ vector1 = SubXYZ(points[0], points[1]); Autodesk.Revit.DB.XYZ vector2 = SubXYZ(points[1], points[2]); Autodesk.Revit.DB.XYZ refer = SubXYZ(line.get_EndPoint(0), line.get_EndPoint(1)); Autodesk.Revit.DB.XYZ cross = CrossMatrix(vector1, vector2); double result = DotMatrix(cross, refer); if (result < PRECISION) { return true; } return false; } /// <summary> /// judge whether given 4 lines can form a rectangular /// </summary> /// <param name="lines"></param> /// <returns>is rectangular</returns> public static bool IsRectangular(CurveArray curves) { //make sure the CurveArray contains 4 line if (curves.Size != 4) { return false; } Line[] lines = new Line[4]; for (int i = 0; i < 4; i++) { lines[i] = curves.get_Item(i) as Line; if (null == lines[i]) { return false; } } //make sure the first line is vertical to 2 lines and parallel to another line Line iniLine = lines[0]; Line[] verticalLines = new Line[2]; Line paraLine = null; int index = 0; for (int i = 1; i < 4; i++) { if (IsVertical(lines[0], lines[i])) { verticalLines[index] = lines[i]; index++; } else { paraLine = lines[i]; } } if (index != 2) { return false; } bool flag = IsVertical(paraLine, verticalLines[0]); return flag; } /// <summary> /// judge whether two lines are vertical /// </summary> /// <param name="line1"></param> /// <param name="line2"></param> /// <returns></returns> private static bool IsVertical(Line line1, Line line2) { Autodesk.Revit.DB.XYZ vector1 = SubXYZ(line1.get_EndPoint(0), line1.get_EndPoint(1)); Autodesk.Revit.DB.XYZ vector2 = SubXYZ(line2.get_EndPoint(0), line2.get_EndPoint(1)); double result = DotMatrix(vector1, vector2); if (Math.Abs(result) < PRECISION) { return true; } return false; } /// <summary> /// subtraction of two Autodesk.Revit.DB.XYZ as Matrix /// </summary> /// <param name="p1"></param> /// <param name="p2"></param> /// <returns></returns> private static Autodesk.Revit.DB.XYZ SubXYZ(Autodesk.Revit.DB.XYZ p1, Autodesk.Revit.DB.XYZ p2) { double x = p1.X - p2.X; double y = p1.Y - p2.Y; double z = p1.Z - p2.Z; Autodesk.Revit.DB.XYZ result = new Autodesk.Revit.DB.XYZ (x, y, z); return result; } /// <summary> /// multiplication cross of two Autodesk.Revit.DB.XYZ as Matrix /// </summary> /// <param name="p1"></param> /// <param name="p2"></param> /// <returns></returns> private static Autodesk.Revit.DB.XYZ CrossMatrix(Autodesk.Revit.DB.XYZ p1, Autodesk.Revit.DB.XYZ p2) { double v1 = p1.X; double v2 = p1.Y; double v3 = p1.Z; double u1 = p2.X; double u2 = p2.Y; double u3 = p2.Z; double x = v3 * u2 - v2 * u3; double y = -v3 * u1 + v1 * u3; double z = v2 * u1 - v1 * u2; Autodesk.Revit.DB.XYZ point = new Autodesk.Revit.DB.XYZ (x, y, z); return point; } /// <summary> /// dot product of two Autodesk.Revit.DB.XYZ as Matrix /// </summary> /// <param name="p1"></param> /// <param name="p2"></param> /// <returns></returns> private static double DotMatrix(Autodesk.Revit.DB.XYZ p1, Autodesk.Revit.DB.XYZ p2) { double v1 = p1.X; double v2 = p1.Y; double v3 = p1.Z; double u1 = p2.X; double u2 = p2.Y; double u3 = p2.Z; double result = v1 * u1 + v2 * u2 + v3 * u3; return result; } /// <summary> /// judge whether the subtraction of two doubles is less than /// the internal decided precision /// </summary> /// <param name="d1"></param> /// <param name="d2"></param> /// <returns></returns> private static bool IsEqual(double d1, double d2) { double diff = Math.Abs(d1 - d2); if (diff < PRECISION) { return true; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //////////////////////////////////////////////////////////////////////////////// // namespace System.Reflection { using System; using System.Diagnostics.SymbolStore; using System.Runtime.Remoting; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using System.IO; using System.Globalization; using System.Runtime.Versioning; using System.Diagnostics.Contracts; [Serializable] [Flags] [System.Runtime.InteropServices.ComVisible(true)] public enum PortableExecutableKinds { NotAPortableExecutableImage = 0x0, ILOnly = 0x1, Required32Bit = 0x2, PE32Plus = 0x4, Unmanaged32Bit = 0x8, [ComVisible(false)] Preferred32Bit = 0x10, } [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public enum ImageFileMachine { I386 = 0x014c, IA64 = 0x0200, AMD64 = 0x8664, ARM = 0x01c4, } [Serializable] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_Module))] [System.Runtime.InteropServices.ComVisible(true)] #pragma warning disable 618 [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted = true)] #pragma warning restore 618 public abstract class Module : _Module, ISerializable, ICustomAttributeProvider { #region Static Constructor static Module() { __Filters _fltObj; _fltObj = new __Filters(); FilterTypeName = new TypeFilter(_fltObj.FilterTypeName); FilterTypeNameIgnoreCase = new TypeFilter(_fltObj.FilterTypeNameIgnoreCase); } #endregion #region Constructor protected Module() { } #endregion #region Public Statics public static readonly TypeFilter FilterTypeName; public static readonly TypeFilter FilterTypeNameIgnoreCase; #if !FEATURE_CORECLR public static bool operator ==(Module left, Module right) { if (ReferenceEquals(left, right)) return true; if ((object)left == null || (object)right == null || left is RuntimeModule || right is RuntimeModule) { return false; } return left.Equals(right); } public static bool operator !=(Module left, Module right) { return !(left == right); } #endif // !FEATURE_CORECLR public override bool Equals(object o) { return base.Equals(o); } public override int GetHashCode() { return base.GetHashCode(); } #endregion #region Literals private const BindingFlags DefaultLookup = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public; #endregion #region object overrides public override String ToString() { return ScopeName; } #endregion public virtual IEnumerable<CustomAttributeData> CustomAttributes { get { return GetCustomAttributesData(); } } #region ICustomAttributeProvider Members public virtual Object[] GetCustomAttributes(bool inherit) { throw new NotImplementedException(); } public virtual Object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotImplementedException(); } public virtual bool IsDefined(Type attributeType, bool inherit) { throw new NotImplementedException(); } public virtual IList<CustomAttributeData> GetCustomAttributesData() { throw new NotImplementedException(); } #endregion #region public instances members public MethodBase ResolveMethod(int metadataToken) { return ResolveMethod(metadataToken, null, null); } public virtual MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments); throw new NotImplementedException(); } public FieldInfo ResolveField(int metadataToken) { return ResolveField(metadataToken, null, null); } public virtual FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.ResolveField(metadataToken, genericTypeArguments, genericMethodArguments); throw new NotImplementedException(); } public Type ResolveType(int metadataToken) { return ResolveType(metadataToken, null, null); } public virtual Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.ResolveType(metadataToken, genericTypeArguments, genericMethodArguments); throw new NotImplementedException(); } public MemberInfo ResolveMember(int metadataToken) { return ResolveMember(metadataToken, null, null); } public virtual MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.ResolveMember(metadataToken, genericTypeArguments, genericMethodArguments); throw new NotImplementedException(); } public virtual byte[] ResolveSignature(int metadataToken) { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.ResolveSignature(metadataToken); throw new NotImplementedException(); } public virtual string ResolveString(int metadataToken) { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.ResolveString(metadataToken); throw new NotImplementedException(); } public virtual void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine) { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) rtModule.GetPEKind(out peKind, out machine); throw new NotImplementedException(); } public virtual int MDStreamVersion { get { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.MDStreamVersion; throw new NotImplementedException(); } } [System.Security.SecurityCritical] // auto-generated_required public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotImplementedException(); } [System.Runtime.InteropServices.ComVisible(true)] public virtual Type GetType(String className, bool ignoreCase) { return GetType(className, false, ignoreCase); } [System.Runtime.InteropServices.ComVisible(true)] public virtual Type GetType(String className) { return GetType(className, false, false); } [System.Runtime.InteropServices.ComVisible(true)] public virtual Type GetType(String className, bool throwOnError, bool ignoreCase) { throw new NotImplementedException(); } public virtual String FullyQualifiedName { #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif get { throw new NotImplementedException(); } } public virtual Type[] FindTypes(TypeFilter filter,Object filterCriteria) { Type[] c = GetTypes(); int cnt = 0; for (int i = 0;i<c.Length;i++) { if (filter!=null && !filter(c[i],filterCriteria)) c[i] = null; else cnt++; } if (cnt == c.Length) return c; Type[] ret = new Type[cnt]; cnt=0; for (int i=0;i<c.Length;i++) { if (c[i] != null) ret[cnt++] = c[i]; } return ret; } public virtual Type[] GetTypes() { throw new NotImplementedException(); } public virtual Guid ModuleVersionId { get { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.ModuleVersionId; throw new NotImplementedException(); } } public virtual int MetadataToken { get { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.MetadataToken; throw new NotImplementedException(); } } public virtual bool IsResource() { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.IsResource(); throw new NotImplementedException(); } public FieldInfo[] GetFields() { return GetFields(Module.DefaultLookup); } public virtual FieldInfo[] GetFields(BindingFlags bindingFlags) { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.GetFields(bindingFlags); throw new NotImplementedException(); } public FieldInfo GetField(String name) { return GetField(name,Module.DefaultLookup); } public virtual FieldInfo GetField(String name, BindingFlags bindingAttr) { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.GetField(name, bindingAttr); throw new NotImplementedException(); } public MethodInfo[] GetMethods() { return GetMethods(Module.DefaultLookup); } public virtual MethodInfo[] GetMethods(BindingFlags bindingFlags) { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.GetMethods(bindingFlags); throw new NotImplementedException(); } public MethodInfo GetMethod( String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { if (name == null) throw new ArgumentNullException("name"); if (types == null) throw new ArgumentNullException("types"); Contract.EndContractBlock(); for (int i = 0; i < types.Length; i++) { if (types[i] == null) throw new ArgumentNullException("types"); } return GetMethodImpl(name, bindingAttr, binder, callConvention, types, modifiers); } public MethodInfo GetMethod(String name, Type[] types) { if (name == null) throw new ArgumentNullException("name"); if (types == null) throw new ArgumentNullException("types"); Contract.EndContractBlock(); for (int i = 0; i < types.Length; i++) { if (types[i] == null) throw new ArgumentNullException("types"); } return GetMethodImpl(name, Module.DefaultLookup, null, CallingConventions.Any, types, null); } public MethodInfo GetMethod(String name) { if (name == null) throw new ArgumentNullException("name"); Contract.EndContractBlock(); return GetMethodImpl(name, Module.DefaultLookup, null, CallingConventions.Any, null, null); } protected virtual MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotImplementedException(); } public virtual String ScopeName { get { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.ScopeName; throw new NotImplementedException(); } } public virtual String Name { get { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.Name; throw new NotImplementedException(); } } public virtual Assembly Assembly { [Pure] get { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeModule rtModule = this as RuntimeModule; if (rtModule != null) return rtModule.Assembly; throw new NotImplementedException(); } } // This API never fails, it will return an empty handle for non-runtime handles and // a valid handle for reflection only modules. public ModuleHandle ModuleHandle { get { return GetModuleHandle(); } } // Used to provide implementation and overriding point for ModuleHandle. // To get a module handle inside mscorlib, use GetNativeHandle instead. internal virtual ModuleHandle GetModuleHandle() { return ModuleHandle.EmptyHandle; } #if FEATURE_X509 && FEATURE_CAS_POLICY public virtual System.Security.Cryptography.X509Certificates.X509Certificate GetSignerCertificate() { throw new NotImplementedException(); } #endif // FEATURE_X509 && FEATURE_CAS_POLICY #endregion #if !FEATURE_CORECLR void _Module.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _Module.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _Module.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { throw new NotImplementedException(); } void _Module.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { throw new NotImplementedException(); } #endif } [Serializable] internal class RuntimeModule : Module { internal RuntimeModule() { throw new NotSupportedException(); } #region FCalls [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetType(RuntimeModule module, String className, bool ignoreCase, bool throwOnError, ObjectHandleOnStack type, ObjectHandleOnStack keepAlive); [System.Security.SecurityCritical] [DllImport(JitHelpers.QCall)] [SuppressUnmanagedCodeSecurity] private static extern bool nIsTransientInternal(RuntimeModule module); [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetScopeName(RuntimeModule module, StringHandleOnStack retString); [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetFullyQualifiedName(RuntimeModule module, StringHandleOnStack retString); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern static RuntimeType[] GetTypes(RuntimeModule module); [System.Security.SecuritySafeCritical] // auto-generated internal RuntimeType[] GetDefinedTypes() { return GetTypes(GetNativeHandle()); } [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern static bool IsResource(RuntimeModule module); #if FEATURE_X509 && FEATURE_CAS_POLICY [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] static private extern void GetSignerCertificate(RuntimeModule module, ObjectHandleOnStack retData); #endif // FEATURE_X509 && FEATURE_CAS_POLICY #endregion #region Module overrides private static RuntimeTypeHandle[] ConvertToTypeHandleArray(Type[] genericArguments) { if (genericArguments == null) return null; int size = genericArguments.Length; RuntimeTypeHandle[] typeHandleArgs = new RuntimeTypeHandle[size]; for (int i = 0; i < size; i++) { Type typeArg = genericArguments[i]; if (typeArg == null) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGenericInstArray")); typeArg = typeArg.UnderlyingSystemType; if (typeArg == null) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGenericInstArray")); if (!(typeArg is RuntimeType)) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGenericInstArray")); typeHandleArgs[i] = typeArg.GetTypeHandleInternal(); } return typeHandleArgs; } [System.Security.SecuritySafeCritical] // auto-generated public override byte[] ResolveSignature(int metadataToken) { MetadataToken tk = new MetadataToken(metadataToken); if (!MetadataImport.IsValidToken(tk)) throw new ArgumentOutOfRangeException("metadataToken", Environment.GetResourceString("Argument_InvalidToken", tk, this)); if (!tk.IsMemberRef && !tk.IsMethodDef && !tk.IsTypeSpec && !tk.IsSignature && !tk.IsFieldDef) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidToken", tk, this), "metadataToken"); ConstArray signature; if (tk.IsMemberRef) signature = MetadataImport.GetMemberRefProps(metadataToken); else signature = MetadataImport.GetSignatureFromToken(metadataToken); byte[] sig = new byte[signature.Length]; for (int i = 0; i < signature.Length; i++) sig[i] = signature[i]; return sig; } [System.Security.SecuritySafeCritical] // auto-generated public override MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { MetadataToken tk = new MetadataToken(metadataToken); if (!MetadataImport.IsValidToken(tk)) throw new ArgumentOutOfRangeException("metadataToken", Environment.GetResourceString("Argument_InvalidToken", tk, this)); RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments); RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments); try { if (!tk.IsMethodDef && !tk.IsMethodSpec) { if (!tk.IsMemberRef) throw new ArgumentException("metadataToken", Environment.GetResourceString("Argument_ResolveMethod", tk, this)); unsafe { ConstArray sig = MetadataImport.GetMemberRefProps(tk); if (*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field) throw new ArgumentException("metadataToken", Environment.GetResourceString("Argument_ResolveMethod", tk, this)); } } IRuntimeMethodInfo methodHandle = ModuleHandle.ResolveMethodHandleInternal(GetNativeHandle(), tk, typeArgs, methodArgs); Type declaringType = RuntimeMethodHandle.GetDeclaringType(methodHandle); if (declaringType.IsGenericType || declaringType.IsArray) { MetadataToken tkDeclaringType = new MetadataToken(MetadataImport.GetParentToken(tk)); if (tk.IsMethodSpec) tkDeclaringType = new MetadataToken(MetadataImport.GetParentToken(tkDeclaringType)); declaringType = ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments); } return System.RuntimeType.GetMethodBase(declaringType as RuntimeType, methodHandle); } catch (BadImageFormatException e) { throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e); } } [System.Security.SecurityCritical] // auto-generated private FieldInfo ResolveLiteralField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { MetadataToken tk = new MetadataToken(metadataToken); if (!MetadataImport.IsValidToken(tk) || !tk.IsFieldDef) throw new ArgumentOutOfRangeException("metadataToken", String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_InvalidToken", tk, this))); int tkDeclaringType; string fieldName; fieldName = MetadataImport.GetName(tk).ToString(); tkDeclaringType = MetadataImport.GetParentToken(tk); Type declaringType = ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments); declaringType.GetFields(); try { return declaringType.GetField(fieldName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); } catch { throw new ArgumentException(Environment.GetResourceString("Argument_ResolveField", tk, this), "metadataToken"); } } [System.Security.SecuritySafeCritical] // auto-generated public override FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { MetadataToken tk = new MetadataToken(metadataToken); if (!MetadataImport.IsValidToken(tk)) throw new ArgumentOutOfRangeException("metadataToken", Environment.GetResourceString("Argument_InvalidToken", tk, this)); RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments); RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments); try { IRuntimeFieldInfo fieldHandle = null; if (!tk.IsFieldDef) { if (!tk.IsMemberRef) throw new ArgumentException("metadataToken", Environment.GetResourceString("Argument_ResolveField", tk, this)); unsafe { ConstArray sig = MetadataImport.GetMemberRefProps(tk); if (*(MdSigCallingConvention*)sig.Signature.ToPointer() != MdSigCallingConvention.Field) throw new ArgumentException("metadataToken", Environment.GetResourceString("Argument_ResolveField", tk, this)); } fieldHandle = ModuleHandle.ResolveFieldHandleInternal(GetNativeHandle(), tk, typeArgs, methodArgs); } fieldHandle = ModuleHandle.ResolveFieldHandleInternal(GetNativeHandle(), metadataToken, typeArgs, methodArgs); RuntimeType declaringType = RuntimeFieldHandle.GetApproxDeclaringType(fieldHandle.Value); if (declaringType.IsGenericType || declaringType.IsArray) { int tkDeclaringType = ModuleHandle.GetMetadataImport(GetNativeHandle()).GetParentToken(metadataToken); declaringType = (RuntimeType)ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments); } return System.RuntimeType.GetFieldInfo(declaringType, fieldHandle); } catch(MissingFieldException) { return ResolveLiteralField(tk, genericTypeArguments, genericMethodArguments); } catch (BadImageFormatException e) { throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e); } } [System.Security.SecuritySafeCritical] // auto-generated public override Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { MetadataToken tk = new MetadataToken(metadataToken); if (tk.IsGlobalTypeDefToken) throw new ArgumentException(Environment.GetResourceString("Argument_ResolveModuleType", tk), "metadataToken"); if (!MetadataImport.IsValidToken(tk)) throw new ArgumentOutOfRangeException("metadataToken", Environment.GetResourceString("Argument_InvalidToken", tk, this)); if (!tk.IsTypeDef && !tk.IsTypeSpec && !tk.IsTypeRef) throw new ArgumentException(Environment.GetResourceString("Argument_ResolveType", tk, this), "metadataToken"); RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments); RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments); try { Type t = GetModuleHandle().ResolveTypeHandle(metadataToken, typeArgs, methodArgs).GetRuntimeType(); if (t == null) throw new ArgumentException(Environment.GetResourceString("Argument_ResolveType", tk, this), "metadataToken"); return t; } catch (BadImageFormatException e) { throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e); } } [System.Security.SecuritySafeCritical] // auto-generated public override MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { MetadataToken tk = new MetadataToken(metadataToken); if (tk.IsProperty) throw new ArgumentException(Environment.GetResourceString("InvalidOperation_PropertyInfoNotAvailable")); if (tk.IsEvent) throw new ArgumentException(Environment.GetResourceString("InvalidOperation_EventInfoNotAvailable")); if (tk.IsMethodSpec || tk.IsMethodDef) return ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments); if (tk.IsFieldDef) return ResolveField(metadataToken, genericTypeArguments, genericMethodArguments); if (tk.IsTypeRef || tk.IsTypeDef || tk.IsTypeSpec) return ResolveType(metadataToken, genericTypeArguments, genericMethodArguments); if (tk.IsMemberRef) { if (!MetadataImport.IsValidToken(tk)) throw new ArgumentOutOfRangeException("metadataToken", Environment.GetResourceString("Argument_InvalidToken", tk, this)); ConstArray sig = MetadataImport.GetMemberRefProps(tk); unsafe { if (*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field) { return ResolveField(tk, genericTypeArguments, genericMethodArguments); } else { return ResolveMethod(tk, genericTypeArguments, genericMethodArguments); } } } throw new ArgumentException("metadataToken", Environment.GetResourceString("Argument_ResolveMember", tk, this)); } [System.Security.SecuritySafeCritical] // auto-generated public override string ResolveString(int metadataToken) { MetadataToken tk = new MetadataToken(metadataToken); if (!tk.IsString) throw new ArgumentException( String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_ResolveString"), metadataToken, ToString())); if (!MetadataImport.IsValidToken(tk)) throw new ArgumentOutOfRangeException("metadataToken", String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_InvalidToken", tk, this))); string str = MetadataImport.GetUserString(metadataToken); if (str == null) throw new ArgumentException( String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_ResolveString"), metadataToken, ToString())); return str; } public override void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine) { ModuleHandle.GetPEKind(GetNativeHandle(), out peKind, out machine); } public override int MDStreamVersion { [System.Security.SecuritySafeCritical] // auto-generated get { return ModuleHandle.GetMDStreamVersion(GetNativeHandle()); } } #endregion #region Data Members #pragma warning disable 169 // If you add any data members, you need to update the native declaration ReflectModuleBaseObject. private RuntimeType m_runtimeType; private RuntimeAssembly m_runtimeAssembly; private IntPtr m_pRefClass; private IntPtr m_pData; private IntPtr m_pGlobals; private IntPtr m_pFields; #pragma warning restore 169 #endregion #region Protected Virtuals protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { return GetMethodInternal(name, bindingAttr, binder, callConvention, types, modifiers); } internal MethodInfo GetMethodInternal(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { if (RuntimeType == null) return null; if (types == null) { return RuntimeType.GetMethod(name, bindingAttr); } else { return RuntimeType.GetMethod(name, bindingAttr, binder, callConvention, types, modifiers); } } #endregion #region Internal Members internal RuntimeType RuntimeType { get { if (m_runtimeType == null) m_runtimeType = ModuleHandle.GetModuleType(GetNativeHandle()); return m_runtimeType; } } [System.Security.SecuritySafeCritical] internal bool IsTransientInternal() { return RuntimeModule.nIsTransientInternal(this.GetNativeHandle()); } internal MetadataImport MetadataImport { [System.Security.SecurityCritical] // auto-generated get { unsafe { return ModuleHandle.GetMetadataImport(GetNativeHandle()); } } } #endregion #region ICustomAttributeProvider Members public override Object[] GetCustomAttributes(bool inherit) { return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); } [System.Security.SecuritySafeCritical] // auto-generated public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); return CustomAttribute.IsDefined(this, attributeRuntimeType); } public override IList<CustomAttributeData> GetCustomAttributesData() { return CustomAttributeData.GetCustomAttributesInternal(this); } #endregion #region Public Virtuals [System.Security.SecurityCritical] // auto-generated_required public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } Contract.EndContractBlock(); UnitySerializationHolder.GetUnitySerializationInfo(info, UnitySerializationHolder.ModuleUnity, this.ScopeName, this.GetRuntimeAssembly()); } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] public override Type GetType(String className, bool throwOnError, bool ignoreCase) { // throw on null strings regardless of the value of "throwOnError" if (className == null) throw new ArgumentNullException("className"); RuntimeType retType = null; Object keepAlive = null; GetType(GetNativeHandle(), className, throwOnError, ignoreCase, JitHelpers.GetObjectHandleOnStack(ref retType), JitHelpers.GetObjectHandleOnStack(ref keepAlive)); GC.KeepAlive(keepAlive); return retType; } [System.Security.SecurityCritical] // auto-generated internal string GetFullyQualifiedName() { String fullyQualifiedName = null; GetFullyQualifiedName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref fullyQualifiedName)); return fullyQualifiedName; } public override String FullyQualifiedName { #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #else [System.Security.SecuritySafeCritical] #endif get { String fullyQualifiedName = GetFullyQualifiedName(); if (fullyQualifiedName != null) { bool checkPermission = true; try { Path.GetFullPathInternal(fullyQualifiedName); } catch(ArgumentException) { checkPermission = false; } if (checkPermission) { new FileIOPermission( FileIOPermissionAccess.PathDiscovery, fullyQualifiedName ).Demand(); } } return fullyQualifiedName; } } [System.Security.SecuritySafeCritical] // auto-generated public override Type[] GetTypes() { return GetTypes(GetNativeHandle()); } #endregion #region Public Members public override Guid ModuleVersionId { [System.Security.SecuritySafeCritical] // auto-generated get { unsafe { Guid mvid; MetadataImport.GetScopeProps(out mvid); return mvid; } } } public override int MetadataToken { [System.Security.SecuritySafeCritical] // auto-generated get { return ModuleHandle.GetToken(GetNativeHandle()); } } public override bool IsResource() { return IsResource(GetNativeHandle()); } public override FieldInfo[] GetFields(BindingFlags bindingFlags) { if (RuntimeType == null) return new FieldInfo[0]; return RuntimeType.GetFields(bindingFlags); } public override FieldInfo GetField(String name, BindingFlags bindingAttr) { if (name == null) throw new ArgumentNullException("name"); if (RuntimeType == null) return null; return RuntimeType.GetField(name, bindingAttr); } public override MethodInfo[] GetMethods(BindingFlags bindingFlags) { if (RuntimeType == null) return new MethodInfo[0]; return RuntimeType.GetMethods(bindingFlags); } public override String ScopeName { [System.Security.SecuritySafeCritical] // auto-generated get { string scopeName = null; GetScopeName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref scopeName)); return scopeName; } } public override String Name { [System.Security.SecuritySafeCritical] // auto-generated get { String s = GetFullyQualifiedName(); #if !FEATURE_PAL int i = s.LastIndexOf('\\'); #else int i = s.LastIndexOf(System.IO.Path.DirectorySeparatorChar); #endif if (i == -1) return s; return new String(s.ToCharArray(), i + 1, s.Length - i - 1); } } public override Assembly Assembly { [Pure] get { return GetRuntimeAssembly(); } } internal RuntimeAssembly GetRuntimeAssembly() { return m_runtimeAssembly; } internal override ModuleHandle GetModuleHandle() { return new ModuleHandle(this); } internal RuntimeModule GetNativeHandle() { return this; } #if FEATURE_X509 && FEATURE_CAS_POLICY [System.Security.SecuritySafeCritical] // auto-generated public override System.Security.Cryptography.X509Certificates.X509Certificate GetSignerCertificate() { byte[] data = null; GetSignerCertificate(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref data)); return (data != null) ? new System.Security.Cryptography.X509Certificates.X509Certificate(data) : null; } #endif // FEATURE_X509 && FEATURE_CAS_POLICY #endregion } }
/* * Copyright (c) 2006, Clutch, Inc. * Original Author: Jeff Cesnik * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Net; using System.Net.Sockets; using System.Threading; using log4net; using OpenSim.Framework; using OpenSim.Framework.Monitoring; namespace OpenMetaverse { /// <summary> /// Base UDP server /// </summary> public abstract class OpenSimUDPBase { private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// This method is called when an incoming packet is received /// </summary> /// <param name="buffer">Incoming packet buffer</param> public abstract void PacketReceived(UDPPacketBuffer buffer); /// <summary>UDP port to bind to in server mode</summary> protected int m_udpPort; /// <summary>Local IP address to bind to in server mode</summary> protected IPAddress m_localBindAddress; /// <summary>UDP socket, used in either client or server mode</summary> private Socket m_udpSocket; /// <summary>Flag to process packets asynchronously or synchronously</summary> private bool m_asyncPacketHandling; /// <summary> /// Are we to use object pool(s) to reduce memory churn when receiving data? /// </summary> public bool UsePools { get; protected set; } /// <summary> /// Pool to use for handling data. May be null if UsePools = false; /// </summary> protected OpenSim.Framework.Pool<UDPPacketBuffer> Pool { get; private set; } /// <summary>Returns true if the server is currently listening for inbound packets, otherwise false</summary> public bool IsRunningInbound { get; private set; } /// <summary>Returns true if the server is currently sending outbound packets, otherwise false</summary> /// <remarks>If IsRunningOut = false, then any request to send a packet is simply dropped.</remarks> public bool IsRunningOutbound { get; private set; } /// <summary> /// Number of UDP receives. /// </summary> public int UdpReceives { get; private set; } /// <summary> /// Number of UDP sends /// </summary> public int UdpSends { get; private set; } /// <summary> /// Number of receives over which to establish a receive time average. /// </summary> private readonly static int s_receiveTimeSamples = 500; /// <summary> /// Current number of samples taken to establish a receive time average. /// </summary> private int m_currentReceiveTimeSamples; /// <summary> /// Cumulative receive time for the sample so far. /// </summary> private int m_receiveTicksInCurrentSamplePeriod; /// <summary> /// The average time taken for each require receive in the last sample. /// </summary> public float AverageReceiveTicksForLastSamplePeriod { get; private set; } public int Port { get { return m_udpPort; } } #region PacketDropDebugging /// <summary> /// For debugging purposes only... random number generator for dropping /// outbound packets. /// </summary> private Random m_dropRandomGenerator = new Random(); /// <summary> /// For debugging purposes only... parameters for a simplified /// model of packet loss with bursts, overall drop rate should /// be roughly 1 - m_dropLengthProbability / (m_dropProbabiliy + m_dropLengthProbability) /// which is about 1% for parameters 0.0015 and 0.15 /// </summary> private double m_dropProbability = 0.0030; private double m_dropLengthProbability = 0.15; private bool m_dropState = false; /// <summary> /// For debugging purposes only... parameters to control the time /// duration over which packet loss bursts can occur, if no packets /// have been sent for m_dropResetTicks milliseconds, then reset the /// state of the packet dropper to its default. /// </summary> private int m_dropLastTick = 0; private int m_dropResetTicks = 500; /// <summary> /// Debugging code used to simulate dropped packets with bursts /// </summary> private bool DropOutgoingPacket() { double rnum = m_dropRandomGenerator.NextDouble(); // if the connection has been idle for awhile (more than m_dropResetTicks) then // reset the state to the default state, don't continue a burst int curtick = Util.EnvironmentTickCount(); if (Util.EnvironmentTickCountSubtract(curtick, m_dropLastTick) > m_dropResetTicks) m_dropState = false; m_dropLastTick = curtick; // if we are dropping packets, then the probability of dropping // this packet is the probability that we stay in the burst if (m_dropState) { m_dropState = (rnum < (1.0 - m_dropLengthProbability)) ? true : false; } else { m_dropState = (rnum < m_dropProbability) ? true : false; } return m_dropState; } #endregion PacketDropDebugging /// <summary> /// Default constructor /// </summary> /// <param name="bindAddress">Local IP address to bind the server to</param> /// <param name="port">Port to listening for incoming UDP packets on</param> /// /// <param name="usePool">Are we to use an object pool to get objects for handing inbound data?</param> public OpenSimUDPBase(IPAddress bindAddress, int port) { m_localBindAddress = bindAddress; m_udpPort = port; // for debugging purposes only, initializes the random number generator // used for simulating packet loss // m_dropRandomGenerator = new Random(); } ~OpenSimUDPBase() { if(m_udpSocket !=null) try { m_udpSocket.Close(); } catch { } } /// <summary> /// Start inbound UDP packet handling. /// </summary> /// <param name="recvBufferSize">The size of the receive buffer for /// the UDP socket. This value is passed up to the operating system /// and used in the system networking stack. Use zero to leave this /// value as the default</param> /// <param name="asyncPacketHandling">Set this to true to start /// receiving more packets while current packet handler callbacks are /// still running. Setting this to false will complete each packet /// callback before the next packet is processed</param> /// <remarks>This method will attempt to set the SIO_UDP_CONNRESET flag /// on the socket to get newer versions of Windows to behave in a sane /// manner (not throwing an exception when the remote side resets the /// connection). This call is ignored on Mono where the flag is not /// necessary</remarks> public virtual void StartInbound(int recvBufferSize, bool asyncPacketHandling) { m_asyncPacketHandling = asyncPacketHandling; if (!IsRunningInbound) { m_log.DebugFormat("[UDPBASE]: Starting inbound UDP loop"); const int SIO_UDP_CONNRESET = -1744830452; IPEndPoint ipep = new IPEndPoint(m_localBindAddress, m_udpPort); m_udpSocket = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); try { if (m_udpSocket.Ttl < 128) { m_udpSocket.Ttl = 128; } } catch (SocketException) { m_log.Debug("[UDPBASE]: Failed to increase default TTL"); } try { // This udp socket flag is not supported under mono, // so we'll catch the exception and continue m_udpSocket.IOControl(SIO_UDP_CONNRESET, new byte[] { 0 }, null); m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag set"); } catch (SocketException) { m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag not supported on this platform, ignoring"); } // On at least Mono 3.2.8, multiple UDP sockets can bind to the same port by default. At the moment // we never want two regions to listen on the same port as they cannot demultiplex each other's messages, // leading to a confusing bug. // By default, Windows does not allow two sockets to bind to the same port. // // Unfortunately, this also causes a crashed sim to leave the socket in a state // where it appears to be in use but is really just hung from the old process // crashing rather than closing it. While this protects agains misconfiguration, // allowing crashed sims to be started up again right away, rather than having to // wait 2 minutes for the socket to clear is more valuable. Commented 12/13/2016 // m_udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, false); if (recvBufferSize != 0) m_udpSocket.ReceiveBufferSize = recvBufferSize; m_udpSocket.Bind(ipep); if (m_udpPort == 0) m_udpPort = ((IPEndPoint)m_udpSocket.LocalEndPoint).Port; IsRunningInbound = true; // kick off an async receive. The Start() method will return, the // actual receives will occur asynchronously and will be caught in // AsyncEndRecieve(). AsyncBeginReceive(); } } /// <summary> /// Start outbound UDP packet handling. /// </summary> public virtual void StartOutbound() { m_log.DebugFormat("[UDPBASE]: Starting outbound UDP loop"); IsRunningOutbound = true; } public virtual void StopInbound() { if (IsRunningInbound) { m_log.DebugFormat("[UDPBASE]: Stopping inbound UDP loop"); IsRunningInbound = false; m_udpSocket.Close(); } } public virtual void StopOutbound() { m_log.DebugFormat("[UDPBASE]: Stopping outbound UDP loop"); IsRunningOutbound = false; } public virtual bool EnablePools() { if (!UsePools) { Pool = new Pool<UDPPacketBuffer>(() => new UDPPacketBuffer(), 500); UsePools = true; return true; } return false; } public virtual bool DisablePools() { if (UsePools) { UsePools = false; // We won't null out the pool to avoid a race condition with code that may be in the middle of using it. return true; } return false; } private void AsyncBeginReceive() { UDPPacketBuffer buf; // FIXME: Disabled for now as this causes issues with reused packet objects interfering with each other // on Windows with m_asyncPacketHandling = true, though this has not been seen on Linux. // Possibly some unexpected issue with fetching UDP data concurrently with multiple threads. Requires more investigation. // if (UsePools) // buf = Pool.GetObject(); // else buf = new UDPPacketBuffer(); if (IsRunningInbound) { try { // kick off an async read m_udpSocket.BeginReceiveFrom( //wrappedBuffer.Instance.Data, buf.Data, 0, UDPPacketBuffer.BUFFER_SIZE, SocketFlags.None, ref buf.RemoteEndPoint, AsyncEndReceive, //wrappedBuffer); buf); } catch (SocketException e) { if (e.SocketErrorCode == SocketError.ConnectionReset) { m_log.Warn("[UDPBASE]: SIO_UDP_CONNRESET was ignored, attempting to salvage the UDP listener on port " + m_udpPort); bool salvaged = false; while (!salvaged) { try { m_udpSocket.BeginReceiveFrom( //wrappedBuffer.Instance.Data, buf.Data, 0, UDPPacketBuffer.BUFFER_SIZE, SocketFlags.None, ref buf.RemoteEndPoint, AsyncEndReceive, //wrappedBuffer); buf); salvaged = true; } catch (SocketException) { } catch (ObjectDisposedException) { return; } } m_log.Warn("[UDPBASE]: Salvaged the UDP listener on port " + m_udpPort); } } catch (ObjectDisposedException e) { m_log.Error( string.Format("[UDPBASE]: Error processing UDP begin receive {0}. Exception ", UdpReceives), e); } catch (Exception e) { m_log.Error( string.Format("[UDPBASE]: Error processing UDP begin receive {0}. Exception ", UdpReceives), e); } } } private void AsyncEndReceive(IAsyncResult iar) { // Asynchronous receive operations will complete here through the call // to AsyncBeginReceive if (IsRunningInbound) { UdpReceives++; // Asynchronous mode will start another receive before the // callback for this packet is even fired. Very parallel :-) if (m_asyncPacketHandling) AsyncBeginReceive(); try { // get the buffer that was created in AsyncBeginReceive // this is the received data UDPPacketBuffer buffer = (UDPPacketBuffer)iar.AsyncState; int startTick = Util.EnvironmentTickCount(); // get the length of data actually read from the socket, store it with the // buffer buffer.DataLength = m_udpSocket.EndReceiveFrom(iar, ref buffer.RemoteEndPoint); // call the abstract method PacketReceived(), passing the buffer that // has just been filled from the socket read. PacketReceived(buffer); // If more than one thread can be calling AsyncEndReceive() at once (e.g. if m_asyncPacketHandler) // then a particular stat may be inaccurate due to a race condition. We won't worry about this // since this should be rare and won't cause a runtime problem. if (m_currentReceiveTimeSamples >= s_receiveTimeSamples) { AverageReceiveTicksForLastSamplePeriod = (float)m_receiveTicksInCurrentSamplePeriod / s_receiveTimeSamples; m_receiveTicksInCurrentSamplePeriod = 0; m_currentReceiveTimeSamples = 0; } else { m_receiveTicksInCurrentSamplePeriod += Util.EnvironmentTickCountSubtract(startTick); m_currentReceiveTimeSamples++; } } catch (SocketException se) { m_log.Error( string.Format( "[UDPBASE]: Error processing UDP end receive {0}, socket error code {1}. Exception ", UdpReceives, se.ErrorCode), se); } catch (ObjectDisposedException e) { m_log.Error( string.Format("[UDPBASE]: Error processing UDP end receive {0}. Exception ", UdpReceives), e); } catch (Exception e) { m_log.Error( string.Format("[UDPBASE]: Error processing UDP end receive {0}. Exception ", UdpReceives), e); } finally { // if (UsePools) // Pool.ReturnObject(buffer); // Synchronous mode waits until the packet callback completes // before starting the receive to fetch another packet if (!m_asyncPacketHandling) AsyncBeginReceive(); } } } public void AsyncBeginSend(UDPPacketBuffer buf) { // if (IsRunningOutbound) // { // This is strictly for debugging purposes to simulate dropped // packets when testing throttles & retransmission code // if (DropOutgoingPacket()) // return; try { m_udpSocket.BeginSendTo( buf.Data, 0, buf.DataLength, SocketFlags.None, buf.RemoteEndPoint, AsyncEndSend, buf); } catch (SocketException) { } catch (ObjectDisposedException) { } // } } void AsyncEndSend(IAsyncResult result) { try { // UDPPacketBuffer buf = (UDPPacketBuffer)result.AsyncState; m_udpSocket.EndSendTo(result); UdpSends++; } catch (SocketException) { } catch (ObjectDisposedException) { } } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the codepipeline-2015-07-09.normal.json service model. */ using System; using Amazon.Runtime; namespace Amazon.CodePipeline { /// <summary> /// Constants used for properties of type ActionCategory. /// </summary> public class ActionCategory : ConstantClass { /// <summary> /// Constant Build for ActionCategory /// </summary> public static readonly ActionCategory Build = new ActionCategory("Build"); /// <summary> /// Constant Deploy for ActionCategory /// </summary> public static readonly ActionCategory Deploy = new ActionCategory("Deploy"); /// <summary> /// Constant Invoke for ActionCategory /// </summary> public static readonly ActionCategory Invoke = new ActionCategory("Invoke"); /// <summary> /// Constant Source for ActionCategory /// </summary> public static readonly ActionCategory Source = new ActionCategory("Source"); /// <summary> /// Constant Test for ActionCategory /// </summary> public static readonly ActionCategory Test = new ActionCategory("Test"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public ActionCategory(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static ActionCategory FindValue(string value) { return FindValue<ActionCategory>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator ActionCategory(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type ActionConfigurationPropertyType. /// </summary> public class ActionConfigurationPropertyType : ConstantClass { /// <summary> /// Constant Boolean for ActionConfigurationPropertyType /// </summary> public static readonly ActionConfigurationPropertyType Boolean = new ActionConfigurationPropertyType("Boolean"); /// <summary> /// Constant Number for ActionConfigurationPropertyType /// </summary> public static readonly ActionConfigurationPropertyType Number = new ActionConfigurationPropertyType("Number"); /// <summary> /// Constant String for ActionConfigurationPropertyType /// </summary> public static readonly ActionConfigurationPropertyType String = new ActionConfigurationPropertyType("String"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public ActionConfigurationPropertyType(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static ActionConfigurationPropertyType FindValue(string value) { return FindValue<ActionConfigurationPropertyType>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator ActionConfigurationPropertyType(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type ActionExecutionStatus. /// </summary> public class ActionExecutionStatus : ConstantClass { /// <summary> /// Constant Failed for ActionExecutionStatus /// </summary> public static readonly ActionExecutionStatus Failed = new ActionExecutionStatus("Failed"); /// <summary> /// Constant InProgress for ActionExecutionStatus /// </summary> public static readonly ActionExecutionStatus InProgress = new ActionExecutionStatus("InProgress"); /// <summary> /// Constant Succeeded for ActionExecutionStatus /// </summary> public static readonly ActionExecutionStatus Succeeded = new ActionExecutionStatus("Succeeded"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public ActionExecutionStatus(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static ActionExecutionStatus FindValue(string value) { return FindValue<ActionExecutionStatus>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator ActionExecutionStatus(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type ActionOwner. /// </summary> public class ActionOwner : ConstantClass { /// <summary> /// Constant AWS for ActionOwner /// </summary> public static readonly ActionOwner AWS = new ActionOwner("AWS"); /// <summary> /// Constant Custom for ActionOwner /// </summary> public static readonly ActionOwner Custom = new ActionOwner("Custom"); /// <summary> /// Constant ThirdParty for ActionOwner /// </summary> public static readonly ActionOwner ThirdParty = new ActionOwner("ThirdParty"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public ActionOwner(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static ActionOwner FindValue(string value) { return FindValue<ActionOwner>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator ActionOwner(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type ArtifactLocationType. /// </summary> public class ArtifactLocationType : ConstantClass { /// <summary> /// Constant S3 for ArtifactLocationType /// </summary> public static readonly ArtifactLocationType S3 = new ArtifactLocationType("S3"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public ArtifactLocationType(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static ArtifactLocationType FindValue(string value) { return FindValue<ArtifactLocationType>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator ArtifactLocationType(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type ArtifactStoreType. /// </summary> public class ArtifactStoreType : ConstantClass { /// <summary> /// Constant S3 for ArtifactStoreType /// </summary> public static readonly ArtifactStoreType S3 = new ArtifactStoreType("S3"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public ArtifactStoreType(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static ArtifactStoreType FindValue(string value) { return FindValue<ArtifactStoreType>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator ArtifactStoreType(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type BlockerType. /// </summary> public class BlockerType : ConstantClass { /// <summary> /// Constant Schedule for BlockerType /// </summary> public static readonly BlockerType Schedule = new BlockerType("Schedule"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public BlockerType(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static BlockerType FindValue(string value) { return FindValue<BlockerType>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator BlockerType(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type EncryptionKeyType. /// </summary> public class EncryptionKeyType : ConstantClass { /// <summary> /// Constant KMS for EncryptionKeyType /// </summary> public static readonly EncryptionKeyType KMS = new EncryptionKeyType("KMS"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public EncryptionKeyType(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static EncryptionKeyType FindValue(string value) { return FindValue<EncryptionKeyType>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator EncryptionKeyType(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type FailureType. /// </summary> public class FailureType : ConstantClass { /// <summary> /// Constant ConfigurationError for FailureType /// </summary> public static readonly FailureType ConfigurationError = new FailureType("ConfigurationError"); /// <summary> /// Constant JobFailed for FailureType /// </summary> public static readonly FailureType JobFailed = new FailureType("JobFailed"); /// <summary> /// Constant PermissionError for FailureType /// </summary> public static readonly FailureType PermissionError = new FailureType("PermissionError"); /// <summary> /// Constant RevisionOutOfSync for FailureType /// </summary> public static readonly FailureType RevisionOutOfSync = new FailureType("RevisionOutOfSync"); /// <summary> /// Constant RevisionUnavailable for FailureType /// </summary> public static readonly FailureType RevisionUnavailable = new FailureType("RevisionUnavailable"); /// <summary> /// Constant SystemUnavailable for FailureType /// </summary> public static readonly FailureType SystemUnavailable = new FailureType("SystemUnavailable"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public FailureType(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static FailureType FindValue(string value) { return FindValue<FailureType>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator FailureType(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type JobStatus. /// </summary> public class JobStatus : ConstantClass { /// <summary> /// Constant Created for JobStatus /// </summary> public static readonly JobStatus Created = new JobStatus("Created"); /// <summary> /// Constant Dispatched for JobStatus /// </summary> public static readonly JobStatus Dispatched = new JobStatus("Dispatched"); /// <summary> /// Constant Failed for JobStatus /// </summary> public static readonly JobStatus Failed = new JobStatus("Failed"); /// <summary> /// Constant InProgress for JobStatus /// </summary> public static readonly JobStatus InProgress = new JobStatus("InProgress"); /// <summary> /// Constant Queued for JobStatus /// </summary> public static readonly JobStatus Queued = new JobStatus("Queued"); /// <summary> /// Constant Succeeded for JobStatus /// </summary> public static readonly JobStatus Succeeded = new JobStatus("Succeeded"); /// <summary> /// Constant TimedOut for JobStatus /// </summary> public static readonly JobStatus TimedOut = new JobStatus("TimedOut"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public JobStatus(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static JobStatus FindValue(string value) { return FindValue<JobStatus>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator JobStatus(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type StageTransitionType. /// </summary> public class StageTransitionType : ConstantClass { /// <summary> /// Constant Inbound for StageTransitionType /// </summary> public static readonly StageTransitionType Inbound = new StageTransitionType("Inbound"); /// <summary> /// Constant Outbound for StageTransitionType /// </summary> public static readonly StageTransitionType Outbound = new StageTransitionType("Outbound"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public StageTransitionType(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static StageTransitionType FindValue(string value) { return FindValue<StageTransitionType>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator StageTransitionType(string value) { return FindValue(value); } } }
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; using NUnit.Framework; using NServiceKit.Common.Reflection; using NServiceKit.Common.Tests.Models; namespace NServiceKit.Common.Tests.Perf { /// <summary>A property accessor performance.</summary> [Ignore("Benchmark for comparing property access")] [TestFixture] public class PropertyAccessorPerf : PerfTestBase { /// <summary>Initializes a new instance of the NServiceKit.Common.Tests.Perf.PropertyAccessorPerf class.</summary> public PropertyAccessorPerf() { this.MultipleIterations = new List<int> { 1000000 }; } /// <summary>A test acessor.</summary> /// <typeparam name="TEntity">Type of the entity.</typeparam> public static class TestAcessor<TEntity> { /// <summary>Typed get property function.</summary> /// /// <typeparam name="TId">Type of the identifier.</typeparam> /// <param name="pi">The pi.</param> /// /// <returns>A Func&lt;TEntity,TId&gt;</returns> public static Func<TEntity, TId> TypedGetPropertyFn<TId>(PropertyInfo pi) { var mi = pi.GetGetMethod(); return (Func<TEntity, TId>)Delegate.CreateDelegate(typeof(Func<TEntity, TId>), mi); } /// <summary> /// Required to cast the return ValueType to an object for caching /// </summary> public static Func<TEntity, object> ValueUnTypedGetPropertyFn<TId>(PropertyInfo pi) { var typedPropertyFn = TypedGetPropertyFn<TId>(pi); return x => typedPropertyFn(x); } /// <summary>Value un typed get property type function reflection.</summary> /// /// <param name="pi">The pi.</param> /// /// <returns>A Func&lt;TEntity,object&gt;</returns> public static Func<TEntity, object> ValueUnTypedGetPropertyTypeFn_Reflection(PropertyInfo pi) { var mi = typeof(StaticAccessors<TEntity>).GetMethod("TypedGetPropertyFn"); var genericMi = mi.MakeGenericMethod(pi.PropertyType); var typedGetPropertyFn = (Delegate)genericMi.Invoke(null, new[] { pi }); return x => typedGetPropertyFn.Method.Invoke(x, new object[] { }); } /// <summary>Value un typed get property type function expression.</summary> /// /// <param name="pi">The pi.</param> /// /// <returns>A Func&lt;TEntity,object&gt;</returns> public static Func<TEntity, object> ValueUnTypedGetPropertyTypeFn_Expr(PropertyInfo pi) { var mi = typeof(StaticAccessors<TEntity>).GetMethod("TypedGetPropertyFn"); var genericMi = mi.MakeGenericMethod(pi.PropertyType); var typedGetPropertyFn = (Delegate)genericMi.Invoke(null, new[] { pi }); var typedMi = typedGetPropertyFn.Method; var obj = Expression.Parameter(typeof(object), "oFunc"); var expr = Expression.Lambda<Func<TEntity, object>>( Expression.Convert( Expression.Call( Expression.Convert(obj, typedMi.DeclaringType), typedMi ), typeof(object) ), obj ); return expr.Compile(); } /// <summary> /// Func to set the Strongly-typed field /// </summary> public static Action<TEntity, TId> TypedSetPropertyFn<TId>(PropertyInfo pi) { var mi = pi.GetSetMethod(); return (Action<TEntity, TId>)Delegate.CreateDelegate(typeof(Action<TEntity, TId>), mi); } /// <summary> /// Required to cast the ValueType to an object for caching /// </summary> public static Action<TEntity, object> ValueUnTypedSetPropertyFn<TId>(PropertyInfo pi) { var typedPropertyFn = TypedSetPropertyFn<TId>(pi); return (x, y) => typedPropertyFn(x, (TId)y); } /// <summary>Value un typed set property type function reflection.</summary> /// /// <param name="pi">The pi.</param> /// /// <returns>An Action&lt;TEntity,object&gt;</returns> public static Action<TEntity, object> ValueUnTypedSetPropertyTypeFn_Reflection(PropertyInfo pi) { var mi = typeof (StaticAccessors<TEntity>).GetMethod("TypedSetPropertyFn"); var genericMi = mi.MakeGenericMethod(pi.PropertyType); var typedSetPropertyFn = (Delegate) genericMi.Invoke(null, new[] {pi}); return (x, y) => typedSetPropertyFn.Method.Invoke(x, new[] { y }); } /// <summary>Value un typed set property type function expression.</summary> /// /// <param name="pi">The pi.</param> /// /// <returns>An Action&lt;TEntity,object&gt;</returns> public static Action<TEntity, object> ValueUnTypedSetPropertyTypeFn_Expr(PropertyInfo pi) { var mi = typeof(StaticAccessors<TEntity>).GetMethod("TypedSetPropertyFn"); var genericMi = mi.MakeGenericMethod(pi.PropertyType); var typedSetPropertyFn = (Delegate)genericMi.Invoke(null, new[] { pi }); var typedMi = typedSetPropertyFn.Method; var paramFunc = Expression.Parameter(typeof(object), "oFunc"); var paramValue = Expression.Parameter(typeof(object), "oValue"); var expr = Expression.Lambda<Action<TEntity, object>>( Expression.Call( Expression.Convert(paramFunc, typedMi.DeclaringType), typedMi, Expression.Convert(paramValue, pi.PropertyType) ), paramFunc, paramValue ); return expr.Compile(); } } private void CompareGet<T>(Func<T, object> reflection, Func<T, object> expr) where T : new() { var obj = new T(); CompareMultipleRuns( "GET Reflection", () => reflection(obj), "GET Expression", () => expr(obj) ); } private void CompareSet<T, TArg>( Action<T, object> reflection, Action<T, object> expr, TArg arg) where T : new() { var obj = new T(); CompareMultipleRuns( "SET Reflection", () => reflection(obj, arg), "SET Expression", () => expr(obj, arg) ); } /// <summary>Compare get int.</summary> [Test] public void Compare_get_int() { var fieldPi = typeof(ModelWithIdAndName).GetProperty("Id"); CompareGet ( TestAcessor<ModelWithIdAndName>.ValueUnTypedGetPropertyTypeFn_Reflection(fieldPi), TestAcessor<ModelWithIdAndName>.ValueUnTypedGetPropertyTypeFn_Expr(fieldPi) ); CompareSet ( TestAcessor<ModelWithIdAndName>.ValueUnTypedSetPropertyTypeFn_Reflection(fieldPi), TestAcessor<ModelWithIdAndName>.ValueUnTypedSetPropertyTypeFn_Expr(fieldPi), 1 ); } /// <summary>Compare get string.</summary> [Test] public void Compare_get_string() { var fieldPi = typeof(ModelWithIdAndName).GetProperty("Name"); CompareGet ( TestAcessor<ModelWithIdAndName>.ValueUnTypedGetPropertyTypeFn_Reflection(fieldPi), TestAcessor<ModelWithIdAndName>.ValueUnTypedGetPropertyTypeFn_Expr(fieldPi) ); CompareSet ( TestAcessor<ModelWithIdAndName>.ValueUnTypedSetPropertyTypeFn_Reflection(fieldPi), TestAcessor<ModelWithIdAndName>.ValueUnTypedSetPropertyTypeFn_Expr(fieldPi), "A" ); } } }
/* * 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 OpenSim 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.IO; using System.Reflection; using System.Threading; using log4net.Config; using NUnit.Framework; using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications.Cache; using OpenSim.Framework.Serialization; using OpenSim.Region.CoreModules.World.Serialiser; using OpenSim.Region.CoreModules.World.Terrain; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Serialization; using OpenSim.Tests.Common; using OpenSim.Tests.Common.Setup; namespace OpenSim.Region.CoreModules.World.Archiver.Tests { [TestFixture] public class ArchiverTests { private Guid m_lastRequestId; private string m_lastErrorMessage; private void LoadCompleted(Guid requestId, string errorMessage) { lock (this) { m_lastRequestId = requestId; m_lastErrorMessage = errorMessage; Console.WriteLine("About to pulse ArchiverTests on LoadCompleted"); Monitor.PulseAll(this); } } private void SaveCompleted(Guid requestId, string errorMessage) { lock (this) { m_lastRequestId = requestId; m_lastErrorMessage = errorMessage; Console.WriteLine("About to pulse ArchiverTests on SaveCompleted"); Monitor.PulseAll(this); } } /// <summary> /// Test saving a V0.2 OpenSim Region Archive. /// </summary> [Test] public void TestSaveOarV0p2() { TestHelper.InMethod(); //log4net.Config.XmlConfigurator.Configure(); ArchiverModule archiverModule = new ArchiverModule(); SerialiserModule serialiserModule = new SerialiserModule(); TerrainModule terrainModule = new TerrainModule(); Scene scene = SceneSetupHelpers.SetupScene(false); SceneSetupHelpers.SetupSceneModules(scene, archiverModule, serialiserModule, terrainModule); SceneObjectPart part1; // Create and add prim 1 { string partName = "My Little Pony"; UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000015"); PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere(); Vector3 groupPosition = new Vector3(10, 20, 30); Quaternion rotationOffset = new Quaternion(20, 30, 40, 50); Vector3 offsetPosition = new Vector3(5, 10, 15); part1 = new SceneObjectPart( ownerId, shape, groupPosition, rotationOffset, offsetPosition); part1.Name = partName; scene.AddNewSceneObject(new SceneObjectGroup(part1), false); } SceneObjectPart part2; // Create and add prim 2 { string partName = "Action Man"; UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000016"); PrimitiveBaseShape shape = PrimitiveBaseShape.CreateCylinder(); Vector3 groupPosition = new Vector3(90, 80, 70); Quaternion rotationOffset = new Quaternion(60, 70, 80, 90); Vector3 offsetPosition = new Vector3(20, 25, 30); part2 = new SceneObjectPart( ownerId, shape, groupPosition, rotationOffset, offsetPosition); part2.Name = partName; scene.AddNewSceneObject(new SceneObjectGroup(part2), false); } MemoryStream archiveWriteStream = new MemoryStream(); scene.EventManager.OnOarFileSaved += SaveCompleted; Guid requestId = new Guid("00000000-0000-0000-0000-808080808080"); lock (this) { archiverModule.ArchiveRegion(archiveWriteStream, requestId); AssetServerBase assetServer = (AssetServerBase)scene.CommsManager.AssetCache.AssetServer; while (assetServer.HasWaitingRequests()) assetServer.ProcessNextRequest(); Monitor.Wait(this, 60000); } Assert.That(m_lastRequestId, Is.EqualTo(requestId)); byte[] archive = archiveWriteStream.ToArray(); MemoryStream archiveReadStream = new MemoryStream(archive); TarArchiveReader tar = new TarArchiveReader(archiveReadStream); bool gotControlFile = false; bool gotObject1File = false; bool gotObject2File = false; string expectedObject1FileName = string.Format( "{0}_{1:000}-{2:000}-{3:000}__{4}.xml", part1.Name, Math.Round(part1.GroupPosition.X), Math.Round(part1.GroupPosition.Y), Math.Round(part1.GroupPosition.Z), part1.UUID); string expectedObject2FileName = string.Format( "{0}_{1:000}-{2:000}-{3:000}__{4}.xml", part2.Name, Math.Round(part2.GroupPosition.X), Math.Round(part2.GroupPosition.Y), Math.Round(part2.GroupPosition.Z), part2.UUID); string filePath; TarArchiveReader.TarEntryType tarEntryType; while (tar.ReadEntry(out filePath, out tarEntryType) != null) { if (ArchiveConstants.CONTROL_FILE_PATH == filePath) { gotControlFile = true; } else if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH)) { string fileName = filePath.Remove(0, ArchiveConstants.OBJECTS_PATH.Length); if (fileName.StartsWith(part1.Name)) { Assert.That(fileName, Is.EqualTo(expectedObject1FileName)); gotObject1File = true; } else if (fileName.StartsWith(part2.Name)) { Assert.That(fileName, Is.EqualTo(expectedObject2FileName)); gotObject2File = true; } } } Assert.That(gotControlFile, Is.True, "No control file in archive"); Assert.That(gotObject1File, Is.True, "No object1 file in archive"); Assert.That(gotObject2File, Is.True, "No object2 file in archive"); // TODO: Test presence of more files and contents of files. // Temporary Console.WriteLine("Successfully completed {0}", MethodBase.GetCurrentMethod()); } /// <summary> /// Test loading a V0.2 OpenSim Region Archive. /// </summary> [Test] public void TestLoadOarV0p2() { TestHelper.InMethod(); //log4net.Config.XmlConfigurator.Configure(); MemoryStream archiveWriteStream = new MemoryStream(); TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream); // Put in a random blank directory to check that this doesn't upset the load process tar.WriteDir("ignoreme"); // Also check that direct entries which will also have a file entry containing that directory doesn't // upset load tar.WriteDir(ArchiveConstants.TERRAINS_PATH); tar.WriteFile(ArchiveConstants.CONTROL_FILE_PATH, ArchiveWriteRequestExecution.Create0p2ControlFile()); string part1Name = "object1"; PrimitiveBaseShape shape = PrimitiveBaseShape.CreateCylinder(); Vector3 groupPosition = new Vector3(90, 80, 70); Quaternion rotationOffset = new Quaternion(60, 70, 80, 90); Vector3 offsetPosition = new Vector3(20, 25, 30); SerialiserModule serialiserModule = new SerialiserModule(); ArchiverModule archiverModule = new ArchiverModule(); Scene scene = SceneSetupHelpers.SetupScene(); SceneSetupHelpers.SetupSceneModules(scene, serialiserModule, archiverModule); SceneObjectPart part1 = new SceneObjectPart( UUID.Zero, shape, groupPosition, rotationOffset, offsetPosition); part1.Name = part1Name; SceneObjectGroup object1 = new SceneObjectGroup(part1); scene.AddNewSceneObject(object1, false); string object1FileName = string.Format( "{0}_{1:000}-{2:000}-{3:000}__{4}.xml", part1Name, Math.Round(groupPosition.X), Math.Round(groupPosition.Y), Math.Round(groupPosition.Z), part1.UUID); tar.WriteFile(ArchiveConstants.OBJECTS_PATH + object1FileName, SceneObjectSerializer.ToXml2Format(object1)); tar.Close(); MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray()); lock (this) { scene.EventManager.OnOarFileLoaded += LoadCompleted; archiverModule.DearchiveRegion(archiveReadStream); } Assert.That(m_lastErrorMessage, Is.Null); SceneObjectPart object1PartLoaded = scene.GetSceneObjectPart(part1Name); Assert.That(object1PartLoaded, Is.Not.Null, "object1 was not loaded"); Assert.That(object1PartLoaded.Name, Is.EqualTo(part1Name), "object1 names not identical"); Assert.That(object1PartLoaded.GroupPosition, Is.EqualTo(groupPosition), "object1 group position not equal"); Assert.That( object1PartLoaded.RotationOffset, Is.EqualTo(rotationOffset), "object1 rotation offset not equal"); Assert.That( object1PartLoaded.OffsetPosition, Is.EqualTo(offsetPosition), "object1 offset position not equal"); // Temporary Console.WriteLine("Successfully completed {0}", MethodBase.GetCurrentMethod()); } /// <summary> /// Test merging a V0.2 OpenSim Region Archive into an existing scene /// </summary> //[Test] public void TestMergeOarV0p2() { TestHelper.InMethod(); //XmlConfigurator.Configure(); MemoryStream archiveWriteStream = new MemoryStream(); string part2Name = "objectMerge"; PrimitiveBaseShape part2Shape = PrimitiveBaseShape.CreateCylinder(); Vector3 part2GroupPosition = new Vector3(90, 80, 70); Quaternion part2RotationOffset = new Quaternion(60, 70, 80, 90); Vector3 part2OffsetPosition = new Vector3(20, 25, 30); // Create an oar file that we can use for the merge { ArchiverModule archiverModule = new ArchiverModule(); SerialiserModule serialiserModule = new SerialiserModule(); TerrainModule terrainModule = new TerrainModule(); Scene scene = SceneSetupHelpers.SetupScene(); SceneSetupHelpers.SetupSceneModules(scene, archiverModule, serialiserModule, terrainModule); SceneObjectPart part2 = new SceneObjectPart( UUID.Zero, part2Shape, part2GroupPosition, part2RotationOffset, part2OffsetPosition); part2.Name = part2Name; SceneObjectGroup object2 = new SceneObjectGroup(part2); scene.AddNewSceneObject(object2, false); // Write out this scene scene.EventManager.OnOarFileSaved += SaveCompleted; lock (this) { archiverModule.ArchiveRegion(archiveWriteStream); Monitor.Wait(this, 60000); } } { ArchiverModule archiverModule = new ArchiverModule(); SerialiserModule serialiserModule = new SerialiserModule(); TerrainModule terrainModule = new TerrainModule(); Scene scene = SceneSetupHelpers.SetupScene(); SceneSetupHelpers.SetupSceneModules(scene, archiverModule, serialiserModule, terrainModule); string part1Name = "objectExisting"; PrimitiveBaseShape part1Shape = PrimitiveBaseShape.CreateCylinder(); Vector3 part1GroupPosition = new Vector3(80, 70, 60); Quaternion part1RotationOffset = new Quaternion(50, 60, 70, 80); Vector3 part1OffsetPosition = new Vector3(15, 20, 25); SceneObjectPart part1 = new SceneObjectPart( UUID.Zero, part1Shape, part1GroupPosition, part1RotationOffset, part1OffsetPosition); part1.Name = part1Name; SceneObjectGroup object1 = new SceneObjectGroup(part1); scene.AddNewSceneObject(object1, false); // Merge in the archive we created earlier byte[] archive = archiveWriteStream.ToArray(); MemoryStream archiveReadStream = new MemoryStream(archive); archiverModule.DearchiveRegion(archiveReadStream, true, Guid.Empty); SceneObjectPart object1Existing = scene.GetSceneObjectPart(part1Name); Assert.That(object1Existing, Is.Not.Null, "object1 was not present after merge"); Assert.That(object1Existing.Name, Is.EqualTo(part1Name), "object1 names not identical after merge"); Assert.That(object1Existing.GroupPosition, Is.EqualTo(part1GroupPosition), "object1 group position not equal after merge"); SceneObjectPart object2PartMerged = scene.GetSceneObjectPart(part2Name); Assert.That(object2PartMerged, Is.Not.Null, "object2 was not present after merge"); Assert.That(object2PartMerged.Name, Is.EqualTo(part2Name), "object2 names not identical after merge"); Assert.That(object2PartMerged.GroupPosition, Is.EqualTo(part2GroupPosition), "object2 group position not equal after merge"); } } } }
#define PROTOTYPE using UnityEngine; using UnityEditor; using System.Collections; using System.Text; using System.Text.RegularExpressions; /** * INSTRUCTIONS * * - Only modify properties in the USER SETTINGS region. * - All content is loaded from external files (pc_AboutEntry_YourProduct. Use the templates! */ /** * Used to pop up the window on import. */ public class pb_AboutWindowSetup : AssetPostprocessor { #region Initialization static void OnPostprocessAllAssets ( string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { string[] entries = System.Array.FindAll(importedAssets, name => name.Contains("pc_AboutEntry") && !name.EndsWith(".meta")); foreach(string str in entries) if( pb_AboutWindow.Init(str, false) ) break; } #endregion } public class pb_AboutWindow : EditorWindow { /** * Modify these constants to customize about screen. */ #region User Settings const string PACKAGE_NAME = "ProBuilder"; /* Path to the root folder */ const string ABOUT_ROOT = "Assets/ProCore/" + PACKAGE_NAME + "/About"; /** * Changelog.txt file should follow this format: * * | -- Product Name 2.1.0 - * | * | # Features * | - All kinds of awesome stuff * | - New flux capacitor design achieves time travel at lower velocities. * | - Dark matter reactor recalibrated. * | * | # Bug Fixes * | - No longer explodes when spacebar is pressed. * | - Fix rolling issue in Rickmeter. * | * | # Changes * | - Changed Blue to Red. * | - Enter key now causes explosions. * * This path is relative to the PRODUCT_ROOT path. * * Note that your changelog may contain multiple entries. Only the top-most * entry will be displayed. */ /** * Advertisement thumb constructor is: * new AdvertisementThumb( PathToAdImage : string, URLToPurchase : string, ProductDescription : string ) * Provide as many or few (or none) as desired. * * Notes - The http:// part is required. Partial URLs do not work on Mac. */ [SerializeField] public static AdvertisementThumb[] advertisements = new AdvertisementThumb[] { new AdvertisementThumb( ABOUT_ROOT + "/Images/ProBuilder_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/probuilder/", "Build and Texture Geometry In-Editor"), new AdvertisementThumb( ABOUT_ROOT + "/Images/ProGrids_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/progrids/", "True Grids and Grid-Snapping"), new AdvertisementThumb( ABOUT_ROOT + "/Images/ProGroups_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/progroups/", "Hide, Freeze, Group, & Organize"), new AdvertisementThumb( ABOUT_ROOT + "/Images/Prototype_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/prototype/", "Design and Build With Zero Lag"), new AdvertisementThumb( ABOUT_ROOT + "/Images/QuickBrush_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/quickbrush/", "Quickly Add Detail Geometry"), new AdvertisementThumb( ABOUT_ROOT + "/Images/QuickDecals_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/quickdecals/", "Add Dirt, Splatters, Posters, etc"), new AdvertisementThumb( ABOUT_ROOT + "/Images/QuickEdit_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/quickedit/", "Edit Imported Meshes!"), }; #endregion /* Recommend you do not modify these. */ #region Private Fields (automatically populated) private string AboutEntryPath = ""; private string ProductName = ""; // private string ProductIdentifer = ""; private string ProductVersion = ""; private string ChangelogPath = ""; private string BannerPath = ABOUT_ROOT + "/Images/Banner.png"; const int AD_HEIGHT = 96; /** * Struct containing data for use in Advertisement shelf. */ [System.Serializable] public struct AdvertisementThumb { public Texture2D image; public string url; public string about; public GUIContent guiContent; public AdvertisementThumb(string imagePath, string url, string about) { guiContent = new GUIContent("", about); this.image = LoadAssetAtPath<Texture2D>(imagePath); guiContent.image = this.image; this.url = url; this.about = about; } } Texture2D banner; // populated by first entry in changelog string changelog = ""; #endregion #region Init /** * Return true if Init took place, false if not. */ public static bool Init (string aboutEntryPath, bool fromMenu) { string identifier, version; if( !GetField(aboutEntryPath, "version: ", out version) || !GetField(aboutEntryPath, "identifier: ", out identifier)) return false; if(fromMenu || EditorPrefs.GetString(identifier) != version) { string tname; pb_AboutWindow win; if(GetField(aboutEntryPath, "name: ", out tname)) win = (pb_AboutWindow)EditorWindow.GetWindow(typeof(pb_AboutWindow), true, tname, true); else win = (pb_AboutWindow)EditorWindow.GetWindow(typeof(pb_AboutWindow)); win.SetAboutEntryPath(aboutEntryPath); win.ShowUtility(); EditorPrefs.SetString(identifier, version); return true; } else { return false; } } public void OnEnable() { banner = LoadAssetAtPath<Texture2D>(BannerPath); // With Unity 4 (on PC) if you have different values for minSize and maxSize, // they do not apply restrictions to window size. #if !UNITY_5 this.minSize = new Vector2(banner.width + 12, banner.height * 7); this.maxSize = new Vector2(banner.width + 12, banner.height * 7); #else this.minSize = new Vector2(banner.width + 12, banner.height * 6); this.maxSize = new Vector2(banner.width + 12, 1440); #endif } public void SetAboutEntryPath(string path) { AboutEntryPath = path; PopulateDataFields(AboutEntryPath); } static T LoadAssetAtPath<T>(string InPath) where T : UnityEngine.Object { return (T) AssetDatabase.LoadAssetAtPath(InPath, typeof(T)); } #endregion #region GUI Color LinkColor = new Color(0f, .682f, .937f, 1f); GUIStyle boldTextStyle, headerTextStyle, linkTextStyle; GUIStyle advertisementStyle; Vector2 scroll = Vector2.zero, adScroll = Vector2.zero; // int mm = 32; void OnGUI() { headerTextStyle = headerTextStyle ?? new GUIStyle( EditorStyles.boldLabel );//GUI.skin.label); headerTextStyle.fontSize = 16; linkTextStyle = linkTextStyle ?? new GUIStyle( GUI.skin.label );//GUI.skin.label); linkTextStyle.normal.textColor = LinkColor; linkTextStyle.alignment = TextAnchor.MiddleLeft; boldTextStyle = boldTextStyle ?? new GUIStyle( GUI.skin.label );//GUI.skin.label); boldTextStyle.fontStyle = FontStyle.Bold; boldTextStyle.alignment = TextAnchor.MiddleLeft; // #if UNITY_4 // richTextLabel.richText = true; // #endif advertisementStyle = advertisementStyle ?? new GUIStyle(GUI.skin.button); advertisementStyle.normal.background = null; if(banner != null) GUILayout.Label(banner); // mm = EditorGUI.IntField(new Rect(Screen.width - 200, 100, 200, 18), "W: ", mm); // grr stupid rich text faiiilluuure { GUILayout.Label("Thank you for purchasing " + ProductName + ". Your support allows us to keep developing this and future tools for everyone.", EditorStyles.wordWrappedLabel); GUILayout.Space(2); GUILayout.Label("Read these quick \"ProTips\" before starting:", headerTextStyle); GUILayout.BeginHorizontal(); GUILayout.Label("1) ", GUILayout.MinWidth(16), GUILayout.MaxWidth(16)); GUILayout.Label("Register", boldTextStyle, GUILayout.MinWidth(58), GUILayout.MaxWidth(58)); GUILayout.Label("for instant email updates, send your invoice # to", GUILayout.MinWidth(284), GUILayout.MaxWidth(284)); if( GUILayout.Button("contact@procore3d.com", linkTextStyle, GUILayout.MinWidth(142), GUILayout.MaxWidth(142)) ) Application.OpenURL("mailto:contact@procore3d.com?subject=Sign me up for the Beta!"); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("2) ", GUILayout.MinWidth(16), GUILayout.MaxWidth(16)); GUILayout.Label("Report bugs", boldTextStyle, GUILayout.MinWidth(82), GUILayout.MaxWidth(82)); GUILayout.Label("to the ProCore Forum at", GUILayout.MinWidth(144), GUILayout.MaxWidth(144)); if( GUILayout.Button("www.procore3d.com/forum", linkTextStyle, GUILayout.MinWidth(162), GUILayout.MaxWidth(162)) ) Application.OpenURL("http://www.procore3d.com/forum"); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("3) ", GUILayout.MinWidth(16), GUILayout.MaxWidth(16)); GUILayout.Label("Customize!", boldTextStyle, GUILayout.MinWidth(74), GUILayout.MaxWidth(74)); GUILayout.Label("Click on \"Edit > Preferences\" then \"" + ProductName + "\"", GUILayout.MinWidth(276), GUILayout.MaxWidth(276)); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("4) ", GUILayout.MinWidth(16), GUILayout.MaxWidth(16)); GUILayout.Label("Documentation", boldTextStyle, GUILayout.MinWidth(102), GUILayout.MaxWidth(102)); GUILayout.Label("Tutorials, & more info:", GUILayout.MinWidth(132), GUILayout.MaxWidth(132)); if( GUILayout.Button("www.procore3d.com/" + ProductName.ToLower(), linkTextStyle, GUILayout.MinWidth(190), GUILayout.MaxWidth(190)) ) Application.OpenURL("http://www.procore3d.com/" + ProductName.ToLower()); GUILayout.EndHorizontal(); GUILayout.Space(4); GUILayout.BeginHorizontal(GUILayout.MaxWidth(50)); GUILayout.Label("Links:", boldTextStyle); linkTextStyle.fontStyle = FontStyle.Italic; linkTextStyle.alignment = TextAnchor.MiddleCenter; if( GUILayout.Button("procore3d.com", linkTextStyle)) Application.OpenURL("http://www.procore3d.com"); if( GUILayout.Button("facebook", linkTextStyle)) Application.OpenURL("http://www.facebook.com/probuilder3d"); if( GUILayout.Button("twitter", linkTextStyle)) Application.OpenURL("http://www.twitter.com/probuilder3d"); linkTextStyle.fontStyle = FontStyle.Normal; GUILayout.EndHorizontal(); GUILayout.Space(4); } HorizontalLine(); // always bold the first line (cause it's the version info stuff) scroll = EditorGUILayout.BeginScrollView(scroll); GUILayout.Label(ProductName + " | version: " + ProductVersion, EditorStyles.boldLabel); GUILayout.Label("\n" + changelog); EditorGUILayout.EndScrollView(); HorizontalLine(); GUILayout.Label("More ProCore Products", EditorStyles.boldLabel); int pad = advertisements.Length * AD_HEIGHT > Screen.width ? 22 : 6; adScroll = EditorGUILayout.BeginScrollView(adScroll, false, false, GUILayout.MinHeight(AD_HEIGHT + pad), GUILayout.MaxHeight(AD_HEIGHT + pad)); GUILayout.BeginHorizontal(); foreach(AdvertisementThumb ad in advertisements) { if(ad.url.ToLower().Contains(ProductName.ToLower())) continue; if(GUILayout.Button(ad.guiContent, advertisementStyle, GUILayout.MinWidth(AD_HEIGHT), GUILayout.MaxWidth(AD_HEIGHT), GUILayout.MinHeight(AD_HEIGHT), GUILayout.MaxHeight(AD_HEIGHT))) { Application.OpenURL(ad.url); } } GUILayout.EndHorizontal(); EditorGUILayout.EndScrollView(); /* shill other products */ } /** * Draw a horizontal line across the screen and update the guilayout. */ void HorizontalLine() { Rect r = GUILayoutUtility.GetLastRect(); Color og = GUI.backgroundColor; GUI.backgroundColor = Color.black; GUI.Box(new Rect(0f, r.y + r.height + 2, Screen.width, 2f), ""); GUI.backgroundColor = og; GUILayout.Space(6); } #endregion #region Data Parsing /* rich text ain't wuurkin' in unity 3.5 */ const string RemoveBraketsRegex = "(\\<.*?\\>)"; /** * Open VersionInfo and Changelog and pull out text to populate vars for OnGUI to display. */ void PopulateDataFields(string entryPath) { /* Get data from VersionInfo.txt */ TextAsset versionInfo = LoadAssetAtPath<TextAsset>( entryPath ); ProductName = ""; // ProductIdentifer = ""; ProductVersion = ""; ChangelogPath = ""; if(versionInfo != null) { string[] txt = versionInfo.text.Split('\n'); foreach(string cheese in txt) { if(cheese.StartsWith("name:")) ProductName = cheese.Replace("name: ", "").Trim(); else if(cheese.StartsWith("version:")) ProductVersion = cheese.Replace("version: ", "").Trim(); else if(cheese.StartsWith("changelog:")) ChangelogPath = cheese.Replace("changelog: ", "").Trim(); } } // notes = notes.Trim(); /* Get first entry in changelog.txt */ TextAsset changelogText = LoadAssetAtPath<TextAsset>( ChangelogPath ); if(changelogText) { string[] split = Regex.Split(changelogText.text, "(?mi)^#\\s", RegexOptions.Multiline); StringBuilder sb = new StringBuilder(); string[] newLineSplit = split[1].Trim().Split('\n'); for(int i = 2; i < newLineSplit.Length; i++) sb.AppendLine(newLineSplit[i]); changelog = sb.ToString(); } } private static bool GetField(string path, string field, out string value) { TextAsset entry = LoadAssetAtPath<TextAsset>(path); value = ""; if(!entry) return false; foreach(string str in entry.text.Split('\n')) { if(str.Contains(field)) { value = str.Replace(field, "").Trim(); return true; } } return false; } #endregion }
// *********************************************************************** // Copyright (c) 2012-2015 Charlie Poole // // 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 NUnit.Compatibility; using NUnit.Framework.Interfaces; namespace NUnit.Framework.Internal { /// <summary> /// The Test abstract class represents a test within the framework. /// </summary> public abstract class Test : ITest, IComparable { #region Fields /// <summary> /// Static value to seed ids. It's started at 1000 so any /// uninitialized ids will stand out. /// </summary> private static int _nextID = 1000; /// <summary> /// The SetUp methods. /// </summary> protected MethodInfo[] setUpMethods; /// <summary> /// The teardown methods /// </summary> protected MethodInfo[] tearDownMethods; /// <summary> /// Used to cache the declaring type for this MethodInfo /// </summary> protected ITypeInfo DeclaringTypeInfo; /// <summary> /// Method property backing field /// </summary> private IMethodInfo _method; #endregion #region Construction /// <summary> /// Constructs a test given its name /// </summary> /// <param name="name">The name of the test</param> protected Test( string name ) { Guard.ArgumentNotNullOrEmpty(name, "name"); Initialize(name); } /// <summary> /// Constructs a test given the path through the /// test hierarchy to its parent and a name. /// </summary> /// <param name="pathName">The parent tests full name</param> /// <param name="name">The name of the test</param> protected Test( string pathName, string name ) { Guard.ArgumentNotNullOrEmpty(pathName, "pathName"); Initialize(name); FullName = pathName + "." + name; } /// <summary> /// TODO: Documentation needed for constructor /// </summary> /// <param name="typeInfo"></param> protected Test(ITypeInfo typeInfo) { Initialize(typeInfo.GetDisplayName()); string nspace = typeInfo.Namespace; if (nspace != null && nspace != "") FullName = nspace + "." + Name; TypeInfo = typeInfo; } /// <summary> /// Construct a test from a MethodInfo /// </summary> /// <param name="method"></param> protected Test(IMethodInfo method) { Initialize(method.Name); Method = method; TypeInfo = method.TypeInfo; FullName = method.TypeInfo.FullName + "." + Name; } private void Initialize(string name) { FullName = Name = name; Id = GetNextId(); Properties = new PropertyBag(); RunState = RunState.Runnable; } private static string GetNextId() { return IdPrefix + unchecked(_nextID++); } #endregion #region ITest Members /// <summary> /// Gets or sets the id of the test /// </summary> /// <value></value> public string Id { get; set; } /// <summary> /// Gets or sets the name of the test /// </summary> public string Name { get; set; } /// <summary> /// Gets or sets the fully qualified name of the test /// </summary> /// <value></value> public string FullName { get; set; } /// <summary> /// Gets the name of the class where this test was declared. /// Returns null if the test is not associated with a class. /// </summary> public string ClassName { get { ITypeInfo typeInfo = TypeInfo; if (Method != null) { if (DeclaringTypeInfo == null) DeclaringTypeInfo = new TypeWrapper(Method.MethodInfo.DeclaringType); typeInfo = DeclaringTypeInfo; } if (typeInfo == null) return null; return typeInfo.IsGenericType ? typeInfo.GetGenericTypeDefinition().FullName : typeInfo.FullName; } } /// <summary> /// Gets the name of the method implementing this test. /// Returns null if the test is not implemented as a method. /// </summary> public virtual string MethodName { get { return null; } } /// <summary> /// Gets the TypeInfo of the fixture used in running this test /// or null if no fixture type is associated with it. /// </summary> public ITypeInfo TypeInfo { get; private set; } /// <summary> /// Gets a MethodInfo for the method implementing this test. /// Returns null if the test is not implemented as a method. /// </summary> public IMethodInfo Method { get { return _method; } set { DeclaringTypeInfo = null; _method = value; } } // public setter needed by NUnitTestCaseBuilder /// <summary> /// Whether or not the test should be run /// </summary> public RunState RunState { get; set; } /// <summary> /// Gets the name used for the top-level element in the /// XML representation of this test /// </summary> public abstract string XmlElementName { get; } /// <summary> /// Gets a string representing the type of test. Used as an attribute /// value in the XML representation of a test and has no other /// function in the framework. /// </summary> public virtual string TestType { get { return this.GetType().Name; } } /// <summary> /// Gets a count of test cases represented by /// or contained under this test. /// </summary> public virtual int TestCaseCount { get { return 1; } } /// <summary> /// Gets the properties for this test /// </summary> public IPropertyBag Properties { get; private set; } /// <summary> /// Returns true if this is a TestSuite /// </summary> public bool IsSuite { get { return this is TestSuite; } } /// <summary> /// Gets a bool indicating whether the current test /// has any descendant tests. /// </summary> public abstract bool HasChildren { get; } /// <summary> /// Gets the parent as a Test object. /// Used by the core to set the parent. /// </summary> public ITest Parent { get; set; } /// <summary> /// Gets this test's child tests /// </summary> /// <value>A list of child tests</value> public abstract System.Collections.Generic.IList<ITest> Tests { get; } /// <summary> /// Gets or sets a fixture object for running this test. /// </summary> public virtual object Fixture { get; set; } #endregion #region Other Public Properties /// <summary> /// Static prefix used for ids in this AppDomain. /// Set by FrameworkController. /// </summary> public static string IdPrefix { get; set; } /// <summary> /// Gets or Sets the Int value representing the seed for the RandomGenerator /// </summary> /// <value></value> public int Seed { get; set; } #endregion #region Internal Properties internal bool RequiresThread { get; set; } internal bool IsAsynchronous { get; set; } #endregion #region Other Public Methods /// <summary> /// Creates a TestResult for this test. /// </summary> /// <returns>A TestResult suitable for this type of test.</returns> public abstract TestResult MakeTestResult(); #if PORTABLE /// <summary> /// Modify a newly constructed test by applying any of NUnit's common /// attributes, based on a supplied ICustomAttributeProvider, which is /// usually the reflection element from which the test was constructed, /// but may not be in some instances. The attributes retrieved are /// saved for use in subsequent operations. /// </summary> /// <param name="provider">An object deriving from MemberInfo</param> public void ApplyAttributesToTest(MemberInfo provider) { foreach (IApplyToTest iApply in provider.GetAttributes<IApplyToTest>(true)) iApply.ApplyToTest(this); } /// <summary> /// Modify a newly constructed test by applying any of NUnit's common /// attributes, based on a supplied ICustomAttributeProvider, which is /// usually the reflection element from which the test was constructed, /// but may not be in some instances. The attributes retrieved are /// saved for use in subsequent operations. /// </summary> /// <param name="provider">An object deriving from MemberInfo</param> public void ApplyAttributesToTest(Assembly provider) { foreach (IApplyToTest iApply in provider.GetAttributes<IApplyToTest>()) iApply.ApplyToTest(this); } #else /// <summary> /// Modify a newly constructed test by applying any of NUnit's common /// attributes, based on a supplied ICustomAttributeProvider, which is /// usually the reflection element from which the test was constructed, /// but may not be in some instances. The attributes retrieved are /// saved for use in subsequent operations. /// </summary> /// <param name="provider">An object implementing ICustomAttributeProvider</param> public void ApplyAttributesToTest(ICustomAttributeProvider provider) { foreach (IApplyToTest iApply in provider.GetCustomAttributes(typeof(IApplyToTest), true)) iApply.ApplyToTest(this); } #endif #endregion #region Protected Methods /// <summary> /// Add standard attributes and members to a test node. /// </summary> /// <param name="thisNode"></param> /// <param name="recursive"></param> protected void PopulateTestNode(TNode thisNode, bool recursive) { thisNode.AddAttribute("id", this.Id.ToString()); thisNode.AddAttribute("name", this.Name); thisNode.AddAttribute("fullname", this.FullName); if (this.MethodName != null) thisNode.AddAttribute("methodname", this.MethodName); if (this.ClassName != null) thisNode.AddAttribute("classname", this.ClassName); thisNode.AddAttribute("runstate", this.RunState.ToString()); if (Properties.Keys.Count > 0) Properties.AddToXml(thisNode, recursive); } #endregion #region IXmlNodeBuilder Members /// <summary> /// Returns the Xml representation of the test /// </summary> /// <param name="recursive">If true, include child tests recursively</param> /// <returns></returns> public TNode ToXml(bool recursive) { return AddToXml(new TNode("dummy"), recursive); } /// <summary> /// Returns an XmlNode representing the current result after /// adding it as a child of the supplied parent node. /// </summary> /// <param name="parentNode">The parent node.</param> /// <param name="recursive">If true, descendant results are included</param> /// <returns></returns> public abstract TNode AddToXml(TNode parentNode, bool recursive); #endregion #region IComparable Members /// <summary> /// Compares this test to another test for sorting purposes /// </summary> /// <param name="obj">The other test</param> /// <returns>Value of -1, 0 or +1 depending on whether the current test is less than, equal to or greater than the other test</returns> public int CompareTo(object obj) { Test other = obj as Test; if (other == null) return -1; return this.FullName.CompareTo(other.FullName); } #endregion } }
#region License /* * All content copyright Marko Lahma, unless otherwise indicated. 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. * */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using Quartz.Util; namespace Quartz.Impl.Calendar { /// <summary> /// This implementation of the Calendar stores a list of holidays (full days /// that are excluded from scheduling). /// </summary> /// <remarks> /// The implementation DOES take the year into consideration, so if you want to /// exclude July 4th for the next 10 years, you need to add 10 entries to the /// exclude list. /// </remarks> /// <author>Sharada Jambula</author> /// <author>Juergen Donnerstag</author> /// <author>Marko Lahma (.NET)</author> [Serializable] public class HolidayCalendar : BaseCalendar { /// <summary> /// Returns a collection of dates representing the excluded /// days. Only the month, day and year of the returned dates are /// significant. /// </summary> public virtual IReadOnlyCollection<DateTime> ExcludedDates { get => new HashSet<DateTime>(dates); internal set => dates = new SortedSet<DateTime>(value); } // A sorted set to store the holidays private SortedSet<DateTime> dates = new SortedSet<DateTime>(); /// <summary> /// Initializes a new instance of the <see cref="HolidayCalendar"/> class. /// </summary> public HolidayCalendar() { } /// <summary> /// Initializes a new instance of the <see cref="HolidayCalendar"/> class. /// </summary> /// <param name="baseCalendar">The base calendar.</param> public HolidayCalendar(ICalendar baseCalendar) { CalendarBase = baseCalendar; } // Make sure that future calendar version changes are done in a DCS-friendly way (with [OnSerializing] and [OnDeserialized] methods). /// <summary> /// Serialization constructor. /// </summary> /// <param name="info"></param> /// <param name="context"></param> protected HolidayCalendar(SerializationInfo info, StreamingContext context) : base(info, context) { int version; try { version = info.GetInt32("version"); } catch { version = 0; } switch (version) { case 0: case 1: throw new NotSupportedException("cannot deserialize old version, use latest Quartz 2.x version to re-serialize all HolidayCalendar instances in database"); case 2: dates = new SortedSet<DateTime>((DateTime[]) info.GetValue("dates", typeof(DateTime[]))!); break; default: throw new NotSupportedException("Unknown serialization version"); } } [System.Security.SecurityCritical] public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("version", 2); info.AddValue("dates", dates.ToArray()); } /// <summary> /// Determine whether the given time (in milliseconds) is 'included' by the /// Calendar. /// <para> /// Note that this Calendar is only has full-day precision. /// </para> /// </summary> public override bool IsTimeIncluded(DateTimeOffset timeStampUtc) { if (!base.IsTimeIncluded(timeStampUtc)) { return false; } //apply the timezone timeStampUtc = TimeZoneUtil.ConvertTime(timeStampUtc, TimeZone); DateTime lookFor = timeStampUtc.Date; return !dates.Contains(lookFor); } /// <summary> /// Determine the next time (in milliseconds) that is 'included' by the /// Calendar after the given time. /// <para> /// Note that this Calendar is only has full-day precision. /// </para> /// </summary> public override DateTimeOffset GetNextIncludedTimeUtc(DateTimeOffset timeUtc) { // Call base calendar implementation first DateTimeOffset baseTime = base.GetNextIncludedTimeUtc(timeUtc); if (timeUtc != DateTimeOffset.MinValue && baseTime > timeUtc) { timeUtc = baseTime; } //apply the timezone timeUtc = TimeZoneUtil.ConvertTime(timeUtc, TimeZone); // Get timestamp for 00:00:00, with the correct timezone offset DateTimeOffset day = new DateTimeOffset(timeUtc.Date, timeUtc.Offset); while (!IsTimeIncluded(day)) { day = day.AddDays(1); } return day; } /// <summary> /// Creates a new object that is a copy of the current instance. /// </summary> /// <returns>A new object that is a copy of this instance.</returns> public override ICalendar Clone() { HolidayCalendar clone = new HolidayCalendar(); CloneFields(clone); clone.dates = new SortedSet<DateTime>(dates); return clone; } /// <summary> /// Add the given Date to the list of excluded days. Only the month, day and /// year of the returned dates are significant. /// </summary> public virtual void AddExcludedDate(DateTime excludedDateUtc) { DateTime date = excludedDateUtc.Date; dates.Add(date); } /// <summary> /// Removes the excluded date. /// </summary> /// <param name="dateToRemoveUtc">The date to remove.</param> public virtual void RemoveExcludedDate(DateTime dateToRemoveUtc) { DateTime date = dateToRemoveUtc.Date; dates.Remove(date); } public override int GetHashCode() { int baseHash = 0; if (CalendarBase != null) { baseHash = CalendarBase.GetHashCode(); } return ExcludedDates.GetHashCode() + 5*baseHash; } public bool Equals(HolidayCalendar obj) { if (obj == null) { return false; } bool baseEqual = CalendarBase == null || CalendarBase.Equals(obj.CalendarBase); return baseEqual && ExcludedDates.SequenceEqual(obj.ExcludedDates); } public override bool Equals(object? obj) { if (!(obj is HolidayCalendar)) { return false; } return Equals((HolidayCalendar) obj); } } }
#if UNITY_EDITOR using UnityEngine; using UnityEditor; using System; using System.IO; using System.Text.RegularExpressions; namespace UMA.AssetBundles { public class UMAAssetBundleManagerSettings : EditorWindow { #region PUBLIC FIELDS public const string DEFAULT_ENCRYPTION_SUFFIX = "encrypted"; #endregion #region PRIVATE FIELDS //AssetBundle settings related string currentEncryptionPassword = ""; string newEncryptionPassword = ""; string currentEncryptionSuffix = ""; string newEncryptionSuffix = ""; bool currentEncodeNamesSetting = false; #if ENABLE_IOS_APP_SLICING bool currentAppSlicingSetting = false; #endif bool newEncodeNamesSetting = false; //server related bool _enableLocalAssetBundleServer; int _port; string _statusMessage; string[] _hosts; string _activeHost; bool portError = false; bool serverException = false; //Testing Build related bool developmentBuild = false; //GUI related Vector2 scrollPos; bool serverRequestLogOpen = true; bool manualEditEncryptionKey = false; bool encryptionSaveButEnabled = false; bool manualEditEncryptionSuffix = false; bool encryptionKeysEnabled = false; #endregion #region PUBLIC PROPERTIES #endregion #region PRIVATE PROPERTIES //server related bool EnableLocalAssetBundleServer { get { return _enableLocalAssetBundleServer; } set { if (_enableLocalAssetBundleServer == value) return; _enableLocalAssetBundleServer = value; EditorPrefs.SetBool(Application.dataPath+"LocalAssetBundleServerEnabled", value); UpdateServer(); } } int Port { get { return _port; } set { if (_port == value) return; _port = value; EditorPrefs.SetInt(Application.dataPath+"LocalAssetBundleServerPort", _port); UpdateServer(); } } string ActiveHost { get { return _activeHost; } set { if (_activeHost == value) return; _activeHost = value; EditorPrefs.SetString(Application.dataPath+"LocalAssetBundleServerURL", _activeHost); } } #endregion #region BASE METHODS [MenuItem("Assets/AssetBundles/UMA Asset Bundle Manager Settings")] [MenuItem("UMA/UMA Asset Bundle Manager Settings")] static void Init() { UMAAssetBundleManagerSettings window = (UMAAssetBundleManagerSettings)EditorWindow.GetWindow<UMAAssetBundleManagerSettings>("UMA AssetBundle Manager"); window.Show(); } void OnFocus() { encryptionKeysEnabled = UMAABMSettings.GetEncryptionEnabled(); currentEncryptionPassword = newEncryptionPassword = UMAABMSettings.GetEncryptionPassword(); currentEncryptionSuffix = newEncryptionSuffix = UMAABMSettings.GetEncryptionSuffix(); if (currentEncryptionSuffix == "") currentEncryptionSuffix = newEncryptionSuffix = DEFAULT_ENCRYPTION_SUFFIX; currentEncodeNamesSetting = newEncodeNamesSetting = UMAABMSettings.GetEncodeNames(); #if ENABLE_IOS_APP_SLICING currentAppSlicingSetting = UMAABMSettings.GetBuildForSlicing(); #endif } void OnEnable() { encryptionKeysEnabled = UMAABMSettings.GetEncryptionEnabled(); currentEncryptionPassword = newEncryptionPassword = UMAABMSettings.GetEncryptionPassword(); currentEncryptionSuffix = newEncryptionSuffix = UMAABMSettings.GetEncryptionSuffix(); if (currentEncryptionSuffix == "") currentEncryptionSuffix = newEncryptionSuffix = DEFAULT_ENCRYPTION_SUFFIX; currentEncodeNamesSetting = newEncodeNamesSetting = UMAABMSettings.GetEncodeNames(); #if ENABLE_IOS_APP_SLICING currentAppSlicingSetting = UMAABMSettings.GetBuildForSlicing(); #endif //localAssetBundleServer status _enableLocalAssetBundleServer = EditorPrefs.GetBool(Application.dataPath+"LocalAssetBundleServerEnabled"); _port = EditorPrefs.GetInt(Application.dataPath + "LocalAssetBundleServerPort", 7888); //When the window is opened we still need to tell the user if the port is available so if (!_enableLocalAssetBundleServer) { UpdateServer(true); ServerStop(); if (serverException) portError = true; } else { UpdateServer(); } } void Start() { ServerStart(); } void OnDisable() { //Makes the Local server stop when the window is closed //also prevents the 'Listener already in use' error when the window is closed and opened ServerStop(); } #endregion #region SERVER RELATED METHODS void ServerStart() { SimpleWebServer.Start(_port); _statusMessage = "Server Running"; UpdateHosts(); if (_activeHost == null) { ActiveHost = _hosts[0]; } SimpleWebServer.ServerURL = ActiveHost; } void ServerStop() { if (SimpleWebServer.Instance != null) { SimpleWebServer.Instance.Stop(); SimpleWebServer.ServerURL = ""; _statusMessage = "Server Stopped"; _hosts = null; } } void UpdateHosts() { var strHostName = System.Net.Dns.GetHostName(); var list = new System.Collections.Generic.List<string>(); try { var ipEntry = System.Net.Dns.GetHostEntry(strHostName); foreach (var addr in ipEntry.AddressList) { if (addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { list.Add(string.Format("http://{0}:{1}/", addr, Port)); } } } catch(Exception ex) { Debug.Log(ex.Message); strHostName = "localhost"; } if (list.Count == 0) { list.Add(string.Format("http://localhost:{0}/", Port)); } portError = false; _hosts = list.ToArray(); } private void UpdateServer(bool test = false) { serverException = false; try { if (SimpleWebServer.Instance != null) { if (!EnableLocalAssetBundleServer) { ServerStop(); Debug.Log("Server Stopped"); } else if (SimpleWebServer.Instance.Port != _port) { ServerStop(); ServerStart(); Debug.Log("Server Started"); } } else if (EnableLocalAssetBundleServer || test) { ServerStart(); if (!test) Debug.Log("Server Started"); } } catch (Exception e) { _statusMessage = string.Format("Simple Webserver Exception: {0}\nStack Trace\n{1}", e.ToString(), e.StackTrace); Debug.LogException(e); EditorPrefs.SetBool(Application.dataPath + "LocalAssetBundleServerEnabled", false); EnableLocalAssetBundleServer = false; serverException = true; ServerStop(); } } #endregion void OnGUI() { scrollPos = EditorGUILayout.BeginScrollView(scrollPos, false, true); EditorGUILayout.BeginVertical(GUILayout.Width(EditorGUIUtility.currentViewWidth - 20f)); EditorGUILayout.Space(); GUILayout.Label("UMA AssetBundle Manager", EditorStyles.boldLabel); BeginVerticalPadded(5, new Color(0.75f, 0.875f, 1f)); GUILayout.Label("AssetBundle Options", EditorStyles.boldLabel); //Asset Bundle Encryption //defined here so we can modify the message if encryption settings change string buildBundlesMsg = ""; MessageType buildBundlesMsgType = MessageType.Info; EditorGUI.BeginChangeCheck(); encryptionKeysEnabled = EditorGUILayout.ToggleLeft("Enable AssetBundle Encryption", encryptionKeysEnabled); if (EditorGUI.EndChangeCheck()) { //If encryption was turned ON generate the encryption password if necessary if (encryptionKeysEnabled) { if (currentEncryptionPassword == "") { if (UMAABMSettings.GetEncryptionPassword() != "") currentEncryptionPassword = UMAABMSettings.GetEncryptionPassword(); else currentEncryptionPassword = EncryptionUtil.GenerateRandomPW(); } UMAABMSettings.SetEncryptionPassword(currentEncryptionPassword); buildBundlesMsg = "You have turned on encryption and need to Rebuild your bundles to encrypt them."; buildBundlesMsgType = MessageType.Warning; } else { UMAABMSettings.DisableEncryption(); currentEncryptionPassword = ""; } } if (encryptionKeysEnabled) { BeginVerticalIndented(10, new Color(0.75f, 0.875f, 1f)); //tip EditorGUILayout.HelpBox("Make sure you turn on 'Use Encrypted Bundles' in the 'DynamicAssetLoader' components in your scenes.", MessageType.Info); //Encryption key //If we can work out a way for people to download a key we can use this tip and the 'EncryptionKeyURL' field //string encryptionKeyToolTip = "This key is used to generate the required encryption keys used when encrypting your bundles. If you change this key you will need to rebuild your bundles otherwise they wont decrypt. If you use the 'Encryption Key URL' field below you MUST ensure this field is set to the same key the url will return."; string encryptionKeyToolTip = "This key is used to generate the required encryption keys used when encrypting your bundles. If you change this key you will need to rebuild your bundles otherwise they wont decrypt."; EditorGUILayout.LabelField(new GUIContent("Bundle Encryption Password", encryptionKeyToolTip)); EditorGUILayout.BeginHorizontal(); if (!manualEditEncryptionKey) { if(GUILayout.Button(new GUIContent("Edit", encryptionKeyToolTip))) { manualEditEncryptionKey = true; } EditorGUI.BeginDisabledGroup(!manualEditEncryptionKey); EditorGUILayout.TextField("", UMAABMSettings.GetEncryptionPassword());//THis bloody field WILL NOT update when you click edit, then canel, the value stays EditorGUI.EndDisabledGroup(); } else { EditorGUI.BeginChangeCheck(); newEncryptionPassword = EditorGUILayout.TextArea(newEncryptionPassword); if (EditorGUI.EndChangeCheck()) { encryptionSaveButEnabled = EncryptionUtil.PasswordValid(newEncryptionPassword); } if (encryptionSaveButEnabled) { if (GUILayout.Button(new GUIContent("Save"), GUILayout.MaxWidth(60))) { currentEncryptionPassword = newEncryptionPassword; UMAABMSettings.SetEncryptionPassword(newEncryptionPassword); EditorGUIUtility.keyboardControl = 0; manualEditEncryptionKey = false; } } else { GUI.enabled = false; if (GUILayout.Button(new GUIContent("Save", "Your Encryptiom Password should be at least 16 characters long"), GUILayout.MaxWidth(60))) { //Do nothing } GUI.enabled = true; } if (GUILayout.Button(new GUIContent("Cancel", "Reset to previous value: "+ currentEncryptionPassword), GUILayout.MaxWidth(60))) { manualEditEncryptionKey = false; newEncryptionPassword = currentEncryptionPassword = UMAABMSettings.GetEncryptionPassword(); encryptionSaveButEnabled = false; EditorGUIUtility.keyboardControl = 0; } } EditorGUILayout.EndHorizontal(); //EncryptionKey URL //not sure how this would work- the delivered key would itself need to be encrypted probably //Encrypted bundle suffix string encryptionSuffixToolTip = "This suffix is appled to the end of your encrypted bundle names when they are built. Must be lower case and alphaNumeric. Cannot be empty. Defaults to "+DEFAULT_ENCRYPTION_SUFFIX; EditorGUILayout.LabelField(new GUIContent("Encrypted Bundle Suffix", encryptionSuffixToolTip)); EditorGUILayout.BeginHorizontal(); if (!manualEditEncryptionSuffix) { if (GUILayout.Button(new GUIContent("Edit", encryptionSuffixToolTip))) { manualEditEncryptionSuffix = true; } EditorGUI.BeginDisabledGroup(!manualEditEncryptionSuffix); EditorGUILayout.TextField(new GUIContent("", encryptionSuffixToolTip), currentEncryptionSuffix); EditorGUI.EndDisabledGroup(); } else { newEncryptionSuffix = EditorGUILayout.TextArea(newEncryptionSuffix); if (GUILayout.Button(new GUIContent("Save"))) { if (newEncryptionSuffix != "") { Regex rgx = new Regex("[^a-zA-Z0-9 -]"); var suffixToSend = rgx.Replace(newEncryptionSuffix, ""); currentEncryptionSuffix = suffixToSend; UMAABMSettings.SetEncryptionSuffix(suffixToSend.ToLower()); EditorGUIUtility.keyboardControl = 0; manualEditEncryptionSuffix = false; } } } EditorGUILayout.EndHorizontal(); //Encode Bundle Names string encodeBundleNamesTooltip = "If true encrypted bundle names will be base64 encoded"; EditorGUI.BeginChangeCheck(); newEncodeNamesSetting = EditorGUILayout.ToggleLeft(new GUIContent("Encode Bundle Names", encodeBundleNamesTooltip), currentEncodeNamesSetting); if (EditorGUI.EndChangeCheck()) { currentEncodeNamesSetting = newEncodeNamesSetting; UMAABMSettings.SetEncodeNames(newEncodeNamesSetting); } EndVerticalIndented(); } #if ENABLE_IOS_APP_SLICING string AppSlicingTooltip = "If true will build bundles uncompressed for use with iOS Resources Catalogs"; EditorGUI.BeginChangeCheck(); bool newAppSlicingSetting = EditorGUILayout.ToggleLeft(new GUIContent("Build for iOS App Slicing", AppSlicingTooltip), currentAppSlicingSetting); if (EditorGUI.EndChangeCheck()) { currentAppSlicingSetting = newAppSlicingSetting; UMAABMSettings.SetBuildForSlicing(newAppSlicingSetting); } #endif //Asset Bundle Building EditorGUILayout.Space(); string buttonBuildAssetBundlesText = "Build AssetBundles"; //Now defined above the encryption //string buildBundlesText = "Click the button below to build your bundles if you have not done so already."; string fullPathToBundles = Path.Combine(Directory.GetParent(Application.dataPath).FullName, Utility.AssetBundlesOutputPath); string fullPathToPlatformBundles = Path.Combine(fullPathToBundles, Utility.GetPlatformName()); //if we have not built any asset bundles there wont be anything in the cache to clear bool showClearCache = false; if (Directory.Exists(fullPathToPlatformBundles)) { buttonBuildAssetBundlesText = "Rebuild AssetBundles"; buildBundlesMsg = buildBundlesMsg == "" ? "Rebuild your assetBundles to reflect your latest changes" : buildBundlesMsg; showClearCache = true; } else { buildBundlesMsg = "You have not built your asset bundles for " + EditorUserBuildSettings.activeBuildTarget.ToString() + " yet. Click this button to build them."; buildBundlesMsgType = MessageType.Warning; showClearCache = false; } EditorGUILayout.HelpBox(buildBundlesMsg, buildBundlesMsgType); if (GUILayout.Button(buttonBuildAssetBundlesText)) { BuildScript.BuildAssetBundles(); Caching.ClearCache (); return; } EndVerticalPadded(5); EditorGUILayout.Space(); //Local AssetBundleServer BeginVerticalPadded(5f, new Color(0.75f, 0.875f, 1f)); GUILayout.Label("AssetBundle Testing Server", EditorStyles.boldLabel); EditorGUILayout.HelpBox("Once you have built your bundles this local Testing Server can be enabled and it will load those AssetBundles rather than the files inside the project.", MessageType.Info); if (!BuildScript.CanRunLocally(EditorUserBuildSettings.activeBuildTarget)) { EditorGUILayout.HelpBox("Builds for " + EditorUserBuildSettings.activeBuildTarget.ToString() + " cannot access this local server, but you can still use it in the editor.", MessageType.Warning); } bool updateURL = false; EnableLocalAssetBundleServer = EditorGUILayout.Toggle("Start Server", EnableLocalAssetBundleServer); //If the server is off we need to show the user a message telling them that they will have to have uploaded their bundles to an external server //and that they need to set the address of that server in DynamicAssetLoader int newPort = Port; EditorGUI.BeginChangeCheck(); newPort = EditorGUILayout.IntField("Port", Port); if (EditorGUI.EndChangeCheck()) { if (newPort != Port) { if (_activeHost != null && _activeHost != "") ActiveHost = _activeHost.Replace(":" + Port.ToString(), ":" + newPort.ToString()); Port = newPort; UpdateHosts(); //we need to start the server to see if it works with this port- regardless of whether it is turned on or not. if (!EnableLocalAssetBundleServer) { UpdateServer(true); } else { UpdateServer(); } if (serverException == false) { //We can use the set IP with this port so update it if (EnableLocalAssetBundleServer) SimpleWebServer.ServerURL = ActiveHost; } else { //We CANT use the set IP with this port so set the saved URL to "" and tell the user the Port is in use elsewhere SimpleWebServer.ServerURL = ""; EnableLocalAssetBundleServer = false; portError = true; } } } if (!EnableLocalAssetBundleServer) { if (portError) EditorGUILayout.HelpBox("There are no hosts available for that port. Its probably in use by another application. Try another.", MessageType.Warning); else { EditorGUILayout.HelpBox("When the local server is not running the game will play in Simulation Mode OR if you have set the 'RemoteServerURL' for each DynamicAssetLoader, bundles will be downloaded from that location.", MessageType.Warning); if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.WebGL) { EditorGUILayout.HelpBox("WARNING: AssetBundles in WebGL builds that you run locally WILL NOT WORK unless the local server is turned on, and you build using the button below!", MessageType.Warning); } } } EditorGUILayout.Space(); if (_hosts != null && _hosts.Length > 0 && EnableLocalAssetBundleServer) { if (_activeHost == null || _activeHost == "") { ActiveHost = _hosts[0]; } int activeHostInt = 0; string[] hostsStrings = new string[_hosts.Length]; for (int i = 0; i < _hosts.Length; i++) { hostsStrings[i] = _hosts[i].Replace("http://", "").TrimEnd(new char[] { '/' }); if (_hosts[i] == _activeHost) { activeHostInt = i; } } EditorGUI.BeginChangeCheck(); int newActiveHostInt = EditorGUILayout.Popup("Host Address: http://", activeHostInt, hostsStrings); if (EditorGUI.EndChangeCheck()) { if (newActiveHostInt != activeHostInt) { ActiveHost = _hosts[newActiveHostInt]; updateURL = true; } } } EditorGUILayout.Space(); if (showClearCache)//no point in showing a button for bundles that dont exist - or is there? The user might be using a remote url to download assetbundles without the localserver? { EditorGUILayout.HelpBox("You can clear the cache to force asset bundles to be redownloaded.", MessageType.Info); if (GUILayout.Button("Clean the Cache")) { _statusMessage = Caching.ClearCache() ? "Cache Cleared." : "Error clearing cache."; } EditorGUILayout.Space(); } EditorGUILayout.Space(); GUILayout.Label("Server Status"); if (_statusMessage != null) { EditorGUILayout.HelpBox(_statusMessage, MessageType.None); } if (SimpleWebServer.Instance != null) { //GUILayout.Label("Server Request Log"); serverRequestLogOpen = EditorGUILayout.Foldout(serverRequestLogOpen, "Server Request Log"); if(serverRequestLogOpen) EditorGUILayout.HelpBox(SimpleWebServer.Instance.GetLog(), MessageType.Info); } if (updateURL) { SimpleWebServer.ServerURL = ActiveHost; } EndVerticalPadded(5); EditorGUILayout.Space(); //Testing Build- only show this if we can run a build for the current platform (i.e. if its not iOS or Android) if (BuildScript.CanRunLocally (EditorUserBuildSettings.activeBuildTarget)) { BeginVerticalPadded (5, new Color (0.75f, 0.875f, 1f)); GUILayout.Label ("Local Testing Build", EditorStyles.boldLabel); //if the bundles are built and the server is turned on then the user can use this option otherwise there is no point //But we will show them that this option is available even if this is not the case if (!showClearCache || !EnableLocalAssetBundleServer) { EditorGUI.BeginDisabledGroup (true); } EditorGUILayout.HelpBox ("Make a testing Build that uses the Local Server using the button below.", MessageType.Info); developmentBuild = EditorGUILayout.Toggle ("Development Build", developmentBuild); if (GUILayout.Button ("Build and Run!")) { BuildScript.BuildAndRunPlayer (developmentBuild); } if (!showClearCache || !EnableLocalAssetBundleServer) {// EditorGUI.EndDisabledGroup (); } EditorGUILayout.Space (); EndVerticalPadded (5); EditorGUILayout.Space (); } //END SCROLL VIEW //for some reason when we build or build assetbundles when this window is open we get an error //InvalidOperationException: Operation is not valid due to the current state of the object //so try catch is here as a nasty hack to get rid of it try { EditorGUILayout.EndVertical(); EditorGUILayout.EndScrollView(); } catch { } } #region GUI HELPERS //these are copied from UMAs GUI Helper- but that is in an editor folder public static void BeginVerticalPadded(float padding, Color backgroundColor) { //for some reason when we build or build assetbundles when this window is open we get an error //InvalidOperationException: Operation is not valid due to the current state of the object //so try catch is here as a nasty hack to get rid of it try { GUI.color = backgroundColor; GUILayout.BeginHorizontal(EditorStyles.textField); GUI.color = Color.white; GUILayout.Space(padding); GUILayout.BeginVertical(); GUILayout.Space(padding); } catch { } } public static void EndVerticalPadded(float padding) { //for some reason when we build or build assetbundles when this window is open we get an error //InvalidOperationException: Operation is not valid due to the current state of the object //so try catch is here as a nasty hack to get rid of it try { GUILayout.Space(padding); GUILayout.EndVertical(); GUILayout.Space(padding); GUILayout.EndHorizontal(); } catch { } } public static void BeginVerticalIndented(float indentation, Color backgroundColor) { GUI.color = backgroundColor; GUILayout.BeginHorizontal(); GUILayout.Space(indentation); GUI.color = Color.white; GUILayout.BeginVertical(); } public static void EndVerticalIndented() { GUILayout.EndVertical(); GUILayout.EndHorizontal(); } #endregion } [System.Serializable] public class UMAABMSettingsStore { public bool encryptionEnabled = false; public string encryptionPassword = ""; public string encryptionSuffix = ""; public bool encodeNames = false; [Tooltip("If true will build uncompressed assetBundles for use with iOS resource catalogs")] public bool buildForAppSlicing = false; public UMAABMSettingsStore() { } public UMAABMSettingsStore(bool _encryptionEnabled, string _encryptionPassword, string _encryptionSuffix, bool _encodeNames) { _encryptionEnabled = encryptionEnabled; encryptionPassword = _encryptionPassword; encryptionSuffix = _encryptionSuffix; encodeNames = _encodeNames; } } public static class UMAABMSettings { #region PUBLIC FIELDS public const string SETTINGS_FILENAME = "UMAEncryptionSettings-DoNotDelete.txt"; #endregion #region STATIC LOAD SAVE Methods private static string GetSettingsFolderPath() { return FileUtils.GetInternalDataStoreFolder(false,true); } //we are saving the encryptions settings to a text file so that teams working on the same project/ github etc/ can all use the same settings public static UMAABMSettingsStore GetEncryptionSettings() { if (!File.Exists(Path.Combine(GetSettingsFolderPath(), SETTINGS_FILENAME))) return null; else return JsonUtility.FromJson<UMAABMSettingsStore>(File.ReadAllText(Path.Combine(GetSettingsFolderPath(), SETTINGS_FILENAME))); } public static bool GetEncryptionEnabled() { var thisSettings = GetEncryptionSettings(); if (thisSettings == null) return false; else if (thisSettings.encryptionEnabled && thisSettings.encryptionPassword != "") return true; else return false; } public static string GetEncryptionPassword() { var thisSettings = GetEncryptionSettings(); if (thisSettings == null) return ""; else return thisSettings.encryptionPassword; } public static string GetEncryptionSuffix() { var thisSettings = GetEncryptionSettings(); if (thisSettings == null) return ""; else return thisSettings.encryptionSuffix; } public static bool GetEncodeNames() { var thisSettings = GetEncryptionSettings(); if (thisSettings == null) return false; else return thisSettings.encodeNames; } /// <summary> /// Should the bundles be built for use with iOS app slicing /// </summary> public static bool GetBuildForSlicing() { var thisSettings = GetEncryptionSettings(); if (thisSettings == null) return false; else return thisSettings.buildForAppSlicing; } public static void ClearEncryptionSettings() { var thisSettings = new UMAABMSettingsStore(); File.WriteAllText(Path.Combine(GetSettingsFolderPath(), SETTINGS_FILENAME), JsonUtility.ToJson(thisSettings)); } public static void SetEncryptionSettings(bool encryptionEnabled, string encryptionPassword = "", string encryptionSuffix = "", bool? encodeNames = null) { var thisSettings = GetEncryptionSettings(); if (thisSettings == null) thisSettings = new UMAABMSettingsStore(); thisSettings.encryptionEnabled = encryptionEnabled; thisSettings.encryptionPassword = encryptionPassword != "" ? encryptionPassword : thisSettings.encryptionPassword; thisSettings.encryptionSuffix = encryptionSuffix != "" ? encryptionSuffix : thisSettings.encryptionSuffix; thisSettings.encodeNames = encodeNames != null ? (bool)encodeNames : thisSettings.encodeNames; File.WriteAllText(Path.Combine(GetSettingsFolderPath(), SETTINGS_FILENAME), JsonUtility.ToJson(thisSettings)); //need to make this show right in Unity when its inspected /*TextAsset textAsset = (TextAsset)AssetDatabase.LoadAssetAtPath(Path.Combine(GetSettingsFolderPath(), SETTINGS_FILENAME), typeof(TextAsset)); EditorUtility.SetDirty(textAsset); AssetDatabase.SaveAssets();*/ AssetDatabase.Refresh(); //AssetDatabase.ImportAsset(Path.Combine(GetSettingsFolderPath(), SETTINGS_FILENAME), typeof(TextAsset)); } /// <summary> /// Turns encryption OFF /// </summary> public static void DisableEncryption() { SetEncryptionSettings(false); } /// <summary> /// Turns encryption ON ands sets the given password (cannot be blank) /// </summary> public static void SetEncryptionPassword(string encryptionPassword) { if (encryptionPassword != "") { SetEncryptionSettings(true, encryptionPassword); } } /// <summary> /// Turns encryption OFF ands unsets any existing password /// </summary> public static void UnsetEncryptionPassword() { var thisSettings = GetEncryptionSettings(); if (thisSettings == null) thisSettings = new UMAABMSettingsStore(); thisSettings.encryptionEnabled = false; thisSettings.encryptionPassword = ""; File.WriteAllText(Path.Combine(GetSettingsFolderPath(), SETTINGS_FILENAME), JsonUtility.ToJson(thisSettings)); AssetDatabase.Refresh(); } /// <summary> /// Turns encryption ON ands sets the given encryption suffix (cannot be blank) /// </summary> public static void SetEncryptionSuffix(string encryptionSuffix) { if (encryptionSuffix != "") { SetEncryptionSettings(true, "", encryptionSuffix); } } /// <summary> /// Turns encryption ON ands sets the encode names setting /// </summary> public static void SetEncodeNames(bool encodeNames) { SetEncryptionSettings(true,"", "", encodeNames); } /// <summary> /// Should the bundles be built for use with iOS app slicing /// </summary> public static void SetBuildForSlicing(bool enabled) { var thisSettings = GetEncryptionSettings(); if (thisSettings == null) thisSettings = new UMAABMSettingsStore(); thisSettings.buildForAppSlicing = enabled; } #endregion } } #endif
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using LibGit2Sharp.Core; using LibGit2Sharp.Core.Handles; namespace LibGit2Sharp { /// <summary> /// Provides methods to directly work against the Git object database /// without involving the index nor the working directory. /// </summary> public class ObjectDatabase : IEnumerable<GitObject> { private readonly Repository repo; private readonly ObjectDatabaseSafeHandle handle; /// <summary> /// Needed for mocking purposes. /// </summary> protected ObjectDatabase() { } internal ObjectDatabase(Repository repo) { this.repo = repo; handle = Proxy.git_repository_odb(repo.Handle); repo.RegisterForCleanup(handle); } #region Implementation of IEnumerable /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>An <see cref="IEnumerator{T}"/> object that can be used to iterate through the collection.</returns> public virtual IEnumerator<GitObject> GetEnumerator() { ICollection<GitOid> oids = Proxy.git_odb_foreach(handle, ptr => ptr.MarshalAs<GitOid>()); return oids .Select(gitOid => repo.Lookup<GitObject>(new ObjectId(gitOid))) .GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>An <see cref="IEnumerator"/> object that can be used to iterate through the collection.</returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion /// <summary> /// Determines if the given object can be found in the object database. /// </summary> /// <param name="objectId">Identifier of the object being searched for.</param> /// <returns>True if the object has been found; false otherwise.</returns> public virtual bool Contains(ObjectId objectId) { Ensure.ArgumentNotNull(objectId, "objectId"); return Proxy.git_odb_exists(handle, objectId); } /// <summary> /// Inserts a <see cref="Blob"/> into the object database, created from the content of a file. /// </summary> /// <param name="path">Path to the file to create the blob from. A relative path is allowed to /// be passed if the <see cref="Repository"/> is a standard, non-bare, repository. The path /// will then be considered as a path relative to the root of the working directory.</param> /// <returns>The created <see cref="Blob"/>.</returns> public virtual Blob CreateBlob(string path) { Ensure.ArgumentNotNullOrEmptyString(path, "path"); if (repo.Info.IsBare && !Path.IsPathRooted(path)) { throw new InvalidOperationException( string.Format(CultureInfo.InvariantCulture, "Cannot create a blob in a bare repository from a relative path ('{0}').", path)); } ObjectId id = Path.IsPathRooted(path) ? Proxy.git_blob_create_fromdisk(repo.Handle, path) : Proxy.git_blob_create_fromfile(repo.Handle, path); return repo.Lookup<Blob>(id); } /// <summary> /// Adds the provided backend to the object database with the specified priority. /// </summary> /// <param name="backend">The backend to add</param> /// <param name="priority">The priority at which libgit2 should consult this backend (higher values are consulted first)</param> public virtual void AddBackend(OdbBackend backend, int priority) { Ensure.ArgumentNotNull(backend, "backend"); Ensure.ArgumentConformsTo(priority, s => s > 0, "priority"); Proxy.git_odb_add_backend(handle, backend.GitOdbBackendPointer, priority); } private class Processor { private readonly Stream stream; private readonly int? numberOfBytesToConsume; private int totalNumberOfReadBytes; public Processor(Stream stream, int? numberOfBytesToConsume) { this.stream = stream; this.numberOfBytesToConsume = numberOfBytesToConsume; } public int Provider(IntPtr content, int max_length, IntPtr data) { var local = new byte[max_length]; int bytesToRead = max_length; if (numberOfBytesToConsume.HasValue) { int totalRemainingBytesToRead = numberOfBytesToConsume.Value - totalNumberOfReadBytes; if (totalRemainingBytesToRead < max_length) { bytesToRead = totalRemainingBytesToRead; } } int numberOfReadBytes = stream.Read(local, 0, bytesToRead); totalNumberOfReadBytes += numberOfReadBytes; Marshal.Copy(local, 0, content, numberOfReadBytes); return numberOfReadBytes; } } /// <summary> /// Inserts a <see cref="Blob"/> into the object database, created from the content of a data provider. /// </summary> /// <param name="stream">The stream from which will be read the content of the blob to be created.</param> /// <param name="hintpath">The hintpath is used to determine what git filters should be applied to the object before it can be placed to the object database.</param> /// <param name="numberOfBytesToConsume">The number of bytes to consume from the stream.</param> /// <returns>The created <see cref="Blob"/>.</returns> public virtual Blob CreateBlob(Stream stream, string hintpath = null, int? numberOfBytesToConsume = null) { Ensure.ArgumentNotNull(stream, "stream"); if (!stream.CanRead) { throw new ArgumentException("The stream cannot be read from.", "stream"); } var proc = new Processor(stream, numberOfBytesToConsume); ObjectId id = Proxy.git_blob_create_fromchunks(repo.Handle, hintpath, proc.Provider); return repo.Lookup<Blob>(id); } /// <summary> /// Inserts a <see cref="Tree"/> into the object database, created from a <see cref="TreeDefinition"/>. /// </summary> /// <param name="treeDefinition">The <see cref="TreeDefinition"/>.</param> /// <returns>The created <see cref="Tree"/>.</returns> public virtual Tree CreateTree(TreeDefinition treeDefinition) { Ensure.ArgumentNotNull(treeDefinition, "treeDefinition"); return treeDefinition.Build(repo); } /// <summary> /// Inserts a <see cref="Commit"/> into the object database, referencing an existing <see cref="Tree"/>. /// <para> /// Prettifing the message includes: /// * Removing empty lines from the beginning and end. /// * Removing trailing spaces from every line. /// * Turning multiple consecutive empty lines between paragraphs into just one empty line. /// * Ensuring the commit message ends with a newline. /// * Removing every line starting with "#". /// </para> /// </summary> /// <param name="author">The <see cref="Signature"/> of who made the change.</param> /// <param name="committer">The <see cref="Signature"/> of who added the change to the repository.</param> /// <param name="message">The description of why a change was made to the repository.</param> /// <param name="prettifyMessage">True to prettify the message, or false to leave it as is</param> /// <param name="tree">The <see cref="Tree"/> of the <see cref="Commit"/> to be created.</param> /// <param name="parents">The parents of the <see cref="Commit"/> to be created.</param> /// <returns>The created <see cref="Commit"/>.</returns> public virtual Commit CreateCommit(Signature author, Signature committer, string message, bool prettifyMessage, Tree tree, IEnumerable<Commit> parents) { Ensure.ArgumentNotNull(message, "message"); Ensure.ArgumentDoesNotContainZeroByte(message, "message"); Ensure.ArgumentNotNull(author, "author"); Ensure.ArgumentNotNull(committer, "committer"); Ensure.ArgumentNotNull(tree, "tree"); Ensure.ArgumentNotNull(parents, "parents"); if (prettifyMessage) { message = Proxy.git_message_prettify(message); } GitOid[] parentIds = parents.Select(p => p.Id.Oid).ToArray(); ObjectId commitId = Proxy.git_commit_create(repo.Handle, null, author, committer, message, tree, parentIds); return repo.Lookup<Commit>(commitId); } /// <summary> /// Inserts a <see cref="TagAnnotation"/> into the object database, pointing to a specific <see cref="GitObject"/>. /// </summary> /// <param name="name">The name.</param> /// <param name="target">The <see cref="GitObject"/> being pointed at.</param> /// <param name="tagger">The tagger.</param> /// <param name="message">The message.</param> /// <returns>The created <see cref="TagAnnotation"/>.</returns> public virtual TagAnnotation CreateTagAnnotation(string name, GitObject target, Signature tagger, string message) { Ensure.ArgumentNotNullOrEmptyString(name, "name"); Ensure.ArgumentNotNull(message, "message"); Ensure.ArgumentNotNull(target, "target"); Ensure.ArgumentNotNull(tagger, "tagger"); Ensure.ArgumentDoesNotContainZeroByte(name, "name"); Ensure.ArgumentDoesNotContainZeroByte(message, "message"); string prettifiedMessage = Proxy.git_message_prettify(message); ObjectId tagId = Proxy.git_tag_annotation_create(repo.Handle, name, target, tagger, prettifiedMessage); return repo.Lookup<TagAnnotation>(tagId); } /// <summary> /// Archive the given commit. /// </summary> /// <param name="commit">The commit.</param> /// <param name="archiver">The archiver to use.</param> public virtual void Archive(Commit commit, ArchiverBase archiver) { Ensure.ArgumentNotNull(commit, "commit"); Ensure.ArgumentNotNull(archiver, "archiver"); archiver.OrchestrateArchiving(commit.Tree, commit.Id, commit.Committer.When); } /// <summary> /// Archive the given tree. /// </summary> /// <param name="tree">The tree.</param> /// <param name="archiver">The archiver to use.</param> public virtual void Archive(Tree tree, ArchiverBase archiver) { Ensure.ArgumentNotNull(tree, "tree"); Ensure.ArgumentNotNull(archiver, "archiver"); archiver.OrchestrateArchiving(tree, null, DateTimeOffset.UtcNow); } /// <summary> /// Returns the merge base (best common ancestor) of the given commits /// and the distance between each of these commits and this base. /// </summary> /// <param name="one">The <see cref="Commit"/> being used as a reference.</param> /// <param name="another">The <see cref="Commit"/> being compared against <paramref name="one"/>.</param> /// <returns>A instance of <see cref="HistoryDivergence"/>.</returns> public virtual HistoryDivergence CalculateHistoryDivergence(Commit one, Commit another) { Ensure.ArgumentNotNull(one, "one"); Ensure.ArgumentNotNull(another, "another"); return new HistoryDivergence(repo, one, another); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace feal.PantryGuide.Api.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Net.Sockets; using System.Threading; using Microsoft.Extensions.Logging; using Orleans.Runtime; namespace Orleans.Messaging { /// <summary> /// The GatewayConnection class does double duty as both the manager of the connection itself (the socket) and the sender of messages /// to the gateway. It uses a single instance of the Receiver class to handle messages from the gateway. /// /// Note that both sends and receives are synchronous. /// </summary> internal class GatewayConnection : OutgoingMessageSender { private readonly MessageFactory messageFactory; internal bool IsLive { get; private set; } internal ProxiedMessageCenter MsgCenter { get; private set; } private Uri addr; internal Uri Address { get { return addr; } private set { addr = value; Silo = addr.ToSiloAddress(); } } internal SiloAddress Silo { get; private set; } private readonly GatewayClientReceiver receiver; private readonly TimeSpan openConnectionTimeout; internal Socket Socket { get; private set; } // Shared by the receiver private DateTime lastConnect; internal GatewayConnection(Uri address, ProxiedMessageCenter mc, MessageFactory messageFactory, ILoggerFactory loggerFactory, TimeSpan openConnectionTimeout) : base("GatewayClientSender_" + address, mc.SerializationManager, loggerFactory) { this.messageFactory = messageFactory; this.openConnectionTimeout = openConnectionTimeout; Address = address; MsgCenter = mc; receiver = new GatewayClientReceiver(this, mc.SerializationManager, loggerFactory); lastConnect = new DateTime(); IsLive = true; } public override void Start() { if (Log.IsVerbose) Log.Verbose(ErrorCode.ProxyClient_GatewayConnStarted, "Starting gateway connection for gateway {0}", Address); lock (Lockable) { if (State == ThreadState.Running) { return; } Connect(); if (!IsLive) return; // If the Connect succeeded receiver.Start(); base.Start(); } } public override void Stop() { IsLive = false; receiver.Stop(); base.Stop(); DrainQueue(RerouteMessage); MsgCenter.RuntimeClient.BreakOutstandingMessagesToDeadSilo(Silo); Socket s; lock (Lockable) { s = Socket; Socket = null; } if (s == null) return; CloseSocket(s); } // passed the exact same socket on which it got SocketException. This way we prevent races between connect and disconnect. public void MarkAsDisconnected(Socket socket2Disconnect) { Socket s = null; lock (Lockable) { if (socket2Disconnect == null || Socket == null) return; if (Socket == socket2Disconnect) // handles races between connect and disconnect, since sometimes we grab the socket outside lock. { s = Socket; Socket = null; Log.Warn(ErrorCode.ProxyClient_MarkGatewayDisconnected, String.Format("Marking gateway at address {0} as Disconnected", Address)); if ( MsgCenter != null && MsgCenter.GatewayManager != null) // We need a refresh... MsgCenter.GatewayManager.ExpediteUpdateLiveGatewaysSnapshot(); } } if (s != null) { CloseSocket(s); } if (socket2Disconnect == s) return; CloseSocket(socket2Disconnect); } public void MarkAsDead() { Log.Warn(ErrorCode.ProxyClient_MarkGatewayDead, String.Format("Marking gateway at address {0} as Dead in my client local gateway list.", Address)); MsgCenter.GatewayManager.MarkAsDead(Address); Stop(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public void Connect() { if (!MsgCenter.Running) { if (Log.IsVerbose) Log.Verbose(ErrorCode.ProxyClient_MsgCtrNotRunning, "Ignoring connection attempt to gateway {0} because the proxy message center is not running", Address); return; } // Yes, we take the lock around a Sleep. The point is to ensure that no more than one thread can try this at a time. // There's still a minor problem as written -- if the sending thread and receiving thread both get here, the first one // will try to reconnect. eventually do so, and then the other will try to reconnect even though it doesn't have to... // Hopefully the initial "if" statement will prevent that. lock (Lockable) { if (!IsLive) { if (Log.IsVerbose) Log.Verbose(ErrorCode.ProxyClient_DeadGateway, "Ignoring connection attempt to gateway {0} because this gateway connection is already marked as non live", Address); return; // if the connection is already marked as dead, don't try to reconnect. It has been doomed. } for (var i = 0; i < ProxiedMessageCenter.CONNECT_RETRY_COUNT; i++) { try { if (Socket != null) { if (Socket.Connected) return; MarkAsDisconnected(Socket); // clean up the socket before reconnecting. } if (lastConnect != new DateTime()) { // We already tried at least once in the past to connect to this GW. // If we are no longer connected to this GW and it is no longer in the list returned // from the GatewayProvider, consider directly this connection dead. if (!MsgCenter.GatewayManager.GetLiveGateways().Contains(Address)) break; // Wait at least ProxiedMessageCenter.MINIMUM_INTERCONNECT_DELAY before reconnection tries var millisecondsSinceLastAttempt = DateTime.UtcNow - lastConnect; if (millisecondsSinceLastAttempt < ProxiedMessageCenter.MINIMUM_INTERCONNECT_DELAY) { var wait = ProxiedMessageCenter.MINIMUM_INTERCONNECT_DELAY - millisecondsSinceLastAttempt; if (Log.IsVerbose) Log.Verbose(ErrorCode.ProxyClient_PauseBeforeRetry, "Pausing for {0} before trying to connect to gateway {1} on trial {2}", wait, Address, i); Thread.Sleep(wait); } } lastConnect = DateTime.UtcNow; Socket = new Socket(Silo.Endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); SocketManager.Connect(Socket, Silo.Endpoint, this.openConnectionTimeout); NetworkingStatisticsGroup.OnOpenedGatewayDuplexSocket(); MsgCenter.OnGatewayConnectionOpen(); SocketManager.WriteConnectionPreamble(Socket, MsgCenter.ClientId); // Identifies this client Log.Info(ErrorCode.ProxyClient_Connected, "Connected to gateway at address {0} on trial {1}.", Address, i); return; } catch (Exception ex) { Log.Warn(ErrorCode.ProxyClient_CannotConnect, $"Unable to connect to gateway at address {Address} on trial {i} (Exception: {ex.Message})"); MarkAsDisconnected(Socket); } } // Failed too many times -- give up MarkAsDead(); } } protected override SocketDirection GetSocketDirection() { return SocketDirection.ClientToGateway; } protected override bool PrepareMessageForSend(Message msg) { if (Cts == null) { return false; } // Check to make sure we're not stopped if (Cts.IsCancellationRequested) { // Recycle the message we've dequeued. Note that this will recycle messages that were queued up to be sent when the gateway connection is declared dead MsgCenter.SendMessage(msg); return false; } if (msg.TargetSilo != null) return true; msg.TargetSilo = Silo; if (msg.TargetGrain.IsSystemTarget) msg.TargetActivation = ActivationId.GetSystemActivation(msg.TargetGrain, msg.TargetSilo); return true; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] protected override bool GetSendingSocket(Message msg, out Socket socketCapture, out SiloAddress targetSilo, out string error) { error = null; targetSilo = Silo; socketCapture = null; try { if (Socket == null || !Socket.Connected) { Connect(); } socketCapture = Socket; if (socketCapture == null || !socketCapture.Connected) { // Failed to connect -- Connect will have already declared this connection dead, so recycle the message return false; } } catch (Exception) { //No need to log any errors, as we alraedy do it inside Connect(). return false; } return true; } protected override void OnGetSendingSocketFailure(Message msg, string error) { msg.TargetSilo = null; // clear previous destination! MsgCenter.SendMessage(msg); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] protected override void OnMessageSerializationFailure(Message msg, Exception exc) { // we only get here if we failed to serialise the msg (or any other catastrophic failure). // Request msg fails to serialise on the sending silo, so we just enqueue a rejection msg. Log.Warn(ErrorCode.ProxyClient_SerializationError, String.Format("Unexpected error serializing message to gateway {0}.", Address), exc); FailMessage(msg, String.Format("Unexpected error serializing message to gateway {0}. {1}", Address, exc)); if (msg.Direction == Message.Directions.Request || msg.Direction == Message.Directions.OneWay) { return; } // Response msg fails to serialize on the responding silo, so we try to send an error response back. // if we failed sending an original response, turn the response body into an error and reply with it. msg.Result = Message.ResponseTypes.Error; msg.BodyObject = Response.ExceptionResponse(exc); try { MsgCenter.SendMessage(msg); } catch (Exception ex) { // If we still can't serialize, drop the message on the floor Log.Warn(ErrorCode.ProxyClient_DroppingMsg, "Unable to serialize message - DROPPING " + msg, ex); msg.ReleaseBodyAndHeaderBuffers(); } } protected override void OnSendFailure(Socket socket, SiloAddress targetSilo) { MarkAsDisconnected(socket); } protected override void ProcessMessageAfterSend(Message msg, bool sendError, string sendErrorStr) { msg.ReleaseBodyAndHeaderBuffers(); if (sendError) { // We can't recycle the current message, because that might wind up with it getting delivered out of order, so we have to reject it FailMessage(msg, sendErrorStr); } } protected override void FailMessage(Message msg, string reason) { msg.ReleaseBodyAndHeaderBuffers(); MessagingStatisticsGroup.OnFailedSentMessage(msg); if (MsgCenter.Running && msg.Direction == Message.Directions.Request) { if (Log.IsVerbose) Log.Verbose(ErrorCode.ProxyClient_RejectingMsg, "Rejecting message: {0}. Reason = {1}", msg, reason); MessagingStatisticsGroup.OnRejectedMessage(msg); Message error = this.messageFactory.CreateRejectionResponse(msg, Message.RejectionTypes.Unrecoverable, reason); MsgCenter.QueueIncomingMessage(error); } else { Log.Warn(ErrorCode.ProxyClient_DroppingMsg, "Dropping message: {0}. Reason = {1}", msg, reason); MessagingStatisticsGroup.OnDroppedSentMessage(msg); } } private void RerouteMessage(Message msg) { msg.TargetActivation = null; msg.TargetSilo = null; MsgCenter.SendMessage(msg); } private void CloseSocket(Socket socket) { SocketManager.CloseSocket(socket); NetworkingStatisticsGroup.OnClosedGatewayDuplexSocket(); MsgCenter.OnGatewayConnectionClosed(); } } }
//--------------------------------------------------------------------------------------------------------- // VehicleEditDlg.cs // Main script file implementing the GUI logic and client API for the vehicle edit dialog, built for use // in Keen's SolConflict and Fury-TV modifications. // // Copyright (c) 2016 Robert MacGregor // This software is licensed under the MIT license. Refer to LICENSE.txt for more information. //--------------------------------------------------------------------------------------------------------- // Ensure that these are all 0-values, otherwise we end up using "" as keys. if ($VehicleEdit::Vehicles::Count $= "") $VehicleEdit::Vehicles::Count = 0; if ($VehicleEdit::Weapons::Count $= "") $VehicleEdit::Weapons::Count = 0; if ($VehicleEdit::Modules::TypeCount $= "") $VehicleEdit::Moduels::TypeCount = 0; if (isFile("VehicleEditPresets.cs")) exec("vehicleEditPresets.cs"); function mVariate(%min, %max, %base, %val) { if (%val == %base) return 0.5; else if (%val > %base) return (%val - %base) / (%max - %base) * 0.5 + 0.5; else if (%val < %base) return (%val - %min) / (%base - %min) * 0.5; } function ShellPopupMenu::getIDByText(%this, %text) { for (%index = 0; %index < 100; %index++) { %indexText = %this.getTextByID(%index); if (%indexText $= %text) return %index; else if (%indexText $="") return -1; } return -1; } //--------------------------------------------------------------------------------------------------------- // Description: Server-side function used for testing the vehicle edit dialog transmission API at // which point the target client can test the GUI behavior on their end. //--------------------------------------------------------------------------------------------------------- function GameConnection::vehicleEditSystemTest(%this) { // Register some test vehicles commandToClient(%this, 'RegisterVehicle', 0, "Cola Fighter", 1, 600, 200, 300, 400, "coke"); commandToClient(%this, 'RegisterSlot', 2, 2); commandToClient(%this, 'RegisterSlot', 2, 2); commandToClient(%this, 'RegisterSlot', 4, 4); commandToClient(%this, 'RegisterSlot', 4, 4); commandToClient(%this, 'RegisterSlot', 4, 4); commandToClient(%this, 'RegisterSlot', 2, 2); commandToClient(%this, 'RegisterSlot', 2, 2); commandToClient(%this, 'RegisterVehicle', 1, "Derm Ravager", 2, 600, 50, 60, 70, "bioderm_heavy"); commandToClient(%this, 'RegisterSlot', 4, 4); commandToClient(%this, 'RegisterVehicle', 2, "Strength", 4, 600, 1, 2, 3, "banner_strength"); // Register some weapons commandToClient(%this, 'RegisterWeapon', 1, "Hellfire Missiles", 2, 2); commandToClient(%this, 'RegisterWeaponText', "Hellfire missiles will\nwreck face from above."); commandToClient(%this, 'RegisterWeapon', 2, "Sleepy Sheep", 2, 2); commandToClient(%this, 'RegisterWeaponText', "Put your enemies to sleep with ease."); commandToClient(%this, 'RegisterWeapon', 3, "Mellow Machinegun", 4, 4); commandToClient(%this, 'RegisterWeaponText', "How mellow can a gun be?\nThe world may never know."); commandToClient(%this, 'RegisterWeapon', 4, "Boring Castro", 4, 4); commandToClient(%this, 'RegisterWeaponText', "Boring!"); // Register Modules commandToClient(%this, 'RegisterModule', 0, "Irridium Plating", "Armor", 1, 700, 500, 0, 0); commandToClient(%this, 'RegisterModule', 1, "Standard Plating", "Armor", 1, 0, 0, 0, 0); commandToClient(%this, 'RegisterModule', 2, "No Plating", "Armor", 1, -400, -200, 0, 0); commandToClient(%this, 'RegisterModule', 4, "Standard Shields", "Shield", 1, 0, 0, 0, 0); commandToClient(%this, 'RegisterModule', 5, "No Shields", "Shield", 1, 0, 0, -400, 400); commandToClient(%this, 'RegisterModule', 6, "Reinforced Shields", "Shield", 1, 0, 0, 400, -100); commandToClient(%this, 'EndVehicleEditData'); } //--------------------------------------------------------------------------------------------------------- // Description: Registers a new vehicle to the vehicle edit dialog. // Parameters: // %serverID - A server relevant identification number for this vehicle. // %name - The name of the vehicle. // %vehicleMask - The bitmask representing this vehicle. It is used for module compatability testing. // %baseWeight - The weight of the vehicle with no alterations. // %baseArmor - The armor of the vehicle with no alterations. // %baseShield - The shield strength of the vehicle with no alterations. // %baseRegen - The energy regeneration rate of the vehicle with no alterations. // %shapeName - The shapename of the vehicle. This is displayed in a 3D preview on the client end. // Note that this parameter has exactly the same expected value as the shapefile parameter on a // datablock, except that the .dts extension must be omitted. //--------------------------------------------------------------------------------------------------------- function clientCmdRegisterVehicle(%serverID, %name, %vehicleMask, %baseWeight, %baseArmor, %baseShield, %baseRegen, %shapename) { %name = strReplace(%name, " ", "_"); $VehicleEdit::Vehicles::Name[$VehicleEdit::Vehicles::Count] = %name; $VehicleEdit::Vehicles::BaseArmor[$VehicleEdit::Vehicles::Count] = %baseArmor; $VehicleEdit::Vehicles::BaseShield[$VehicleEdit::Vehicles::Count] = %baseShield; $VehicleEdit::Vehicles::BaseRegen[$VehicleEdit::Vehicles::Count] = %baseRegen; $VehicleEdit::Vehicles::BaseWeight[$VehicleEdit::Vehicles::Count] = %baseWeight; $VehicleEdit::Vehicles::ShapeName[$VehicleEdit::Vehicles::Count] = %shapename; $VehicleEdit::Vehicles::Mask[$VehicleEdit::Vehicles::Count] = %vehicleMask; $VehicleEdit::Vehicles::ServerID[$VehicleEdit::Vehicles::Count] = %serverID; $VehicleEdit::Vehicles::NameToID[%name] = $VehicleEdit::Vehicles::Count; $VehicleEdit::Vehicles::Count++; } //--------------------------------------------------------------------------------------------------------- // Description: Registers a weapon slot with the given compatability mask to the last registered vehicle. // Parameters: // %mask - The bitmask representing //--------------------------------------------------------------------------------------------------------- function clientCmdRegisterSlot(%typeMask, %sizeMask) { %id = $VehicleEdit::Vehicles::Count - 1; if ($VehicleEdit::Vehicles::Slots::Count[%id] $= "") $VehicleEdit::Vehicles::Slots::Count[%id] = 0; $VehicleEdit::Vehicles::Slots::TypeMask[%id, $VehicleEdit::Vehicles::Slots::Count[%id]] = %typeMask; $VehicleEdit::Vehicles::Slots::SizeMask[%id, $VehicleEdit::Vehicles::Slots::Count[%id]] = %sizeMask; $VehicleEdit::Vehicles::Slots::Count[%id]++; } function clientCmdRegisterModule(%serverID, %name, %type, %vehicleMask, %relWeight, %relArmor, %relShield, %relRegen) { if ($VehicleEdit::Modules::Count[%type] $= "") $VehicleEdit::Modules::Count[%type] = 0; if ($VehicleEdit::Modules::TypeCount $= "") $VehicleEdit::Modules::TypeCount = 0; %id = $VehicleEdit::Modules::Count[%type]; if ($VehicleEdit::Modules::TypeToID[%type] $= "") { $VehicleEdit::Modules::TypeToID[%type] = $VehicleEdit::Modules::TypeCount; $VehicleEdit::Modules::Types[$VehicleEdit::Modules::TypeCount] = %type; $VehicleEdit::Modules::TypeCount++; } $VehicleEdit::Modules::Name[%type, %id] = %name; $VehicleEdit::Modules::RelativeArmor[%type, %id] = %relArmor; $VehicleEdit::Modules::RelativeShield[%type, %id] = %relShield; $VehicleEdit::Modules::RelativeRegen[%type, %id] = %relRegen; $VehicleEdit::Modules::RelativeWeight[%type, %id] = %relWeight; $VehicleEdit::Modules::VehicleMask[%type, %id] = %vehicleMask; $VehicleEdit::Weapons::ServerID[%type, %id] = %serverID; $VehicleEdit::Modules::NameToID[%type, %name] = $VehicleEdit::Modules::Count[%type]; $VehicleEdit::Modules::Count[%type]++; } function clientCmdRegisterWeapon(%serverID, %name, %typeMask, %sizeMask) { $VehicleEdit::Weapons::ServerID[$VehicleEdit::Weapons::Count] = %serverID; $VehicleEdit::Weapons::Name[$VehicleEdit::Weapons::Count] = %name; $VehicleEdit::Weapons::TypeMask[$VehicleEdit::Weapons::Count] = %typeMask; $VehicleEdit::Weapons::SizeMask[$VehicleEdit::Weapons::Count] = %typeMask; $VehicleEdit::Weapons::NameToID[%name] = $VehicleEdit::Weapons::Count; $VehicleEdit::Weapons::Count++; } function clientCmdRegisterWeaponText(%text) { $VehicleEdit::Weapons::WeaponTexts[$VehicleEdit::Weapons::Count - 1] = %text; } function VehicleEdit::resetInternalDatabase() { for (%vehicleID = 0; %vehicleID < $VehicleEdit::Vehicles::Count; %vehicleID++) { $VehicleEdit::Vehicles::CompatibleModules[%vehicleID] = ""; $VehicleEdit::Vehicles::CompatibleWeapons[%vehicleID] = ""; $VehicleEdit::Vehicles::MaximumArmor[%vehicleID] = $VehicleEdit::Vehicles::MinimumArmor[%vehicleID] = $VehicleEdit::Vehicles::BaseArmor[%vehicleID] = $VehicleEdit::Vehicles::MaximumShield[%vehicleID] = $VehicleEdit::Vehicles::MinimumShield[%vehicleID] = $VehicleEdit::Vehicles::BaseShield[%vehicleID] = $VehicleEdit::Vehicles::MaximumRegen[%vehicleID] = $VehicleEdit::Vehicles::MinimumRegen[%vehicleID] = $VehicleEdit::Vehicles::BaseRegen[%vehicleID] = $VehicleEdit::Vehicles::MaximumWeight[%vehicleID] = $VehicleEdit::Vehicles::MinimumWeight[%vehicleID] = $VehicleEdit::Vehicles::BaseWeight[%vehicleID] = $VehicleEdit::Vehicles::Name[%vehicleID] = ""; for (%slotID = 0; %slotID < $VehicleEdit::Vehicles::Slots::Count[%vehicleID]; %slotID++) $VehicleEdit::Vehicles::Slots::SizeMask[%vehicleID, %slotID] = $VehicleEdit::Vehicles::Slots::TypeMask[%vehicleID, %slotID] = ""; $VehicleEdit::Vehicles::Slots::Count[%vehicleID] = 0; } for (%weaponID = 0; %weaponID < $VehicleEdit::Weapons::Count; %weaponID++) $VehicleEdit::Weapons::SizeMask[%weaponID] = $VehicleEdit::Weapons::TypeMask[%weaponID] = ""; for (%moduleTypeID = 0; %moduleTypeID < $VehicleEdit::Modules::TypeCount; %moduleTypeID++) { %typeName = $VehicleEdit::Modules::Types[%moduleTypeID]; $VehicleEdit::Modules::MinimumWeight[%typeName] = $VehicleEdit::Modules::MaximumWeight[%typeName] = $VehicleEdit::Modules::MaximumShield[%typeName] = $VehicleEdit::Modules::MinimumShield[%typeName] = $VehicleEdit::Modules::MaximumArmor[%typeName] = $VehicleEdit::Modules::MinimumArmor[%typeName] = $VehicleEdit::Modules::MaximumRegen[%typeName] = $VehicleEdit::Modules::MinimumRegen[%typeName] = ""; for (%moduleID = 0; %moduleID < $VehicleEdit::Modules::Count[%typeName]; %moduleID++) { $VehicleEdit::Modules::Name[%typeName, %moduleID] = $VehicleEdit::RelativeRegen[%typeName, %moduleID] = $VehicleEdit::Modules::RelativeArmor[%typeName, %moduleID] = $VehicleEdit::Modules::RelativeWeight[%typeName, %moduleID] = $VehicleEdit::Modules::RelativeShield[%typeName, %moduleID] = ""; } $VehicleEdit::Modules::Count[%typeName] = 0; } $VehicleEdit::Modules::TypeCount = 0; $VehicleEdit::Vehicles::Count = 0; $VehicleEdit::Weapons::Count = 0; } function clientCmdEndVehicleEditData() { // FIXME: This is a potential server-sided DoS. Really shitty one, though. // We loop over vehicles and foreach compatible module in a given type, we figure the best and worst influences for (%vehicleID = 0; %vehicleID < $VehicleEdit::Vehicles::Count; %vehicleID++) { $VehicleEdit::Vehicles::CompatibleModules[%vehicleID] = ""; $VehicleEdit::Vehicles::CompatibleWeapons[%vehicleID] = ""; $VehicleEdit::Vehicles::MaximumArmor[%vehicleID] = $VehicleEdit::Vehicles::MinimumArmor[%vehicleID] = $VehicleEdit::Vehicles::BaseArmor[%vehicleID]; $VehicleEdit::Vehicles::MaximumShield[%vehicleID] = $VehicleEdit::Vehicles::MinimumShield[%vehicleID] = $VehicleEdit::Vehicles::BaseShield[%vehicleID]; $VehicleEdit::Vehicles::MaximumRegen[%vehicleID] = $VehicleEdit::Vehicles::MinimumRegen[%vehicleID] = $VehicleEdit::Vehicles::BaseRegen[%vehicleID]; $VehicleEdit::Vehicles::MaximumWeight[%vehicleID] = $VehicleEdit::Vehicles::MinimumWeight[%vehicleID] = $VehicleEdit::Vehicles::BaseWeight[%vehicleID]; %baseArmor = $VehicleEdit::Vehicles::BaseArmor[%vehicleID]; %baseRegen = $VehicleEdit::Vehicles::BaseRegen[%vehicleID]; %baseShield = $VehicleEdit::Vehicles::BaseShield[%vehicleID]; %baseWeight = $VehicleEdit::Vehicles::BaseWeight[%vehicleID]; // Process foreach weapon slot and find compatible weapons for (%slotID = 0; %slotID < $VehicleEdit::Vehicles::Slots::Count[%vehicleID]; %slotID++) { // Check each weapon against this slot for (%weaponID = 0; %weaponID < $VehicleEdit::Weapons::Count; %weaponID++) if ($VehicleEdit::Weapons::SizeMask[%weaponID] & $VehicleEdit::Vehicles::Slots::SizeMask[%vehicleID, %slotID] && $VehicleEdit::Weapons::TypeMask[%weaponID] & $VehicleEdit::Vehicles::Slots::TypeMask[%vehicleID, %slotID]) $VehicleEdit::Vehicles::CompatibleWeapons[%vehicleID, %slotID] = $VehicleEdit::Vehicles::CompatibleWeapons[%vehicleID, %slotID] SPC %weaponID; $VehicleEdit::Vehicles::CompatibleWeapons[%vehicleID, %slotID] = trim($VehicleEdit::Vehicles::CompatibleWeapons[%vehicleID, %slotID]); } // Process minimum and maximum values on a per module-type basis as well as build compatible lists for (%moduleTypeID = 0; %moduleTypeID < $VehicleEdit::Modules::TypeCount; %moduleTypeID++) { %typeName = $VehicleEdit::Modules::Types[%moduleTypeID]; // Now loop foreach module in this type for (%moduleID = 0; %moduleID < $VehicleEdit::Modules::Count[%typeName]; %moduleID++) { if ($VehicleEdit::Modules::VehicleMask[%typeName, %moduleID] & $VehicleEdit::Vehicles::Mask[%vehicleID]) { $VehicleEdit::Vehicles::CompatibleModules[%vehicleID, %typeName] = $VehicleEdit::Vehicles::CompatibleModules[%vehicleID, %typeName] SPC %moduleID; %relArmor = $VehicleEdit::Modules::RelativeArmor[%typeName, %moduleID]; %newArmor = %baseArmor + %relArmor; %relShield = $VehicleEdit::Modules::RelativeShield[%typeName, %moduleID]; %newShield = %baseShield + %relShield; %relRegen = $VehicleEdit::Modules::RelativeRegen[%typeName, %moduleID]; %newRegen = %baseRegen + %relRegen; %relWeight = $VehicleEdit::Modules::RelativeWeight[%typeName, %moduleID]; %newWeight = %baseWeight + %relWeight; // Now grab the minimum and maximums if (%newWeight > $VehicleEdit::Vehicles::MaximumWeight[%vehicleID]) { $VehicleEdit::Vehicles::MaximumWeight[%vehicleID, %typeName] = %newWeight; $VehicleEdit::Vehicles::MaximumRelativeWeight[%vehicleID, %typeName] = %relWeight; } else if (%newWeight < $VehicleEdit::Vehicles::MinimumWeight[%vehicleID]) { $VehicleEdit::Vehicles::MinimumWeight[%vehicleID, %typeName] = %newWeight; $VehicleEdit::Vehicles::MinimumRelativeWeight[%vehicleID, %typeName] = %relWeight; } if (%newShield > $VehicleEdit::Vehicles::MaximumShield[%vehicleID]) { $VehicleEdit::Vehicles::MaximumShield[%vehicleID, %typeName] = %newShield; $VehicleEdit::Vehicles::MaximumRelativeShield[%vehicleID, %typeName] = %relShield; } else if (%newWeight < $VehicleEdit::Vehicles::MinimumShield[%vehicleID]) { $VehicleEdit::Vehicles::MinimumShield[%vehicleID, %typeName] = %newShield; $VehicleEdit::Vehicles::MinimumRelativeShield[%vehicleID, %typeName] = %relShield; } if (%newRegen > $VehicleEdit::Vehicles::MaximumRegen[%vehicleID]) { $VehicleEdit::Vehicles::MaximumRegen[%vehicleID, %typeName] = %newRegen; $VehicleEdit::Vehicles::MaximumRelativeRegen[%vehicleID, %typeName] = %relRegen; } else if (%newRegen < $VehicleEdit::Vehicles::MinimumRegen[%vehicleID]) { $VehicleEdit::Vehicles::MinimumRegen[%vehicleID, %typeName] = %newRegen; $VehicleEdit::Vehicles::MinimumRelativeRegen[%vehicleID, %typeName] = %relRegen; } if (%newArmor > $VehicleEdit::Vehicles::MaximumArmor[%vehicleID]) { $VehicleEdit::Vehicles::MaximumArmor[%vehicleID, %typeName] = %newArmor; $VehicleEdit::Vehicles::MaximumRelativeArmor[%vehicleID, %typeName] = %relArmor; } else if (%newArmor < $VehicleEdit::Vehicles::MinimumArmor[%vehicleID]) { $VehicleEdit::Vehicles::MinimumArmor[%vehicleID, %typeName] = %newArmor; $VehicleEdit::Vehicles::MinimumRelativeArmor[%vehicleID, %typeName] = %relArmor; } } } $VehicleEdit::Vehicles::CompatibleModules[%vehicleID, %typeName] = trim($VehicleEdit::Vehicles::CompatibleModules[%vehicleID, %typeName]); } // Figure out what the overall minimum and maximum values are for the vehicle // Technically isn't necessary the way TS works %currentMinRelArmor = %currentMaxRelArmor = %currentMinRelShield = %currentMaxRelShield = %currentMinRelRegen = %currentMaxRelRegen = %currentMinRelWeight = %currentMaxRelWeight = 0; for (%moduleTypeID = 0; %moduleTypeID < $VehicleEdit::Modules::TypeCount; %moduleTypeID++) { %typeName = $VehicleEdit::Modules::Types[%moduleTypeID]; %currentMinRelArmor += $VehicleEdit::Vehicles::MinimumRelativeArmor[%vehicleID, %typeName]; %currentMaxRelArmor += $VehicleEdit::Vehicles::MaximumRelativeArmor[%vehicleID, %typeName]; %currentMinRelRegen += $VehicleEdit::Vehicles::MinimumRelativeRegen[%vehicleID, %typeName]; %currentMaxRelRegen += $VehicleEdit::Vehicles::MaximumRelativeRegen[%vehicleID, %typeName]; %currentMinRelShield += $VehicleEdit::Vehicles::MinimumRelativeShield[%vehicleID, %typeName]; %currentMaxRelShield += $VehicleEdit::Vehicles::MaximumRelativeShield[%vehicleID, %typeName]; %currentMinRelWeight += $VehicleEdit::Vehicles::MinimumRelativeWeight[%vehicleID, %typeName]; %currentMaxRelWeight += $VehicleEdit::Vehicles::MaximumRelativeWeight[%vehicleID, %typeName]; } // After all this, assign the overall minimums and maximums $VehicleEdit::Vehicles::MaximumArmor[%vehicleID] = %baseArmor + %currentMaxRelArmor; $VehicleEdit::Vehicles::MinimumArmor[%vehicleID] = %baseArmor + %currentMinRelArmor; $VehicleEdit::Vehicles::MaximumRegen[%vehicleID] = %baseArmor + %currentMaxRelRegen; $VehicleEdit::Vehicles::MinimumRegen[%vehicleID] = %baseArmor + %currentMinRelRegen; $VehicleEdit::Vehicles::MaximumWeight[%vehicleID] = %baseArmor + %currentMaxRelWeight; $VehicleEdit::Vehicles::MinimumWeight[%vehicleID] = %baseArmor + %currentMinRelWeight; $VehicleEdit::Vehicles::MaximumShield[%vehicleID] = %baseArmor + %currentMaxRelShield; $VehicleEdit::Vehicles::MinimumShield[%vehicleID] = %baseArmor + %currentMinRelShield; } // Now foreach vehicle we set preset defaults for (%vehicleID = 0; %vehicleID < $VehicleEdit::Vehicles::Count; %vehicleID++) for (%presetID = 1; %presetID < 6; %presetID++) if ($VehicleEdit::Presets::Name[%vehicleID, %presetID] $= "") $VehicleEdit::Presets::Name[%vehicleID, %presetID] = "Preset " @ %presetID; } function VehicleEdit::checkPresetsActive() { %active = $VehicleEdit::WeaponSelectionActive || $VehicleEdit::ModuleSelectionActive; VehiclePreset1.setActive(%active); VehiclePreset2.setActive(%active); VehiclePreset3.setActive(%active); VehiclePreset4.setActive(%active); VehiclePreset5.setActive(%active); VehicleEditPresetName.setActive(%active); } function VehicleEdit::onTabSelect(%id) { %selected = nameToID("VehiclePreset" @ %id); for (%iteration = 1; %iteration < 6; %iteration++) { %toggled = nameToID("VehiclePreset" @ %iteration); %toggled.setValue(false); } %selected.setValue(true); $VehicleEdit::SelectedPreset[$VehicleEdit::CurrentVehicleSelection] = %id; %vehicleID = $VehicleEdit::CurrentVehicleSelection; %vehicleName = $VehicleEdit::Vehicles::Name[%vehicleID]; // Set the preset name text VehicleEditPresetName.setText($VehicleEdit::Presets::Name[%vehicleID, %id]); // Set default preset values and load them for (%weaponSlot = 0; %weaponSlot < $VehicleEdit::Vehicles::Slots::Count[%vehicleID]; %weaponSlot++) { if ($VehicleEdit::Presets::Weapon[%vehicleName, %id, %weaponSlot] $= "") $VehicleEdit::Presets::Weapon[%vehicleName, %id, %weaponSlot] = $VehicleEdit::Weapons::Name[getWord($VehicleEdit::Vehicles::CompatibleWeapons[%vehicleID, %weaponSlot], 0)]; if ($VehicleEdit::Presets::Firegroup[%vehicleName, %id, %weaponSlot] $= "") $VehicleEdit::Presets::Firegroup[%vehicleName, %id, %weaponSlot] = 15; $VehicleEdit::CurrentSelectedFiregroup[%weaponSlot] = $VehicleEdit::Presets::Firegroup[%vehicleName, %id, %weaponSlot]; $VehicleEdit::CurrentWeaponSelection[%weaponSlot] = $VehicleEdit::Weapons::NameToID[$VehicleEdit::Presets::Weapon[%vehicleName, %id, %weaponSlot]]; } for (%moduleTypeID = 0; %moduleTypeID < $VehicleEdit::Modules::TypeCount; %moduleTypeID++) { %typeName = $VehicleEdit::Modules::Types[%moduleTypeID]; if ($VehicleEdit::Presets::Module[%vehicleName, %id, %typeName] $= "") $VehicleEdit::Presets::Module[%vehicleName, %id, %typeName] = $VehicleEdit::Modules::Name[%typeName, getWord($VehicleEdit::Vehicles::CompatibleModules[%vehicleID, %typeName], 0)]; $VehicleEdit::CurrentModuleSelection[%typeName] = $VehicleEdit::Modules::NameToID[%typeName, $VehicleEdit::Presets::Module[%vehicleName, %id, %typeName]]; } VehicleEdit::ModuleTypeChanged(); VehicleEdit::ModuleSlotChanged(); VehicleEdit::WeaponSlotChanged(); } function VehicleEdit::onFiregroupToggled(%bit) { %slot = VehicleSlotSelection.getValue(); %mask = FiregroupAlpha.getValue() | (FiregroupBeta.getValue() << 1) | (FiregroupCharlie.getValue() << 2) | (FiregroupDelta.getValue() << 3); $VehicleEdit::CurrentSelectedFiregroup[%slot] = %mask; } function VehicleEdit::setWeaponSelectionActive(%active) { FiregroupAlpha.setActive(%active); FiregroupBeta.setActive(%active); FiregroupCharlie.setActive(%active); FiregroupDelta.setActive(%active); VehicleSlotSelection.setActive(%active); if (!%active) VehicleWeaponSelection.setText(""); VehicleWeaponSelection.setActive(%active); VehicleSlotMinimumText.setVisible(%active); VehicleSlotMaximumText.setVisible(%active); VehicleSlotType.setVisible(%active); VehicleSlotSize.setVisible(%active); WeaponSelectionText.setVisible(%active); if (!%active) VehicleSlotText.setValue("Not Applicable"); $VehicleEdit::WeaponSelectionActive = %active; VehicleEdit::checkPresetsActive(); } function VehicleEdit::setModuleSelectionActive(%active) { if (!%active) VehicleModuleSelection.setText(""); if (!%active) VehicleModuleType.setText(""); VehicleModuleSelection.setActive(%active); VehicleModuleType.setActive(%active); VehicleModuleArmor.setActive(%active); VehicleModuleShield.setActive(%active); VehicleModuleEnergy.setActive(%active); VehicleModuleWeight.setActive(%active); VehicleModuleArmorText.setVisible(%active); VehicleModuleShieldText.setVisible(%active); VehicleModuleEnergyText.setVisible(%active); VehicleModuleWeightText.setVisible(%active); if (%active) ModuleTypeText.setText("Module Type"); else ModuleTypeText.setText("Not Applicable"); $VehicleEdit::ModuleSelectionActive = %active; VehicleEdit::checkPresetsActive(); } function VehicleEdit::WeaponChanged() { %id = $VehicleEdit::Weapons::NameToID[VehicleWeaponSelection.getValue()]; WeaponSelectionText.setText($VehicleEdit::Weapons::WeaponTexts[%id]); %weaponSlot = VehicleSlotSelection.getValue(); // Update the current selection $VehicleEdit::CurrentWeaponSelection[%weaponSlot] = %id; } function VehicleEdit::VehicleChanged() { %name = VehicleDropdown.getValue(); %name = strReplace(%name, " ", "_"); %id = $VehicleEdit::Vehicles::NameToID[%name]; $VehicleEdit::CurrentVehicleSelection = $VehicleEdit::Vehicles::NameToID[%name]; if ($VehicleEdit::SelectedPreset[%id] $= "") $VehicleEdit::SelectedPreset[%id] = 1; VehicleEdit::onTabSelect($VehicleEdit::SelectedPreset[%id]); // Update slider values VehicleEdit::CurrentVehicleArmorChanged(); VehicleEdit::CurrentVehicleShieldChanged(); VehicleEdit::CurrentVehicleRegenChanged(); VehicleEdit::CurrentVehicleWeightChanged(); // Rename all of the tabs for (%presetID = 1; %presetID < 6; %presetID++) { %tab = nameToID("VehiclePreset" @ %presetID); %tab.setText($VehicleEdit::Presets::Name[%id, %presetID]); } // Update the slot slider if ($VehicleEdit::Vehicles::Slots::Count[%id] == 0) VehicleEdit::setWeaponSelectionActive(false); else { VehicleEdit::setWeaponSelectionActive(true); // Select the first weapon slot VehicleSlotSelection.setValue(0); VehicleEdit::WeaponSlotChanged(); VehicleSlotMaximumText.setText("Slot" SPC $VehicleEdit::Vehicles::Slots::Count[%id]); VehicleSlotSelection.ticks = $VehicleEdit::Vehicles::Slots::Count[%id]; VehicleSlotSelection.range = "0" SPC $VehicleEdit::Vehicles::Slots::Count[%id] - 1; VehicleSlotSelection.setValue(getWord(VehicleSlotSelection.range, 0)); // First, destroy the old labels for (%iteration = 0; %iteration < VehicleSlotSelection.tickLabelCount; %iteration++) VehicleSlotSelection.tickLabel[%iteration].delete(); // Put down new ones VehicleSlotSelection.tickLabelCount = $VehicleEdit::Vehicles::Slots::Count[%id]; %sliderExtent = VehicleSlotSelection.getExtent(); %sliderWidth = getWord(%sliderExtent, 0); %sliderHeight = getWord(%sliderExtent, 1); %sliderStart = VehicleSlotSelection.getPosition(); %sliderStart = setWord(%sliderStart, 1, getWord(%sliderStart, 1) + 19); %sliderEnd = (getWord(%sliderStart, 0) + %sliderWidth) SPC (%sliderHeight + 10); for (%iteration = 0; %iteration < VehicleSlotSelection.tickLabelCount; %iteration++) { // Ticks are just percentages across the slider, so we just apply them across // the slider %percent = %iteration / (VehicleSlotSelection.tickLabelCount - 1); %distance = %sliderWidth * %percent; // This is just the start position, we need to apply an offset by -(width / 2) %labelText = (%iteration + 1); %labelPosition = (getWord(%sliderStart, 0) + %distance) SPC getWord(%sliderStart, 1); %labelWidth = strlen(%labelText) * 5; if (%iteration != VehicleSlotSelection.tickLabelCount - 1) %labelText = %labelText @ "-------"; echo(%labelWidth); %labelPosition = setWord(%labelPosition, 0, getWord(%labelPosition, 0) - (%labelWidth / 2)); %label = new GuiMLTextCtrl() { profile = "ShellTextProfile"; horizSizing = "right"; vertSizing = "bottom"; extent = "50 36"; minExtent = "8 8"; visible = "1"; hideCursor = "0"; helpTag = "0"; lineSpacing = "2"; allowColorChars = "0"; }; VehicleSlotSelection.tickLabel[%iteration] = %label; FieldWeaponInfo.add(%label); %label.setText(%labelText); %label.setPosition(getWord(%labelPosition, 0), getWord(%labelPosition, 1)); } } // Sync the preview model VehiclePreview.setModel($VehicleEdit::Vehicles::ShapeName[$VehicleEdit::CurrentVehicleSelection], ""); // Populate the module types VehicleModuleType.clear(); %moduleTypeCount = 0; for (%iteration = 0; %iteration < $VehicleEdit::Modules::TypeCount; %iteration++) { %type = $VehicleEdit::Modules::Types[%iteration]; // And then for each type we check to see if there's any compatible Modules for (%moduleID = 0; %moduleID < $VehicleEdit::Modules::Count[%type]; %moduleID++) { if ($VehicleEdit::Modules::VehicleMask[%type, %moduleID] & $VehicleEdit::Vehicles::Mask[%id]) { VehicleModuleType.add(%type, %moduleTypeCount); %moduleTypeCount++; break; } } } if (%moduleTypeCount == 0) VehicleEdit::setModuleSelectionActive(false); else { VehicleEdit::setModuleSelectionActive(true); VehicleModuleType.setSelected(0); VehicleEdit::ModuleTypeChanged(); VehicleEdit::ModuleSlotChanged(); } } function VehicleEdit::CurrentVehicleArmorChanged() { VehicleCurrentArmor.range = "0" SPC $VehicleEdit::Vehicles::BaseArmor[$VehicleEdit::CurrentVehicleSelection]; VehicleCurrentArmor.setValue(getWord(VehicleCurrentArmor.range, 1) / 2); VehicleCurrentArmorText.setText(VehicleCurrentArmor.getValue() SPC "Units"); } function VehicleEdit::CurrentVehicleShieldChanged() { VehicleCurrentShield.range = "0" SPC $VehicleEdit::Vehicles::BaseShield[$VehicleEdit::CurrentVehicleSelection]; VehicleCurrentShield.setValue(getWord(VehicleCurrentShield.range, 1) / 2); VehicleCurrentShieldText.setText(VehicleCurrentShield.getValue() SPC "Units"); } function VehicleEdit::CurrentVehicleRegenChanged() { VehicleCurrentRegen.range = "0" SPC $VehicleEdit::Vehicles::BaseRegen[$VehicleEdit::CurrentVehicleSelection]; VehicleCurrentRegen.setValue(getWord(VehicleCurrentRegen.range, 1) / 2); VehicleCurrentRegenText.setText(VehicleCurrentRegen.getValue() SPC "Units"); } function VehicleEdit::CurrentVehicleWeightChanged() { VehicleCurrentWeight.range = "0" SPC $VehicleEdit::Vehicles::BaseWeight[$VehicleEdit::CurrentVehicleSelection]; VehicleCurrentWeight.setValue(getWord(VehicleCurrentWeight.range, 1) / 2); VehicleCurrentWeightText.setText(VehicleCurrentWeight.getValue() SPC "Lbs"); } function VehicleEdit::WeaponSlotChanged() { %val = mFloor(VehicleSlotSelection.getValue()); // Up to max - 1 for identification %max = getWord(VehicleSlotSelection.range, 1); VehicleSlotText.setText("Weapon Slot" SPC (%val + 1)); // Now we populate the weapon list with compatible weapons VehicleWeaponSelection.clear(); %weaponCount = 0; for (%iteration = 0; %iteration < $VehicleEdit::Weapons::Count; %iteration++) { if ($VehicleEdit::Vehicles::Slots::TypeMask[$VehicleEdit::CurrentVehicleSelection, %val] & $VehicleEdit::Weapons::TypeMask[%iteration] && $VehicleEdit::Vehicles::Slots::SizeMask[$VehicleEdit::CurrentVehicleSelection, %val] & $VehicleEdit::Weapons::SizeMask[%iteration]) { VehicleWeaponSelection.add($VehicleEdit::Weapons::Name[%iteration], %weaponCount); %weaponCount++; } } // Set the weapon selection accordingly %weaponName = $VehicleEdit::Weapons::Name[$VehicleEdit::CurrentWeaponSelection[%val]]; %selectedID = VehicleWeaponSelection.getIDByText(%weaponName); // Check Fire Groups %vehicleName = $VehicleEdit::Vehicles::Name[$VehicleEdit::CurrentVehicleSelection]; // Update the fire group check boxes FireGroupAlpha.setValue($VehicleEdit::CurrentSelectedFiregroup[%val] & 1); FireGroupBeta.setValue($VehicleEdit::CurrentSelectedFiregroup[%val] & 2); FireGroupCharlie.setValue($VehicleEdit::CurrentSelectedFiregroup[%val] & 4); FireGroupDelta.setValue($VehicleEdit::CurrentSelectedFiregroup[%val] & 8); VehicleWeaponSelection.setSelected(%selectedID); VehicleEdit::WeaponChanged(); } function VehicleEdit::ModuleTypeChanged() { %type = VehicleModuleType.getValue(); VehicleModuleSelection.clear(); for (%iteration = 0; %iteration < $VehicleEdit::Modules::Count[%type]; %iteration++) VehicleModuleSelection.add($VehicleEdit::Modules::Name[%type, %iteration], %iteration); %selectedID = $VehicleEdit::CurrentModuleSelection[%type]; %selectedName = $VehicleEdit::Modules::Name[%type, %selectedID]; %selectedID = VehicleModuleSelection.getIDByText(%selectedName); VehicleModuleSelection.setSelected(%selectedID); VehicleEdit::ModuleSlotChanged(); } function VehicleEdit::_processCombinedModules() { // Loop foreach module type and calculate combined relative values for (%moduleTypeID = 0; %moduleTypeID < $VehicleEdit::Modules::TypeCount; %moduleTypeID++) { %typeName = $VehicleEdit::Modules::Types[%moduleTypeID]; %selectedID = $VehicleEdit::CurrentModuleSelection[%typeName]; %relArmor += $VehicleEdit::Modules::RelativeArmor[%typeName, %selectedID]; %relShield += $VehicleEdit::Modules::RelativeShield[%typeName, %selectedID]; %relWeight += $VehicleEdit::Modules::RelativeWeight[%typeName, %selectedID]; %relRegen += $VehicleEdit::Modules::RelativeRegen[%typeName, %selectedID]; } // Now update the sliders %vehicleID = $VehicleEdit::CurrentVehicleSelection; // Armor %baseArmor = $VehicleEdit::Vehicles::BaseArmor[%vehicleID]; %minimumArmor = $VehicleEdit::Vehicles::MinimumArmor[%vehicleID]; %maximumArmor = $VehicleEdit::Vehicles::MaximumArmor[%vehicleID]; VehicleEdit::_processModuleAffects(VehicleCurrentArmorText, VehicleCurrentArmor, %minimumArmor, %maximumArmor, %baseArmor, %relArmor, false, true); // Regen %baseRegen = $VehicleEdit::Vehicles::BaseRegen[%vehicleID]; %minimumRegen = $VehicleEdit::Vehicles::MinimumRegen[%vehicleID]; %maximumRegen = $VehicleEdit::Vehicles::MaximumRegen[%vehicleID]; VehicleEdit::_processModuleAffects(VehicleCurrentRegenText, VehicleCurrentRegen, %minimumRegen, %maximumRegen, %baseRegen, %relRegen, false, true); // Weight %baseWeight = $VehicleEdit::Vehicles::BaseRegen[%vehicleID]; %minimumWeight = $VehicleEdit::Vehicles::MinimumWeight[%vehicleID]; %maximumWeight = $VehicleEdit::Vehicles::MaximumWeight[%vehicleID]; VehicleEdit::_processModuleAffects(VehicleCurrentWeightText, VehicleCurrentWeight, %minimumWeight, %maximumWeight, %baseWeight, %relWeight, true, true); // Shield %baseShield = $VehicleEdit::Vehicles::BaseShield[%vehicleID]; %minimumShield = $VehicleEdit::Vehicles::MinimumShield[%vehicleID]; %maximumShield = $VehicleEdit::Vehicles::MaximumShield[%vehicleID]; VehicleEdit::_processModuleAffects(VehicleCurrentShieldText, VehicleCurrentShield, %minimumShield, %maximumShield, %baseShield, %relShield, false, true); } function VehicleEdit::_processModuleAffects(%text, %slider, %minVal, %maxVal, %baseVal, %relVal, %invert, %displayBase) { %slider.range = "0 1"; %newValue = %baseVal + %relVal; %sliderValue = mVariate(%minVal, %maxVal, %baseVal, %newValue); %slider.setValue(%sliderValue); if (%relVal == 0) { %displayed = "(No Change)"; if (%displayBase) %displayed = %baseVal SPC %displayed; } else { %colors[0] = "<color:FF0000>"; %colors[1] = "<color:00FF00>"; %color = %colors[%relVal > 0 ^ %invert]; %displayed = %relVal > 0 ? %color @ "+" @ %relVal SPC "Units" : %color @ %relVal SPC "Units"; if (%displayBase) %displayed = (%baseVal + %relVal) SPC %color @ "(" @ %displayed @ ")"; } %text.setText(%displayed); } function VehicleEdit::ModuleSlotChanged() { %moduleType = VehicleModuleType.getValue(); %vehicleID = $VehicleEdit::CurrentVehicleSelection; %moduleName = VehicleModuleSelection.getValue(); %moduleID = $VehicleEdit::Modules::NameToID[%moduleType, %moduleName]; // Update the current selection $VehicleEdit::CurrentModuleSelection[%moduleType] = %moduleID; // Armor %baseArmor = $VehicleEdit::Vehicles::BaseArmor[%vehicleID]; %relativeArmor = $VehicleEdit::Modules::RelativeArmor[%moduleType, %moduleID]; %minimumArmor = $VehicleEdit::Vehicles::MinimumArmor[%vehicleID, %moduleType]; %maximumArmor = $VehicleEdit::Vehicles::MaximumArmor[%vehicleID, %moduleType]; VehicleEdit::_processModuleAffects(VehicleModuleArmorText, VehicleModuleArmor, %minimumArmor, %maximumArmor, %baseArmor, %relativeArmor, false); // Shield %baseShield = $VehicleEdit::Vehicles::BaseShield[%vehicleID]; %relativeShield = $VehicleEdit::Modules::RelativeShield[%moduleType, %moduleID]; %minimumShield = $VehicleEdit::Vehicles::MinimumShield[%vehicleID, %moduleType]; %maximumShield = $VehicleEdit::Vehicles::MaximumShield[%vehicleID, %moduleType]; VehicleEdit::_processModuleAffects(VehicleModuleShieldText, VehicleModuleShield, %minimumShield, %maximumShield, %baseShield, %relativeShield, false); // Energy %baseRegen = $VehicleEdit::Vehicles::BaseRegen[%vehicleID]; %relativeRegen = $VehicleEdit::Modules::RelativeRegen[%moduleType, %moduleID]; %minimumRegen = $VehicleEdit::Vehicles::MinimumRegen[%vehicleID, %moduleType]; %maximumRegen = $VehicleEdit::Vehicles::MaximumRegen[%vehicleID, %moduleType]; VehicleEdit::_processModuleAffects(VehicleModuleEnergyText, VehicleModuleEnergy, %minimumRegen, %maximumRegen, %baseRegen, %relativeRegen, false); // Weight %baseWeight = $VehicleEdit::Vehicles::BaseWeight[%vehicleID]; %relativeWeight = $VehicleEdit::Modules::RelativeWeight[%moduleType, %moduleID]; %minimumWeight = $VehicleEdit::Vehicles::MinimumWeight[%vehicleID, %moduleType]; %maximumWeight = $VehicleEdit::Vehicles::MaximumWeight[%vehicleID, %moduleType]; VehicleEdit::_processModuleAffects(VehicleModuleWeightText, VehicleModuleWeight, %minimumWeight, %maximumWeight, %baseWeight, %relativeWeight, true); VehicleEdit::_processCombinedModules(); } function VehicleEdit::Exit() { canvas.popDialog(); } function VehicleEdit::Save() { // Save preset values %vehicleID = $VehicleEdit::CurrentVehicleSelection; %vehicleName = $VehicleEdit::Vehicles::Name[%vehicleID]; %presetID = $VehicleEdit::SelectedPreset[$VehicleEdit::CurrentVehicleSelection]; for (%weaponSlot = 0; %weaponSlot < $VehicleEdit::Vehicles::Slots::Count[%vehicleID]; %weaponSlot++) { %weaponID = $VehicleEdit::CurrentWeaponSelection[%weaponSlot]; $VehicleEdit::Presets::Weapon[%vehicleName, %presetID, %weaponSlot] = $VehicleEdit::Weapons::Name[%weaponID]; $VehicleEdit::Presets::Firegroup[%vehicleName, %presetID, %weaponSlot] = $VehicleEdit::CurrentSelectedFiregroup[%weaponSlot]; } for (%moduleTypeID = 0; %moduleTypeID < $VehicleEdit::Modules::TypeCount; %moduleTypeID++) { %moduleTypeName = $VehicleEdit::Modules::Types[%moduleTypeID]; $VehicleEdit::Presets::Module[%vehicleName, %presetID, %moduleTypeName] = $VehicleEdit::Modules::Name[%moduleTypeName, $VehicleEdit::CurrentModuleSelection[%moduleTypeName]]; } $VehicleEdit::Presets::Name[%vehicleID, %presetID] = VehicleEditPresetName.getValue(); nameToID("VehiclePreset" @ %presetID).setText($VehicleEdit::Presets::Name[%vehicleID, %presetID]); export("$VehicleEdit::Presets::*", "vehicleEditPresets.cs", false); } function VehicleEditDlg::onWake(%this) { VehicleEditDlg.setVisible(true); VehicleDropdown.clear(); // Repopulate the vehicles for (%iteration = 0; %iteration < $VehicleEdit::Vehicles::Count; %iteration++) VehicleDropdown.add(strReplace($VehicleEdit::Vehicles::Name[%iteration], "_", " "), %iteration); // Select the first vehicle in our list VehicleDropDown.setSelected(0); VehicleEdit::VehicleChanged(); } function VehicleEditDlg::onSleep(%this) { VehicleEditDlg.setVisible(false); } function ToggleVehicleEdit(%val) { if (%val && VehicleEditDlg.isVisible()) canvas.popDialog(); else if (%val) canvas.pushDialog(VehicleEditDlg); } package VehicleEditHooks { function OptionsDlg::onWake(%this) { if (!$VehicleEdit::BuiltBindings) { $RemapName[$RemapCount] = "Vehicle Loadout"; $RemapCmd[$RemapCount] = "ToggleVehicleEdit"; $RemapCount++; $VehicleEdit::BuiltBindings = true; } parent::onWake(%this); } function disconnect() { VehicleEdit::resetInternalDatabase(); parent::disconnect(); } }; if (!isActivePackage(VehicleEditHooks)) activatePackage(VehicleEditHooks);
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using Moq; using NUnit.Framework; using ShoppingListApp.Domain.Abstract; using ShoppingListApp.Domain.Concrete; using ShoppingListApp.Domain.Entities; namespace ShoppingListApp.Domain.Test { [TestFixture] public class ItemXmlRepositoryTest { private Mock<IRepositoryNameProvider> repositoryNameProvider; private Mock<IDataPathProvider> dataPathProvider; [SetUp] public void Init() { File.Copy(@"./ItemRepository.example.xml", @"./ItemRepository.example.orig.xml"); File.Copy(@"./ItemRepository.invalid.xml", @"./ItemRepository.invalid.orig.xml"); File.Copy(@"./ItemRepository.invalidempty.xml", @"./ItemRepository.invalidempty.orig.xml"); File.Copy(@"./ItemRepository.empty.xml", @"./ItemRepository.empty.orig.xml"); File.Copy(@"./ItemRepository.invalidxsd.xml", @"./ItemRepository.invalidxsd.orig.xml"); File.Copy(@"./ItemRepository.Category.example.xml", @"./ItemRepository.Category.example.orig.xml"); this.repositoryNameProvider = new Mock<IRepositoryNameProvider>(); this.dataPathProvider = new Mock<IDataPathProvider>(); this.dataPathProvider.Setup(provider => provider.DataPath).Returns(@"./"); } [TearDown] public static void Dispose() { Thread.Sleep(10); // otherwise access to filesystem is too fast and creates access denied File.Delete(@"./ItemRepository.example.xml"); File.Copy(@"./ItemRepository.example.orig.xml", @"./ItemRepository.example.xml"); File.Delete(@"./ItemRepository.example.orig.xml"); File.Delete(@"./ItemRepository.invalid.xml"); File.Copy(@"./ItemRepository.invalid.orig.xml", @"./ItemRepository.invalid.xml"); File.Delete(@"./ItemRepository.invalid.orig.xml"); File.Delete(@"./ItemRepository.invalidempty.xml"); File.Copy(@"./ItemRepository.invalidempty.orig.xml", @"./ItemRepository.invalidempty.xml"); File.Delete(@"./ItemRepository.invalidempty.orig.xml"); File.Delete(@"./ItemRepository.empty.xml"); File.Copy(@"./ItemRepository.empty.orig.xml", @"./ItemRepository.empty.xml"); File.Delete(@"./ItemRepository.empty.orig.xml"); File.Delete(@"./ItemRepository.invalidxsd.xml"); File.Copy(@"./ItemRepository.invalidxsd.orig.xml", @"./ItemRepository.invalidxsd.xml"); File.Delete(@"./ItemRepository.invalidxsd.orig.xml"); File.Delete(@"./ItemRepository.Category.example.xml"); File.Copy(@"./ItemRepository.Category.example.orig.xml", @"./ItemRepository.Category.example.xml"); File.Delete(@"./ItemRepository.Category.example.orig.xml"); File.Delete(@"./ItemRepository.doesnotexists.xml"); } [Test] [SetUICulture("en-US")] public void ItemRepositoryIsResetToDefaultUS_WhenXsdSchemaIsInvalid() { // Arrange this.repositoryNameProvider.Setup(x => x.RepositoryName).Returns(@"./ItemRepository.invalidxsd.xml"); // Act IEnumerable<Item> testee = (new ItemXmlRepository(this.repositoryNameProvider.Object, dataPathProvider.Object)).Repository; // Assert Assert.AreEqual(File.ReadAllText(@"./DefaultItemRepository.xml").Replace("\r\n", "\n"), File.ReadAllText(@"./ItemRepository.invalidxsd.xml").Replace("\r\n", "\n")); } [Test] [SetUICulture("fr-FR")] public void ItemRepositoryIsResetToDefaultFR_WhenXsdSchemaIsInvalid() { // Arrange this.repositoryNameProvider.Setup(x => x.RepositoryName).Returns(@"./ItemRepository.invalidxsd.xml"); // Act IEnumerable<Item> testee = (new ItemXmlRepository(this.repositoryNameProvider.Object, dataPathProvider.Object)).Repository; // Assert Assert.AreEqual(File.ReadAllText(@"./DefaultItemRepository_fr.xml").Replace("\r\n", "\n"), File.ReadAllText(@"./ItemRepository.invalidxsd.xml").Replace("\r\n", "\n")); } [Test] [SetUICulture("de-DE")] public void ItemRepositoryIsResetToDefaultDE_WhenXsdSchemaIsInvalid() { // Arrange this.repositoryNameProvider.Setup(x => x.RepositoryName).Returns(@"./ItemRepository.invalidxsd.xml"); // Act IEnumerable<Item> testee = (new ItemXmlRepository(this.repositoryNameProvider.Object, dataPathProvider.Object)).Repository; // Assert Assert.AreEqual(File.ReadAllText(@"./DefaultItemRepository_de.xml").Replace("\r\n", "\n"), File.ReadAllText(@"./ItemRepository.invalidxsd.xml").Replace("\r\n", "\n")); } [Test] public void ItemRepositoryContainsItemsFromPersistentRepository_WhenReadFromXmlFileRepository() { // Arrange IEnumerable<Item> expectedResult = new List<Item>() { new Item() { ItemId = 1, ItemName = "Item1", ItemCategory = "-" }, new Item() { ItemId = 2, ItemName = "Item2", ItemCategory = "Category1" }, new Item() { ItemId = 3, ItemName = "Item3", ItemCategory = "-" }, new Item() { ItemId = 4, ItemName = "Item4", ItemCategory = "Category325" }, new Item() { ItemId = 5, ItemName = "Item5", ItemCategory = "-" } }; this.repositoryNameProvider.Setup(x => x.RepositoryName).Returns(@"./ItemRepository.example.xml"); // Act IEnumerable<Item> testee = (new ItemXmlRepository(this.repositoryNameProvider.Object, dataPathProvider.Object)).Repository; // Assert Assert.AreEqual(5, testee.Count()); Assert.AreEqual(expectedResult.Select(Item => Item.ItemId).AsEnumerable(), testee.Select(Item => Item.ItemId).AsEnumerable()); Assert.AreEqual(expectedResult.Select(Item => Item.ItemName).AsEnumerable(), testee.Select(Item => Item.ItemName).AsEnumerable()); } [Test] public void ItemRepositoryIsEmpty_WhenReadFromEmptyXmlFileRepository() { // Arrange IEnumerable<Item> expectedResult = new List<Item>(); this.repositoryNameProvider.Setup(x => x.RepositoryName).Returns(@"./ItemRepository.empty.xml"); // Act IEnumerable<Item> testee = (new ItemXmlRepository(this.repositoryNameProvider.Object, dataPathProvider.Object)).Repository; // Assert Assert.AreEqual(0, testee.Count()); Assert.AreEqual(expectedResult.Select(Item => Item.ItemId).AsEnumerable(), testee.Select(Item => Item.ItemId).AsEnumerable()); Assert.AreEqual(expectedResult.Select(Item => Item.ItemName).AsEnumerable(), testee.Select(Item => Item.ItemName).AsEnumerable()); } [Test] [SetUICulture("en-US")] public void ItemRepositoryIsEmpty_WhenReadFromNewlyCreatedXmlFileRepository_WhichDidNotExistPreviously() { // Arrange this.repositoryNameProvider.Setup(x => x.RepositoryName).Returns(@"./ItemRepository.doesnotexists.xml"); // Act IEnumerable<Item> testee = (new ItemXmlRepository(this.repositoryNameProvider.Object, dataPathProvider.Object)).Repository; // Assert Assert.AreEqual(File.ReadAllText(@"./DefaultItemRepository.xml").Replace("\r\n", "\n"), File.ReadAllText(@"./ItemRepository.doesnotexists.xml").Replace("\r\n", "\n")); } [Test] [SetUICulture("en-US")] public void ItemRepositoryIsEmpty_WhenReadFromNewlyCreatedXmlFileRepository_WhichWasAnInvalidXmlFile() { // Arrange this.repositoryNameProvider.Setup(x => x.RepositoryName).Returns(@"./ItemRepository.invalid.xml"); // Act IEnumerable<Item> testee = (new ItemXmlRepository(this.repositoryNameProvider.Object, dataPathProvider.Object)).Repository; // Assert Assert.AreEqual(File.ReadAllText(@"./DefaultItemRepository.xml").Replace("\r\n", "\n"), File.ReadAllText(@"./ItemRepository.invalid.xml").Replace("\r\n", "\n")); } [Test] [SetUICulture("en-US")] public void ItemRepositoryIsEmpty_WhenReadFromNewlyCreatedXmlFileRepository_WhichWasAnInvalidEmptyXmlFile() { // Arrange this.repositoryNameProvider.Setup(x => x.RepositoryName).Returns(@"./ItemRepository.invalidempty.xml"); // Act IEnumerable<Item> testee = (new ItemXmlRepository(this.repositoryNameProvider.Object, dataPathProvider.Object)).Repository; // Assert Assert.AreEqual(File.ReadAllText(@"./DefaultItemRepository.xml").Replace("\r\n", "\n"), File.ReadAllText(@"./ItemRepository.invalidempty.xml").Replace("\r\n", "\n")); } [Test] public void ItemRepositoryIsEmpty_WhenNoPersistentRepositoryNameProviderIsAvailable() { // Arrange ItemXmlRepository testee = null; // Act // Assert Assert.Throws(typeof(ArgumentNullException), () => testee = new ItemXmlRepository(null, dataPathProvider.Object)); } [Test] public void ItemRepositoryIsEmpty_WhenNoRepositoryNameIsAvailable() { // Arrange ItemXmlRepository testee = null; this.repositoryNameProvider.Setup(x => x.RepositoryName).Returns((string)null); // Act // Assert Assert.Throws(typeof(ArgumentOutOfRangeException), () => testee = new ItemXmlRepository(this.repositoryNameProvider.Object, dataPathProvider.Object)); } [Test] public void ItemRepositoryIsEmpty_WhenEmptyRepositoryNameIsAvailable() { // Arrange ItemXmlRepository testee = null; this.repositoryNameProvider.Setup(x => x.RepositoryName).Returns(string.Empty); // Act // Assert Assert.Throws(typeof(ArgumentOutOfRangeException), () => testee = new ItemXmlRepository(this.repositoryNameProvider.Object, dataPathProvider.Object)); } [Test] public void ItemsAddedToPersistentRepository_WhenWrittenToXmlFileRepository() { // Arrange ItemXmlRepository testee = null; this.repositoryNameProvider.Setup(x => x.RepositoryName).Returns(@"./ItemRepository.example.xml"); // Act testee = new ItemXmlRepository(this.repositoryNameProvider.Object, dataPathProvider.Object); testee.Add("Item6"); testee.Save(); testee.Add("Item7"); testee.Save(); testee.Add("Item8"); testee.Save(); // Assert Assert.AreEqual(File.ReadAllText(@"./ItemRepository.Add.Expected.Xml").Replace("\r\n", "\n"), File.ReadAllText(@"./ItemRepository.example.xml").Replace("\r\n", "\n")); } [Test] public void FirstItemAddedToPersistentRepository_WhenWrittenToXmlFileRepository() { // Arrange ItemXmlRepository testee = null; this.repositoryNameProvider.Setup(x => x.RepositoryName).Returns(@"./ItemRepository.empty.xml"); // Act testee = new ItemXmlRepository(this.repositoryNameProvider.Object, dataPathProvider.Object); testee.Add("Item15"); testee.Save(); // Assert Assert.AreEqual(File.ReadAllText(@"./ItemRepository.AddFirst.Expected.Xml").Replace("\r\n", "\n"), File.ReadAllText(@"./ItemRepository.empty.xml").Replace("\r\n", "\n")); } [Test] public void InvalidItemNameThrowsException_WhenWrittenToXmlFileRepository() { // Arrange ItemXmlRepository testee = null; this.repositoryNameProvider.Setup(x => x.RepositoryName).Returns(@"./ItemRepository.example.xml"); // Act testee = new ItemXmlRepository(this.repositoryNameProvider.Object, dataPathProvider.Object); // Assert Assert.Throws(typeof(ArgumentOutOfRangeException), () => testee.Add(string.Empty)); } [Test] public void NullItemNameThrowsException_WhenWrittenToXmlFileRepository() { // Arrange ItemXmlRepository testee = null; this.repositoryNameProvider.Setup(x => x.RepositoryName).Returns(@"./ItemRepository.example.xml"); // Act testee = new ItemXmlRepository(this.repositoryNameProvider.Object, dataPathProvider.Object); // Assert Assert.Throws(typeof(ArgumentOutOfRangeException), () => testee.Add(null)); } [Test] public void ItemRemovedFromPersistentRepository_WhenWrittenToXmlFileRepository() { // Arrange ItemXmlRepository testee = null; this.repositoryNameProvider.Setup(x => x.RepositoryName).Returns(@"./ItemRepository.example.xml"); // Act testee = new ItemXmlRepository(this.repositoryNameProvider.Object, dataPathProvider.Object); testee.Remove(3); // Remove ItemId 3 testee.Save(); // Assert Assert.AreEqual(File.ReadAllText(@"./ItemRepository.Remove.Expected.Xml").Replace("\r\n", "\n"), File.ReadAllText(@"./ItemRepository.example.xml").Replace("\r\n", "\n")); } [Test] public void NonExistingItemRemovedFromPersistentRepositoryThrowsException_WhenWrittenToXmlFileRepository() { // Arrange ItemXmlRepository testee = null; this.repositoryNameProvider.Setup(x => x.RepositoryName).Returns(@"./ItemRepository.empty.xml"); // Act testee = new ItemXmlRepository(this.repositoryNameProvider.Object, dataPathProvider.Object); // Assert Assert.Throws(typeof(ArgumentOutOfRangeException), () => testee.Remove(1)); } [Test] public void ItemModifiedOnPersistentRepository_WhenWrittenToXmlFileRepository() { // Arrange ItemXmlRepository testee = null; uint itemId = 4; string itemName = "Item12"; this.repositoryNameProvider.Setup(x => x.RepositoryName).Returns(@"./ItemRepository.example.xml"); // Act testee = new ItemXmlRepository(this.repositoryNameProvider.Object, dataPathProvider.Object); testee.ModifyName(itemId, itemName); testee.Save(); // Assert Assert.AreEqual(File.ReadAllText(@"./ItemRepository.Modified.Expected.Xml").Replace("\r\n", "\n"), File.ReadAllText(@"./ItemRepository.example.xml").Replace("\r\n", "\n")); } [Test] public void NonExistingItemModifiedOnPersistentRepositoryThrowsException_WhenWrittenToXmlFileRepository() { // Arrange ItemXmlRepository testee = null; uint itemId = 4; string itemName = "Item12"; this.repositoryNameProvider.Setup(x => x.RepositoryName).Returns(@"./ItemRepository.empty.xml"); // Act testee = new ItemXmlRepository(this.repositoryNameProvider.Object, dataPathProvider.Object); // Assert Assert.Throws(typeof(ArgumentOutOfRangeException), () => testee.ModifyName(itemId, itemName)); } [Test] public void InvalidItemNameModifiedOnPersistentRepositoryThrowsException_WhenWrittenToXmlFileRepository() { // Arrange ItemXmlRepository testee = null; uint itemId = 1; this.repositoryNameProvider.Setup(x => x.RepositoryName).Returns(@"./ItemRepository.example.xml"); // Act testee = new ItemXmlRepository(this.repositoryNameProvider.Object, dataPathProvider.Object); // Assert Assert.Throws(typeof(ArgumentOutOfRangeException), () => testee.ModifyName(itemId, null)); } [Test] public void ItemCategoryModifiedOnPersistentRepository_WhenWrittenToXmlFileRepository() { // Arrange ItemXmlRepository testee = null; uint itemId = 4; string itemCategory = "Others"; this.repositoryNameProvider.Setup(x => x.RepositoryName).Returns(@"./ItemRepository.example.xml"); // Act testee = new ItemXmlRepository(this.repositoryNameProvider.Object, dataPathProvider.Object); testee.ChangeItemCategory(itemId, itemCategory); testee.Save(); // Assert Assert.AreEqual(File.ReadAllText(@"./ItemRepository.ModifiedCategory.Expected.Xml").Replace("\r\n", "\n"), File.ReadAllText(@"./ItemRepository.example.xml").Replace("\r\n", "\n")); } [Test] public void NonExistingItemCategoryModifiedOnPersistentRepositoryThrowsException_WhenWrittenToXmlFileRepository() { // Arrange ItemXmlRepository testee = null; uint itemId = 4; string itemCategory = "Others"; this.repositoryNameProvider.Setup(x => x.RepositoryName).Returns(@"./ItemRepository.empty.xml"); // Act testee = new ItemXmlRepository(this.repositoryNameProvider.Object, dataPathProvider.Object); // Assert Assert.Throws(typeof(ArgumentOutOfRangeException), () => testee.ChangeItemCategory(itemId, itemCategory)); } [Test] public void InvalidItemCategoryModifiedOnPersistentRepositoryThrowsException_WhenWrittenToXmlFileRepository() { // Arrange ItemXmlRepository testee = null; uint itemId = 1; this.repositoryNameProvider.Setup(x => x.RepositoryName).Returns(@"./ItemRepository.example.xml"); // Act testee = new ItemXmlRepository(this.repositoryNameProvider.Object, dataPathProvider.Object); // Assert Assert.Throws(typeof(ArgumentOutOfRangeException), () => testee.ChangeItemCategory(itemId, null)); } [Test] public void ItemRepositoryIsEmpty_WhenResetToEmpty() { // Arrange this.repositoryNameProvider.Setup(x => x.RepositoryName).Returns(@"./ItemRepository.example.xml"); // Act ItemXmlRepository testee = new ItemXmlRepository(this.repositoryNameProvider.Object, dataPathProvider.Object); testee.ResetToEmpty(); // Assert Assert.AreEqual(File.ReadAllText(@"./ItemRepository.empty.xml").Replace("\r\n", "\n"), File.ReadAllText(@"./ItemRepository.example.xml").Replace("\r\n", "\n")); } [Test] [SetUICulture("en-US")] public void ItemRepositoryContainsDefaults_WhenResetToDefaults() { // Arrange this.repositoryNameProvider.Setup(x => x.RepositoryName).Returns(@"./ItemRepository.example.xml"); // Act ItemXmlRepository testee = new ItemXmlRepository(this.repositoryNameProvider.Object, dataPathProvider.Object); testee.ResetToDefault(); // Assert Assert.AreEqual(File.ReadAllText(@"./DefaultItemRepository.xml").Replace("\r\n", "\n"), File.ReadAllText(@"./ItemRepository.example.xml").Replace("\r\n", "\n")); } [Test] [SetUICulture("en-US")] public void ItemRepositoryCategoryIsNotUpdated_WhenOldCategoryIsNotInUse() { // Arrange this.repositoryNameProvider.Setup(x => x.RepositoryName).Returns(@"./ItemRepository.example.xml"); // Act ItemXmlRepository testee = new ItemXmlRepository(this.repositoryNameProvider.Object, dataPathProvider.Object); testee.UpdateChangedCategoryName(null, "newCategoryName"); // Assert Assert.AreEqual(File.ReadAllText(@"./ItemRepository.example.xml").Replace("\r\n", "\n"), File.ReadAllText(@"./ItemRepository.example.xml").Replace("\r\n", "\n")); } [Test] public void ItemRepositoryCategoryThrowsArgumentOutOfRangeException_WhenNewCategoryIsInvalid() { // Arrange this.repositoryNameProvider.Setup(x => x.RepositoryName).Returns(@"./ItemRepository.example.xml"); // Act ItemXmlRepository testee = new ItemXmlRepository(this.repositoryNameProvider.Object, dataPathProvider.Object); // Assert Assert.Throws(typeof(ArgumentOutOfRangeException), () => testee.UpdateChangedCategoryName("Category1", null)); } [Test] [SetUICulture("en-US")] public void ItemRepositoryCategoryIsUpdatedForAllItemsInTheCategory_WhenOldCategoryIsRenamedToNewCategory() { // Arrange this.repositoryNameProvider.Setup(x => x.RepositoryName).Returns(@"./ItemRepository.Category.example.xml"); // Act ItemXmlRepository testee = new ItemXmlRepository(this.repositoryNameProvider.Object, dataPathProvider.Object); testee.UpdateChangedCategoryName("OldCategory", "newCategoryName"); testee.Save(); // Assert Assert.AreEqual(File.ReadAllText(@"./ItemRepository.UpdatedCategory.Expected.xml").Replace("\r\n", "\n"), File.ReadAllText(@"./ItemRepository.Category.example.xml").Replace("\r\n", "\n")); } } }
/** * JsonReader.cs * Stream-like access to JSON text. * * The authors disclaim copyright to this source code. For more details, see * the COPYING file included with this distribution. **/ using System; using System.Collections.Generic; using System.Globalization; using System.IO; namespace LitJson { public enum JsonToken { None, ObjectStart, PropertyName, ObjectEnd, ArrayStart, ArrayEnd, Int, Long, ULong, Double, String, Boolean, Null } public class JsonReader { private static IDictionary<int, IDictionary<int, int[]>> parse_table; private Stack<int> automaton_stack; private int current_input; private int current_symbol; private bool end_of_json; private bool end_of_input; private Lexer lexer; private bool parser_in_string; private bool parser_return; private bool read_started; private TextReader reader; private bool reader_is_owned; private object token_value; private JsonToken token; public bool AllowComments { get { return lexer.AllowComments; } set { lexer.AllowComments = value; } } public bool AllowSingleQuotedStrings { get { return lexer.AllowSingleQuotedStrings; } set { lexer.AllowSingleQuotedStrings = value; } } public bool EndOfInput { get { return end_of_input; } } public bool EndOfJson { get { return end_of_json; } } public JsonToken Token { get { return token; } } public object Value { get { return token_value; } } static JsonReader () { PopulateParseTable (); } public JsonReader (string json_text) : this (new StringReader (json_text), true) { } public JsonReader (TextReader reader) : this (reader, false) { } private JsonReader (TextReader reader, bool owned) { if (reader == null) throw new ArgumentNullException ("reader"); parser_in_string = false; parser_return = false; read_started = false; automaton_stack = new Stack<int> (); automaton_stack.Push ((int) ParserToken.End); automaton_stack.Push ((int) ParserToken.Text); lexer = new Lexer (reader); end_of_input = false; end_of_json = false; this.reader = reader; reader_is_owned = owned; } private static void PopulateParseTable () { parse_table = new Dictionary<int, IDictionary<int, int[]>> (); TableAddRow (ParserToken.Array); TableAddCol (ParserToken.Array, '[', '[', (int) ParserToken.ArrayPrime); TableAddRow (ParserToken.ArrayPrime); TableAddCol (ParserToken.ArrayPrime, '"', (int) ParserToken.Value, (int) ParserToken.ValueRest, ']'); TableAddCol (ParserToken.ArrayPrime, '[', (int) ParserToken.Value, (int) ParserToken.ValueRest, ']'); TableAddCol (ParserToken.ArrayPrime, ']', ']'); TableAddCol (ParserToken.ArrayPrime, '{', (int) ParserToken.Value, (int) ParserToken.ValueRest, ']'); TableAddCol (ParserToken.ArrayPrime, (int) ParserToken.Number, (int) ParserToken.Value, (int) ParserToken.ValueRest, ']'); TableAddCol (ParserToken.ArrayPrime, (int) ParserToken.True, (int) ParserToken.Value, (int) ParserToken.ValueRest, ']'); TableAddCol (ParserToken.ArrayPrime, (int) ParserToken.False, (int) ParserToken.Value, (int) ParserToken.ValueRest, ']'); TableAddCol (ParserToken.ArrayPrime, (int) ParserToken.Null, (int) ParserToken.Value, (int) ParserToken.ValueRest, ']'); TableAddRow (ParserToken.Object); TableAddCol (ParserToken.Object, '{', '{', (int) ParserToken.ObjectPrime); TableAddRow (ParserToken.ObjectPrime); TableAddCol (ParserToken.ObjectPrime, '"', (int) ParserToken.Pair, (int) ParserToken.PairRest, '}'); TableAddCol (ParserToken.ObjectPrime, '}', '}'); TableAddRow (ParserToken.Pair); TableAddCol (ParserToken.Pair, '"', (int) ParserToken.String, ':', (int) ParserToken.Value); TableAddRow (ParserToken.PairRest); TableAddCol (ParserToken.PairRest, ',', ',', (int) ParserToken.Pair, (int) ParserToken.PairRest); TableAddCol (ParserToken.PairRest, '}', (int) ParserToken.Epsilon); TableAddRow (ParserToken.String); TableAddCol (ParserToken.String, '"', '"', (int) ParserToken.CharSeq, '"'); TableAddRow (ParserToken.Text); TableAddCol (ParserToken.Text, '[', (int) ParserToken.Array); TableAddCol (ParserToken.Text, '{', (int) ParserToken.Object); TableAddRow (ParserToken.Value); TableAddCol (ParserToken.Value, '"', (int) ParserToken.String); TableAddCol (ParserToken.Value, '[', (int) ParserToken.Array); TableAddCol (ParserToken.Value, '{', (int) ParserToken.Object); TableAddCol (ParserToken.Value, (int) ParserToken.Number, (int) ParserToken.Number); TableAddCol (ParserToken.Value, (int) ParserToken.True, (int) ParserToken.True); TableAddCol (ParserToken.Value, (int) ParserToken.False, (int) ParserToken.False); TableAddCol (ParserToken.Value, (int) ParserToken.Null, (int) ParserToken.Null); TableAddRow (ParserToken.ValueRest); TableAddCol (ParserToken.ValueRest, ',', ',', (int) ParserToken.Value, (int) ParserToken.ValueRest); TableAddCol (ParserToken.ValueRest, ']', (int) ParserToken.Epsilon); } private static void TableAddCol (ParserToken row, int col, params int[] symbols) { parse_table[(int) row].Add (col, symbols); } private static void TableAddRow (ParserToken rule) { parse_table.Add ((int) rule, new Dictionary<int, int[]> ()); } private void ProcessNumber (string number) { var numStyle = NumberStyles.Any; var culture = new CultureInfo("en-US"); if (number.IndexOf('.') != -1 || number.IndexOf('e') != -1 || number.IndexOf('E') != -1) { double n_double; if (Double.TryParse(number, numStyle, culture, out n_double)) { token = JsonToken.Double; token_value = n_double; return; } } int n_int32; if (Int32.TryParse(number, numStyle, culture, out n_int32)) { token = JsonToken.Int; token_value = n_int32; return; } long n_int64; if (Int64.TryParse(number, out n_int64)) { token = JsonToken.Long; token_value = n_int64; return; } ulong n_uint64; if (UInt64.TryParse(number, numStyle, culture, out n_uint64)) { token = JsonToken.ULong; token_value = n_uint64; return; } // Shouldn't happen, but just in case, return something token = JsonToken.Int; token_value = 0; } private void ProcessSymbol () { if (current_symbol == '[') { token = JsonToken.ArrayStart; parser_return = true; } else if (current_symbol == ']') { token = JsonToken.ArrayEnd; parser_return = true; } else if (current_symbol == '{') { token = JsonToken.ObjectStart; parser_return = true; } else if (current_symbol == '}') { token = JsonToken.ObjectEnd; parser_return = true; } else if (current_symbol == '"') { if (parser_in_string) { parser_in_string = false; parser_return = true; } else { if (token == JsonToken.None) token = JsonToken.String; parser_in_string = true; } } else if (current_symbol == (int) ParserToken.CharSeq) { token_value = lexer.StringValue; } else if (current_symbol == (int) ParserToken.False) { token = JsonToken.Boolean; token_value = false; parser_return = true; } else if (current_symbol == (int) ParserToken.Null) { token = JsonToken.Null; parser_return = true; } else if (current_symbol == (int) ParserToken.Number) { ProcessNumber (lexer.StringValue); parser_return = true; } else if (current_symbol == (int) ParserToken.Pair) { token = JsonToken.PropertyName; } else if (current_symbol == (int) ParserToken.True) { token = JsonToken.Boolean; token_value = true; parser_return = true; } } private bool ReadToken () { if (end_of_input) return false; lexer.NextToken (); if (lexer.EndOfInput) { Close (); return false; } current_input = lexer.Token; return true; } public void Close () { if (end_of_input) return; end_of_input = true; end_of_json = true; if (reader_is_owned) reader.Dispose (); reader = null; } public bool Read () { if (end_of_input) return false; if (end_of_json) { end_of_json = false; automaton_stack.Clear (); automaton_stack.Push ((int) ParserToken.End); automaton_stack.Push ((int) ParserToken.Text); } parser_in_string = false; parser_return = false; token = JsonToken.None; token_value = null; if (! read_started) { read_started = true; if (! ReadToken ()) return false; } int[] entry_symbols; while (true) { if (parser_return) { if (automaton_stack.Peek () == (int) ParserToken.End) end_of_json = true; return true; } current_symbol = automaton_stack.Pop (); ProcessSymbol (); if (current_symbol == current_input) { if (! ReadToken ()) { if (automaton_stack.Peek () != (int) ParserToken.End) throw new JsonException ( "Input doesn't evaluate to proper JSON text"); if (parser_return) return true; return false; } continue; } try { entry_symbols = parse_table[current_symbol][current_input]; } catch (KeyNotFoundException e) { throw new JsonException ((ParserToken) current_input, e); } if (entry_symbols[0] == (int) ParserToken.Epsilon) continue; for (int i = entry_symbols.Length - 1; i >= 0; i--) automaton_stack.Push (entry_symbols[i]); } } } }
namespace AutoMapper.Execution { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Configuration; using static System.Linq.Expressions.Expression; using static Internal.ExpressionFactory; using static ExpressionBuilder; using System.Diagnostics; using Internal; public class TypeMapPlanBuilder { private static readonly Expression<Func<AutoMapperMappingException>> CtorExpression = () => new AutoMapperMappingException(null, null, default, null, null); private static readonly Expression<Action<ResolutionContext>> IncTypeDepthInfo = ctxt => ctxt.IncrementTypeDepth(default); private static readonly Expression<Action<ResolutionContext>> DecTypeDepthInfo = ctxt => ctxt.DecrementTypeDepth(default); private readonly IConfigurationProvider _configurationProvider; private readonly ParameterExpression _destination; private readonly ParameterExpression _initialDestination; private readonly TypeMap _typeMap; public TypeMapPlanBuilder(IConfigurationProvider configurationProvider, TypeMap typeMap) { _configurationProvider = configurationProvider; _typeMap = typeMap; Source = Parameter(typeMap.SourceType, "src"); _initialDestination = Parameter(typeMap.DestinationTypeToUse, "dest"); Context = Parameter(typeof(ResolutionContext), "ctxt"); _destination = Variable(_initialDestination.Type, "typeMapDestination"); } public ParameterExpression Source { get; } public ParameterExpression Context { get; } public LambdaExpression CreateMapperLambda(HashSet<TypeMap> typeMapsPath) { var customExpression = TypeConverterMapper() ?? _typeMap.CustomMapFunction ?? _typeMap.CustomMapExpression; if(customExpression != null) { return Lambda(customExpression.ReplaceParameters(Source, _initialDestination, Context), Source, _initialDestination, Context); } CheckForCycles(typeMapsPath); if(typeMapsPath != null) { return null; } var destinationFunc = CreateDestinationFunc(); var assignmentFunc = CreateAssignmentFunc(destinationFunc); var mapperFunc = CreateMapperFunc(assignmentFunc); var checkContext = CheckContext(_typeMap, Context); var lambaBody = checkContext != null ? new[] {checkContext, mapperFunc} : new[] {mapperFunc}; return Lambda(Block(new[] {_destination}, lambaBody), Source, _initialDestination, Context); } private void CheckForCycles(HashSet<TypeMap> typeMapsPath) { var inlineWasChecked = _typeMap.WasInlineChecked; _typeMap.WasInlineChecked = true; if (typeMapsPath == null) { typeMapsPath = new HashSet<TypeMap>(); } typeMapsPath.Add(_typeMap); var members = _typeMap.MemberMaps .Concat(_typeMap.IncludedDerivedTypes.Select(ResolveTypeMap).SelectMany(tm=>tm.MemberMaps)) .Where(pm=>pm.CanResolveValue) .ToArray() .Select(pm=> new { MemberTypeMap = ResolveMemberTypeMap(pm), MemberMap = pm }) .Where(p => p.MemberTypeMap != null && !p.MemberTypeMap.PreserveReferences && p.MemberTypeMap.MapExpression == null); foreach(var item in members) { var memberMap = item.MemberMap; var memberTypeMap = item.MemberTypeMap; if(!inlineWasChecked && typeMapsPath.Count % _configurationProvider.MaxExecutionPlanDepth == 0) { memberMap.Inline = false; Debug.WriteLine($"Resetting Inline: {memberMap.DestinationName} in {_typeMap.SourceType} - {_typeMap.DestinationType}"); } if(typeMapsPath.Contains(memberTypeMap)) { if(memberTypeMap.SourceType.IsValueType) { if(memberTypeMap.MaxDepth == 0) { memberTypeMap.MaxDepth = 10; } typeMapsPath.Remove(_typeMap); return; } SetPreserveReferences(memberTypeMap); foreach(var derivedTypeMap in memberTypeMap.IncludedDerivedTypes.Select(ResolveTypeMap)) { SetPreserveReferences(derivedTypeMap); } } memberTypeMap.CreateMapperLambda(_configurationProvider, typeMapsPath); } typeMapsPath.Remove(_typeMap); return; void SetPreserveReferences(TypeMap memberTypeMap) { Debug.WriteLine($"Setting PreserveReferences: {_typeMap.SourceType} - {_typeMap.DestinationType} => {memberTypeMap.SourceType} - {memberTypeMap.DestinationType}"); memberTypeMap.PreserveReferences = true; } TypeMap ResolveMemberTypeMap(IMemberMap memberMap) { if(memberMap.SourceType == null || memberMap.Types.ContainsGenericParameters) { return null; } var types = new TypePair(memberMap.SourceType, memberMap.DestinationType); return ResolveTypeMap(types); } TypeMap ResolveTypeMap(TypePair types) { var typeMap = _configurationProvider.ResolveTypeMap(types); if(typeMap == null && _configurationProvider.FindMapper(types) is IObjectMapperInfo mapper) { typeMap = _configurationProvider.ResolveTypeMap(mapper.GetAssociatedTypes(types)); } return typeMap; } } private LambdaExpression TypeConverterMapper() { if (_typeMap.TypeConverterType == null) return null; // (src, dest, ctxt) => ((ITypeConverter<TSource, TDest>)ctxt.Options.CreateInstance<TypeConverterType>()).ToType(src, ctxt); var converterInterfaceType = typeof(ITypeConverter<,>).MakeGenericType(_typeMap.SourceType, _typeMap.DestinationTypeToUse); return Lambda( Call( ToType(CreateInstance(_typeMap.TypeConverterType), converterInterfaceType), converterInterfaceType.GetDeclaredMethod("Convert"), Source, _initialDestination, Context ), Source, _initialDestination, Context); } private Expression CreateDestinationFunc() { var newDestFunc = ToType(CreateNewDestinationFunc(), _typeMap.DestinationTypeToUse); var getDest = _typeMap.DestinationTypeToUse.IsValueType ? newDestFunc : Coalesce(_initialDestination, newDestFunc); Expression destinationFunc = Assign(_destination, getDest); if (_typeMap.PreserveReferences) { var dest = Variable(typeof(object), "dest"); var setValue = Context.Type.GetDeclaredMethod("CacheDestination"); var set = Call(Context, setValue, Source, Constant(_destination.Type), _destination); var setCache = IfThen(NotEqual(Source, Constant(null)), set); destinationFunc = Block(new[] {dest}, Assign(dest, destinationFunc), setCache, dest); } return destinationFunc; } private Expression CreateAssignmentFunc(Expression destinationFunc) { var isConstructorMapping = _typeMap.IsConstructorMapping; var actions = new List<Expression>(); foreach (var propertyMap in _typeMap.PropertyMaps.Where(pm => pm.CanResolveValue)) { var property = TryPropertyMap(propertyMap); if (isConstructorMapping && _typeMap.ConstructorParameterMatches(propertyMap.DestinationName)) property = _initialDestination.IfNullElse(Default(property.Type), property); actions.Add(property); } foreach (var pathMap in _typeMap.PathMaps.Where(pm => !pm.Ignored)) actions.Add(TryPathMap(pathMap)); foreach (var beforeMapAction in _typeMap.BeforeMapActions) actions.Insert(0, beforeMapAction.ReplaceParameters(Source, _destination, Context)); actions.Insert(0, destinationFunc); if (_typeMap.MaxDepth > 0) { actions.Insert(0, Call(Context, ((MethodCallExpression) IncTypeDepthInfo.Body).Method, Constant(_typeMap.Types))); } actions.AddRange( _typeMap.AfterMapActions.Select( afterMapAction => afterMapAction.ReplaceParameters(Source, _destination, Context))); if (_typeMap.MaxDepth > 0) actions.Add(Call(Context, ((MethodCallExpression) DecTypeDepthInfo.Body).Method, Constant(_typeMap.Types))); actions.Add(_destination); return Block(actions); } private Expression TryPathMap(PathMap pathMap) { var destination = ((MemberExpression) pathMap.DestinationExpression.ConvertReplaceParameters(_destination)).Expression; var createInnerObjects = CreateInnerObjects(destination); var setFinalValue = CreatePropertyMapFunc(pathMap, destination, pathMap.MemberPath.Last); var pathMapExpression = Block(createInnerObjects, setFinalValue); return TryMemberMap(pathMap, pathMapExpression); } private Expression CreateInnerObjects(Expression destination) => Block(destination.GetMembers() .Select(NullCheck) .Concat(new[] {Empty()})); private Expression NullCheck(MemberExpression memberExpression) { var setter = GetSetter(memberExpression); var ifNull = setter == null ? (Expression) Throw(Constant(new NullReferenceException( $"{memberExpression} cannot be null because it's used by ForPath."))) : Assign(setter, DelegateFactory.GenerateConstructorExpression(memberExpression.Type)); return memberExpression.IfNullElse(ifNull); } private Expression CreateMapperFunc(Expression assignmentFunc) { var mapperFunc = assignmentFunc; if(_typeMap.Condition != null) mapperFunc = Condition(_typeMap.Condition.Body, mapperFunc, Default(_typeMap.DestinationTypeToUse)); var overMaxDepth = Context.OverMaxDepth(_typeMap); if (overMaxDepth != null) mapperFunc = Condition( overMaxDepth, Default(_typeMap.DestinationTypeToUse), mapperFunc); if(_typeMap.Profile.AllowNullDestinationValues) mapperFunc = Source.IfNullElse(Default(_typeMap.DestinationTypeToUse), mapperFunc); return CheckReferencesCache(mapperFunc); } private Expression CheckReferencesCache(Expression valueBuilder) { if(!_typeMap.PreserveReferences) { return valueBuilder; } var cache = Variable(_typeMap.DestinationTypeToUse, "cachedDestination"); var getDestination = Context.Type.GetDeclaredMethod("GetDestination"); var assignCache = Assign(cache, ToType(Call(Context, getDestination, Source, Constant(_destination.Type)), _destination.Type)); var condition = Condition( AndAlso(NotEqual(Source, Constant(null)), NotEqual(assignCache, Constant(null))), cache, valueBuilder); return Block(new[] { cache }, condition); } private Expression CreateNewDestinationFunc() { if(_typeMap.CustomCtorExpression != null) { return _typeMap.CustomCtorExpression.ReplaceParameters(Source); } if(_typeMap.CustomCtorFunction != null) { return _typeMap.CustomCtorFunction.ReplaceParameters(Source, Context); } if(_typeMap.ConstructDestinationUsingServiceLocator) { return CreateInstance(_typeMap.DestinationTypeToUse); } if(_typeMap.ConstructorMap?.CanResolve == true) { return CreateNewDestinationExpression(_typeMap.ConstructorMap); } if(_typeMap.DestinationTypeToUse.IsInterface) { var ctor = Call(null, typeof(DelegateFactory).GetDeclaredMethod(nameof(DelegateFactory.CreateCtor), new[] { typeof(Type) }), Call(null, typeof(ProxyGenerator).GetDeclaredMethod(nameof(ProxyGenerator.GetProxyType)), Constant(_typeMap.DestinationTypeToUse))); // We're invoking a delegate here to make it have the right accessibility return Invoke(ctor); } return DelegateFactory.GenerateConstructorExpression(_typeMap.DestinationTypeToUse); } private Expression CreateNewDestinationExpression(ConstructorMap constructorMap) { var ctorArgs = constructorMap.CtorParams.Select(CreateConstructorParameterExpression); var variables = constructorMap.Ctor.GetParameters().Select(parameter => Variable(parameter.ParameterType, parameter.Name)).ToArray(); var body = variables.Zip(ctorArgs, (variable, expression) => (Expression) Assign(variable, ToType(expression, variable.Type))) .Concat(new[] { CheckReferencesCache(New(constructorMap.Ctor, variables)) }) .ToArray(); return Block(variables, body); } private Expression ResolveSource(ConstructorParameterMap ctorParamMap) { if(ctorParamMap.CustomMapExpression != null) return ctorParamMap.CustomMapExpression.ConvertReplaceParameters(Source) .NullCheck(ctorParamMap.DestinationType); if(ctorParamMap.CustomMapFunction != null) return ctorParamMap.CustomMapFunction.ConvertReplaceParameters(Source, Context); if (ctorParamMap.SourceMemberName != null) { return MemberAccesses(ctorParamMap.SourceMemberName, Source); } if (ctorParamMap.HasDefaultValue) return Constant(ctorParamMap.Parameter.GetDefaultValue()); return Chain(ctorParamMap.SourceMembers, ctorParamMap.DestinationType); } private Expression CreateConstructorParameterExpression(ConstructorParameterMap ctorParamMap) { var resolvedExpression = ResolveSource(ctorParamMap); var resolvedValue = Variable(resolvedExpression.Type, "resolvedValue"); var tryMap = Block(new[] {resolvedValue}, Assign(resolvedValue, resolvedExpression), MapExpression(_configurationProvider, _typeMap.Profile, new TypePair(resolvedExpression.Type, ctorParamMap.DestinationType), resolvedValue, Context)); return TryMemberMap(ctorParamMap, tryMap); } private Expression TryPropertyMap(PropertyMap propertyMap) { var pmExpression = CreatePropertyMapFunc(propertyMap, _destination, propertyMap.DestinationMember); if (pmExpression == null) return null; return TryMemberMap(propertyMap, pmExpression); } private static Expression TryMemberMap(IMemberMap memberMap, Expression memberMapExpression) { var exception = Parameter(typeof(Exception), "ex"); var mappingExceptionCtor = ((NewExpression) CtorExpression.Body).Constructor; return TryCatch(memberMapExpression, MakeCatchBlock(typeof(Exception), exception, Block( Throw(New(mappingExceptionCtor, Constant("Error mapping types."), exception, Constant(memberMap.TypeMap.Types), Constant(memberMap.TypeMap), Constant(memberMap))), Default(memberMapExpression.Type)) , null)); } private Expression CreatePropertyMapFunc(IMemberMap memberMap, Expression destination, MemberInfo destinationMember) { var destMember = MakeMemberAccess(destination, destinationMember); Expression getter; if (destinationMember is PropertyInfo pi && pi.GetGetMethod(true) == null) getter = Default(memberMap.DestinationType); else getter = destMember; Expression destValueExpr; if (memberMap.UseDestinationValue == true || (memberMap.UseDestinationValue == null && !ReflectionHelper.CanBeSet(destinationMember))) { destValueExpr = getter; } else { if (_initialDestination.Type.IsValueType) destValueExpr = Default(memberMap.DestinationType); else destValueExpr = Condition(Equal(_initialDestination, Constant(null)), Default(memberMap.DestinationType), getter); } var valueResolverExpr = BuildValueResolverFunc(memberMap, getter); var resolvedValue = Variable(valueResolverExpr.Type, "resolvedValue"); var setResolvedValue = Assign(resolvedValue, valueResolverExpr); valueResolverExpr = resolvedValue; var typePair = new TypePair(valueResolverExpr.Type, memberMap.DestinationType); valueResolverExpr = memberMap.Inline ? MapExpression(_configurationProvider, _typeMap.Profile, typePair, valueResolverExpr, Context, memberMap, destValueExpr) : ContextMap(typePair, valueResolverExpr, Context, destValueExpr, memberMap); valueResolverExpr = memberMap.ValueTransformers .Concat(_typeMap.ValueTransformers) .Concat(_typeMap.Profile.ValueTransformers) .Where(vt => vt.IsMatch(memberMap)) .Aggregate(valueResolverExpr, (current, vtConfig) => ToType(ReplaceParameters(vtConfig.TransformerExpression, ToType(current, vtConfig.ValueType)), memberMap.DestinationType)); ParameterExpression propertyValue; Expression setPropertyValue; if (valueResolverExpr == resolvedValue) { propertyValue = resolvedValue; setPropertyValue = setResolvedValue; } else { propertyValue = Variable(valueResolverExpr.Type, "propertyValue"); setPropertyValue = Assign(propertyValue, valueResolverExpr); } Expression mapperExpr; if (destinationMember is FieldInfo) { mapperExpr = memberMap.SourceType != memberMap.DestinationType ? Assign(destMember, ToType(propertyValue, memberMap.DestinationType)) : Assign(getter, propertyValue); } else { var setter = ((PropertyInfo)destinationMember).GetSetMethod(true); if (setter == null) mapperExpr = propertyValue; else mapperExpr = Assign(destMember, ToType(propertyValue, memberMap.DestinationType)); } var source = GetCustomSource(memberMap); if (memberMap.Condition != null) mapperExpr = IfThen( memberMap.Condition.ConvertReplaceParameters( source, _destination, ToType(propertyValue, memberMap.Condition.Parameters[2].Type), ToType(getter, memberMap.Condition.Parameters[2].Type), Context ), mapperExpr ); mapperExpr = Block(new[] {setResolvedValue, setPropertyValue, mapperExpr}.Distinct()); if (memberMap.PreCondition != null) mapperExpr = IfThen( memberMap.PreCondition.ConvertReplaceParameters( source, _destination, Context ), mapperExpr ); return Block(new[] {resolvedValue, propertyValue}.Distinct(), mapperExpr); } private Expression BuildValueResolverFunc(IMemberMap memberMap, Expression destValueExpr) { Expression valueResolverFunc; var destinationPropertyType = memberMap.DestinationType; if (memberMap.ValueConverterConfig != null) { valueResolverFunc = ToType(BuildConvertCall(memberMap), destinationPropertyType); } else if (memberMap.ValueResolverConfig != null) { valueResolverFunc = ToType(BuildResolveCall(destValueExpr, memberMap), destinationPropertyType); } else if (memberMap.CustomMapFunction != null) { valueResolverFunc = memberMap.CustomMapFunction.ConvertReplaceParameters(GetCustomSource(memberMap), _destination, destValueExpr, Context); } else if (memberMap.CustomMapExpression != null) { var nullCheckedExpression = memberMap.CustomMapExpression.ReplaceParameters(Source) .NullCheck(destinationPropertyType); var destinationNullable = destinationPropertyType.IsNullableType(); var returnType = destinationNullable && destinationPropertyType.GetTypeOfNullable() == nullCheckedExpression.Type ? destinationPropertyType : nullCheckedExpression.Type; valueResolverFunc = TryCatch( ToType(nullCheckedExpression, returnType), Catch(typeof(NullReferenceException), Default(returnType)), Catch(typeof(ArgumentNullException), Default(returnType)) ); } else if(memberMap.SourceMembers.Any() && memberMap.SourceType != null) { var last = memberMap.SourceMembers.Last(); if(last is PropertyInfo pi && pi.GetGetMethod(true) == null) { valueResolverFunc = Default(last.GetMemberType()); } else { valueResolverFunc = Chain(memberMap.SourceMembers, destinationPropertyType); } } else { valueResolverFunc = Throw(Constant(new Exception("I done blowed up"))); } if (memberMap.NullSubstitute != null) { var nullSubstitute = Constant(memberMap.NullSubstitute); valueResolverFunc = Coalesce(valueResolverFunc, ToType(nullSubstitute, valueResolverFunc.Type)); } else if (!memberMap.TypeMap.Profile.AllowNullDestinationValues) { var toCreate = memberMap.SourceType ?? destinationPropertyType; if (!toCreate.IsAbstract && toCreate.IsClass && !toCreate.IsArray) valueResolverFunc = Coalesce( valueResolverFunc, ToType(DelegateFactory.GenerateNonNullConstructorExpression(toCreate), memberMap.SourceType) ); } return valueResolverFunc; } private Expression GetCustomSource(IMemberMap memberMap) => memberMap.CustomSource?.ConvertReplaceParameters(Source) ?? Source; private Expression Chain(IEnumerable<MemberInfo> members, Type destinationType) => members.MemberAccesses(Source).NullCheck(destinationType); private Expression CreateInstance(Type type) => Call(Property(Context, nameof(ResolutionContext.Options)), nameof(IMappingOperationOptions.CreateInstance), new[] {type}); private Expression BuildResolveCall(Expression destValueExpr, IMemberMap memberMap) { var typeMap = memberMap.TypeMap; var valueResolverConfig = memberMap.ValueResolverConfig; var resolverInstance = valueResolverConfig.Instance != null ? Constant(valueResolverConfig.Instance) : CreateInstance(typeMap.MakeGenericType(valueResolverConfig.ConcreteType)); var source = GetCustomSource(memberMap); var sourceMember = valueResolverConfig.SourceMember?.ReplaceParameters(source) ?? (valueResolverConfig.SourceMemberName != null ? PropertyOrField(source, valueResolverConfig.SourceMemberName) : null); var iResolverType = valueResolverConfig.InterfaceType; if (iResolverType.ContainsGenericParameters) { iResolverType = iResolverType.GetGenericTypeDefinition().MakeGenericType(new[] { typeMap.SourceType, typeMap.DestinationType }.Concat(iResolverType.GenericTypeArguments.Skip(2)).ToArray()); } var parameters = new[] { source, _destination, sourceMember, destValueExpr }.Where(p => p != null) .Zip(iResolverType.GetGenericArguments(), ToType) .Concat(new[] {Context}); return Call(ToType(resolverInstance, iResolverType), iResolverType.GetDeclaredMethod("Resolve"), parameters); } private Expression BuildConvertCall(IMemberMap memberMap) { var valueConverterConfig = memberMap.ValueConverterConfig; var iResolverType = valueConverterConfig.InterfaceType; var iResolverTypeArgs = iResolverType.GetGenericArguments(); var resolverInstance = valueConverterConfig.Instance != null ? Constant(valueConverterConfig.Instance) : CreateInstance(valueConverterConfig.ConcreteType); var source = GetCustomSource(memberMap); var sourceMember = valueConverterConfig.SourceMember?.ReplaceParameters(source) ?? (valueConverterConfig.SourceMemberName != null ? PropertyOrField(source, valueConverterConfig.SourceMemberName) : memberMap.SourceMembers.Any() ? Chain(memberMap.SourceMembers, iResolverTypeArgs[1]) : Block( Throw(Constant(BuildExceptionMessage())), Default(iResolverTypeArgs[0]) ) ); return Call(ToType(resolverInstance, iResolverType), iResolverType.GetDeclaredMethod("Convert"), ToType(sourceMember, iResolverTypeArgs[0]), Context); AutoMapperConfigurationException BuildExceptionMessage() => new AutoMapperConfigurationException($"Cannot find a source member to pass to the value converter of type {valueConverterConfig.ConcreteType.FullName}. Configure a source member to map from."); } } }
// 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.ComponentModel.Tests { public class ComponentTests { [Fact] public void Ctor_Default() { var component = new SubComponent(); Assert.True(component.CanRaiseEvents); Assert.Null(component.Container); Assert.False(component.DesignMode); Assert.Same(component.Events, component.Events); Assert.Null(component.Site); } public static IEnumerable<object[]> Container_Get_TestData() { yield return new object[] { new Container() }; yield return new object[] { null }; } [Theory] [MemberData(nameof(Container_Get_TestData))] public void Container_GetWithSite_ReturnsExpected(Container result) { var site = new MockSite { Container = result }; var component = new Component { Site = site }; Assert.Same(result, component.Container); } [Fact] public void DesignMode_GetWithCustomSite_ReturnsNull() { // DesignMode uses the private _site field instead of the Site property. var component = new DifferentSiteComponent(); Assert.Null(component.Container); } [Theory] [InlineData(true)] [InlineData(false)] public void DesignMode_GetWithSite_ReturnsExpected(bool result) { var site = new MockSite { DesignMode = result }; var component = new SubComponent { Site = site }; Assert.Equal(result, component.DesignMode); } [Fact] public void DesignMode_GetWithCustomSite_ReturnsFalse() { // DesignMode uses the private _site field instead of the Site property. var component = new DifferentSiteComponent(); Assert.False(component.DesignMode); } public static IEnumerable<object[]> Site_Set_TestData() { yield return new object[] { new MockSite() }; yield return new object[] { null }; } [Theory] [MemberData(nameof(Site_Set_TestData))] public void Site_Set_GetReturnsExpected(ISite value) { var component = new Component { Site = value }; Assert.Same(value, component.Site); // Set same. component.Site = value; Assert.Same(value, component.Site); } [Fact] public void Dispose_NullSite_Success() { var component = new SubComponent(); component.Dispose(); Assert.Null(component.Site); component.Dispose(); Assert.Null(component.Site); } [Fact] public void Dispose_NullSiteContainer_Success() { var site = new MockSite { Container = null }; var component = new SubComponent { Site = site }; component.Dispose(); Assert.Same(site, component.Site); component.Dispose(); Assert.Same(site, component.Site); } [Fact] public void Dispose_NonNullSiteContainer_RemovesComponentFromContainer() { var site = new MockSite { Container = new Container() }; var component = new SubComponent { Site = site }; component.Dispose(); Assert.Null(component.Site); component.Dispose(); Assert.Null(component.Site); } [Fact] public void Dispose_InvokeWithDisposed_CallsHandler() { var component = new SubComponent(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(component, sender); Assert.Same(EventArgs.Empty, e); callCount++; }; component.Disposed += handler; component.Dispose(); Assert.Equal(1, callCount); component.Dispose(); Assert.Equal(2, callCount); // Remove handler. component.Disposed -= handler; component.Dispose(); Assert.Equal(2, callCount); } [Fact] public void Dispose_InvokeCannotRaiseEvents_DoesNotCallHandler() { var component = new NoEventsComponent(); int callCount = 0; component.Disposed += (sender, e) => callCount++; component.Dispose(); Assert.Equal(0, callCount); } [Theory] [InlineData(true, 1)] [InlineData(false, 0)] public void Dispose_InvokeBoolWithDisposed_CallsHandlerIfDisposing(bool disposing, int expectedCallCount) { var component = new SubComponent(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(component, sender); Assert.Same(EventArgs.Empty, e); callCount++; }; component.Disposed += handler; component.Dispose(disposing); Assert.Equal(expectedCallCount, callCount); component.Dispose(disposing); Assert.Equal(expectedCallCount * 2, callCount); // Remove handler. component.Disposed -= handler; component.Dispose(disposing); Assert.Equal(expectedCallCount * 2, callCount); } [Theory] [InlineData(true)] [InlineData(false)] public void Dispose_InvokeDisposingCannotRaiseEvents_DoesNotCallHandler(bool disposing) { var component = new NoEventsComponent(); int callCount = 0; component.Disposed += (sender, e) => callCount++; component.Dispose(disposing); Assert.Equal(0, callCount); } [Fact] public void Finalize_Invoke_DoesNotCallDisposedEvent() { var component = new SubComponent(); int callCount = 0; component.Disposed += (sender, e) => callCount++; MethodInfo method = typeof(Component).GetMethod("Finalize", BindingFlags.NonPublic | BindingFlags.Instance); Assert.NotNull(method); method.Invoke(component, null); Assert.Equal(0, callCount); } [Theory] [InlineData(null)] [InlineData(typeof(int))] public void GetService_InvokeWithoutSite_ReturnsNull(Type serviceType) { var component = new SubComponent(); Assert.Null(component.GetService(serviceType)); } [Theory] [InlineData(null, null)] [InlineData(null, typeof(bool))] [InlineData(typeof(int), null)] [InlineData(typeof(int), typeof(bool))] public void GetService_InvokeWithSite_ReturnsExpected(Type serviceType, Type result) { var site = new MockSite { ServiceType = result }; var component = new SubComponent { Site = site }; Assert.Same(result, component.GetService(serviceType)); } public static IEnumerable<object[]> ToString_TestData() { yield return new object[] { new Component(), "System.ComponentModel.Component" }; yield return new object[] { new Component { Site = new MockSite { Name = "name" } }, "name [System.ComponentModel.Component]" }; yield return new object[] { new Component { Site = new MockSite { Name = string.Empty } }, " [System.ComponentModel.Component]" }; yield return new object[] { new Component { Site = new MockSite { Name = null } }, " [System.ComponentModel.Component]" }; // ToString uses the private _site field instead of the Site property. yield return new object[] { new DifferentSiteComponent { Site = new MockSite { Name = "Name2" } }, "System.ComponentModel.Tests.ComponentTests+DifferentSiteComponent" }; } [Theory] [MemberData(nameof(ToString_TestData))] public void ToString_HasSite_ReturnsExpected(Component component, string expected) { Assert.Equal(expected, component.ToString()); } private class SubComponent : Component { public new bool CanRaiseEvents => base.CanRaiseEvents; public new bool DesignMode => base.DesignMode; public new EventHandlerList Events => base.Events; public new void Dispose(bool disposing) => base.Dispose(disposing); public new object GetService(Type serviceType) => base.GetService(serviceType); } private class NoEventsComponent : Component { protected override bool CanRaiseEvents => false; public new void Dispose(bool disposing) => base.Dispose(disposing); } private class DifferentSiteComponent : Component { public new bool DesignMode => base.DesignMode; public override ISite Site { get => new MockSite { Container = new Container(), DesignMode = true, Name = "Name1" }; set { } } } } }
using NBitcoin; using NBitcoin.RPC; using Nito.AsyncEx; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using WalletWasabi.BitcoinCore.Rpc; using WalletWasabi.Blockchain.Blocks; using WalletWasabi.CoinJoin.Common.Models; using WalletWasabi.CoinJoin.Coordinator.Banning; using WalletWasabi.CoinJoin.Coordinator.Participants; using WalletWasabi.CoinJoin.Coordinator.Rounds; using WalletWasabi.Helpers; using WalletWasabi.Logging; namespace WalletWasabi.CoinJoin.Coordinator { public class Coordinator : IDisposable { private volatile bool _disposedValue = false; // To detect redundant calls public Coordinator(Network network, BlockNotifier blockNotifier, string folderPath, IRPCClient rpc, CoordinatorRoundConfig roundConfig) { Network = Guard.NotNull(nameof(network), network); BlockNotifier = Guard.NotNull(nameof(blockNotifier), blockNotifier); FolderPath = Guard.NotNullOrEmptyOrWhitespace(nameof(folderPath), folderPath, trim: true); RpcClient = Guard.NotNull(nameof(rpc), rpc); RoundConfig = Guard.NotNull(nameof(roundConfig), roundConfig); Rounds = new List<CoordinatorRound>(); RoundsListLock = new AsyncLock(); CoinJoins = new List<uint256>(); UnconfirmedCoinJoins = new List<uint256>(); CoinJoinsLock = new AsyncLock(); LastSuccessfulCoinJoinTime = DateTimeOffset.UtcNow; Directory.CreateDirectory(FolderPath); UtxoReferee = new UtxoReferee(Network, FolderPath, RpcClient, RoundConfig); if (File.Exists(CoinJoinsFilePath)) { try { var getTxTasks = new List<(Task<Transaction> txTask, string line)>(); var batch = RpcClient.PrepareBatch(); var toRemove = new List<string>(); string[] allLines = File.ReadAllLines(CoinJoinsFilePath); foreach (string line in allLines) { try { getTxTasks.Add((batch.GetRawTransactionAsync(uint256.Parse(line)), line)); } catch (Exception ex) { toRemove.Add(line); var logEntry = ex is RPCException rpce && rpce.RPCCode == RPCErrorCode.RPC_INVALID_ADDRESS_OR_KEY ? $"CoinJoins file contains invalid transaction ID {line}" : $"CoinJoins file got corrupted. Deleting offending line \"{line.Substring(0, 20)}\"."; Logger.LogWarning($"{logEntry}. {ex.GetType()}: {ex.Message}"); } } batch.SendBatchAsync().GetAwaiter().GetResult(); foreach (var (txTask, line) in getTxTasks) { try { var tx = txTask.GetAwaiter().GetResult(); CoinJoins.Add(tx.GetHash()); } catch (Exception ex) { toRemove.Add(line); var logEntry = ex is RPCException rpce && rpce.RPCCode == RPCErrorCode.RPC_INVALID_ADDRESS_OR_KEY ? $"CoinJoins file contains invalid transaction ID {line}" : $"CoinJoins file got corrupted. Deleting offending line \"{line.Substring(0, 20)}\"."; Logger.LogWarning($"{logEntry}. {ex.GetType()}: {ex.Message}"); } } if (toRemove.Count != 0) // a little performance boost, it'll be empty almost always { var newAllLines = allLines.Where(x => !toRemove.Contains(x)); File.WriteAllLines(CoinJoinsFilePath, newAllLines); } } catch (Exception ex) { Logger.LogWarning($"CoinJoins file got corrupted. Deleting {CoinJoinsFilePath}. {ex.GetType()}: {ex.Message}"); File.Delete(CoinJoinsFilePath); } uint256[] mempoolHashes = RpcClient.GetRawMempoolAsync().GetAwaiter().GetResult(); UnconfirmedCoinJoins.AddRange(CoinJoins.Intersect(mempoolHashes)); } try { string roundCountFilePath = Path.Combine(folderPath, "RoundCount.txt"); if (File.Exists(roundCountFilePath)) { string roundCount = File.ReadAllText(roundCountFilePath); CoordinatorRound.RoundCount = long.Parse(roundCount); } else { // First time initializes (so the first constructor will increment it and we'll start from 1.) CoordinatorRound.RoundCount = 0; } } catch (Exception ex) { CoordinatorRound.RoundCount = 0; Logger.LogInfo($"{nameof(CoordinatorRound.RoundCount)} file was corrupt. Resetting to 0."); Logger.LogDebug(ex); } BlockNotifier.OnBlock += BlockNotifier_OnBlockAsync; } public event EventHandler<Transaction>? CoinJoinBroadcasted; public DateTimeOffset LastSuccessfulCoinJoinTime { get; private set; } private List<CoordinatorRound> Rounds { get; } private AsyncLock RoundsListLock { get; } private List<uint256> CoinJoins { get; } public string CoinJoinsFilePath => Path.Combine(FolderPath, $"CoinJoins{Network}.txt"); private AsyncLock CoinJoinsLock { get; } private List<uint256> UnconfirmedCoinJoins { get; } public IRPCClient RpcClient { get; } public CoordinatorRoundConfig RoundConfig { get; private set; } public Network Network { get; } public BlockNotifier BlockNotifier { get; } public string FolderPath { get; } public UtxoReferee UtxoReferee { get; } private async void BlockNotifier_OnBlockAsync(object? sender, Block block) { try { using (await CoinJoinsLock.LockAsync()) { foreach (Transaction tx in block.Transactions) { await ProcessConfirmedTransactionAsync(tx).ConfigureAwait(false); } } } catch (Exception ex) { Logger.LogWarning(ex); } } public async Task ProcessConfirmedTransactionAsync(Transaction tx) { // This should not be needed until we would only accept unconfirmed CJ outputs an no other unconf outs. But it'll be more bulletproof for future extensions. // Turns out you shouldn't accept RBF at all never. (See below.) // https://github.com/zkSNACKs/WalletWasabi/issues/145 // if it spends a banned output AND it's not CJ output // ban all the outputs of the transaction tx.PrecomputeHash(false, true); UnconfirmedCoinJoins.Remove(tx.GetHash()); // Locked outside. if (RoundConfig.DosSeverity <= 1) { return; } foreach (TxIn input in tx.Inputs) { OutPoint prevOut = input.PrevOut; // if coin is not banned var foundElem = await UtxoReferee.TryGetBannedAsync(prevOut, notedToo: true).ConfigureAwait(false); if (foundElem is { }) { if (!AnyRunningRoundContainsInput(prevOut, out _)) { int newSeverity = foundElem.Severity + 1; await UtxoReferee.UnbanAsync(prevOut).ConfigureAwait(false); // since it's not an UTXO anymore if (RoundConfig.DosSeverity >= newSeverity) { var txCoins = tx.Outputs.AsIndexedOutputs().Select(x => x.ToCoin().Outpoint); await UtxoReferee.BanUtxosAsync(newSeverity, foundElem.TimeOfBan, forceNoted: foundElem.IsNoted, foundElem.BannedForRound, txCoins.ToArray()).ConfigureAwait(false); } } } } } public async Task MakeSureTwoRunningRoundsAsync(Money? feePerInputs = null, Money? feePerOutputs = null) { using (await RoundsListLock.LockAsync().ConfigureAwait(false)) { int runningRoundCount = Rounds.Count(x => x.Status == CoordinatorRoundStatus.Running); int confirmationTarget = await AdjustConfirmationTargetAsync(lockCoinJoins: true).ConfigureAwait(false); if (runningRoundCount == 0) { var round = new CoordinatorRound(RpcClient, UtxoReferee, RoundConfig, confirmationTarget, RoundConfig.ConfirmationTarget, RoundConfig.ConfirmationTargetReductionRate); round.CoinJoinBroadcasted += Round_CoinJoinBroadcasted; round.StatusChanged += Round_StatusChangedAsync; await round.ExecuteNextPhaseAsync(RoundPhase.InputRegistration, feePerInputs, feePerOutputs).ConfigureAwait(false); Rounds.Add(round); var round2 = new CoordinatorRound(RpcClient, UtxoReferee, RoundConfig, confirmationTarget, RoundConfig.ConfirmationTarget, RoundConfig.ConfirmationTargetReductionRate); round2.StatusChanged += Round_StatusChangedAsync; round2.CoinJoinBroadcasted += Round_CoinJoinBroadcasted; await round2.ExecuteNextPhaseAsync(RoundPhase.InputRegistration, feePerInputs, feePerOutputs).ConfigureAwait(false); Rounds.Add(round2); } else if (runningRoundCount == 1) { var round = new CoordinatorRound(RpcClient, UtxoReferee, RoundConfig, confirmationTarget, RoundConfig.ConfirmationTarget, RoundConfig.ConfirmationTargetReductionRate); round.StatusChanged += Round_StatusChangedAsync; round.CoinJoinBroadcasted += Round_CoinJoinBroadcasted; await round.ExecuteNextPhaseAsync(RoundPhase.InputRegistration, feePerInputs, feePerOutputs).ConfigureAwait(false); Rounds.Add(round); } } } /// <summary> /// Depending on the number of unconfirmed coinjoins lower the confirmation target. /// https://github.com/zkSNACKs/WalletWasabi/issues/1155 /// </summary> private async Task<int> AdjustConfirmationTargetAsync(bool lockCoinJoins) { try { int unconfirmedCoinJoinsCount = 0; if (lockCoinJoins) { using (await CoinJoinsLock.LockAsync().ConfigureAwait(false)) { unconfirmedCoinJoinsCount = UnconfirmedCoinJoins.Count; } } else { unconfirmedCoinJoinsCount = UnconfirmedCoinJoins.Count; } int confirmationTarget = CoordinatorRound.AdjustConfirmationTarget(unconfirmedCoinJoinsCount, RoundConfig.ConfirmationTarget, RoundConfig.ConfirmationTargetReductionRate); return confirmationTarget; } catch (Exception ex) { Logger.LogWarning("Adjusting confirmation target failed. Falling back to default, specified in config."); Logger.LogWarning(ex); return RoundConfig.ConfirmationTarget; } } private void Round_CoinJoinBroadcasted(object? sender, Transaction transaction) { CoinJoinBroadcasted?.Invoke(sender, transaction); } private async void Round_StatusChangedAsync(object? sender, CoordinatorRoundStatus status) { try { var round = sender as CoordinatorRound; Money feePerInputs = null; Money feePerOutputs = null; // If success save the coinjoin. if (status == CoordinatorRoundStatus.Succeded) { uint256[] mempoolHashes = null; try { mempoolHashes = await RpcClient.GetRawMempoolAsync().ConfigureAwait(false); } catch (Exception ex) { Logger.LogError(ex); } using (await CoinJoinsLock.LockAsync().ConfigureAwait(false)) { if (mempoolHashes is { }) { var fallOuts = UnconfirmedCoinJoins.Where(x => !mempoolHashes.Contains(x)); CoinJoins.RemoveAll(x => fallOuts.Contains(x)); UnconfirmedCoinJoins.RemoveAll(x => fallOuts.Contains(x)); } uint256 coinJoinHash = round.CoinJoin.GetHash(); CoinJoins.Add(coinJoinHash); UnconfirmedCoinJoins.Add(coinJoinHash); LastSuccessfulCoinJoinTime = DateTimeOffset.UtcNow; await File.AppendAllLinesAsync(CoinJoinsFilePath, new[] { coinJoinHash.ToString() }).ConfigureAwait(false); // When a round succeeded, adjust the denomination as to users still be able to register with the latest round's active output amount. IEnumerable<(Money value, int count)> outputs = round.CoinJoin.GetIndistinguishableOutputs(includeSingle: true); var bestOutput = outputs.OrderByDescending(x => x.count).FirstOrDefault(); if (bestOutput != default) { Money activeOutputAmount = bestOutput.value; int currentConfirmationTarget = await AdjustConfirmationTargetAsync(lockCoinJoins: false).ConfigureAwait(false); var fees = await CoordinatorRound.CalculateFeesAsync(RpcClient, currentConfirmationTarget).ConfigureAwait(false); feePerInputs = fees.feePerInputs; feePerOutputs = fees.feePerOutputs; Money newDenominationToGetInWithactiveOutputs = activeOutputAmount - (feePerInputs + (2 * feePerOutputs)); if (newDenominationToGetInWithactiveOutputs < RoundConfig.Denomination) { if (newDenominationToGetInWithactiveOutputs > Money.Coins(0.01m)) { RoundConfig.Denomination = newDenominationToGetInWithactiveOutputs; RoundConfig.ToFile(); } } } } } // If aborted in signing phase, then ban Alices that did not sign. if (status == CoordinatorRoundStatus.Aborted && round.Phase == RoundPhase.Signing) { IEnumerable<Alice> alicesDidntSign = round.GetAlicesByNot(AliceState.SignedCoinJoin, syncLock: false); CoordinatorRound nextRound = GetCurrentInputRegisterableRoundOrDefault(syncLock: false); if (nextRound is { }) { int nextRoundAlicesCount = nextRound.CountAlices(syncLock: false); var alicesSignedCount = round.AnonymitySet - alicesDidntSign.Count(); // New round's anonset should be the number of alices that signed in this round. // Except if the number of alices in the next round is already larger. var newAnonymitySet = Math.Max(alicesSignedCount, nextRoundAlicesCount); // But it cannot be larger than the current anonset of that round. newAnonymitySet = Math.Min(newAnonymitySet, nextRound.AnonymitySet); // Only change the anonymity set of the next round if new anonset does not equal and newanonset is larger than 1. if (nextRound.AnonymitySet != newAnonymitySet && newAnonymitySet > 1) { nextRound.UpdateAnonymitySet(newAnonymitySet, syncLock: false); if (nextRoundAlicesCount >= nextRound.AnonymitySet) { // Progress to the next phase, which will be OutputRegistration await nextRound.ExecuteNextPhaseAsync(RoundPhase.ConnectionConfirmation).ConfigureAwait(false); } } } foreach (Alice alice in alicesDidntSign) // Because the event sometimes is raised from inside the lock. { // If it is from any coinjoin, then do not ban. IEnumerable<OutPoint> utxosToBan = alice.Inputs.Select(x => x.Outpoint); await UtxoReferee.BanUtxosAsync(1, DateTimeOffset.UtcNow, forceNoted: false, round.RoundId, utxosToBan.ToArray()).ConfigureAwait(false); } } // If finished start a new round. if (status is CoordinatorRoundStatus.Aborted or CoordinatorRoundStatus.Succeded) { round.StatusChanged -= Round_StatusChangedAsync; round.CoinJoinBroadcasted -= Round_CoinJoinBroadcasted; await MakeSureTwoRunningRoundsAsync(feePerInputs, feePerOutputs).ConfigureAwait(false); } } catch (Exception ex) { Logger.LogWarning(ex); } } public void AbortAllRoundsInInputRegistration(string reason, [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) { using (RoundsListLock.Lock()) { foreach (var r in Rounds.Where(x => x.Status == CoordinatorRoundStatus.Running && x.Phase == RoundPhase.InputRegistration)) { r.Abort(reason, callerFilePath: callerFilePath, callerLineNumber: callerLineNumber); } } } public IEnumerable<CoordinatorRound> GetRunningRounds() { using (RoundsListLock.Lock()) { return Rounds.Where(x => x.Status == CoordinatorRoundStatus.Running).ToArray(); } } public CoordinatorRound GetCurrentInputRegisterableRoundOrDefault(bool syncLock = true) { if (syncLock) { using (RoundsListLock.Lock()) { return Rounds.FirstOrDefault(x => x.Status == CoordinatorRoundStatus.Running && x.Phase == RoundPhase.InputRegistration); } } return Rounds.FirstOrDefault(x => x.Status == CoordinatorRoundStatus.Running && x.Phase == RoundPhase.InputRegistration); } public CoordinatorRound TryGetRound(long roundId) { using (RoundsListLock.Lock()) { return Rounds.SingleOrDefault(x => x.RoundId == roundId); } } public bool AnyRunningRoundContainsInput(OutPoint input, out List<Alice> alices) { using (RoundsListLock.Lock()) { alices = new List<Alice>(); foreach (var round in Rounds.Where(x => x.Status == CoordinatorRoundStatus.Running)) { if (round.ContainsInput(input, out List<Alice> roundAlices)) { foreach (var alice in roundAlices) { alices.Add(alice); } } } return alices.Count > 0; } } public async Task<bool> ContainsUnconfirmedCoinJoinAsync(uint256 hash) { using (await CoinJoinsLock.LockAsync().ConfigureAwait(false)) { return UnconfirmedCoinJoins.Contains(hash); } } public int GetCoinJoinCount() { return CoinJoins.Count; } public async Task<IEnumerable<uint256>> GetUnconfirmedCoinJoinsAsync() { using (await CoinJoinsLock.LockAsync()) { return UnconfirmedCoinJoins.ToArray(); } } #region IDisposable Support protected virtual void Dispose(bool disposing) { if (!_disposedValue) { if (disposing) { using (RoundsListLock.Lock()) { if (BlockNotifier is { }) { BlockNotifier.OnBlock -= BlockNotifier_OnBlockAsync; } foreach (CoordinatorRound round in Rounds) { round.StatusChanged -= Round_StatusChangedAsync; round.CoinJoinBroadcasted -= Round_CoinJoinBroadcasted; } try { string roundCountFilePath = Path.Combine(FolderPath, "RoundCount.txt"); IoHelpers.EnsureContainingDirectoryExists(roundCountFilePath); File.WriteAllText(roundCountFilePath, CoordinatorRound.RoundCount.ToString()); } catch (Exception ex) { Logger.LogDebug(ex); } } } _disposedValue = true; } } // This code added to correctly implement the disposable pattern. public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); //// GC.SuppressFinalize(this); } #endregion IDisposable Support } }
/******************************************************************** 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. *********************************************************************/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using Tao.DevIl; namespace Multiverse.Tools.MosaicCreator { public partial class MosaicCreator : Form { protected Image src; public MosaicCreator() { InitializeComponent(); if (tileSizeComboBox.SelectedItem == null) { tileSizeComboBox.SelectedItem = "512"; } if (mpsComboBox.SelectedItem == null) { mpsComboBox.SelectedItem = "4"; } } protected void WriteMMF(string mosaicName, int tileSize, int tileW, int tileH) { int baseStart = mosaicName.LastIndexOf('\\'); int extOff = mosaicName.LastIndexOf('.'); string basename = mosaicName.Substring(baseStart + 1, extOff - baseStart - 1); StreamWriter w = new StreamWriter(mosaicName); bool isHeightmap = heightMapCheckbox.Checked; w.WriteLine("L3DT Mosaic master file"); w.WriteLine("#MosaicName:\t{0}", basename); w.WriteLine("#MosaicType:\t{0}", "XXX"); w.WriteLine("#FileExt:\t{0}", "png"); w.WriteLine("#nPxlsX:\t{0}", tileW * tileSize); w.WriteLine("#nPxlsY:\t{0}", tileH * tileSize); w.WriteLine("#nMapsX:\t{0}", tileW); w.WriteLine("#nMapsY:\t{0}", tileH); w.WriteLine("#SubMapSize:\t{0}", tileSize); w.WriteLine("#HorizScale:\t{0}", mpsComboBox.Text); w.WriteLine("#WrapFlag:\tFALSE"); if (isHeightmap) { w.WriteLine("#UnifiedScale:\tTRUE"); w.WriteLine("#GlobalMinAlt:\t{0}", minAltTextBox.Text); w.WriteLine("#GlobalMaxAlt:\t{0}", maxAltTextBox.Text); } for (int i = 0; i < tileW * tileH; i++) { w.WriteLine("#TileState:\t{0}\tOK", i); } w.WriteLine("#EOF"); w.Close(); } protected void CreateMosaic(string mosaicName) { //src.Save("temp.png"); //return; if (src != null) { string basename = mosaicName.Substring(0, mosaicName.LastIndexOf('.')); int tileSize = int.Parse(tileSizeComboBox.Text); int tileW = src.Width / tileSize; int tileH = src.Height / tileSize; if ((tileW * tileSize) < src.Width) { tileW++; } if ((tileH * tileSize) < src.Height) { tileH++; } for (int tileY = 0; tileY < tileH; tileY++) { for (int tileX = 0; tileX < tileW; tileX++) { Image dest = new Image(src, tileX * tileSize, tileY * tileSize, tileSize, tileSize); dest.Save(string.Format("{0}_x{1}y{2}.png", basename, tileX, tileY)); } } WriteMMF(mosaicName, tileSize, tileW, tileH); } } private void heightMapCheckbox_CheckedChanged(object sender, EventArgs e) { altPanel.Enabled = heightMapCheckbox.Checked; } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } private void loadImageToolStripMenuItem_Click(object sender, EventArgs e) { using (OpenFileDialog dlg = new OpenFileDialog()) { dlg.Title = "Source Image"; dlg.DefaultExt = "png"; dlg.Filter = "PNG Image File (*.png)|*.png"; dlg.RestoreDirectory = true; if (dlg.ShowDialog() == DialogResult.OK) { sourceImageFilenameLabel.Text = dlg.FileName; src = new Image(dlg.FileName); sourceImageInfoLabel.Text = string.Format("Pixel Format: {0}\nWidth: {1}\nHeight: {2}", src.PixelFormatName, src.Width, src.Height); } } } private void launchOnlineHelpToolStripMenuItem_Click(object sender, EventArgs e) { string target = "http://www.multiversemmo.com/wiki/Using_Mosaic_Creator"; System.Diagnostics.Process.Start(target); } private void launchReleaseNotesToolStripMenuItem_Click(object sender, EventArgs e) { string releaseNotesURL = "http://www.multiversemmo.com/wiki/Tools_Version_1.5_Release_Notes"; System.Diagnostics.Process.Start(releaseNotesURL); } private void submitFeedbackOrABugToolStripMenuItem_Click(object sender, EventArgs e) { string feedbackURL = "http://www.multiverse.net/developer/feedback.jsp?Tool=MosaicCreator"; System.Diagnostics.Process.Start(feedbackURL); } private void aboutMosaicCreatorToolStripMenuItem_Click(object sender, EventArgs e) { string assemblyVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); string msg = string.Format("Multiverse Mosaic Creator\n\nVersion: {0}\n\nCopyright 2012 The Multiverse Software Foundation\n\nPortions of this software are covered by additional copyrights and license agreements which can be found in the Licenses folder in this program's install folder.\n\nPortions of this software utilize SpeedTree technology. Copyright 2001-2006 Interactive Data Visualization, Inc. All rights reserved.", assemblyVersion); DialogResult result = MessageBox.Show(this, msg, "About Multiverse Mosaic Creator", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void saveMosaicToolStripMenuItem_Click(object sender, EventArgs e) { using (SaveFileDialog dlg = new SaveFileDialog()) { dlg.Title = "Save Mosaic"; dlg.DefaultExt = "mmf"; dlg.Filter = "Image Mosaic (*.mmf)|*.mmf"; dlg.RestoreDirectory = true; if (dlg.ShowDialog() == DialogResult.OK) { CreateMosaic(dlg.FileName); } } } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Interpreter; namespace Microsoft.PythonTools.EnvironmentsList { public sealed class EnvironmentView : DependencyObject { public static readonly RoutedCommand OpenInteractiveWindow = new RoutedCommand(); public static readonly RoutedCommand OpenInteractiveScripts = new RoutedCommand(); public static readonly RoutedCommand OpenInPowerShell = new RoutedCommand(); public static readonly RoutedCommand OpenInCommandPrompt = new RoutedCommand(); public static readonly RoutedCommand MakeGlobalDefault = new RoutedCommand(); public static readonly RoutedCommand MakeActiveInCurrentProject = new RoutedCommand(); public static readonly RoutedCommand EnableIPythonInteractive = new RoutedCommand(); public static readonly RoutedCommand DisableIPythonInteractive = new RoutedCommand(); public static readonly Lazy<EnvironmentView> AddNewEnvironmentView = new Lazy<EnvironmentView>(() => new EnvironmentView()); public static readonly Lazy<IEnumerable<EnvironmentView>> AddNewEnvironmentViewOnce = new Lazy<IEnumerable<EnvironmentView>>(() => new[] { AddNewEnvironmentView.Value }); public static readonly Lazy<EnvironmentView> OnlineHelpView = new Lazy<EnvironmentView>(() => new EnvironmentView()); public static readonly Lazy<IEnumerable<EnvironmentView>> OnlineHelpViewOnce = new Lazy<IEnumerable<EnvironmentView>>(() => new[] { OnlineHelpView.Value }); /// <summary> /// Used with <see cref="CommonUtils.FindFile"/> to more efficiently /// find interpreter executables. /// </summary> private static readonly string[] _likelyInterpreterPaths = new[] { "Scripts" }; /// <summary> /// Used with <see cref="CommonUtils.FindFile"/> to more efficiently /// find interpreter libraries. /// </summary> private static readonly string[] _likelyLibraryPaths = new[] { "Lib" }; private readonly IInterpreterOptionsService _service; private readonly IPythonInterpreterFactoryWithDatabase _withDb; public IPythonInterpreterFactory Factory { get; private set; } private EnvironmentView() { } internal EnvironmentView( IInterpreterOptionsService service, IPythonInterpreterFactory factory, Redirector redirector ) { if (service == null) { throw new ArgumentNullException(nameof(service)); } if (factory == null) { throw new ArgumentNullException(nameof(factory)); } _service = service; Factory = factory; _withDb = factory as IPythonInterpreterFactoryWithDatabase; if (_withDb != null) { _withDb.IsCurrentChanged += Factory_IsCurrentChanged; IsCheckingDatabase = _withDb.IsCheckingDatabase; IsCurrent = _withDb.IsCurrent; } if (_service.IsConfigurable(factory.Configuration.Id)) { IsConfigurable = true; } Description = Factory.Configuration.FullDescription; IsDefault = (_service != null && _service.DefaultInterpreter == Factory); PrefixPath = Factory.Configuration.PrefixPath; InterpreterPath = Factory.Configuration.InterpreterPath; WindowsInterpreterPath = Factory.Configuration.WindowsInterpreterPath; LibraryPath = Factory.Configuration.LibraryPath; Extensions = new ObservableCollection<object>(); Extensions.Add(new EnvironmentPathsExtensionProvider()); if (IsConfigurable) { Extensions.Add(new ConfigurationExtensionProvider(_service)); } CanBeDefault = Factory.CanBeDefault(); } public override string ToString() { return string.Format( "{{{0}:{1}}}", GetType().FullName, _withDb == null ? "(null)" : _withDb.Configuration.FullDescription ); } public ObservableCollection<object> Extensions { get; private set; } private void Factory_IsCurrentChanged(object sender, EventArgs e) { Debug.Assert(_withDb != null); if (_withDb == null) { return; } Dispatcher.BeginInvoke((Action)(() => { IsCheckingDatabase = _withDb.IsCheckingDatabase; IsCurrent = _withDb.IsCurrent; })); } #region Read-only State Dependency Properties private static readonly DependencyPropertyKey IsConfigurablePropertyKey = DependencyProperty.RegisterReadOnly("IsConfigurable", typeof(bool), typeof(EnvironmentView), new PropertyMetadata(false)); private static readonly DependencyPropertyKey CanBeDefaultPropertyKey = DependencyProperty.RegisterReadOnly("CanBeDefault", typeof(bool), typeof(EnvironmentView), new PropertyMetadata(true)); private static readonly DependencyPropertyKey IsDefaultPropertyKey = DependencyProperty.RegisterReadOnly("IsDefault", typeof(bool), typeof(EnvironmentView), new PropertyMetadata(false)); private static readonly DependencyPropertyKey IsCurrentPropertyKey = DependencyProperty.RegisterReadOnly("IsCurrent", typeof(bool), typeof(EnvironmentView), new PropertyMetadata(true)); private static readonly DependencyPropertyKey IsCheckingDatabasePropertyKey = DependencyProperty.RegisterReadOnly("IsCheckingDatabase", typeof(bool), typeof(EnvironmentView), new PropertyMetadata(false)); private static readonly DependencyPropertyKey RefreshDBProgressPropertyKey = DependencyProperty.RegisterReadOnly("RefreshDBProgress", typeof(int), typeof(EnvironmentView), new PropertyMetadata(0)); private static readonly DependencyPropertyKey RefreshDBMessagePropertyKey = DependencyProperty.RegisterReadOnly("RefreshDBMessage", typeof(string), typeof(EnvironmentView), new PropertyMetadata()); private static readonly DependencyPropertyKey IsRefreshingDBPropertyKey = DependencyProperty.RegisterReadOnly("IsRefreshingDB", typeof(bool), typeof(EnvironmentView), new PropertyMetadata(false)); private static readonly DependencyPropertyKey IsRefreshDBProgressIndeterminatePropertyKey = DependencyProperty.RegisterReadOnly("IsRefreshDBProgressIndeterminate", typeof(bool), typeof(EnvironmentView), new PropertyMetadata(false)); public static readonly DependencyProperty IsConfigurableProperty = IsConfigurablePropertyKey.DependencyProperty; public static readonly DependencyProperty CanBeDefaultProperty = CanBeDefaultPropertyKey.DependencyProperty; public static readonly DependencyProperty IsDefaultProperty = IsDefaultPropertyKey.DependencyProperty; public static readonly DependencyProperty IsCurrentProperty = IsCurrentPropertyKey.DependencyProperty; public static readonly DependencyProperty IsCheckingDatabaseProperty = IsCheckingDatabasePropertyKey.DependencyProperty; public static readonly DependencyProperty RefreshDBMessageProperty = RefreshDBMessagePropertyKey.DependencyProperty; public static readonly DependencyProperty RefreshDBProgressProperty = RefreshDBProgressPropertyKey.DependencyProperty; public static readonly DependencyProperty IsRefreshingDBProperty = IsRefreshingDBPropertyKey.DependencyProperty; public static readonly DependencyProperty IsRefreshDBProgressIndeterminateProperty = IsRefreshDBProgressIndeterminatePropertyKey.DependencyProperty; public bool IsConfigurable { get { return Factory == null ? false : (bool)GetValue(IsConfigurableProperty); } set { if (Factory != null) { SetValue(IsConfigurablePropertyKey, value); } } } public bool CanBeDefault { get { return Factory == null ? false : (bool)GetValue(CanBeDefaultProperty); } set { if (Factory != null) { SetValue(CanBeDefaultPropertyKey, value); } } } public bool IsDefault { get { return Factory == null ? false : (bool)GetValue(IsDefaultProperty); } internal set { if (Factory != null) { SetValue(IsDefaultPropertyKey, value); } } } public bool IsCurrent { get { return Factory == null ? true : (bool)GetValue(IsCurrentProperty); } internal set { if (Factory != null) { SetValue(IsCurrentPropertyKey, value); } } } public bool IsCheckingDatabase { get { return Factory == null ? false : (bool)GetValue(IsCheckingDatabaseProperty); } internal set { if (Factory != null) { SetValue(IsCheckingDatabasePropertyKey, value); } } } public int RefreshDBProgress { get { return Factory == null ? 0 : (int)GetValue(RefreshDBProgressProperty); } internal set { if (Factory != null) { SetValue(RefreshDBProgressPropertyKey, value); } } } public string RefreshDBMessage { get { return Factory == null ? string.Empty : (string)GetValue(RefreshDBMessageProperty); } internal set { if (Factory != null) { SetValue(RefreshDBMessagePropertyKey, value); } } } public bool IsRefreshingDB { get { return Factory == null ? false : (bool)GetValue(IsRefreshingDBProperty); } internal set { if (Factory != null) { SetValue(IsRefreshingDBPropertyKey, value); } } } public bool IsRefreshDBProgressIndeterminate { get { return Factory == null ? false : (bool)GetValue(IsRefreshDBProgressIndeterminateProperty); } internal set { if (Factory != null) { SetValue(IsRefreshDBProgressIndeterminatePropertyKey, value); } } } #endregion #region Configuration Dependency Properties private static readonly DependencyPropertyKey DescriptionPropertyKey = DependencyProperty.RegisterReadOnly("Description", typeof(string), typeof(EnvironmentView), new PropertyMetadata()); private static readonly DependencyPropertyKey PrefixPathPropertyKey = DependencyProperty.RegisterReadOnly("PrefixPath", typeof(string), typeof(EnvironmentView), new PropertyMetadata()); private static readonly DependencyPropertyKey InterpreterPathPropertyKey = DependencyProperty.RegisterReadOnly("InterpreterPath", typeof(string), typeof(EnvironmentView), new PropertyMetadata()); private static readonly DependencyPropertyKey WindowsInterpreterPathPropertyKey = DependencyProperty.RegisterReadOnly("WindowsInterpreterPath", typeof(string), typeof(EnvironmentView), new PropertyMetadata()); private static readonly DependencyPropertyKey LibraryPathPropertyKey = DependencyProperty.RegisterReadOnly("LibraryPath", typeof(string), typeof(EnvironmentView), new PropertyMetadata()); private static readonly DependencyPropertyKey PathEnvironmentVariablePropertyKey = DependencyProperty.RegisterReadOnly("PathEnvironmentVariable", typeof(string), typeof(EnvironmentView), new PropertyMetadata()); public static readonly DependencyProperty DescriptionProperty = DescriptionPropertyKey.DependencyProperty; public static readonly DependencyProperty PrefixPathProperty = PrefixPathPropertyKey.DependencyProperty; public static readonly DependencyProperty InterpreterPathProperty = InterpreterPathPropertyKey.DependencyProperty; public static readonly DependencyProperty WindowsInterpreterPathProperty = WindowsInterpreterPathPropertyKey.DependencyProperty; public static readonly DependencyProperty LibraryPathProperty = LibraryPathPropertyKey.DependencyProperty; public static readonly DependencyProperty PathEnvironmentVariableProperty = PathEnvironmentVariablePropertyKey.DependencyProperty; public string Description { get { return Factory == null ? string.Empty : (string)GetValue(DescriptionProperty); } set { if (Factory != null) { SetValue(DescriptionPropertyKey, value); } } } public string PrefixPath { get { return Factory == null ? string.Empty : (string)GetValue(PrefixPathProperty); } set { if (Factory != null) { SetValue(PrefixPathPropertyKey, value); } } } public string InterpreterPath { get { return Factory == null ? string.Empty : (string)GetValue(InterpreterPathProperty); } set { if (Factory != null) { SetValue(InterpreterPathPropertyKey, value); } } } public string WindowsInterpreterPath { get { return Factory == null ? string.Empty : (string)GetValue(WindowsInterpreterPathProperty); } set { if (Factory != null) { SetValue(WindowsInterpreterPathPropertyKey, value); } } } public string LibraryPath { get { return Factory == null ? string.Empty : (string)GetValue(LibraryPathProperty); } set { if (Factory != null) { SetValue(LibraryPathPropertyKey, value); } } } public string PathEnvironmentVariable { get { return Factory == null ? string.Empty : (string)GetValue(PathEnvironmentVariableProperty); } set { if (Factory != null) { SetValue(PathEnvironmentVariablePropertyKey, value); } } } #endregion } public sealed class EnvironmentViewTemplateSelector : DataTemplateSelector { public DataTemplate Environment { get; set; } public DataTemplate AddNewEnvironment { get; set; } public DataTemplate OnlineHelp { get; set; } public override DataTemplate SelectTemplate(object item, DependencyObject container) { if (EnvironmentView.AddNewEnvironmentView.IsValueCreated) { if (object.ReferenceEquals(item, EnvironmentView.AddNewEnvironmentView.Value) && AddNewEnvironment != null) { return AddNewEnvironment; } } if (EnvironmentView.OnlineHelpView.IsValueCreated) { if (object.ReferenceEquals(item, EnvironmentView.OnlineHelpView.Value) && OnlineHelp != null) { return OnlineHelp; } } if (item is EnvironmentView && Environment != null) { return Environment; } return base.SelectTemplate(item, container); } } }
#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.Text; using System.IO; using System.Xml; using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Linq; using System.Globalization; namespace Newtonsoft.Json { /// <summary> /// Specifies the state of the <see cref="JsonWriter"/>. /// </summary> public enum WriteState { /// <summary> /// An exception has been thrown, which has left the <see cref="JsonWriter"/> in an invalid state. /// You may call the <see cref="JsonWriter.Close"/> method to put the <see cref="JsonWriter"/> in the <c>Closed</c> state. /// Any other <see cref="JsonWriter"/> method calls results in an <see cref="InvalidOperationException"/> being thrown. /// </summary> Error, /// <summary> /// The <see cref="JsonWriter.Close"/> method has been called. /// </summary> Closed, /// <summary> /// An object is being written. /// </summary> Object, /// <summary> /// A array is being written. /// </summary> Array, /// <summary> /// A constructor is being written. /// </summary> Constructor, /// <summary> /// A property is being written. /// </summary> Property, /// <summary> /// A write method has not been called. /// </summary> Start } /// <summary> /// Specifies formatting options for the <see cref="JsonTextWriter"/>. /// </summary> public enum Formatting { /// <summary> /// No special formatting is applied. This is the default. /// </summary> None, /// <summary> /// Causes child objects to be indented according to the <see cref="JsonTextWriter.Indentation"/> and <see cref="JsonTextWriter.IndentChar"/> settings. /// </summary> Indented } /// <summary> /// Represents a writer that provides a fast, non-cached, forward-only way of generating Json data. /// </summary> public abstract class JsonWriter : IDisposable { private enum State { Start, Property, ObjectStart, Object, ArrayStart, Array, ConstructorStart, Constructor, Bytes, Closed, Error } // array that gives a new state based on the current state an the token being written private static readonly State[][] stateArray = new[] { // Start PropertyName ObjectStart Object ArrayStart Array ConstructorStart Constructor Closed Error // /* None */new[]{ State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error }, /* StartObject */new[]{ State.ObjectStart, State.ObjectStart, State.Error, State.Error, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.Error, State.Error }, /* StartArray */new[]{ State.ArrayStart, State.ArrayStart, State.Error, State.Error, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.Error, State.Error }, /* StartConstructor */new[]{ State.ConstructorStart, State.ConstructorStart, State.Error, State.Error, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.Error, State.Error }, /* StartProperty */new[]{ State.Property, State.Error, State.Property, State.Property, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error }, /* Comment */new[]{ State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error }, /* Raw */new[]{ State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error }, /* Value */new[]{ State.Start, State.Object, State.Error, State.Error, State.Array, State.Array, State.Constructor, State.Constructor, State.Error, State.Error }, }; private int _top; private readonly List<JTokenType> _stack; private State _currentState; private Formatting _formatting; /// <summary> /// Gets the top. /// </summary> /// <value>The top.</value> protected internal int Top { get { return _top; } } /// <summary> /// Gets the state of the writer. /// </summary> public WriteState WriteState { get { switch (_currentState) { case State.Error: return WriteState.Error; case State.Closed: return WriteState.Closed; case State.Object: case State.ObjectStart: return WriteState.Object; case State.Array: case State.ArrayStart: return WriteState.Array; case State.Constructor: case State.ConstructorStart: return WriteState.Constructor; case State.Property: return WriteState.Property; case State.Start: return WriteState.Start; default: throw new JsonWriterException("Invalid state: " + _currentState); } } } /// <summary> /// Indicates how the output is formatted. /// </summary> public Formatting Formatting { get { return _formatting; } set { _formatting = value; } } /// <summary> /// Creates an instance of the <c>JsonWriter</c> class. /// </summary> public JsonWriter() { _stack = new List<JTokenType>(8); _stack.Add(JTokenType.None); _currentState = State.Start; _formatting = Formatting.None; } private void Push(JTokenType value) { _top++; if (_stack.Count <= _top) _stack.Add(value); else _stack[_top] = value; } private JTokenType Pop() { JTokenType value = Peek(); _top--; return value; } private JTokenType Peek() { return _stack[_top]; } /// <summary> /// Flushes whatever is in the buffer to the underlying streams and also flushes the underlying stream. /// </summary> public abstract void Flush(); /// <summary> /// Closes this stream and the underlying stream. /// </summary> public virtual void Close() { AutoCompleteAll(); } /// <summary> /// Writes the beginning of a Json object. /// </summary> public virtual void WriteStartObject() { AutoComplete(JsonToken.StartObject); Push(JTokenType.Object); } /// <summary> /// Writes the end of a Json object. /// </summary> public void WriteEndObject() { AutoCompleteClose(JsonToken.EndObject); } /// <summary> /// Writes the beginning of a Json array. /// </summary> public virtual void WriteStartArray() { AutoComplete(JsonToken.StartArray); Push(JTokenType.Array); } /// <summary> /// Writes the end of an array. /// </summary> public void WriteEndArray() { AutoCompleteClose(JsonToken.EndArray); } /// <summary> /// Writes the start of a constructor with the given name. /// </summary> /// <param name="name">The name of the constructor.</param> public virtual void WriteStartConstructor(string name) { AutoComplete(JsonToken.StartConstructor); Push(JTokenType.Constructor); } /// <summary> /// Writes the end constructor. /// </summary> public void WriteEndConstructor() { AutoCompleteClose(JsonToken.EndConstructor); } /// <summary> /// Writes the property name of a name/value pair on a Json object. /// </summary> /// <param name="name">The name of the property.</param> public virtual void WritePropertyName(string name) { AutoComplete(JsonToken.PropertyName); } /// <summary> /// Writes the end of the current Json object or array. /// </summary> public void WriteEnd() { WriteEnd(Peek()); } /// <summary> /// Writes the current <see cref="JsonReader"/> token. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param> public void WriteToken(JsonReader reader) { ValidationUtils.ArgumentNotNull(reader, "reader"); int initialDepth; if (reader.TokenType == JsonToken.None) initialDepth = -1; else if (!IsStartToken(reader.TokenType)) initialDepth = reader.Depth + 1; else initialDepth = reader.Depth; WriteToken(reader, initialDepth); } internal void WriteToken(JsonReader reader, int initialDepth) { do { switch (reader.TokenType) { case JsonToken.None: // read to next break; case JsonToken.StartObject: WriteStartObject(); break; case JsonToken.StartArray: WriteStartArray(); break; case JsonToken.StartConstructor: string constructorName = reader.Value.ToString(); // write a JValue date when the constructor is for a date if (string.Compare(constructorName, "Date", StringComparison.Ordinal) == 0) WriteConstructorDate(reader); else WriteStartConstructor(reader.Value.ToString()); break; case JsonToken.PropertyName: WritePropertyName(reader.Value.ToString()); break; case JsonToken.Comment: WriteComment(reader.Value.ToString()); break; case JsonToken.Integer: WriteValue((long)reader.Value); break; case JsonToken.Float: WriteValue((double)reader.Value); break; case JsonToken.String: WriteValue(reader.Value.ToString()); break; case JsonToken.Boolean: WriteValue((bool)reader.Value); break; case JsonToken.Null: WriteNull(); break; case JsonToken.Undefined: WriteUndefined(); break; case JsonToken.EndObject: WriteEndObject(); break; case JsonToken.EndArray: WriteEndArray(); break; case JsonToken.EndConstructor: WriteEndConstructor(); break; case JsonToken.Date: WriteValue((DateTime)reader.Value); break; case JsonToken.Raw: WriteRawValue((string)reader.Value); break; case JsonToken.Bytes: WriteValue((byte[])reader.Value); break; default: throw MiscellaneousUtils.CreateArgumentOutOfRangeException("TokenType", reader.TokenType, "Unexpected token type."); } } while ( // stop if we have reached the end of the token being read initialDepth - 1 < reader.Depth - (IsEndToken(reader.TokenType) ? 1 : 0) && reader.Read()); } private void WriteConstructorDate(JsonReader reader) { if (!reader.Read()) throw new Exception("Unexpected end while reading date constructor."); if (reader.TokenType != JsonToken.Integer) throw new Exception("Unexpected token while reading date constructor. Expected Integer, got " + reader.TokenType); long ticks = (long)reader.Value; DateTime date = JsonConvert.ConvertJavaScriptTicksToDateTime(ticks); if (!reader.Read()) throw new Exception("Unexpected end while reading date constructor."); if (reader.TokenType != JsonToken.EndConstructor) throw new Exception("Unexpected token while reading date constructor. Expected EndConstructor, got " + reader.TokenType); WriteValue(date); } private bool IsEndToken(JsonToken token) { switch (token) { case JsonToken.EndObject: case JsonToken.EndArray: case JsonToken.EndConstructor: return true; default: return false; } } private bool IsStartToken(JsonToken token) { switch (token) { case JsonToken.StartObject: case JsonToken.StartArray: case JsonToken.StartConstructor: return true; default: return false; } } private void WriteEnd(JTokenType type) { switch (type) { case JTokenType.Object: WriteEndObject(); break; case JTokenType.Array: WriteEndArray(); break; case JTokenType.Constructor: WriteEndConstructor(); break; default: throw new JsonWriterException("Unexpected type when writing end: " + type); } } private void AutoCompleteAll() { while (_top > 0) { WriteEnd(); } } private JTokenType GetTypeForCloseToken(JsonToken token) { switch (token) { case JsonToken.EndObject: return JTokenType.Object; case JsonToken.EndArray: return JTokenType.Array; case JsonToken.EndConstructor: return JTokenType.Constructor; default: throw new JsonWriterException("No type for token: " + token); } } private JsonToken GetCloseTokenForType(JTokenType type) { switch (type) { case JTokenType.Object: return JsonToken.EndObject; case JTokenType.Array: return JsonToken.EndArray; case JTokenType.Constructor: return JsonToken.EndConstructor; default: throw new JsonWriterException("No close token for type: " + type); } } private void AutoCompleteClose(JsonToken tokenBeingClosed) { // write closing symbol and calculate new state int levelsToComplete = 0; for (int i = 0; i < _top; i++) { int currentLevel = _top - i; if (_stack[currentLevel] == GetTypeForCloseToken(tokenBeingClosed)) { levelsToComplete = i + 1; break; } } if (levelsToComplete == 0) throw new JsonWriterException("No token to close."); for (int i = 0; i < levelsToComplete; i++) { JsonToken token = GetCloseTokenForType(Pop()); if (_currentState != State.ObjectStart && _currentState != State.ArrayStart) WriteIndent(); WriteEnd(token); } JTokenType currentLevelType = Peek(); switch (currentLevelType) { case JTokenType.Object: _currentState = State.Object; break; case JTokenType.Array: _currentState = State.Array; break; case JTokenType.Constructor: _currentState = State.Array; break; case JTokenType.None: _currentState = State.Start; break; default: throw new JsonWriterException("Unknown JsonType: " + currentLevelType); } } /// <summary> /// Writes the specified end token. /// </summary> /// <param name="token">The end token to write.</param> protected virtual void WriteEnd(JsonToken token) { } /// <summary> /// Writes indent characters. /// </summary> protected virtual void WriteIndent() { } /// <summary> /// Writes the JSON value delimiter. /// </summary> protected virtual void WriteValueDelimiter() { } /// <summary> /// Writes an indent space. /// </summary> protected virtual void WriteIndentSpace() { } internal void AutoComplete(JsonToken tokenBeingWritten) { int token; switch (tokenBeingWritten) { default: token = (int)tokenBeingWritten; break; case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Undefined: case JsonToken.Date: case JsonToken.Bytes: // a value is being written token = 7; break; } // gets new state based on the current state and what is being written State newState = stateArray[token][(int)_currentState]; if (newState == State.Error) throw new JsonWriterException("Token {0} in state {1} would result in an invalid JavaScript object.".FormatWith(CultureInfo.InvariantCulture, tokenBeingWritten.ToString(), _currentState.ToString())); if ((_currentState == State.Object || _currentState == State.Array || _currentState == State.Constructor) && tokenBeingWritten != JsonToken.Comment) { WriteValueDelimiter(); } else if (_currentState == State.Property) { if (_formatting == Formatting.Indented) WriteIndentSpace(); } WriteState writeState = WriteState; // don't indent a property when it is the first token to be written (i.e. at the start) if ((tokenBeingWritten == JsonToken.PropertyName && writeState != WriteState.Start) || writeState == WriteState.Array || writeState == WriteState.Constructor) { WriteIndent(); } _currentState = newState; } #region WriteValue methods /// <summary> /// Writes a null value. /// </summary> public virtual void WriteNull() { AutoComplete(JsonToken.Null); } /// <summary> /// Writes an undefined value. /// </summary> public virtual void WriteUndefined() { AutoComplete(JsonToken.Undefined); } /// <summary> /// Writes raw JSON without changing the writer's state. /// </summary> /// <param name="json">The raw JSON to write.</param> public virtual void WriteRaw(string json) { } /// <summary> /// Writes raw JSON where a value is expected and updates the writer's state. /// </summary> /// <param name="json">The raw JSON to write.</param> public virtual void WriteRawValue(string json) { // hack. want writer to change state as if a value had been written AutoComplete(JsonToken.Undefined); WriteRaw(json); } /// <summary> /// Writes a <see cref="String"/> value. /// </summary> /// <param name="value">The <see cref="String"/> value to write.</param> public virtual void WriteValue(string value) { AutoComplete(JsonToken.String); } /// <summary> /// Writes a <see cref="Int32"/> value. /// </summary> /// <param name="value">The <see cref="Int32"/> value to write.</param> public virtual void WriteValue(int value) { AutoComplete(JsonToken.Integer); } /// <summary> /// Writes a <see cref="UInt32"/> value. /// </summary> /// <param name="value">The <see cref="UInt32"/> value to write.</param> [CLSCompliant(false)] public virtual void WriteValue(uint value) { AutoComplete(JsonToken.Integer); } /// <summary> /// Writes a <see cref="Int64"/> value. /// </summary> /// <param name="value">The <see cref="Int64"/> value to write.</param> public virtual void WriteValue(long value) { AutoComplete(JsonToken.Integer); } /// <summary> /// Writes a <see cref="UInt64"/> value. /// </summary> /// <param name="value">The <see cref="UInt64"/> value to write.</param> [CLSCompliant(false)] public virtual void WriteValue(ulong value) { AutoComplete(JsonToken.Integer); } /// <summary> /// Writes a <see cref="Single"/> value. /// </summary> /// <param name="value">The <see cref="Single"/> value to write.</param> public virtual void WriteValue(float value) { AutoComplete(JsonToken.Float); } /// <summary> /// Writes a <see cref="Double"/> value. /// </summary> /// <param name="value">The <see cref="Double"/> value to write.</param> public virtual void WriteValue(double value) { AutoComplete(JsonToken.Float); } /// <summary> /// Writes a <see cref="Boolean"/> value. /// </summary> /// <param name="value">The <see cref="Boolean"/> value to write.</param> public virtual void WriteValue(bool value) { AutoComplete(JsonToken.Boolean); } /// <summary> /// Writes a <see cref="Int16"/> value. /// </summary> /// <param name="value">The <see cref="Int16"/> value to write.</param> public virtual void WriteValue(short value) { AutoComplete(JsonToken.Integer); } /// <summary> /// Writes a <see cref="UInt16"/> value. /// </summary> /// <param name="value">The <see cref="UInt16"/> value to write.</param> [CLSCompliant(false)] public virtual void WriteValue(ushort value) { AutoComplete(JsonToken.Integer); } /// <summary> /// Writes a <see cref="Char"/> value. /// </summary> /// <param name="value">The <see cref="Char"/> value to write.</param> public virtual void WriteValue(char value) { AutoComplete(JsonToken.String); } /// <summary> /// Writes a <see cref="Byte"/> value. /// </summary> /// <param name="value">The <see cref="Byte"/> value to write.</param> public virtual void WriteValue(byte value) { AutoComplete(JsonToken.Integer); } /// <summary> /// Writes a <see cref="SByte"/> value. /// </summary> /// <param name="value">The <see cref="SByte"/> value to write.</param> [CLSCompliant(false)] public virtual void WriteValue(sbyte value) { AutoComplete(JsonToken.Integer); } /// <summary> /// Writes a <see cref="Decimal"/> value. /// </summary> /// <param name="value">The <see cref="Decimal"/> value to write.</param> public virtual void WriteValue(decimal value) { AutoComplete(JsonToken.Float); } /// <summary> /// Writes a <see cref="DateTime"/> value. /// </summary> /// <param name="value">The <see cref="DateTime"/> value to write.</param> public virtual void WriteValue(DateTime value) { AutoComplete(JsonToken.Date); } #if !PocketPC && !NET20 /// <summary> /// Writes a <see cref="DateTimeOffset"/> value. /// </summary> /// <param name="value">The <see cref="DateTimeOffset"/> value to write.</param> public virtual void WriteValue(DateTimeOffset value) { AutoComplete(JsonToken.Date); } #endif /// <summary> /// Writes a <see cref="Nullable{Int32}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Int32}"/> value to write.</param> public virtual void WriteValue(int? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{UInt32}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{UInt32}"/> value to write.</param> [CLSCompliant(false)] public virtual void WriteValue(uint? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{Int64}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Int64}"/> value to write.</param> public virtual void WriteValue(long? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{UInt64}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{UInt64}"/> value to write.</param> [CLSCompliant(false)] public virtual void WriteValue(ulong? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{Single}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Single}"/> value to write.</param> public virtual void WriteValue(float? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{Double}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Double}"/> value to write.</param> public virtual void WriteValue(double? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{Boolean}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Boolean}"/> value to write.</param> public virtual void WriteValue(bool? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{Int16}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Int16}"/> value to write.</param> public virtual void WriteValue(short? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{UInt16}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{UInt16}"/> value to write.</param> [CLSCompliant(false)] public virtual void WriteValue(ushort? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{Char}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Char}"/> value to write.</param> public virtual void WriteValue(char? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{Byte}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Byte}"/> value to write.</param> public virtual void WriteValue(byte? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{SByte}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{SByte}"/> value to write.</param> [CLSCompliant(false)] public virtual void WriteValue(sbyte? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{Decimal}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Decimal}"/> value to write.</param> public virtual void WriteValue(decimal? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{DateTime}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{DateTime}"/> value to write.</param> public virtual void WriteValue(DateTime? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } #if !PocketPC && !NET20 /// <summary> /// Writes a <see cref="Nullable{DateTimeOffset}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{DateTimeOffset}"/> value to write.</param> public virtual void WriteValue(DateTimeOffset? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } #endif /// <summary> /// Writes a <see cref="T:Byte[]"/> value. /// </summary> /// <param name="value">The <see cref="T:Byte[]"/> value to write.</param> public virtual void WriteValue(byte[] value) { if (value == null) WriteNull(); else AutoComplete(JsonToken.Bytes); } /// <summary> /// Writes a <see cref="Object"/> value. /// An error will raised if the value cannot be written as a single JSON token. /// </summary> /// <param name="value">The <see cref="Object"/> value to write.</param> public virtual void WriteValue(object value) { if (value == null) { WriteNull(); return; } else if (value is IConvertible) { IConvertible convertible = value as IConvertible; switch (convertible.GetTypeCode()) { case TypeCode.String: WriteValue(convertible.ToString(CultureInfo.InvariantCulture)); return; case TypeCode.Char: WriteValue(convertible.ToChar(CultureInfo.InvariantCulture)); return; case TypeCode.Boolean: WriteValue(convertible.ToBoolean(CultureInfo.InvariantCulture)); return; case TypeCode.SByte: WriteValue(convertible.ToSByte(CultureInfo.InvariantCulture)); return; case TypeCode.Int16: WriteValue(convertible.ToInt16(CultureInfo.InvariantCulture)); return; case TypeCode.UInt16: WriteValue(convertible.ToUInt16(CultureInfo.InvariantCulture)); return; case TypeCode.Int32: WriteValue(convertible.ToInt32(CultureInfo.InvariantCulture)); return; case TypeCode.Byte: WriteValue(convertible.ToByte(CultureInfo.InvariantCulture)); return; case TypeCode.UInt32: WriteValue(convertible.ToUInt32(CultureInfo.InvariantCulture)); return; case TypeCode.Int64: WriteValue(convertible.ToInt64(CultureInfo.InvariantCulture)); return; case TypeCode.UInt64: WriteValue(convertible.ToUInt64(CultureInfo.InvariantCulture)); return; case TypeCode.Single: WriteValue(convertible.ToSingle(CultureInfo.InvariantCulture)); return; case TypeCode.Double: WriteValue(convertible.ToDouble(CultureInfo.InvariantCulture)); return; case TypeCode.DateTime: WriteValue(convertible.ToDateTime(CultureInfo.InvariantCulture)); return; case TypeCode.Decimal: WriteValue(convertible.ToDecimal(CultureInfo.InvariantCulture)); return; case TypeCode.DBNull: WriteNull(); return; } } #if !PocketPC && !NET20 else if (value is DateTimeOffset) { WriteValue((DateTimeOffset)value); return; } #endif else if (value is byte[]) { WriteValue((byte[])value); return; } throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType())); } #endregion /// <summary> /// Writes out a comment <code>/*...*/</code> containing the specified text. /// </summary> /// <param name="text">Text to place inside the comment.</param> public virtual void WriteComment(string text) { AutoComplete(JsonToken.Comment); } /// <summary> /// Writes out the given white space. /// </summary> /// <param name="ws">The string of white space characters.</param> public virtual void WriteWhitespace(string ws) { if (ws != null) { if (!StringUtils.IsWhiteSpace(ws)) throw new JsonWriterException("Only white space characters should be used."); } } void IDisposable.Dispose() { Dispose(true); } private void Dispose(bool disposing) { if (WriteState != WriteState.Closed) Close(); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using Marten.Events.Projections.Async; using Marten.Schema.Identity; using Marten.Storage; using Marten.Util; namespace Marten.Events.Projections { public class ViewProjection<TView, TId>: DocumentProjection<TView>, IDocumentProjection where TView : class { private readonly Func<IQuerySession, TId[], IReadOnlyList<TView>> _sessionLoadMany; public ViewProjection() { var loadManyMethod = typeof(IQuerySession).GetMethods() .FirstOrDefault(x => x.Name == "LoadMany" && x.GetParameters().Any(y => y.ParameterType == typeof(TId[]))); if (loadManyMethod == null) { throw new ArgumentException($"{typeof(TId)} is not supported."); } var sessionParameter = Expression.Parameter(typeof(IQuerySession), "a"); var idParameter = Expression.Parameter(typeof(TId[]), "e"); var body = Expression.Call(sessionParameter, loadManyMethod.MakeGenericMethod(typeof(TView)), idParameter); var lambda = Expression.Lambda<Func<IQuerySession, TId[], IReadOnlyList<TView>>>(body, sessionParameter, idParameter); _sessionLoadMany = ExpressionCompiler.Compile<Func<IQuerySession, TId[], IReadOnlyList<TView>>>(lambda); } private class EventHandler { public Func<IDocumentSession, object, Guid, TId> IdSelector { get; } public Func<IDocumentSession, object, Guid, List<TId>> IdsSelector { get; } public Func<IDocumentSession, TView, object, Task> Handler { get; } public Func<IDocumentSession, TView, object, Task<bool>> ShouldDelete { get; } public ProjectionEventType Type { get; set; } public EventHandler( Func<IDocumentSession, object, Guid, TId> idSelector, Func<IDocumentSession, object, Guid, List<TId>> idsSelector, Func<IDocumentSession, TView, object, Task> handler, Func<IDocumentSession, TView, object, Task<bool>> shouldDelete, ProjectionEventType type) { IdSelector = idSelector; IdsSelector = idsSelector; Handler = handler; ShouldDelete = shouldDelete ?? defaultShouldDelete; Type = type; } private Task<bool> defaultShouldDelete(IDocumentSession session, TView view, object @event) => Task.FromResult(true); } private class EventProjection { public TId ViewId { get; } public Func<IDocumentSession, TView, Task> ProjectTo { get; } public Func<IDocumentSession, TView, Task<bool>> ShouldDelete { get; } public ProjectionEventType Type { get; set; } public EventProjection(EventHandler eventHandler, TId viewId, IEvent @event, object projectionEvent) { ViewId = viewId; Type = eventHandler.Type; if (Type == ProjectionEventType.Delete) { ShouldDelete = (session, view) => eventHandler.ShouldDelete(session, view, projectionEvent ?? @event.Data); } else { ProjectTo = (session, view) => eventHandler.Handler(session, view, projectionEvent ?? @event.Data); } } } public enum ProjectionEventType { CreateAndUpdate, UpdateOnly, Delete, } private readonly IDictionary<Type, EventHandler> _handlers = new ConcurrentDictionary<Type, EventHandler>(); public Type[] Consumes => getUniqueEventTypes(); public AsyncOptions AsyncOptions { get; } = new AsyncOptions(); public ViewProjection<TView, TId> DeleteEvent<TEvent>() where TEvent : class => projectEvent<TEvent>( (session, @event, streamId) => convertToTId(streamId), null, null, null, ProjectionEventType.Delete); public ViewProjection<TView, TId> DeleteEvent<TEvent>(Func<TView, TEvent, bool> shouldDelete) where TEvent : class => projectEvent<TEvent>( (session, @event, streamId) => convertToTId(streamId), null, null, (_, view, @event) => Task.FromResult(shouldDelete(view, @event)), ProjectionEventType.Delete); public ViewProjection<TView, TId> DeleteEvent<TEvent>(Func<IDocumentSession, TView, TEvent, bool> shouldDelete) where TEvent : class => projectEvent<TEvent>( (session, @event, streamId) => convertToTId(streamId), null, null, (session, view, @event) => Task.FromResult(shouldDelete(session, view, @event)), ProjectionEventType.Delete); public ViewProjection<TView, TId> DeleteEvent<TEvent>(Func<TEvent, TId> viewIdSelector) where TEvent : class { if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector)); return projectEvent<TEvent>( (session, @event, streamId) => viewIdSelector(@event as TEvent), null, null, null, ProjectionEventType.Delete); } public ViewProjection<TView, TId> DeleteEvent<TEvent>( Func<TEvent, TId> viewIdSelector, Func<TView, TEvent, bool> shouldDelete) where TEvent : class { if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector)); return projectEvent<TEvent>( (session, @event, streamId) => viewIdSelector(@event as TEvent), null, null, (_, view, @event) => Task.FromResult(shouldDelete(view, @event)), ProjectionEventType.Delete); } public ViewProjection<TView, TId> DeleteEvent<TEvent>( Func<TEvent, TId> viewIdSelector, Func<IDocumentSession, TView, TEvent, bool> shouldDelete) where TEvent : class { if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector)); return projectEvent<TEvent>( (session, @event, streamId) => viewIdSelector(@event as TEvent), null, null, (session, view, @event) => Task.FromResult(shouldDelete(session, view, @event)), ProjectionEventType.Delete); } public ViewProjection<TView, TId> DeleteEvent<TEvent>(Func<IDocumentSession, TEvent, TId> viewIdSelector) where TEvent : class { if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector)); return projectEvent<TEvent>( (session, @event, streamId) => viewIdSelector(session, @event as TEvent), null, null, null, ProjectionEventType.Delete); } public ViewProjection<TView, TId> DeleteEvent<TEvent>( Func<IDocumentSession, TEvent, TId> viewIdSelector, Func<TView, TEvent, bool> shouldDelete) where TEvent : class { if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector)); return projectEvent<TEvent>( (session, @event, streamId) => viewIdSelector(session, @event as TEvent), null, null, (_, view, @event) => Task.FromResult(shouldDelete(view, @event)), ProjectionEventType.Delete); } public ViewProjection<TView, TId> DeleteEvent<TEvent>( Func<IDocumentSession, TEvent, TId> viewIdSelector, Func<IDocumentSession, TView, TEvent, bool> shouldDelete) where TEvent : class { if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector)); return projectEvent<TEvent>( (session, @event, streamId) => viewIdSelector(session, @event as TEvent), null, null, (session, view, @event) => Task.FromResult(shouldDelete(session, view, @event)), ProjectionEventType.Delete); } public ViewProjection<TView, TId> DeleteEvent<TEvent>(Func<TEvent, List<TId>> viewIdsSelector) where TEvent : class { if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector)); return projectEvent<TEvent>( null, (session, @event, streamId) => viewIdsSelector(@event as TEvent), null, null, ProjectionEventType.Delete); } public ViewProjection<TView, TId> DeleteEvent<TEvent>( Func<TEvent, List<TId>> viewIdsSelector, Func<TView, TEvent, bool> shouldDelete) where TEvent : class { if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector)); return projectEvent<TEvent>( null, (session, @event, streamId) => viewIdsSelector(@event as TEvent), null, (_, view, @event) => Task.FromResult(shouldDelete(view, @event)), ProjectionEventType.Delete); } public ViewProjection<TView, TId> DeleteEvent<TEvent>( Func<TEvent, List<TId>> viewIdsSelector, Func<IDocumentSession, TView, TEvent, bool> shouldDelete) where TEvent : class { if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector)); return projectEvent<TEvent>( null, (session, @event, streamId) => viewIdsSelector(@event as TEvent), null, (session, view, @event) => Task.FromResult(shouldDelete(session, view, @event)), ProjectionEventType.Delete); } public ViewProjection<TView, TId> DeleteEvent<TEvent>(Func<IDocumentSession, TEvent, List<TId>> viewIdsSelector) where TEvent : class { if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector)); return projectEvent<TEvent>( null, (session, @event, streamId) => viewIdsSelector(session, @event as TEvent), null, null, ProjectionEventType.Delete); } public ViewProjection<TView, TId> DeleteEvent<TEvent>( Func<IDocumentSession, TEvent, List<TId>> viewIdsSelector, Func<TView, TEvent, bool> shouldDelete) where TEvent : class { if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector)); return projectEvent<TEvent>( null, (session, @event, streamId) => viewIdsSelector(session, @event as TEvent), null, (_, view, @event) => Task.FromResult(shouldDelete(view, @event)), ProjectionEventType.Delete); } public ViewProjection<TView, TId> DeleteEvent<TEvent>( Func<IDocumentSession, TEvent, List<TId>> viewIdsSelector, Func<IDocumentSession, TView, TEvent, bool> shouldDelete) where TEvent : class { if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector)); return projectEvent<TEvent>( null, (session, @event, streamId) => viewIdsSelector(session, @event as TEvent), null, (session, view, @event) => Task.FromResult(shouldDelete(session, view, @event)), ProjectionEventType.Delete); } public ViewProjection<TView, TId> DeleteEventAsync<TEvent>(Func<TView, TEvent, Task<bool>> shouldDelete) where TEvent : class => projectEvent<TEvent>( (session, @event, streamId) => convertToTId(streamId), null, null, (_, view, @event) => shouldDelete(view, @event), ProjectionEventType.Delete); public ViewProjection<TView, TId> DeleteEventAsync<TEvent>( Func<IDocumentSession, TView, TEvent, Task<bool>> shouldDelete) where TEvent : class => projectEvent<TEvent>( (session, @event, streamId) => convertToTId(streamId), null, null, shouldDelete, ProjectionEventType.Delete); public ViewProjection<TView, TId> DeleteEventAsync<TEvent>( Func<TEvent, TId> viewIdSelector, Func<TView, TEvent, Task<bool>> shouldDelete) where TEvent : class { if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector)); return projectEvent<TEvent>( (session, @event, streamId) => viewIdSelector(@event as TEvent), null, null, (_, view, @event) => shouldDelete(view, @event), ProjectionEventType.Delete); } public ViewProjection<TView, TId> DeleteEventAsync<TEvent>( Func<TEvent, TId> viewIdSelector, Func<IDocumentSession, TView, TEvent, Task<bool>> shouldDelete) where TEvent : class { if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector)); return projectEvent<TEvent>( (session, @event, streamId) => viewIdSelector(@event as TEvent), null, null, shouldDelete, ProjectionEventType.Delete); } public ViewProjection<TView, TId> DeleteEventAsync<TEvent>( Func<IDocumentSession, TEvent, TId> viewIdSelector, Func<TView, TEvent, Task<bool>> shouldDelete) where TEvent : class { if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector)); return projectEvent<TEvent>( (session, @event, streamId) => viewIdSelector(session, @event as TEvent), null, null, (_, view, @event) => shouldDelete(view, @event), ProjectionEventType.Delete); } public ViewProjection<TView, TId> DeleteEventAsync<TEvent>( Func<IDocumentSession, TEvent, TId> viewIdSelector, Func<IDocumentSession, TView, TEvent, Task<bool>> shouldDelete) where TEvent : class { if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector)); return projectEvent<TEvent>( (session, @event, streamId) => viewIdSelector(session, @event as TEvent), null, null, shouldDelete, ProjectionEventType.Delete); } public ViewProjection<TView, TId> DeleteEventAsync<TEvent>( Func<TEvent, List<TId>> viewIdsSelector, Func<TView, TEvent, Task<bool>> shouldDelete) where TEvent : class { if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector)); return projectEvent<TEvent>( null, (session, @event, streamId) => viewIdsSelector(@event as TEvent), null, (_, view, @event) => shouldDelete(view, @event), ProjectionEventType.Delete); } public ViewProjection<TView, TId> DeleteEvent<TEvent>( Func<TEvent, List<TId>> viewIdsSelector, Func<IDocumentSession, TView, TEvent, Task<bool>> shouldDelete) where TEvent : class { if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector)); return projectEvent<TEvent>( null, (session, @event, streamId) => viewIdsSelector(@event as TEvent), null, shouldDelete, ProjectionEventType.Delete); } public ViewProjection<TView, TId> DeleteEventAsync<TEvent>( Func<IDocumentSession, TEvent, List<TId>> viewIdsSelector, Func<TView, TEvent, Task<bool>> shouldDelete) where TEvent : class { if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector)); return projectEvent<TEvent>( null, (session, @event, streamId) => viewIdsSelector(session, @event as TEvent), null, (_, view, @event) => shouldDelete(view, @event), ProjectionEventType.Delete); } public ViewProjection<TView, TId> DeleteEvent<TEvent>( Func<IDocumentSession, TEvent, List<TId>> viewIdsSelector, Func<IDocumentSession, TView, TEvent, Task<bool>> shouldDelete) where TEvent : class { if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector)); return projectEvent<TEvent>( null, (session, @event, streamId) => viewIdsSelector(session, @event as TEvent), null, shouldDelete, ProjectionEventType.Delete); } public ViewProjection<TView, TId> ProjectEvent<TEvent>(Action<TView, TEvent> handler, bool onlyUpdate = false) where TEvent : class => projectEvent( (session, @event, streamId) => convertToTId(streamId), null, (IDocumentSession _, TView view, TEvent @event) => { handler(view, @event); return Task.CompletedTask; }, type: onlyUpdate ? ProjectionEventType.UpdateOnly : ProjectionEventType.CreateAndUpdate); public ViewProjection<TView, TId> ProjectEvent<TEvent>(Action<IDocumentSession, TView, TEvent> handler, bool onlyUpdate = false) where TEvent : class => projectEvent( (session, @event, streamId) => convertToTId(streamId), null, (IDocumentSession session, TView view, TEvent @event) => { handler(session, view, @event); return Task.CompletedTask; }, type: onlyUpdate ? ProjectionEventType.UpdateOnly : ProjectionEventType.CreateAndUpdate); public ViewProjection<TView, TId> ProjectEvent<TEvent>(Func<IDocumentSession, TEvent, TId> viewIdSelector, Action<TView, TEvent> handler, bool onlyUpdate = false) where TEvent : class { if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector)); return projectEvent( (session, @event, streamId) => viewIdSelector(session, @event as TEvent), null, (IDocumentSession _, TView view, TEvent @event) => { handler(view, @event); return Task.CompletedTask; }, type: onlyUpdate ? ProjectionEventType.UpdateOnly : ProjectionEventType.CreateAndUpdate); } public ViewProjection<TView, TId> ProjectEvent<TEvent>(Func<IDocumentSession, TEvent, TId> viewIdSelector, Action<IDocumentSession, TView, TEvent> handler, bool onlyUpdate = false) where TEvent : class { if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector)); return projectEvent( (session, @event, streamId) => viewIdSelector(session, @event as TEvent), null, (IDocumentSession session, TView view, TEvent @event) => { handler(session, view, @event); return Task.CompletedTask; }, type: onlyUpdate ? ProjectionEventType.UpdateOnly : ProjectionEventType.CreateAndUpdate); } public ViewProjection<TView, TId> ProjectEvent<TEvent>(Func<TEvent, TId> viewIdSelector, Action<TView, TEvent> handler, bool onlyUpdate = false) where TEvent : class { if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector)); return projectEvent( (session, @event, streamId) => viewIdSelector(@event as TEvent), null, (IDocumentSession _, TView view, TEvent @event) => { handler(view, @event); return Task.CompletedTask; }, type: onlyUpdate ? ProjectionEventType.UpdateOnly : ProjectionEventType.CreateAndUpdate); } public ViewProjection<TView, TId> ProjectEvent<TEvent>(Func<TEvent, TId> viewIdSelector, Action<IDocumentSession, TView, TEvent> handler, bool onlyUpdate = false) where TEvent : class { if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector)); return projectEvent( (session, @event, streamId) => viewIdSelector(@event as TEvent), null, (IDocumentSession session, TView view, TEvent @event) => { handler(session, view, @event); return Task.CompletedTask; }, type: onlyUpdate ? ProjectionEventType.UpdateOnly : ProjectionEventType.CreateAndUpdate); } public ViewProjection<TView, TId> ProjectEvent<TEvent>(Func<IDocumentSession, TEvent, List<TId>> viewIdsSelector, Action<TView, TEvent> handler, bool onlyUpdate = false) where TEvent : class { if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector)); return projectEvent( null, (session, @event, streamId) => viewIdsSelector(session, @event as TEvent), (IDocumentSession _, TView view, TEvent @event) => { handler(view, @event); return Task.CompletedTask; }, type: onlyUpdate ? ProjectionEventType.UpdateOnly : ProjectionEventType.CreateAndUpdate); } public ViewProjection<TView, TId> ProjectEvent<TEvent>(Func<IDocumentSession, TEvent, List<TId>> viewIdsSelector, Action<IDocumentSession, TView, TEvent> handler, bool onlyUpdate = false) where TEvent : class { if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector)); return projectEvent( null, (session, @event, streamId) => viewIdsSelector(session, @event as TEvent), (IDocumentSession session, TView view, TEvent @event) => { handler(session, view, @event); return Task.CompletedTask; }, type: onlyUpdate ? ProjectionEventType.UpdateOnly : ProjectionEventType.CreateAndUpdate); } public ViewProjection<TView, TId> ProjectEvent<TEvent>(Func<TEvent, List<TId>> viewIdsSelector, Action<TView, TEvent> handler, bool onlyUpdate = false) where TEvent : class { if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector)); return projectEvent( null, (session, @event, streamId) => viewIdsSelector(@event as TEvent), (IDocumentSession _, TView view, TEvent @event) => { handler(view, @event); return Task.CompletedTask; }, type: onlyUpdate ? ProjectionEventType.UpdateOnly : ProjectionEventType.CreateAndUpdate); } public ViewProjection<TView, TId> ProjectEvent<TEvent>(Func<TEvent, List<TId>> viewIdsSelector, Action<IDocumentSession, TView, TEvent> handler, bool onlyUpdate = false) where TEvent : class { if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector)); return projectEvent( null, (session, @event, streamId) => viewIdsSelector(@event as TEvent), (IDocumentSession session, TView view, TEvent @event) => { handler(session, view, @event); return Task.CompletedTask; }, type: onlyUpdate ? ProjectionEventType.UpdateOnly : ProjectionEventType.CreateAndUpdate); } public ViewProjection<TView, TId> ProjectEventAsync<TEvent>(Func<TView, TEvent, Task> handler, bool onlyUpdate = false) where TEvent : class => projectEvent( (session, @event, streamId) => convertToTId(streamId), null, (IDocumentSession _, TView view, TEvent @event) => handler(view, @event), type: onlyUpdate ? ProjectionEventType.UpdateOnly : ProjectionEventType.CreateAndUpdate); public ViewProjection<TView, TId> ProjectEventAsync<TEvent>(Func<IDocumentSession, TView, TEvent, Task> handler, bool onlyUpdate = false) where TEvent : class => projectEvent( (session, @event, streamId) => convertToTId(streamId), null, handler, type: onlyUpdate ? ProjectionEventType.UpdateOnly : ProjectionEventType.CreateAndUpdate); public ViewProjection<TView, TId> ProjectEventAsync<TEvent>(Func<IDocumentSession, TEvent, TId> viewIdSelector, Func<TView, TEvent, Task> handler, bool onlyUpdate = false) where TEvent : class { if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector)); return projectEvent( (session, @event, streamId) => viewIdSelector(session, @event as TEvent), null, (IDocumentSession _, TView view, TEvent @event) => handler(view, @event), type: onlyUpdate ? ProjectionEventType.UpdateOnly : ProjectionEventType.CreateAndUpdate); } public ViewProjection<TView, TId> ProjectEventAsync<TEvent>(Func<IDocumentSession, TEvent, TId> viewIdSelector, Func<IDocumentSession, TView, TEvent, Task> handler, bool onlyUpdate = false) where TEvent : class { if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector)); return projectEvent( (session, @event, streamId) => viewIdSelector(session, @event as TEvent), null, handler, type: onlyUpdate ? ProjectionEventType.UpdateOnly : ProjectionEventType.CreateAndUpdate); } public ViewProjection<TView, TId> ProjectEventAsync<TEvent>(Func<TEvent, TId> viewIdSelector, Func<TView, TEvent, Task> handler, bool onlyUpdate = false) where TEvent : class { if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector)); return projectEvent( (session, @event, streamId) => viewIdSelector(@event as TEvent), null, (IDocumentSession _, TView view, TEvent @event) => handler(view, @event), type: onlyUpdate ? ProjectionEventType.UpdateOnly : ProjectionEventType.CreateAndUpdate); } public ViewProjection<TView, TId> ProjectEventAsync<TEvent>(Func<TEvent, TId> viewIdSelector, Func<IDocumentSession, TView, TEvent, Task> handler, bool onlyUpdate = false) where TEvent : class { if (viewIdSelector == null) throw new ArgumentNullException(nameof(viewIdSelector)); return projectEvent( (session, @event, streamId) => viewIdSelector(@event as TEvent), null, handler, type: onlyUpdate ? ProjectionEventType.UpdateOnly : ProjectionEventType.CreateAndUpdate); } public ViewProjection<TView, TId> ProjectEventAsync<TEvent>(Func<IDocumentSession, TEvent, List<TId>> viewIdsSelector, Func<TView, TEvent, Task> handler, bool onlyUpdate = false) where TEvent : class { if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector)); return projectEvent( null, (session, @event, streamId) => viewIdsSelector(session, @event as TEvent), (IDocumentSession _, TView view, TEvent @event) => handler(view, @event), type: onlyUpdate ? ProjectionEventType.UpdateOnly : ProjectionEventType.CreateAndUpdate); } public ViewProjection<TView, TId> ProjectEventAsync<TEvent>(Func<IDocumentSession, TEvent, List<TId>> viewIdsSelector, Func<IDocumentSession, TView, TEvent, Task> handler, bool onlyUpdate = false) where TEvent : class { if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector)); return projectEvent( null, (session, @event, streamId) => viewIdsSelector(session, @event as TEvent), handler, type: onlyUpdate ? ProjectionEventType.UpdateOnly : ProjectionEventType.CreateAndUpdate); } public ViewProjection<TView, TId> ProjectEventAsync<TEvent>(Func<TEvent, List<TId>> viewIdsSelector, Func<TView, TEvent, Task> handler, bool onlyUpdate = false) where TEvent : class { if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector)); return projectEvent( null, (session, @event, streamId) => viewIdsSelector(@event as TEvent), (IDocumentSession _, TView view, TEvent @event) => handler(view, @event), type: onlyUpdate ? ProjectionEventType.UpdateOnly : ProjectionEventType.CreateAndUpdate); } public ViewProjection<TView, TId> ProjectEventAsync<TEvent>(Func<TEvent, List<TId>> viewIdsSelector, Func<IDocumentSession, TView, TEvent, Task> handler, bool onlyUpdate = false) where TEvent : class { if (viewIdsSelector == null) throw new ArgumentNullException(nameof(viewIdsSelector)); return projectEvent( null, (session, @event, streamId) => viewIdsSelector(@event as TEvent), handler, type: onlyUpdate ? ProjectionEventType.UpdateOnly : ProjectionEventType.CreateAndUpdate); } private ViewProjection<TView, TId> projectEvent<TEvent>( Func<IDocumentSession, object, Guid, TId> viewIdSelector, Func<IDocumentSession, object, Guid, List<TId>> viewIdsSelector, Func<IDocumentSession, TView, TEvent, Task> handler, Func<IDocumentSession, TView, TEvent, Task<bool>> shouldDelete = null, ProjectionEventType type = ProjectionEventType.CreateAndUpdate) where TEvent : class { if (viewIdSelector == null && viewIdsSelector == null) throw new ArgumentException($"{nameof(viewIdSelector)} or {nameof(viewIdsSelector)} must be provided."); if (handler == null && type == ProjectionEventType.CreateAndUpdate) throw new ArgumentNullException(nameof(handler)); EventHandler eventHandler; if (type == ProjectionEventType.CreateAndUpdate || type == ProjectionEventType.UpdateOnly) { eventHandler = new EventHandler( viewIdSelector, viewIdsSelector, (session, view, @event) => handler(session, view, @event as TEvent), null, type); } else { eventHandler = new EventHandler( viewIdSelector, viewIdsSelector, null, shouldDelete == null ? (Func<IDocumentSession, TView, object, Task<bool>>)null : (session, view, @event) => shouldDelete(session, view, @event as TEvent), type); } _handlers.Add(typeof(TEvent), eventHandler); return this; } private TId convertToTId(Guid streamId) { if (streamId is TId) { return (TId)Convert.ChangeType(streamId, typeof(TId)); } else { throw new InvalidOperationException("IdSelector must be used if Id type is different than Guid."); } } void IProjection.Apply(IDocumentSession session, EventPage page) { var projections = getEventProjections(session, page); var viewIds = projections.Select(projection => projection.ViewId).Distinct().ToArray(); if (viewIds.Length > 0) { var views = _sessionLoadMany(session, viewIds); applyProjections(session, projections, views); } } async Task IProjection.ApplyAsync(IDocumentSession session, EventPage page, CancellationToken token) { var projections = getEventProjections(session, page); var viewIds = projections.Select(projection => projection.ViewId).Distinct().ToArray(); if (viewIds.Length > 0) { var views = _sessionLoadMany(session, viewIds); await applyProjectionsAsync(session, projections, views); } } private void applyProjections(IDocumentSession session, ICollection<EventProjection> projections, IEnumerable<TView> views) { var idAssigner = session.Tenant.IdAssignmentFor<TView>(); var resolver = session.Tenant.StorageFor<TView>(); var viewMap = views.ToDictionary(view => (TId)resolver.IdentityFor(view), view => view); foreach (var eventProjection in projections) { var viewId = eventProjection.ViewId; var hasExistingView = viewMap.TryGetValue(viewId, out var view); if (!hasExistingView) { if (eventProjection.Type == ProjectionEventType.CreateAndUpdate) { view = newView(session.Tenant, idAssigner, viewId); viewMap.Add(viewId, view); hasExistingView = true; } } using (NoSynchronizationContextScope.Enter()) { if (eventProjection.Type == ProjectionEventType.CreateAndUpdate || (eventProjection.Type == ProjectionEventType.UpdateOnly && hasExistingView)) { session.Store(view); eventProjection.ProjectTo(session, view).Wait(); } else if (eventProjection.Type == ProjectionEventType.Delete && hasExistingView) { var shouldDeleteTask = eventProjection.ShouldDelete(session, view); shouldDeleteTask.Wait(); if (shouldDeleteTask.Result) { session.Delete(view); } } } } } private async Task applyProjectionsAsync(IDocumentSession session, ICollection<EventProjection> projections, IEnumerable<TView> views) { var idAssigner = session.Tenant.IdAssignmentFor<TView>(); var resolver = session.Tenant.StorageFor<TView>(); var viewMap = views.ToDictionary(view => (TId)resolver.IdentityFor(view), view => view); foreach (var eventProjection in projections) { var viewId = eventProjection.ViewId; var hasExistingView = viewMap.TryGetValue(viewId, out var view); if (!hasExistingView) { if (eventProjection.Type == ProjectionEventType.CreateAndUpdate) { view = newView(session.Tenant, idAssigner, viewId); viewMap.Add(viewId, view); hasExistingView = true; } } if (eventProjection.Type == ProjectionEventType.CreateAndUpdate || (eventProjection.Type == ProjectionEventType.UpdateOnly && hasExistingView)) { session.Store(view); eventProjection.ProjectTo(session, view).Wait(); } else if (eventProjection.Type == ProjectionEventType.Delete && hasExistingView && await eventProjection.ShouldDelete(session, view)) { session.Delete(view); } } } private static TView newView(ITenant tenant, IdAssignment<TView> idAssigner, TId id) { var view = New<TView>.Instance(); idAssigner.Assign(tenant, view, id); return view; } private IList<EventProjection> getEventProjections(IDocumentSession session, EventPage page) { var projections = new List<EventProjection>(); foreach (var streamEvent in page.Events) { EventHandler handler; var eventType = streamEvent.Data.GetType(); if (_handlers.TryGetValue(eventType, out handler)) { appendProjections(projections, handler, session, streamEvent, eventType, false); } else { var genericEventType = typeof(ProjectionEvent<>).MakeGenericType(eventType); if (_handlers.TryGetValue(genericEventType, out handler)) { appendProjections(projections, handler, session, streamEvent, genericEventType, true /* Yeah, genericEventType would always be ProjectionEvent<>. */); } } } return projections; } private void appendProjections(List<EventProjection> projections, EventHandler handler, IDocumentSession session, IEvent streamEvent, Type eventType, bool isProjectionEvent) { object projectionEvent = null; if (isProjectionEvent) { var timestamp = streamEvent.Timestamp.UtcDateTime; projectionEvent = Activator.CreateInstance( eventType, streamEvent.Id, streamEvent.Version, // Inline projections don't have the timestamp set, set it manually timestamp == default ? DateTime.UtcNow : timestamp, streamEvent.Sequence, streamEvent.StreamId, streamEvent.StreamKey, streamEvent.TenantId, streamEvent.Data ); } if (handler.IdSelector != null) { var viewId = handler.IdSelector(session, isProjectionEvent ? projectionEvent : streamEvent.Data, streamEvent.StreamId); if (!EqualityComparer<TId>.Default.Equals(viewId, default)) { projections.Add(new EventProjection(handler, viewId, streamEvent, projectionEvent)); } } else { foreach (var viewId in handler.IdsSelector(session, isProjectionEvent ? projectionEvent : streamEvent.Data, streamEvent.StreamId)) { if (!EqualityComparer<TId>.Default.Equals(viewId, default)) { projections.Add(new EventProjection(handler, viewId, streamEvent, projectionEvent)); } } } } private Type[] getUniqueEventTypes() { return _handlers.Keys .Distinct() .Select(type => { var genericType = type.GenericTypeArguments.FirstOrDefault(); if (genericType == null) { return type; } else { return genericType; } }) .ToArray(); } } public class ProjectionEvent<T> { public Guid Id { get; protected set; } public int Version { get; protected set; } public DateTime Timestamp { get; protected set; } public T Data { get; protected set; } public long Sequence { get; protected set; } public Guid StreamId { get; protected set; } public string StreamKey { get; protected set; } public string TenantId { get; protected set; } public ProjectionEvent(Guid id, int version, DateTime timestamp, long sequence, Guid streamId, string streamKey, string tenantId, T data) { Id = id; Version = version; Timestamp = timestamp; Sequence = sequence; StreamId = streamId; StreamKey = streamKey; TenantId = tenantId; Data = data; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Binary { using System; using System.Collections.Generic; using System.Diagnostics; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Common; /// <summary> /// Utilities for binary hash codes. /// </summary> internal static class BinaryHashCodeUtils { /// <summary> /// Gets the Ignite-specific hash code for the provided value. /// </summary> public static unsafe int GetHashCode<T>(T val, Marshaller marsh, IDictionary<int, int> affinityKeyFieldIds) { Debug.Assert(marsh != null); Debug.Assert(val != null); var type = val.GetType(); if (type == typeof(int)) return TypeCaster<int>.Cast(val); if (type == typeof(long)) return GetLongHashCode(TypeCaster<long>.Cast(val)); if (type == typeof(string)) return BinaryUtils.GetStringHashCode((string) (object) val); if (type == typeof(Guid)) return GetGuidHashCode(TypeCaster<Guid>.Cast(val)); if (type == typeof(uint)) { var val0 = TypeCaster<uint>.Cast(val); return *(int*) &val0; } if (type == typeof(ulong)) { var val0 = TypeCaster<ulong>.Cast(val); return GetLongHashCode(*(long*) &val0); } if (type == typeof(bool)) return TypeCaster<bool>.Cast(val) ? 1231 : 1237; if (type == typeof(byte)) return unchecked((sbyte) TypeCaster<byte>.Cast(val)); if (type == typeof(short)) return TypeCaster<short>.Cast(val); if (type == typeof(char)) return TypeCaster<char>.Cast(val); if (type == typeof(float)) { var floatVal = TypeCaster<float>.Cast(val); return *(int*) &floatVal; } if (type == typeof(double)) { var doubleVal = TypeCaster<double>.Cast(val); return GetLongHashCode(*(long*) &doubleVal); } if (type == typeof(sbyte)) return TypeCaster<sbyte>.Cast(val); if (type == typeof(ushort)) { var val0 = TypeCaster<ushort>.Cast(val); return *(short*) &val0; } if (type == typeof(IntPtr)) { var val0 = TypeCaster<IntPtr>.Cast(val).ToInt64(); return GetLongHashCode(val0); } if (type == typeof(UIntPtr)) { var val0 = TypeCaster<UIntPtr>.Cast(val).ToUInt64(); return GetLongHashCode(*(long*) &val0); } if (type.IsArray) { return GetArrayHashCode(val, marsh, affinityKeyFieldIds); } if (type == typeof(BinaryObject)) { return val.GetHashCode(); } // DateTime, when used as key, is always written as BinaryObject. return GetComplexTypeHashCode(val, marsh, affinityKeyFieldIds); } /// <summary> /// Gets the Ignite-specific hash code for an array. /// </summary> private static int GetArrayHashCode<T>(T val, Marshaller marsh, IDictionary<int, int> affinityKeyFieldIds) { var res = 1; var bytes = val as sbyte[]; // Matches byte[] too. if (bytes != null) { foreach (var x in bytes) res = 31 * res + x; return res; } var ints = val as int[]; // Matches uint[] too. if (ints != null) { foreach (var x in ints) res = 31 * res + x; return res; } var longs = val as long[]; // Matches ulong[] too. if (longs != null) { foreach (var x in longs) res = 31 * res + GetLongHashCode(x); return res; } var guids = val as Guid[]; if (guids != null) { foreach (var x in guids) res = 31 * res + GetGuidHashCode(x); return res; } var shorts = val as short[]; // Matches ushort[] too. if (shorts != null) { foreach (var x in shorts) res = 31 * res + x; return res; } var chars = val as char[]; if (chars != null) { foreach (var x in chars) res = 31 * res + x; return res; } // This covers all other arrays. // We don't have special handling for unlikely use cases such as float[] and double[]. var arr = val as Array; Debug.Assert(arr != null); if (arr.Rank != 1) { throw new IgniteException( string.Format("Failed to compute hash code for object '{0}' of type '{1}': " + "multidimensional arrays are not supported", val, val.GetType())); } foreach (var element in arr) { res = 31 * res + (element == null ? 0 : GetHashCode(element, marsh, affinityKeyFieldIds)); } return res; } // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local private static int GetComplexTypeHashCode<T>(T val, Marshaller marsh, IDictionary<int, int> affinityKeyFieldIds) { using (var stream = new BinaryHeapStream(128)) { var writer = marsh.StartMarshal(stream); int? hashCode = null; writer.OnObjectWritten += (header, obj) => { if (affinityKeyFieldIds != null && affinityKeyFieldIds.ContainsKey(header.TypeId)) { var err = string.Format( "Affinity keys are not supported. Object '{0}' has an affinity key.", obj); throw new IgniteException(err); } // In case of composite objects we need the last hash code. hashCode = header.HashCode; }; writer.Write(val); if (hashCode != null) { // ReSharper disable once PossibleInvalidOperationException (false detection). return hashCode.Value; } throw new IgniteException( string.Format("Failed to compute hash code for object '{0}' of type '{1}'", val, val.GetType())); } } private static int GetLongHashCode(long longVal) { return (int) (longVal ^ ((longVal >> 32) & 0xFFFFFFFF)); } private static unsafe int GetGuidHashCode(Guid val) { var bytes = val.ToByteArray(); byte* jBytes = stackalloc byte[16]; jBytes[0] = bytes[6]; // c1 jBytes[1] = bytes[7]; // c2 jBytes[2] = bytes[4]; // b1 jBytes[3] = bytes[5]; // b2 jBytes[4] = bytes[0]; // a1 jBytes[5] = bytes[1]; // a2 jBytes[6] = bytes[2]; // a3 jBytes[7] = bytes[3]; // a4 jBytes[8] = bytes[15]; // k jBytes[9] = bytes[14]; // j jBytes[10] = bytes[13]; // i jBytes[11] = bytes[12]; // h jBytes[12] = bytes[11]; // g jBytes[13] = bytes[10]; // f jBytes[14] = bytes[9]; // e jBytes[15] = bytes[8]; // d var hi = *(long*) &jBytes[0]; var lo = *(long*) &jBytes[8]; var hilo = hi ^ lo; return (int) (hilo ^ ((hilo >> 32) & 0xFFFFFFFF)); } } }
namespace PokerTell.DatabaseSetup.Tests { using System; using Microsoft.Practices.Composite.Events; using Microsoft.Practices.Unity; using Moq; using NUnit.Framework; using PokerTell.DatabaseSetup.ViewModels; using PokerTell.Infrastructure.Interfaces.DatabaseSetup; public class ConfigureDataProviderViewModelTests { #region Constants and Fields IUnityContainer _container; StubBuilder _stub; #endregion #region Public Methods [SetUp] public void _Init() { _stub = new StubBuilder(); _container = new UnityContainer() .RegisterType<IEventAggregator, EventAggregator>() .RegisterInstance(_stub.Out<IDatabaseSettings>()) .RegisterInstance(_stub.Out<IDataProvider>()) .RegisterInstance(_stub.Out<IDatabaseConnector>()); } [Test] public void Initialize_SettingsContainServerConnectStringForDataProvider_InitializesAccordingToServerConnectString() { var dataProviderInfo = new MySqlInfo(); const string serverConnectStringFoundInSettings = "data source = servername; user id = username; password = pass;"; var settingsMock = new Mock<IDatabaseSettings>(); settingsMock .Setup(ds => ds.ProviderIsAvailable(dataProviderInfo)) .Returns(true); settingsMock .Setup(ds => ds.GetServerConnectStringFor(dataProviderInfo)) .Returns(serverConnectStringFoundInSettings); _container .RegisterInstance(settingsMock.Object); var sut = _container .Resolve<ConfigureDataProviderViewModelMock>(); sut.DataProviderInfoMock = dataProviderInfo; sut.Initialize(); string actualServerConnectString = new DatabaseConnectionInfo(sut.ServerName, sut.UserName, sut.Password).ServerConnectString; Assert.That(actualServerConnectString, Is.EqualTo(serverConnectStringFoundInSettings)); } [Test] public void Initialize_SettingsDontContainServerConnectStringForDataProvider_InitializesToDefault() { var settingsMock = new Mock<IDatabaseSettings>(); settingsMock .Setup(ds => ds.ProviderIsAvailable(It.IsAny<IDataProviderInfo>())) .Returns(false); _container .RegisterInstance(settingsMock.Object); ConfigureDataProviderViewModel sut = _container .Resolve<ConfigureDataProviderViewModelMock>() .Initialize(); bool initializedToDefault = sut.ServerName.Equals("localhost") && sut.UserName.Equals("root") && sut.Password.Equals(string.Empty); Assert.That(initializedToDefault, Is.True); } [Test] public void SaveCommandExecute_ValidSetupValues_SavesServerConnectStringToDatabaseSettings() { var settingsMock = new Mock<IDatabaseSettings>(); _container .RegisterInstance(settingsMock.Object); ConfigureDataProviderViewModelMock sut = _container .Resolve<ConfigureDataProviderViewModelMock>() .InitializeServerNameUserNameAndPasswordToValidValues(); sut.SaveCommand.Execute(null); settingsMock.Verify(ds => ds.SetServerConnectStringFor(sut.DataProviderInfoMock, It.IsAny<string>())); } [Test] public void TestConnectionCommandCanExecute_PasswordEmpty_ReturnsTrue() { ConfigureDataProviderViewModelMock sut = _container .Resolve<ConfigureDataProviderViewModelMock>() .InitializeServerNameUserNameAndPasswordToValidValues(); sut.Password = string.Empty; Assert.That(sut.TestConnectionCommand.CanExecute(null), Is.True); } [Test] public void TestConnectionCommandCanExecute_ServerNameEmpty_ReturnsFalse() { ConfigureDataProviderViewModelMock sut = _container .Resolve<ConfigureDataProviderViewModelMock>() .InitializeServerNameUserNameAndPasswordToValidValues(); sut.ServerName = string.Empty; Assert.That(sut.TestConnectionCommand.CanExecute(null), Is.False); } [Test] public void TestConnectionCommandCanExecute_ServerNameNotSet_ReturnsFalse() { ConfigureDataProviderViewModelMock sut = _container .Resolve<ConfigureDataProviderViewModelMock>() .InitializeServerNameUserNameAndPasswordToValidValues(); sut.ServerName = null; Assert.That(sut.TestConnectionCommand.CanExecute(null), Is.False); } [Test] public void TestConnectionCommandCanExecute_ServerNameUserNameAndPasswordValid_ReturnsTrue() { ConfigureDataProviderViewModelMock sut = _container .Resolve<ConfigureDataProviderViewModelMock>() .InitializeServerNameUserNameAndPasswordToValidValues(); Assert.That(sut.TestConnectionCommand.CanExecute(null), Is.True); } [Test] public void TestConnectionCommandCanExecute_UserNameEmpty_ReturnsFalse() { ConfigureDataProviderViewModelMock sut = _container .Resolve<ConfigureDataProviderViewModelMock>() .InitializeServerNameUserNameAndPasswordToValidValues(); sut.UserName = string.Empty; Assert.That(sut.TestConnectionCommand.CanExecute(null), Is.False); } [Test] public void TestConnectionCommandCanExecute_UserNameNotSet_ReturnsFalse() { ConfigureDataProviderViewModelMock sut = _container .Resolve<ConfigureDataProviderViewModelMock>() .InitializeServerNameUserNameAndPasswordToValidValues(); sut.UserName = null; Assert.That(sut.TestConnectionCommand.CanExecute(null), Is.False); } [Test] public void TestConnectionCommandExecute_DataProviderDoesNotThrowError_ObtainsServerConnectString() { ConfigureDataProviderViewModelMock sut = _container .Resolve<ConfigureDataProviderViewModelMock>() .InitializeServerNameUserNameAndPasswordToValidValues(); sut.TestConnectionCommand.Execute(null); Assert.That(sut.ServerConnectString, Is.Not.EqualTo(string.Empty)); } [Test] public void TestConnectionCommandExecute_DataProviderSuccessfullyOpensConnection_SaveCommandCanExecute() { var dataProviderStub = new Mock<IDataProvider>(); dataProviderStub .SetupGet(dp => dp.IsConnectedToServer) .Returns(true); var databaseConnectorStub = new Mock<IDatabaseConnector>(); databaseConnectorStub .SetupGet(dc => dc.DataProvider) .Returns(dataProviderStub.Object); _container .RegisterInstance(dataProviderStub.Object) .RegisterInstance(databaseConnectorStub.Object); ConfigureDataProviderViewModelMock sut = _container .Resolve<ConfigureDataProviderViewModelMock>() .InitializeServerNameUserNameAndPasswordToValidValues(); sut.TestConnectionCommand.Execute(null); Assert.That(sut.SaveCommand.CanExecute(null), Is.True); } [Test] public void TestConnectionCommandExecute_DataProviderCannotOpenConnection_SaveCommandCannotExecute() { var dataProviderStub = new Mock<IDataProvider>(); dataProviderStub .SetupGet(dp => dp.IsConnectedToServer) .Returns(false); _container .RegisterInstance(dataProviderStub.Object); ConfigureDataProviderViewModelMock sut = _container .Resolve<ConfigureDataProviderViewModelMock>() .InitializeServerNameUserNameAndPasswordToValidValues(); sut.TestConnectionCommand.Execute(null); Assert.That(sut.SaveCommand.CanExecute(null), Is.False); } #endregion } internal class ConfigureDataProviderViewModelMock : ConfigureDataProviderViewModel { #region Constructors and Destructors public ConfigureDataProviderViewModelMock( IEventAggregator eventAggregator, IDatabaseSettings databaseSettings, IDatabaseConnector databaseConnector) : base(eventAggregator, databaseSettings, databaseConnector) { DataProviderInfoMock = new SqLiteInfo(); } #endregion #region Properties public IDataProviderInfo DataProviderInfoMock { get; set; } public string ServerConnectString { get { return _serverConnectString; } } protected override IDataProviderInfo DataProviderInfo { get { return DataProviderInfoMock; } } #endregion #region Public Methods public ConfigureDataProviderViewModelMock InitializeServerNameUserNameAndPasswordToValidValues() { ServerName = "someServer"; UserName = "someUser"; Password = "somePassword"; return this; } #endregion } }
using SDL2; using System; using System.Collections.Generic; using static System.Math; namespace Doomnet { public class ViewRenderer { private const double TO_RADIAN = PI / 180; private readonly int sWidth; private readonly int sHeight; private readonly IntPtr viewSurface; private readonly IntPtr renderer; private readonly IntPtr mapRenderer; private readonly IntPtr mapSurface = SDL.SDL_CreateRGBSurface(0, 5000, 5000, 32, 0, 0, 0, 0); private double aDelta; public ViewRenderer(int width, int height) { sWidth = width; sHeight = height; viewSurface = SDL.SDL_CreateRGBSurface(0, width, height, 32, 0, 0, 0, 0); renderer = SDL.SDL_CreateSoftwareRenderer(ViewSurface); mapRenderer = SDL.SDL_CreateSoftwareRenderer(MapSurface); } public IntPtr MapSurface { get { return mapSurface; } } public IntPtr ViewSurface { get { return viewSurface; } } public IntPtr Renderer { get { return renderer; } } /// <summary> /// Get point intersecting the side of the level bounding box /// </summary> /// <param name="posX">X position of the player</param> /// <param name="posY">Y position of the player</param> /// <param name="angle">View angle of the player</param> /// <param name="width">width of the level Bounding box</param> /// <param name="height">height of the level bounding box</param> /// <returns></returns> public Tuple<double, double> GetSideLine(int posX, int posY, double angle, int width, int height) { int p0X = posX; int p0Y = posY; var alph = angle; double p1X; double p1Y; if (alph >= 0 && alph < 45) { p1Y = (width - p0X) * Tan(alph * TO_RADIAN) + p0Y; p1X = width; } else if (alph >= 45 && alph < 135) { p1X = p0X - (height - p0Y) * Tan((alph - 90) * TO_RADIAN); p1Y = height; } else if (alph >= 135 && alph < 225) { p1Y = p0Y - p0X * Tan((alph - 180) * TO_RADIAN); p1X = 0; } else if (alph >= 225 && alph < 315) { p1X = p0Y * Tan((alph - 270) * TO_RADIAN) + p0X; p1Y = 0; } else if (alph < 360 && alph >= 315) { p1Y = (width - p0X) * Tan(alph * TO_RADIAN) + p0Y; p1X = width; } else { throw new ArgumentOutOfRangeException(nameof(angle), $"Angle must be between 0 and 360, value is {angle}"); } return new Tuple<double, double>(p1X, p1Y); } private Level level; private int column; private PointD point1 = new PointD(); private PointD point2 = new PointD(); /// <summary> /// Draw what is visible to the player /// </summary> /// <param name="start">Player position</param> /// <param name="angle">Player view angle</param> /// <param name="level">Current level</param> /// <returns></returns> public IntPtr DrawVision(Thing start, int angle, Level level) { this.level = level; SDL.SDL_SetRenderDrawColor(mapRenderer, 100, 149, 237, 255); SDL.SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL.SDL_RenderFillRect(mapRenderer, IntPtr.Zero); SDL.SDL_RenderFillRect(renderer, IntPtr.Zero); int width = level.Width; int height = level.Height; const double baseAngle = 90; int p0X = start.posX; int p0Y = start.posY; var rootNode = level.RootNode; var i = 0; aDelta = baseAngle * i / sWidth - baseAngle / 2; var alpha = aDelta + angle; if (alpha < 0) alpha += 360; alpha = alpha % 360; var point = GetSideLine(p0X, p0Y, alpha, width, height); var p1X = point.Item1; var p1Y = point.Item2; point2 = new PointD { X = p1X, Y = p1Y }; SortSectors(rootNode, new PointD { X = start.posX, Y = start.posY }); SDL.SDL_SetRenderDrawColor(mapRenderer, 255, 0, 0, 255); SDL.SDL_RenderDrawLine(mapRenderer, (int)p0X, (int)p0Y, (int)p1X, (int)p1Y); //foreach (var sector in sectors) //{ // column = i; // //RenderNode(rootNode, new PointD {X = start.posX, Y = start.posY}, new PointD {X = p1X, Y = p1Y}); // RenderSsector(sector, new PointD {X = start.posX, Y = start.posY}, new PointD {X = p1X, Y = p1Y}); //} //Marshal.Copy(pixels, 0, structure.pixels, 1024 * 768); SDL.SDL_RenderPresent(renderer); SDL.SDL_RenderPresent(mapRenderer); return ViewSurface; } private double GetPointsAngle(PointD a, PointD b, PointD c) { var ab2 = Pow(a.X - b.X, 2) + Pow(a.Y - b.Y, 2); var ac2 = Pow(a.X - c.X, 2) + Pow(a.Y - c.Y, 2); var bc2 = Pow(b.X - c.X, 2) + Pow(b.Y - c.Y, 2); var sqrt = (2 * Sqrt(ab2) * Sqrt(ac2)); var div = (ab2 + ac2 - bc2) / sqrt; var angle = Acos(div); if (div > 1 || div < -1) { angle = 0; } if (FindSide(a, b, c) < 0) angle = -angle; return angle; } private int AngleToScreen(double angle) { angle = -45.0 * TO_RADIAN + angle; if (angle < 0) angle = 2 * PI + angle; return (int)(Tan(angle) * sWidth / 2) + sWidth / 2; } private void RenderSsector(SSector sect, PointD start, PointD endLeft) { foreach (var segment in sect.Segments) { var line = segment.line; var leftAngle = GetPointsAngle(start, endLeft, new PointD { X = segment.start.X, Y = segment.start.Y }) / TO_RADIAN; var rightAngle = GetPointsAngle(start, endLeft, new PointD { X = segment.end.X, Y = segment.end.Y }) / TO_RADIAN; //if (leftAngle < rightAngle) //{ // continue; //} if (leftAngle > 90.0) { continue; } if (rightAngle < 0) { continue; } var side = FindSide(new PointD { X = segment.start.X, Y = segment.start.Y }, new PointD { X = segment.end.X, Y = segment.end.Y }, start); var sidedef = side >= 0 ? line.right : line.left; var oSidedef = side > 0 ? line.left : line.right; if (sidedef == null) continue; var distanceLeft = Sqrt(Pow(start.X - segment.start.X, 2) + Pow(start.Y - segment.start.Y, 2)); var distanceRight = Sqrt(Pow(start.X - segment.end.X, 2) + Pow(start.Y - segment.end.Y, 2)); //distance = Sqrt(distance)*Cos(aDelta*TO_RADIAN); var offset = segment.offset; Texture texture; short bottom; short top; var distanceDelt = distanceRight - distanceLeft; var min = AngleToScreen(leftAngle * TO_RADIAN); var max = AngleToScreen(rightAngle * TO_RADIAN); if (min > sWidth || max < 0) continue; var color = (byte)((distanceLeft / level.Width * 4) * 255); SDL.SDL_SetRenderDrawColor(mapRenderer, color, color, color, 255); SDL.SDL_SetRenderDrawColor(mapRenderer, (byte)segment.start.X, (byte)segment.start.Y, (byte)segment.angle, 255); SDL.SDL_RenderDrawLine(mapRenderer, (int)segment.start.X, (int)segment.start.Y, segment.end.X, segment.end.Y); //SDL.SDL_RenderDrawLine(mapRenderer, (int)start.X, (int)start.Y, segment.start.X, segment.start.Y); //SDL.SDL_RenderDrawLine(mapRenderer, (int)start.X, (int)start.Y, segment.end.X, segment.end.Y); if (oSidedef != null) { for (int i = min; i < max; i++) { var distance = distanceLeft + (distanceDelt) * (i - min) / (max - min); texture = sidedef.lower; if (texture != null) { bottom = sidedef.sector.bottom; top = oSidedef.sector.bottom; var loffset = (short)((offset + i) % texture.Width); DrawColumn(top, bottom, distance, texture, loffset, i); } texture = sidedef.upper; if (texture != null) { bottom = oSidedef.sector.top; top = sidedef.sector.top; var loffset = (short)((offset + i) % texture.Width); DrawColumn(top, bottom, distance, texture, loffset, i); } texture = sidedef.middle; if (texture != null) { bottom = oSidedef.sector.bottom; top = oSidedef.sector.top; var loffset = (short)((offset + i) % texture.Width); DrawColumn(top, bottom, distance, texture, loffset, i); } } } else { texture = sidedef.middle; if (texture == null) continue; bottom = sidedef.sector.bottom; top = sidedef.sector.top; for (int i = min; i < max; i++) { var loffset = (short)((offset + i) % texture.Width); var distance = distanceLeft + (distanceDelt) * (i - min) / (max - min); DrawColumn(top, bottom, distance, texture, loffset, i); } } } } private void DrawColumn(short top, short bottom, double distance, Texture texture, int offset, int column) { var wallHeight = top - bottom; var colHeight = (int)(wallHeight / distance * sHeight); var viewBottom = (int)((bottom - 64) / distance * sHeight); var srcrect = new SDL.SDL_Rect { h = colHeight, w = 1, x = offset, y = 0 }; var dstrect = new SDL.SDL_Rect { h = colHeight, w = 1, x = sWidth - column, y = sHeight / 2 - (viewBottom + colHeight) }; SDL.SDL_RenderCopy(renderer, texture.SdlTexture, ref srcrect, ref dstrect); } private int FindSide(PointD start, PointD end, PointD point) { return Sign((end.X - start.X) * (point.Y - start.Y) - (end.Y - start.Y) * (point.X - start.X) * -1); } private void SortSectors(Node node, PointD start) { var side = Sign((node.EndX - node.StartX) * (start.Y - node.StartY) - (node.EndY - node.StartY) * (start.X - node.StartX)); SDL.SDL_SetRenderDrawColor(mapRenderer, 0, 0, 0, 255); SDL.SDL_RenderDrawLine(mapRenderer, (int)node.StartX, (int)node.StartY, node.EndX, node.EndY); side = -side; if (side > 0) { List<SSector> l; if (node.LeftNode != null) SortSectors(node.LeftNode, start); else { RenderSsector(node.LeftSector, start, point2); } if (node.RightNode != null) SortSectors(node.RightNode, start); else { RenderSsector(node.RightSector, start, point2); } } else if (side <= 0) { List<SSector> l; if (node.RightNode != null) SortSectors(node.RightNode, start); else { RenderSsector(node.RightSector, start, point2); } if (node.LeftNode != null) SortSectors(node.LeftNode, start); else { RenderSsector(node.LeftSector, start, point2); } } else { return; //Debugger.Break(); } } public static Tuple<double, double> FindIntersection(double p0X, double p0Y, double p1X, double p1Y, double p2X, double p2Y, double p3X, double p3Y) { double s1X = p1X - p0X; double s1Y = p1Y - p0Y; double s2X = p3X - p2X; double s2Y = p3Y - p2Y; try { double s = (-s1Y * (p0X - p2X) + s1X * (p0Y - p2Y)) / (-s2X * s1Y + s1X * s2Y); double t = (s2X * (p0Y - p2Y) - s2Y * (p0X - p2X)) / (-s2X * s1Y + s1X * s2Y); if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { return new Tuple<double, double>(p0X + t * s1X, p0Y + t * s1Y); } } catch (DivideByZeroException) { return null; } return null; } } }
/* * Copyright (c) 2018 Algolia * http://www.algolia.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.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Algolia.Search.Http; using Algolia.Search.Models.ApiKeys; using Algolia.Search.Models.Batch; using Algolia.Search.Models.Common; using Algolia.Search.Models.Enums; using Algolia.Search.Models.Mcm; using Algolia.Search.Models.Personalization; using Algolia.Search.Models.Search; namespace Algolia.Search.Clients { /// <summary> /// Search Client interface /// </summary> public interface ISearchClient { /// <summary> /// Initialize an index for the given client /// </summary> /// <param name="indexName"></param> /// <returns></returns> SearchIndex InitIndex(string indexName); /// <summary> /// Retrieve one or more objects, potentially from different indices, in a single API call. /// </summary> /// <typeparam name="T">Type of the data to send/retrieve</typeparam> MultipleGetObjectsResponse<T> MultipleGetObjects<T>(IEnumerable<MultipleGetObject> queries, RequestOptions requestOptions = null) where T : class; /// <summary> /// Retrieve one or more objects, potentially from different indices, in a single API call. /// </summary> /// <typeparam name="T">Type of the data to send/retrieve</typeparam> Task<MultipleGetObjectsResponse<T>> MultipleGetObjectsAsync<T>( IEnumerable<MultipleGetObject> queries, RequestOptions requestOptions = null, CancellationToken ct = default) where T : class; /// <summary> /// This method allows to send multiple search queries, potentially targeting multiple indices, in a single API call. /// </summary> /// <typeparam name="T">Type of the data to send/retrieve</typeparam> MultipleQueriesResponse<T> MultipleQueries<T>(MultipleQueriesRequest request, RequestOptions requestOptions = null) where T : class; /// <summary> /// This method allows to send multiple search queries, potentially targeting multiple indices, in a single API call. /// </summary> /// <typeparam name="T">Type of the data to send/retrieve</typeparam> Task<MultipleQueriesResponse<T>> MultipleQueriesAsync<T>(MultipleQueriesRequest request, RequestOptions requestOptions = null, CancellationToken ct = default) where T : class; /// <summary> /// Perform multiple write operations, potentially targeting multiple indices, in a single API call. /// </summary> /// <typeparam name="T">Type of the data to send/retrieve</typeparam> MultipleIndexBatchIndexingResponse MultipleBatch<T>(IEnumerable<BatchOperation<T>> operations, RequestOptions requestOptions = null) where T : class; /// <summary> /// Perform multiple write operations, potentially targeting multiple indices, in a single API call. /// </summary> /// <typeparam name="T">Type of the data to send/retrieve</typeparam> Task<MultipleIndexBatchIndexingResponse> MultipleBatchAsync<T>( IEnumerable<BatchOperation<T>> operations, RequestOptions requestOptions = null, CancellationToken ct = default) where T : class; /// <summary> /// Get a list of indexes/indices with their associated metadata. /// </summary> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <returns></returns> ListIndicesResponse ListIndices(RequestOptions requestOptions = null); /// <summary> /// Get a list of indexes/indices with their associated metadata. /// </summary> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <param name="ct">Optional cancellation token</param> /// <returns></returns> Task<ListIndicesResponse> ListIndicesAsync(RequestOptions requestOptions = null, CancellationToken ct = default); /// <summary> /// Generate a virtual API Key without any call to the server. /// </summary> /// <param name="parentApiKey"></param> /// <param name="restriction"></param> /// <returns></returns> string GenerateSecuredApiKeys(string parentApiKey, SecuredApiKeyRestriction restriction); /// <summary> /// Gets how many seconds are left before the secured API key expires. /// </summary> /// <param name="securedAPIKey">The secured API Key</param> TimeSpan GetSecuredApiKeyRemainingValidity(string securedAPIKey); /// <summary> /// Get the full list of API Keys. /// </summary> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <returns></returns> ListApiKeysResponse ListApiKeys(RequestOptions requestOptions = null); /// <summary> /// Get the full list of API Keys. /// </summary> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <param name="ct">Optional cancellation token</param> /// <returns></returns> Task<ListApiKeysResponse> ListApiKeysAsync(RequestOptions requestOptions = null, CancellationToken ct = default); /// <summary> /// Get the permissions of an API Key. /// </summary> /// <param name="apiKey"></param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <returns></returns> ApiKey GetApiKey(string apiKey, RequestOptions requestOptions = null); /// <summary> /// Get the permissions of an API Key. /// </summary> /// <param name="apiKey"></param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <param name="ct">Optional cancellation token</param> /// <returns></returns> Task<ApiKey> GetApiKeyAsync(string apiKey, RequestOptions requestOptions = null, CancellationToken ct = default); /// <summary> /// Add a new API Key with specific permissions/restrictions. /// </summary> /// <param name="apiKey"></param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <returns></returns> AddApiKeyResponse AddApiKey(ApiKey apiKey, RequestOptions requestOptions = null); /// <summary> /// Add a new API Key with specific permissions/restrictions. /// </summary> /// <param name="apiKey"></param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <param name="ct">Optional cancellation token</param> /// <returns></returns> Task<AddApiKeyResponse> AddApiKeyAsync(ApiKey apiKey, RequestOptions requestOptions = null, CancellationToken ct = default); /// <summary> /// Update the permissions of an existing API Key. /// </summary> /// <param name="request"></param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <returns></returns> UpdateApiKeyResponse UpdateApiKey(ApiKey request, RequestOptions requestOptions = null); /// <summary> /// Update the permissions of an existing API Key. /// </summary> /// <param name="request"></param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <param name="ct">Optional cancellation token</param> /// <returns></returns> Task<UpdateApiKeyResponse> UpdateApiKeyAsync(ApiKey request, RequestOptions requestOptions = null, CancellationToken ct = default); /// <summary> /// Delete an existing API Key /// </summary> /// <param name="apiKey"></param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <returns></returns> DeleteApiKeyResponse DeleteApiKey(string apiKey, RequestOptions requestOptions = null); /// <summary> /// Delete an existing API Key /// </summary> /// <param name="apiKey"></param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <param name="ct">Optional cancellation token</param> /// <returns></returns> Task<DeleteApiKeyResponse> DeleteApiKeyAsync(string apiKey, RequestOptions requestOptions = null, CancellationToken ct = default); /// <summary> /// Restore the given APIKey /// </summary> /// <param name="apiKey">The API Key to restore</param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <returns></returns> RestoreApiKeyResponse RestoreApiKey(string apiKey, RequestOptions requestOptions = null); /// <summary> /// Restore the given APIKey /// </summary> /// <param name="apiKey">The API Key to restore</param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <param name="ct">Optional cancellation token</param> Task<RestoreApiKeyResponse> RestoreApiKeyAsync(string apiKey, RequestOptions requestOptions = null, CancellationToken ct = default); /// <summary> /// List the clusters available in a multi-clusters setup for a single appID /// </summary> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <returns></returns> IEnumerable<ClustersResponse> ListClusters(RequestOptions requestOptions = null); /// <summary> /// List the clusters available in a multi-clusters setup for a single appID /// </summary> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <param name="ct">Optional cancellation token</param> /// <returns></returns> Task<IEnumerable<ClustersResponse>> ListClustersAsync(RequestOptions requestOptions = null, CancellationToken ct = default); /// <summary> /// Search for userIDs /// The data returned will usually be a few seconds behind real-time, because userID usage may take up to a few seconds propagate to the different cluster /// </summary> /// <param name="query"></param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <returns></returns> SearchResponse<UserIdResponse> SearchUserIDs(SearchUserIdsRequest query, RequestOptions requestOptions = null); /// <summary> /// Search for userIDs /// The data returned will usually be a few seconds behind real-time, because userID usage may take up to a few seconds propagate to the different cluster /// </summary> /// <param name="query"></param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <param name="ct">Optional cancellation token</param> /// <returns></returns> Task<SearchResponse<UserIdResponse>> SearchUserIDsAsync(SearchUserIdsRequest query, RequestOptions requestOptions = null, CancellationToken ct = default); /// <summary> /// List the userIDs assigned to a multi-clusters appID. /// </summary> /// <param name="hitsPerPage"></param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <param name="page"></param> /// <returns></returns> ListUserIdsResponse ListUserIds(int page = 0, int hitsPerPage = 1000, RequestOptions requestOptions = null); /// <summary> /// List the userIDs assigned to a multi-clusters appID. /// </summary> /// <param name="hitsPerPage"></param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <param name="ct">Optional cancellation token</param> /// <param name="page"></param> /// <returns></returns> Task<ListUserIdsResponse> ListUserIdsAsync(int page = 0, int hitsPerPage = 1000, RequestOptions requestOptions = null, CancellationToken ct = default); /// <summary> /// Returns the userID data stored in the mapping. /// </summary> /// <param name="userId"></param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <returns></returns> UserIdResponse GetUserId(string userId, RequestOptions requestOptions = null); /// <summary> /// Returns the userID data stored in the mapping. /// </summary> /// <param name="userId"></param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <param name="ct">Optional cancellation token</param> /// <returns></returns> Task<UserIdResponse> GetUserIdAsync(string userId, RequestOptions requestOptions = null, CancellationToken ct = default); /// <summary> /// Get the top 10 userIDs with the highest number of records per cluster. /// The data returned will usually be a few seconds behind real-time, because userID usage may take up to a few seconds to propagate to the different clusters. /// </summary> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <returns></returns> TopUserIdResponse GetTopUserId(RequestOptions requestOptions = null); /// <summary> /// Get the top 10 userIDs with the highest number of records per cluster. /// The data returned will usually be a few seconds behind real-time, because userID usage may take up to a few seconds to propagate to the different clusters. /// </summary> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <param name="ct">Optional cancellation token</param> /// <returns></returns> Task<TopUserIdResponse> GetTopUserIdAsync(RequestOptions requestOptions = null, CancellationToken ct = default); /// <summary> /// Assign or Move a userID to a cluster. /// The time it takes to migrate (move) a user is proportional to the amount of data linked to the userID. /// </summary> /// <param name="userId"></param> /// <param name="clusterName"></param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <returns></returns> AssignUserIdResponse AssignUserId(string userId, string clusterName, RequestOptions requestOptions = null); /// <summary> /// Assign or Move a userID to a cluster. /// The time it takes to migrate (move) a user is proportional to the amount of data linked to the userID. /// </summary> /// <param name="userId"></param> /// <param name="clusterName"></param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <param name="ct">Optional cancellation token</param> /// <returns></returns> Task<AssignUserIdResponse> AssignUserIdAsync(string userId, string clusterName, RequestOptions requestOptions = null, CancellationToken ct = default); /// <summary> /// Assign or Move userIDs to a cluster. /// The time it takes to migrate (move) a user is proportional to the amount of data linked to each userID. /// </summary> /// <param name="users">List of users to save</param> /// <param name="clusterName">The cluster name</param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <returns></returns> AssignUserIdsResponse AssignUserIds(IEnumerable<string> users, string clusterName, RequestOptions requestOptions = null); /// <summary> /// Assign or Move userIDs to a cluster. /// The time it takes to migrate (move) a user is proportional to the amount of data linked to each userID. /// </summary> /// <param name="users">List of users to save</param> /// <param name="clusterName">The cluster name</param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <param name="ct">Optional cancellation token</param> /// <returns></returns> Task<AssignUserIdsResponse> AssignUserIdsAsync(IEnumerable<string> users, string clusterName, RequestOptions requestOptions = null, CancellationToken ct = default); /// <summary> /// Remove a userID and its associated data from the multi-clusters. /// </summary> /// <param name="userId"></param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <returns></returns> RemoveUserIdResponse RemoveUserId(string userId, RequestOptions requestOptions = null); /// <summary> /// Remove a userID and its associated data from the multi-clusters. /// </summary> /// <param name="userId"></param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <param name="ct">Optional cancellation token</param> /// <returns></returns> Task<RemoveUserIdResponse> RemoveUserIdAsync(string userId, RequestOptions requestOptions = null, CancellationToken ct = default); /// <summary> /// Get cluster pending (migrating, creating, deleting) mapping state. Query cluster pending mapping status and get cluster mappings. /// </summary> /// <param name="retrieveMappings">Whether or not the cluster mappings should be retrieved</param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> HasPendingMappingsResponse HasPendingMappings(bool retrieveMappings = false, RequestOptions requestOptions = null); /// <summary> /// Get cluster pending (migrating, creating, deleting) mapping state. Query cluster pending mapping status and get cluster mappings. /// </summary> /// <param name="retrieveMappings">Whether or not the cluster mappings should be retrieved</param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <param name="ct">Optional cancellation token</param> Task<HasPendingMappingsResponse> HasPendingMappingsAsync(bool retrieveMappings = false, RequestOptions requestOptions = null, CancellationToken ct = default); /// <summary> /// Get the logs of the latest search and indexing operations /// You can retrieve the logs of your last 1,000 API calls. It is designed for immediate, real-time debugging. /// </summary> /// <returns></returns> LogResponse GetLogs(RequestOptions requestOptions = null, int offset = 0, int length = 10); /// <summary> /// Get the logs of the latest search and indexing operations /// You can retrieve the logs of your last 1,000 API calls. It is designed for immediate, real-time debugging. /// </summary> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <param name="ct">Optional cancellation token</param> /// <param name="offset">Specify the first entry to retrieve (0-based, 0 is the most recent log entry).</param> /// <param name="length">Specify the maximum number of entries to retrieve starting at the offset. Maximum allowed value: 1,000.</param> /// <returns></returns> Task<LogResponse> GetLogsAsync(RequestOptions requestOptions = null, CancellationToken ct = default, int offset = 0, int length = 10); /// <summary> /// Copy the settings of an index to another index /// </summary> /// <param name="sourceIndex"></param> /// <param name="destinationIndex">The destination index</param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <returns></returns> CopyToResponse CopySettings(string sourceIndex, string destinationIndex, RequestOptions requestOptions = null); /// <summary> /// Copy the settings of an index to another index /// </summary> /// <param name="sourceIndex"></param> /// <param name="destinationIndex">The destination index</param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <param name="ct">Optional cancellation token</param> /// <returns></returns> Task<CopyToResponse> CopySettingsAsync(string sourceIndex, string destinationIndex, RequestOptions requestOptions = null, CancellationToken ct = default); /// <summary> /// Copy the rules of an index to another index /// </summary> /// <param name="sourceIndex"></param> /// <param name="destinationIndex">The destination index</param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <returns></returns> CopyToResponse CopyRules(string sourceIndex, string destinationIndex, RequestOptions requestOptions = null); /// <summary> /// Copy the rules of an index to another index /// </summary> /// <param name="sourceIndex"></param> /// <param name="destinationIndex">The destination index</param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <param name="ct">Optional cancellation token</param> /// <returns></returns> Task<CopyToResponse> CopyRulesAsync(string sourceIndex, string destinationIndex, RequestOptions requestOptions = null, CancellationToken ct = default); /// <summary> /// Make a copy of the synonyms of an index /// </summary> /// <param name="sourceIndex"></param> /// <param name="destinationIndex">The destination index</param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <returns></returns> CopyToResponse CopySynonyms(string sourceIndex, string destinationIndex, RequestOptions requestOptions = null); /// <summary> /// Make a copy of the synonyms of an index /// </summary> /// <param name="sourceIndex"></param> /// <param name="destinationIndex">The destination index</param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <param name="ct">Optional cancellation token</param> /// <returns></returns> Task<CopyToResponse> CopySynonymsAsync(string sourceIndex, string destinationIndex, RequestOptions requestOptions = null, CancellationToken ct = default); /// <summary> /// Make a copy of an index, including its objects, settings, synonyms, and query rules. /// </summary> /// <param name="sourceIndex"></param> /// <param name="destinationIndex">The destination index</param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <param name="scope">The scope copy</param> /// <returns></returns> CopyToResponse CopyIndex(string sourceIndex, string destinationIndex, RequestOptions requestOptions = null, IEnumerable<string> scope = null); /// <summary> /// Make a copy of an index, including its objects, settings, synonyms, and query rules. /// </summary> /// <param name="sourceIndex"></param> /// <param name="destinationIndex">The destination index</param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <param name="ct">Optional cancellation token</param> /// <param name="scope">The scope copy</param> /// <returns></returns> Task<CopyToResponse> CopyIndexAsync(string sourceIndex, string destinationIndex, RequestOptions requestOptions = null, CancellationToken ct = default, IEnumerable<string> scope = null); /// <summary> /// Rename an index. Normally used to reindex your data atomically, without any down time. /// </summary> /// <param name="sourceIndex"></param> /// <param name="destinationIndex">The destination index</param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <returns></returns> MoveIndexResponse MoveIndex(string sourceIndex, string destinationIndex, RequestOptions requestOptions = null); /// <summary> /// Rename an index. Normally used to reindex your data atomically, without any down time. /// </summary> /// <param name="sourceIndex"></param> /// <param name="destinationIndex">The destination index</param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> /// <param name="ct">Optional cancellation token</param> /// <returns></returns> Task<MoveIndexResponse> MoveIndexAsync(string sourceIndex, string destinationIndex, RequestOptions requestOptions = null, CancellationToken ct = default); /// <summary> /// Returns the personalization strategy of the application /// </summary> /// <param name="requestOptions"></param> /// <returns></returns> [Obsolete("Endpoint will be deprecated, please use PersonalizationClient instead.")] GetStrategyResponse GetPersonalizationStrategy(RequestOptions requestOptions = null); /// <summary> /// Returns the personalization strategy of the application /// </summary> /// <param name="requestOptions"></param> /// <param name="ct">Optional cancellation token</param> [Obsolete("Endpoint will be deprecated, please use PersonalizationClient instead.")] Task<GetStrategyResponse> GetPersonalizationStrategyAsync(RequestOptions requestOptions = null, CancellationToken ct = default); /// <summary> /// This command configures the personalization strategy /// </summary> /// <param name="request">The personalization strategy</param> /// <param name="requestOptions">Request options for the query</param> /// <returns></returns> [Obsolete("Endpoint will be deprecated, please use PersonalizationClient instead.")] SetStrategyResponse SetPersonalizationStrategy(SetStrategyRequest request, RequestOptions requestOptions = null); /// <summary> /// This command configures the personalization strategy /// </summary> /// <param name="request">The personalization strategy></param> /// <param name="requestOptions">Request options for the query</param> /// <param name="ct">Request options for the query</param> /// <returns></returns> [Obsolete("Endpoint will be deprecated, please use PersonalizationClient instead.")] Task<SetStrategyResponse> SetPersonalizationStrategyAsync(SetStrategyRequest request, RequestOptions requestOptions = null, CancellationToken ct = default); /// <summary> /// This function waits for the Algolia's API task to finish /// </summary> /// <param name="indexName">Your index name</param> /// <param name="taskId">taskID returned by Algolia API</param> /// <param name="timeToWait"></param> /// <param name="requestOptions">Add extra http header or query parameters to Algolia</param> void WaitTask(string indexName, long taskId, int timeToWait = 100, RequestOptions requestOptions = null); /// <summary> /// Execute a custom request /// </summary> /// <param name="data">Body data</param> /// <param name="uri">The URI to request</param> /// <param name="method">The HTTP method</param> /// <param name="callType">CallType.Write or CallType.Read</param> /// <param name="requestOptions">Add extra http header and query parameters to the request</param> /// <typeparam name="TResult">The type of the result</typeparam> /// <typeparam name="TData">The type of the input</typeparam> /// <returns></returns> TResult CustomRequest<TResult, TData>(TData data, string uri, HttpMethod method, CallType callType, RequestOptions requestOptions = null) where TResult : class where TData : class; /// <summary> /// Execute a custom request asynchronously /// </summary> /// <param name="data">Body data</param> /// <param name="uri">The URI to request</param> /// <param name="method">The HTTP method</param> /// <param name="callType">CallType.Write or CallType.Read</param> /// <param name="requestOptions">Add extra http header and query parameters to the request</param> /// <param name="ct">Optional cancellation token</param> /// <typeparam name="TResult">The type of the result</typeparam> /// <typeparam name="TData">The type of the input</typeparam> /// <returns></returns> Task<TResult> CustomRequestAsync<TResult, TData>(TData data, string uri, HttpMethod method, CallType callType, RequestOptions requestOptions = null, CancellationToken ct = default) where TResult : class where TData : class; } }
using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.Security; using System.Xml; using System.IO; using System.Configuration.Provider; using Nucleo.Caching; namespace Nucleo.Security { public class XmlMembershipProvider : FormsMembershipProvider { private readonly string _cacheKey = CacheManagement.GetSafeKey(string.Format("{0}_{1}", "XmlMembershipProvider", "Users")); private XmlDocument _document = null; private string _sourceFile = null; private bool _enableCaching = false; #region " Properties " protected internal override string CustomDescription { get { return "The membership provider that uses XML as its data store."; } } protected XmlDocument Document { get { if (_document == null) { if (CacheManagement.Enabled && CacheManagement.Contains(_cacheKey)) _document = CacheManagement.Get<XmlDocument>(_cacheKey); else _document = new XmlDocument(); string file = this.SourceFile; if (file.StartsWith("~/")) file = file.Replace("~/", AppDomain.CurrentDomain.BaseDirectory + "/"); if (File.Exists(file)) _document.Load(file); else { _document.AppendChild(Document.CreateElement("Users")); _document.Save(file); } if (CacheManagement.Enabled) CacheManagement.Add(_cacheKey, _document); } return _document; } } public bool EnableCaching { get { return _enableCaching; } } public string SourceFile { get { return _sourceFile; } set { _sourceFile = value; } } #endregion #region " Methods " public override bool ChangePassword(string userName, string oldPassword, string newPassword) { XmlElement userElement = this.Document.SelectSingleNode(@"//User[./UserName = '" + userName + "']") as XmlElement; if (userElement == null) throw new ProviderException("The user ID doesn't exist in the current system"); //Password has to match the old password if (userElement["Password"].InnerText == oldPassword) { userElement["Password"].InnerText = newPassword; this.SaveChanges(); return true; } return false; } public override bool ChangePasswordQuestionAndAnswer(string userName, string password, string newPasswordQuestion, string newPasswordAnswer) { XmlElement userElement = this.GetUserByName(userName); if (userElement == null) throw new ProviderException("The user ID doesn't exist in the current system"); if (this.ValidateUser(userName, password)) { userElement["PasswordQuestion"].InnerText = newPasswordQuestion; userElement["PasswordAnswer"].InnerText = newPasswordAnswer; this.SaveChanges(); return true; } else return false; } public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { MembershipUser user = this.GetUser(username, true) as MembershipUser; if (user != null) { status = MembershipCreateStatus.DuplicateUserName; return null; } XmlElement userElement = this.InstantiateUserElement(); userElement["UserName"].InnerText = username; userElement["Password"].InnerText = password; userElement["Email"].InnerText = email; userElement["PasswordQuestion"].InnerText = passwordQuestion; userElement["PasswordAnswer"].InnerText = passwordAnswer; userElement["IsApproved"].InnerText = isApproved.ToString(); userElement["ProviderUserKey"].InnerText = (providerUserKey == null ? string.Empty : providerUserKey.ToString()); userElement["CreationDate"].InnerText = DateTime.Today.ToString(); userElement["LastLoginDate"].InnerText = DateTime.Today.ToString(); userElement["LastActivityDate"].InnerText = DateTime.Today.ToString(); this.Document.DocumentElement.AppendChild(userElement); this.SaveChanges(); //Ensure that the password meets regulations status = this.ProcessPassword(password); //Only return an instantiated user if the password meets the correct requirements if (status != MembershipCreateStatus.Success) return null; else return new MembershipUser(this.Name, username, providerUserKey, email, passwordQuestion, null, isApproved, false, DateTime.Today, DateTime.Today, DateTime.Today, DateTime.MinValue, DateTime.MinValue); } public override bool DeleteUser(string username, bool deleteAllRelatedData) { XmlElement userElement = this.GetUserByName(username); if (userElement == null) throw new ProviderException("The user ID doesn't exist in the current system"); this.Document.RemoveChild(userElement); this.SaveChanges(); return true; } public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords) { return this.InstantiateCollection(this.Document.SelectNodes(string.Format("//User[contains(./Email,'{0}')]", emailToMatch)), pageIndex, pageSize, out totalRecords); } public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) { return this.InstantiateCollection(this.Document.SelectNodes(string.Format("//User[contains(./UserName,'{0}')]", usernameToMatch)), pageIndex, pageSize, out totalRecords); } public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) { return this.InstantiateCollection(this.Document.DocumentElement.ChildNodes, pageIndex, pageSize, out totalRecords); } //TODO:Figure out how to return number of users online public override int GetNumberOfUsersOnline() { return 0; } public override string GetPassword(string username, string answer) { XmlElement userElement = this.GetUserByName(username); if (userElement == null) throw new ProviderException("The user ID doesn't exist in the current system"); if (userElement["PasswordAnswer"].InnerText == answer) return userElement["Password"].InnerText; else throw new ProviderException("The password answers do not match up"); } public override MembershipUser GetUser(string username, bool userIsOnline) { XmlElement userElement = this.GetUserByName(username); if (userElement == null) return null; else { this.UpdateUserActivity(userElement); this.SaveChanges(); return this.InstantiateUser(userElement); } } public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) { XmlElement userElement = this.GetUserByKey(providerUserKey); if (userElement == null) return null; else { this.UpdateUserActivity(userElement); this.SaveChanges(); return this.InstantiateUser(userElement); } } public override string GetUserNameByEmail(string email) { XmlElement userElement = this.Document.SelectSingleNode(@"//User[./Email = '" + email + "']") as XmlElement; if (userElement != null) return userElement["UserName"].InnerText; return null; } private XmlElement GetUserByKey(object providerUserKey) { return this.Document.SelectSingleNode(@"//User[./ProviderUserKey = '" + providerUserKey + "']") as XmlElement; } private XmlElement GetUserByName(string userName) { return this.Document.SelectSingleNode(@"//User[./UserName = '" + userName + "']") as XmlElement; } public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config) { if (string.IsNullOrEmpty(name)) name = "NucleoXmlMembershipProvider"; if (config["description"] != null) config.Remove("description"); config.Add("description", "The XML membership provider that uses an XML file to do its processing"); _sourceFile = config["sourceFile"]; config.Remove("sourceFile"); try { _enableCaching = base.GetBooleanValue(config, "enableCaching", false); config.Remove("enableCaching"); } catch { } base.Initialize(name, config); } private MembershipUserCollection InstantiateCollection(XmlNodeList usersList, int pageIndex, int pageSize, out int totalRecords) { MembershipUserCollection users = new MembershipUserCollection(); totalRecords = usersList.Count; int start, max; this.GetPagingInformation(pageIndex, pageSize, totalRecords, out start, out max); for (int i = start; i <= max; i++) { XmlElement userElement = usersList[i] as XmlElement; users.Add(this.InstantiateUser(userElement)); } return users; } //TODO:Instantiate a user based on an element protected MembershipUser InstantiateUser(XmlElement userElement) { return new MembershipUser(this.Name, userElement["UserName"].InnerText, userElement["ProviderUserKey"].InnerText, userElement["Email"].InnerText, userElement["PaswordQuestion"].InnerText, userElement["PasswordAnswer"].InnerText, bool.Parse(userElement["IsApproved"].InnerText), bool.Parse(userElement["IsLockedOut"].InnerText), this.ProcessDateField(userElement["CreationDate"], DateTime.MinValue), this.ProcessDateField(userElement["LastLoginDate"], DateTime.MinValue), this.ProcessDateField(userElement["LastActivityDate"], DateTime.MinValue), this.ProcessDateField(userElement["LastPasswordChangedDate"], DateTime.MinValue), this.ProcessDateField(userElement["LastLockoutDate"], DateTime.MinValue)); } private DateTime ProcessDateField(XmlElement element, DateTime defaultDate) { if (element == null || string.IsNullOrEmpty(element.InnerText)) return defaultDate; DateTime dateValue; if (!DateTime.TryParse(element.InnerText, out dateValue)) return defaultDate; else return dateValue; } protected XmlElement InstantiateUserElement() { XmlElement userElement = this.Document.CreateElement("User"); userElement.AppendChild(this.Document.CreateElement("UserName")); userElement.AppendChild(this.Document.CreateElement("Password")); userElement.AppendChild(this.Document.CreateElement("PasswordQuestion")); userElement.AppendChild(this.Document.CreateElement("PasswordAnswer")); userElement.AppendChild(this.Document.CreateElement("Email")); userElement.AppendChild(this.Document.CreateElement("ProviderUserKey")); userElement.AppendChild(this.Document.CreateElement("CreationDate")); userElement.AppendChild(this.Document.CreateElement("LastLoginDate")); userElement.AppendChild(this.Document.CreateElement("LastActivityDate")); userElement.AppendChild(this.Document.CreateElement("LastLockoutDate")); userElement.AppendChild(this.Document.CreateElement("LastPasswordChangedDate")); userElement.AppendChild(this.Document.CreateElement("IsApproved")); userElement.AppendChild(this.Document.CreateElement("IsLockedOut")); userElement.AppendChild(this.Document.CreateElement("Comment")); userElement["IsApproved"].InnerText = true.ToString(); userElement["IsLockedOut"].InnerText = false.ToString(); return userElement; } //TODO:finish PerformAuthorizationCheck public virtual void PerformAuthorizationCheck(string action) { } public override string ResetPassword(string username, string answer) { string newPassword = "Pa$$w0rd"; XmlElement userElement = this.GetUserByName(username); if (userElement == null) throw new ProviderException("The user ID doesn't exist in the current system"); if (userElement["PasswordAnswer"].InnerText != answer) throw new ProviderException("The answer doesn't match what exists for the user"); else { userElement["Password"].InnerText = newPassword; this.SaveChanges(); return newPassword; } } private void SaveChanges() { this.Document.Save(this.SourceFile); if (_enableCaching && CacheManagement.Enabled) CacheManagement.Add(_cacheKey, this.Document); } public override bool UnlockUser(string userName) { XmlElement userElement = this.GetUserByName(userName); if (userElement == null) throw new ProviderException("The user ID doesn't exist in the current system"); userElement["IsLockedOut"].InnerText = false.ToString(); this.SaveChanges(); return true; } public override void UpdateUser(MembershipUser user) { XmlElement userElement = this.GetUserByName(user.UserName); if (userElement == null) throw new ProviderException("The user ID doesn't exist in the current system"); userElement["Email"].InnerText = user.Email; userElement["ProviderUserKey"].InnerText = user.ProviderUserKey.ToString(); userElement["LastLoginDate"].InnerText = user.LastLoginDate.ToString(); userElement["LastActivityDate"].InnerText = user.LastActivityDate.ToString(); userElement["IsApproved"].InnerText = user.IsApproved.ToString(); userElement["Comment"].InnerText = user.Comment; this.SaveChanges(); } private void UpdateUserActivity(XmlElement userElement) { if (userElement == null) return; userElement["LastActivityDate"].InnerText = DateTime.Today.ToString(); this.SaveChanges(); } public override bool ValidateUser(string username, string password) { return (this.Document.SelectNodes("//User[./UserName = '" + username + "' && Password='" + password + "']").Count > 0); } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using Microsoft.VisualStudio.TestTools.UnitTesting; using NDProperty.Propertys; using NDProperty.Providers; using NDProperty.Providers.Binding; namespace NDProperty.Test { [TestClass] public class UnitTest1 { [ClassInitialize] public static void Initialize(TestContext context) { // PropertyRegistar<Configuration>.Initilize(Providers.LocalValueManager.Instance, Providers.InheritenceValueManager.Instance, Providers.DefaultValueManager.Instance); } [TestMethod] public void TestSetAndGet() { var t1 = new TestObject(); const string str1 = "Hallo Welt!"; const string str2 = "Hallo Welt!2"; t1.Str = str1; Assert.AreEqual(str1, t1.Str); t1.Str = str2; Assert.AreEqual(str2, t1.Str); } [TestMethod] public void TestSetAndGetMultipleObjects() { var t1 = new TestObject(); var t2 = new TestObject(); const string str1 = "Hallo Welt!"; const string str2 = "Hallo Welt!2"; t1.Str = str1; t2.Str = str2; Assert.AreEqual(str1, t1.Str); Assert.AreEqual(str2, t2.Str); } [TestMethod] public void TestListener() { var t = new TestObject(); const string str1 = "Hallo Welt!"; const string str2 = "Hallo Welt!2"; ChangedEventArgs<Configuration, TestObject, string> eventArg = null; t.StrChanged += (sender, e) => { eventArg = e; }; t.Str = str1; Assert.IsNotNull(eventArg); Assert.AreEqual(str1, eventArg.NewValue); Assert.IsNull(eventArg.OldValue); Assert.AreSame(t, eventArg.ChangedObject); eventArg = null; t.Str = str2; Assert.IsNotNull(eventArg); Assert.AreEqual(str2, eventArg.NewValue); Assert.AreEqual(str1, eventArg.OldValue); Assert.AreSame(t, eventArg.ChangedObject); } [TestMethod] public void TestINotifyPropertyChanged() { var t = new TestObject(); const string str1 = "Hallo Welt!"; const string str2 = "Hallo Welt!2"; PropertyChangedEventArgs eventArg = null; t.PropertyChanged += (sender, e) => { eventArg = e; }; t.NotifyTest = str1; Assert.IsNotNull(eventArg); Assert.AreEqual(nameof(t.NotifyTest), eventArg.PropertyName); eventArg = null; t.NotifyTest = str2; Assert.IsNotNull(eventArg); Assert.AreEqual(nameof(t.NotifyTest), eventArg.PropertyName); } [TestMethod] public void TestSettingsCallOnChangedEquals() { var t = new TestObject(); const string str1 = "Hallo Welt!"; var p1 = PropertyRegistar<Configuration>.Register<TestObject, string>(x => x.TestChangeMethod, str1, NDPropertySettings.None); var p2 = PropertyRegistar<Configuration>.Register<TestObject, string>(x => x.TestChangeMethod, str1, NDPropertySettings.CallOnChangedHandlerOnEquals); PropertyRegistar<Configuration>.SetValue(p1, t, str1); t.testArguments = null; PropertyRegistar<Configuration>.SetValue(p1, t, str1); Assert.IsNull(t.testArguments); PropertyRegistar<Configuration>.SetValue(p2, t, str1); Assert.IsNotNull(t.testArguments); Assert.AreEqual(str1, t.testArguments.Property.NewValue); //Assert.AreEqual(str1, t.testArguments.OldValue); } [TestMethod] public void TestReject() { var t = new TestObject(); const string str1 = "Hallo Welt!"; const string str2 = "Hallo Welt!2"; ChangedEventArgs<Configuration, TestObject, string> eventArg = null; t.Str = str1; try { t.Reject = true; t.StrChanged += (sender, e) => { eventArg = e; }; t.Str = str2; Assert.IsNull(eventArg); Assert.AreEqual(str1, t.Str); } finally { t.Reject = false; } } [TestMethod] public void TestRejectAndMutate() { var t = new TestObject(); const string str1 = "Hallo Welt!"; const string str2 = "Hallo Welt!2"; const string str3 = "Hallo Welt!3"; ChangedEventArgs<Configuration, TestObject, string> eventArg = null; t.Str = str1; t.Reject = true; try { t.Mutate = str3; t.StrChanged += (sender, e) => { eventArg = e; }; t.Str = str2; Assert.IsNull(eventArg); Assert.AreEqual(str1, t.Str); } finally { t.Mutate = null; } } [TestMethod] public void TestMutate() { var t = new TestObject(); const string str1 = "Hallo Welt!"; const string str2 = "Hallo Welt!2"; const string str3 = "Hallo Welt!3"; ChangedEventArgs<Configuration, TestObject, string> eventArg = null; t.Str = str1; t.Mutate = str3; t.StrChanged += (sender, e) => { eventArg = e; }; t.Str = str2; Assert.IsNotNull(eventArg); Assert.AreEqual(str3, eventArg.NewValue); Assert.AreEqual(str1, eventArg.OldValue); Assert.AreSame(t, eventArg.ChangedObject); Assert.AreEqual(str3, t.Str); } [TestMethod] public void TestInheritedGet() { var tp = new TestObject(); var tc = new TestObject(); const string str1 = "Hallo Welt!"; const string str2 = "Hallo Welt!2"; tc.Parent = tp; tp.InheritedStr = str1; Assert.AreEqual(str1, tc.InheritedStr); tp.InheritedStr = str2; Assert.AreEqual(str2, tc.InheritedStr); } [TestMethod] public void TestInheritedListener() { var tp = new TestObject(); var tc = new TestObject(); const string str1 = "Hallo Welt!"; const string str2 = "Hallo Welt!2"; tc.Parent = tp; ChangedEventArgs<Configuration, TestObject, string> eventArg = null; object eventSender = null; tc.InheritedStrChanged += (sender, e) => { eventArg = e; eventSender = sender; }; tp.InheritedStr = str1; Assert.IsNotNull(eventArg); Assert.AreEqual(str1, eventArg.NewValue); Assert.IsNull(eventArg.OldValue); Assert.AreSame(tc, eventArg.ChangedObject); Assert.AreSame(tp, eventSender); eventArg = null; eventSender = null; tp.InheritedStr = str2; Assert.IsNotNull(eventArg); Assert.AreEqual(str2, eventArg.NewValue); Assert.AreEqual(str1, eventArg.OldValue); Assert.AreSame(tp, eventSender); } [TestMethod] public void TestInheritedParentChanged() { var tp1 = new TestObject(); var tp2 = new TestObject(); var tc = new TestObject(); const string str1 = "Hallo Welt!"; const string str2 = "Hallo Welt!2"; tp1.InheritedStr = str1; tp2.InheritedStr = str2; ChangedEventArgs<Configuration, TestObject, string> eventArg = null; object eventSender = null; tc.InheritedStrChanged += (sender, e) => { eventArg = e; eventSender = sender; }; tc.Parent = tp1; Assert.IsNotNull(eventArg); Assert.AreEqual(str1, eventArg.NewValue); Assert.IsNull(eventArg.OldValue); Assert.AreSame(tc, eventArg.ChangedObject); Assert.AreSame(tc, eventSender); // sender is the chile because it changed it parent Assert.AreEqual(str1, tc.InheritedStr); eventArg = null; eventSender = null; tc.Parent = tp2; Assert.IsNotNull(eventArg); Assert.AreEqual(str2, eventArg.NewValue); Assert.AreEqual(str1, eventArg.OldValue); Assert.AreSame(tc, eventSender); // sender is the chile because it changed it parent Assert.AreEqual(str2, tc.InheritedStr); // Check no Listener are fired if both parents had the same value eventArg = null; eventSender = null; tp1.InheritedStr = str2; tc.Parent = tp1; Assert.IsNull(eventArg); Assert.IsNull(eventSender); Assert.AreEqual(str2, tc.InheritedStr); } [TestMethod] public void TestOneWayBinding() { var t1 = new TestObject(); var t2 = new TestObject(); const string str0 = "Hallo Welt!0"; const string str1 = "Hallo Welt!1"; const string str2 = "Hallo Welt!2"; ChangedEventArgs<Configuration, TestObject, string> eventArg = null; t1.StrChanged += (sender, e) => { eventArg = e; }; t2.Str = str0; using (TestObject.StrProperty.Bind(t1, TestObject.StrProperty.Of(t2).OneWay())) { Assert.IsNotNull(eventArg); Assert.AreEqual(str0, t1.Str); Assert.AreEqual(str0, eventArg.NewValue); Assert.AreEqual(null, eventArg.OldValue); eventArg = null; t2.Str = str1; Assert.IsNotNull(eventArg); Assert.AreEqual(str1, t1.Str); Assert.AreEqual(str1, eventArg.NewValue); Assert.AreEqual(str0, eventArg.OldValue); eventArg = null; } // check if new value is notified if binding is cancled. Assert.IsNotNull(eventArg); Assert.AreEqual(null, t1.Str); Assert.AreEqual(null, eventArg.NewValue); Assert.AreEqual(str1, eventArg.OldValue); // check if binding is actual gone. eventArg = null; t2.Str = str2; Assert.IsNull(eventArg); Assert.AreEqual(null, t1.Str); } [TestMethod] public void TestOneWayBindingOver() { var t1 = new TestObject(); var t2 = new TestObject(); var t3 = new TestObject(); var t4 = new TestObject(); const string str1 = "Hallo 1"; const string str2 = "Hallo 3"; const string str3 = "Hallo 4"; const string str4 = "Hallo 5"; t3.Str = str2; t4.Str = str3; t2.Parent = t3; ChangedEventArgs<Configuration, TestObject, string> eventArg1 = null; ChangedEventArgs<Configuration, TestObject, string> eventArg2 = null; ChangedEventArgs<Configuration, TestObject, string> eventArg3 = null; ChangedEventArgs<Configuration, TestObject, string> eventArg4 = null; t1.StrChanged += (sender, e) => { eventArg1 = e; }; t2.StrChanged += (sender, e) => { eventArg2 = e; }; t3.StrChanged += (sender, e) => { eventArg3 = e; }; t4.StrChanged += (sender, e) => { eventArg4 = e; }; using (TestObject.StrProperty.Bind(t1, TestObject.ParentProperty.Of(t2).Over(TestObject.StrProperty).OneWay())) { Assert.IsNotNull(eventArg1); Assert.IsNull(eventArg2); Assert.IsNull(eventArg3); Assert.IsNull(eventArg4); Assert.AreEqual(str2, t1.Str); Assert.AreEqual(null, t2.Str); Assert.AreEqual(str2, t3.Str); Assert.AreEqual(str3, t4.Str); Assert.AreEqual(str2, eventArg1.NewValue); Assert.AreEqual(null, eventArg1.OldValue); eventArg1 = null; eventArg2 = null; eventArg3 = null; eventArg4 = null; t3.Str = str1; Assert.IsNotNull(eventArg1); Assert.IsNull(eventArg2); Assert.IsNotNull(eventArg3); Assert.IsNull(eventArg4); Assert.AreEqual(str1, t1.Str); Assert.AreEqual(null, t2.Str); Assert.AreEqual(str1, t3.Str); Assert.AreEqual(str3, t4.Str); Assert.AreEqual(str1, eventArg1.NewValue); Assert.AreEqual(str1, eventArg3.NewValue); Assert.AreEqual(str2, eventArg1.OldValue); Assert.AreEqual(str2, eventArg3.OldValue); eventArg1 = null; eventArg2 = null; eventArg3 = null; eventArg4 = null; t2.Parent = t4; Assert.IsNotNull(eventArg1); Assert.IsNull(eventArg2); Assert.IsNull(eventArg3); Assert.IsNull(eventArg4); Assert.AreEqual(str3, t1.Str); Assert.AreEqual(null, t2.Str); Assert.AreEqual(str1, t3.Str); Assert.AreEqual(str3, t4.Str); Assert.AreEqual(str3, eventArg1.NewValue); Assert.AreEqual(str1, eventArg1.OldValue); eventArg1 = null; eventArg2 = null; eventArg3 = null; eventArg4 = null; } // check if new value is notified if binding is cancled. Assert.IsNotNull(eventArg1); Assert.IsNull(eventArg2); Assert.IsNull(eventArg3); Assert.IsNull(eventArg4); Assert.AreEqual(null, t1.Str); Assert.AreEqual(null, t2.Str); Assert.AreEqual(str1, t3.Str); Assert.AreEqual(str3, t4.Str); Assert.AreEqual(null, eventArg1.NewValue); Assert.AreEqual(str3, eventArg1.OldValue); eventArg1 = null; eventArg2 = null; eventArg3 = null; eventArg4 = null; // check if binding is actual gone. t4.Str = str4; Assert.IsNull(eventArg1); Assert.AreEqual(null, t1.Str); Assert.AreEqual(null, t2.Str); Assert.AreEqual(str1, t3.Str); Assert.AreEqual(str4, t4.Str); } [TestMethod] public void TestTwoWayBinding() { var t1 = new TestObject(); var t2 = new TestObject(); const string str1 = "Hallo Welt!"; const string str2 = "Hallo Welt!2"; const string str3 = "Hallo Welt!3"; ChangedEventArgs<Configuration, TestObject, string> eventArg1 = null; ChangedEventArgs<Configuration, TestObject, string> eventArg2 = null; t1.StrChanged += (sender, e) => { eventArg1 = e; }; t2.StrChanged += (sender, e) => { eventArg2 = e; }; using (TestObject.StrProperty.Bind(t1, TestObject.StrProperty.Of(t2).TwoWay())) { t1.Str = str1; Assert.IsNotNull(eventArg1); Assert.IsNotNull(eventArg2); Assert.AreEqual(str1, t2.Str); Assert.AreEqual(str1, t1.Str); Assert.AreEqual(str1, eventArg1.NewValue); Assert.AreEqual(str1, eventArg2.NewValue); Assert.AreEqual(null, eventArg1.OldValue); Assert.AreEqual(null, eventArg2.OldValue); eventArg1 = null; eventArg2 = null; t2.Str = str2; Assert.IsNotNull(eventArg1); Assert.IsNotNull(eventArg2); Assert.AreEqual(str2, t2.Str); Assert.AreEqual(str2, t1.Str); Assert.AreEqual(str2, eventArg1.NewValue); Assert.AreEqual(str1, eventArg1.OldValue); Assert.AreEqual(str2, eventArg2.NewValue); Assert.AreEqual(str1, eventArg2.OldValue); eventArg1 = null; eventArg2 = null; } // check if new value is notified if binding is cancled. Assert.IsNotNull(eventArg1); Assert.IsNull(eventArg2); Assert.AreEqual(str1, t1.Str); Assert.AreEqual(str2, t2.Str); Assert.AreEqual(str1, eventArg1.NewValue); Assert.AreEqual(str2, eventArg1.OldValue); // check if binding is actual gone. eventArg1 = null; eventArg2 = null; t2.Str = str3; Assert.IsNull(eventArg1); Assert.IsNotNull(eventArg2); Assert.AreEqual(str1, t1.Str); Assert.AreEqual(str3, t2.Str); Assert.AreEqual(str3, eventArg2.NewValue); Assert.AreEqual(str2, eventArg2.OldValue); } } public class Configuration : NDProperty.IInitializer<Configuration> { public IEnumerable<Providers.ValueProvider<Configuration>> ValueProviders => new Providers.ValueProvider<Configuration>[] { BindingProvider<Configuration>.Instance, LocalValueProvider<Configuration>.Instance, InheritanceValueProvider<Configuration>.Instance, DefaultValueProvider<Configuration>.Instance, }; } public struct MyStruct { public static explicit operator MyStruct(int i) { return new MyStruct(); } } public partial class TestObject : System.ComponentModel.INotifyPropertyChanged { public bool Reject { get; set; } public string Mutate { get; set; } [NDP(Settings = NDPropertySettings.CallOnChangedHandlerOnEquals | NDPropertySettings.ReadOnly)] //[System.ComponentModel.DefaultValue("asdf")] private void OnTestAttributeChanging(OnChangingArg<Configuration, MyStruct> arg) { var test = TestAttributeProperty.ToString(); } [NDP(Settings = NDPropertySettings.ReadOnly)] [System.ComponentModel.DefaultValue("")] private void OnMyBlaChanging(OnChangingArg<Configuration, string> arg) { var test = TestAttributeProperty.ToString(); } [NDP] private void OnNotifyTestChanging(OnChangingArg<Configuration, string> arg) { } #region Attach public static readonly global::NDProperty.Propertys.NDAttachedPropertyKey<Configuration, string, object> AttachProperty = global::NDProperty.PropertyRegistar<Configuration>.RegisterAttached<string, object>(OnAttachChanged, default(string), global::NDProperty.Propertys.NDPropertySettings.None); public static global::NDProperty.Utils.AttachedHelper<Configuration, string, object> Attach { get; } = global::NDProperty.Utils.AttachedHelper.Create(AttachProperty); private static void OnAttachChanged(OnChangingArg<Configuration, string, object> arg) { } #endregion #region Str public static readonly NDPropertyKey<Configuration, TestObject, string> StrProperty = PropertyRegistar<Configuration>.Register<TestObject, string>(t => t.OnStrChanged, default(string), NDPropertySettings.None); public string Str { get { return PropertyRegistar<Configuration>.GetValue(StrProperty, this); } set { PropertyRegistar<Configuration>.SetValue(StrProperty, this, value); } } public event EventHandler<ChangedEventArgs<Configuration, TestObject, string>> StrChanged { add { PropertyRegistar<Configuration>.AddEventHandler(StrProperty, this, value); } remove { PropertyRegistar<Configuration>.RemoveEventHandler(StrProperty, this, value); } } private void OnStrChanged(OnChangingArg<Configuration, string> arg) { if (Reject) arg.Provider.Reject = Reject; if (Mutate != null) arg.Provider.MutatedValue = Mutate; } #endregion #region InheritedStr public static readonly NDPropertyKey<Configuration, TestObject, string> InheritedStrProperty = PropertyRegistar<Configuration>.Register<TestObject, string>(t => t.OnInheritedStrChanged, default(string), NDPropertySettings.Inherited); public string InheritedStr { get => PropertyRegistar<Configuration>.GetValue(InheritedStrProperty, this); set => PropertyRegistar<Configuration>.SetValue(InheritedStrProperty, this, value); } public event EventHandler<ChangedEventArgs<Configuration, TestObject, string>> InheritedStrChanged { add => PropertyRegistar<Configuration>.AddEventHandler(InheritedStrProperty, this, value); remove => PropertyRegistar<Configuration>.RemoveEventHandler(InheritedStrProperty, this, value); } private void OnInheritedStrChanged(OnChangingArg<Configuration, string> arg) { } #endregion #region Parent public static readonly NDPropertyKey<Configuration, TestObject, TestObject> ParentProperty = PropertyRegistar<Configuration>.Register<TestObject, TestObject>(t => t.OnParentChanged, default(TestObject), NDPropertySettings.ParentReference); public TestObject Parent { get => PropertyRegistar<Configuration>.GetValue(ParentProperty, this); set => PropertyRegistar<Configuration>.SetValue(ParentProperty, this, value); } public event EventHandler<ChangedEventArgs<Configuration, TestObject, TestObject>> ParentChanged { add => PropertyRegistar<Configuration>.AddEventHandler(ParentProperty, this, value); remove => PropertyRegistar<Configuration>.RemoveEventHandler(ParentProperty, this, value); } private void OnParentChanged(OnChangingArg<Configuration, TestObject> arg) { } #endregion // BUg in Source code generator adds the triva at the end of the glass to the generated class. This leads to generating #endregion in the generated class. which produces an error. public override string ToString() { return base.ToString(); } public OnChangingArg<Configuration, string> testArguments; public event PropertyChangedEventHandler PropertyChanged; internal void TestChangeMethod(OnChangingArg<Configuration, string> arg) { testArguments = arg; } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/spanner/v1/type.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Cloud.Spanner.V1 { /// <summary>Holder for reflection information generated from google/spanner/v1/type.proto</summary> public static partial class TypeReflection { #region Descriptor /// <summary>File descriptor for google/spanner/v1/type.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static TypeReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Chxnb29nbGUvc3Bhbm5lci92MS90eXBlLnByb3RvEhFnb29nbGUuc3Bhbm5l", "ci52MRocZ29vZ2xlL2FwaS9hbm5vdGF0aW9ucy5wcm90byKaAQoEVHlwZRIp", "CgRjb2RlGAEgASgOMhsuZ29vZ2xlLnNwYW5uZXIudjEuVHlwZUNvZGUSMwoS", "YXJyYXlfZWxlbWVudF90eXBlGAIgASgLMhcuZ29vZ2xlLnNwYW5uZXIudjEu", "VHlwZRIyCgtzdHJ1Y3RfdHlwZRgDIAEoCzIdLmdvb2dsZS5zcGFubmVyLnYx", "LlN0cnVjdFR5cGUifwoKU3RydWN0VHlwZRIzCgZmaWVsZHMYASADKAsyIy5n", "b29nbGUuc3Bhbm5lci52MS5TdHJ1Y3RUeXBlLkZpZWxkGjwKBUZpZWxkEgwK", "BG5hbWUYASABKAkSJQoEdHlwZRgCIAEoCzIXLmdvb2dsZS5zcGFubmVyLnYx", "LlR5cGUqjgEKCFR5cGVDb2RlEhkKFVRZUEVfQ09ERV9VTlNQRUNJRklFRBAA", "EggKBEJPT0wQARIJCgVJTlQ2NBACEgsKB0ZMT0FUNjQQAxINCglUSU1FU1RB", "TVAQBBIICgREQVRFEAUSCgoGU1RSSU5HEAYSCQoFQllURVMQBxIJCgVBUlJB", "WRAIEgoKBlNUUlVDVBAJQpIBChVjb20uZ29vZ2xlLnNwYW5uZXIudjFCCVR5", "cGVQcm90b1ABWjhnb29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVh", "cGlzL3NwYW5uZXIvdjE7c3Bhbm5lcqoCF0dvb2dsZS5DbG91ZC5TcGFubmVy", "LlYxygIXR29vZ2xlXENsb3VkXFNwYW5uZXJcVjFiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Google.Cloud.Spanner.V1.TypeCode), }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Spanner.V1.Type), global::Google.Cloud.Spanner.V1.Type.Parser, new[]{ "Code", "ArrayElementType", "StructType" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Spanner.V1.StructType), global::Google.Cloud.Spanner.V1.StructType.Parser, new[]{ "Fields" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Spanner.V1.StructType.Types.Field), global::Google.Cloud.Spanner.V1.StructType.Types.Field.Parser, new[]{ "Name", "Type" }, null, null, null)}) })); } #endregion } #region Enums /// <summary> /// `TypeCode` is used as part of [Type][google.spanner.v1.Type] to /// indicate the type of a Cloud Spanner value. /// /// Each legal value of a type can be encoded to or decoded from a JSON /// value, using the encodings described below. All Cloud Spanner values can /// be `null`, regardless of type; `null`s are always encoded as a JSON /// `null`. /// </summary> public enum TypeCode { /// <summary> /// Not specified. /// </summary> [pbr::OriginalName("TYPE_CODE_UNSPECIFIED")] Unspecified = 0, /// <summary> /// Encoded as JSON `true` or `false`. /// </summary> [pbr::OriginalName("BOOL")] Bool = 1, /// <summary> /// Encoded as `string`, in decimal format. /// </summary> [pbr::OriginalName("INT64")] Int64 = 2, /// <summary> /// Encoded as `number`, or the strings `"NaN"`, `"Infinity"`, or /// `"-Infinity"`. /// </summary> [pbr::OriginalName("FLOAT64")] Float64 = 3, /// <summary> /// Encoded as `string` in RFC 3339 timestamp format. The time zone /// must be present, and must be `"Z"`. /// </summary> [pbr::OriginalName("TIMESTAMP")] Timestamp = 4, /// <summary> /// Encoded as `string` in RFC 3339 date format. /// </summary> [pbr::OriginalName("DATE")] Date = 5, /// <summary> /// Encoded as `string`. /// </summary> [pbr::OriginalName("STRING")] String = 6, /// <summary> /// Encoded as a base64-encoded `string`, as described in RFC 4648, /// section 4. /// </summary> [pbr::OriginalName("BYTES")] Bytes = 7, /// <summary> /// Encoded as `list`, where the list elements are represented /// according to [array_element_type][google.spanner.v1.Type.array_element_type]. /// </summary> [pbr::OriginalName("ARRAY")] Array = 8, /// <summary> /// Encoded as `list`, where list element `i` is represented according /// to [struct_type.fields[i]][google.spanner.v1.StructType.fields]. /// </summary> [pbr::OriginalName("STRUCT")] Struct = 9, } #endregion #region Messages /// <summary> /// `Type` indicates the type of a Cloud Spanner value, as might be stored in a /// table cell or returned from an SQL query. /// </summary> public sealed partial class Type : pb::IMessage<Type> { private static readonly pb::MessageParser<Type> _parser = new pb::MessageParser<Type>(() => new Type()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Type> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Spanner.V1.TypeReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Type() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Type(Type other) : this() { code_ = other.code_; ArrayElementType = other.arrayElementType_ != null ? other.ArrayElementType.Clone() : null; StructType = other.structType_ != null ? other.StructType.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Type Clone() { return new Type(this); } /// <summary>Field number for the "code" field.</summary> public const int CodeFieldNumber = 1; private global::Google.Cloud.Spanner.V1.TypeCode code_ = 0; /// <summary> /// Required. The [TypeCode][google.spanner.v1.TypeCode] for this type. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Spanner.V1.TypeCode Code { get { return code_; } set { code_ = value; } } /// <summary>Field number for the "array_element_type" field.</summary> public const int ArrayElementTypeFieldNumber = 2; private global::Google.Cloud.Spanner.V1.Type arrayElementType_; /// <summary> /// If [code][google.spanner.v1.Type.code] == [ARRAY][google.spanner.v1.TypeCode.ARRAY], then `array_element_type` /// is the type of the array elements. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Spanner.V1.Type ArrayElementType { get { return arrayElementType_; } set { arrayElementType_ = value; } } /// <summary>Field number for the "struct_type" field.</summary> public const int StructTypeFieldNumber = 3; private global::Google.Cloud.Spanner.V1.StructType structType_; /// <summary> /// If [code][google.spanner.v1.Type.code] == [STRUCT][google.spanner.v1.TypeCode.STRUCT], then `struct_type` /// provides type information for the struct's fields. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Spanner.V1.StructType StructType { get { return structType_; } set { structType_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Type); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Type other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Code != other.Code) return false; if (!object.Equals(ArrayElementType, other.ArrayElementType)) return false; if (!object.Equals(StructType, other.StructType)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Code != 0) hash ^= Code.GetHashCode(); if (arrayElementType_ != null) hash ^= ArrayElementType.GetHashCode(); if (structType_ != null) hash ^= StructType.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Code != 0) { output.WriteRawTag(8); output.WriteEnum((int) Code); } if (arrayElementType_ != null) { output.WriteRawTag(18); output.WriteMessage(ArrayElementType); } if (structType_ != null) { output.WriteRawTag(26); output.WriteMessage(StructType); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Code != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Code); } if (arrayElementType_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(ArrayElementType); } if (structType_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(StructType); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Type other) { if (other == null) { return; } if (other.Code != 0) { Code = other.Code; } if (other.arrayElementType_ != null) { if (arrayElementType_ == null) { arrayElementType_ = new global::Google.Cloud.Spanner.V1.Type(); } ArrayElementType.MergeFrom(other.ArrayElementType); } if (other.structType_ != null) { if (structType_ == null) { structType_ = new global::Google.Cloud.Spanner.V1.StructType(); } StructType.MergeFrom(other.StructType); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { code_ = (global::Google.Cloud.Spanner.V1.TypeCode) input.ReadEnum(); break; } case 18: { if (arrayElementType_ == null) { arrayElementType_ = new global::Google.Cloud.Spanner.V1.Type(); } input.ReadMessage(arrayElementType_); break; } case 26: { if (structType_ == null) { structType_ = new global::Google.Cloud.Spanner.V1.StructType(); } input.ReadMessage(structType_); break; } } } } } /// <summary> /// `StructType` defines the fields of a [STRUCT][google.spanner.v1.TypeCode.STRUCT] type. /// </summary> public sealed partial class StructType : pb::IMessage<StructType> { private static readonly pb::MessageParser<StructType> _parser = new pb::MessageParser<StructType>(() => new StructType()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<StructType> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Spanner.V1.TypeReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public StructType() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public StructType(StructType other) : this() { fields_ = other.fields_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public StructType Clone() { return new StructType(this); } /// <summary>Field number for the "fields" field.</summary> public const int FieldsFieldNumber = 1; private static readonly pb::FieldCodec<global::Google.Cloud.Spanner.V1.StructType.Types.Field> _repeated_fields_codec = pb::FieldCodec.ForMessage(10, global::Google.Cloud.Spanner.V1.StructType.Types.Field.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.Spanner.V1.StructType.Types.Field> fields_ = new pbc::RepeatedField<global::Google.Cloud.Spanner.V1.StructType.Types.Field>(); /// <summary> /// The list of fields that make up this struct. Order is /// significant, because values of this struct type are represented as /// lists, where the order of field values matches the order of /// fields in the [StructType][google.spanner.v1.StructType]. In turn, the order of fields /// matches the order of columns in a read request, or the order of /// fields in the `SELECT` clause of a query. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Cloud.Spanner.V1.StructType.Types.Field> Fields { get { return fields_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as StructType); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(StructType other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!fields_.Equals(other.fields_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= fields_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { fields_.WriteTo(output, _repeated_fields_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += fields_.CalculateSize(_repeated_fields_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(StructType other) { if (other == null) { return; } fields_.Add(other.fields_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { fields_.AddEntriesFrom(input, _repeated_fields_codec); break; } } } } #region Nested types /// <summary>Container for nested types declared in the StructType message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { /// <summary> /// Message representing a single field of a struct. /// </summary> public sealed partial class Field : pb::IMessage<Field> { private static readonly pb::MessageParser<Field> _parser = new pb::MessageParser<Field>(() => new Field()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Field> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Spanner.V1.StructType.Descriptor.NestedTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Field() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Field(Field other) : this() { name_ = other.name_; Type = other.type_ != null ? other.Type.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Field Clone() { return new Field(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// The name of the field. For reads, this is the column name. For /// SQL queries, it is the column alias (e.g., `"Word"` in the /// query `"SELECT 'hello' AS Word"`), or the column name (e.g., /// `"ColName"` in the query `"SELECT ColName FROM Table"`). Some /// columns might have an empty name (e.g., !"SELECT /// UPPER(ColName)"`). Note that a query result can contain /// multiple fields with the same name. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "type" field.</summary> public const int TypeFieldNumber = 2; private global::Google.Cloud.Spanner.V1.Type type_; /// <summary> /// The type of the field. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Spanner.V1.Type Type { get { return type_; } set { type_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Field); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Field other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (!object.Equals(Type, other.Type)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (type_ != null) hash ^= Type.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (type_ != null) { output.WriteRawTag(18); output.WriteMessage(Type); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (type_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Type); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Field other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.type_ != null) { if (type_ == null) { type_ = new global::Google.Cloud.Spanner.V1.Type(); } Type.MergeFrom(other.Type); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { if (type_ == null) { type_ = new global::Google.Cloud.Spanner.V1.Type(); } input.ReadMessage(type_); break; } } } } } } #endregion } #endregion } #endregion Designer generated code
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Security; using ZErrorCode = System.IO.Compression.ZLibNative.ErrorCode; using ZFlushCode = System.IO.Compression.ZLibNative.FlushCode; namespace System.IO.Compression { /// <summary> /// Provides a wrapper around the ZLib compression API /// </summary> internal sealed class Deflater : IDisposable { private ZLibNative.ZLibStreamHandle _zlibStream; private GCHandle _inputBufferHandle; private bool _isDisposed; private const int minWindowBits = -15; // WindowBits must be between -8..-15 to write no header, 8..15 for a private const int maxWindowBits = 31; // zlib header, or 24..31 for a GZip header // Note, DeflateStream or the deflater do not try to be thread safe. // The lock is just used to make writing to unmanaged structures atomic to make sure // that they do not get inconsistent fields that may lead to an unmanaged memory violation. // To prevent *managed* buffer corruption or other weird behaviour users need to synchronise // on the stream explicitly. private readonly object _syncLock = new object(); #region exposed members internal Deflater(CompressionLevel compressionLevel, int windowBits) { Debug.Assert(windowBits >= minWindowBits && windowBits <= maxWindowBits); ZLibNative.CompressionLevel zlibCompressionLevel; int memLevel; switch (compressionLevel) { // See the note in ZLibNative.CompressionLevel for the recommended combinations. case CompressionLevel.Optimal: zlibCompressionLevel = ZLibNative.CompressionLevel.BestCompression; memLevel = ZLibNative.Deflate_DefaultMemLevel; break; case CompressionLevel.Fastest: zlibCompressionLevel = ZLibNative.CompressionLevel.BestSpeed; memLevel = ZLibNative.Deflate_DefaultMemLevel; break; case CompressionLevel.NoCompression: zlibCompressionLevel = ZLibNative.CompressionLevel.NoCompression; memLevel = ZLibNative.Deflate_NoCompressionMemLevel; break; default: throw new ArgumentOutOfRangeException("compressionLevel"); } ZLibNative.CompressionStrategy strategy = ZLibNative.CompressionStrategy.DefaultStrategy; DeflateInit(zlibCompressionLevel, windowBits, memLevel, strategy); } ~Deflater() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } [SecuritySafeCritical] private void Dispose(bool disposing) { if (!_isDisposed) { if (disposing) _zlibStream.Dispose(); if (_inputBufferHandle.IsAllocated) DeallocateInputBufferHandle(); _isDisposed = true; } } public bool NeedsInput() { return 0 == _zlibStream.AvailIn; } internal void SetInput(byte[] inputBuffer, int startIndex, int count) { Debug.Assert(NeedsInput(), "We have something left in previous input!"); Debug.Assert(null != inputBuffer); Debug.Assert(startIndex >= 0 && count >= 0 && count + startIndex <= inputBuffer.Length); Debug.Assert(!_inputBufferHandle.IsAllocated); if (0 == count) return; lock (_syncLock) { _inputBufferHandle = GCHandle.Alloc(inputBuffer, GCHandleType.Pinned); _zlibStream.NextIn = _inputBufferHandle.AddrOfPinnedObject() + startIndex; _zlibStream.AvailIn = (uint)count; } } internal int GetDeflateOutput(byte[] outputBuffer) { Contract.Ensures(Contract.Result<int>() >= 0 && Contract.Result<int>() <= outputBuffer.Length); Debug.Assert(null != outputBuffer, "Can't pass in a null output buffer!"); Debug.Assert(!NeedsInput(), "GetDeflateOutput should only be called after providing input"); Debug.Assert(_inputBufferHandle.IsAllocated); try { int bytesRead; ReadDeflateOutput(outputBuffer, ZFlushCode.NoFlush, out bytesRead); return bytesRead; } finally { // Before returning, make sure to release input buffer if necesary: if (0 == _zlibStream.AvailIn && _inputBufferHandle.IsAllocated) DeallocateInputBufferHandle(); } } private unsafe ZErrorCode ReadDeflateOutput(byte[] outputBuffer, ZFlushCode flushCode, out int bytesRead) { lock (_syncLock) { fixed (byte* bufPtr = outputBuffer) { _zlibStream.NextOut = (IntPtr)bufPtr; _zlibStream.AvailOut = (uint)outputBuffer.Length; ZErrorCode errC = Deflate(flushCode); bytesRead = outputBuffer.Length - (int)_zlibStream.AvailOut; return errC; } } } internal bool Finish(byte[] outputBuffer, out int bytesRead) { Debug.Assert(null != outputBuffer, "Can't pass in a null output buffer!"); Debug.Assert(outputBuffer.Length > 0, "Can't pass in an empty output buffer!"); Debug.Assert(NeedsInput(), "We have something left in previous input!"); Debug.Assert(!_inputBufferHandle.IsAllocated); // Note: we require that NeedsInput() == true, i.e. that 0 == _zlibStream.AvailIn. // If there is still input left we should never be getting here; instead we // should be calling GetDeflateOutput. ZErrorCode errC = ReadDeflateOutput(outputBuffer, ZFlushCode.Finish, out bytesRead); return errC == ZErrorCode.StreamEnd; } /// <summary> /// Returns true if there was something to flush. Otherwise False. /// </summary> internal bool Flush(byte[] outputBuffer, out int bytesRead) { Debug.Assert(null != outputBuffer, "Can't pass in a null output buffer!"); Debug.Assert(outputBuffer.Length > 0, "Can't pass in an empty output buffer!"); Debug.Assert(NeedsInput(), "We have something left in previous input!"); Debug.Assert(!_inputBufferHandle.IsAllocated); // Note: we require that NeedsInput() == true, i.e. that 0 == _zlibStream.AvailIn. // If there is still input left we should never be getting here; instead we // should be calling GetDeflateOutput. return ReadDeflateOutput(outputBuffer, ZFlushCode.SyncFlush, out bytesRead) == ZErrorCode.Ok; } #endregion #region helpers & native call wrappers private void DeallocateInputBufferHandle() { Debug.Assert(_inputBufferHandle.IsAllocated); lock (_syncLock) { _zlibStream.AvailIn = 0; _zlibStream.NextIn = ZLibNative.ZNullPtr; _inputBufferHandle.Free(); } } [SecuritySafeCritical] private void DeflateInit(ZLibNative.CompressionLevel compressionLevel, int windowBits, int memLevel, ZLibNative.CompressionStrategy strategy) { ZErrorCode errC; try { errC = ZLibNative.CreateZLibStreamForDeflate(out _zlibStream, compressionLevel, windowBits, memLevel, strategy); } catch (Exception cause) { throw new ZLibException(SR.ZLibErrorDLLLoadError, cause); } switch (errC) { case ZErrorCode.Ok: return; case ZErrorCode.MemError: throw new ZLibException(SR.ZLibErrorNotEnoughMemory, "deflateInit2_", (int)errC, _zlibStream.GetErrorMessage()); case ZErrorCode.VersionError: throw new ZLibException(SR.ZLibErrorVersionMismatch, "deflateInit2_", (int)errC, _zlibStream.GetErrorMessage()); case ZErrorCode.StreamError: throw new ZLibException(SR.ZLibErrorIncorrectInitParameters, "deflateInit2_", (int)errC, _zlibStream.GetErrorMessage()); default: throw new ZLibException(SR.ZLibErrorUnexpected, "deflateInit2_", (int)errC, _zlibStream.GetErrorMessage()); } } [SecuritySafeCritical] private ZErrorCode Deflate(ZFlushCode flushCode) { ZErrorCode errC; try { errC = _zlibStream.Deflate(flushCode); } catch (Exception cause) { throw new ZLibException(SR.ZLibErrorDLLLoadError, cause); } switch (errC) { case ZErrorCode.Ok: case ZErrorCode.StreamEnd: return errC; case ZErrorCode.BufError: return errC; // This is a recoverable error case ZErrorCode.StreamError: throw new ZLibException(SR.ZLibErrorInconsistentStream, "deflate", (int)errC, _zlibStream.GetErrorMessage()); default: throw new ZLibException(SR.ZLibErrorUnexpected, "deflate", (int)errC, _zlibStream.GetErrorMessage()); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void TestMixOnesZerosUInt32() { var test = new BooleanTwoComparisonOpTest__TestMixOnesZerosUInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.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 (Sse2.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(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.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 works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } 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 BooleanTwoComparisonOpTest__TestMixOnesZerosUInt32 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(UInt32); private const int Op2ElementCount = VectorSize / sizeof(UInt32); private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt32[] _data2 = new UInt32[Op2ElementCount]; private static Vector128<UInt32> _clsVar1; private static Vector128<UInt32> _clsVar2; private Vector128<UInt32> _fld1; private Vector128<UInt32> _fld2; private BooleanTwoComparisonOpTest__DataTable<UInt32, UInt32> _dataTable; static BooleanTwoComparisonOpTest__TestMixOnesZerosUInt32() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (uint)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize); } public BooleanTwoComparisonOpTest__TestMixOnesZerosUInt32() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (uint)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (uint)(random.Next(0, int.MaxValue)); } _dataTable = new BooleanTwoComparisonOpTest__DataTable<UInt32, UInt32>(_data1, _data2, VectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse41.TestMixOnesZeros( Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_Load() { var result = Sse41.TestMixOnesZeros( Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_LoadAligned() { var result = Sse41.TestMixOnesZeros( Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { var method = typeof(Sse41).GetMethod(nameof(Sse41.TestMixOnesZeros), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) }); if (method != null) { var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunReflectionScenario_Load() { var method = typeof(Sse41).GetMethod(nameof(Sse41.TestMixOnesZeros), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) }); if (method != null) { var result = method.Invoke(null, new object[] { Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunReflectionScenario_LoadAligned() {var method = typeof(Sse41).GetMethod(nameof(Sse41.TestMixOnesZeros), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) }); if (method != null) { var result = method.Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunClsVarScenario() { var result = Sse41.TestMixOnesZeros( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr); var result = Sse41.TestMixOnesZeros(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)); var result = Sse41.TestMixOnesZeros(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr)); var result = Sse41.TestMixOnesZeros(left, right); ValidateResult(left, right, result); } public void RunLclFldScenario() { var test = new BooleanTwoComparisonOpTest__TestMixOnesZerosUInt32(); var result = Sse41.TestMixOnesZeros(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunFldScenario() { var result = Sse41.TestMixOnesZeros(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<UInt32> left, Vector128<UInt32> right, bool result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(UInt32[] left, UInt32[] right, bool result, [CallerMemberName] string method = "") { var expectedResult1 = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult1 &= (((left[i] & right[i]) == 0)); } var expectedResult2 = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult2 &= (((~left[i] & right[i]) == 0)); } if (((expectedResult1 == false) && (expectedResult2 == false)) != result) { Succeeded = false; Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.TestMixOnesZeros)}<UInt32>(Vector128<UInt32>, Vector128<UInt32>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
//----------------------------------------------------------------------- // <copyright file="GraphStages.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Akka.Actor; using Akka.Streams.Dsl; using Akka.Streams.Implementation.Stages; using Akka.Streams.Stage; using Akka.Util; namespace Akka.Streams.Implementation.Fusing { /// <summary> /// TBD /// </summary> public static class GraphStages { /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> /// <returns>TBD</returns> public static SimpleLinearGraphStage<T> Identity<T>() => Implementation.Fusing.Identity<T>.Instance; /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> /// <returns>TBD</returns> internal static GraphStageWithMaterializedValue<FlowShape<T, T>, Task> TerminationWatcher<T>() => Implementation.Fusing.TerminationWatcher<T>.Instance; /// <summary> /// Fusing graphs that have cycles involving FanIn stages might lead to deadlocks if /// demand is not carefully managed. /// /// This means that FanIn stages need to early pull every relevant input on startup. /// This can either be implemented inside the stage itself, or this method can be used, /// which adds a detacher stage to every input. /// </summary> /// <typeparam name="T">TBD</typeparam> /// <param name="stage">TBD</param> /// <returns>TBD</returns> internal static IGraph<UniformFanInShape<T, T>, NotUsed> WithDetachedInputs<T>(GraphStage<UniformFanInShape<T, T>> stage) { return GraphDsl.Create(builder => { var concat = builder.Add(stage); var detachers = concat.Ins.Select(inlet => { var detacher = builder.Add(new Detacher<T>()); builder.From(detacher).To(inlet); return detacher.Inlet; }).ToArray(); return new UniformFanInShape<T, T>(concat.Out, detachers); }); } } /// <summary> /// INTERNAL API /// </summary> public class GraphStageModule : AtomicModule { /// <summary> /// TBD /// </summary> public readonly IGraphStageWithMaterializedValue<Shape, object> Stage; /// <summary> /// TBD /// </summary> /// <param name="shape">TBD</param> /// <param name="attributes">TBD</param> /// <param name="stage">TBD</param> public GraphStageModule(Shape shape, Attributes attributes, IGraphStageWithMaterializedValue<Shape, object> stage) { Shape = shape; Attributes = attributes; Stage = stage; } /// <summary> /// TBD /// </summary> public override Shape Shape { get; } /// <summary> /// TBD /// </summary> /// <param name="shape">TBD</param> /// <returns>TBD</returns> public override IModule ReplaceShape(Shape shape) => new CopiedModule(shape, Attributes.None, this); /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override IModule CarbonCopy() => ReplaceShape(Shape.DeepCopy()); /// <summary> /// TBD /// </summary> public override Attributes Attributes { get; } /// <summary> /// TBD /// </summary> /// <param name="attributes">TBD</param> /// <returns>TBD</returns> public override IModule WithAttributes(Attributes attributes) => new GraphStageModule(Shape, attributes, Stage); /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override string ToString() => $"GraphStage({Stage}) [{GetHashCode()}%08x]"; } /// <summary> /// INTERNAL API /// </summary> /// <typeparam name="T">TBD</typeparam> public abstract class SimpleLinearGraphStage<T> : GraphStage<FlowShape<T, T>> { /// <summary> /// TBD /// </summary> public readonly Inlet<T> Inlet; /// <summary> /// TBD /// </summary> public readonly Outlet<T> Outlet; /// <summary> /// TBD /// </summary> protected SimpleLinearGraphStage(string name = null) { name = name ?? GetType().Name; Inlet = new Inlet<T>(name + ".in"); Outlet = new Outlet<T>(name + ".out"); Shape = new FlowShape<T, T>(Inlet, Outlet); } /// <summary> /// TBD /// </summary> public override FlowShape<T, T> Shape { get; } } /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> public sealed class Identity<T> : SimpleLinearGraphStage<T> { #region internal classes private sealed class Logic : InAndOutGraphStageLogic { private readonly Identity<T> _stage; public Logic(Identity<T> stage) : base(stage.Shape) { _stage = stage; SetHandler(stage.Inlet, this); SetHandler(stage.Outlet, this); } public override void OnPush() => Push(_stage.Outlet, Grab(_stage.Inlet)); public override void OnPull() => Pull(_stage.Inlet); } #endregion /// <summary> /// TBD /// </summary> public static readonly Identity<T> Instance = new Identity<T>(); private Identity() { } /// <summary> /// TBD /// </summary> protected override Attributes InitialAttributes { get; } = Attributes.CreateName("identityOp"); /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this); } /// <summary> /// INTERNAL API /// </summary> /// <typeparam name="T">TBD</typeparam> public sealed class Detacher<T> : SimpleLinearGraphStage<T> { #region internal classes private sealed class Logic : InAndOutGraphStageLogic { private readonly Detacher<T> _stage; public Logic(Detacher<T> stage) : base(stage.Shape) { _stage = stage; SetHandler(stage.Inlet, this); SetHandler(stage.Outlet, this); } public override void PreStart() => TryPull(_stage.Inlet); public override void OnPush() { var outlet = _stage.Outlet; if (IsAvailable(outlet)) { var inlet = _stage.Inlet; Push(outlet, Grab(inlet)); TryPull(inlet); } } public override void OnUpstreamFinish() { if (!IsAvailable(_stage.Inlet)) CompleteStage(); } public override void OnPull() { var inlet = _stage.Inlet; if (IsAvailable(inlet)) { var outlet = _stage.Outlet; Push(outlet, Grab(inlet)); if (IsClosed(inlet)) CompleteStage(); else Pull(inlet); } } } #endregion /// <summary> /// TBD /// </summary> public Detacher() : base("Detacher") { } /// <summary> /// TBD /// </summary> protected override Attributes InitialAttributes { get; } = Attributes.CreateName("Detacher"); /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this); /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override string ToString() => "Detacher"; } /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> internal sealed class TerminationWatcher<T> : GraphStageWithMaterializedValue<FlowShape<T, T>, Task> { /// <summary> /// TBD /// </summary> public static readonly TerminationWatcher<T> Instance = new TerminationWatcher<T>(); #region internal classes private sealed class Logic : InAndOutGraphStageLogic { private readonly TerminationWatcher<T> _stage; private readonly TaskCompletionSource<NotUsed> _finishPromise; public Logic(TerminationWatcher<T> stage, TaskCompletionSource<NotUsed> finishPromise) : base(stage.Shape) { _stage = stage; _finishPromise = finishPromise; SetHandler(stage._inlet, this); SetHandler(stage._outlet, this); } public override void OnPush() => Push(_stage._outlet, Grab(_stage._inlet)); public override void OnUpstreamFinish() { _finishPromise.TrySetResult(NotUsed.Instance); CompleteStage(); } public override void OnUpstreamFailure(Exception e) { _finishPromise.TrySetException(e); FailStage(e); } public override void OnPull() => Pull(_stage._inlet); public override void OnDownstreamFinish() { _finishPromise.TrySetResult(NotUsed.Instance); CompleteStage(); } } #endregion private readonly Inlet<T> _inlet = new Inlet<T>("terminationWatcher.in"); private readonly Outlet<T> _outlet = new Outlet<T>("terminationWatcher.out"); private TerminationWatcher() { Shape = new FlowShape<T, T>(_inlet, _outlet); } /// <summary> /// TBD /// </summary> protected override Attributes InitialAttributes { get; } = DefaultAttributes.TerminationWatcher; /// <summary> /// TBD /// </summary> public override FlowShape<T, T> Shape { get; } /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> public override ILogicAndMaterializedValue<Task> CreateLogicAndMaterializedValue(Attributes inheritedAttributes) { var finishPromise = new TaskCompletionSource<NotUsed>(); return new LogicAndMaterializedValue<Task>(new Logic(this, finishPromise), finishPromise.Task); } /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override string ToString() => "TerminationWatcher"; } // TODO: fix typo /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> internal sealed class FLowMonitorImpl<T> : AtomicReference<object>, IFlowMonitor { /// <summary> /// TBD /// </summary> public FLowMonitorImpl() : base(FlowMonitor.Initialized.Instance) { } /// <summary> /// TBD /// </summary> public FlowMonitor.IStreamState State { get { var value = Value; if(value is T) return new FlowMonitor.Received<T>((T)value); return value as FlowMonitor.IStreamState; } } } /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> internal sealed class MonitorFlow<T> : GraphStageWithMaterializedValue<FlowShape<T, T>, IFlowMonitor> { #region Logic private sealed class Logic : InAndOutGraphStageLogic { private readonly MonitorFlow<T> _stage; private readonly FLowMonitorImpl<T> _monitor; public Logic(MonitorFlow<T> stage, FLowMonitorImpl<T> monitor) : base(stage.Shape) { _stage = stage; _monitor = monitor; SetHandler(stage.In, this); SetHandler(stage.Out, this); } public override void OnPush() { var message = Grab(_stage.In); Push(_stage.Out, message); _monitor.Value = message is FlowMonitor.IStreamState ? new FlowMonitor.Received<T>(message) : (object)message; } public override void OnUpstreamFinish() { CompleteStage(); _monitor.Value = FlowMonitor.Finished.Instance; } public override void OnUpstreamFailure(Exception e) { FailStage(e); _monitor.Value = new FlowMonitor.Failed(e); } public override void OnPull() => Pull(_stage.In); public override void OnDownstreamFinish() { CompleteStage(); _monitor.Value = FlowMonitor.Finished.Instance; } public override string ToString() => "MonitorFlowLogic"; } #endregion /// <summary> /// TBD /// </summary> public MonitorFlow() { Shape = new FlowShape<T, T>(In, Out); } /// <summary> /// TBD /// </summary> public Inlet<T> In { get; } = new Inlet<T>("MonitorFlow.in"); /// <summary> /// TBD /// </summary> public Outlet<T> Out { get; } = new Outlet<T>("MonitorFlow.out"); /// <summary> /// TBD /// </summary> public override FlowShape<T, T> Shape { get; } /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> public override ILogicAndMaterializedValue<IFlowMonitor> CreateLogicAndMaterializedValue(Attributes inheritedAttributes) { var monitor = new FLowMonitorImpl<T>(); var logic = new Logic(this, monitor); return new LogicAndMaterializedValue<IFlowMonitor>(logic, monitor); } /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override string ToString() => "MonitorFlow"; } /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> public sealed class TickSource<T> : GraphStageWithMaterializedValue<SourceShape<T>, ICancelable> { #region internal classes [SuppressMessage("ReSharper", "MethodSupportsCancellation")] private sealed class Logic : TimerGraphStageLogic, ICancelable { private readonly TickSource<T> _stage; private readonly AtomicBoolean _cancelled = new AtomicBoolean(); private readonly AtomicReference<Action<NotUsed>> _cancelCallback = new AtomicReference<Action<NotUsed>>(null); public Logic(TickSource<T> stage) : base(stage.Shape) { _stage = stage; SetHandler(_stage.Out, EagerTerminateOutput); } public override void PreStart() { _cancelCallback.Value = GetAsyncCallback<NotUsed>(_ => CompleteStage()); if(_cancelled) CompleteStage(); else ScheduleRepeatedly("TickTimer", _stage._initialDelay, _stage._interval); } protected internal override void OnTimer(object timerKey) { if (IsAvailable(_stage.Out) && !_cancelled) Push(_stage.Out, _stage._tick); } public void Cancel() { if(!_cancelled.GetAndSet(true)) _cancelCallback.Value?.Invoke(NotUsed.Instance); } public bool IsCancellationRequested => _cancelled; public CancellationToken Token { get; } public void CancelAfter(TimeSpan delay) => Task.Delay(delay).ContinueWith(_ => Cancel()); public void CancelAfter(int millisecondsDelay) => Task.Delay(millisecondsDelay).ContinueWith(_ => Cancel()); public void Cancel(bool throwOnFirstException) => Cancel(); public override string ToString() => "TickSourceLogic"; } #endregion private readonly TimeSpan _initialDelay; private readonly TimeSpan _interval; private readonly T _tick; /// <summary> /// TBD /// </summary> /// <param name="initialDelay">TBD</param> /// <param name="interval">TBD</param> /// <param name="tick">TBD</param> public TickSource(TimeSpan initialDelay, TimeSpan interval, T tick) { _initialDelay = initialDelay; _interval = interval; _tick = tick; Shape = new SourceShape<T>(Out); } /// <summary> /// TBD /// </summary> protected override Attributes InitialAttributes { get; } = DefaultAttributes.TickSource; /// <summary> /// TBD /// </summary> public Outlet<T> Out { get; } = new Outlet<T>("TimerSource.out"); /// <summary> /// TBD /// </summary> public override SourceShape<T> Shape { get; } /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> public override ILogicAndMaterializedValue<ICancelable> CreateLogicAndMaterializedValue(Attributes inheritedAttributes) { var logic = new Logic(this); return new LogicAndMaterializedValue<ICancelable>(logic, logic); } /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override string ToString() => $"TickSource({_initialDelay}, {_interval}, {_tick})"; } /// <summary> /// TBD /// </summary> public interface IMaterializedValueSource { /// <summary> /// TBD /// </summary> IModule Module { get; } /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> IMaterializedValueSource CopySource(); /// <summary> /// TBD /// </summary> Outlet Outlet { get; } /// <summary> /// TBD /// </summary> StreamLayout.IMaterializedValueNode Computation { get; } /// <summary> /// TBD /// </summary> /// <param name="result">TBD</param> void SetValue(object result); } /// <summary> /// INTERNAL API /// /// This source is not reusable, it is only created internally. /// </summary> /// <typeparam name="T">TBD</typeparam> public sealed class MaterializedValueSource<T> : GraphStage<SourceShape<T>>, IMaterializedValueSource { #region internal classes private sealed class Logic : GraphStageLogic { private readonly MaterializedValueSource<T> _source; public Logic(MaterializedValueSource<T> source) : base(source.Shape) { _source = source; SetHandler(source.Outlet, EagerTerminateOutput); } public override void PreStart() { var cb = GetAsyncCallback<T>(element => Emit(_source.Outlet, element, CompleteStage)); _source._promise.Task.ContinueWith(task => cb(task.Result), TaskContinuationOptions.ExecuteSynchronously); } } #endregion private static readonly Attributes Name = Attributes.CreateName("matValueSource"); /// <summary> /// TBD /// </summary> public StreamLayout.IMaterializedValueNode Computation { get; } Outlet IMaterializedValueSource.Outlet => Outlet; /// <summary> /// TBD /// </summary> public readonly Outlet<T> Outlet; private readonly TaskCompletionSource<T> _promise = new TaskCompletionSource<T>(); /// <summary> /// TBD /// </summary> /// <param name="computation">TBD</param> /// <param name="outlet">TBD</param> public MaterializedValueSource(StreamLayout.IMaterializedValueNode computation, Outlet<T> outlet) { Computation = computation; Outlet = outlet; Shape = new SourceShape<T>(Outlet); } /// <summary> /// TBD /// </summary> /// <param name="computation">TBD</param> public MaterializedValueSource(StreamLayout.IMaterializedValueNode computation) : this(computation, new Outlet<T>("matValue")) { } /// <summary> /// TBD /// </summary> protected override Attributes InitialAttributes => Name; /// <summary> /// TBD /// </summary> public override SourceShape<T> Shape { get; } /// <summary> /// TBD /// </summary> /// <param name="value">TBD</param> public void SetValue(T value) => _promise.SetResult(value); void IMaterializedValueSource.SetValue(object result) => SetValue((T)result); /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public MaterializedValueSource<T> CopySource() => new MaterializedValueSource<T>(Computation, Outlet); IMaterializedValueSource IMaterializedValueSource.CopySource() => CopySource(); /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this); /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override string ToString() => $"MaterializedValueSource({Computation})"; } /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> public sealed class SingleSource<T> : GraphStage<SourceShape<T>> { #region Internal classes private sealed class Logic : OutGraphStageLogic { private readonly SingleSource<T> _stage; public Logic(SingleSource<T> stage) : base(stage.Shape) { _stage = stage; SetHandler(stage.Outlet, this); } public override void OnPull() { Push(_stage.Outlet, _stage._element); CompleteStage(); } } #endregion private readonly T _element; /// <summary> /// TBD /// </summary> public readonly Outlet<T> Outlet = new Outlet<T>("single.out"); /// <summary> /// TBD /// </summary> /// <param name="element">TBD</param> public SingleSource(T element) { ReactiveStreamsCompliance.RequireNonNullElement(element); _element = element; Shape = new SourceShape<T>(Outlet); } /// <summary> /// TBD /// </summary> public override SourceShape<T> Shape { get; } /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this); } /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> public sealed class TaskSource<T> : GraphStage<SourceShape<T>> { #region Internal classes private sealed class Logic : OutGraphStageLogic { private readonly TaskSource<T> _stage; public Logic(TaskSource<T> stage) : base(stage.Shape) { _stage = stage; SetHandler(stage.Outlet, this); } public override void OnPull() { var callback = GetAsyncCallback<Task<T>>(t => { if (!t.IsCanceled && !t.IsFaulted) Emit(_stage.Outlet, t.Result, CompleteStage); else FailStage(t.IsFaulted ? Flatten(t.Exception) : new TaskCanceledException("Task was cancelled.")); }); _stage._task.ContinueWith(t => callback(t), TaskContinuationOptions.ExecuteSynchronously); SetHandler(_stage.Outlet, EagerTerminateOutput); // After first pull we won't produce anything more } private Exception Flatten(AggregateException exception) => exception.InnerExceptions.Count == 1 ? exception.InnerExceptions[0] : exception; } #endregion private readonly Task<T> _task; /// <summary> /// TBD /// </summary> public readonly Outlet<T> Outlet = new Outlet<T>("task.out"); /// <summary> /// TBD /// </summary> /// <param name="task">TBD</param> public TaskSource(Task<T> task) { ReactiveStreamsCompliance.RequireNonNullElement(task); _task = task; Shape = new SourceShape<T>(Outlet); } /// <summary> /// TBD /// </summary> public override SourceShape<T> Shape { get; } /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this); /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override string ToString() => "TaskSource"; } /// <summary> /// INTERNAL API /// /// Discards all received elements. /// </summary> public sealed class IgnoreSink<T> : GraphStageWithMaterializedValue<SinkShape<T>, Task> { #region Internal classes private sealed class Logic : InGraphStageLogic { private readonly IgnoreSink<T> _stage; private readonly TaskCompletionSource<int> _completion; public Logic(IgnoreSink<T> stage, TaskCompletionSource<int> completion) : base(stage.Shape) { _stage = stage; _completion = completion; SetHandler(stage.Inlet, this); } public override void PreStart() => Pull(_stage.Inlet); public override void OnPush() => Pull(_stage.Inlet); public override void OnUpstreamFinish() { base.OnUpstreamFinish(); _completion.TrySetResult(0); } public override void OnUpstreamFailure(Exception e) { base.OnUpstreamFailure(e); _completion.TrySetException(e); } } #endregion public IgnoreSink() { Shape = new SinkShape<T>(Inlet); } protected override Attributes InitialAttributes { get; } = DefaultAttributes.IgnoreSink; public Inlet<T> Inlet { get; } = new Inlet<T>("Ignore.in"); public override SinkShape<T> Shape { get; } public override ILogicAndMaterializedValue<Task> CreateLogicAndMaterializedValue(Attributes inheritedAttributes) { var completion = new TaskCompletionSource<int>(); var logic = new Logic(this, completion); return new LogicAndMaterializedValue<Task>(logic, completion.Task); } public override string ToString() => "IgnoreSink"; } };
// *********************************************************************** // Copyright (c) 2008 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 !NETSTANDARD1_3 && !NETSTANDARD1_6 using System; using System.Reflection; namespace NUnit.Framework.Internal { [TestFixture] public class RuntimeFrameworkTests { static RuntimeType currentRuntime = Type.GetType("Mono.Runtime", false) != null ? RuntimeType.Mono : RuntimeType.Net; [Test] public void CanGetCurrentFramework() { RuntimeFramework framework = RuntimeFramework.CurrentFramework; Assert.That(framework.Runtime, Is.EqualTo(currentRuntime), "#1"); Assert.That(framework.ClrVersion, Is.EqualTo(Environment.Version), "#2"); } #if NET_4_5 [Test] public void TargetFrameworkIsSetCorrectly() { // We use reflection so it will compile and pass on Mono, // including older versions that do not have the property. var prop = typeof(AppDomainSetup).GetProperty("FrameworkName"); Assume.That(prop, Is.Not.Null); Assert.That( prop.GetValue(AppDomain.CurrentDomain.SetupInformation), Is.EqualTo(".NETFramework,Version=v4.5")); } [Test] public void DoesNotRunIn40CompatibilityModeWhenCompiled45() { var uri = new Uri( "http://host.com/path./" ); var uriStr = uri.ToString(); Assert.AreEqual( "http://host.com/path./", uriStr ); } #elif NET_4_0 [Test] [Platform(Exclude = "Mono", Reason = "Mono does not run assemblies targeting 4.0 in compatibility mode")] public void RunsIn40CompatibilityModeWhenCompiled40() { var uri = new Uri("http://host.com/path./"); var uriStr = uri.ToString(); Assert.AreEqual("http://host.com/path/", uriStr); } #endif [Test] public void CurrentFrameworkHasBuildSpecified() { Assert.That(RuntimeFramework.CurrentFramework.ClrVersion.Build, Is.GreaterThan(0)); } [TestCaseSource("frameworkData")] public void CanCreateUsingFrameworkVersion(FrameworkData data) { RuntimeFramework framework = new RuntimeFramework(data.runtime, data.frameworkVersion); Assert.AreEqual(data.runtime, framework.Runtime, "#1"); Assert.AreEqual(data.frameworkVersion, framework.FrameworkVersion, "#2"); Assert.AreEqual(data.clrVersion, framework.ClrVersion, "#3"); } [TestCaseSource("frameworkData")] public void CanCreateUsingClrVersion(FrameworkData data) { Assume.That(data.frameworkVersion.Major != 3, "#0"); RuntimeFramework framework = new RuntimeFramework(data.runtime, data.clrVersion); Assert.AreEqual(data.runtime, framework.Runtime, "#1"); Assert.AreEqual(data.frameworkVersion, framework.FrameworkVersion, "#2"); Assert.AreEqual(data.clrVersion, framework.ClrVersion, "#3"); } [TestCaseSource("frameworkData")] public void CanParseRuntimeFramework(FrameworkData data) { RuntimeFramework framework = RuntimeFramework.Parse(data.representation); Assert.AreEqual(data.runtime, framework.Runtime, "#1"); Assert.AreEqual(data.clrVersion, framework.ClrVersion, "#2"); } [TestCaseSource("frameworkData")] public void CanDisplayFrameworkAsString(FrameworkData data) { RuntimeFramework framework = new RuntimeFramework(data.runtime, data.frameworkVersion); Assert.AreEqual(data.representation, framework.ToString(), "#1"); Assert.AreEqual(data.displayName, framework.DisplayName, "#2"); } [TestCaseSource("matchData")] public bool CanMatchRuntimes(RuntimeFramework f1, RuntimeFramework f2) { return f1.Supports(f2); } internal static TestCaseData[] matchData = new TestCaseData[] { new TestCaseData( new RuntimeFramework(RuntimeType.Net, new Version(3,5)), new RuntimeFramework(RuntimeType.Net, new Version(2,0))) .Returns(true), new TestCaseData( new RuntimeFramework(RuntimeType.Net, new Version(2,0)), new RuntimeFramework(RuntimeType.Net, new Version(3,5))) .Returns(false), new TestCaseData( new RuntimeFramework(RuntimeType.Net, new Version(3,5)), new RuntimeFramework(RuntimeType.Net, new Version(3,5))) .Returns(true), new TestCaseData( new RuntimeFramework(RuntimeType.Net, new Version(2,0)), new RuntimeFramework(RuntimeType.Net, new Version(2,0))) .Returns(true), new TestCaseData( new RuntimeFramework(RuntimeType.Net, new Version(2,0)), new RuntimeFramework(RuntimeType.Net, new Version(2,0,50727))) .Returns(true), new TestCaseData( new RuntimeFramework(RuntimeType.Net, new Version(2,0,50727)), new RuntimeFramework(RuntimeType.Net, new Version(2,0))) .Returns(true), new TestCaseData( new RuntimeFramework(RuntimeType.Net, new Version(2,0,50727)), new RuntimeFramework(RuntimeType.Net, new Version(2,0))) .Returns(true), new TestCaseData( new RuntimeFramework(RuntimeType.Net, new Version(2,0)), new RuntimeFramework(RuntimeType.Mono, new Version(2,0))) .Returns(false), new TestCaseData( new RuntimeFramework(RuntimeType.Net, new Version(2,0)), new RuntimeFramework(RuntimeType.Net, new Version(1,1))) .Returns(false), new TestCaseData( new RuntimeFramework(RuntimeType.Net, new Version(2,0,50727)), new RuntimeFramework(RuntimeType.Net, new Version(2,0,40607))) .Returns(false), new TestCaseData( new RuntimeFramework(RuntimeType.Mono, new Version(1,1)), // non-existent version but it works new RuntimeFramework(RuntimeType.Mono, new Version(1,0))) .Returns(true), new TestCaseData( new RuntimeFramework(RuntimeType.Mono, new Version(2,0)), new RuntimeFramework(RuntimeType.Any, new Version(2,0))) .Returns(true), new TestCaseData( new RuntimeFramework(RuntimeType.Any, new Version(2,0)), new RuntimeFramework(RuntimeType.Mono, new Version(2,0))) .Returns(true), new TestCaseData( new RuntimeFramework(RuntimeType.Any, new Version(2,0)), new RuntimeFramework(RuntimeType.Any, new Version(2,0))) .Returns(true), new TestCaseData( new RuntimeFramework(RuntimeType.Any, new Version(2,0)), new RuntimeFramework(RuntimeType.Any, new Version(4,0))) .Returns(false), new TestCaseData( new RuntimeFramework(RuntimeType.Net, RuntimeFramework.DefaultVersion), new RuntimeFramework(RuntimeType.Net, new Version(2,0))) .Returns(true), new TestCaseData( new RuntimeFramework(RuntimeType.Net, new Version(2,0)), new RuntimeFramework(RuntimeType.Net, RuntimeFramework.DefaultVersion)) .Returns(true), new TestCaseData( new RuntimeFramework(RuntimeType.Any, RuntimeFramework.DefaultVersion), new RuntimeFramework(RuntimeType.Net, new Version(2,0))) .Returns(true), new TestCaseData( new RuntimeFramework(RuntimeType.Net, new Version(2,0)), new RuntimeFramework(RuntimeType.Any, RuntimeFramework.DefaultVersion)) .Returns(true) }; public struct FrameworkData { public RuntimeType runtime; public Version frameworkVersion; public Version clrVersion; public string representation; public string displayName; public FrameworkData(RuntimeType runtime, Version frameworkVersion, Version clrVersion, string representation, string displayName) { this.runtime = runtime; this.frameworkVersion = frameworkVersion; this.clrVersion = clrVersion; this.representation = representation; this.displayName = displayName; } public override string ToString() { return string.Format("<{0},{1},{2}>", this.runtime, this.frameworkVersion, this.clrVersion); } } internal static FrameworkData[] frameworkData = new FrameworkData[] { new FrameworkData(RuntimeType.Net, new Version(1,0), new Version(1,0,3705), "net-1.0", "Net 1.0"), // new FrameworkData(RuntimeType.Net, new Version(1,0,3705), new Version(1,0,3705), "net-1.0.3705", "Net 1.0.3705"), // new FrameworkData(RuntimeType.Net, new Version(1,0), new Version(1,0,3705), "net-1.0.3705", "Net 1.0.3705"), new FrameworkData(RuntimeType.Net, new Version(1,1), new Version(1,1,4322), "net-1.1", "Net 1.1"), // new FrameworkData(RuntimeType.Net, new Version(1,1,4322), new Version(1,1,4322), "net-1.1.4322", "Net 1.1.4322"), new FrameworkData(RuntimeType.Net, new Version(2,0), new Version(2,0,50727), "net-2.0", "Net 2.0"), // new FrameworkData(RuntimeType.Net, new Version(2,0,40607), new Version(2,0,40607), "net-2.0.40607", "Net 2.0.40607"), // new FrameworkData(RuntimeType.Net, new Version(2,0,50727), new Version(2,0,50727), "net-2.0.50727", "Net 2.0.50727"), new FrameworkData(RuntimeType.Net, new Version(3,0), new Version(2,0,50727), "net-3.0", "Net 3.0"), new FrameworkData(RuntimeType.Net, new Version(3,5), new Version(2,0,50727), "net-3.5", "Net 3.5"), new FrameworkData(RuntimeType.Net, new Version(4,0), new Version(4,0,30319), "net-4.0", "Net 4.0"), new FrameworkData(RuntimeType.Net, RuntimeFramework.DefaultVersion, RuntimeFramework.DefaultVersion, "net", "Net"), new FrameworkData(RuntimeType.Mono, new Version(1,0), new Version(1,1,4322), "mono-1.0", "Mono 1.0"), new FrameworkData(RuntimeType.Mono, new Version(2,0), new Version(2,0,50727), "mono-2.0", "Mono 2.0"), // new FrameworkData(RuntimeType.Mono, new Version(2,0,50727), new Version(2,0,50727), "mono-2.0.50727", "Mono 2.0.50727"), new FrameworkData(RuntimeType.Mono, new Version(3,5), new Version(2,0,50727), "mono-3.5", "Mono 3.5"), new FrameworkData(RuntimeType.Mono, new Version(4,0), new Version(4,0,30319), "mono-4.0", "Mono 4.0"), new FrameworkData(RuntimeType.Mono, RuntimeFramework.DefaultVersion, RuntimeFramework.DefaultVersion, "mono", "Mono"), new FrameworkData(RuntimeType.Any, new Version(1,1), new Version(1,1,4322), "v1.1", "v1.1"), new FrameworkData(RuntimeType.Any, new Version(2,0), new Version(2,0,50727), "v2.0", "v2.0"), // new FrameworkData(RuntimeType.Any, new Version(2,0,50727), new Version(2,0,50727), "v2.0.50727", "v2.0.50727"), new FrameworkData(RuntimeType.Any, new Version(3,5), new Version(2,0,50727), "v3.5", "v3.5"), new FrameworkData(RuntimeType.Any, new Version(4,0), new Version(4,0,30319), "v4.0", "v4.0"), new FrameworkData(RuntimeType.Any, RuntimeFramework.DefaultVersion, RuntimeFramework.DefaultVersion, "any", "Any") }; } } #endif
// Copyright (c) rubicon IT GmbH, www.rubicon.eu // // See the NOTICE file distributed with this work for additional information // regarding copyright ownership. rubicon licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. // using System; using System.Linq.Expressions; using Remotion.Linq.Clauses.Expressions; using Remotion.Linq.Utilities; namespace Remotion.Linq.Parsing { /// <summary> /// Implements an <see cref="ExpressionTreeVisitor"/> that throws an exception for every expression type that is not explicitly supported. /// Inherit from this class to ensure that an exception is thrown when an expression is passed /// </summary> internal abstract class ThrowingExpressionTreeVisitor : ExpressionTreeVisitor { protected abstract Exception CreateUnhandledItemException<T> (T unhandledItem, string visitMethod); /// <summary> /// Called when an unhandled item is visited. This method provides the item the visitor cannot handle (<paramref name="unhandledItem"/>), /// the <paramref name="visitMethod"/> that is not implemented in the visitor, and a delegate that can be used to invoke the /// <paramref name="baseBehavior"/> of the <see cref="ExpressionTreeVisitor"/> class. The default behavior of this method is to call the /// <see cref="CreateUnhandledItemException{T}"/> method, but it can be overridden to do something else. /// </summary> /// <typeparam name="TItem">The type of the item that could not be handled. Either an <see cref="Expression"/> type, a <see cref="MemberBinding"/> /// type, or <see cref="ElementInit"/>.</typeparam> /// <typeparam name="TResult">The result type expected for the visited <paramref name="unhandledItem"/>.</typeparam> /// <param name="unhandledItem">The unhandled item.</param> /// <param name="visitMethod">The visit method that is not implemented.</param> /// <param name="baseBehavior">The behavior exposed by <see cref="ExpressionTreeVisitor"/> for this item type.</param> /// <returns>An object to replace <paramref name="unhandledItem"/> in the expression tree. Alternatively, the method can throw any exception.</returns> protected virtual TResult VisitUnhandledItem<TItem, TResult> (TItem unhandledItem, string visitMethod, Func<TItem, TResult> baseBehavior) where TItem: TResult { ArgumentUtility.CheckNotNull ("unhandledItem", unhandledItem); ArgumentUtility.CheckNotNullOrEmpty ("visitMethod", visitMethod); ArgumentUtility.CheckNotNull ("baseBehavior", baseBehavior); throw CreateUnhandledItemException (unhandledItem, visitMethod); } protected internal override Expression VisitExtensionExpression (ExtensionExpression expression) { if (expression.CanReduce) return VisitExpression (expression.ReduceAndCheck ()); else return VisitUnhandledItem<ExtensionExpression, Expression> (expression, "VisitExtensionExpression", BaseVisitExtensionExpression); } protected Expression BaseVisitExtensionExpression (ExtensionExpression expression) { return base.VisitExtensionExpression (expression); } protected internal override Expression VisitUnknownNonExtensionExpression (Expression expression) { var expressionAsExtensionExpression = expression as ExtensionExpression; if (expressionAsExtensionExpression != null && expressionAsExtensionExpression.CanReduce) return VisitExpression (expressionAsExtensionExpression.ReduceAndCheck()); return VisitUnhandledItem<Expression, Expression> (expression, "VisitUnknownNonExtensionExpression", BaseVisitUnknownNonExtensionExpression); } protected Expression BaseVisitUnknownNonExtensionExpression (Expression expression) { return base.VisitUnknownNonExtensionExpression (expression); } protected override Expression VisitUnaryExpression (UnaryExpression expression) { return VisitUnhandledItem<UnaryExpression, Expression> (expression, "VisitUnaryExpression", BaseVisitUnaryExpression); } protected Expression BaseVisitUnaryExpression (UnaryExpression expression) { return base.VisitUnaryExpression (expression); } protected override Expression VisitBinaryExpression (BinaryExpression expression) { return VisitUnhandledItem<BinaryExpression, Expression> (expression, "VisitBinaryExpression", BaseVisitBinaryExpression); } protected Expression BaseVisitBinaryExpression (BinaryExpression expression) { return base.VisitBinaryExpression (expression); } protected override Expression VisitTypeBinaryExpression (TypeBinaryExpression expression) { return VisitUnhandledItem<TypeBinaryExpression, Expression> (expression, "VisitTypeBinaryExpression", BaseVisitTypeBinaryExpression); } protected Expression BaseVisitTypeBinaryExpression (TypeBinaryExpression expression) { return base.VisitTypeBinaryExpression (expression); } protected override Expression VisitConstantExpression (ConstantExpression expression) { return VisitUnhandledItem<ConstantExpression, Expression> (expression, "VisitConstantExpression", BaseVisitConstantExpression); } protected Expression BaseVisitConstantExpression (ConstantExpression expression) { return base.VisitConstantExpression (expression); } protected override Expression VisitConditionalExpression (ConditionalExpression expression) { return VisitUnhandledItem<ConditionalExpression, Expression> (expression, "VisitConditionalExpression", BaseVisitConditionalExpression); } protected Expression BaseVisitConditionalExpression (ConditionalExpression arg) { return base.VisitConditionalExpression (arg); } protected override Expression VisitParameterExpression (ParameterExpression expression) { return VisitUnhandledItem<ParameterExpression, Expression> (expression, "VisitParameterExpression", BaseVisitParameterExpression); } protected Expression BaseVisitParameterExpression (ParameterExpression expression) { return base.VisitParameterExpression (expression); } protected override Expression VisitLambdaExpression (LambdaExpression expression) { return VisitUnhandledItem<LambdaExpression, Expression> (expression, "VisitLambdaExpression", BaseVisitLambdaExpression); } protected Expression BaseVisitLambdaExpression (LambdaExpression expression) { return base.VisitLambdaExpression (expression); } protected override Expression VisitMethodCallExpression (MethodCallExpression expression) { return VisitUnhandledItem<MethodCallExpression, Expression> (expression, "VisitMethodCallExpression", BaseVisitMethodCallExpression); } protected Expression BaseVisitMethodCallExpression (MethodCallExpression expression) { return base.VisitMethodCallExpression (expression); } protected override Expression VisitInvocationExpression (InvocationExpression expression) { return VisitUnhandledItem<InvocationExpression, Expression> (expression, "VisitInvocationExpression", BaseVisitInvocationExpression); } protected Expression BaseVisitInvocationExpression (InvocationExpression expression) { return base.VisitInvocationExpression (expression); } protected override Expression VisitMemberExpression (MemberExpression expression) { return VisitUnhandledItem<MemberExpression, Expression> (expression, "VisitMemberExpression", BaseVisitMemberExpression); } protected Expression BaseVisitMemberExpression (MemberExpression expression) { return base.VisitMemberExpression (expression); } protected override Expression VisitNewExpression (NewExpression expression) { return VisitUnhandledItem<NewExpression, Expression> (expression, "VisitNewExpression", BaseVisitNewExpression); } protected Expression BaseVisitNewExpression (NewExpression expression) { return base.VisitNewExpression (expression); } protected override Expression VisitNewArrayExpression (NewArrayExpression expression) { return VisitUnhandledItem<NewArrayExpression, Expression> (expression, "VisitNewArrayExpression", BaseVisitNewArrayExpression); } protected Expression BaseVisitNewArrayExpression (NewArrayExpression expression) { return base.VisitNewArrayExpression (expression); } protected override Expression VisitMemberInitExpression (MemberInitExpression expression) { return VisitUnhandledItem<MemberInitExpression, Expression> (expression, "VisitMemberInitExpression", BaseVisitMemberInitExpression); } protected Expression BaseVisitMemberInitExpression (MemberInitExpression expression) { return base.VisitMemberInitExpression (expression); } protected override Expression VisitListInitExpression (ListInitExpression expression) { return VisitUnhandledItem<ListInitExpression, Expression> (expression, "VisitListInitExpression", BaseVisitListInitExpression); } protected Expression BaseVisitListInitExpression (ListInitExpression expression) { return base.VisitListInitExpression (expression); } protected override ElementInit VisitElementInit (ElementInit elementInit) { return VisitUnhandledItem<ElementInit, ElementInit> (elementInit, "VisitElementInit", BaseVisitElementInit); } protected ElementInit BaseVisitElementInit (ElementInit elementInit) { return base.VisitElementInit (elementInit); } protected override MemberBinding VisitMemberAssignment (MemberAssignment memberAssigment) { return VisitUnhandledItem<MemberAssignment, MemberBinding> (memberAssigment, "VisitMemberAssignment", BaseVisitMemberAssignment); } protected MemberBinding BaseVisitMemberAssignment (MemberAssignment memberAssigment) { return base.VisitMemberAssignment (memberAssigment); } protected override MemberBinding VisitMemberMemberBinding (MemberMemberBinding binding) { return VisitUnhandledItem<MemberMemberBinding, MemberBinding> (binding, "VisitMemberMemberBinding", BaseVisitMemberMemberBinding); } protected MemberBinding BaseVisitMemberMemberBinding (MemberMemberBinding binding) { return base.VisitMemberMemberBinding (binding); } protected override MemberBinding VisitMemberListBinding (MemberListBinding listBinding) { return VisitUnhandledItem<MemberListBinding, MemberBinding> (listBinding, "VisitMemberListBinding", BaseVisitMemberListBinding); } protected MemberBinding BaseVisitMemberListBinding (MemberListBinding listBinding) { return base.VisitMemberListBinding (listBinding); } protected override Expression VisitSubQueryExpression (SubQueryExpression expression) { return VisitUnhandledItem<SubQueryExpression, Expression> (expression, "VisitSubQueryExpression", BaseVisitSubQueryExpression); } protected Expression BaseVisitSubQueryExpression (SubQueryExpression expression) { return base.VisitSubQueryExpression (expression); } protected override Expression VisitQuerySourceReferenceExpression (QuerySourceReferenceExpression expression) { return VisitUnhandledItem<QuerySourceReferenceExpression, Expression> ( expression, "VisitQuerySourceReferenceExpression", BaseVisitQuerySourceReferenceExpression); } protected Expression BaseVisitQuerySourceReferenceExpression (QuerySourceReferenceExpression expression) { return base.VisitQuerySourceReferenceExpression (expression); } } }
/* * 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.Collections.Generic; using System.Linq; using System.Numerics; using Newtonsoft.Json; using QuantConnect.Configuration; using QuantConnect.Interfaces; using QuantConnect.Util; namespace QuantConnect { /// <summary> /// Defines a unique identifier for securities /// </summary> /// <remarks> /// The SecurityIdentifier contains information about a specific security. /// This includes the symbol and other data specific to the SecurityType. /// The symbol is limited to 12 characters /// </remarks> [JsonConverter(typeof(SecurityIdentifierJsonConverter))] public struct SecurityIdentifier : IEquatable<SecurityIdentifier> { #region Empty, DefaultDate Fields private static readonly string MapFileProviderTypeName = Config.Get("map-file-provider", "LocalDiskMapFileProvider"); private static readonly char[] InvalidCharacters = {'|', ' '}; /// <summary> /// Gets an instance of <see cref="SecurityIdentifier"/> that is empty, that is, one with no symbol specified /// </summary> public static readonly SecurityIdentifier Empty = new SecurityIdentifier(string.Empty, 0); /// <summary> /// Gets the date to be used when it does not apply. /// </summary> public static readonly DateTime DefaultDate = DateTime.FromOADate(0); /// <summary> /// Gets the set of invalids symbol characters /// </summary> public static readonly HashSet<char> InvalidSymbolCharacters = new HashSet<char>(InvalidCharacters); #endregion #region Scales, Widths and Market Maps // these values define the structure of the 'otherData' // the constant width fields are used via modulus, so the width is the number of zeros specified, // {put/call:1}{oa-date:5}{style:1}{strike:6}{strike-scale:2}{market:3}{security-type:2} private const ulong SecurityTypeWidth = 100; private const ulong SecurityTypeOffset = 1; private const ulong MarketWidth = 1000; private const ulong MarketOffset = SecurityTypeOffset * SecurityTypeWidth; private const int StrikeDefaultScale = 4; private static readonly ulong StrikeDefaultScaleExpanded = Pow(10, StrikeDefaultScale); private const ulong StrikeScaleWidth = 100; private const ulong StrikeScaleOffset = MarketOffset * MarketWidth; private const ulong StrikeWidth = 1000000; private const ulong StrikeOffset = StrikeScaleOffset * StrikeScaleWidth; private const ulong OptionStyleWidth = 10; private const ulong OptionStyleOffset = StrikeOffset * StrikeWidth; private const ulong DaysWidth = 100000; private const ulong DaysOffset = OptionStyleOffset * OptionStyleWidth; private const ulong PutCallOffset = DaysOffset * DaysWidth; private const ulong PutCallWidth = 10; #endregion #region Member variables private readonly string _symbol; private readonly ulong _properties; private readonly SidBox _underlying; #endregion #region Properties /// <summary> /// Gets whether or not this <see cref="SecurityIdentifier"/> is a derivative, /// that is, it has a valid <see cref="Underlying"/> property /// </summary> public bool HasUnderlying { get { return _underlying != null; } } /// <summary> /// Gets the underlying security identifier for this security identifier. When there is /// no underlying, this property will return a value of <see cref="Empty"/>. /// </summary> public SecurityIdentifier Underlying { get { if (_underlying == null) { throw new InvalidOperationException("No underlying specified for this identifier. Check that HasUnderlying is true before accessing the Underlying property."); } return _underlying.SecurityIdentifier; } } /// <summary> /// Gets the date component of this identifier. For equities this /// is the first date the security traded. Technically speaking, /// in LEAN, this is the first date mentioned in the map_files. /// For options this is the expiry date. For futures this is the /// settlement date. For forex and cfds this property will throw an /// exception as the field is not specified. /// </summary> public DateTime Date { get { var stype = SecurityType; switch (stype) { case SecurityType.Equity: case SecurityType.Option: case SecurityType.Future: var oadate = ExtractFromProperties(DaysOffset, DaysWidth); return DateTime.FromOADate(oadate); default: throw new InvalidOperationException("Date is only defined for SecurityType.Equity, SecurityType.Option and SecurityType.Future"); } } } /// <summary> /// Gets the original symbol used to generate this security identifier. /// For equities, by convention this is the first ticker symbol for which /// the security traded /// </summary> public string Symbol { get { return _symbol; } } /// <summary> /// Gets the market component of this security identifier. If located in the /// internal mappings, the full string is returned. If the value is unknown, /// the integer value is returned as a string. /// </summary> public string Market { get { var marketCode = ExtractFromProperties(MarketOffset, MarketWidth); var market = QuantConnect.Market.Decode((int)marketCode); // if we couldn't find it, send back the numeric representation return market ?? marketCode.ToString(); } } /// <summary> /// Gets the security type component of this security identifier. /// </summary> public SecurityType SecurityType { get { return (SecurityType)ExtractFromProperties(SecurityTypeOffset, SecurityTypeWidth); } } /// <summary> /// Gets the option strike price. This only applies to SecurityType.Option /// and will thrown anexception if accessed otherwse. /// </summary> public decimal StrikePrice { get { if (SecurityType != SecurityType.Option) { throw new InvalidOperationException("OptionType is only defined for SecurityType.Option"); } var scale = ExtractFromProperties(StrikeScaleOffset, StrikeScaleWidth); var unscaled = ExtractFromProperties(StrikeOffset, StrikeWidth); var pow = Math.Pow(10, (int)scale - StrikeDefaultScale); return unscaled * (decimal)pow; } } /// <summary> /// Gets the option type component of this security identifier. This /// only applies to SecurityType.Open and will throw an exception if /// accessed otherwise. /// </summary> public OptionRight OptionRight { get { if (SecurityType != SecurityType.Option) { throw new InvalidOperationException("OptionRight is only defined for SecurityType.Option"); } return (OptionRight)ExtractFromProperties(PutCallOffset, PutCallWidth); } } /// <summary> /// Gets the option style component of this security identifier. This /// only applies to SecurityType.Open and will throw an exception if /// accessed otherwise. /// </summary> public OptionStyle OptionStyle { get { if (SecurityType != SecurityType.Option) { throw new InvalidOperationException("OptionStyle is only defined for SecurityType.Option"); } return (OptionStyle)(ExtractFromProperties(OptionStyleOffset, OptionStyleWidth)); } } #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="SecurityIdentifier"/> class /// </summary> /// <param name="symbol">The base36 string encoded as a long using alpha [0-9A-Z]</param> /// <param name="properties">Other data defining properties of the symbol including market, /// security type, listing or expiry date, strike/call/put/style for options, ect...</param> public SecurityIdentifier(string symbol, ulong properties) { if (symbol == null) { throw new ArgumentNullException("symbol", "SecurityIdentifier requires a non-null string 'symbol'"); } if (symbol.IndexOfAny(InvalidCharacters) != -1) { throw new ArgumentException("symbol must not contain the characters '|' or ' '.", "symbol"); } _symbol = symbol; _properties = properties; _underlying = null; } /// <summary> /// Initializes a new instance of the <see cref="SecurityIdentifier"/> class /// </summary> /// <param name="symbol">The base36 string encoded as a long using alpha [0-9A-Z]</param> /// <param name="properties">Other data defining properties of the symbol including market, /// security type, listing or expiry date, strike/call/put/style for options, ect...</param> /// <param name="underlying">Specifies a <see cref="SecurityIdentifier"/> that represents the underlying security</param> public SecurityIdentifier(string symbol, ulong properties, SecurityIdentifier underlying) : this(symbol, properties) { if (symbol == null) { throw new ArgumentNullException("symbol", "SecurityIdentifier requires a non-null string 'symbol'"); } _symbol = symbol; _properties = properties; if (underlying != Empty) { _underlying = new SidBox(underlying); } } #endregion #region AddMarket, GetMarketCode, and Generate /// <summary> /// Generates a new <see cref="SecurityIdentifier"/> for an option /// </summary> /// <param name="expiry">The date the option expires</param> /// <param name="underlying">The underlying security's symbol</param> /// <param name="market">The market</param> /// <param name="strike">The strike price</param> /// <param name="optionRight">The option type, call or put</param> /// <param name="optionStyle">The option style, American or European</param> /// <returns>A new <see cref="SecurityIdentifier"/> representing the specified option security</returns> public static SecurityIdentifier GenerateOption(DateTime expiry, SecurityIdentifier underlying, string market, decimal strike, OptionRight optionRight, OptionStyle optionStyle) { return Generate(expiry, underlying.Symbol, SecurityType.Option, market, strike, optionRight, optionStyle, underlying); } /// <summary> /// Generates a new <see cref="SecurityIdentifier"/> for a future /// </summary> /// <param name="expiry">The date the option expires</param> /// <param name="underlying">The underlying security's symbol</param> /// <param name="market">The market</param> /// <returns>A new <see cref="SecurityIdentifier"/> representing the specified futures security</returns> public static SecurityIdentifier GenerateFuture(DateTime expiry, SecurityIdentifier underlying, string market) { return Generate(expiry, underlying.Symbol, SecurityType.Future, market, 0, 0, 0, underlying); } /// <summary> /// Helper overload that will search the mapfiles to resolve the first date. This implementation /// uses the configured <see cref="IMapFileProvider"/> via the <see cref="Composer.Instance"/> /// </summary> /// <param name="symbol">The symbol as it is known today</param> /// <param name="market">The market</param> /// <param name="mapSymbol">Specifies if symbol should be mapped using map file provider</param> /// <returns>A new <see cref="SecurityIdentifier"/> representing the specified symbol today</returns> public static SecurityIdentifier GenerateEquity(string symbol, string market, bool mapSymbol = true) { if (mapSymbol) { var provider = Composer.Instance.GetExportedValueByTypeName<IMapFileProvider>(MapFileProviderTypeName); var resolver = provider.Get(market); var mapFile = resolver.ResolveMapFile(symbol, DateTime.Today); var firstDate = mapFile.FirstDate; if (mapFile.Any()) { symbol = mapFile.OrderBy(x => x.Date).First().MappedSymbol; } return GenerateEquity(firstDate, symbol, market); } else { return GenerateEquity(DefaultDate, symbol, market); } } /// <summary> /// Generates a new <see cref="SecurityIdentifier"/> for an equity /// </summary> /// <param name="date">The first date this security traded (in LEAN this is the first date in the map_file</param> /// <param name="symbol">The ticker symbol this security traded under on the <paramref name="date"/></param> /// <param name="market">The security's market</param> /// <returns>A new <see cref="SecurityIdentifier"/> representing the specified equity security</returns> public static SecurityIdentifier GenerateEquity(DateTime date, string symbol, string market) { return Generate(date, symbol, SecurityType.Equity, market); } /// <summary> /// Generates a new <see cref="SecurityIdentifier"/> for a custom security /// </summary> /// <param name="symbol">The ticker symbol of this security</param> /// <param name="market">The security's market</param> /// <returns>A new <see cref="SecurityIdentifier"/> representing the specified base security</returns> public static SecurityIdentifier GenerateBase(string symbol, string market) { return Generate(DefaultDate, symbol, SecurityType.Base, market); } /// <summary> /// Generates a new <see cref="SecurityIdentifier"/> for a forex pair /// </summary> /// <param name="symbol">The currency pair in the format similar to: 'EURUSD'</param> /// <param name="market">The security's market</param> /// <returns>A new <see cref="SecurityIdentifier"/> representing the specified forex pair</returns> public static SecurityIdentifier GenerateForex(string symbol, string market) { return Generate(DefaultDate, symbol, SecurityType.Forex, market); } /// <summary> /// Generates a new <see cref="SecurityIdentifier"/> for a CFD security /// </summary> /// <param name="symbol">The CFD contract symbol</param> /// <param name="market">The security's market</param> /// <returns>A new <see cref="SecurityIdentifier"/> representing the specified CFD security</returns> public static SecurityIdentifier GenerateCfd(string symbol, string market) { return Generate(DefaultDate, symbol, SecurityType.Cfd, market); } /// <summary> /// Generic generate method. This method should be used carefully as some parameters are not required and /// some parameters mean different things for different security types /// </summary> private static SecurityIdentifier Generate(DateTime date, string symbol, SecurityType securityType, string market, decimal strike = 0, OptionRight optionRight = 0, OptionStyle optionStyle = 0, SecurityIdentifier? underlying = null) { if ((ulong)securityType >= SecurityTypeWidth || securityType < 0) { throw new ArgumentOutOfRangeException("securityType", "securityType must be between 0 and 99"); } if ((int)optionRight > 1 || optionRight < 0) { throw new ArgumentOutOfRangeException("optionRight", "optionType must be either 0 or 1"); } // normalize input strings market = market.ToLower(); symbol = symbol.ToUpper(); var marketIdentifier = QuantConnect.Market.Encode(market); if (!marketIdentifier.HasValue) { throw new ArgumentOutOfRangeException("market", string.Format("The specified market wasn't found in the markets lookup. Requested: {0}. " + "You can add markets by calling QuantConnect.Market.AddMarket(string,ushort)", market)); } var days = (ulong)date.ToOADate() * DaysOffset; var marketCode = (ulong)marketIdentifier * MarketOffset; ulong strikeScale; var strk = NormalizeStrike(strike, out strikeScale) * StrikeOffset; strikeScale *= StrikeScaleOffset; var style = (ulong)optionStyle * OptionStyleOffset; var putcall = (ulong)optionRight * PutCallOffset; var otherData = putcall + days + style + strk + strikeScale + marketCode + (ulong)securityType; return new SecurityIdentifier(symbol, otherData, underlying ?? Empty); } /// <summary> /// Converts an upper case alpha numeric string into a long /// </summary> private static ulong DecodeBase36(string symbol) { int pos = 0; ulong result = 0; for (int i = symbol.Length - 1; i > -1; i--) { var c = symbol[i]; // assumes alpha numeric upper case only strings var value = (uint)(c <= 57 ? c - '0' : c - 'A' + 10); result += value * Pow(36, pos++); } return result; } /// <summary> /// Converts a long to an uppercase alpha numeric string /// </summary> private static string EncodeBase36(ulong data) { var stack = new Stack<char>(); while (data != 0) { var value = data % 36; var c = value < 10 ? (char)(value + '0') : (char)(value - 10 + 'A'); stack.Push(c); data /= 36; } return new string(stack.ToArray()); } /// <summary> /// The strike is normalized into deci-cents and then a scale factor /// is also saved to bring it back to un-normalized /// </summary> private static ulong NormalizeStrike(decimal strike, out ulong scale) { var str = strike; if (strike == 0) { scale = 0; return 0; } // convert strike to default scaling, this keeps the scale always positive strike *= StrikeDefaultScaleExpanded; scale = 0; while (strike % 10 == 0) { strike /= 10; scale++; } if (strike >= 1000000) { throw new ArgumentException("The specified strike price's precision is too high: " + str); } return (ulong)strike; } /// <summary> /// Accurately performs the integer exponentiation /// </summary> private static ulong Pow(uint x, int pow) { // don't use Math.Pow(double, double) due to precision issues return (ulong)BigInteger.Pow(x, pow); } #endregion #region Parsing routines /// <summary> /// Parses the specified string into a <see cref="SecurityIdentifier"/> /// The string must be a 40 digit number. The first 20 digits must be parseable /// to a 64 bit unsigned integer and contain ancillary data about the security. /// The second 20 digits must also be parseable as a 64 bit unsigned integer and /// contain the symbol encoded from base36, this provides for 12 alpha numeric case /// insensitive characters. /// </summary> /// <param name="value">The string value to be parsed</param> /// <returns>A new <see cref="SecurityIdentifier"/> instance if the <paramref name="value"/> is able to be parsed.</returns> /// <exception cref="FormatException">This exception is thrown if the string's length is not exactly 40 characters, or /// if the components are unable to be parsed as 64 bit unsigned integers</exception> public static SecurityIdentifier Parse(string value) { Exception exception; SecurityIdentifier identifier; if (!TryParse(value, out identifier, out exception)) { throw exception; } return identifier; } /// <summary> /// Attempts to parse the specified <see paramref="value"/> as a <see cref="SecurityIdentifier"/>. /// </summary> /// <param name="value">The string value to be parsed</param> /// <param name="identifier">The result of parsing, when this function returns true, <paramref name="identifier"/> /// was properly created and reflects the input string, when this function returns false <paramref name="identifier"/> /// will equal default(SecurityIdentifier)</param> /// <returns>True on success, otherwise false</returns> public static bool TryParse(string value, out SecurityIdentifier identifier) { Exception exception; return TryParse(value, out identifier, out exception); } /// <summary> /// Helper method impl to be used by parse and tryparse /// </summary> private static bool TryParse(string value, out SecurityIdentifier identifier, out Exception exception) { if (!TryParseProperties(value, out exception, out identifier)) { return false; } return true; } /// <summary> /// Parses the string into its component ulong pieces /// </summary> private static bool TryParseProperties(string value, out Exception exception, out SecurityIdentifier identifier) { exception = null; identifier = Empty; if (string.IsNullOrWhiteSpace(value)) { return true; } var sids = value.Split('|'); for (var i = sids.Length - 1; i > -1; i--) { var current = sids[i]; var parts = current.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length != 2) { exception = new FormatException("The string must be splittable on space into two parts."); return false; } var symbol = parts[0]; var otherData = parts[1]; var props = DecodeBase36(otherData); // toss the previous in as the underlying, if Empty, ignored by ctor identifier = new SecurityIdentifier(symbol, props, identifier); } return true; } /// <summary> /// Extracts the embedded value from _otherData /// </summary> private ulong ExtractFromProperties(ulong offset, ulong width) { return (_properties/offset)%width; } #endregion #region Equality members and ToString /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <returns> /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false. /// </returns> /// <param name="other">An object to compare with this object.</param> public bool Equals(SecurityIdentifier other) { return _properties == other._properties && _symbol == other._symbol && _underlying == other._underlying; } /// <summary> /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// true if the specified object is equal to the current object; otherwise, false. /// </returns> /// <param name="obj">The object to compare with the current object. </param><filterpriority>2</filterpriority> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (obj.GetType() != GetType()) return false; return Equals((SecurityIdentifier)obj); } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> /// <filterpriority>2</filterpriority> public override int GetHashCode() { unchecked { return (_symbol.GetHashCode()*397) ^ _properties.GetHashCode(); } } /// <summary> /// Override equals operator /// </summary> public static bool operator ==(SecurityIdentifier left, SecurityIdentifier right) { return Equals(left, right); } /// <summary> /// Override not equals operator /// </summary> public static bool operator !=(SecurityIdentifier left, SecurityIdentifier right) { return !Equals(left, right); } /// <summary> /// Returns a string that represents the current object. /// </summary> /// <returns> /// A string that represents the current object. /// </returns> /// <filterpriority>2</filterpriority> public override string ToString() { var props = EncodeBase36(_properties); if (HasUnderlying) { return _symbol + ' ' + props + '|' + _underlying.SecurityIdentifier; } return _symbol + ' ' + props; } #endregion /// <summary> /// Provides a reference type container for a security identifier instance. /// This is used to maintain a reference to an underlying /// </summary> private sealed class SidBox : IEquatable<SidBox> { public readonly SecurityIdentifier SecurityIdentifier; public SidBox(SecurityIdentifier securityIdentifier) { SecurityIdentifier = securityIdentifier; } public bool Equals(SidBox other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return SecurityIdentifier.Equals(other.SecurityIdentifier); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj is SidBox && Equals((SidBox)obj); } public override int GetHashCode() { return SecurityIdentifier.GetHashCode(); } public static bool operator ==(SidBox left, SidBox right) { return Equals(left, right); } public static bool operator !=(SidBox left, SidBox right) { return !Equals(left, right); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Xsl.XsltOld { using System.Diagnostics; using System.Text; using System.Globalization; using System.Collections; using System.Collections.Generic; using System.Xml.XPath; using System.Xml.Xsl.Runtime; internal class NumberAction : ContainerAction { private const long msofnfcNil = 0x00000000; // no flags private const long msofnfcTraditional = 0x00000001; // use traditional numbering private const long msofnfcAlwaysFormat = 0x00000002; // if requested format is not supported, use Arabic (Western) style private const int cchMaxFormat = 63; // max size of formatted result private const int cchMaxFormatDecimal = 11; // max size of formatted decimal result (doesn't handle the case of a very large pwszSeparator or minlen) internal class FormatInfo { public bool isSeparator; // False for alphanumeric strings of chars public NumberingSequence numSequence; // Specifies numbering sequence public int length; // Minimum length of decimal numbers (if necessary, pad to left with zeros) public string formatString; // Format string for separator token public FormatInfo(bool isSeparator, string formatString) { this.isSeparator = isSeparator; this.formatString = formatString; } public FormatInfo() { } } private static FormatInfo s_defaultFormat = new FormatInfo(false, "0"); private static FormatInfo s_defaultSeparator = new FormatInfo(true, "."); private class NumberingFormat : NumberFormatterBase { private NumberingSequence _seq; private int _cMinLen; private string _separator; private int _sizeGroup; internal NumberingFormat() { } internal void setNumberingType(NumberingSequence seq) { _seq = seq; } //void setLangID(LID langid) {_langid = langid;} //internal void setTraditional(bool fTraditional) {_grfnfc = fTraditional ? msofnfcTraditional : 0;} internal void setMinLen(int cMinLen) { _cMinLen = cMinLen; } internal void setGroupingSeparator(string separator) { _separator = separator; } internal void setGroupingSize(int sizeGroup) { if (0 <= sizeGroup && sizeGroup <= 9) { _sizeGroup = sizeGroup; } } internal String FormatItem(object value) { double dblVal; if (value is int) { dblVal = (int)value; } else { dblVal = XmlConvert.ToXPathDouble(value); if (0.5 <= dblVal && !double.IsPositiveInfinity(dblVal)) { dblVal = XmlConvert.XPathRound(dblVal); } else { // It is an error if the number is NaN, infinite or less than 0.5; an XSLT processor may signal the error; // if it does not signal the error, it must recover by converting the number to a string as if by a call // to the string function and inserting the resulting string into the result tree. return XmlConvert.ToXPathString(value); } } Debug.Assert(dblVal >= 1); switch (_seq) { case NumberingSequence.Arabic: break; case NumberingSequence.UCLetter: case NumberingSequence.LCLetter: if (dblVal <= MaxAlphabeticValue) { StringBuilder sb = new StringBuilder(); ConvertToAlphabetic(sb, dblVal, _seq == NumberingSequence.UCLetter ? 'A' : 'a', 26); return sb.ToString(); } break; case NumberingSequence.UCRoman: case NumberingSequence.LCRoman: if (dblVal <= MaxRomanValue) { StringBuilder sb = new StringBuilder(); ConvertToRoman(sb, dblVal, _seq == NumberingSequence.UCRoman); return sb.ToString(); } break; } return ConvertToArabic(dblVal, _cMinLen, _sizeGroup, _separator); } private static string ConvertToArabic(double val, int minLength, int groupSize, string groupSeparator) { String str; if (groupSize != 0 && groupSeparator != null) { NumberFormatInfo NumberFormat = new NumberFormatInfo(); NumberFormat.NumberGroupSizes = new int[] { groupSize }; NumberFormat.NumberGroupSeparator = groupSeparator; if (Math.Floor(val) == val) { NumberFormat.NumberDecimalDigits = 0; } str = val.ToString("N", NumberFormat); } else { str = Convert.ToString(val, CultureInfo.InvariantCulture); } if (str.Length >= minLength) { return str; } else { StringBuilder sb = new StringBuilder(minLength); sb.Append('0', minLength - str.Length); sb.Append(str); return sb.ToString(); } } } // States: private const int OutputNumber = 2; private String _level; private String _countPattern; private int _countKey = Compiler.InvalidQueryKey; private String _from; private int _fromKey = Compiler.InvalidQueryKey; private String _value; private int _valueKey = Compiler.InvalidQueryKey; private Avt _formatAvt; private Avt _langAvt; private Avt _letterAvt; private Avt _groupingSepAvt; private Avt _groupingSizeAvt; // Compile time precalculated AVTs private List<FormatInfo> _formatTokens; private String _lang; private String _letter; private String _groupingSep; private String _groupingSize; private bool _forwardCompatibility; internal override bool CompileAttribute(Compiler compiler) { string name = compiler.Input.LocalName; string value = compiler.Input.Value; if (Ref.Equal(name, compiler.Atoms.Level)) { if (value != "any" && value != "multiple" && value != "single") { throw XsltException.Create(SR.Xslt_InvalidAttrValue, "level", value); } _level = value; } else if (Ref.Equal(name, compiler.Atoms.Count)) { _countPattern = value; _countKey = compiler.AddQuery(value, /*allowVars:*/true, /*allowKey:*/true, /*pattern*/true); } else if (Ref.Equal(name, compiler.Atoms.From)) { _from = value; _fromKey = compiler.AddQuery(value, /*allowVars:*/true, /*allowKey:*/true, /*pattern*/true); } else if (Ref.Equal(name, compiler.Atoms.Value)) { _value = value; _valueKey = compiler.AddQuery(value); } else if (Ref.Equal(name, compiler.Atoms.Format)) { _formatAvt = Avt.CompileAvt(compiler, value); } else if (Ref.Equal(name, compiler.Atoms.Lang)) { _langAvt = Avt.CompileAvt(compiler, value); } else if (Ref.Equal(name, compiler.Atoms.LetterValue)) { _letterAvt = Avt.CompileAvt(compiler, value); } else if (Ref.Equal(name, compiler.Atoms.GroupingSeparator)) { _groupingSepAvt = Avt.CompileAvt(compiler, value); } else if (Ref.Equal(name, compiler.Atoms.GroupingSize)) { _groupingSizeAvt = Avt.CompileAvt(compiler, value); } else { return false; } return true; } internal override void Compile(Compiler compiler) { CompileAttributes(compiler); CheckEmpty(compiler); _forwardCompatibility = compiler.ForwardCompatibility; _formatTokens = ParseFormat(PrecalculateAvt(ref _formatAvt)); _letter = ParseLetter(PrecalculateAvt(ref _letterAvt)); _lang = PrecalculateAvt(ref _langAvt); _groupingSep = PrecalculateAvt(ref _groupingSepAvt); if (_groupingSep != null && _groupingSep.Length > 1) { throw XsltException.Create(SR.Xslt_CharAttribute, "grouping-separator"); } _groupingSize = PrecalculateAvt(ref _groupingSizeAvt); } private int numberAny(Processor processor, ActionFrame frame) { int result = 0; // Our current point will be our end point in this search XPathNavigator endNode = frame.Node; if (endNode.NodeType == XPathNodeType.Attribute || endNode.NodeType == XPathNodeType.Namespace) { endNode = endNode.Clone(); endNode.MoveToParent(); } XPathNavigator startNode = endNode.Clone(); if (_fromKey != Compiler.InvalidQueryKey) { bool hitFrom = false; // First try to find start by traversing up. This gives the best candidate or we hit root do { if (processor.Matches(startNode, _fromKey)) { hitFrom = true; break; } } while (startNode.MoveToParent()); Debug.Assert( processor.Matches(startNode, _fromKey) || // we hit 'from' or startNode.NodeType == XPathNodeType.Root // we are at root ); // from this point (matched parent | root) create descendent quiery: // we have to reset 'result' on each 'from' node, because this point can' be not last from point; XPathNodeIterator sel = startNode.SelectDescendants(XPathNodeType.All, /*matchSelf:*/ true); while (sel.MoveNext()) { if (processor.Matches(sel.Current, _fromKey)) { hitFrom = true; result = 0; } else if (MatchCountKey(processor, frame.Node, sel.Current)) { result++; } if (sel.Current.IsSamePosition(endNode)) { break; } } if (!hitFrom) { result = 0; } } else { // without 'from' we startting from the root startNode.MoveToRoot(); XPathNodeIterator sel = startNode.SelectDescendants(XPathNodeType.All, /*matchSelf:*/ true); // and count root node by itself while (sel.MoveNext()) { if (MatchCountKey(processor, frame.Node, sel.Current)) { result++; } if (sel.Current.IsSamePosition(endNode)) { break; } } } return result; } // check 'from' condition: // if 'from' exist it has to be ancestor-or-self for the nav private bool checkFrom(Processor processor, XPathNavigator nav) { if (_fromKey == Compiler.InvalidQueryKey) { return true; } do { if (processor.Matches(nav, _fromKey)) { return true; } } while (nav.MoveToParent()); return false; } private bool moveToCount(XPathNavigator nav, Processor processor, XPathNavigator contextNode) { do { if (_fromKey != Compiler.InvalidQueryKey && processor.Matches(nav, _fromKey)) { return false; } if (MatchCountKey(processor, contextNode, nav)) { return true; } } while (nav.MoveToParent()); return false; } private int numberCount(XPathNavigator nav, Processor processor, XPathNavigator contextNode) { Debug.Assert(nav.NodeType != XPathNodeType.Attribute && nav.NodeType != XPathNodeType.Namespace); Debug.Assert(MatchCountKey(processor, contextNode, nav)); XPathNavigator runner = nav.Clone(); int number = 1; if (runner.MoveToParent()) { runner.MoveToFirstChild(); while (!runner.IsSamePosition(nav)) { if (MatchCountKey(processor, contextNode, runner)) { number++; } if (!runner.MoveToNext()) { Debug.Fail("We implementing preceding-sibling::node() and some how miss context node 'nav'"); break; } } } return number; } private static object SimplifyValue(object value) { // If result of xsl:number is not in correct range it should be returned as is. // so we need intermidiate string value. // If it's already a double we would like to keep it as double. // So this function converts to string only if if result is nodeset or RTF Debug.Assert(!(value is int)); if (Type.GetTypeCode(value.GetType()) == TypeCode.Object) { XPathNodeIterator nodeset = value as XPathNodeIterator; if (nodeset != null) { if (nodeset.MoveNext()) { return nodeset.Current.Value; } return string.Empty; } XPathNavigator nav = value as XPathNavigator; if (nav != null) { return nav.Value; } } return value; } internal override void Execute(Processor processor, ActionFrame frame) { Debug.Assert(processor != null && frame != null); ArrayList list = processor.NumberList; switch (frame.State) { case Initialized: Debug.Assert(frame != null); Debug.Assert(frame.NodeSet != null); list.Clear(); if (_valueKey != Compiler.InvalidQueryKey) { list.Add(SimplifyValue(processor.Evaluate(frame, _valueKey))); } else if (_level == "any") { int number = numberAny(processor, frame); if (number != 0) { list.Add(number); } } else { bool multiple = (_level == "multiple"); XPathNavigator contextNode = frame.Node; // context of xsl:number element. We using this node in MatchCountKey() XPathNavigator countNode = frame.Node.Clone(); // node we count for if (countNode.NodeType == XPathNodeType.Attribute || countNode.NodeType == XPathNodeType.Namespace) { countNode.MoveToParent(); } while (moveToCount(countNode, processor, contextNode)) { list.Insert(0, numberCount(countNode, processor, contextNode)); if (!multiple || !countNode.MoveToParent()) { break; } } if (!checkFrom(processor, countNode)) { list.Clear(); } } /*CalculatingFormat:*/ frame.StoredOutput = Format(list, _formatAvt == null ? _formatTokens : ParseFormat(_formatAvt.Evaluate(processor, frame)), _langAvt == null ? _lang : _langAvt.Evaluate(processor, frame), _letterAvt == null ? _letter : ParseLetter(_letterAvt.Evaluate(processor, frame)), _groupingSepAvt == null ? _groupingSep : _groupingSepAvt.Evaluate(processor, frame), _groupingSizeAvt == null ? _groupingSize : _groupingSizeAvt.Evaluate(processor, frame) ); goto case OutputNumber; case OutputNumber: Debug.Assert(frame.StoredOutput != null); if (!processor.TextEvent(frame.StoredOutput)) { frame.State = OutputNumber; break; } frame.Finished(); break; default: Debug.Fail("Invalid Number Action execution state"); break; } } private bool MatchCountKey(Processor processor, XPathNavigator contextNode, XPathNavigator nav) { if (_countKey != Compiler.InvalidQueryKey) { return processor.Matches(nav, _countKey); } if (contextNode.Name == nav.Name && BasicNodeType(contextNode.NodeType) == BasicNodeType(nav.NodeType)) { return true; } return false; } private XPathNodeType BasicNodeType(XPathNodeType type) { if (type == XPathNodeType.SignificantWhitespace || type == XPathNodeType.Whitespace) { return XPathNodeType.Text; } else { return type; } } // SDUB: perf. // for each call to xsl:number Format() will build new NumberingFormat object. // in case of no AVTs we can build this object at compile time and reuse it on execution time. // even partial step in this derection will be usefull (when cFormats == 0) private static string Format(ArrayList numberlist, List<FormatInfo> tokens, string lang, string letter, string groupingSep, string groupingSize) { StringBuilder result = new StringBuilder(); int cFormats = 0; if (tokens != null) { cFormats = tokens.Count; } NumberingFormat numberingFormat = new NumberingFormat(); if (groupingSize != null) { try { numberingFormat.setGroupingSize(Convert.ToInt32(groupingSize, CultureInfo.InvariantCulture)); } catch (System.FormatException) { } catch (System.OverflowException) { } } if (groupingSep != null) { if (groupingSep.Length > 1) { // It is a breaking change to throw an exception, SQLBUDT 324367 //throw XsltException.Create(SR.Xslt_CharAttribute, "grouping-separator"); } numberingFormat.setGroupingSeparator(groupingSep); } if (0 < cFormats) { FormatInfo prefix = tokens[0]; Debug.Assert(prefix == null || prefix.isSeparator); FormatInfo sufix = null; if (cFormats % 2 == 1) { sufix = tokens[cFormats - 1]; cFormats--; } FormatInfo periodicSeparator = 2 < cFormats ? tokens[cFormats - 2] : s_defaultSeparator; FormatInfo periodicFormat = 0 < cFormats ? tokens[cFormats - 1] : s_defaultFormat; if (prefix != null) { result.Append(prefix.formatString); } int numberlistCount = numberlist.Count; for (int i = 0; i < numberlistCount; i++) { int formatIndex = i * 2; bool haveFormat = formatIndex < cFormats; if (0 < i) { FormatInfo thisSeparator = haveFormat ? tokens[formatIndex + 0] : periodicSeparator; Debug.Assert(thisSeparator.isSeparator); result.Append(thisSeparator.formatString); } FormatInfo thisFormat = haveFormat ? tokens[formatIndex + 1] : periodicFormat; Debug.Assert(!thisFormat.isSeparator); //numberingFormat.setletter(this.letter); //numberingFormat.setLang(this.lang); numberingFormat.setNumberingType(thisFormat.numSequence); numberingFormat.setMinLen(thisFormat.length); result.Append(numberingFormat.FormatItem(numberlist[i])); } if (sufix != null) { result.Append(sufix.formatString); } } else { numberingFormat.setNumberingType(NumberingSequence.Arabic); for (int i = 0; i < numberlist.Count; i++) { if (i != 0) { result.Append("."); } result.Append(numberingFormat.FormatItem(numberlist[i])); } } return result.ToString(); } /* ---------------------------------------------------------------------------- mapFormatToken() Maps a token of alphanumeric characters to a numbering format ID and a minimum length bound. Tokens specify the character(s) that begins a Unicode numbering sequence. For example, "i" specifies lower case roman numeral numbering. Leading "zeros" specify a minimum length to be maintained by padding, if necessary. ---------------------------------------------------------------------------- */ private static void mapFormatToken(String wsToken, int startLen, int tokLen, out NumberingSequence seq, out int pminlen) { char wch = wsToken[startLen]; bool UseArabic = false; pminlen = 1; seq = NumberingSequence.Nil; switch ((int)wch) { case 0x0030: // Digit zero case 0x0966: // Hindi digit zero case 0x0e50: // Thai digit zero case 0xc77b: // Korean digit zero case 0xff10: // Digit zero (double-byte) do { // Leading zeros request padding. Track how much. pminlen++; } while ((--tokLen > 0) && (wch == wsToken[++startLen])); if (wsToken[startLen] != (char)(wch + 1)) { // If next character isn't "one", then use Arabic UseArabic = true; } break; } if (!UseArabic) { // Map characters of token to number format ID switch ((int)wsToken[startLen]) { case 0x0031: seq = NumberingSequence.Arabic; break; case 0x0041: seq = NumberingSequence.UCLetter; break; case 0x0049: seq = NumberingSequence.UCRoman; break; case 0x0061: seq = NumberingSequence.LCLetter; break; case 0x0069: seq = NumberingSequence.LCRoman; break; case 0x0410: seq = NumberingSequence.UCRus; break; case 0x0430: seq = NumberingSequence.LCRus; break; case 0x05d0: seq = NumberingSequence.Hebrew; break; case 0x0623: seq = NumberingSequence.ArabicScript; break; case 0x0905: seq = NumberingSequence.Hindi2; break; case 0x0915: seq = NumberingSequence.Hindi1; break; case 0x0967: seq = NumberingSequence.Hindi3; break; case 0x0e01: seq = NumberingSequence.Thai1; break; case 0x0e51: seq = NumberingSequence.Thai2; break; case 0x30a2: seq = NumberingSequence.DAiueo; break; case 0x30a4: seq = NumberingSequence.DIroha; break; case 0x3131: seq = NumberingSequence.DChosung; break; case 0x4e00: seq = NumberingSequence.FEDecimal; break; case 0x58f1: seq = NumberingSequence.DbNum3; break; case 0x58f9: seq = NumberingSequence.ChnCmplx; break; case 0x5b50: seq = NumberingSequence.Zodiac2; break; case 0xac00: seq = NumberingSequence.Ganada; break; case 0xc77c: seq = NumberingSequence.KorDbNum1; break; case 0xd558: seq = NumberingSequence.KorDbNum3; break; case 0xff11: seq = NumberingSequence.DArabic; break; case 0xff71: seq = NumberingSequence.Aiueo; break; case 0xff72: seq = NumberingSequence.Iroha; break; case 0x7532: if (tokLen > 1 && wsToken[startLen + 1] == 0x5b50) { // 60-based Zodiak numbering begins with two characters seq = NumberingSequence.Zodiac3; tokLen--; startLen++; } else { // 10-based Zodiak numbering begins with one character seq = NumberingSequence.Zodiac1; } break; default: seq = NumberingSequence.Arabic; break; } } //if (tokLen != 1 || UseArabic) { if (UseArabic) { // If remaining token length is not 1, then don't recognize // sequence and default to Arabic with no zero padding. seq = NumberingSequence.Arabic; pminlen = 0; } } /* ---------------------------------------------------------------------------- parseFormat() Parse format string into format tokens (alphanumeric) and separators (non-alphanumeric). */ private static List<FormatInfo> ParseFormat(string formatString) { if (formatString == null || formatString.Length == 0) { return null; } int length = 0; bool lastAlphaNumeric = CharUtil.IsAlphaNumeric(formatString[length]); List<FormatInfo> tokens = new List<FormatInfo>(); int count = 0; if (lastAlphaNumeric) { // If the first one is alpha num add empty separator as a prefix. tokens.Add(null); } while (length <= formatString.Length) { // Loop until a switch from format token to separator is detected (or vice-versa) bool currentchar = length < formatString.Length ? CharUtil.IsAlphaNumeric(formatString[length]) : !lastAlphaNumeric; if (lastAlphaNumeric != currentchar) { FormatInfo formatInfo = new FormatInfo(); if (lastAlphaNumeric) { // We just finished a format token. Map it to a numbering format ID and a min-length bound. mapFormatToken(formatString, count, length - count, out formatInfo.numSequence, out formatInfo.length); } else { formatInfo.isSeparator = true; // We just finished a separator. Save its length and a pointer to it. formatInfo.formatString = formatString.Substring(count, length - count); } count = length; length++; // Begin parsing the next format token or separator tokens.Add(formatInfo); // Flip flag from format token to separator (or vice-versa) lastAlphaNumeric = currentchar; } else { length++; } } return tokens; } private string ParseLetter(string letter) { if (letter == null || letter == "traditional" || letter == "alphabetic") { return letter; } if (!_forwardCompatibility) { throw XsltException.Create(SR.Xslt_InvalidAttrValue, "letter-value", letter); } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Globalization { /* ** Calendar support range: ** Calendar Minimum Maximum ** ========== ========== ========== ** Gregorian 1960/01/28 2050/01/22 ** JapaneseLunisolar 1960/01/01 2049/12/29 */ public class JapaneseLunisolarCalendar : EastAsianLunisolarCalendar { // // The era value for the current era. // public const int JapaneseEra = 1; internal GregorianCalendarHelper helper; internal const int MIN_LUNISOLAR_YEAR = 1960; internal const int MAX_LUNISOLAR_YEAR = 2049; internal const int MIN_GREGORIAN_YEAR = 1960; internal const int MIN_GREGORIAN_MONTH = 1; internal const int MIN_GREGORIAN_DAY = 28; internal const int MAX_GREGORIAN_YEAR = 2050; internal const int MAX_GREGORIAN_MONTH = 1; internal const int MAX_GREGORIAN_DAY = 22; internal static DateTime minDate = new DateTime(MIN_GREGORIAN_YEAR, MIN_GREGORIAN_MONTH, MIN_GREGORIAN_DAY); internal static DateTime maxDate = new DateTime((new DateTime(MAX_GREGORIAN_YEAR, MAX_GREGORIAN_MONTH, MAX_GREGORIAN_DAY, 23, 59, 59, 999)).Ticks + 9999); public override DateTime MinSupportedDateTime { get { return (minDate); } } public override DateTime MaxSupportedDateTime { get { return (maxDate); } } protected override int DaysInYearBeforeMinSupportedYear { get { // 1959 from ChineseLunisolarCalendar return 354; } } private static readonly int[,] s_yinfo = { /*Y LM Lmon Lday DaysPerMonth D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 #Days 1960 */ { 6 , 1 , 28 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 29 384 1961 */{ 0 , 2 , 15 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355 1962 */{ 0 , 2 , 5 , 19808 },/* 29 30 29 29 30 30 29 30 29 30 30 29 0 354 1963 */{ 4 , 1 , 25 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384 1964 */{ 0 , 2 , 13 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355 1965 */{ 0 , 2 , 2 , 21104 },/* 29 30 29 30 29 29 30 29 29 30 30 30 0 354 1966 */{ 3 , 1 , 22 , 26928 },/* 29 30 30 29 30 29 29 30 29 29 30 30 29 383 1967 */{ 0 , 2 , 9 , 55632 },/* 30 30 29 30 30 29 29 30 29 30 29 30 0 355 1968 */{ 7 , 1 , 30 , 27304 },/* 29 30 30 29 30 29 30 29 30 29 30 29 30 384 1969 */{ 0 , 2 , 17 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354 1970 */{ 0 , 2 , 6 , 39632 },/* 30 29 29 30 30 29 30 29 30 30 29 30 0 355 1971 */{ 5 , 1 , 27 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 1972 */{ 0 , 2 , 15 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354 1973 */{ 0 , 2 , 3 , 42208 },/* 30 29 30 29 29 30 29 29 30 30 30 29 0 354 1974 */{ 4 , 1 , 23 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384 1975 */{ 0 , 2 , 11 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 1976 */{ 8 , 1 , 31 , 54600 },/* 30 30 29 30 29 30 29 30 29 30 29 29 30 384 1977 */{ 0 , 2 , 18 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354 1978 */{ 0 , 2 , 7 , 54944 },/* 30 30 29 30 29 30 30 29 30 29 30 29 0 355 1979 */{ 6 , 1 , 28 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384 1980 */{ 0 , 2 , 16 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355 1981 */{ 0 , 2 , 5 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354 1982 */{ 4 , 1 , 25 , 42200 },/* 30 29 30 29 29 30 29 29 30 30 29 30 30 384 1983 */{ 0 , 2 , 13 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 1984 */{ 10 , 2 , 2 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384 1985 */{ 0 , 2 , 20 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354 1986 */{ 0 , 2 , 9 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354 1987 */{ 6 , 1 , 29 , 46504 },/* 30 29 30 30 29 30 29 30 30 29 30 29 30 385 1988 */{ 0 , 2 , 18 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354 1989 */{ 0 , 2 , 6 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355 1990 */{ 5 , 1 , 27 , 18872 },/* 29 30 29 29 30 29 29 30 30 29 30 30 30 384 1991 */{ 0 , 2 , 15 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354 1992 */{ 0 , 2 , 4 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354 1993 */{ 3 , 1 , 23 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 29 383 1994 */{ 0 , 2 , 10 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355 1995 */{ 8 , 1 , 31 , 27976 },/* 29 30 30 29 30 30 29 30 29 30 29 29 30 384 1996 */{ 0 , 2 , 19 , 23248 },/* 29 30 29 30 30 29 30 29 30 30 29 30 0 355 1997 */{ 0 , 2 , 8 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354 1998 */{ 5 , 1 , 28 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 29 384 1999 */{ 0 , 2 , 16 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354 2000 */{ 0 , 2 , 5 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354 2001 */{ 4 , 1 , 24 , 58536 },/* 30 30 30 29 29 30 29 29 30 29 30 29 30 384 2002 */{ 0 , 2 , 12 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354 2003 */{ 0 , 2 , 1 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 0 355 2004 */{ 2 , 1 , 22 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384 2005 */{ 0 , 2 , 9 , 22208 },/* 29 30 29 30 29 30 30 29 30 30 29 29 0 354 2006 */{ 7 , 1 , 29 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385 2007 */{ 0 , 2 , 18 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354 2008 */{ 0 , 2 , 7 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354 2009 */{ 5 , 1 , 26 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384 2010 */{ 0 , 2 , 14 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354 2011 */{ 0 , 2 , 3 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354 2012 */{ 3 , 1 , 23 , 47696 },/* 30 29 30 30 30 29 30 29 29 30 29 30 29 384 2013 */{ 0 , 2 , 10 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355 2014 */{ 9 , 1 , 31 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384 2015 */{ 0 , 2 , 19 , 19360 },/* 29 30 29 29 30 29 30 30 30 29 30 29 0 354 2016 */{ 0 , 2 , 8 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355 2017 */{ 5 , 1 , 28 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384 2018 */{ 0 , 2 , 16 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354 2019 */{ 0 , 2 , 5 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354 2020 */{ 4 , 1 , 25 , 46248 },/* 30 29 30 30 29 30 29 29 30 29 30 29 30 384 2021 */{ 0 , 2 , 12 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354 2022 */{ 0 , 2 , 1 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355 2023 */{ 2 , 1 , 22 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384 2024 */{ 0 , 2 , 10 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354 2025 */{ 6 , 1 , 29 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384 2026 */{ 0 , 2 , 17 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355 2027 */{ 0 , 2 , 7 , 21104 },/* 29 30 29 30 29 29 30 29 29 30 30 30 0 354 2028 */{ 5 , 1 , 27 , 26928 },/* 29 30 30 29 30 29 29 30 29 29 30 30 29 383 2029 */{ 0 , 2 , 13 , 55600 },/* 30 30 29 30 30 29 29 30 29 29 30 30 0 355 2030 */{ 0 , 2 , 3 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354 2031 */{ 3 , 1 , 23 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 29 384 2032 */{ 0 , 2 , 11 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355 2033 */{ 11 , 1 , 31 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 2034 */{ 0 , 2 , 19 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354 2035 */{ 0 , 2 , 8 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354 2036 */{ 6 , 1 , 28 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384 2037 */{ 0 , 2 , 15 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 2038 */{ 0 , 2 , 4 , 54560 },/* 30 30 29 30 29 30 29 30 29 29 30 29 0 354 2039 */{ 5 , 1 , 24 , 55968 },/* 30 30 29 30 30 29 30 29 30 29 30 29 29 384 2040 */{ 0 , 2 , 12 , 46752 },/* 30 29 30 30 29 30 30 29 30 29 30 29 0 355 2041 */{ 0 , 2 , 1 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355 2042 */{ 2 , 1 , 22 , 19160 },/* 29 30 29 29 30 29 30 29 30 30 29 30 30 384 2043 */{ 0 , 2 , 10 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354 2044 */{ 7 , 1 , 30 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384 2045 */{ 0 , 2 , 17 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 2046 */{ 0 , 2 , 6 , 45648 },/* 30 29 30 30 29 29 30 29 29 30 29 30 0 354 2047 */{ 5 , 1 , 26 , 46376 },/* 30 29 30 30 29 30 29 30 29 29 30 29 30 384 2048 */{ 0 , 2 , 14 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354 2049 */{ 0 , 2 , 2 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 0 355 */ }; internal override int MinCalendarYear { get { return (MIN_LUNISOLAR_YEAR); } } internal override int MaxCalendarYear { get { return (MAX_LUNISOLAR_YEAR); } } internal override DateTime MinDate { get { return (minDate); } } internal override DateTime MaxDate { get { return (maxDate); } } internal override EraInfo[] CalEraInfo { get { return (JapaneseCalendar.GetEraInfo()); } } internal override int GetYearInfo(int lunarYear, int index) { if ((lunarYear < MIN_LUNISOLAR_YEAR) || (lunarYear > MAX_LUNISOLAR_YEAR)) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, MIN_LUNISOLAR_YEAR, MAX_LUNISOLAR_YEAR)); } return s_yinfo[lunarYear - MIN_LUNISOLAR_YEAR, index]; } internal override int GetYear(int year, DateTime time) { return helper.GetYear(year, time); } internal override int GetGregorianYear(int year, int era) { return helper.GetGregorianYear(year, era); } // Trim off the eras that are before our date range private static EraInfo[] TrimEras(EraInfo[] baseEras) { EraInfo[] newEras = new EraInfo[baseEras.Length]; int newIndex = 0; // Eras have most recent first, so start with that for (int i = 0; i < baseEras.Length; i++) { // If this one's minimum year is bigger than our maximum year // then we can't use it. if (baseEras[i].yearOffset + baseEras[i].minEraYear >= MAX_LUNISOLAR_YEAR) { // skip this one. continue; } // If this one's maximum era is less than our minimum era // then we've gotten too low in the era #s, so we're done if (baseEras[i].yearOffset + baseEras[i].maxEraYear < MIN_LUNISOLAR_YEAR) { break; } // Wasn't too large or too small, can use this one newEras[newIndex] = baseEras[i]; newIndex++; } // If we didn't copy any then something was wrong, just return base if (newIndex == 0) return baseEras; // Resize the output array Array.Resize(ref newEras, newIndex); return newEras; } // Construct an instance of JapaneseLunisolar calendar. public JapaneseLunisolarCalendar() { helper = new GregorianCalendarHelper(this, TrimEras(JapaneseCalendar.GetEraInfo())); } public override int GetEra(DateTime time) { return (helper.GetEra(time)); } internal override CalendarId BaseCalendarID { get { return (CalendarId.JAPAN); } } internal override CalendarId ID { get { return (CalendarId.JAPANESELUNISOLAR); } } public override int[] Eras { get { return (helper.Eras); } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using OrchardCore.Environment.Extensions.Features; using OrchardCore.Environment.Extensions.Loaders; using OrchardCore.Environment.Extensions.Manifests; using OrchardCore.Environment.Extensions.Utility; using OrchardCore.Modules; namespace OrchardCore.Environment.Extensions { public class ExtensionManager : IExtensionManager { private readonly IApplicationContext _applicationContext; private readonly IEnumerable<IExtensionDependencyStrategy> _extensionDependencyStrategies; private readonly IEnumerable<IExtensionPriorityStrategy> _extensionPriorityStrategies; private readonly ITypeFeatureProvider _typeFeatureProvider; private readonly IFeaturesProvider _featuresProvider; private IDictionary<string, ExtensionEntry> _extensions; private IEnumerable<IExtensionInfo> _extensionsInfos; private IDictionary<string, FeatureEntry> _features; private IFeatureInfo[] _featureInfos; private readonly ConcurrentDictionary<string, Lazy<IEnumerable<IFeatureInfo>>> _featureDependencies = new ConcurrentDictionary<string, Lazy<IEnumerable<IFeatureInfo>>>(); private readonly ConcurrentDictionary<string, Lazy<IEnumerable<IFeatureInfo>>> _dependentFeatures = new ConcurrentDictionary<string, Lazy<IEnumerable<IFeatureInfo>>>(); private static readonly Func<IFeatureInfo, IFeatureInfo[], IFeatureInfo[]> GetDependentFeaturesFunc = new Func<IFeatureInfo, IFeatureInfo[], IFeatureInfo[]>( (currentFeature, fs) => fs .Where(f => f.Dependencies.Any(dep => dep == currentFeature.Id)) .ToArray()); private static readonly Func<IFeatureInfo, IFeatureInfo[], IFeatureInfo[]> GetFeatureDependenciesFunc = new Func<IFeatureInfo, IFeatureInfo[], IFeatureInfo[]>( (currentFeature, fs) => fs .Where(f => currentFeature.Dependencies.Any(dep => dep == f.Id)) .ToArray()); private bool _isInitialized = false; private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1); public ExtensionManager( IApplicationContext applicationContext, IEnumerable<IExtensionDependencyStrategy> extensionDependencyStrategies, IEnumerable<IExtensionPriorityStrategy> extensionPriorityStrategies, ITypeFeatureProvider typeFeatureProvider, IFeaturesProvider featuresProvider, ILogger<ExtensionManager> logger) { _applicationContext = applicationContext; _extensionDependencyStrategies = extensionDependencyStrategies; _extensionPriorityStrategies = extensionPriorityStrategies; _typeFeatureProvider = typeFeatureProvider; _featuresProvider = featuresProvider; L = logger; } public ILogger L { get; set; } public IExtensionInfo GetExtension(string extensionId) { EnsureInitialized(); ExtensionEntry extension; if (!String.IsNullOrEmpty(extensionId) && _extensions.TryGetValue(extensionId, out extension)) { return extension.ExtensionInfo; } return new NotFoundExtensionInfo(extensionId); } public IEnumerable<IExtensionInfo> GetExtensions() { EnsureInitialized(); return _extensionsInfos; } public IEnumerable<IFeatureInfo> GetFeatures(string[] featureIdsToLoad) { EnsureInitialized(); var allDependencies = featureIdsToLoad .SelectMany(featureId => GetFeatureDependencies(featureId)) .Distinct(); return _featureInfos .Where(f => allDependencies.Any(d => d.Id == f.Id)); } public Task<ExtensionEntry> LoadExtensionAsync(IExtensionInfo extensionInfo) { EnsureInitialized(); ExtensionEntry extension; if (_extensions.TryGetValue(extensionInfo.Id, out extension)) { return Task.FromResult(extension); } return Task.FromResult<ExtensionEntry>(null); } public async Task<IEnumerable<FeatureEntry>> LoadFeaturesAsync() { await EnsureInitializedAsync(); return _features.Values; } public async Task<IEnumerable<FeatureEntry>> LoadFeaturesAsync(string[] featureIdsToLoad) { await EnsureInitializedAsync(); var features = GetFeatures(featureIdsToLoad).Select(f => f.Id).ToList(); var loadedFeatures = _features.Values .Where(f => features.Contains(f.FeatureInfo.Id)); return loadedFeatures; } public IEnumerable<IFeatureInfo> GetFeatureDependencies(string featureId) { EnsureInitialized(); return _featureDependencies.GetOrAdd(featureId, (key) => new Lazy<IEnumerable<IFeatureInfo>>(() => { if (!_features.ContainsKey(key)) { return Enumerable.Empty<IFeatureInfo>(); } var feature = _features[key].FeatureInfo; return GetFeatureDependencies(feature, _featureInfos); })).Value; } public IEnumerable<IFeatureInfo> GetDependentFeatures(string featureId) { EnsureInitialized(); return _dependentFeatures.GetOrAdd(featureId, (key) => new Lazy<IEnumerable<IFeatureInfo>>(() => { if (!_features.ContainsKey(key)) { return Enumerable.Empty<IFeatureInfo>(); } var feature = _features[key].FeatureInfo; return GetDependentFeatures(feature, _featureInfos); })).Value; } private IEnumerable<IFeatureInfo> GetFeatureDependencies( IFeatureInfo feature, IFeatureInfo[] features) { var dependencies = new HashSet<IFeatureInfo>() { feature }; var stack = new Stack<IFeatureInfo[]>(); stack.Push(GetFeatureDependenciesFunc(feature, features)); while (stack.Count > 0) { var next = stack.Pop(); foreach (var dependency in next.Where(dependency => !dependencies.Contains(dependency))) { dependencies.Add(dependency); stack.Push(GetFeatureDependenciesFunc(dependency, features)); } } // Preserve the underlying order of feature infos. return _featureInfos.Where(f => dependencies.Any(d => d.Id == f.Id)); } private IEnumerable<IFeatureInfo> GetDependentFeatures( IFeatureInfo feature, IFeatureInfo[] features) { var dependencies = new HashSet<IFeatureInfo>() { feature }; var stack = new Stack<IFeatureInfo[]>(); stack.Push(GetDependentFeaturesFunc(feature, features)); while (stack.Count > 0) { var next = stack.Pop(); foreach (var dependency in next.Where(dependency => !dependencies.Contains(dependency))) { dependencies.Add(dependency); stack.Push(GetDependentFeaturesFunc(dependency, features)); } } // Preserve the underlying order of feature infos. return _featureInfos.Where(f => dependencies.Any(d => d.Id == f.Id)); } public IEnumerable<IFeatureInfo> GetFeatures() { EnsureInitialized(); return _featureInfos; } private static string GetSourceFeatureNameForType(Type type, string extensionId) { var attribute = type.GetCustomAttributes<FeatureAttribute>(false).FirstOrDefault(); return attribute?.FeatureName ?? extensionId; } private void EnsureInitialized() { if (_isInitialized) { return; } EnsureInitializedAsync().GetAwaiter().GetResult(); } private async Task EnsureInitializedAsync() { if (_isInitialized) { return; } await _semaphore.WaitAsync(); try { if (_isInitialized) { return; } var modules = _applicationContext.Application.Modules; var loadedExtensions = new ConcurrentDictionary<string, ExtensionEntry>(); // Load all extensions in parallel await modules.ForEachAsync((module) => { if (!module.ModuleInfo.Exists) { return Task.CompletedTask; } var manifestInfo = new ManifestInfo(module.ModuleInfo); var extensionInfo = new ExtensionInfo(module.SubPath, manifestInfo, (mi, ei) => { return _featuresProvider.GetFeatures(ei, mi); }); var entry = new ExtensionEntry { ExtensionInfo = extensionInfo, Assembly = module.Assembly, ExportedTypes = module.Assembly.ExportedTypes }; loadedExtensions.TryAdd(module.Name, entry); return Task.CompletedTask; }); var loadedFeatures = new Dictionary<string, FeatureEntry>(); // Get all valid types from any extension var allTypesByExtension = loadedExtensions.SelectMany(extension => extension.Value.ExportedTypes.Where(IsComponentType) .Select(type => new { ExtensionEntry = extension.Value, Type = type })).ToArray(); var typesByFeature = allTypesByExtension .GroupBy(typeByExtension => GetSourceFeatureNameForType( typeByExtension.Type, typeByExtension.ExtensionEntry.ExtensionInfo.Id)) .ToDictionary( group => group.Key, group => group.Select(typesByExtension => typesByExtension.Type).ToArray()); foreach (var loadedExtension in loadedExtensions) { var extension = loadedExtension.Value; foreach (var feature in extension.ExtensionInfo.Features) { // Features can have no types if (typesByFeature.TryGetValue(feature.Id, out var featureTypes)) { foreach (var type in featureTypes) { _typeFeatureProvider.TryAdd(type, feature); } } else { featureTypes = Array.Empty<Type>(); } loadedFeatures.Add(feature.Id, new CompiledFeatureEntry(feature, featureTypes)); } }; // Feature infos and entries are ordered by priority and dependencies. _featureInfos = Order(loadedFeatures.Values.Select(f => f.FeatureInfo)); _features = _featureInfos.ToDictionary(f => f.Id, f => loadedFeatures[f.Id]); // Extensions are also ordered according to the weight of their first features. _extensionsInfos = _featureInfos.Where(f => f.Id == f.Extension.Features.First().Id) .Select(f => f.Extension); _extensions = _extensionsInfos.ToDictionary(e => e.Id, e => loadedExtensions[e.Id]); _isInitialized = true; } finally { _semaphore.Release(); } } private bool IsComponentType(Type type) { return type.IsClass && !type.IsAbstract && type.IsPublic; } private IFeatureInfo[] Order(IEnumerable<IFeatureInfo> featuresToOrder) { return featuresToOrder .OrderBy(x => x.Id) .OrderByDependenciesAndPriorities(HasDependency, GetPriority) .ToArray(); } private bool HasDependency(IFeatureInfo f1, IFeatureInfo f2) { return _extensionDependencyStrategies.Any(s => s.HasDependency(f1, f2)); } private int GetPriority(IFeatureInfo feature) { return _extensionPriorityStrategies.Sum(s => s.GetPriority(feature)); } } }
namespace Versioning { using System; using System.Reflection; public class InvoicePost : Sage_Container { SageDataObject110.InvoicePost ip11; SageDataObject120.InvoicePost ip12; SageDataObject130.InvoicePost ip13; SageDataObject140.InvoicePost ip14; SageDataObject150.InvoicePost ip15; SageDataObject160.InvoicePost ip16; SageDataObject170.InvoicePost ip17; public InvoicePost(object a, int version) : base(version) { switch (m_version) { case 11: ip11 = (SageDataObject110.InvoicePost)a; break; case 12: ip12 = (SageDataObject120.InvoicePost)a; break; case 13: ip13 = (SageDataObject130.InvoicePost)a; break; case 14: ip14 = (SageDataObject140.InvoicePost)a; break; case 15: ip15 = (SageDataObject150.InvoicePost)a; break; case 16: ip16 = (SageDataObject160.InvoicePost)a; break; case 17: ip17 = (SageDataObject170.InvoicePost)a; break; } } public bool Update() { switch (m_version) { case 11: return ip11.Update(); case 12: return ip12.Update(); case 13: return ip13.Update(); case 14: return ip14.Update(); case 15: return ip15.Update(); case 16: return ip16.Update(); case 17: return ip17.Update(); } return false; } public Fields HDGet() { switch (m_version) { case 11: { Object temp = ip11.Header.GetType().InvokeMember("Fields", BindingFlags.GetProperty, null, ip11.Header, new Object[0]); return new Fields(temp, m_version); } case 12: { Object temp = ip12.Header.GetType().InvokeMember("Fields", BindingFlags.GetProperty, null, ip12.Header, new Object[0]); return new Fields(temp, m_version); } case 13: { Object temp = ip13.Header.GetType().InvokeMember("Fields", BindingFlags.GetProperty, null, ip13.Header, new Object[0]); return new Fields(temp, m_version); } case 14: { Object temp = ip14.Header.GetType().InvokeMember("Fields", BindingFlags.GetProperty, null, ip14.Header, new Object[0]); return new Fields(temp, m_version); } case 15: { Object temp = ip15.Header.GetType().InvokeMember("Fields", BindingFlags.GetProperty, null, ip15.Header, new Object[0]); return new Fields(temp, m_version); } case 16: { Object temp = ip16.Header.GetType().InvokeMember("Fields", BindingFlags.GetProperty, null, ip16.Header, new Object[0]); return new Fields(temp, m_version); } case 17: { Object temp = ip17.Header.GetType().InvokeMember("Fields", BindingFlags.GetProperty, null, ip17.Header, new Object[0]); return new Fields(temp, m_version); } } throw new InvalidOperationException(); } public InvoiceItem AddItem() { switch (m_version) { case 11: { Object temp = ip11.Items.GetType().InvokeMember("Add", BindingFlags.InvokeMethod, null, ip11.Items, new Object[0]); return new InvoiceItem(temp, m_version); } case 12: { Object temp = ip12.Items.GetType().InvokeMember("Add", BindingFlags.InvokeMethod, null, ip12.Items, new Object[0]); return new InvoiceItem(temp, m_version); } case 13: { Object temp = ip13.Items.GetType().InvokeMember("Add", BindingFlags.InvokeMethod, null, ip13.Items, new Object[0]); return new InvoiceItem(temp, m_version); } case 14: { Object temp = ip14.Items.GetType().InvokeMember("Add", BindingFlags.InvokeMethod, null, ip14.Items, new Object[0]); return new InvoiceItem(temp, m_version); } case 15: { Object temp = ip15.Items.GetType().InvokeMember("Add", BindingFlags.InvokeMethod, null, ip15.Items, new Object[0]); return new InvoiceItem(temp, m_version); } case 16: { Object temp = ip16.Items.GetType().InvokeMember("Add", BindingFlags.InvokeMethod, null, ip16.Items, new Object[0]); return new InvoiceItem(temp, m_version); } case 17: { Object temp = ip17.Items.GetType().InvokeMember("Add", BindingFlags.InvokeMethod, null, ip17.Items, new Object[0]); return new InvoiceItem(temp, m_version); } } return null; } public LedgerType Type { get { switch (m_version) { case 11: return (LedgerType)ip11.Type; case 12: return (LedgerType)ip12.Type; case 13: return (LedgerType)ip13.Type; case 14: return (LedgerType)ip14.Type; case 15: return (LedgerType)ip15.Type; case 16: return (LedgerType)ip16.Type; case 17: return (LedgerType)ip17.Type; } throw new InvalidOperationException(); } set { switch (m_version) { case 11: ip11.Type = (SageDataObject110.InvoiceType)value; break; case 12: ip12.Type = (SageDataObject120.InvoiceType)value; break; case 13: ip13.Type = (SageDataObject130.InvoiceType)value; break; case 14: ip14.Type = (SageDataObject140.InvoiceType)value; break; case 15: ip15.Type = (SageDataObject150.InvoiceType)value; break; case 16: ip16.Type = (SageDataObject160.InvoiceType)value; break; case 17: ip17.Type = (SageDataObject170.InvoiceType)value; break; } } } public int GetNextNumber { get { switch (m_version) { case 11: return ip11.GetNextNumber(); case 12: return ip12.GetNextNumber(); case 13: return ip13.GetNextNumber(); case 14: return ip14.GetNextNumber(); case 15: return ip15.GetNextNumber(); case 16: return ip16.GetNextNumber(); case 17: return ip17.GetNextNumber(); } return -1; } } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the kms-2014-11-01.normal.json service model. */ using System; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.KeyManagementService.Model; using Amazon.KeyManagementService.Model.Internal.MarshallTransformations; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.KeyManagementService { /// <summary> /// Implementation for accessing KeyManagementService /// /// AWS Key Management Service /// <para> /// AWS Key Management Service (KMS) is an encryption and key management web service. /// This guide describes the KMS actions that you can call programmatically. For general /// information about KMS, see (need an address here). For the KMS developer guide, see /// (need address here). /// </para> /// <note> AWS provides SDKs that consist of libraries and sample code for various programming /// languages and platforms (Java, Ruby, .Net, iOS, Android, etc.). The SDKs provide a /// convenient way to create programmatic access to KMS and AWS. For example, the SDKs /// take care of tasks such as signing requests (see below), managing errors, and retrying /// requests automatically. For more information about the AWS SDKs, including how to /// download and install them, see <a href="http://aws.amazon.com/tools/">Tools for Amazon /// Web Services</a>. </note> /// <para> /// We recommend that you use the AWS SDKs to make programmatic API calls to KMS. However, /// you can also use the KMS Query API to make to make direct calls to the KMS web service. /// /// </para> /// /// <para> /// <b>Signing Requests</b> /// </para> /// /// <para> /// Requests must be signed by using an access key ID and a secret access key. We strongly /// recommend that you do not use your AWS account access key ID and secret key for everyday /// work with KMS. Instead, use the access key ID and secret access key for an IAM user, /// or you can use the AWS Security Token Service to generate temporary security credentials /// that you can use to sign requests. /// </para> /// /// <para> /// All KMS operations require <a href="http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature /// Version 4</a>. /// </para> /// /// <para> /// <b>Recording API Requests</b> /// </para> /// /// <para> /// KMS supports AWS CloudTrail, a service that records AWS API calls and related events /// for your AWS account and delivers them to an Amazon S3 bucket that you specify. By /// using the information collected by CloudTrail, you can determine what requests were /// made to KMS, who made the request, when it was made, and so on. To learn more about /// CloudTrail, including how to turn it on and find your log files, see the <a href="http://docs.aws.amazon.com/awscloudtrail/latest/userguide/whatiscloudtrail.html">AWS /// CloudTrail User Guide</a> /// </para> /// /// <para> /// <b>Additional Resources</b> /// </para> /// /// <para> /// For more information about credentials and request signing, see the following: /// </para> /// <ul> <li> <a href="http://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html">AWS /// Security Credentials</a>. This topic provides general information about the types /// of credentials used for accessing AWS. </li> <li> <a href="http://docs.aws.amazon.com/STS/latest/UsingSTS/">AWS /// Security Token Service</a>. This guide describes how to create and use temporary security /// credentials. </li> <li> <a href="http://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html">Signing /// AWS API Requests</a>. This set of topics walks you through the process of signing /// a request using an access key ID and a secret access key. </li> </ul> /// </summary> public partial class AmazonKeyManagementServiceClient : AmazonServiceClient, IAmazonKeyManagementService { #region Constructors /// <summary> /// Constructs AmazonKeyManagementServiceClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonKeyManagementServiceClient(AWSCredentials credentials) : this(credentials, new AmazonKeyManagementServiceConfig()) { } /// <summary> /// Constructs AmazonKeyManagementServiceClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonKeyManagementServiceClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonKeyManagementServiceConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonKeyManagementServiceClient with AWS Credentials and an /// AmazonKeyManagementServiceClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonKeyManagementServiceClient Configuration Object</param> public AmazonKeyManagementServiceClient(AWSCredentials credentials, AmazonKeyManagementServiceConfig clientConfig) : base(credentials, clientConfig) { } /// <summary> /// Constructs AmazonKeyManagementServiceClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> public AmazonKeyManagementServiceClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonKeyManagementServiceConfig()) { } /// <summary> /// Constructs AmazonKeyManagementServiceClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="region">The region to connect.</param> public AmazonKeyManagementServiceClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonKeyManagementServiceConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonKeyManagementServiceClient with AWS Access Key ID, AWS Secret Key and an /// AmazonKeyManagementServiceClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonKeyManagementServiceClient Configuration Object</param> public AmazonKeyManagementServiceClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonKeyManagementServiceConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig) { } /// <summary> /// Constructs AmazonKeyManagementServiceClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> public AmazonKeyManagementServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonKeyManagementServiceConfig()) { } /// <summary> /// Constructs AmazonKeyManagementServiceClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="region">The region to connect.</param> public AmazonKeyManagementServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonKeyManagementServiceConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonKeyManagementServiceClient with AWS Access Key ID, AWS Secret Key and an /// AmazonKeyManagementServiceClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="clientConfig">The AmazonKeyManagementServiceClient Configuration Object</param> public AmazonKeyManagementServiceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonKeyManagementServiceConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig) { } #endregion #region Overrides protected override AbstractAWSSigner CreateSigner() { return new AWS4Signer(); } #endregion #region Dispose protected override void Dispose(bool disposing) { base.Dispose(disposing); } #endregion #region CreateAlias internal CreateAliasResponse CreateAlias(CreateAliasRequest request) { var marshaller = new CreateAliasRequestMarshaller(); var unmarshaller = CreateAliasResponseUnmarshaller.Instance; return Invoke<CreateAliasRequest,CreateAliasResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateAlias operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateAlias operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<CreateAliasResponse> CreateAliasAsync(CreateAliasRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateAliasRequestMarshaller(); var unmarshaller = CreateAliasResponseUnmarshaller.Instance; return InvokeAsync<CreateAliasRequest,CreateAliasResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateGrant internal CreateGrantResponse CreateGrant(CreateGrantRequest request) { var marshaller = new CreateGrantRequestMarshaller(); var unmarshaller = CreateGrantResponseUnmarshaller.Instance; return Invoke<CreateGrantRequest,CreateGrantResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateGrant operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateGrant operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<CreateGrantResponse> CreateGrantAsync(CreateGrantRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateGrantRequestMarshaller(); var unmarshaller = CreateGrantResponseUnmarshaller.Instance; return InvokeAsync<CreateGrantRequest,CreateGrantResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateKey internal CreateKeyResponse CreateKey(CreateKeyRequest request) { var marshaller = new CreateKeyRequestMarshaller(); var unmarshaller = CreateKeyResponseUnmarshaller.Instance; return Invoke<CreateKeyRequest,CreateKeyResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateKey operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateKey operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<CreateKeyResponse> CreateKeyAsync(CreateKeyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateKeyRequestMarshaller(); var unmarshaller = CreateKeyResponseUnmarshaller.Instance; return InvokeAsync<CreateKeyRequest,CreateKeyResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region Decrypt internal DecryptResponse Decrypt(DecryptRequest request) { var marshaller = new DecryptRequestMarshaller(); var unmarshaller = DecryptResponseUnmarshaller.Instance; return Invoke<DecryptRequest,DecryptResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the Decrypt operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the Decrypt operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DecryptResponse> DecryptAsync(DecryptRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DecryptRequestMarshaller(); var unmarshaller = DecryptResponseUnmarshaller.Instance; return InvokeAsync<DecryptRequest,DecryptResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteAlias internal DeleteAliasResponse DeleteAlias(DeleteAliasRequest request) { var marshaller = new DeleteAliasRequestMarshaller(); var unmarshaller = DeleteAliasResponseUnmarshaller.Instance; return Invoke<DeleteAliasRequest,DeleteAliasResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteAlias operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteAlias operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DeleteAliasResponse> DeleteAliasAsync(DeleteAliasRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteAliasRequestMarshaller(); var unmarshaller = DeleteAliasResponseUnmarshaller.Instance; return InvokeAsync<DeleteAliasRequest,DeleteAliasResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeKey internal DescribeKeyResponse DescribeKey(DescribeKeyRequest request) { var marshaller = new DescribeKeyRequestMarshaller(); var unmarshaller = DescribeKeyResponseUnmarshaller.Instance; return Invoke<DescribeKeyRequest,DescribeKeyResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeKey operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeKey operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeKeyResponse> DescribeKeyAsync(DescribeKeyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeKeyRequestMarshaller(); var unmarshaller = DescribeKeyResponseUnmarshaller.Instance; return InvokeAsync<DescribeKeyRequest,DescribeKeyResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DisableKey internal DisableKeyResponse DisableKey(DisableKeyRequest request) { var marshaller = new DisableKeyRequestMarshaller(); var unmarshaller = DisableKeyResponseUnmarshaller.Instance; return Invoke<DisableKeyRequest,DisableKeyResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DisableKey operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DisableKey operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DisableKeyResponse> DisableKeyAsync(DisableKeyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DisableKeyRequestMarshaller(); var unmarshaller = DisableKeyResponseUnmarshaller.Instance; return InvokeAsync<DisableKeyRequest,DisableKeyResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DisableKeyRotation internal DisableKeyRotationResponse DisableKeyRotation(DisableKeyRotationRequest request) { var marshaller = new DisableKeyRotationRequestMarshaller(); var unmarshaller = DisableKeyRotationResponseUnmarshaller.Instance; return Invoke<DisableKeyRotationRequest,DisableKeyRotationResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DisableKeyRotation operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DisableKeyRotation operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DisableKeyRotationResponse> DisableKeyRotationAsync(DisableKeyRotationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DisableKeyRotationRequestMarshaller(); var unmarshaller = DisableKeyRotationResponseUnmarshaller.Instance; return InvokeAsync<DisableKeyRotationRequest,DisableKeyRotationResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region EnableKey internal EnableKeyResponse EnableKey(EnableKeyRequest request) { var marshaller = new EnableKeyRequestMarshaller(); var unmarshaller = EnableKeyResponseUnmarshaller.Instance; return Invoke<EnableKeyRequest,EnableKeyResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the EnableKey operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the EnableKey operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<EnableKeyResponse> EnableKeyAsync(EnableKeyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new EnableKeyRequestMarshaller(); var unmarshaller = EnableKeyResponseUnmarshaller.Instance; return InvokeAsync<EnableKeyRequest,EnableKeyResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region EnableKeyRotation internal EnableKeyRotationResponse EnableKeyRotation(EnableKeyRotationRequest request) { var marshaller = new EnableKeyRotationRequestMarshaller(); var unmarshaller = EnableKeyRotationResponseUnmarshaller.Instance; return Invoke<EnableKeyRotationRequest,EnableKeyRotationResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the EnableKeyRotation operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the EnableKeyRotation operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<EnableKeyRotationResponse> EnableKeyRotationAsync(EnableKeyRotationRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new EnableKeyRotationRequestMarshaller(); var unmarshaller = EnableKeyRotationResponseUnmarshaller.Instance; return InvokeAsync<EnableKeyRotationRequest,EnableKeyRotationResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region Encrypt internal EncryptResponse Encrypt(EncryptRequest request) { var marshaller = new EncryptRequestMarshaller(); var unmarshaller = EncryptResponseUnmarshaller.Instance; return Invoke<EncryptRequest,EncryptResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the Encrypt operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the Encrypt operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<EncryptResponse> EncryptAsync(EncryptRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new EncryptRequestMarshaller(); var unmarshaller = EncryptResponseUnmarshaller.Instance; return InvokeAsync<EncryptRequest,EncryptResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GenerateDataKey internal GenerateDataKeyResponse GenerateDataKey(GenerateDataKeyRequest request) { var marshaller = new GenerateDataKeyRequestMarshaller(); var unmarshaller = GenerateDataKeyResponseUnmarshaller.Instance; return Invoke<GenerateDataKeyRequest,GenerateDataKeyResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GenerateDataKey operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GenerateDataKey operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<GenerateDataKeyResponse> GenerateDataKeyAsync(GenerateDataKeyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GenerateDataKeyRequestMarshaller(); var unmarshaller = GenerateDataKeyResponseUnmarshaller.Instance; return InvokeAsync<GenerateDataKeyRequest,GenerateDataKeyResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GenerateDataKeyWithoutPlaintext internal GenerateDataKeyWithoutPlaintextResponse GenerateDataKeyWithoutPlaintext(GenerateDataKeyWithoutPlaintextRequest request) { var marshaller = new GenerateDataKeyWithoutPlaintextRequestMarshaller(); var unmarshaller = GenerateDataKeyWithoutPlaintextResponseUnmarshaller.Instance; return Invoke<GenerateDataKeyWithoutPlaintextRequest,GenerateDataKeyWithoutPlaintextResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GenerateDataKeyWithoutPlaintext operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GenerateDataKeyWithoutPlaintext operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<GenerateDataKeyWithoutPlaintextResponse> GenerateDataKeyWithoutPlaintextAsync(GenerateDataKeyWithoutPlaintextRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GenerateDataKeyWithoutPlaintextRequestMarshaller(); var unmarshaller = GenerateDataKeyWithoutPlaintextResponseUnmarshaller.Instance; return InvokeAsync<GenerateDataKeyWithoutPlaintextRequest,GenerateDataKeyWithoutPlaintextResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GenerateRandom internal GenerateRandomResponse GenerateRandom(GenerateRandomRequest request) { var marshaller = new GenerateRandomRequestMarshaller(); var unmarshaller = GenerateRandomResponseUnmarshaller.Instance; return Invoke<GenerateRandomRequest,GenerateRandomResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GenerateRandom operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GenerateRandom operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<GenerateRandomResponse> GenerateRandomAsync(GenerateRandomRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GenerateRandomRequestMarshaller(); var unmarshaller = GenerateRandomResponseUnmarshaller.Instance; return InvokeAsync<GenerateRandomRequest,GenerateRandomResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GetKeyPolicy internal GetKeyPolicyResponse GetKeyPolicy(GetKeyPolicyRequest request) { var marshaller = new GetKeyPolicyRequestMarshaller(); var unmarshaller = GetKeyPolicyResponseUnmarshaller.Instance; return Invoke<GetKeyPolicyRequest,GetKeyPolicyResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetKeyPolicy operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetKeyPolicy operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<GetKeyPolicyResponse> GetKeyPolicyAsync(GetKeyPolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GetKeyPolicyRequestMarshaller(); var unmarshaller = GetKeyPolicyResponseUnmarshaller.Instance; return InvokeAsync<GetKeyPolicyRequest,GetKeyPolicyResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GetKeyRotationStatus internal GetKeyRotationStatusResponse GetKeyRotationStatus(GetKeyRotationStatusRequest request) { var marshaller = new GetKeyRotationStatusRequestMarshaller(); var unmarshaller = GetKeyRotationStatusResponseUnmarshaller.Instance; return Invoke<GetKeyRotationStatusRequest,GetKeyRotationStatusResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetKeyRotationStatus operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetKeyRotationStatus operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<GetKeyRotationStatusResponse> GetKeyRotationStatusAsync(GetKeyRotationStatusRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GetKeyRotationStatusRequestMarshaller(); var unmarshaller = GetKeyRotationStatusResponseUnmarshaller.Instance; return InvokeAsync<GetKeyRotationStatusRequest,GetKeyRotationStatusResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListAliases internal ListAliasesResponse ListAliases(ListAliasesRequest request) { var marshaller = new ListAliasesRequestMarshaller(); var unmarshaller = ListAliasesResponseUnmarshaller.Instance; return Invoke<ListAliasesRequest,ListAliasesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListAliases operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListAliases operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ListAliasesResponse> ListAliasesAsync(ListAliasesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListAliasesRequestMarshaller(); var unmarshaller = ListAliasesResponseUnmarshaller.Instance; return InvokeAsync<ListAliasesRequest,ListAliasesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListGrants internal ListGrantsResponse ListGrants(ListGrantsRequest request) { var marshaller = new ListGrantsRequestMarshaller(); var unmarshaller = ListGrantsResponseUnmarshaller.Instance; return Invoke<ListGrantsRequest,ListGrantsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListGrants operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListGrants operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ListGrantsResponse> ListGrantsAsync(ListGrantsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListGrantsRequestMarshaller(); var unmarshaller = ListGrantsResponseUnmarshaller.Instance; return InvokeAsync<ListGrantsRequest,ListGrantsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListKeyPolicies internal ListKeyPoliciesResponse ListKeyPolicies(ListKeyPoliciesRequest request) { var marshaller = new ListKeyPoliciesRequestMarshaller(); var unmarshaller = ListKeyPoliciesResponseUnmarshaller.Instance; return Invoke<ListKeyPoliciesRequest,ListKeyPoliciesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListKeyPolicies operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListKeyPolicies operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ListKeyPoliciesResponse> ListKeyPoliciesAsync(ListKeyPoliciesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListKeyPoliciesRequestMarshaller(); var unmarshaller = ListKeyPoliciesResponseUnmarshaller.Instance; return InvokeAsync<ListKeyPoliciesRequest,ListKeyPoliciesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListKeys internal ListKeysResponse ListKeys(ListKeysRequest request) { var marshaller = new ListKeysRequestMarshaller(); var unmarshaller = ListKeysResponseUnmarshaller.Instance; return Invoke<ListKeysRequest,ListKeysResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListKeys operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListKeys operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ListKeysResponse> ListKeysAsync(ListKeysRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListKeysRequestMarshaller(); var unmarshaller = ListKeysResponseUnmarshaller.Instance; return InvokeAsync<ListKeysRequest,ListKeysResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region PutKeyPolicy internal PutKeyPolicyResponse PutKeyPolicy(PutKeyPolicyRequest request) { var marshaller = new PutKeyPolicyRequestMarshaller(); var unmarshaller = PutKeyPolicyResponseUnmarshaller.Instance; return Invoke<PutKeyPolicyRequest,PutKeyPolicyResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the PutKeyPolicy operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutKeyPolicy operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<PutKeyPolicyResponse> PutKeyPolicyAsync(PutKeyPolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new PutKeyPolicyRequestMarshaller(); var unmarshaller = PutKeyPolicyResponseUnmarshaller.Instance; return InvokeAsync<PutKeyPolicyRequest,PutKeyPolicyResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ReEncrypt internal ReEncryptResponse ReEncrypt(ReEncryptRequest request) { var marshaller = new ReEncryptRequestMarshaller(); var unmarshaller = ReEncryptResponseUnmarshaller.Instance; return Invoke<ReEncryptRequest,ReEncryptResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ReEncrypt operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ReEncrypt operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ReEncryptResponse> ReEncryptAsync(ReEncryptRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ReEncryptRequestMarshaller(); var unmarshaller = ReEncryptResponseUnmarshaller.Instance; return InvokeAsync<ReEncryptRequest,ReEncryptResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region RetireGrant internal RetireGrantResponse RetireGrant(RetireGrantRequest request) { var marshaller = new RetireGrantRequestMarshaller(); var unmarshaller = RetireGrantResponseUnmarshaller.Instance; return Invoke<RetireGrantRequest,RetireGrantResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the RetireGrant operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RetireGrant operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<RetireGrantResponse> RetireGrantAsync(RetireGrantRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new RetireGrantRequestMarshaller(); var unmarshaller = RetireGrantResponseUnmarshaller.Instance; return InvokeAsync<RetireGrantRequest,RetireGrantResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region RevokeGrant internal RevokeGrantResponse RevokeGrant(RevokeGrantRequest request) { var marshaller = new RevokeGrantRequestMarshaller(); var unmarshaller = RevokeGrantResponseUnmarshaller.Instance; return Invoke<RevokeGrantRequest,RevokeGrantResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the RevokeGrant operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RevokeGrant operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<RevokeGrantResponse> RevokeGrantAsync(RevokeGrantRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new RevokeGrantRequestMarshaller(); var unmarshaller = RevokeGrantResponseUnmarshaller.Instance; return InvokeAsync<RevokeGrantRequest,RevokeGrantResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UpdateKeyDescription internal UpdateKeyDescriptionResponse UpdateKeyDescription(UpdateKeyDescriptionRequest request) { var marshaller = new UpdateKeyDescriptionRequestMarshaller(); var unmarshaller = UpdateKeyDescriptionResponseUnmarshaller.Instance; return Invoke<UpdateKeyDescriptionRequest,UpdateKeyDescriptionResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UpdateKeyDescription operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateKeyDescription operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<UpdateKeyDescriptionResponse> UpdateKeyDescriptionAsync(UpdateKeyDescriptionRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new UpdateKeyDescriptionRequestMarshaller(); var unmarshaller = UpdateKeyDescriptionResponseUnmarshaller.Instance; return InvokeAsync<UpdateKeyDescriptionRequest,UpdateKeyDescriptionResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion } }