context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; namespace LitJson { internal struct PropertyMetadata { public MemberInfo Info; public bool IsField; public Type Type; } internal struct ArrayMetadata { private Type element_type; private bool is_array; private bool is_list; public Type ElementType { get { if (element_type == null) return typeof (JsonData); return element_type; } set { element_type = value; } } public bool IsArray { get { return is_array; } set { is_array = value; } } public bool IsList { get { return is_list; } set { is_list = value; } } } internal struct ObjectMetadata { private Type element_type; private bool is_dictionary; private IDictionary<string, PropertyMetadata> properties; public Type ElementType { get { if (element_type == null) return typeof (JsonData); return element_type; } set { element_type = value; } } public bool IsDictionary { get { return is_dictionary; } set { is_dictionary = value; } } public IDictionary<string, PropertyMetadata> Properties { get { return properties; } set { properties = value; } } } internal delegate void ExporterFunc (object obj, JsonWriter writer); public delegate void ExporterFunc<T> (T obj, JsonWriter writer); internal delegate object ImporterFunc (object input); public delegate TValue ImporterFunc<TJson, TValue> (TJson input); public delegate IJsonWrapper WrapperFactory (); public class JsonMapper { #region Fields private static readonly int max_nesting_depth; private static readonly IFormatProvider datetime_format; private static readonly IDictionary<Type, ExporterFunc> base_exporters_table; private static readonly IDictionary<Type, ExporterFunc> custom_exporters_table; private static readonly IDictionary<Type, IDictionary<Type, ImporterFunc>> base_importers_table; private static readonly IDictionary<Type, IDictionary<Type, ImporterFunc>> custom_importers_table; private static readonly IDictionary<Type, ArrayMetadata> array_metadata; private static readonly object array_metadata_lock = new Object (); private static readonly IDictionary<Type, IDictionary<Type, MethodInfo>> conv_ops; private static readonly object conv_ops_lock = new Object (); private static readonly IDictionary<Type, ObjectMetadata> object_metadata; private static readonly object object_metadata_lock = new Object (); private static readonly IDictionary<Type, IList<PropertyMetadata>> type_properties; private static readonly object type_properties_lock = new Object (); private static readonly JsonWriter static_writer; private static readonly object static_writer_lock = new Object (); #endregion #region Constructors static JsonMapper () { max_nesting_depth = 100; array_metadata = new Dictionary<Type, ArrayMetadata> (); conv_ops = new Dictionary<Type, IDictionary<Type, MethodInfo>> (); object_metadata = new Dictionary<Type, ObjectMetadata> (); type_properties = new Dictionary<Type, IList<PropertyMetadata>> (); static_writer = new JsonWriter (); datetime_format = DateTimeFormatInfo.InvariantInfo; base_exporters_table = new Dictionary<Type, ExporterFunc> (); custom_exporters_table = new Dictionary<Type, ExporterFunc> (); base_importers_table = new Dictionary<Type, IDictionary<Type, ImporterFunc>> (); custom_importers_table = new Dictionary<Type, IDictionary<Type, ImporterFunc>> (); RegisterBaseExporters (); RegisterBaseImporters (); } #endregion #region Private Methods private static void AddArrayMetadata (Type type) { if (array_metadata.ContainsKey (type)) return; ArrayMetadata data = new ArrayMetadata (); data.IsArray = type.IsArray; if (type.GetInterface ("System.Collections.IList") != null) data.IsList = true; foreach (PropertyInfo p_info in type.GetProperties ()) { if (p_info.Name != "Item") continue; ParameterInfo[] parameters = p_info.GetIndexParameters (); if (parameters.Length != 1) continue; if (parameters[0].ParameterType == typeof (int)) data.ElementType = p_info.PropertyType; } lock (array_metadata_lock) { try { array_metadata.Add (type, data); } catch (ArgumentException) { return; } } } private static void AddObjectMetadata (Type type) { if (object_metadata.ContainsKey (type)) return; ObjectMetadata data = new ObjectMetadata (); if (type.GetInterface ("System.Collections.IDictionary") != null) data.IsDictionary = true; data.Properties = new Dictionary<string, PropertyMetadata> (); foreach (PropertyInfo p_info in type.GetProperties ()) { if (p_info.Name == "Item") { ParameterInfo[] parameters = p_info.GetIndexParameters (); if (parameters.Length != 1) continue; if (parameters[0].ParameterType == typeof (string)) data.ElementType = p_info.PropertyType; continue; } PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = p_info; p_data.Type = p_info.PropertyType; data.Properties.Add (p_info.Name, p_data); } foreach (FieldInfo f_info in type.GetFields ()) { PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = f_info; p_data.IsField = true; p_data.Type = f_info.FieldType; data.Properties.Add (f_info.Name, p_data); } lock (object_metadata_lock) { try { object_metadata.Add (type, data); } catch (ArgumentException) { return; } } } private static void AddTypeProperties (Type type) { if (type_properties.ContainsKey (type)) return; IList<PropertyMetadata> props = new List<PropertyMetadata> (); foreach (PropertyInfo p_info in type.GetProperties ()) { if (p_info.Name == "Item") continue; PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = p_info; p_data.IsField = false; props.Add (p_data); } foreach (FieldInfo f_info in type.GetFields ()) { PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = f_info; p_data.IsField = true; props.Add (p_data); } lock (type_properties_lock) { try { type_properties.Add (type, props); } catch (ArgumentException) { return; } } } private static MethodInfo GetConvOp (Type t1, Type t2) { lock (conv_ops_lock) { if (! conv_ops.ContainsKey (t1)) conv_ops.Add (t1, new Dictionary<Type, MethodInfo> ()); } if (conv_ops[t1].ContainsKey (t2)) return conv_ops[t1][t2]; MethodInfo op = t1.GetMethod ( "op_Implicit", new Type[] { t2 }); lock (conv_ops_lock) { try { conv_ops[t1].Add (t2, op); } catch (ArgumentException) { return conv_ops[t1][t2]; } } return op; } private static object ReadValue (Type inst_type, JsonReader reader) { reader.Read (); if (reader.Token == JsonToken.ArrayEnd) return null; Type underlying_type = Nullable.GetUnderlyingType(inst_type); Type value_type = underlying_type ?? inst_type; if (reader.Token == JsonToken.Null) { #if NETSTANDARD1_5 if (inst_type.IsClass() || underlying_type != null) { return null; } #else if (inst_type.IsClass || underlying_type != null) { return null; } #endif throw new JsonException (String.Format ( "Can't assign null to an instance of type {0}", inst_type)); } if (reader.Token == JsonToken.Double || reader.Token == JsonToken.Int || reader.Token == JsonToken.Long || reader.Token == JsonToken.String || reader.Token == JsonToken.Boolean) { Type json_type = reader.Value.GetType (); if (value_type.IsAssignableFrom (json_type)) return reader.Value; // If there's a custom importer that fits, use it if (custom_importers_table.ContainsKey (json_type) && custom_importers_table[json_type].ContainsKey ( value_type)) { ImporterFunc importer = custom_importers_table[json_type][value_type]; return importer (reader.Value); } // Maybe there's a base importer that works if (base_importers_table.ContainsKey (json_type) && base_importers_table[json_type].ContainsKey ( value_type)) { ImporterFunc importer = base_importers_table[json_type][value_type]; return importer (reader.Value); } // Maybe it's an enum #if NETSTANDARD1_5 if (value_type.IsEnum()) return Enum.ToObject (value_type, reader.Value); #else if (value_type.IsEnum) return Enum.ToObject (value_type, reader.Value); #endif // Try using an implicit conversion operator MethodInfo conv_op = GetConvOp (value_type, json_type); if (conv_op != null) return conv_op.Invoke (null, new object[] { reader.Value }); // No luck throw new JsonException (String.Format ( "Can't assign value '{0}' (type {1}) to type {2}", reader.Value, json_type, inst_type)); } object instance = null; if (reader.Token == JsonToken.ArrayStart) { AddArrayMetadata (inst_type); ArrayMetadata t_data = array_metadata[inst_type]; if (! t_data.IsArray && ! t_data.IsList) throw new JsonException (String.Format ( "Type {0} can't act as an array", inst_type)); IList list; Type elem_type; if (! t_data.IsArray) { list = (IList) Activator.CreateInstance (inst_type); elem_type = t_data.ElementType; } else { list = new ArrayList (); elem_type = inst_type.GetElementType (); } while (true) { object item = ReadValue (elem_type, reader); if (item == null && reader.Token == JsonToken.ArrayEnd) break; list.Add (item); } if (t_data.IsArray) { int n = list.Count; instance = Array.CreateInstance (elem_type, n); for (int i = 0; i < n; i++) ((Array) instance).SetValue (list[i], i); } else instance = list; } else if (reader.Token == JsonToken.ObjectStart) { AddObjectMetadata (value_type); ObjectMetadata t_data = object_metadata[value_type]; instance = Activator.CreateInstance (value_type); while (true) { reader.Read (); if (reader.Token == JsonToken.ObjectEnd) break; string property = (string) reader.Value; if (t_data.Properties.ContainsKey (property)) { PropertyMetadata prop_data = t_data.Properties[property]; if (prop_data.IsField) { ((FieldInfo) prop_data.Info).SetValue ( instance, ReadValue (prop_data.Type, reader)); } else { PropertyInfo p_info = (PropertyInfo) prop_data.Info; if (p_info.CanWrite) p_info.SetValue ( instance, ReadValue (prop_data.Type, reader), null); else ReadValue (prop_data.Type, reader); } } else { if (! t_data.IsDictionary) { if (! reader.SkipNonMembers) { throw new JsonException (String.Format ( "The type {0} doesn't have the " + "property '{1}'", inst_type, property)); } else { ReadSkip (reader); continue; } } ((IDictionary) instance).Add ( property, ReadValue ( t_data.ElementType, reader)); } } } return instance; } private static IJsonWrapper ReadValue (WrapperFactory factory, JsonReader reader) { reader.Read (); if (reader.Token == JsonToken.ArrayEnd || reader.Token == JsonToken.Null) return null; IJsonWrapper instance = factory (); if (reader.Token == JsonToken.String) { instance.SetString ((string) reader.Value); return instance; } if (reader.Token == JsonToken.Double) { instance.SetDouble ((double) reader.Value); return instance; } if (reader.Token == JsonToken.Int) { instance.SetInt ((int) reader.Value); return instance; } if (reader.Token == JsonToken.Long) { instance.SetLong ((long) reader.Value); return instance; } if (reader.Token == JsonToken.Boolean) { instance.SetBoolean ((bool) reader.Value); return instance; } if (reader.Token == JsonToken.ArrayStart) { instance.SetJsonType (JsonType.Array); while (true) { IJsonWrapper item = ReadValue (factory, reader); if (item == null && reader.Token == JsonToken.ArrayEnd) break; ((IList) instance).Add (item); } } else if (reader.Token == JsonToken.ObjectStart) { instance.SetJsonType (JsonType.Object); while (true) { reader.Read (); if (reader.Token == JsonToken.ObjectEnd) break; string property = (string) reader.Value; ((IDictionary) instance)[property] = ReadValue ( factory, reader); } } return instance; } private static void ReadSkip (JsonReader reader) { ToWrapper ( delegate { return new JsonMockWrapper (); }, reader); } private static void RegisterBaseExporters () { base_exporters_table[typeof (byte)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((byte) obj)); }; base_exporters_table[typeof (char)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToString ((char) obj)); }; base_exporters_table[typeof (DateTime)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToString ((DateTime) obj, datetime_format)); }; base_exporters_table[typeof (decimal)] = delegate (object obj, JsonWriter writer) { writer.Write ((decimal) obj); }; base_exporters_table[typeof (sbyte)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((sbyte) obj)); }; base_exporters_table[typeof (short)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((short) obj)); }; base_exporters_table[typeof (ushort)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((ushort) obj)); }; base_exporters_table[typeof (uint)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToUInt64 ((uint) obj)); }; base_exporters_table[typeof (ulong)] = delegate (object obj, JsonWriter writer) { writer.Write ((ulong) obj); }; } private static void RegisterBaseImporters () { ImporterFunc importer; importer = delegate (object input) { return Convert.ToByte ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (byte), importer); importer = delegate (object input) { return Convert.ToUInt64 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (ulong), importer); importer = delegate (object input) { return Convert.ToSByte ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (sbyte), importer); importer = delegate (object input) { return Convert.ToInt16 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (short), importer); importer = delegate (object input) { return Convert.ToUInt16 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (ushort), importer); importer = delegate (object input) { return Convert.ToUInt32 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (uint), importer); importer = delegate (object input) { return Convert.ToSingle ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (float), importer); importer = delegate (object input) { return Convert.ToDouble ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (double), importer); importer = delegate (object input) { return Convert.ToDecimal ((double) input); }; RegisterImporter (base_importers_table, typeof (double), typeof (decimal), importer); importer = delegate (object input) { return Convert.ToUInt32 ((long) input); }; RegisterImporter (base_importers_table, typeof (long), typeof (uint), importer); importer = delegate (object input) { return Convert.ToChar ((string) input); }; RegisterImporter (base_importers_table, typeof (string), typeof (char), importer); importer = delegate (object input) { return Convert.ToDateTime ((string) input, datetime_format); }; RegisterImporter (base_importers_table, typeof (string), typeof (DateTime), importer); } private static void RegisterImporter ( IDictionary<Type, IDictionary<Type, ImporterFunc>> table, Type json_type, Type value_type, ImporterFunc importer) { if (! table.ContainsKey (json_type)) table.Add (json_type, new Dictionary<Type, ImporterFunc> ()); table[json_type][value_type] = importer; } private static void WriteValue (object obj, JsonWriter writer, bool writer_is_private, int depth) { if (depth > max_nesting_depth) throw new JsonException ( String.Format ("Max allowed object depth reached while " + "trying to export from type {0}", obj.GetType ())); if (obj == null) { writer.Write (null); return; } if (obj is IJsonWrapper) { if (writer_is_private) writer.TextWriter.Write (((IJsonWrapper) obj).ToJson ()); else ((IJsonWrapper) obj).ToJson (writer); return; } if (obj is String) { writer.Write ((string) obj); return; } if (obj is Double) { writer.Write ((double) obj); return; } if (obj is Int32) { writer.Write ((int) obj); return; } if (obj is Boolean) { writer.Write ((bool) obj); return; } if (obj is Int64) { writer.Write ((long) obj); return; } if (obj is Array) { writer.WriteArrayStart (); foreach (object elem in (Array) obj) WriteValue (elem, writer, writer_is_private, depth + 1); writer.WriteArrayEnd (); return; } if (obj is IList) { writer.WriteArrayStart (); foreach (object elem in (IList) obj) WriteValue (elem, writer, writer_is_private, depth + 1); writer.WriteArrayEnd (); return; } if (obj is IDictionary) { writer.WriteObjectStart (); foreach (DictionaryEntry entry in (IDictionary) obj) { writer.WritePropertyName ((string) entry.Key); WriteValue (entry.Value, writer, writer_is_private, depth + 1); } writer.WriteObjectEnd (); return; } Type obj_type = obj.GetType (); // See if there's a custom exporter for the object if (custom_exporters_table.ContainsKey (obj_type)) { ExporterFunc exporter = custom_exporters_table[obj_type]; exporter (obj, writer); return; } // If not, maybe there's a base exporter if (base_exporters_table.ContainsKey (obj_type)) { ExporterFunc exporter = base_exporters_table[obj_type]; exporter (obj, writer); return; } // Last option, let's see if it's an enum if (obj is Enum) { Type e_type = Enum.GetUnderlyingType (obj_type); if (e_type == typeof (long) || e_type == typeof (uint) || e_type == typeof (ulong)) writer.Write ((ulong) obj); else writer.Write ((int) obj); return; } // Okay, so it looks like the input should be exported as an // object AddTypeProperties (obj_type); IList<PropertyMetadata> props = type_properties[obj_type]; writer.WriteObjectStart (); foreach (PropertyMetadata p_data in props) { if (p_data.IsField) { writer.WritePropertyName (p_data.Info.Name); WriteValue (((FieldInfo) p_data.Info).GetValue (obj), writer, writer_is_private, depth + 1); } else { PropertyInfo p_info = (PropertyInfo) p_data.Info; if (p_info.CanRead) { writer.WritePropertyName (p_data.Info.Name); WriteValue (p_info.GetValue (obj, null), writer, writer_is_private, depth + 1); } } } writer.WriteObjectEnd (); } #endregion public static string ToJson (object obj) { lock (static_writer_lock) { static_writer.Reset (); WriteValue (obj, static_writer, true, 0); return static_writer.ToString (); } } public static void ToJson (object obj, JsonWriter writer) { WriteValue (obj, writer, false, 0); } public static JsonData ToObject (JsonReader reader) { return (JsonData) ToWrapper ( delegate { return new JsonData (); }, reader); } public static JsonData ToObject (TextReader reader) { JsonReader json_reader = new JsonReader (reader); return (JsonData) ToWrapper ( delegate { return new JsonData (); }, json_reader); } public static JsonData ToObject (string json) { return (JsonData) ToWrapper ( delegate { return new JsonData (); }, json); } public static T ToObject<T> (JsonReader reader) { return (T) ReadValue (typeof (T), reader); } public static T ToObject<T> (TextReader reader) { JsonReader json_reader = new JsonReader (reader); return (T) ReadValue (typeof (T), json_reader); } public static T ToObject<T> (string json) { JsonReader reader = new JsonReader (json); return (T) ReadValue (typeof (T), reader); } public static object ToObject(string json, Type ConvertType ) { JsonReader reader = new JsonReader(json); return ReadValue(ConvertType, reader); } public static IJsonWrapper ToWrapper (WrapperFactory factory, JsonReader reader) { return ReadValue (factory, reader); } public static IJsonWrapper ToWrapper (WrapperFactory factory, string json) { JsonReader reader = new JsonReader (json); return ReadValue (factory, reader); } public static void RegisterExporter<T> (ExporterFunc<T> exporter) { ExporterFunc exporter_wrapper = delegate (object obj, JsonWriter writer) { exporter ((T) obj, writer); }; custom_exporters_table[typeof (T)] = exporter_wrapper; } public static void RegisterImporter<TJson, TValue> ( ImporterFunc<TJson, TValue> importer) { ImporterFunc importer_wrapper = delegate (object input) { return importer ((TJson) input); }; RegisterImporter (custom_importers_table, typeof (TJson), typeof (TValue), importer_wrapper); } public static void UnregisterExporters () { custom_exporters_table.Clear (); } public static void UnregisterImporters () { custom_importers_table.Clear (); } } }
// <copyright file="DenseVectorTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2013 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Complex; using NUnit.Framework; using System; using System.Collections.Generic; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex { #if NOSYSNUMERICS using Complex = Numerics.Complex; #else using Complex = System.Numerics.Complex; #endif /// <summary> /// Dense vector tests. /// </summary> public class DenseVectorTests : VectorTests { /// <summary> /// Creates a new instance of the Vector class. /// </summary> /// <param name="size">The size of the <strong>Vector</strong> to construct.</param> /// <returns>The new <c>Vector</c>.</returns> protected override Vector<Complex> CreateVector(int size) { return new DenseVector(size); } /// <summary> /// Creates a new instance of the Vector class. /// </summary> /// <param name="data">The array to create this vector from.</param> /// <returns>The new <c>Vector</c>.</returns> protected override Vector<Complex> CreateVector(IList<Complex> data) { var vector = new DenseVector(data.Count); for (var index = 0; index < data.Count; index++) { vector[index] = data[index]; } return vector; } /// <summary> /// Can create a dense vector form array. /// </summary> [Test] public void CanCreateDenseVectorFromArray() { var data = new Complex[Data.Length]; Array.Copy(Data, data, Data.Length); var vector = new DenseVector(data); for (var i = 0; i < data.Length; i++) { Assert.AreEqual(data[i], vector[i]); } vector[0] = new Complex(10.0, 1); Assert.AreEqual(new Complex(10.0, 1), data[0]); } /// <summary> /// Can create a dense vector from another dense vector. /// </summary> [Test] public void CanCreateDenseVectorFromAnotherDenseVector() { var vector = new DenseVector(Data); var other = DenseVector.OfVector(vector); Assert.AreNotSame(vector, other); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(vector[i], other[i]); } } /// <summary> /// Can create a dense vector from another vector. /// </summary> [Test] public void CanCreateDenseVectorFromAnotherVector() { var vector = (Vector<Complex>) new DenseVector(Data); var other = DenseVector.OfVector(vector); Assert.AreNotSame(vector, other); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(vector[i], other[i]); } } /// <summary> /// Can create a dense vector from user defined vector. /// </summary> [Test] public void CanCreateDenseVectorFromUserDefinedVector() { var vector = new UserDefinedVector(Data); var other = DenseVector.OfVector(vector); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(vector[i], other[i]); } } /// <summary> /// Can create a dense vector with constant values. /// </summary> [Test] public void CanCreateDenseVectorWithConstantValues() { var vector = DenseVector.Create(5, 5); foreach (var t in vector) { Assert.AreEqual(t, new Complex(5.0, 0)); } } /// <summary> /// Can create a dense matrix. /// </summary> [Test] public void CanCreateDenseMatrix() { var vector = new DenseVector(3); var matrix = Matrix<Complex>.Build.SameAs(vector, 2, 3); Assert.IsInstanceOf<DenseMatrix>(matrix); Assert.AreEqual(2, matrix.RowCount); Assert.AreEqual(3, matrix.ColumnCount); } /// <summary> /// Can convert a dense vector to an array. /// </summary> [Test] public void CanConvertDenseVectorToArray() { var vector = new DenseVector(Data); var array = (Complex[]) vector; Assert.IsInstanceOf(typeof (Complex[]), array); CollectionAssert.AreEqual(vector, array); } /// <summary> /// Can convert an array to a dense vector. /// </summary> [Test] public void CanConvertArrayToDenseVector() { var array = new[] {new Complex(1, 1), new Complex(2, 1), new Complex(3, 1), new Complex(4, 1)}; var vector = (DenseVector) array; Assert.IsInstanceOf(typeof (DenseVector), vector); CollectionAssert.AreEqual(array, array); } /// <summary> /// Can call unary plus operator on a vector. /// </summary> [Test] public void CanCallUnaryPlusOperatorOnDenseVector() { var vector = new DenseVector(Data); var other = +vector; for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(vector[i], other[i]); } } /// <summary> /// Can add two dense vectors using "+" operator. /// </summary> [Test] public void CanAddTwoDenseVectorsUsingOperator() { var vector = new DenseVector(Data); var other = new DenseVector(Data); var result = vector + other; CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified."); CollectionAssert.AreEqual(Data, other, "Making sure the original vector wasn't modified."); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i]*2.0, result[i]); } } /// <summary> /// Can call unary negate operator on a dense vector. /// </summary> [Test] public void CanCallUnaryNegationOperatorOnDenseVector() { var vector = new DenseVector(Data); var other = -vector; for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(-Data[i], other[i]); } } /// <summary> /// Can subtract two dense vectors using "-" operator. /// </summary> [Test] public void CanSubtractTwoDenseVectorsUsingOperator() { var vector = new DenseVector(Data); var other = new DenseVector(Data); var result = vector - other; CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified."); CollectionAssert.AreEqual(Data, other, "Making sure the original vector wasn't modified."); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Complex.Zero, result[i]); } } /// <summary> /// Can multiply a dense vector by a scalar using "*" operator. /// </summary> [Test] public void CanMultiplyDenseVectorByScalarUsingOperators() { var vector = new DenseVector(Data); vector = vector*new Complex(2.0, 1); for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i]*new Complex(2.0, 1), vector[i]); } vector = vector*1.0; for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i]*new Complex(2.0, 1), vector[i]); } vector = new DenseVector(Data); vector = new Complex(2.0, 1)*vector; for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i]*new Complex(2.0, 1), vector[i]); } vector = 1.0*vector; for (var i = 0; i < Data.Length; i++) { Assert.AreEqual(Data[i]*new Complex(2.0, 1), vector[i]); } } /// <summary> /// Can divide a dense vector by a scalar using "/" operator. /// </summary> [Test] public void CanDivideDenseVectorByComplexUsingOperators() { var vector = new DenseVector(Data); vector = vector/new Complex(2.0, 1); for (var i = 0; i < Data.Length; i++) { AssertHelpers.AlmostEqualRelative(Data[i]/new Complex(2.0, 1), vector[i], 14); } vector = vector/1.0; for (var i = 0; i < Data.Length; i++) { AssertHelpers.AlmostEqualRelative(Data[i]/new Complex(2.0, 1), vector[i], 14); } } /// <summary> /// Can calculate an outer product for a dense vector. /// </summary> [Test] public void CanCalculateOuterProductForDenseVector() { var vector1 = CreateVector(Data); var vector2 = CreateVector(Data); var m = Vector<Complex>.OuterProduct(vector1, vector2); for (var i = 0; i < vector1.Count; i++) { for (var j = 0; j < vector2.Count; j++) { Assert.AreEqual(m[i, j], vector1[i]*vector2[j]); } } } } }
using System; using System.Runtime.InteropServices; using System.Text; using UnityEngine; namespace LuaInterface { #pragma warning disable 414 public class MonoPInvokeCallbackAttribute : System.Attribute { private Type type; public MonoPInvokeCallbackAttribute(Type t) { type = t; } } #pragma warning restore 414 public enum LuaTypes : int { LUA_TNONE = -1, LUA_TNIL = 0, LUA_TBOOLEAN = 1, LUA_TLIGHTUSERDATA = 2, LUA_TNUMBER = 3, LUA_TSTRING = 4, LUA_TTABLE = 5, LUA_TFUNCTION = 6, LUA_TUSERDATA = 7, LUA_TTHREAD = 8, } public enum LuaGCOptions { LUA_GCSTOP = 0, LUA_GCRESTART = 1, LUA_GCCOLLECT = 2, LUA_GCCOUNT = 3, LUA_GCCOUNTB = 4, LUA_GCSTEP = 5, LUA_GCSETPAUSE = 6, LUA_GCSETSTEPMUL = 7, } public enum LuaThreadStatus : int { LUA_YIELD = 1, LUA_ERRRUN = 2, LUA_ERRSYNTAX = 3, LUA_ERRMEM = 4, LUA_ERRERR = 5, } public sealed class LuaIndexes { #if LUA_5_3 // for lua5.3 public static int LUA_REGISTRYINDEX = -1000000 - 1000; #else // for lua5.1 or luajit public static int LUA_REGISTRYINDEX = -10000; public static int LUA_GLOBALSINDEX = -10002; #endif } [StructLayout(LayoutKind.Sequential)] public struct ReaderInfo { public String chunkData; public bool finished; } #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int LuaCSFunction(IntPtr luaState); #else public delegate int LuaCSFunction(IntPtr luaState); #endif public delegate string LuaChunkReader(IntPtr luaState, ref ReaderInfo data, ref uint size); public delegate int LuaFunctionCallback(IntPtr luaState); public class LuaDLL { public static int LUA_MULTRET = -1; #if UNITY_IPHONE && !UNITY_EDITOR const string LUADLL = "__Internal"; #else const string LUADLL = "slua"; #endif //pdc [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] public static extern int luaopen_protobuf_c(IntPtr luaState); //lpeg [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] public static extern int luaopen_lpeg(IntPtr luaState); //cjson [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] public static extern int luaopen_cjson(IntPtr luaState); //lua socket [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] public static extern int luaopen_socket_core(IntPtr luaState); //lua socket mime [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] public static extern int luaopen_mime_core(IntPtr luaState); //sproto [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] public static extern int luaopen_sproto_core(IntPtr luaState); //sqlite [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] public static extern int luaopen_lsqlite3(IntPtr luaState); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_openextlibs(IntPtr L); // Thread Funcs [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_tothread(IntPtr L, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_xmove(IntPtr from, IntPtr to, int n); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_newthread(IntPtr L); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_status(IntPtr L); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_pushthread(IntPtr L); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_gc(IntPtr luaState, LuaGCOptions what, int data); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_typename(IntPtr luaState, int type); public static string lua_typenamestr(IntPtr luaState, LuaTypes type) { IntPtr p = lua_typename(luaState, (int)type); return Marshal.PtrToStringAnsi(p); } public static string luaL_typename(IntPtr luaState, int stackPos) { return LuaDLL.lua_typenamestr(luaState, LuaDLL.lua_type(luaState, stackPos)); } public static bool lua_isfunction(IntPtr luaState, int stackPos) { return lua_type(luaState, stackPos) == LuaTypes.LUA_TFUNCTION; } public static bool lua_islightuserdata(IntPtr luaState, int stackPos) { return lua_type(luaState, stackPos) == LuaTypes.LUA_TLIGHTUSERDATA; } public static bool lua_istable(IntPtr luaState, int stackPos) { return lua_type(luaState, stackPos) == LuaTypes.LUA_TTABLE; } public static bool lua_isthread(IntPtr luaState, int stackPos) { return lua_type(luaState, stackPos) == LuaTypes.LUA_TTHREAD; } [Obsolete] public static void luaL_error(IntPtr luaState, string message) { //LuaDLL.lua_pushstring(luaState, message); //LuaDLL.lua_error(luaState); } [Obsolete] public static void luaL_error(IntPtr luaState, string fmt, params object[] args) { //string str = string.Format(fmt, args); //luaL_error(luaState, str); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern string luaL_gsub(IntPtr luaState, string str, string pattern, string replacement); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_isuserdata(IntPtr luaState, int stackPos); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_rawequal(IntPtr luaState, int stackPos1, int stackPos2); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_setfield(IntPtr luaState, int stackPos, string name); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_callmeta(IntPtr luaState, int stackPos, string name); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr luaL_newstate(); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_close(IntPtr luaState); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaL_openlibs(IntPtr luaState); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_loadstring(IntPtr luaState, string chunk); public static int luaL_dostring(IntPtr luaState, string chunk) { int result = LuaDLL.luaL_loadstring(luaState, chunk); if (result != 0) return result; return LuaDLL.lua_pcall(luaState, 0, -1, 0); } public static int lua_dostring(IntPtr luaState, string chunk) { return LuaDLL.luaL_dostring(luaState, chunk); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_createtable(IntPtr luaState, int narr, int nrec); public static void lua_newtable(IntPtr luaState) { LuaDLL.lua_createtable(luaState, 0, 0); } #if LUA_5_3 [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_getglobal(IntPtr luaState, string name); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_setglobal(IntPtr luaState, string name); public static void lua_insert(IntPtr luaState, int newTop) { lua_rotate(luaState, newTop, 1); } public static void lua_pushglobaltable(IntPtr l) { lua_rawgeti(l, LuaIndexes.LUA_REGISTRYINDEX, 2); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_rotate(IntPtr luaState, int index, int n); public static int lua_rawlen(IntPtr luaState, int stackPos) { return LuaDLLWrapper.luaS_rawlen(luaState, stackPos); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_loadbufferx(IntPtr luaState, byte[] buff, int size, string name, IntPtr x); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_callk(IntPtr luaState, int nArgs, int nResults,int ctx,IntPtr k); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_pcallk(IntPtr luaState, int nArgs, int nResults, int errfunc,int ctx,IntPtr k); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_pcall(IntPtr luaState, int nArgs, int nResults, int errfunc); public static int lua_call(IntPtr luaState, int nArgs, int nResults) { return lua_callk(luaState, nArgs, nResults, 0, IntPtr.Zero); } public static int lua_pcall(IntPtr luaState, int nArgs, int nResults, int errfunc) { return luaS_pcall(luaState, nArgs, nResults, errfunc); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern double lua_tonumberx(IntPtr luaState, int index, IntPtr x); public static double lua_tonumber(IntPtr luaState, int index) { return lua_tonumberx(luaState, index, IntPtr.Zero); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern Int64 lua_tointegerx(IntPtr luaState, int index,IntPtr x); public static int lua_tointeger(IntPtr luaState, int index) { return (int)lua_tointegerx(luaState, index, IntPtr.Zero); } public static int luaL_loadbuffer(IntPtr luaState, byte[] buff, int size, string name) { return luaL_loadbufferx(luaState, buff, size, name, IntPtr.Zero); } public static void lua_remove(IntPtr l, int idx) { lua_rotate(l, (idx), -1); lua_pop(l, 1); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawgeti(IntPtr luaState, int tableIndex, Int64 index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawseti(IntPtr luaState, int tableIndex, Int64 index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushinteger(IntPtr luaState, Int64 i); public static Int64 luaL_checkinteger(IntPtr luaState, int stackPos) { luaL_checktype(luaState, stackPos, LuaTypes.LUA_TNUMBER); return lua_tointegerx(luaState, stackPos, IntPtr.Zero); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_yield(IntPtr luaState,int nrets); public static int lua_yield(IntPtr luaState,int nrets) { return luaS_yield(luaState,nrets); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_resume(IntPtr L, IntPtr from, int narg); public static void lua_replace(IntPtr luaState, int index) { lua_copy(luaState, -1, (index)); lua_pop(luaState, 1); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_copy(IntPtr luaState,int from,int toidx); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_isinteger(IntPtr luaState, int p); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_compare(IntPtr luaState, int index1, int index2, int op); public static int lua_equal(IntPtr luaState, int index1, int index2) { return lua_compare(luaState, index1, index2, 0); } #else [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_resume(IntPtr L, int narg); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_lessthan(IntPtr luaState, int stackPos1, int stackPos2); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_getfenv(IntPtr luaState, int stackPos); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_yield(IntPtr L, int nresults); public static void lua_getglobal(IntPtr luaState, string name) { LuaDLL.lua_pushstring(luaState, name); LuaDLL.lua_gettable(luaState, LuaIndexes.LUA_GLOBALSINDEX); } public static void lua_setglobal(IntPtr luaState, string name) { LuaDLL.lua_pushstring(luaState, name); LuaDLL.lua_insert(luaState, -2); LuaDLL.lua_settable(luaState, LuaIndexes.LUA_GLOBALSINDEX); } public static void lua_pushglobaltable(IntPtr l) { LuaDLL.lua_pushvalue(l, LuaIndexes.LUA_GLOBALSINDEX); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_insert(IntPtr luaState, int newTop); public static int lua_rawlen(IntPtr luaState, int stackPos) { return LuaDLLWrapper.luaS_objlen(luaState, stackPos); } public static int lua_strlen(IntPtr luaState, int stackPos) { return lua_rawlen(luaState, stackPos); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_call(IntPtr luaState, int nArgs, int nResults); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_pcall(IntPtr luaState, int nArgs, int nResults, int errfunc); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern double lua_tonumber(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_tointeger(IntPtr luaState, int index); public static int luaL_loadbuffer(IntPtr luaState, byte[] buff, int size, string name) { return LuaDLLWrapper.luaLS_loadbuffer(luaState, buff, size, name); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_remove(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawgeti(IntPtr luaState, int tableIndex, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawseti(IntPtr luaState, int tableIndex, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushinteger(IntPtr luaState, IntPtr i); public static void lua_pushinteger(IntPtr luaState, int i) { lua_pushinteger(luaState, (IntPtr)i); } public static int luaL_checkinteger(IntPtr luaState, int stackPos) { luaL_checktype(luaState, stackPos, LuaTypes.LUA_TNUMBER); return lua_tointeger(luaState, stackPos); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_replace(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_setfenv(IntPtr luaState, int stackPos); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_equal(IntPtr luaState, int index1, int index2); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_loadfile(IntPtr luaState, string filename); #endif [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_settop(IntPtr luaState, int newTop); public static void lua_pop(IntPtr luaState, int amount) { LuaDLL.lua_settop(luaState, -(amount) - 1); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_gettable(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawget(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_settable(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawset(IntPtr luaState, int index); #if LUA_5_3 [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_setmetatable(IntPtr luaState, int objIndex); #else [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_setmetatable(IntPtr luaState, int objIndex); #endif [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_getmetatable(IntPtr luaState, int objIndex); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushvalue(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_gettop(IntPtr luaState); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern LuaTypes lua_type(IntPtr luaState, int index); public static bool lua_isnil(IntPtr luaState, int index) { return (LuaDLL.lua_type(luaState, index) == LuaTypes.LUA_TNIL); } public static bool lua_isnumber(IntPtr luaState, int index) { return LuaDLLWrapper.lua_isnumber(luaState, index) > 0; } public static bool lua_isboolean(IntPtr luaState, int index) { return LuaDLL.lua_type(luaState, index) == LuaTypes.LUA_TBOOLEAN; } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_ref(IntPtr luaState, int registryIndex); public static void lua_getref(IntPtr luaState, int reference) { LuaDLL.lua_rawgeti(luaState, LuaIndexes.LUA_REGISTRYINDEX, reference); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaL_unref(IntPtr luaState, int registryIndex, int reference); public static void lua_unref(IntPtr luaState, int reference) { LuaDLL.luaL_unref(luaState, LuaIndexes.LUA_REGISTRYINDEX, reference); } public static bool lua_isstring(IntPtr luaState, int index) { return LuaDLLWrapper.lua_isstring(luaState, index) > 0; } public static bool lua_iscfunction(IntPtr luaState, int index) { return LuaDLLWrapper.lua_iscfunction(luaState, index) > 0; } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushnil(IntPtr luaState); public static void luaL_checktype(IntPtr luaState, int p, LuaTypes t) { LuaTypes ct = LuaDLL.lua_type (luaState, p); if (ct != t) { throw new Exception(string.Format("arg {0} expect {1}, got {2}", p, lua_typenamestr(luaState, t), lua_typenamestr(luaState, ct))); } } public static void lua_pushcfunction(IntPtr luaState, LuaCSFunction function) { IntPtr fn = Marshal.GetFunctionPointerForDelegate(function); lua_pushcclosure(luaState, fn, 0); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_tocfunction(IntPtr luaState, int index); public static bool lua_toboolean(IntPtr luaState, int index) { return LuaDLLWrapper.lua_toboolean(luaState, index) > 0; } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr luaS_tolstring32(IntPtr luaState, int index, out int strLen); public static string lua_tostring(IntPtr luaState, int index) { int strlen; IntPtr str = luaS_tolstring32(luaState, index, out strlen); // fix il2cpp 64 bit if (str != IntPtr.Zero) { return Marshal.PtrToStringAnsi(str, strlen); } return null; } public static byte[] lua_tobytes(IntPtr luaState, int index) { int strlen; IntPtr str = luaS_tolstring32(luaState, index, out strlen); // fix il2cpp 64 bit if (str != IntPtr.Zero) { byte[] res = new byte[strlen]; for( int i = 0 ; i<res.Length ; i++ ) { res[i] = Marshal.ReadByte(str,i); } return res; } return null; } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_atpanic(IntPtr luaState, LuaCSFunction panicf); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushnumber(IntPtr luaState, double number); public static void lua_pushboolean(IntPtr luaState, bool value) { LuaDLLWrapper.lua_pushboolean(luaState, value ? 1 : 0); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushstring(IntPtr luaState, string str); public static void lua_pushlstring(IntPtr luaState, byte[] str, int size) { LuaDLLWrapper.luaS_pushlstring(luaState, str, size); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_newmetatable(IntPtr luaState, string meta); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_getfield(IntPtr luaState, int stackPos, string meta); public static void luaL_getmetatable(IntPtr luaState, string meta) { LuaDLL.lua_getfield(luaState, LuaIndexes.LUA_REGISTRYINDEX, meta); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr luaL_checkudata(IntPtr luaState, int stackPos, string meta); public static bool luaL_getmetafield(IntPtr luaState, int stackPos, string field) { return LuaDLLWrapper.luaL_getmetafield(luaState, stackPos, field) > 0; } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_load(IntPtr luaState, LuaChunkReader chunkReader, ref ReaderInfo data, string chunkName); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_error(IntPtr luaState); public static bool lua_checkstack(IntPtr luaState, int extra) { return LuaDLLWrapper.lua_checkstack(luaState, extra) > 0; } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_next(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushlightuserdata(IntPtr luaState, IntPtr udata); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaL_where(IntPtr luaState, int level); public static double luaL_checknumber(IntPtr luaState, int stackPos) { luaL_checktype(luaState, stackPos, LuaTypes.LUA_TNUMBER); return lua_tonumber(luaState, stackPos); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_concat(IntPtr luaState, int n); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_newuserdata(IntPtr luaState, int val); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_rawnetobj(IntPtr luaState, int obj); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_touserdata(IntPtr luaState, int index); public static int lua_absindex(IntPtr luaState, int index) { return index > 0 ? index : lua_gettop(luaState) + index + 1; } public static int lua_upvalueindex(int i) { #if LUA_5_3 return LuaIndexes.LUA_REGISTRYINDEX - i; #else return LuaIndexes.LUA_GLOBALSINDEX - i; #endif } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushcclosure(IntPtr l, IntPtr f, int nup); public static void lua_pushcclosure(IntPtr l, LuaCSFunction f, int nup) { IntPtr fn = Marshal.GetFunctionPointerForDelegate(f); lua_pushcclosure(l, fn, nup); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_checkVector2(IntPtr l, int p, out float x, out float y); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_checkVector3(IntPtr l, int p, out float x, out float y, out float z); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_checkVector4(IntPtr l, int p, out float x, out float y, out float z, out float w); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_checkQuaternion(IntPtr l, int p, out float x, out float y, out float z, out float w); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_checkColor(IntPtr l, int p, out float x, out float y, out float z, out float w); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_pushVector2(IntPtr l, float x, float y); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_pushVector3(IntPtr l, float x, float y, float z); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_pushVector4(IntPtr l, float x, float y, float z, float w); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_pushQuaternion(IntPtr l, float x, float y, float z, float w); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_pushColor(IntPtr l, float x, float y, float z, float w); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_setDataVec(IntPtr l, int p, float x, float y, float z, float w); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_checkluatype(IntPtr l, int p, string t); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaS_pushobject(IntPtr l, int index, string t, bool gco, int cref); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_getcacheud(IntPtr l, int index, int cref); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_subclassof(IntPtr l, int index, string t); } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Web.SessionState.HttpSessionStateContainer.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Web.SessionState { public partial class HttpSessionStateContainer : IHttpSessionState { #region Methods and constructors public void Abandon() { } public void Add(string name, Object value) { } public void Clear() { } public void CopyTo(Array array, int index) { } public System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); } public HttpSessionStateContainer(string id, ISessionStateItemCollection sessionItems, System.Web.HttpStaticObjectsCollection staticObjects, int timeout, bool newSession, System.Web.HttpCookieMode cookieMode, SessionStateMode mode, bool isReadonly) { } public void Remove(string name) { } public void RemoveAll() { } public void RemoveAt(int index) { } #endregion #region Properties and indexers public int CodePage { get { return default(int); } set { } } public System.Web.HttpCookieMode CookieMode { get { return default(System.Web.HttpCookieMode); } } public int Count { get { return default(int); } } public bool IsAbandoned { get { return default(bool); } } public bool IsCookieless { get { return default(bool); } } public bool IsNewSession { get { return default(bool); } } public bool IsReadOnly { get { return default(bool); } } public bool IsSynchronized { get { return default(bool); } } public Object this [string name] { get { return default(Object); } set { } } public Object this [int index] { get { return default(Object); } set { } } public System.Collections.Specialized.NameObjectCollectionBase.KeysCollection Keys { get { return default(System.Collections.Specialized.NameObjectCollectionBase.KeysCollection); } } public int LCID { get { return default(int); } set { } } public SessionStateMode Mode { get { return default(SessionStateMode); } } public string SessionID { get { return default(string); } } public System.Web.HttpStaticObjectsCollection StaticObjects { get { return default(System.Web.HttpStaticObjectsCollection); } } public Object SyncRoot { get { return default(Object); } } public int Timeout { get { return default(int); } set { } } #endregion } }
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 ErrorHandling.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) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.IO; using System.Threading; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.CoreModules; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Interfaces; namespace OpenSim.Region.ScriptEngine.Shared { [Serializable] public class EventAbortException : Exception { public EventAbortException() { } protected EventAbortException( SerializationInfo info, StreamingContext context) { } } [Serializable] public class SelfDeleteException : Exception { public SelfDeleteException() { } protected SelfDeleteException( SerializationInfo info, StreamingContext context) { } } [Serializable] public class ScriptDeleteException : Exception { public ScriptDeleteException() { } protected ScriptDeleteException( SerializationInfo info, StreamingContext context) { } } /// <summary> /// Used to signal when the script is stopping in co-operation with the script engine /// (instead of through Thread.Abort()). /// </summary> [Serializable] public class ScriptCoopStopException : Exception { public ScriptCoopStopException() { } protected ScriptCoopStopException( SerializationInfo info, StreamingContext context) { } } public class DetectParams { public const int AGENT = 1; public const int ACTIVE = 2; public const int PASSIVE = 4; public const int SCRIPTED = 8; public const int OS_NPC = 0x01000000; public DetectParams() { Key = UUID.Zero; OffsetPos = new LSL_Types.Vector3(); LinkNum = 0; Group = UUID.Zero; Name = String.Empty; Owner = UUID.Zero; Position = new LSL_Types.Vector3(); Rotation = new LSL_Types.Quaternion(); Type = 0; Velocity = new LSL_Types.Vector3(); initializeSurfaceTouch(); } public UUID Key; public LSL_Types.Vector3 OffsetPos; public int LinkNum; public UUID Group; public string Name; public UUID Owner; public LSL_Types.Vector3 Position; public LSL_Types.Quaternion Rotation; public int Type; public LSL_Types.Vector3 Velocity; private LSL_Types.Vector3 touchST; public LSL_Types.Vector3 TouchST { get { return touchST; } } private LSL_Types.Vector3 touchNormal; public LSL_Types.Vector3 TouchNormal { get { return touchNormal; } } private LSL_Types.Vector3 touchBinormal; public LSL_Types.Vector3 TouchBinormal { get { return touchBinormal; } } private LSL_Types.Vector3 touchPos; public LSL_Types.Vector3 TouchPos { get { return touchPos; } } private LSL_Types.Vector3 touchUV; public LSL_Types.Vector3 TouchUV { get { return touchUV; } } private int touchFace; public int TouchFace { get { return touchFace; } } // This can be done in two places including the constructor // so be carefull what gets added here private void initializeSurfaceTouch() { touchST = new LSL_Types.Vector3(-1.0, -1.0, 0.0); touchNormal = new LSL_Types.Vector3(); touchBinormal = new LSL_Types.Vector3(); touchPos = new LSL_Types.Vector3(); touchUV = new LSL_Types.Vector3(-1.0, -1.0, 0.0); touchFace = -1; } /* * Set up the surface touch detected values */ public SurfaceTouchEventArgs SurfaceTouchArgs { set { if (value == null) { // Initialise to defaults if no value initializeSurfaceTouch(); } else { // Set the values from the touch data provided by the client touchST = new LSL_Types.Vector3(value.STCoord); touchUV = new LSL_Types.Vector3(value.UVCoord); touchNormal = new LSL_Types.Vector3(value.Normal); touchBinormal = new LSL_Types.Vector3(value.Binormal); touchPos = new LSL_Types.Vector3(value.Position); touchFace = value.FaceIndex; } } } public void Populate(Scene scene) { SceneObjectPart part = scene.GetSceneObjectPart(Key); if (part == null) // Avatar, maybe? { ScenePresence presence = scene.GetScenePresence(Key); if (presence == null) return; Name = presence.Firstname + " " + presence.Lastname; Owner = Key; Position = new LSL_Types.Vector3(presence.AbsolutePosition); Rotation = new LSL_Types.Quaternion( presence.Rotation.X, presence.Rotation.Y, presence.Rotation.Z, presence.Rotation.W); Velocity = new LSL_Types.Vector3(presence.Velocity); if (presence.PresenceType != PresenceType.Npc) { Type = AGENT; } else { Type = OS_NPC; INPCModule npcModule = scene.RequestModuleInterface<INPCModule>(); INPC npcData = npcModule.GetNPC(presence.UUID, presence.Scene); if (npcData.SenseAsAgent) { Type |= AGENT; } } if (presence.Velocity != Vector3.Zero) Type |= ACTIVE; Group = presence.ControllingClient.ActiveGroupId; return; } part = part.ParentGroup.RootPart; // We detect objects only LinkNum = 0; // Not relevant Group = part.GroupID; Name = part.Name; Owner = part.OwnerID; if (part.Velocity == Vector3.Zero) Type = PASSIVE; else Type = ACTIVE; foreach (SceneObjectPart p in part.ParentGroup.Parts) { if (p.Inventory.ContainsScripts()) { Type |= SCRIPTED; // Scripted break; } } Position = new LSL_Types.Vector3(part.AbsolutePosition); Quaternion wr = part.ParentGroup.GroupRotation; Rotation = new LSL_Types.Quaternion(wr.X, wr.Y, wr.Z, wr.W); Velocity = new LSL_Types.Vector3(part.Velocity); } } /// <summary> /// Holds all the data required to execute a scripting event. /// </summary> public class EventParams { public EventParams(string eventName, Object[] eventParams, DetectParams[] detectParams) { EventName = eventName; Params = eventParams; DetectParams = detectParams; } public string EventName; public Object[] Params; public DetectParams[] DetectParams; } }
/****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2017. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using UnityEditorInternal; namespace Leap.Unity { [CustomPropertyDrawer(typeof(SHashSetAttribute))] public class SerializableHashSetEditor : PropertyDrawer { private ReorderableList _list; private SerializedProperty _currProperty; private List<Value> _values = new List<Value>(); private class Value { public int index; public bool isDuplicate; public SerializedProperty value; public Value(int index, bool isDuplicate, SerializedProperty value) { this.index = index; this.isDuplicate = isDuplicate; this.value = value; } } public SerializableHashSetEditor() { _list = new ReorderableList(_values, typeof(Value), draggable: true, displayHeader: true, displayAddButton: true, displayRemoveButton: true); _list.drawElementCallback = drawElementCallback; _list.elementHeightCallback = elementHeightCallback; _list.drawHeaderCallback = drawHeader; _list.onAddCallback = onAddCallback; _list.onRemoveCallback = onRemoveCallback; _list.onReorderCallback = onReorderCallback; } public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { if (property.hasMultipleDifferentValues) { GUI.Box(position, ""); EditorGUI.LabelField(position, "Multi-object editing not supported for Serialized HashSets.", EditorStyles.miniLabel); } else { _currProperty = property; updatePairsFromProperty(property); EditorGUIUtility.labelWidth /= 2; _list.DoList(position); EditorGUIUtility.labelWidth *= 2; } } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { if (property.hasMultipleDifferentValues) { return EditorGUIUtility.singleLineHeight; } else { updatePairsFromProperty(property); return _list.GetHeight(); } } private void updatePairsFromProperty(SerializedProperty property) { SerializedProperty values = property.FindPropertyRelative("_values"); var dup = (fieldInfo.GetValue(property.serializedObject.targetObject) as ICanReportDuplicateInformation).GetDuplicationInformation(); _values.Clear(); int count = values.arraySize; for (int i = 0; i < count; i++) { SerializedProperty value = values.GetArrayElementAtIndex(i); bool isDup = false; if (i < dup.Count) { isDup = dup[i] > 1; } _values.Add(new Value(i, isDup, value)); } } private void drawHeader(Rect rect) { EditorGUI.LabelField(rect, _currProperty.displayName); rect.x += rect.width - 110; rect.width = 110; if (GUI.Button(rect, "Clear Duplicates")) { markDirty(_currProperty); Undo.RecordObject(_currProperty.serializedObject.targetObject, "Cleared duplicates"); (fieldInfo.GetValue(_currProperty.serializedObject.targetObject) as ICanReportDuplicateInformation).ClearDuplicates(); _currProperty.serializedObject.Update(); markDirty(_currProperty); updatePairsFromProperty(_currProperty); } } private void drawElementCallback(Rect rect, int index, bool isActive, bool isFocused) { Value value = _values[index]; if (value.isDuplicate) { GUI.contentColor = new Color(1, 0.7f, 0); GUI.color = new Color(1, 0.7f, 0.5f); } if (value.value.propertyType == SerializedPropertyType.ObjectReference && value.value.objectReferenceValue == null) { GUI.contentColor = new Color(1, 0, 0); GUI.color = new Color(1, 0, 0); } drawProp(value.value, rect); GUI.contentColor = Color.white; GUI.color = Color.white; GUI.backgroundColor = Color.white; } private void onAddCallback(ReorderableList list) { SerializedProperty values = _currProperty.FindPropertyRelative("_values"); values.arraySize++; updatePairsFromProperty(_currProperty); } private void onRemoveCallback(ReorderableList list) { SerializedProperty values = _currProperty.FindPropertyRelative("_values"); actuallyDeleteAt(values, list.index); updatePairsFromProperty(_currProperty); } private void onReorderCallback(ReorderableList list) { SerializedProperty values = _currProperty.FindPropertyRelative("_values"); int startIndex = -1, endIndex = -1; bool isForward = true; for (int i = 0; i < _values.Count; i++) { if (i != _values[i].index) { if (_values[i].index - i > 1) { isForward = false; } startIndex = i; break; } } for (int i = _values.Count; i-- != 0;) { if (i != _values[i].index) { endIndex = i; break; } } if (isForward) { values.MoveArrayElement(startIndex, endIndex); } else { values.MoveArrayElement(endIndex, startIndex); } updatePairsFromProperty(_currProperty); } private float elementHeightCallback(int index) { Value value = _values[index]; float size = getSize(value.value); _list.elementHeight = size; return size; } private float getSize(SerializedProperty prop) { float size = 0; if (prop.propertyType == SerializedPropertyType.Generic) { SerializedProperty copy = prop.Copy(); SerializedProperty endProp = copy.GetEndProperty(false); copy.NextVisible(true); while (!SerializedProperty.EqualContents(copy, endProp)) { size += EditorGUI.GetPropertyHeight(copy); copy.NextVisible(false); } } else { size = EditorGUI.GetPropertyHeight(prop, GUIContent.none, false); } return size; } private void drawProp(SerializedProperty prop, Rect r) { if (prop.propertyType == SerializedPropertyType.Generic) { SerializedProperty copy = prop.Copy(); SerializedProperty endProp = copy.GetEndProperty(false); copy.NextVisible(true); while (!SerializedProperty.EqualContents(copy, endProp)) { r.height = EditorGUI.GetPropertyHeight(copy); EditorGUI.PropertyField(r, copy, true); r.y += r.height; copy.NextVisible(false); } } else { r.height = EditorGUI.GetPropertyHeight(prop); EditorGUI.PropertyField(r, prop, GUIContent.none, false); } } private void markDirty(SerializedProperty property) { SerializedProperty values = property.FindPropertyRelative("_values"); int size = values.arraySize; values.InsertArrayElementAtIndex(size); actuallyDeleteAt(values, size); } private static void actuallyDeleteAt(SerializedProperty property, int index) { int arraySize = property.arraySize; while (property.arraySize == arraySize) { property.DeleteArrayElementAtIndex(index); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AonWeb.FluentHttp.Helpers; namespace AonWeb.FluentHttp.Handlers { public class HttpHandlerRegister { private delegate Task HandlerDelegate(HttpHandlerContext context); private readonly ISet<IHttpHandler> _handlerInstances; private readonly IDictionary<HandlerType, IDictionary<HandlerPriority, ICollection<HandlerDelegate>>> _handlers; public HttpHandlerRegister() { _handlerInstances = new HashSet<IHttpHandler>(); _handlers = new Dictionary<HandlerType, IDictionary<HandlerPriority, ICollection<HandlerDelegate>>>(); } public async Task OnSending(HttpSendingContext context) { foreach (var handler in GetHandlers(HandlerType.Sending)) await handler(context); } public async Task OnSent(HttpSentContext context) { foreach (var handler in GetHandlers(HandlerType.Sent)) await handler(context); } public async Task OnException(HttpExceptionContext context) { foreach (var handler in GetHandlers(HandlerType.Exception)) await handler(context); } public HttpHandlerRegister WithHandler(IHttpHandler handler) { if (handler == null) throw new ArgumentNullException(nameof(handler)); if (_handlerInstances.Contains(handler)) throw new InvalidOperationException(SR.HanderAlreadyExistsError); _handlerInstances.Add(handler); WithAsyncSendingHandler( handler.GetPriority(HandlerType.Sending), async ctx => { if (handler.Enabled) await handler.OnSending(ctx); }); WithAsyncSentHandler(handler.GetPriority(HandlerType.Sent), async ctx => { if (handler.Enabled) await handler.OnSent(ctx); }); WithAsyncExceptionHandler(handler.GetPriority(HandlerType.Exception), async ctx => { if (handler.Enabled) await handler.OnException(ctx); }); return this; } public HttpHandlerRegister WithConfiguration<THandler>(Action<THandler> configure, bool throwOnNotFound = true) where THandler : class, IHttpHandler { if (configure == null) throw new ArgumentNullException(nameof(configure)); var handler = _handlerInstances.OfType<THandler>().FirstOrDefault(); if (handler == null) { if (throwOnNotFound) throw new KeyNotFoundException(string.Format(SR.HanderDoesNotExistErrorFormat, typeof(THandler).Name)); } else { configure(handler); } return this; } #region Sending public HttpHandlerRegister WithSendingHandler(Action<HttpSendingContext> handler) { return WithSendingHandler(HandlerPriority.Default, handler); } public HttpHandlerRegister WithSendingHandler(HandlerPriority priority, Action<HttpSendingContext> handler) { if (handler == null) throw new ArgumentNullException(nameof(handler)); return WithAsyncSendingHandler(priority, handler.ToTask); } public HttpHandlerRegister WithAsyncSendingHandler(Func<HttpSendingContext, Task> handler) { return WithAsyncSendingHandler(HandlerPriority.Default, handler); } public HttpHandlerRegister WithAsyncSendingHandler(HandlerPriority priority, Func<HttpSendingContext, Task> handler) { if (handler == null) throw new ArgumentNullException(nameof(handler)); WithHandler(HandlerType.Sending, priority, context => handler((HttpSendingContext)context)); return this; } #endregion #region Sent public HttpHandlerRegister WithSentHandler(Action<HttpSentContext> handler) { return WithSentHandler(HandlerPriority.Default, handler); } public HttpHandlerRegister WithSentHandler(HandlerPriority priority, Action<HttpSentContext> handler) { if (handler == null) throw new ArgumentNullException(nameof(handler)); return WithAsyncSentHandler(priority, handler.ToTask); } public HttpHandlerRegister WithAsyncSentHandler(Func<HttpSentContext, Task> handler) { return WithAsyncSentHandler(HandlerPriority.Default, handler); } public HttpHandlerRegister WithAsyncSentHandler(HandlerPriority priority, Func<HttpSentContext, Task> handler) { if (handler == null) throw new ArgumentNullException(nameof(handler)); WithHandler(HandlerType.Sent, priority, context => handler((HttpSentContext)context)); return this; } #endregion #region Exception public HttpHandlerRegister WithExceptionHandler(Action<HttpExceptionContext> handler) { return WithExceptionHandler(HandlerPriority.Default, handler); } public HttpHandlerRegister WithExceptionHandler(HandlerPriority priority, Action<HttpExceptionContext> handler) { if (handler == null) throw new ArgumentNullException(nameof(handler)); return WithAsyncExceptionHandler(priority, handler.ToTask); } public HttpHandlerRegister WithAsyncExceptionHandler(Func<HttpExceptionContext, Task> handler) { return WithAsyncExceptionHandler(HandlerPriority.Default, handler); } public HttpHandlerRegister WithAsyncExceptionHandler(HandlerPriority priority, Func<HttpExceptionContext, Task> handler) { if (handler == null) throw new ArgumentNullException(nameof(handler)); WithHandler(HandlerType.Exception, priority, context => handler((HttpExceptionContext)context)); return this; } #endregion private IEnumerable<HandlerDelegate> GetHandlers(HandlerType type) { IDictionary<HandlerPriority, ICollection<HandlerDelegate>> handlers; lock (_handlers) { if (!_handlers.TryGetValue(type, out handlers)) { return Enumerable.Empty<HandlerDelegate>(); } return handlers.Keys.OrderBy(k => k).SelectMany(k => { ICollection<HandlerDelegate> col; if (!handlers.TryGetValue(k, out col)) { return Enumerable.Empty<HandlerDelegate>(); } return col; }); } } private void WithHandler(HandlerType type, HandlerPriority priority, HandlerDelegate handler) { if (handler == null) throw new ArgumentNullException(nameof(handler)); lock (_handlers) { if (!_handlers.ContainsKey(type)) { _handlers[type] = new Dictionary<HandlerPriority, ICollection<HandlerDelegate>>() { {priority, new List<HandlerDelegate> {handler}} }; } else { var handlersForType = _handlers[type]; if (!handlersForType.ContainsKey(priority)) { handlersForType[priority] = new List<HandlerDelegate> { handler }; } else { handlersForType[priority].Add(handler); } } } } } }
using System; using System.Drawing; using System.Reflection; using System.IO; using System.Windows.Forms; namespace IronAHK.Rusty { partial class Core { delegate void AsyncCallDlgOptions(ComplexDlgOptions options); delegate void AsyncComplexDialoge(IComplexDialoge complexDlg); // TODO: organise Dialogs.cs #region FileSelectFile /// <summary> /// Displays a standard dialog that allows the user to open or save files. /// </summary> /// <param name="OutputVar">The user selected files.</param> /// <param name="Options"> /// <list type="bullet"> /// <item><term>M</term>: <description>allow muliple files to be selected.</description></item> /// <item><term>S</term>: <description>show a save as dialog rather than a file open dialog.</description></item> /// <item><term>1</term>: <description>only allow existing file or directory paths.</description></item> /// <item><term>8</term>: <description>prompt to create files.</description></item> /// <item><term>16:</term>: <description>prompt to overwrite files.</description></item> /// <item><term>32</term>: <description>follow the target of a shortcut rather than using the shortcut file itself.</description></item> /// </list> /// </param> /// <param name="RootDir">The file path to initially select.</param> /// <param name="Prompt">Text displayed in the window to instruct the user what to do.</param> /// <param name="Filter">Indicates which types of files are shown by the dialog, e.g. <c>Audio (*.wav; *.mp2; *.mp3)</c>.</param> public static void FileSelectFile(out string OutputVar, string Options, string RootDir, string Prompt, string Filter) { bool save = false, multi = false, check = false, create = false, overwite = false, shortcuts = false; Options = Options.ToUpperInvariant(); if (Options.Contains("M")) { Options = Options.Replace("M", string.Empty); multi = true; } if (Options.Contains("S")) { Options = Options.Replace("S", string.Empty); save = true; } int result; if (int.TryParse(Options.Trim(), out result)) { if ((result & 1) == 1 || (result & 2) == 2) check = true; if ((result & 8) == 8) create = true; if ((result & 16) == 16) overwite = true; if ((result & 32) == 32) shortcuts = true; } ErrorLevel = 0; OutputVar = null; if (save) { var saveas = new SaveFileDialog { CheckPathExists = check, CreatePrompt = create, OverwritePrompt = overwite, DereferenceLinks = shortcuts, Filter = Filter }; var selected = dialogOwner == null ? saveas.ShowDialog() : saveas.ShowDialog(dialogOwner); if (selected == DialogResult.OK) OutputVar = saveas.FileName; else ErrorLevel = 1; } else { var open = new OpenFileDialog { Multiselect = multi, CheckFileExists = check, DereferenceLinks = shortcuts, Filter = Filter }; var selected = dialogOwner == null ? open.ShowDialog() : open.ShowDialog(dialogOwner); if (selected == DialogResult.OK) OutputVar = multi ? string.Join("\n", open.FileNames) : open.FileName; else ErrorLevel = 1; } } #endregion #region FileSelectFolder /// <summary> /// Displays a standard dialog that allows the user to select a folder. /// </summary> /// <param name="OutputVar">The user selected folder.</param> /// <param name="StartingFolder">An asterisk followed by a path to initially select a folder, can be left blank for none.</param> /// <param name="Options"> /// <list type="bullet"> /// <item><term>1</term>: <description>show a new folder button in the dialog.</description></item> /// </list> /// </param> /// <param name="Prompt">Text displayed in the window to instruct the user what to do.</param> public static void FileSelectFolder(out string OutputVar, string StartingFolder, int Options, string Prompt) { var select = new FolderBrowserDialog(); select.ShowNewFolderButton = (Options & 1) == 1; if (!string.IsNullOrEmpty(Prompt)) select.Description = Prompt; StartingFolder = StartingFolder.Trim(); if (StartingFolder.Length > 2 && StartingFolder[0] == '*') select.SelectedPath = StartingFolder.Substring(1); else if (StartingFolder.Length != 0) { // TODO: convert CLSID to special folder enumeration for folder select dialog } ErrorLevel = 0; var selected = dialogOwner == null ? select.ShowDialog() : select.ShowDialog(dialogOwner); if (selected == DialogResult.OK) OutputVar = select.SelectedPath; else { OutputVar = string.Empty; ErrorLevel = 1; } } #endregion #region InputBox /// <summary> /// Displays an input box to ask the user to enter a string. /// </summary> /// <param name="OutputVar">The name of the variable in which to store the text entered by the user.</param> /// <param name="Title">The title of the input box. If blank or omitted, it defaults to the name of the script.</param> /// <param name="Prompt">The text of the input box, which is usually a message to the user indicating what kind of input is expected.</param> /// <param name="Hide">If this parameter is the word HIDE, the user's input will be masked, which is useful for passwords.</param> /// <param name="Width">If this parameter is blank or omitted, the starting width of the window will be 375.</param> /// <param name="Height">If this parameter is blank or omitted, the starting height of the window will be 189.</param> /// <param name="X">The X coordinate of the window (use 0,0 to move it to the upper left corner of the desktop). If either coordinate is blank or omitted, the dialog will be centered in that dimension. Either coordinate can be negative to position the window partially or entirely off the desktop.</param> /// <param name="Y">The Y coordinate of the window (see <paramref name="X"/>).</param> /// <param name="Font">Not yet implemented (leave blank). In the future it might accept something like verdana:8</param> /// <param name="Timeout">Timeout in seconds (can contain a decimal point). If this value exceeds 2147483 (24.8 days), it will be set to 2147483. After the timeout has elapsed, the InputBox window will be automatically closed and ErrorLevel will be set to 2. OutputVar will still be set to what the user entered.</param> /// <param name="Default">A string that will appear in the InputBox's edit field when the dialog first appears. The user can change it by backspacing or other means.</param> public static DialogResult InputBox(out string OutputVar, string Title, string Prompt, string Hide, string Width, string Height, string X, string Y, string Font, string Timeout, string Default) { var input = new InputDialog { Title = Title, Prompt = Prompt }; if (dialogOwner != null) input.Owner = dialogOwner; int n; if (!string.IsNullOrEmpty(Width) && int.TryParse(Width, out n)) input.Size = new Size(n, input.Size.Height); if (!string.IsNullOrEmpty(Height) && int.TryParse(Height, out n)) input.Size = new Size(input.Size.Width, n); if (!string.IsNullOrEmpty(X) && int.TryParse(X, out n)) input.Location = new Point(n, input.Location.X); if (!string.IsNullOrEmpty(Y) && int.TryParse(Y, out n)) input.Location = new Point(input.Location.Y, n); input.Hide = Hide.ToLowerInvariant().Contains(Keyword_Hide); var result = input.ShowDialog(); if (result == DialogResult.OK) OutputVar = input.Message; else OutputVar = null; switch (result) { case DialogResult.OK: ErrorLevel = 0; break; default: ErrorLevel = 1; break; } return result; } #endregion #region MsgBox /// <summary> /// Show a message box. /// </summary> /// <param name="Text">The text to show in the prompt.</param> public static void MsgBox(string Text) { var title = Environment.GetEnvironmentVariable("SCRIPT") ?? string.Empty; if (!string.IsNullOrEmpty(title) && File.Exists(title)) title = Path.GetFileName(title); if (dialogOwner != null) MessageBox.Show(dialogOwner, Text, title); else MessageBox.Show(Text, title); } /// <summary> /// Displays the specified text in a small window containing one or more buttons (such as Yes and No). /// </summary> /// <param name="Options"> /// <para>Indicates the type of message box and the possible button combinations. If blank or omitted, it defaults to 0. See the table below for allowed values.</para> /// <para>This parameter will not be recognized if it contains an expression or a variable reference such as %option%. Instead, use a literal numeric value.</para> /// </param> /// <param name="Title">The title of the message box window. If omitted or blank, it defaults to the name of the script (without path).</param> /// <param name="Text"> /// <para>If all the parameters are omitted, the MsgBox will display the text "Press OK to continue." Otherwise, this parameter is the text displayed inside the message box to instruct the user what to do, or to present information.</para> /// <para>Escape sequences can be used to denote special characters. For example, `n indicates a linefeed character, which ends the current line and begins a new one. Thus, using text1`n`ntext2 would create a blank line between text1 and text2.</para> /// <para>If Text is long, it can be broken up into several shorter lines by means of a continuation section, which might improve readability and maintainability.</para> /// </param> /// <param name="Timeout"> /// <para>(optional) Timeout in seconds (can contain a decimal point but cannot be an expression). If this value exceeds 2147483 (24.8 days), it will be set to 2147483. After the timeout has elapsed the message box will be automatically closed and the IfMsgBox command will see the value TIMEOUT.</para> /// <para>Known limitation: If the MsgBox contains only an OK button, IfMsgBox will think that the OK button was pressed if the MsgBox times out while its own thread is interrupted by another.</para> /// </param> public static DialogResult MsgBox(int Options, string Title, string Text, int Timeout) { MessageBoxButtons buttons = MessageBoxButtons.OK; switch (Options & 0xf) { case 0: buttons = MessageBoxButtons.OK; break; case 1: buttons = MessageBoxButtons.OKCancel; break; case 2: buttons = MessageBoxButtons.AbortRetryIgnore; break; case 3: buttons = MessageBoxButtons.YesNoCancel; break; case 4: buttons = MessageBoxButtons.YesNo; break; case 5: buttons = MessageBoxButtons.RetryCancel; break; //case 6: /* Cancel/Try Again/Continue */ ; break; //case 7: /* Adds a Help button */ ; break; // help done differently } MessageBoxIcon icon = MessageBoxIcon.None; switch (Options & 0xf0) { case 16: icon = MessageBoxIcon.Hand; break; case 32: icon = MessageBoxIcon.Question; break; case 48: icon = MessageBoxIcon.Exclamation; break; case 64: icon = MessageBoxIcon.Asterisk; break; } MessageBoxDefaultButton defaultbutton = MessageBoxDefaultButton.Button1; switch (Options & 0xf00) { case 256: defaultbutton = MessageBoxDefaultButton.Button2; break; case 512: defaultbutton = MessageBoxDefaultButton.Button3; break; } var options = default(MessageBoxOptions); switch (Options & 0xf0000) { case 131072: options = MessageBoxOptions.DefaultDesktopOnly; break; case 262144: options = MessageBoxOptions.ServiceNotification; break; case 524288: options = MessageBoxOptions.RightAlign; break; case 1048576: options = MessageBoxOptions.RtlReading; break; } bool help = (Options & 0xf000) == 16384; if (string.IsNullOrEmpty(Title)) { var script = Environment.GetEnvironmentVariable("SCRIPT"); if (!string.IsNullOrEmpty(script) && File.Exists(script)) Title = Path.GetFileName(script); } var result = DialogResult.None; if (dialogOwner != null) result = MessageBox.Show(dialogOwner, Text, Title, buttons, icon, defaultbutton, options); else result = MessageBox.Show(Text, Title, buttons, icon, defaultbutton, options, help); return result; } #endregion #region Progress /// <summary> /// Creates or updates a window containing a progress bar or an image. /// </summary> /// <param name="ProgressParam1"> /// <para>If the progress window already exists: If Param1 is the word OFF, the window is destroyed. If Param1 is the word SHOW, the window is shown if it is currently hidden.</para> /// <para>Otherwise, if Param1 is an pure number, its bar's position is changed to that value. If Param1 is blank, its bar position will be unchanged but its text will be updated to reflect any new strings provided in SubText, MainText, and WinTitle. In both of these modes, if the window doesn't yet exist, it will be created with the defaults for all options.</para> /// <para>If the progress window does not exist: A new progress window is created (replacing any old one), and Param1 is a string of zero or more options from the list below.</para> /// </param> /// <param name="SubText">The text to display below the image or bar indicator. Although word-wrapping will occur, to begin a new line explicitly, use linefeed (`n). To set an existing window's text to be blank, specify %A_Space%. For the purpose of auto-calculating the window's height, blank lines can be reserved in a way similar to MainText below.</param> /// <param name="MainText"> /// <para>The text to display above the image or bar indicator (its font is semi-bold). Although word-wrapping will occur, to begin a new line explicitly, use linefeed (`n).</para> /// <para>If blank or omitted, no space will be reserved in the window for MainText. To reserve space for single line to be added later, or to set an existing window's text to be blank, specify %A_Space%. To reserve extra lines beyond the first, append one or more linefeeds (`n).</para> /// <para>Once the height of MainText's control area has been set, it cannot be changed without recreating the window.</para> /// </param> /// <param name="WinTitle">The text to display below the image or bar indicator. Although word-wrapping will occur, to begin a new line explicitly, use linefeed (`n). To set an existing window's text to be blank, specify %A_Space%. For the purpose of auto-calculating the window's height, blank lines can be reserved in a way similar to MainText below.</param> /// <param name="FontName"> /// <para>The name of the font to use for both MainText and SubText. The font table lists the fonts included with the various versions of Windows. If unspecified or if the font cannot be found, the system's default GUI font will be used.</para> /// <para>See the options section below for how to change the size, weight, and color of the font.</para> /// </param> public static void Progress(string ProgressParam1, string SubText, string MainText, string WinTitle, string FontName) { InitDialoges(); var progressOptions = new ComplexDlgOptions() { SubText = SubText, MainText = MainText, WinTitle = WinTitle, }; progressOptions.ParseGuiID(ProgressParam1); progressOptions.ParseComplexOptions(ProgressParam1); ProgressAssync(progressOptions); } private static void ProgressAssync(ComplexDlgOptions Options) { ProgressDialog thisProgress = null; if(progressDialgos.ContainsKey(Options.GUIID)) { thisProgress = progressDialgos[Options.GUIID]; if(thisProgress.InvokeRequired) { thisProgress.Invoke(new AsyncCallDlgOptions(ProgressAssync), Options); } } if(thisProgress != null) { Options.AppendShowHideTo(thisProgress); } else { thisProgress = new ProgressDialog(); progressDialgos.Add(Options.GUIID, thisProgress); } Options.AppendTo(thisProgress); #region Parse Progress specific Options short num; if(!short.TryParse(Options.Param1, out num)) { num = 0; } thisProgress.ProgressValue = num; #endregion if(!Options.Hide && !thisProgress.Visible) thisProgress.Show(); } #endregion #region SplashImage /// <summary> /// Creates or updates a window containing a progress bar or an image. /// </summary> /// <param name="ImageFile"> /// <para>If this is the word OFF, the window is destroyed. If this is the word SHOW, the window is shown if it is currently hidden.</para> /// <para>Otherwise, this is the file name of the BMP, GIF, or JPG image to display (to display other file formats such as PNG, TIF, and ICO, consider using the Gui command to create a window containing a picture control).</para> /// <para>ImageFile is assumed to be in %A_WorkingDir% if an absolute path isn't specified. If ImageFile and Options are blank and the window already exists, its image will be unchanged but its text will be updated to reflect any new strings provided in SubText, MainText, and WinTitle.</para> /// <para>For newly created windows, if ImageFile is blank or there is a problem loading the image, the window will be displayed without the picture.</para> /// </param> /// <param name="Options">A string of zero or more options from the list further below.</param> /// <param name="SubText">The text to display below the image or bar indicator. Although word-wrapping will occur, to begin a new line explicitly, use linefeed (`n). To set an existing window's text to be blank, specify %A_Space%. For the purpose of auto-calculating the window's height, blank lines can be reserved in a way similar to MainText below.</param> /// <param name="MainText"> /// <para>The text to display above the image or bar indicator (its font is semi-bold). Although word-wrapping will occur, to begin a new line explicitly, use linefeed (`n).</para> /// <para>If blank or omitted, no space will be reserved in the window for MainText. To reserve space for single line to be added later, or to set an existing window's text to be blank, specify %A_Space%. To reserve extra lines beyond the first, append one or more linefeeds (`n).</para> /// <para>Once the height of MainText's control area has been set, it cannot be changed without recreating the window.</para> /// </param> /// <param name="WinTitle">The title of the window. If omitted and the window is being newly created, the title defaults to the name of the script (without path). If the B (borderless) option has been specified, there will be no visible title bar but the window can still be referred to by this title in commands such as WinMove.</param> /// <param name="FontName"> /// <para>The name of the font to use for both MainText and SubText. The font table lists the fonts included with the various versions of Windows. If unspecified or if the font cannot be found, the system's default GUI font will be used.</para> /// <para>See the options section below for how to change the size, weight, and color of the font.</para> /// </param> public static void SplashImage(string ImageFile, string Options, string SubText, string MainText, string WinTitle, string FontName) { InitDialoges(); if(string.IsNullOrEmpty(ImageFile)) return; var splashOptions = new ComplexDlgOptions() { SubText = SubText, MainText = MainText, WinTitle = WinTitle, }; splashOptions.ParseGuiID(ImageFile); splashOptions.ParseComplexOptions(Options); SplashImageAssync(splashOptions); } private static void SplashImageAssync(ComplexDlgOptions Options) { SplashDialog thisSplash = null; System.Drawing.Image thisImage = null; if(splashDialogs.ContainsKey(Options.GUIID)) { thisSplash = splashDialogs[Options.GUIID]; if(thisSplash.InvokeRequired) { thisSplash.Invoke(new AsyncCallDlgOptions(SplashImageAssync), Options); } } if(thisSplash != null) { Options.AppendShowHideTo(thisSplash); } else { thisSplash = new SplashDialog(); splashDialogs.Add(Options.GUIID, thisSplash); } Options.AppendTo(thisSplash); #region Splash specific Options if(File.Exists(Options.Param1)) { try { thisImage = System.Drawing.Bitmap.FromFile(Options.Param1); } catch(Exception) { ErrorLevel = 1; return; } if(thisImage != null) { thisSplash.Image = thisImage; } } #endregion if(!Options.Hide && !thisSplash.Visible) thisSplash.Show(); } #endregion } }
/******************************************************************** 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.ComponentModel; using System.Drawing; using System.Linq; using System.Windows.Forms; using System.Xml.Serialization; using Microsoft.MultiverseInterfaceStudio.FrameXml.Serialization; using System.Drawing.Design; using System.Collections; namespace Microsoft.MultiverseInterfaceStudio.FrameXml.Controls { /// <summary> /// Generic base class for all WoW controls. /// </summary> /// <typeparam name="TS">The type of the Serialization Object.</typeparam> public partial class GenericControl<TS> : BaseControl, ICustomTypeDescriptor where TS: LayoutFrameType, new() { #region Control support [Browsable(false)] public Control InnerControl { get; private set; } private StringFormat stringFormat = new StringFormat(); /// <summary> /// Initializes a new instance of the <see cref="GenericControl&lt;TS&gt;"/> class. /// </summary> /// <remarks>The class has a non-default constructor. Don't remove this empty default constructor.</remarks> public GenericControl() { Initialize(); } private void Initialize() { this.SetStyle(ControlStyles.SupportsTransparentBackColor, true); this.SetStyle(ControlStyles.UserPaint, true); this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true); // used for displaying the type name in the center of the control stringFormat.Alignment = StringAlignment.Center; stringFormat.LineAlignment = StringAlignment.Center; } /// <summary> /// Initializes a new instance of the <see cref="GenericControl&lt;TS&gt;"/> class. /// </summary> /// <param name="control">The inner control.</param> public GenericControl(Control control) { this.InnerControl = control; if (InnerControl != null) { InnerControl.Parent = this; InnerControl.Dock = DockStyle.Fill; } Initialize(); } /// <summary> /// Gets or sets a value indicating whether this instance has border. /// </summary> /// <value> /// <c>true</c> if this instance has border; otherwise, <c>false</c>. /// </value> protected bool HasBorder { get; set;} protected virtual bool DrawName { get { return true; } } protected override void OnPaint(PaintEventArgs e) { if (this.DrawName) { // draw the control name in the middle. If there are specific inner controls, this text might be hidden. e.Graphics.DrawString(this.Name, Font, Brushes.Black, this.ClientRectangle, stringFormat); } base.OnPaint(e); // draw the border if necessary if (this.HasBorder) { Rectangle rect = this.ClientRectangle; if (rect.Width > 0) rect.Width--; if (rect.Height > 0) rect.Height--; e.Graphics.DrawRectangle(Pens.Black, rect); } } /// <summary> /// Raises the <see cref="E:System.Windows.Forms.Control.ControlAdded"/> event. /// Brings the newly added control in front. /// </summary> /// <param name="e">A <see cref="T:System.Windows.Forms.ControlEventArgs"/> that contains the event data.</param> protected override void OnControlAdded(ControlEventArgs e) { if (e.Control != this.InnerControl && !(this is GenericFrameControl<TS>)) throw new ArgumentException("This control cannot host further controls."); base.OnControlAdded(e); e.Control.BringToFront(); } [Category("Design")] public string name { get { return this.LayoutFrameType.name; } set { string oldName = this.Name; // TODO: verify control name uniqueness this.Name = value; this.LayoutFrameType.name = value; this.Site.Name = this.LayoutFrameType.ExpandedName; } } #endregion #region Serialization Support private TS typedSerializationObject = null; [Browsable(false)] public TS TypedSerializationObject { get { if (typedSerializationObject == null) { typedSerializationObject = new TS(); OnUpdateControl(); } return typedSerializationObject; } set { typedSerializationObject = value; OnUpdateControl(); } } [Browsable(false)] public override SerializationObject SerializationObject { get { return TypedSerializationObject; } set { TypedSerializationObject = (TS)value; } } #endregion #region ICustomTypeDescriptor Members public AttributeCollection GetAttributes() { return TypeDescriptorHelper.GetAttributes(this); } public string GetClassName() { return TypeDescriptorHelper.GetClassName(this); } public string GetComponentName() { return TypeDescriptorHelper.GetComponentName(this); } public TypeConverter GetConverter() { return TypeDescriptorHelper.GetConverter(this); } public EventDescriptor GetDefaultEvent() { return TypeDescriptorHelper.GetDefaultEvent(this); } public PropertyDescriptor GetDefaultProperty() { return TypeDescriptorHelper.GetDefaultProperty(this); } public object GetEditor(Type editorBaseType) { return TypeDescriptorHelper.GetEditor(this, editorBaseType); } public EventDescriptorCollection GetEvents() { return TypeDescriptorHelper.GetEvents(this); } public EventDescriptorCollection GetEvents(Attribute[] attributes) { return TypeDescriptorHelper.GetEvents(this, attributes); } public PropertyDescriptorCollection GetProperties() { return TypeDescriptorHelper.GetProperties(this); } public PropertyDescriptorCollection GetProperties(Attribute[] attributes) { return TypeDescriptorHelper.GetProperties(this, attributes); } public object GetPropertyOwner(PropertyDescriptor pd) { return TypeDescriptorHelper.GetPropertyOwner(this, pd); } #endregion #region layouting support protected override void OnMove(EventArgs e) { base.OnMove(e); if (this.SuspendLayouting) return; if (this.ControlAnchors.Left != null) { this.ControlAnchors.Left.SetX(this.Left, this.Parent); } if (this.ControlAnchors.Top != null) { this.ControlAnchors.Top.SetY(this.Top, this.Parent); } if (this.ControlAnchors.Right != null) { this.ControlAnchors.Right.SetX(this.Right, this.Parent); } if (this.ControlAnchors.Bottom != null) { this.ControlAnchors.Bottom.SetY(this.Bottom, this.Parent); } if ((this.ControlAnchors.Left != null || this.ControlAnchors.Right != null) && this.ControlAnchors.Top == null && this.ControlAnchors.Bottom == null) { ControlAnchors.SideAnchor sideAnchor = this.ControlAnchors.Left != null ? this.ControlAnchors.Left : this.ControlAnchors.Right; sideAnchor.SetY(this.Top + this.Height / 2, this.Parent); } if ((this.ControlAnchors.Top != null || this.ControlAnchors.Bottom != null) && this.ControlAnchors.Left == null && this.ControlAnchors.Right == null) { ControlAnchors.SideAnchor sideAnchor = this.ControlAnchors.Top != null ? this.ControlAnchors.Top : this.ControlAnchors.Bottom; sideAnchor.SetX(this.Left + this.Width / 2, this.Parent); } if (this.ControlAnchors.Center != null) { this.ControlAnchors.Center.SetX((this.Right + this.Left) / 2, this.Parent); this.ControlAnchors.Center.SetY((this.Top + this.Bottom) / 2, this.Parent); } ChangeLayoutOfDependencies(); this.OnPropertyChanged(new PropertyChangedEventArgs("anchors")); } /// <summary> /// Raises the <see cref="E:System.Windows.Forms.Control.Resize"/> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param> protected override void OnResize(EventArgs e) { base.OnResize(e); if (this.SuspendLayouting) return; if (this.ControlAnchors.Left != null && this.ControlAnchors.Right != null) { this.ControlAnchors.Left.SetX(this.Left, this.Parent); this.ControlAnchors.Right.SetX(this.Right, this.Parent); } if (this.ControlAnchors.Top != null && this.ControlAnchors.Bottom != null) { this.ControlAnchors.Top.SetY(this.Top, this.Parent); this.ControlAnchors.Bottom.SetY(this.Bottom, this.Parent); } if (this.ControlAnchors.Center != null) { this.ControlAnchors.Center.SetX((this.Right + this.Left) / 2, this.Parent); this.ControlAnchors.Center.SetY((this.Top + this.Bottom) / 2, this.Parent); } Dimension.Size dimension = Dimension.Clone<Dimension.Size>(this.TypedSerializationObject.SizeDimension); if (dimension == null) { dimension = new Dimension.Size(); } dimension.Update(this.Width, this.Height); this.TypedSerializationObject.SizeDimension = dimension; ChangeLayoutOfDependencies(); this.OnPropertyChanged(new PropertyChangedEventArgs("size")); } #endregion protected override void OnParentChanged(EventArgs e) { base.OnParentChanged(e); ISerializableControl parent = (this.Parent as ISerializableControl); if ((parent == null) || (parent.DesignerLoader == null)) { this.DesignerLoader = null; } else { this.DesignerLoader = parent.DesignerLoader; if (string.IsNullOrEmpty(this.name)) { string typeName = typeof(TS).Name; if (typeName.EndsWith("Type")) { typeName = typeName.Substring(0, typeName.Length - 4); } var names = from layoutFrame in this.DesignerLoader.LayoutFrames select layoutFrame.ExpandedName; this.name = UniqueName.GetUniqueName(this.name, typeName, names); } this.LayoutFrameType.Parent = parent.SerializationObject as LayoutFrameType; this.Site.Name = this.LayoutFrameType.ExpandedName; } } /// <summary> /// Called after the control has been added to another container. /// </summary> /// <remarks>Adds the TOPLEFT anchor</remarks> protected override void InitLayout() { base.InitLayout(); // set ControlFactory ISerializableControl serializableParent = this.Parent as ISerializableControl; if (serializableParent == null) return; this.DesignerLoader = serializableParent.DesignerLoader; if (this.SuspendLayouting) return; if (this.LayoutFrameType.SizeDimension == null) this.LayoutFrameType.SizeDimension = Dimension.FromSize<Dimension.Size>(this.Size); LayoutFrameTypeAnchors anchors; if (this.LayoutFrameType.AnchorsCollection.Count == 0) { anchors = new LayoutFrameTypeAnchors(); this.LayoutFrameType.AnchorsCollection.Add(anchors); } else { anchors = this.LayoutFrameType.AnchorsCollection[0]; } if (anchors.Anchor.Count == 0) { LayoutFrameTypeAnchorsAnchor anchor = new LayoutFrameTypeAnchorsAnchor(); anchor.point = FRAMEPOINT.TOPLEFT; anchor.Offset = new Dimension(); anchor.Offset.Update(this.Left, this.Top); anchors.Anchor.Add(anchor); this.DoChangeLayout(); } } /// <summary> /// Gets or sets the size of the control. /// </summary> /// <value>The size dimension.</value> /// <remarks> /// Appears as "Size" in the property grid. /// </remarks> [Category("Layout")] [DisplayName("Size")] [XmlIgnore] public Dimension.Size SizeDimension { get { return TypedSerializationObject.SizeDimension; } set { TypedSerializationObject.SizeDimension = value; } } [XmlIgnore] [TypeConverter(typeof(InheritsTypeConverter))] [Category("Appearance")] public string inherits { get { return TypedSerializationObject.inherits; } set { TypedSerializationObject.inherits = value; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. #pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters using System; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Reflection; using Microsoft.CodeAnalysis; using Roslyn.Utilities; using Microsoft.CodeAnalysis.Scripting.Hosting; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.Text; using System.IO; namespace Microsoft.CodeAnalysis.Scripting { /// <summary> /// A class that represents a script that you can run. /// /// Create a script using a language specific script class such as CSharpScript or VisualBasicScript. /// </summary> public abstract class Script { internal readonly ScriptCompiler Compiler; internal readonly ScriptBuilder Builder; private Compilation _lazyCompilation; internal Script(ScriptCompiler compiler, ScriptBuilder builder, SourceText sourceText, ScriptOptions options, Type globalsTypeOpt, Script previousOpt) { Debug.Assert(sourceText != null); Debug.Assert(options != null); Debug.Assert(compiler != null); Debug.Assert(builder != null); Compiler = compiler; Builder = builder; Previous = previousOpt; SourceText = sourceText; Options = options; GlobalsType = globalsTypeOpt; } internal static Script<T> CreateInitialScript<T>(ScriptCompiler compiler, SourceText sourceText, ScriptOptions optionsOpt, Type globalsTypeOpt, InteractiveAssemblyLoader assemblyLoaderOpt) { return new Script<T>(compiler, new ScriptBuilder(assemblyLoaderOpt ?? new InteractiveAssemblyLoader()), sourceText, optionsOpt ?? ScriptOptions.Default, globalsTypeOpt, previousOpt: null); } /// <summary> /// A script that will run first when this script is run. /// Any declarations made in the previous script can be referenced in this script. /// The end state from running this script includes all declarations made by both scripts. /// </summary> public Script Previous { get; } /// <summary> /// The options used by this script. /// </summary> public ScriptOptions Options { get; } /// <summary> /// The source code of the script. /// </summary> public string Code => SourceText.ToString(); /// <summary> /// The <see cref="SourceText"/> of the script. /// </summary> internal SourceText SourceText { get; } /// <summary> /// The type of an object whose members can be accessed by the script as global variables. /// </summary> public Type GlobalsType { get; } /// <summary> /// The expected return type of the script. /// </summary> public abstract Type ReturnType { get; } /// <summary> /// Creates a new version of this script with the specified options. /// </summary> public Script WithOptions(ScriptOptions options) => WithOptionsInternal(options); internal abstract Script WithOptionsInternal(ScriptOptions options); /// <summary> /// Continues the script with given code snippet. /// </summary> public Script<object> ContinueWith(string code, ScriptOptions options = null) => ContinueWith<object>(code, options); /// <summary> /// Continues the script with given <see cref="Stream"/> representing code. /// </summary> /// <exception cref="ArgumentNullException">Stream is null.</exception> /// <exception cref="ArgumentException">Stream is not readable or seekable.</exception> public Script<object> ContinueWith(Stream code, ScriptOptions options = null) => ContinueWith<object>(code, options); /// <summary> /// Continues the script with given code snippet. /// </summary> public Script<TResult> ContinueWith<TResult>(string code, ScriptOptions options = null) { options = options ?? InheritOptions(Options); return new Script<TResult>(Compiler, Builder, SourceText.From(code ?? "", options.FileEncoding), options, GlobalsType, this); } /// <summary> /// Continues the script with given <see cref="Stream"/> representing code. /// </summary> /// <exception cref="ArgumentNullException">Stream is null.</exception> /// <exception cref="ArgumentException">Stream is not readable or seekable.</exception> public Script<TResult> ContinueWith<TResult>(Stream code, ScriptOptions options = null) { if (code == null) throw new ArgumentNullException(nameof(code)); options = options ?? InheritOptions(Options); return new Script<TResult>(Compiler, Builder, SourceText.From(code, options.FileEncoding), options, GlobalsType, this); } private static ScriptOptions InheritOptions(ScriptOptions previous) { // don't inherit references or imports, they have already been applied: return previous. WithReferences(ImmutableArray<MetadataReference>.Empty). WithImports(ImmutableArray<string>.Empty); } /// <summary> /// Get's the <see cref="Compilation"/> that represents the semantics of the script. /// </summary> public Compilation GetCompilation() { if (_lazyCompilation == null) { var compilation = Compiler.CreateSubmission(this); Interlocked.CompareExchange(ref _lazyCompilation, compilation, null); } return _lazyCompilation; } /// <summary> /// Runs the script from the beginning and returns the result of the last code snippet. /// </summary> /// <param name="globals"> /// An instance of <see cref="Script.GlobalsType"/> holding on values of global variables accessible from the script. /// Must be specified if and only if the script was created with a <see cref="Script.GlobalsType"/>. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>The result of the last code snippet.</returns> internal Task<object> EvaluateAsync(object globals = null, CancellationToken cancellationToken = default(CancellationToken)) => CommonEvaluateAsync(globals, cancellationToken); internal abstract Task<object> CommonEvaluateAsync(object globals, CancellationToken cancellationToken); /// <summary> /// Runs the script from the beginning. /// </summary> /// <param name="globals"> /// An instance of <see cref="Script.GlobalsType"/> holding on values for global variables accessible from the script. /// Must be specified if and only if the script was created with <see cref="Script.GlobalsType"/>. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> public Task<ScriptState> RunAsync(object globals, CancellationToken cancellationToken) => CommonRunAsync(globals, null, cancellationToken); /// <summary> /// Runs the script from the beginning. /// </summary> /// <param name="globals"> /// An instance of <see cref="Script.GlobalsType"/> holding on values for global variables accessible from the script. /// Must be specified if and only if the script was created with <see cref="Script.GlobalsType"/>. /// </param> /// <param name="catchException"> /// If specified, any exception thrown by the script top-level code is passed to <paramref name="catchException"/>. /// If it returns true the exception is caught and stored on the resulting <see cref="ScriptState"/>, otherwise the exception is propagated to the caller. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> public Task<ScriptState> RunAsync(object globals = null, Func<Exception, bool> catchException = null, CancellationToken cancellationToken = default(CancellationToken)) => CommonRunAsync(globals, catchException, cancellationToken); internal abstract Task<ScriptState> CommonRunAsync(object globals, Func<Exception, bool> catchException, CancellationToken cancellationToken); /// <summary> /// Run the script from the specified state. /// </summary> /// <param name="previousState"> /// Previous state of the script execution. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> public Task<ScriptState> RunFromAsync(ScriptState previousState, CancellationToken cancellationToken) => CommonRunFromAsync(previousState, null, cancellationToken); /// <summary> /// Run the script from the specified state. /// </summary> /// <param name="previousState"> /// Previous state of the script execution. /// </param> /// <param name="catchException"> /// If specified, any exception thrown by the script top-level code is passed to <paramref name="catchException"/>. /// If it returns true the exception is caught and stored on the resulting <see cref="ScriptState"/>, otherwise the exception is propagated to the caller. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> public Task<ScriptState> RunFromAsync(ScriptState previousState, Func<Exception, bool> catchException = null, CancellationToken cancellationToken = default(CancellationToken)) => CommonRunFromAsync(previousState, catchException, cancellationToken); internal abstract Task<ScriptState> CommonRunFromAsync(ScriptState previousState, Func<Exception, bool> catchException, CancellationToken cancellationToken); /// <summary> /// Forces the script through the compilation step. /// If not called directly, the compilation step will occur on the first call to Run. /// </summary> public ImmutableArray<Diagnostic> Compile(CancellationToken cancellationToken = default(CancellationToken)) => CommonCompile(cancellationToken); internal abstract ImmutableArray<Diagnostic> CommonCompile(CancellationToken cancellationToken); internal abstract Func<object[], Task> CommonGetExecutor(CancellationToken cancellationToken); // Apply recursive alias <host> to the host assembly reference, so that we hide its namespaces and global types behind it. internal static readonly MetadataReferenceProperties HostAssemblyReferenceProperties = MetadataReferenceProperties.Assembly.WithAliases(ImmutableArray.Create("<host>")).WithRecursiveAliases(true); /// <summary> /// Gets the references that need to be assigned to the compilation. /// This can be different than the list of references defined by the <see cref="ScriptOptions"/> instance. /// </summary> internal ImmutableArray<MetadataReference> GetReferencesForCompilation( CommonMessageProvider messageProvider, DiagnosticBag diagnostics, MetadataReference languageRuntimeReferenceOpt = null) { var resolver = Options.MetadataResolver; var references = ArrayBuilder<MetadataReference>.GetInstance(); try { if (Previous == null) { var corLib = MetadataReference.CreateFromAssemblyInternal(typeof(object).GetTypeInfo().Assembly); references.Add(corLib); if (GlobalsType != null) { var globalsAssembly = GlobalsType.GetTypeInfo().Assembly; // If the assembly doesn't have metadata (it's an in-memory or dynamic assembly), // the host has to add reference to the metadata where globals type is located explicitly. if (MetadataReference.HasMetadata(globalsAssembly)) { references.Add(MetadataReference.CreateFromAssemblyInternal(globalsAssembly, HostAssemblyReferenceProperties)); } } if (languageRuntimeReferenceOpt != null) { references.Add(languageRuntimeReferenceOpt); } } // add new references: foreach (var reference in Options.MetadataReferences) { var unresolved = reference as UnresolvedMetadataReference; if (unresolved != null) { var resolved = resolver.ResolveReference(unresolved.Reference, null, unresolved.Properties); if (resolved.IsDefault) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_MetadataFileNotFound, Location.None, unresolved.Reference)); } else { references.AddRange(resolved); } } else { references.Add(reference); } } return references.ToImmutable(); } finally { references.Free(); } } // TODO: remove internal bool HasReturnValue() { return GetCompilation().HasSubmissionResult(); } } public sealed class Script<T> : Script { private ImmutableArray<Func<object[], Task>> _lazyPrecedingExecutors; private Func<object[], Task<T>> _lazyExecutor; internal Script(ScriptCompiler compiler, ScriptBuilder builder, SourceText sourceText, ScriptOptions options, Type globalsTypeOpt, Script previousOpt) : base(compiler, builder, sourceText, options, globalsTypeOpt, previousOpt) { } public override Type ReturnType => typeof(T); public new Script<T> WithOptions(ScriptOptions options) { return (options == Options) ? this : new Script<T>(Compiler, Builder, SourceText, options, GlobalsType, Previous); } internal override Script WithOptionsInternal(ScriptOptions options) => WithOptions(options); internal override ImmutableArray<Diagnostic> CommonCompile(CancellationToken cancellationToken) { // TODO: avoid throwing exception, report all diagnostics https://github.com/dotnet/roslyn/issues/5949 try { GetPrecedingExecutors(cancellationToken); GetExecutor(cancellationToken); return ImmutableArray.CreateRange(GetCompilation().GetDiagnostics(cancellationToken).Where(d => d.Severity == DiagnosticSeverity.Warning)); } catch (CompilationErrorException e) { return ImmutableArray.CreateRange(e.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error || d.Severity == DiagnosticSeverity.Warning)); } } internal override Func<object[], Task> CommonGetExecutor(CancellationToken cancellationToken) => GetExecutor(cancellationToken); internal override Task<object> CommonEvaluateAsync(object globals, CancellationToken cancellationToken) => EvaluateAsync(globals, cancellationToken).CastAsync<T, object>(); internal override Task<ScriptState> CommonRunAsync(object globals, Func<Exception, bool> catchException, CancellationToken cancellationToken) => RunAsync(globals, catchException, cancellationToken).CastAsync<ScriptState<T>, ScriptState>(); internal override Task<ScriptState> CommonRunFromAsync(ScriptState previousState, Func<Exception, bool> catchException, CancellationToken cancellationToken) => RunFromAsync(previousState, catchException, cancellationToken).CastAsync<ScriptState<T>, ScriptState>(); /// <exception cref="CompilationErrorException">Compilation has errors.</exception> private Func<object[], Task<T>> GetExecutor(CancellationToken cancellationToken) { if (_lazyExecutor == null) { Interlocked.CompareExchange(ref _lazyExecutor, Builder.CreateExecutor<T>(Compiler, GetCompilation(), Options.EmitDebugInformation, cancellationToken), null); } return _lazyExecutor; } /// <exception cref="CompilationErrorException">Compilation has errors.</exception> private ImmutableArray<Func<object[], Task>> GetPrecedingExecutors(CancellationToken cancellationToken) { if (_lazyPrecedingExecutors.IsDefault) { var preceding = TryGetPrecedingExecutors(null, cancellationToken); Debug.Assert(!preceding.IsDefault); InterlockedOperations.Initialize(ref _lazyPrecedingExecutors, preceding); } return _lazyPrecedingExecutors; } /// <exception cref="CompilationErrorException">Compilation has errors.</exception> private ImmutableArray<Func<object[], Task>> TryGetPrecedingExecutors(Script lastExecutedScriptInChainOpt, CancellationToken cancellationToken) { Script script = Previous; if (script == lastExecutedScriptInChainOpt) { return ImmutableArray<Func<object[], Task>>.Empty; } var scriptsReversed = ArrayBuilder<Script>.GetInstance(); while (script != null && script != lastExecutedScriptInChainOpt) { scriptsReversed.Add(script); script = script.Previous; } if (lastExecutedScriptInChainOpt != null && script != lastExecutedScriptInChainOpt) { scriptsReversed.Free(); return default(ImmutableArray<Func<object[], Task>>); } var executors = ArrayBuilder<Func<object[], Task>>.GetInstance(scriptsReversed.Count); // We need to build executors in the order in which they are chained, // so that assemblies created for the submissions are loaded in the correct order. for (int i = scriptsReversed.Count - 1; i >= 0; i--) { executors.Add(scriptsReversed[i].CommonGetExecutor(cancellationToken)); } return executors.ToImmutableAndFree(); } /// <summary> /// Runs the script from the beginning and returns the result of the last code snippet. /// </summary> /// <param name="globals"> /// An instance of <see cref="Script.GlobalsType"/> holding on values of global variables accessible from the script. /// Must be specified if and only if the script was created with a <see cref="Script.GlobalsType"/>. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>The result of the last code snippet.</returns> internal new Task<T> EvaluateAsync(object globals = null, CancellationToken cancellationToken = default(CancellationToken)) => RunAsync(globals, cancellationToken).GetEvaluationResultAsync(); /// <summary> /// Runs the script from the beginning. /// </summary> /// <param name="globals"> /// An instance of <see cref="Script.GlobalsType"/> holding on values for global variables accessible from the script. /// Must be specified if and only if the script was created with <see cref="Script.GlobalsType"/>. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> /// <exception cref="CompilationErrorException">Compilation has errors.</exception> /// <exception cref="ArgumentException">The type of <paramref name="globals"/> doesn't match <see cref="Script.GlobalsType"/>.</exception> public new Task<ScriptState<T>> RunAsync(object globals, CancellationToken cancellationToken) => RunAsync(globals, null, cancellationToken); /// <summary> /// Runs the script from the beginning. /// </summary> /// <param name="globals"> /// An instance of <see cref="Script.GlobalsType"/> holding on values for global variables accessible from the script. /// Must be specified if and only if the script was created with <see cref="Script.GlobalsType"/>. /// </param> /// <param name="catchException"> /// If specified, any exception thrown by the script top-level code is passed to <paramref name="catchException"/>. /// If it returns true the exception is caught and stored on the resulting <see cref="ScriptState"/>, otherwise the exception is propagated to the caller. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> /// <exception cref="CompilationErrorException">Compilation has errors.</exception> /// <exception cref="ArgumentException">The type of <paramref name="globals"/> doesn't match <see cref="Script.GlobalsType"/>.</exception> public new Task<ScriptState<T>> RunAsync(object globals = null, Func<Exception, bool> catchException = null, CancellationToken cancellationToken = default(CancellationToken)) { // The following validation and executor construction may throw; // do so synchronously so that the exception is not wrapped in the task. ValidateGlobals(globals, GlobalsType); var executionState = ScriptExecutionState.Create(globals); var precedingExecutors = GetPrecedingExecutors(cancellationToken); var currentExecutor = GetExecutor(cancellationToken); return RunSubmissionsAsync(executionState, precedingExecutors, currentExecutor, catchException, cancellationToken); } /// <summary> /// Creates a delegate that will run this script from the beginning when invoked. /// </summary> /// <remarks> /// The delegate doesn't hold on this script or its compilation. /// </remarks> public ScriptRunner<T> CreateDelegate(CancellationToken cancellationToken = default(CancellationToken)) { var precedingExecutors = GetPrecedingExecutors(cancellationToken); var currentExecutor = GetExecutor(cancellationToken); var globalsType = GlobalsType; return (globals, token) => { ValidateGlobals(globals, globalsType); return ScriptExecutionState.Create(globals).RunSubmissionsAsync<T>(precedingExecutors, currentExecutor, null, null, token); }; } /// <summary> /// Run the script from the specified state. /// </summary> /// <param name="previousState"> /// Previous state of the script execution. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> /// <exception cref="ArgumentNullException"><paramref name="previousState"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="previousState"/> is not a previous execution state of this script.</exception> public new Task<ScriptState<T>> RunFromAsync(ScriptState previousState, CancellationToken cancellationToken) => RunFromAsync(previousState, null, cancellationToken); /// <summary> /// Run the script from the specified state. /// </summary> /// <param name="previousState"> /// Previous state of the script execution. /// </param> /// <param name="catchException"> /// If specified, any exception thrown by the script top-level code is passed to <paramref name="catchException"/>. /// If it returns true the exception is caught and stored on the resulting <see cref="ScriptState"/>, otherwise the exception is propagated to the caller. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running the script, including all declared variables and return value.</returns> /// <exception cref="ArgumentNullException"><paramref name="previousState"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="previousState"/> is not a previous execution state of this script.</exception> public new Task<ScriptState<T>> RunFromAsync(ScriptState previousState, Func<Exception, bool> catchException = null, CancellationToken cancellationToken = default(CancellationToken)) { // The following validation and executor construction may throw; // do so synchronously so that the exception is not wrapped in the task. if (previousState == null) { throw new ArgumentNullException(nameof(previousState)); } if (previousState.Script == this) { // this state is already the output of running this script. return Task.FromResult((ScriptState<T>)previousState); } var precedingExecutors = TryGetPrecedingExecutors(previousState.Script, cancellationToken); if (precedingExecutors.IsDefault) { throw new ArgumentException(ScriptingResources.StartingStateIncompatible, nameof(previousState)); } var currentExecutor = GetExecutor(cancellationToken); ScriptExecutionState newExecutionState = previousState.ExecutionState.FreezeAndClone(); return RunSubmissionsAsync(newExecutionState, precedingExecutors, currentExecutor, catchException, cancellationToken); } private async Task<ScriptState<T>> RunSubmissionsAsync( ScriptExecutionState executionState, ImmutableArray<Func<object[], Task>> precedingExecutors, Func<object[], Task> currentExecutor, Func<Exception, bool> catchExceptionOpt, CancellationToken cancellationToken) { var exceptionOpt = (catchExceptionOpt != null) ? new StrongBox<Exception>() : null; T result = await executionState.RunSubmissionsAsync<T>(precedingExecutors, currentExecutor, exceptionOpt, catchExceptionOpt, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); return new ScriptState<T>(executionState, this, result, exceptionOpt?.Value); } private static void ValidateGlobals(object globals, Type globalsType) { if (globalsType != null) { if (globals == null) { throw new ArgumentException(ScriptingResources.ScriptRequiresGlobalVariables, nameof(globals)); } var runtimeType = globals.GetType().GetTypeInfo(); var globalsTypeInfo = globalsType.GetTypeInfo(); if (!globalsTypeInfo.IsAssignableFrom(runtimeType)) { throw new ArgumentException(string.Format(ScriptingResources.GlobalsNotAssignable, runtimeType, globalsTypeInfo), nameof(globals)); } } else if (globals != null) { throw new ArgumentException(ScriptingResources.GlobalVariablesWithoutGlobalType, nameof(globals)); } } } }
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2011 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit wiki.developer.mindtouch.com; * please review the licensing section. * * 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.Configuration; using System.IO; using System.Reflection; using System.Web; using log4net; using MindTouch.Xml; namespace MindTouch.Dream { /// <summary> /// Fluent interface for building an <see cref="DreamApplication"/>. /// </summary> public class DreamApplicationConfigurationBuilder { //--- Class Fields --- private static readonly ILog _log = LogUtils.CreateLog(); //--- Class Methods --- /// <summary> /// Create configuration from <see cref="ConfigurationManager.AppSettings"/> and execution base path. /// </summary> /// <returns>Configuration instance.</returns> public static DreamApplicationConfigurationBuilder FromAppSettings() { var basePath = HttpContext.Current.Server.MapPath("~"); return FromAppSettings(basePath, null); } /// <summary> /// Create configuration from <see cref="ConfigurationManager.AppSettings"/> and execution base path. /// </summary> /// <param name="basePath">File system path to execution base.</param> /// <returns>Configuration instance.</returns> public static DreamApplicationConfigurationBuilder FromAppSettings(string basePath) { return FromAppSettings(basePath, null); } /// <summary> /// Create configuration from <see cref="ConfigurationManager.AppSettings"/>, execution base path and storage path. /// </summary> /// <param name="basePath">File system path to execution base.</param> /// <param name="storagePath">File sytem path to where the host should keep it's local storage.</param> /// <returns>Configuration instance.</returns> public static DreamApplicationConfigurationBuilder FromAppSettings(string basePath, string storagePath) { var config = new DreamApplicationConfiguration(); var settings = ConfigurationManager.AppSettings; var debugSetting = settings["dream.env.debug"] ?? "debugger-only"; if(string.IsNullOrEmpty(storagePath)) { storagePath = settings["dream.storage.path"] ?? settings["storage-dir"] ?? Path.Combine(basePath, "App_Data"); } if(string.IsNullOrEmpty(storagePath)) { storagePath = Path.Combine(basePath, "storage"); } else if(!Path.IsPathRooted(storagePath)) { storagePath = Path.Combine(basePath, storagePath); } var guid = settings["dream.guid"] ?? settings["guid"]; var hostPath = settings["dream.host.path"] ?? settings["host-path"]; config.Apikey = settings["dream.apikey"] ?? settings["apikey"] ?? StringUtil.CreateAlphaNumericKey(8); config.HostConfig = new XDoc("config") .Elem("guid", guid) .Elem("storage-dir", storagePath) .Elem("host-path", hostPath) .Elem("connect-limit", settings["connect-limit"]) .Elem("apikey", config.Apikey) .Elem("debug", debugSetting); var rootRedirect = settings["dream.root.redirect"]; if(!string.IsNullOrEmpty(rootRedirect)) { config.HostConfig.Elem("root-redirect", rootRedirect); } config.ServicesDirectory = settings["dream.service.path"] ?? settings["service-dir"] ?? Path.Combine("bin", "services"); if(!Path.IsPathRooted(config.ServicesDirectory)) { config.ServicesDirectory = Path.Combine(basePath, config.ServicesDirectory); } return new DreamApplicationConfigurationBuilder(config); } /// <summary> /// Create a new default configuration builder, i.e. not pre-initialized with external settings. /// </summary> /// <returns>New configuration instance.</returns> public static DreamApplicationConfigurationBuilder Create() { return new DreamApplicationConfigurationBuilder(new DreamApplicationConfiguration()); } //--- Fields --- private Assembly _assembly; private readonly DreamApplicationConfiguration _configuration; private DreamServiceRegistrationBuilder _serviceRegistrationBuilder; //--- Constructors --- private DreamApplicationConfigurationBuilder(DreamApplicationConfiguration configuration) { _configuration = configuration; } //--- Methods --- /// <summary> /// Defined the master apikey for the application. /// </summary> /// <param name="apikey">Api key</param> /// <returns>Current builder instance.</returns> public DreamApplicationConfigurationBuilder WithApikey(string apikey) { _configuration.Apikey = apikey; return this; } /// <summary> /// Define the directory to scan for <see cref="IDreamService"/> types. /// </summary> /// <param name="servicesDirectory">Absolute path to directory containing assemblies with service types.</param> /// <returns>Current builder instance.</returns> public DreamApplicationConfigurationBuilder WithServicesDirectory(string servicesDirectory) { _configuration.ServicesDirectory = servicesDirectory; return this; } /// <summary> /// Define the <see cref="DreamHostService"/> xml configuration. /// </summary> /// <param name="hostConfig"></param> /// <returns>Current builder instance.</returns> public DreamApplicationConfigurationBuilder WithHostConfig(XDoc hostConfig) { _configuration.HostConfig = hostConfig; return this; } /// <summary> /// Attach the <see cref="HttpApplication"/> that the <see cref="DreamApplication"/> to be built will be attached to. /// </summary> /// <param name="application">HttpApplication to attach to.</param> /// <returns>Current builder instance.</returns> public DreamApplicationConfigurationBuilder ForHttpApplication(HttpApplication application) { return WithApplicationAssembly(application.GetType().BaseType.Assembly); } /// <summary> /// Add a service configuration. /// </summary> /// <param name="configurationCallback">Service configuration callback.</param> /// <returns>Current builder instance.</returns> public DreamApplicationConfigurationBuilder WithServiceConfiguration(Action<DreamServiceRegistrationBuilder> configurationCallback) { if(_serviceRegistrationBuilder == null) { _serviceRegistrationBuilder = new DreamServiceRegistrationBuilder(); } configurationCallback(_serviceRegistrationBuilder); return this; } /// <summary> /// Attach the assembly to scan for services by the conventions of <see cref="DreamServiceRegistrationBuilder.ScanAssemblyForServices(System.Reflection.Assembly)"/> /// </summary> /// <remarks> /// By default, the assembly that the HttpApplication lives in will be scanned. /// </remarks> /// <param name="assembly">Service assembly.</param> /// <returns>Current builder instance.</returns> public DreamApplicationConfigurationBuilder WithApplicationAssembly(Assembly assembly) { _assembly = assembly; return this; } /// <summary> /// Provide an assembly scanning filter. /// </summary> /// <param name="filter">Filter callback.</param> /// <returns>Current builder instance.</returns> public DreamApplicationConfigurationBuilder WithFilteredAssemblyServices(Func<Type, bool> filter) { if(_assembly == null) { throw new ArgumentException("Builder does not have an assembly to scan"); } WithServiceConfiguration(builder => builder.ScanAssemblyForServices(_assembly, filter)); return this; } /// <summary> /// Set the path prefix for the application. /// </summary> /// <param name="prefix">Path prefix.</param> /// <returns>Current builder instance.</returns> public DreamApplicationConfigurationBuilder WithPathPrefix(string prefix) { _configuration.Prefix = prefix; return this; } /// <summary> /// Create the new <see cref="DreamApplication"/> inside the <see cref="HttpApplication"/>. /// </summary> /// <returns>Application instance.</returns> public DreamApplication CreateApplication() { return DreamApplication.Create(Build()); } internal DreamApplicationConfiguration Build() { if(_serviceRegistrationBuilder == null) { WithFilteredAssemblyServices(t => true); } _configuration.Script = _serviceRegistrationBuilder.Build(); return _configuration; } } }
using System; using System.IO; using SharpCompress.IO; namespace SharpCompress.Common.Rar.Headers { internal class FileHeader : RarHeader { private const byte SALT_SIZE = 8; private const byte NEWLHD_SIZE = 32; protected override void ReadFromReader(MarkingBinaryReader reader) { uint lowUncompressedSize = reader.ReadUInt32(); HostOS = (HostOS)reader.ReadByte(); FileCRC = reader.ReadUInt32(); FileLastModifiedTime = Utility.DosDateToDateTime(reader.ReadInt32()); RarVersion = reader.ReadByte(); PackingMethod = reader.ReadByte(); short nameSize = reader.ReadInt16(); FileAttributes = reader.ReadInt32(); uint highCompressedSize = 0; uint highUncompressedkSize = 0; if (FlagUtility.HasFlag(FileFlags, FileFlags.LARGE)) { highCompressedSize = reader.ReadUInt32(); highUncompressedkSize = reader.ReadUInt32(); } else { if (lowUncompressedSize == 0xffffffff) { lowUncompressedSize = 0xffffffff; highUncompressedkSize = int.MaxValue; } } CompressedSize = UInt32To64(highCompressedSize, AdditionalSize); UncompressedSize = UInt32To64(highUncompressedkSize, lowUncompressedSize); nameSize = nameSize > 4 * 1024 ? (short)(4 * 1024) : nameSize; byte[] fileNameBytes = reader.ReadBytes(nameSize); switch (HeaderType) { case HeaderType.FileHeader: { if (FlagUtility.HasFlag(FileFlags, FileFlags.UNICODE)) { int length = 0; while (length < fileNameBytes.Length && fileNameBytes[length] != 0) { length++; } if (length != nameSize) { length++; FileName = FileNameDecoder.Decode(fileNameBytes, length); } else { FileName = DecodeDefault(fileNameBytes); } } else { FileName = DecodeDefault(fileNameBytes); } FileName = ConvertPath(FileName, HostOS); } break; case HeaderType.NewSubHeader: { int datasize = HeaderSize - NEWLHD_SIZE - nameSize; if (FlagUtility.HasFlag(FileFlags, FileFlags.SALT)) { datasize -= SALT_SIZE; } if (datasize > 0) { SubData = reader.ReadBytes(datasize); } if (NewSubHeaderType.SUBHEAD_TYPE_RR.Equals(fileNameBytes)) { RecoverySectors = SubData[8] + (SubData[9] << 8) + (SubData[10] << 16) + (SubData[11] << 24); } } break; } if (FlagUtility.HasFlag(FileFlags, FileFlags.SALT)) { Salt = reader.ReadBytes(SALT_SIZE); } if (FlagUtility.HasFlag(FileFlags, FileFlags.EXTTIME)) { // verify that the end of the header hasn't been reached before reading the Extended Time. // some tools incorrectly omit Extended Time despite specifying FileFlags.EXTTIME, which most parsers tolerate. if (ReadBytes + reader.CurrentReadByteCount <= HeaderSize - 2) { ushort extendedFlags = reader.ReadUInt16(); FileLastModifiedTime = ProcessExtendedTime(extendedFlags, FileLastModifiedTime, reader, 0); FileCreatedTime = ProcessExtendedTime(extendedFlags, null, reader, 1); FileLastAccessedTime = ProcessExtendedTime(extendedFlags, null, reader, 2); FileArchivedTime = ProcessExtendedTime(extendedFlags, null, reader, 3); } } } //only the full .net framework will do other code pages than unicode/utf8 private string DecodeDefault(byte[] bytes) { return ArchiveEncoding.Default.GetString(bytes, 0, bytes.Length); } private long UInt32To64(uint x, uint y) { long l = x; l <<= 32; return l + y; } private static DateTime? ProcessExtendedTime(ushort extendedFlags, DateTime? time, MarkingBinaryReader reader, int i) { uint rmode = (uint)extendedFlags >> (3 - i) * 4; if ((rmode & 8) == 0) { return null; } if (i != 0) { uint DosTime = reader.ReadUInt32(); time = Utility.DosDateToDateTime(DosTime); } if ((rmode & 4) == 0) { time = time.Value.AddSeconds(1); } uint nanosecondHundreds = 0; int count = (int)rmode & 3; for (int j = 0; j < count; j++) { byte b = reader.ReadByte(); nanosecondHundreds |= (((uint)b) << ((j + 3 - count) * 8)); } //10^-7 to 10^-3 return time.Value.AddMilliseconds(nanosecondHundreds * Math.Pow(10, -4)); } private static string ConvertPath(string path, HostOS os) { #if PORTABLE || NETFX_CORE return path.Replace('\\', '/'); #else switch (os) { case HostOS.MacOS: case HostOS.Unix: { if (Path.DirectorySeparatorChar == '\\') { return path.Replace('/', '\\'); } } break; default: { if (Path.DirectorySeparatorChar == '/') { return path.Replace('\\', '/'); } } break; } return path; #endif } internal long DataStartPosition { get; set; } internal HostOS HostOS { get; private set; } internal uint FileCRC { get; private set; } internal DateTime? FileLastModifiedTime { get; private set; } internal DateTime? FileCreatedTime { get; private set; } internal DateTime? FileLastAccessedTime { get; private set; } internal DateTime? FileArchivedTime { get; private set; } internal byte RarVersion { get; private set; } internal byte PackingMethod { get; private set; } internal int FileAttributes { get; private set; } internal FileFlags FileFlags { get { return (FileFlags)base.Flags; } } internal long CompressedSize { get; private set; } internal long UncompressedSize { get; private set; } internal string FileName { get; private set; } internal byte[] SubData { get; private set; } internal int RecoverySectors { get; private set; } internal byte[] Salt { get; private set; } public override string ToString() { return FileName; } public Stream PackedStream { get; set; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules { public class SunModule : ISunModule { /// <summary> /// Note: Sun Hour can be a little deceaving. Although it's based on a 24 hour clock /// it is not based on ~06:00 == Sun Rise. Rather it is based on 00:00 being sun-rise. /// </summary> private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // // Global Constants used to determine where in the sky the sun is // private const double m_SeasonalTilt = 0.03 * Math.PI; // A daily shift of approximately 1.7188 degrees private const double m_AverageTilt = -0.25 * Math.PI; // A 45 degree tilt private const double m_SunCycle = 2.0D * Math.PI; // A perfect circle measured in radians private const double m_SeasonalCycle = 2.0D * Math.PI; // Ditto // // Per Region Values // private bool ready = false; // This solves a chick before the egg problem // the local SunFixedHour and SunFixed variables MUST be updated // at least once with the proper Region Settings before we start // updating those region settings in GenSunPos() private bool receivedEstateToolsSunUpdate = false; // Configurable values private string m_RegionMode = "SL"; // Sun's position information is updated and sent to clients every m_UpdateInterval frames private int m_UpdateInterval = 0; // Number of real time hours per virtual day private double m_DayLengthHours = 0; // Number of virtual days to a virtual year private int m_YearLengthDays = 0; // Ratio of Daylight hours to Night time hours. This is accomplished by shifting the // sun's orbit above the horizon private double m_HorizonShift = 0; // Used to scale current and positional time to adjust length of an hour during day vs night. private double m_DayTimeSunHourScale; // private double m_longitude = 0; // private double m_latitude = 0; // Configurable defaults Defaults close to SL private string d_mode = "SL"; private int d_frame_mod = 100; // Every 10 seconds (actually less) private double d_day_length = 4; // A VW day is 4 RW hours long private int d_year_length = 60; // There are 60 VW days in a VW year private double d_day_night = 0.5; // axis offset: Default Hoizon shift to try and closely match the sun model in LL Viewer private double d_DayTimeSunHourScale = 0.5; // Day/Night hours are equal // private double d_longitude = -73.53; // private double d_latitude = 41.29; // Frame counter private uint m_frame = 0; // Cached Scene reference private Scene m_scene = null; // Calculated Once in the lifetime of a region private long TicksToEpoch; // Elapsed time for 1/1/1970 private uint SecondsPerSunCycle; // Length of a virtual day in RW seconds private uint SecondsPerYear; // Length of a virtual year in RW seconds private double SunSpeed; // Rate of passage in radians/second private double SeasonSpeed; // Rate of change for seasonal effects // private double HoursToRadians; // Rate of change for seasonal effects private long TicksUTCOffset = 0; // seconds offset from UTC // Calculated every update private float OrbitalPosition; // Orbital placement at a point in time private double HorizonShift; // Axis offset to skew day and night private double TotalDistanceTravelled; // Distance since beginning of time (in radians) private double SeasonalOffset; // Seaonal variation of tilt private float Magnitude; // Normal tilt // private double VWTimeRatio; // VW time as a ratio of real time // Working values private Vector3 Position = Vector3.Zero; private Vector3 Velocity = Vector3.Zero; private Quaternion Tilt = new Quaternion(1.0f, 0.0f, 0.0f, 0.0f); // Used to fix the sun in the sky so it doesn't move based on current time private bool m_SunFixed = false; private float m_SunFixedHour = 0f; private const int TICKS_PER_SECOND = 10000000; // Current time in elapsed seconds since Jan 1st 1970 private ulong CurrentTime { get { return (ulong)(((DateTime.Now.Ticks) - TicksToEpoch + TicksUTCOffset) / TICKS_PER_SECOND); } } // Time in seconds since UTC to use to calculate sun position. ulong PosTime = 0; /// <summary> /// Calculate the sun's orbital position and its velocity. /// </summary> private void GenSunPos() { // Time in seconds since UTC to use to calculate sun position. PosTime = CurrentTime; if (m_SunFixed) { // SunFixedHour represents the "hour of day" we would like // It's represented in 24hr time, with 0 hour being sun-rise // Because our day length is probably not 24hrs {LL is 6} we need to do a bit of math // Determine the current "day" from current time, so we can use "today" // to determine Seasonal Tilt and what'not // Integer math rounded is on purpose to drop fractional day, determines number // of virtual days since Epoch PosTime = CurrentTime / SecondsPerSunCycle; // Since we want number of seconds since Epoch, multiply back up PosTime *= SecondsPerSunCycle; // Then offset by the current Fixed Sun Hour // Fixed Sun Hour needs to be scaled to reflect the user configured Seconds Per Sun Cycle PosTime += (ulong)((m_SunFixedHour / 24.0) * (ulong)SecondsPerSunCycle); } else { if (m_DayTimeSunHourScale != 0.5f) { ulong CurDaySeconds = CurrentTime % SecondsPerSunCycle; double CurDayPercentage = (double)CurDaySeconds / SecondsPerSunCycle; ulong DayLightSeconds = (ulong)(m_DayTimeSunHourScale * SecondsPerSunCycle); ulong NightSeconds = SecondsPerSunCycle - DayLightSeconds; PosTime = CurrentTime / SecondsPerSunCycle; PosTime *= SecondsPerSunCycle; if (CurDayPercentage < 0.5) { PosTime += (ulong)((CurDayPercentage / .5) * DayLightSeconds); } else { PosTime += DayLightSeconds; PosTime += (ulong)(((CurDayPercentage - 0.5) / .5) * NightSeconds); } } } TotalDistanceTravelled = SunSpeed * PosTime; // distance measured in radians OrbitalPosition = (float)(TotalDistanceTravelled % m_SunCycle); // position measured in radians // TotalDistanceTravelled += HoursToRadians-(0.25*Math.PI)*Math.Cos(HoursToRadians)-OrbitalPosition; // OrbitalPosition = (float) (TotalDistanceTravelled%SunCycle); SeasonalOffset = SeasonSpeed * PosTime; // Present season determined as total radians travelled around season cycle Tilt.W = (float)(m_AverageTilt + (m_SeasonalTilt * Math.Sin(SeasonalOffset))); // Calculate seasonal orbital N/S tilt // m_log.Debug("[SUN] Total distance travelled = "+TotalDistanceTravelled+", present position = "+OrbitalPosition+"."); // m_log.Debug("[SUN] Total seasonal progress = "+SeasonalOffset+", present tilt = "+Tilt.W+"."); // The sun rotates about the Z axis Position.X = (float)Math.Cos(-TotalDistanceTravelled); Position.Y = (float)Math.Sin(-TotalDistanceTravelled); Position.Z = 0; // For interest we rotate it slightly about the X access. // Celestial tilt is a value that ranges .025 Position *= Tilt; // Finally we shift the axis so that more of the // circle is above the horizon than below. This // makes the nights shorter than the days. Position = Vector3.Normalize(Position); Position.Z = Position.Z + (float)HorizonShift; Position = Vector3.Normalize(Position); // m_log.Debug("[SUN] Position("+Position.X+","+Position.Y+","+Position.Z+")"); Velocity.X = 0; Velocity.Y = 0; Velocity.Z = (float)SunSpeed; // Correct angular velocity to reflect the seasonal rotation Magnitude = Position.Length(); if (m_SunFixed) { Velocity.X = 0; Velocity.Y = 0; Velocity.Z = 0; } else { Velocity = (Velocity * Tilt) * (1.0f / Magnitude); } // TODO: Decouple this, so we can get rid of Linden Hour info // Update Region infor with new Sun Position and Hour // set estate settings for region access to sun position if (receivedEstateToolsSunUpdate) { m_scene.RegionInfo.RegionSettings.SunVector = Position; m_scene.RegionInfo.RegionSettings.SunPosition = GetCurrentTimeAsLindenSunHour(); } } private float GetCurrentTimeAsLindenSunHour() { if (m_SunFixed) return m_SunFixedHour + 6; return GetCurrentSunHour() + 6.0f; } #region IRegion Methods // Called immediately after the module is loaded for a given region // i.e. Immediately after instance creation. public void Initialise(Scene scene, IConfigSource config) { m_scene = scene; m_frame = 0; // This one puts an entry in the main help screen m_scene.AddCommand(this, String.Empty, "sun", "Usage: sun [param] [value] - Get or Update Sun module paramater", null); // This one enables the ability to type just "sun" without any parameters m_scene.AddCommand(this, "sun", "", "", HandleSunConsoleCommand); foreach (KeyValuePair<string, string> kvp in GetParamList()) { m_scene.AddCommand(this, String.Format("sun {0}", kvp.Key), String.Format("{0} - {1}", kvp.Key, kvp.Value), "", HandleSunConsoleCommand); } TimeZone local = TimeZone.CurrentTimeZone; TicksUTCOffset = local.GetUtcOffset(local.ToLocalTime(DateTime.Now)).Ticks; m_log.Debug("[SUN]: localtime offset is " + TicksUTCOffset); // Align ticks with Second Life TicksToEpoch = new DateTime(1970, 1, 1).Ticks; // Just in case they don't have the stanzas try { // Mode: determines how the sun is handled m_RegionMode = config.Configs["Sun"].GetString("mode", d_mode); // Mode: determines how the sun is handled // m_latitude = config.Configs["Sun"].GetDouble("latitude", d_latitude); // Mode: determines how the sun is handled // m_longitude = config.Configs["Sun"].GetDouble("longitude", d_longitude); // Year length in days m_YearLengthDays = config.Configs["Sun"].GetInt("year_length", d_year_length); // Day length in decimal hours m_DayLengthHours = config.Configs["Sun"].GetDouble("day_length", d_day_length); // Horizon shift, this is used to shift the sun's orbit, this affects the day / night ratio // must hard code to ~.5 to match sun position in LL based viewers m_HorizonShift = config.Configs["Sun"].GetDouble("day_night_offset", d_day_night); // Scales the sun hours 0...12 vs 12...24, essentially makes daylight hours longer/shorter vs nighttime hours m_DayTimeSunHourScale = config.Configs["Sun"].GetDouble("day_time_sun_hour_scale", d_DayTimeSunHourScale); // Update frequency in frames m_UpdateInterval = config.Configs["Sun"].GetInt("update_interval", d_frame_mod); } catch (Exception e) { m_log.Debug("[SUN]: Configuration access failed, using defaults. Reason: " + e.Message); m_RegionMode = d_mode; m_YearLengthDays = d_year_length; m_DayLengthHours = d_day_length; m_HorizonShift = d_day_night; m_UpdateInterval = d_frame_mod; m_DayTimeSunHourScale = d_DayTimeSunHourScale; // m_latitude = d_latitude; // m_longitude = d_longitude; } switch (m_RegionMode) { case "T1": default: case "SL": // Time taken to complete a cycle (day and season) SecondsPerSunCycle = (uint) (m_DayLengthHours * 60 * 60); SecondsPerYear = (uint) (SecondsPerSunCycle*m_YearLengthDays); // Ration of real-to-virtual time // VWTimeRatio = 24/m_day_length; // Speed of rotation needed to complete a cycle in the // designated period (day and season) SunSpeed = m_SunCycle/SecondsPerSunCycle; SeasonSpeed = m_SeasonalCycle/SecondsPerYear; // Horizon translation HorizonShift = m_HorizonShift; // Z axis translation // HoursToRadians = (SunCycle/24)*VWTimeRatio; // Insert our event handling hooks scene.EventManager.OnFrame += SunUpdate; scene.EventManager.OnAvatarEnteringNewParcel += AvatarEnteringParcel; scene.EventManager.OnEstateToolsSunUpdate += EstateToolsSunUpdate; scene.EventManager.OnGetCurrentTimeAsLindenSunHour += GetCurrentTimeAsLindenSunHour; ready = true; m_log.Debug("[SUN]: Mode is " + m_RegionMode); m_log.Debug("[SUN]: Initialization completed. Day is " + SecondsPerSunCycle + " seconds, and year is " + m_YearLengthDays + " days"); m_log.Debug("[SUN]: Axis offset is " + m_HorizonShift); m_log.Debug("[SUN]: Percentage of time for daylight " + m_DayTimeSunHourScale); m_log.Debug("[SUN]: Positional data updated every " + m_UpdateInterval + " frames"); break; } scene.RegisterModuleInterface<ISunModule>(this); } public void PostInitialise() { } public void Close() { ready = false; // Remove our hooks m_scene.EventManager.OnFrame -= SunUpdate; m_scene.EventManager.OnAvatarEnteringNewParcel -= AvatarEnteringParcel; m_scene.EventManager.OnEstateToolsSunUpdate -= EstateToolsSunUpdate; m_scene.EventManager.OnGetCurrentTimeAsLindenSunHour -= GetCurrentTimeAsLindenSunHour; } public string Name { get { return "SunModule"; } } public bool IsSharedModule { get { return false; } } #endregion #region EventManager Events public void SunToClient(IClientAPI client) { if (m_RegionMode != "T1") { if (ready) { if (m_SunFixed) { // m_log.DebugFormat("[SUN]: SunHour {0}, Position {1}, PosTime {2}, OrbitalPosition : {3} ", m_SunFixedHour, Position.ToString(), PosTime.ToString(), OrbitalPosition.ToString()); client.SendSunPos(Position, Velocity, PosTime, SecondsPerSunCycle, SecondsPerYear, OrbitalPosition); } else { // m_log.DebugFormat("[SUN]: SunHour {0}, Position {1}, PosTime {2}, OrbitalPosition : {3} ", m_SunFixedHour, Position.ToString(), PosTime.ToString(), OrbitalPosition.ToString()); client.SendSunPos(Position, Velocity, CurrentTime, SecondsPerSunCycle, SecondsPerYear, OrbitalPosition); } } } } public void SunUpdate() { if (((m_frame++ % m_UpdateInterval) != 0) || !ready || m_SunFixed || !receivedEstateToolsSunUpdate) return; GenSunPos(); // Generate shared values once SunUpdateToAllClients(); } /// <summary> /// When an avatar enters the region, it's probably a good idea to send them the current sun info /// </summary> /// <param name="avatar"></param> /// <param name="localLandID"></param> /// <param name="regionID"></param> private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, UUID regionID) { SunToClient(avatar.ControllingClient); } /// <summary> /// /// </summary> /// <param name="regionHandle"></param> /// <param name="FixedTime">Is the sun's position fixed?</param> /// <param name="useEstateTime">Use the Region or Estate Sun hour?</param> /// <param name="FixedSunHour">What hour of the day is the Sun Fixed at?</param> public void EstateToolsSunUpdate(ulong regionHandle, bool FixedSun, bool useEstateTime, float FixedSunHour) { if (m_scene.RegionInfo.RegionHandle == regionHandle) { // Must limit the Sun Hour to 0 ... 24 while (FixedSunHour > 24.0f) FixedSunHour -= 24; while (FixedSunHour < 0) FixedSunHour += 24; m_SunFixedHour = FixedSunHour; m_SunFixed = FixedSun; m_log.DebugFormat("[SUN]: Sun Settings Update: Fixed Sun? : {0}", m_SunFixed.ToString()); m_log.DebugFormat("[SUN]: Sun Settings Update: Sun Hour : {0}", m_SunFixedHour.ToString()); receivedEstateToolsSunUpdate = true; // Generate shared values GenSunPos(); // When sun settings are updated, we should update all clients with new settings. SunUpdateToAllClients(); m_log.DebugFormat("[SUN]: PosTime : {0}", PosTime.ToString()); } } #endregion private void SunUpdateToAllClients() { m_scene.ForEachScenePresence(delegate(ScenePresence sp) { if (!sp.IsChildAgent) { SunToClient(sp.ControllingClient); } }); } #region ISunModule Members public double GetSunParameter(string param) { switch (param.ToLower()) { case "year_length": return m_YearLengthDays; case "day_length": return m_DayLengthHours; case "day_night_offset": return m_HorizonShift; case "day_time_sun_hour_scale": return m_DayTimeSunHourScale; case "update_interval": return m_UpdateInterval; default: throw new Exception("Unknown sun parameter."); } } public void SetSunParameter(string param, double value) { HandleSunConsoleCommand("sun", new string[] {param, value.ToString() }); } public float GetCurrentSunHour() { float ticksleftover = CurrentTime % SecondsPerSunCycle; return (24.0f * (ticksleftover / SecondsPerSunCycle)); } #endregion public void HandleSunConsoleCommand(string module, string[] cmdparams) { if (m_scene.ConsoleScene() == null) { // FIXME: If console region is root then this will be printed by every module. Currently, there is no // way to prevent this, short of making the entire module shared (which is complete overkill). // One possibility is to return a bool to signal whether the module has completely handled the command m_log.InfoFormat("[Sun]: Please change to a specific region in order to set Sun parameters."); return; } if (m_scene.ConsoleScene() != m_scene) { m_log.InfoFormat("[Sun]: Console Scene is not my scene."); return; } m_log.InfoFormat("[Sun]: Processing command."); foreach (string output in ParseCmdParams(cmdparams)) { m_log.Info("[SUN] " + output); } } private Dictionary<string, string> GetParamList() { Dictionary<string, string> Params = new Dictionary<string, string>(); Params.Add("year_length", "number of days to a year"); Params.Add("day_length", "number of seconds to a day"); Params.Add("day_night_offset", "induces a horizon shift"); Params.Add("update_interval", "how often to update the sun's position in frames"); Params.Add("day_time_sun_hour_scale", "scales day light vs nite hours to change day/night ratio"); return Params; } private List<string> ParseCmdParams(string[] args) { List<string> Output = new List<string>(); if ((args.Length == 1) || (args[1].ToLower() == "help") || (args[1].ToLower() == "list")) { Output.Add("The following parameters can be changed or viewed:"); foreach (KeyValuePair<string, string> kvp in GetParamList()) { Output.Add(String.Format("{0} - {1}",kvp.Key, kvp.Value)); } return Output; } if (args.Length == 2) { try { double value = GetSunParameter(args[1]); Output.Add(String.Format("Parameter {0} is {1}.", args[1], value.ToString())); } catch (Exception) { Output.Add(String.Format("Unknown parameter {0}.", args[1])); } } else if (args.Length == 3) { float value = 0.0f; if (!float.TryParse(args[2], out value)) { Output.Add(String.Format("The parameter value {0} is not a valid number.", args[2])); } switch (args[1].ToLower()) { case "year_length": m_YearLengthDays = (int)value; break; case "day_length": m_DayLengthHours = value; break; case "day_night_offset": m_HorizonShift = value; break; case "day_time_sun_hour_scale": m_DayTimeSunHourScale = value; break; case "update_interval": m_UpdateInterval = (int)value; break; default: Output.Add(String.Format("Unknown parameter {0}.", args[1])); return Output; } Output.Add(String.Format("Parameter {0} set to {1}.", args[1], value.ToString())); // Generate shared values GenSunPos(); // When sun settings are updated, we should update all clients with new settings. SunUpdateToAllClients(); } return Output; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Android.App; using Android.Content; using Android.Content.PM; using Android.Graphics; using Android.OS; using Android.Views; using Android.Widget; using NuGetSearch.Common; namespace NuGetSearch.Android { /// <summary> /// Package detail activity. /// </summary> [Activity(Label = "NuGet Package Detail", ConfigurationChanges = ConfigChanges.Orientation)] public class PackageDetailActivity : Activity { private INuGetGalleryClient nugetGalleryClient; private INetworkChecker networkChecker; /// <summary> /// Initializes a new instance of the <see cref="NuGetSearch.Android.PackageDetailActivity"/> class. /// </summary> public PackageDetailActivity() : base() { this.nugetGalleryClient = new NuGetGalleryClient(new NetworkProvider()); this.networkChecker = new AndroidNetworkChecker(this); } /// <summary> /// Adds menu items to the menu for this activity /// </summary> /// <returns>base OnCreateOptionsMenu return value</returns> /// <param name="menu">The menu for this activity</param> public override bool OnCreateOptionsMenu(IMenu menu) { this.MenuInflater.Inflate(Resource.Menu.PackageDetailMenu, menu); return base.OnCreateOptionsMenu(menu); } /// <summary> /// Handles menu item selection events /// </summary> /// <returns>base OnOptionsItemSelected return value</returns> /// <param name="item">The selected menu item</param> public override bool OnOptionsItemSelected(IMenuItem item) { switch (item.ItemId) { case Resource.Id.newSearchMenu: var searchIntent = new Intent(this, typeof(SearchActivity)); searchIntent.AddFlags(ActivityFlags.ClearTop); this.StartActivity(searchIntent); break; } return base.OnOptionsItemSelected(item); } /// <summary> /// Activity Creation /// </summary> /// <param name="bundle"></param> protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); this.SetContentView(Resource.Layout.PackageDetail); // Get the id and title values from the intent string extraId = Intent.GetStringExtra("id"); string extraTitle = Intent.GetStringExtra("title"); // Display the package details using the specified id and title this.DisplayPackageDetailsAsync(extraId, extraTitle); } /// <summary> /// Displays the package details /// </summary> /// <returns>Task</returns> /// <param name="packageUrl">The url of the package to display</param> /// <param name="title">The title of the package to display</param> private Task DisplayPackageDetailsAsync(string packageUrl, string title) { // Check if there is network connectivity, an if there is not, then return if (!this.networkChecker.ValidateNetworkConnectivity()) { return Task.Run(() => { }); } // Show the progress dialog ProgressDialog progressDialog = ProgressDialog.Show(this, null, Resources.GetString(Resource.String.wait_loading), true); return Task.Run(() => { try { // If the package url was not specified, then retrieve the package url of the latest version based on the title if (string.IsNullOrEmpty(packageUrl)) { packageUrl = nugetGalleryClient.GetPackageLatestIdAsync(title).Result; } // Retrieve package details var pd = nugetGalleryClient.GetPackageDetailAsync(packageUrl).Result; // Display the package details RunOnUiThread(() => { this.DisplayPackageDetails(pd); }); // Retrieve the version history var history = nugetGalleryClient.GetPackageHistoryAsync(pd.Title).Result; // Display the version history RunOnUiThread(() => { this.DisplayVersionHistory(pd.Id, history); }); } finally { // Hide the progress dialog RunOnUiThread(() => { progressDialog.Dismiss(); progressDialog.Dispose(); }); } }); } /// <summary> /// Displays the specified icon /// </summary> /// <param name="url">The url of the icon to display</param> private void DisplayIcon(string url) { var iconImageView = FindViewById<ImageView>(Resource.Id.icon); // Check if the icon manager has finished loading the bitmap or not if (AndroidIconManager.Current.IsLoaded(url)) { // If the icon manager has loaded the bitmap, then get it Bitmap icon = AndroidIconManager.Current.GetIcon(url); if (icon == null) { // If the bitmap failed to load, then set the default icon image iconImageView.SetImageResource(Resource.Drawable.packageDefaultIcon); } else { // If the bitmap was loaded successfully, then set the bitmap image try { iconImageView.SetImageBitmap(icon); } catch { iconImageView.SetImageResource(Resource.Drawable.packageDefaultIcon); } } } else { // If the icon manager has not finished loading the bitmap, then set the default icon image for now iconImageView.SetImageResource(Resource.Drawable.packageDefaultIcon); } } /// <summary> /// Displays the package details /// </summary> /// <param name="pd">The package details to display</param> private void DisplayPackageDetails(PackageDetail pd) { // Set default icon image until the real icon can be loaded FindViewById<ImageView>(Resource.Id.icon).SetImageResource(Resource.Drawable.packageDefaultIcon); // Tell the icon manager to load the icon AndroidIconManager.Current.Load(pd.IconUrl, x => { RunOnUiThread(() => { this.DisplayIcon(x); }); }); // Populate the header fields (title and version) FindViewById<TextView>(Resource.Id.title).Text = pd.DisplayTitle; FindViewById<TextView>(Resource.Id.version).Text = pd.Version; // Show the header layout FindViewById<RelativeLayout>(Resource.Id.headerLayout).Visibility = ViewStates.Visible; // Check if this package is prerelease and if so, show the prerelease indicator FindViewById<TextView>(Resource.Id.prerelease).Visibility = pd.IsPrerelease ? ViewStates.Visible : ViewStates.Gone; // Populate the description FindViewById<TextView>(Resource.Id.description).Text = pd.Description; // Display project site link, license link, authors, tags, and dependencies list this.DisplayProjectSite(pd); this.DisplayLicense(pd); this.DisplayAuthors(pd); this.DisplayTags(pd); this.DisplayDependencies(pd); // Show the detail layout FindViewById<ScrollView>(Resource.Id.detailLayout).Visibility = ViewStates.Visible; } /// <summary> /// Displays the project site link from the specified package details /// </summary> /// <param name="pd"></param> private void DisplayProjectSite(PackageDetail pd) { var projectSiteCaptionTextView = FindViewById<TextView>(Resource.Id.projectSiteCaption); var projectSiteTextView = FindViewById<TextView>(Resource.Id.projectSite); // Show/hide the project site caption projectSiteCaptionTextView.Visibility = string.IsNullOrEmpty(pd.ProjectUrl) ? ViewStates.Gone : ViewStates.Visible; // Populate and show/hide the project site projectSiteTextView.Text = pd.ProjectUrl; projectSiteTextView.Visibility = string.IsNullOrEmpty(pd.ProjectUrl) ? ViewStates.Gone : ViewStates.Visible; } /// <summary> /// Displays the license link from the specified package details /// </summary> /// <param name="pd"></param> private void DisplayLicense(PackageDetail pd) { var licenseCaptionTextView = FindViewById<TextView>(Resource.Id.licenseCaption); var licenseTextView = FindViewById<TextView>(Resource.Id.license); // Show/hide the license caption licenseCaptionTextView.Visibility = string.IsNullOrEmpty(pd.LicenseUrl) ? ViewStates.Gone : ViewStates.Visible; // Populate and show/hide the license licenseTextView.Text = pd.LicenseUrl; licenseTextView.Visibility = string.IsNullOrEmpty(pd.LicenseUrl) ? ViewStates.Gone : ViewStates.Visible; } /// <summary> /// Displays the authors for the specified package details /// </summary> /// <param name="pd"></param> private void DisplayAuthors(PackageDetail pd) { var authorsCaptionTextView = FindViewById<TextView>(Resource.Id.authorsCaption); var authorsTextView = FindViewById<TextView>(Resource.Id.authors); // Populate and show/hide the authors caption and authors if (pd.Authors.Any()) { authorsCaptionTextView.Visibility = ViewStates.Visible; authorsTextView.Text = string.Join(", ", pd.Authors.ToArray()); authorsTextView.Visibility = ViewStates.Visible; } else { authorsCaptionTextView.Visibility = ViewStates.Gone; authorsTextView.Text = string.Empty; authorsTextView.Visibility = ViewStates.Gone; } } /// <summary> /// Displays the tags for the specified package details /// </summary> /// <param name="pd"></param> private void DisplayTags(PackageDetail pd) { var tagsCaptionTextView = FindViewById<TextView>(Resource.Id.tagsCaption); var tagsTextView = FindViewById<TextView>(Resource.Id.tags); // Populate and show/hide the tags caption and tags if (pd.Tags.Any()) { tagsCaptionTextView.Visibility = ViewStates.Visible; tagsTextView.Text = string.Join(", ", pd.Tags.ToArray()); tagsTextView.Visibility = ViewStates.Visible; } else { tagsCaptionTextView.Visibility = ViewStates.Gone; tagsTextView.Text = string.Empty; tagsTextView.Visibility = ViewStates.Gone; } } /// <summary> /// Called when the user clicks on a dependency in the dependency list /// </summary> /// <param name="packageTitle">The package title of the dependency</param> private void DependencySelected(string packageTitle) { if (!this.networkChecker.ValidateNetworkConnectivity()) { return; } // Start the Package Detail Activity var packageDetailIntent = new Intent(this, typeof(PackageDetailActivity)); packageDetailIntent.PutExtra("title", packageTitle); this.StartActivity(packageDetailIntent); } /// <summary> /// Displays the dependencies from the specified package details /// </summary> /// <param name="pd"></param> private void DisplayDependencies(PackageDetail pd) { var dependenciesCaptionTextView = FindViewById<TextView>(Resource.Id.dependenciesCaption); var dependenciesLayout = FindViewById<LinearLayout>(Resource.Id.dependencies); // Check if there are any dependencies if (pd.Dependencies.Any()) { // If there are dependencies, then create a DependencyAdapter to display them var da = new DependencyAdapter(this, pd.Dependencies, this.DependencySelected); for (int i = 0; i < da.Count; i++) { dependenciesLayout.AddView(da.GetView(i, null, null)); } // Show the dependencies caption and dependencies dependenciesCaptionTextView.Visibility = ViewStates.Visible; dependenciesLayout.Visibility = ViewStates.Visible; } else { // If there are no dependencies, then hide the dependencies caption and dependencies dependenciesCaptionTextView.Visibility = ViewStates.Gone; dependenciesLayout.Visibility = ViewStates.Gone; } } /// <summary> /// Displays version history from the specified package details /// </summary> /// <param name="currentId">The id of the version that is currently being displayed</param> /// <param name="history">The history items that make up the version history</param> private void DisplayVersionHistory(string currentId, IEnumerable<HistoryItem> history) { var versionHistoryLayout = FindViewById<TableLayout>(Resource.Id.versionHistory); // Check if there is any history available if (history.Any()) { // Create a table row for each history item foreach (var h in history) { // Create table row TableRow tableRow = new TableRow(this) { Tag = h.Id }; tableRow.SetPadding(0, 10, 0, 10); tableRow.SetBackgroundColor(Color.White); if (h.Id != currentId) { tableRow.Click += this.VersionHistoryTableRow_Click; } // Create version text view and add it to the table row var versionTextView = new TextView(this) { Text = h.Version }; versionTextView.SetTextColor(Color.Argb(255, 102, 102, 102)); versionTextView.SetTypeface(null, (h.Id == currentId) ? TypefaceStyle.Normal : TypefaceStyle.Bold); versionTextView.SetPadding(5, 0, 10, 0); versionTextView.SetBackgroundColor(Color.White); tableRow.AddView(versionTextView); // Create download count text view and add it to the table row var downloadCountTextView = new TextView(this) { Text = h.VersionDownloadCount.ToString("n0"), Gravity = GravityFlags.Right }; downloadCountTextView.SetTextColor(Color.Argb(255, 153, 153, 153)); downloadCountTextView.SetPadding(0, 0, 10, 0); downloadCountTextView.SetBackgroundColor(Color.White); tableRow.AddView(downloadCountTextView); // Create last updated text view and add it to the table row var lastUpdatedTextView = new TextView(this) { Text = h.Published.ToShortDateString(), Gravity = GravityFlags.Right }; lastUpdatedTextView.SetTextColor(Color.Argb(255, 153, 153, 153)); lastUpdatedTextView.SetPadding(0, 0, 5, 0); lastUpdatedTextView.SetBackgroundColor(Color.White); tableRow.AddView(lastUpdatedTextView); // Add the table row to the table layout versionHistoryLayout.AddView(tableRow); // Create a "separator line" and add it to the table layout View v = new View(this); v.LayoutParameters = new TableRow.LayoutParams(ViewGroup.LayoutParams.FillParent, 1); v.SetBackgroundColor(Color.Argb(255, 240, 240, 240)); versionHistoryLayout.AddView(v); } // Show the history layout versionHistoryLayout.Visibility = ViewStates.Visible; } else { // If there is no history, then hide the history layout versionHistoryLayout.Visibility = ViewStates.Gone; } } /// <summary> /// Click event handler for the version history table /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void VersionHistoryTableRow_Click(object sender, EventArgs e) { // Check if there is network connectivity, an if there is not, then return if (!this.networkChecker.ValidateNetworkConnectivity()) { return; } // Start a new Package Detail Activity for this specific version id View view = sender as View; var packageDetailIntent = new Intent(this, typeof(PackageDetailActivity)); packageDetailIntent.PutExtra("id", view.Tag.ToString()); this.StartActivity(packageDetailIntent); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Tanka.FileSystem.WebApiSample.Areas.HelpPage.ModelDescriptions; using Tanka.FileSystem.WebApiSample.Areas.HelpPage.Models; namespace Tanka.FileSystem.WebApiSample.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Drawing { [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Color { private object _dummy; public static readonly System.Drawing.Color Empty; public byte A { get { throw null; } } public static System.Drawing.Color AliceBlue { get { throw null; } } public static System.Drawing.Color AntiqueWhite { get { throw null; } } public static System.Drawing.Color Aqua { get { throw null; } } public static System.Drawing.Color Aquamarine { get { throw null; } } public static System.Drawing.Color Azure { get { throw null; } } public byte B { get { throw null; } } public static System.Drawing.Color Beige { get { throw null; } } public static System.Drawing.Color Bisque { get { throw null; } } public static System.Drawing.Color Black { get { throw null; } } public static System.Drawing.Color BlanchedAlmond { get { throw null; } } public static System.Drawing.Color Blue { get { throw null; } } public static System.Drawing.Color BlueViolet { get { throw null; } } public static System.Drawing.Color Brown { get { throw null; } } public static System.Drawing.Color BurlyWood { get { throw null; } } public static System.Drawing.Color CadetBlue { get { throw null; } } public static System.Drawing.Color Chartreuse { get { throw null; } } public static System.Drawing.Color Chocolate { get { throw null; } } public static System.Drawing.Color Coral { get { throw null; } } public static System.Drawing.Color CornflowerBlue { get { throw null; } } public static System.Drawing.Color Cornsilk { get { throw null; } } public static System.Drawing.Color Crimson { get { throw null; } } public static System.Drawing.Color Cyan { get { throw null; } } public static System.Drawing.Color DarkBlue { get { throw null; } } public static System.Drawing.Color DarkCyan { get { throw null; } } public static System.Drawing.Color DarkGoldenrod { get { throw null; } } public static System.Drawing.Color DarkGray { get { throw null; } } public static System.Drawing.Color DarkGreen { get { throw null; } } public static System.Drawing.Color DarkKhaki { get { throw null; } } public static System.Drawing.Color DarkMagenta { get { throw null; } } public static System.Drawing.Color DarkOliveGreen { get { throw null; } } public static System.Drawing.Color DarkOrange { get { throw null; } } public static System.Drawing.Color DarkOrchid { get { throw null; } } public static System.Drawing.Color DarkRed { get { throw null; } } public static System.Drawing.Color DarkSalmon { get { throw null; } } public static System.Drawing.Color DarkSeaGreen { get { throw null; } } public static System.Drawing.Color DarkSlateBlue { get { throw null; } } public static System.Drawing.Color DarkSlateGray { get { throw null; } } public static System.Drawing.Color DarkTurquoise { get { throw null; } } public static System.Drawing.Color DarkViolet { get { throw null; } } public static System.Drawing.Color DeepPink { get { throw null; } } public static System.Drawing.Color DeepSkyBlue { get { throw null; } } public static System.Drawing.Color DimGray { get { throw null; } } public static System.Drawing.Color DodgerBlue { get { throw null; } } public static System.Drawing.Color Firebrick { get { throw null; } } public static System.Drawing.Color FloralWhite { get { throw null; } } public static System.Drawing.Color ForestGreen { get { throw null; } } public static System.Drawing.Color Fuchsia { get { throw null; } } public byte G { get { throw null; } } public static System.Drawing.Color Gainsboro { get { throw null; } } public static System.Drawing.Color GhostWhite { get { throw null; } } public static System.Drawing.Color Gold { get { throw null; } } public static System.Drawing.Color Goldenrod { get { throw null; } } public static System.Drawing.Color Gray { get { throw null; } } public static System.Drawing.Color Green { get { throw null; } } public static System.Drawing.Color GreenYellow { get { throw null; } } public static System.Drawing.Color Honeydew { get { throw null; } } public static System.Drawing.Color HotPink { get { throw null; } } public static System.Drawing.Color IndianRed { get { throw null; } } public static System.Drawing.Color Indigo { get { throw null; } } public bool IsEmpty { get { throw null; } } public bool IsKnownColor { get { throw null; } } public bool IsNamedColor { get { throw null; } } public bool IsSystemColor { get { throw null; } } public static System.Drawing.Color Ivory { get { throw null; } } public static System.Drawing.Color Khaki { get { throw null; } } public static System.Drawing.Color Lavender { get { throw null; } } public static System.Drawing.Color LavenderBlush { get { throw null; } } public static System.Drawing.Color LawnGreen { get { throw null; } } public static System.Drawing.Color LemonChiffon { get { throw null; } } public static System.Drawing.Color LightBlue { get { throw null; } } public static System.Drawing.Color LightCoral { get { throw null; } } public static System.Drawing.Color LightCyan { get { throw null; } } public static System.Drawing.Color LightGoldenrodYellow { get { throw null; } } public static System.Drawing.Color LightGray { get { throw null; } } public static System.Drawing.Color LightGreen { get { throw null; } } public static System.Drawing.Color LightPink { get { throw null; } } public static System.Drawing.Color LightSalmon { get { throw null; } } public static System.Drawing.Color LightSeaGreen { get { throw null; } } public static System.Drawing.Color LightSkyBlue { get { throw null; } } public static System.Drawing.Color LightSlateGray { get { throw null; } } public static System.Drawing.Color LightSteelBlue { get { throw null; } } public static System.Drawing.Color LightYellow { get { throw null; } } public static System.Drawing.Color Lime { get { throw null; } } public static System.Drawing.Color LimeGreen { get { throw null; } } public static System.Drawing.Color Linen { get { throw null; } } public static System.Drawing.Color Magenta { get { throw null; } } public static System.Drawing.Color Maroon { get { throw null; } } public static System.Drawing.Color MediumAquamarine { get { throw null; } } public static System.Drawing.Color MediumBlue { get { throw null; } } public static System.Drawing.Color MediumOrchid { get { throw null; } } public static System.Drawing.Color MediumPurple { get { throw null; } } public static System.Drawing.Color MediumSeaGreen { get { throw null; } } public static System.Drawing.Color MediumSlateBlue { get { throw null; } } public static System.Drawing.Color MediumSpringGreen { get { throw null; } } public static System.Drawing.Color MediumTurquoise { get { throw null; } } public static System.Drawing.Color MediumVioletRed { get { throw null; } } public static System.Drawing.Color MidnightBlue { get { throw null; } } public static System.Drawing.Color MintCream { get { throw null; } } public static System.Drawing.Color MistyRose { get { throw null; } } public static System.Drawing.Color Moccasin { get { throw null; } } public string Name { get { throw null; } } public static System.Drawing.Color NavajoWhite { get { throw null; } } public static System.Drawing.Color Navy { get { throw null; } } public static System.Drawing.Color OldLace { get { throw null; } } public static System.Drawing.Color Olive { get { throw null; } } public static System.Drawing.Color OliveDrab { get { throw null; } } public static System.Drawing.Color Orange { get { throw null; } } public static System.Drawing.Color OrangeRed { get { throw null; } } public static System.Drawing.Color Orchid { get { throw null; } } public static System.Drawing.Color PaleGoldenrod { get { throw null; } } public static System.Drawing.Color PaleGreen { get { throw null; } } public static System.Drawing.Color PaleTurquoise { get { throw null; } } public static System.Drawing.Color PaleVioletRed { get { throw null; } } public static System.Drawing.Color PapayaWhip { get { throw null; } } public static System.Drawing.Color PeachPuff { get { throw null; } } public static System.Drawing.Color Peru { get { throw null; } } public static System.Drawing.Color Pink { get { throw null; } } public static System.Drawing.Color Plum { get { throw null; } } public static System.Drawing.Color PowderBlue { get { throw null; } } public static System.Drawing.Color Purple { get { throw null; } } public byte R { get { throw null; } } public static System.Drawing.Color Red { get { throw null; } } public static System.Drawing.Color RosyBrown { get { throw null; } } public static System.Drawing.Color RoyalBlue { get { throw null; } } public static System.Drawing.Color SaddleBrown { get { throw null; } } public static System.Drawing.Color Salmon { get { throw null; } } public static System.Drawing.Color SandyBrown { get { throw null; } } public static System.Drawing.Color SeaGreen { get { throw null; } } public static System.Drawing.Color SeaShell { get { throw null; } } public static System.Drawing.Color Sienna { get { throw null; } } public static System.Drawing.Color Silver { get { throw null; } } public static System.Drawing.Color SkyBlue { get { throw null; } } public static System.Drawing.Color SlateBlue { get { throw null; } } public static System.Drawing.Color SlateGray { get { throw null; } } public static System.Drawing.Color Snow { get { throw null; } } public static System.Drawing.Color SpringGreen { get { throw null; } } public static System.Drawing.Color SteelBlue { get { throw null; } } public static System.Drawing.Color Tan { get { throw null; } } public static System.Drawing.Color Teal { get { throw null; } } public static System.Drawing.Color Thistle { get { throw null; } } public static System.Drawing.Color Tomato { get { throw null; } } public static System.Drawing.Color Transparent { get { throw null; } } public static System.Drawing.Color Turquoise { get { throw null; } } public static System.Drawing.Color Violet { get { throw null; } } public static System.Drawing.Color Wheat { get { throw null; } } public static System.Drawing.Color White { get { throw null; } } public static System.Drawing.Color WhiteSmoke { get { throw null; } } public static System.Drawing.Color Yellow { get { throw null; } } public static System.Drawing.Color YellowGreen { get { throw null; } } public override bool Equals(object obj) { throw null; } public static System.Drawing.Color FromArgb(int argb) { throw null; } public static System.Drawing.Color FromArgb(int alpha, System.Drawing.Color baseColor) { throw null; } public static System.Drawing.Color FromArgb(int red, int green, int blue) { throw null; } public static System.Drawing.Color FromArgb(int alpha, int red, int green, int blue) { throw null; } public static System.Drawing.Color FromKnownColor(System.Drawing.KnownColor color) { throw null; } public static System.Drawing.Color FromName(string name) { throw null; } public float GetBrightness() { throw null; } public override int GetHashCode() { throw null; } public float GetHue() { throw null; } public float GetSaturation() { throw null; } public static bool operator ==(System.Drawing.Color left, System.Drawing.Color right) { throw null; } public static bool operator !=(System.Drawing.Color left, System.Drawing.Color right) { throw null; } public int ToArgb() { throw null; } public System.Drawing.KnownColor ToKnownColor() { throw null; } public override string ToString() { throw null; } } public partial class ColorConverter : System.ComponentModel.TypeConverter { public ColorConverter() { } public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { throw null; } public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { throw null; } public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { throw null; } public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { throw null; } public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { throw null; } public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { throw null; } } public enum KnownColor { ActiveBorder = 1, ActiveCaption = 2, ActiveCaptionText = 3, AliceBlue = 28, AntiqueWhite = 29, AppWorkspace = 4, Aqua = 30, Aquamarine = 31, Azure = 32, Beige = 33, Bisque = 34, Black = 35, BlanchedAlmond = 36, Blue = 37, BlueViolet = 38, Brown = 39, BurlyWood = 40, ButtonFace = 168, ButtonHighlight = 169, ButtonShadow = 170, CadetBlue = 41, Chartreuse = 42, Chocolate = 43, Control = 5, ControlDark = 6, ControlDarkDark = 7, ControlLight = 8, ControlLightLight = 9, ControlText = 10, Coral = 44, CornflowerBlue = 45, Cornsilk = 46, Crimson = 47, Cyan = 48, DarkBlue = 49, DarkCyan = 50, DarkGoldenrod = 51, DarkGray = 52, DarkGreen = 53, DarkKhaki = 54, DarkMagenta = 55, DarkOliveGreen = 56, DarkOrange = 57, DarkOrchid = 58, DarkRed = 59, DarkSalmon = 60, DarkSeaGreen = 61, DarkSlateBlue = 62, DarkSlateGray = 63, DarkTurquoise = 64, DarkViolet = 65, DeepPink = 66, DeepSkyBlue = 67, Desktop = 11, DimGray = 68, DodgerBlue = 69, Firebrick = 70, FloralWhite = 71, ForestGreen = 72, Fuchsia = 73, Gainsboro = 74, GhostWhite = 75, Gold = 76, Goldenrod = 77, GradientActiveCaption = 171, GradientInactiveCaption = 172, Gray = 78, GrayText = 12, Green = 79, GreenYellow = 80, Highlight = 13, HighlightText = 14, Honeydew = 81, HotPink = 82, HotTrack = 15, InactiveBorder = 16, InactiveCaption = 17, InactiveCaptionText = 18, IndianRed = 83, Indigo = 84, Info = 19, InfoText = 20, Ivory = 85, Khaki = 86, Lavender = 87, LavenderBlush = 88, LawnGreen = 89, LemonChiffon = 90, LightBlue = 91, LightCoral = 92, LightCyan = 93, LightGoldenrodYellow = 94, LightGray = 95, LightGreen = 96, LightPink = 97, LightSalmon = 98, LightSeaGreen = 99, LightSkyBlue = 100, LightSlateGray = 101, LightSteelBlue = 102, LightYellow = 103, Lime = 104, LimeGreen = 105, Linen = 106, Magenta = 107, Maroon = 108, MediumAquamarine = 109, MediumBlue = 110, MediumOrchid = 111, MediumPurple = 112, MediumSeaGreen = 113, MediumSlateBlue = 114, MediumSpringGreen = 115, MediumTurquoise = 116, MediumVioletRed = 117, Menu = 21, MenuBar = 173, MenuHighlight = 174, MenuText = 22, MidnightBlue = 118, MintCream = 119, MistyRose = 120, Moccasin = 121, NavajoWhite = 122, Navy = 123, OldLace = 124, Olive = 125, OliveDrab = 126, Orange = 127, OrangeRed = 128, Orchid = 129, PaleGoldenrod = 130, PaleGreen = 131, PaleTurquoise = 132, PaleVioletRed = 133, PapayaWhip = 134, PeachPuff = 135, Peru = 136, Pink = 137, Plum = 138, PowderBlue = 139, Purple = 140, Red = 141, RosyBrown = 142, RoyalBlue = 143, SaddleBrown = 144, Salmon = 145, SandyBrown = 146, ScrollBar = 23, SeaGreen = 147, SeaShell = 148, Sienna = 149, Silver = 150, SkyBlue = 151, SlateBlue = 152, SlateGray = 153, Snow = 154, SpringGreen = 155, SteelBlue = 156, Tan = 157, Teal = 158, Thistle = 159, Tomato = 160, Transparent = 27, Turquoise = 161, Violet = 162, Wheat = 163, White = 164, WhiteSmoke = 165, Window = 24, WindowFrame = 25, WindowText = 26, Yellow = 166, YellowGreen = 167, } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Point { private object _dummy; public static readonly System.Drawing.Point Empty; public Point(System.Drawing.Size sz) { throw null; } public Point(int dw) { throw null; } public Point(int x, int y) { throw null; } [System.ComponentModel.BrowsableAttribute(false)] public bool IsEmpty { get { throw null; } } public int X { get { throw null; } set { } } public int Y { get { throw null; } set { } } public static System.Drawing.Point Add(System.Drawing.Point pt, System.Drawing.Size sz) { throw null; } public static System.Drawing.Point Ceiling(System.Drawing.PointF value) { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public void Offset(System.Drawing.Point p) { } public void Offset(int dx, int dy) { } public static System.Drawing.Point operator +(System.Drawing.Point pt, System.Drawing.Size sz) { throw null; } public static bool operator ==(System.Drawing.Point left, System.Drawing.Point right) { throw null; } public static explicit operator System.Drawing.Size (System.Drawing.Point p) { throw null; } public static implicit operator System.Drawing.PointF (System.Drawing.Point p) { throw null; } public static bool operator !=(System.Drawing.Point left, System.Drawing.Point right) { throw null; } public static System.Drawing.Point operator -(System.Drawing.Point pt, System.Drawing.Size sz) { throw null; } public static System.Drawing.Point Round(System.Drawing.PointF value) { throw null; } public static System.Drawing.Point Subtract(System.Drawing.Point pt, System.Drawing.Size sz) { throw null; } public override string ToString() { throw null; } public static System.Drawing.Point Truncate(System.Drawing.PointF value) { throw null; } } public partial class PointConverter : System.ComponentModel.TypeConverter { public PointConverter() { } public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { throw null; } public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { throw null; } public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { throw null; } public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { throw null; } public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary propertyValues) { throw null; } public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { throw null; } public override System.ComponentModel.PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributes) { throw null; } public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct PointF { private object _dummy; public static readonly System.Drawing.PointF Empty; public PointF(float x, float y) { throw null; } public bool IsEmpty { get { throw null; } } public float X { get { throw null; } set { } } public float Y { get { throw null; } set { } } public static System.Drawing.PointF Add(System.Drawing.PointF pt, System.Drawing.Size sz) { throw null; } public static System.Drawing.PointF Add(System.Drawing.PointF pt, System.Drawing.SizeF sz) { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public static System.Drawing.PointF operator +(System.Drawing.PointF pt, System.Drawing.Size sz) { throw null; } public static System.Drawing.PointF operator +(System.Drawing.PointF pt, System.Drawing.SizeF sz) { throw null; } public static bool operator ==(System.Drawing.PointF left, System.Drawing.PointF right) { throw null; } public static bool operator !=(System.Drawing.PointF left, System.Drawing.PointF right) { throw null; } public static System.Drawing.PointF operator -(System.Drawing.PointF pt, System.Drawing.Size sz) { throw null; } public static System.Drawing.PointF operator -(System.Drawing.PointF pt, System.Drawing.SizeF sz) { throw null; } public static System.Drawing.PointF Subtract(System.Drawing.PointF pt, System.Drawing.Size sz) { throw null; } public static System.Drawing.PointF Subtract(System.Drawing.PointF pt, System.Drawing.SizeF sz) { throw null; } public override string ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Rectangle { private object _dummy; public static readonly System.Drawing.Rectangle Empty; public Rectangle(System.Drawing.Point location, System.Drawing.Size size) { throw null; } public Rectangle(int x, int y, int width, int height) { throw null; } [System.ComponentModel.BrowsableAttribute(false)] public int Bottom { get { throw null; } } public int Height { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public bool IsEmpty { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] public int Left { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] public System.Drawing.Point Location { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public int Right { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] public System.Drawing.Size Size { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public int Top { get { throw null; } } public int Width { get { throw null; } set { } } public int X { get { throw null; } set { } } public int Y { get { throw null; } set { } } public static System.Drawing.Rectangle Ceiling(System.Drawing.RectangleF value) { throw null; } public bool Contains(System.Drawing.Point pt) { throw null; } public bool Contains(System.Drawing.Rectangle rect) { throw null; } public bool Contains(int x, int y) { throw null; } public override bool Equals(object obj) { throw null; } public static System.Drawing.Rectangle FromLTRB(int left, int top, int right, int bottom) { throw null; } public override int GetHashCode() { throw null; } public static System.Drawing.Rectangle Inflate(System.Drawing.Rectangle rect, int x, int y) { throw null; } public void Inflate(System.Drawing.Size size) { } public void Inflate(int width, int height) { } public void Intersect(System.Drawing.Rectangle rect) { } public static System.Drawing.Rectangle Intersect(System.Drawing.Rectangle a, System.Drawing.Rectangle b) { throw null; } public bool IntersectsWith(System.Drawing.Rectangle rect) { throw null; } public void Offset(System.Drawing.Point pos) { } public void Offset(int x, int y) { } public static bool operator ==(System.Drawing.Rectangle left, System.Drawing.Rectangle right) { throw null; } public static bool operator !=(System.Drawing.Rectangle left, System.Drawing.Rectangle right) { throw null; } public static System.Drawing.Rectangle Round(System.Drawing.RectangleF value) { throw null; } public override string ToString() { throw null; } public static System.Drawing.Rectangle Truncate(System.Drawing.RectangleF value) { throw null; } public static System.Drawing.Rectangle Union(System.Drawing.Rectangle a, System.Drawing.Rectangle b) { throw null; } } public partial class RectangleConverter : System.ComponentModel.TypeConverter { public RectangleConverter() { } public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { throw null; } public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { throw null; } public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { throw null; } public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { throw null; } public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary propertyValues) { throw null; } public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { throw null; } public override System.ComponentModel.PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributes) { throw null; } public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct RectangleF { private object _dummy; public static readonly System.Drawing.RectangleF Empty; public RectangleF(System.Drawing.PointF location, System.Drawing.SizeF size) { throw null; } public RectangleF(float x, float y, float width, float height) { throw null; } public float Bottom { get { throw null; } } public float Height { get { throw null; } set { } } public bool IsEmpty { get { throw null; } } public float Left { get { throw null; } } public System.Drawing.PointF Location { get { throw null; } set { } } public float Right { get { throw null; } } public System.Drawing.SizeF Size { get { throw null; } set { } } public float Top { get { throw null; } } public float Width { get { throw null; } set { } } public float X { get { throw null; } set { } } public float Y { get { throw null; } set { } } public bool Contains(System.Drawing.PointF pt) { throw null; } public bool Contains(System.Drawing.RectangleF rect) { throw null; } public bool Contains(float x, float y) { throw null; } public override bool Equals(object obj) { throw null; } public static System.Drawing.RectangleF FromLTRB(float left, float top, float right, float bottom) { throw null; } public override int GetHashCode() { throw null; } public static System.Drawing.RectangleF Inflate(System.Drawing.RectangleF rect, float x, float y) { throw null; } public void Inflate(System.Drawing.SizeF size) { } public void Inflate(float x, float y) { } public void Intersect(System.Drawing.RectangleF rect) { } public static System.Drawing.RectangleF Intersect(System.Drawing.RectangleF a, System.Drawing.RectangleF b) { throw null; } public bool IntersectsWith(System.Drawing.RectangleF rect) { throw null; } public void Offset(System.Drawing.PointF pos) { } public void Offset(float x, float y) { } public static bool operator ==(System.Drawing.RectangleF left, System.Drawing.RectangleF right) { throw null; } public static implicit operator System.Drawing.RectangleF (System.Drawing.Rectangle r) { throw null; } public static bool operator !=(System.Drawing.RectangleF left, System.Drawing.RectangleF right) { throw null; } public override string ToString() { throw null; } public static System.Drawing.RectangleF Union(System.Drawing.RectangleF a, System.Drawing.RectangleF b) { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Size { private object _dummy; public static readonly System.Drawing.Size Empty; public Size(System.Drawing.Point pt) { throw null; } public Size(int width, int height) { throw null; } public int Height { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public bool IsEmpty { get { throw null; } } public int Width { get { throw null; } set { } } public static System.Drawing.Size Add(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; } public static System.Drawing.Size Ceiling(System.Drawing.SizeF value) { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public static System.Drawing.Size operator +(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; } public static bool operator ==(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; } public static explicit operator System.Drawing.Point (System.Drawing.Size size) { throw null; } public static implicit operator System.Drawing.SizeF (System.Drawing.Size p) { throw null; } public static bool operator !=(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; } public static System.Drawing.Size operator -(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; } public static System.Drawing.Size Round(System.Drawing.SizeF value) { throw null; } public static System.Drawing.Size Subtract(System.Drawing.Size sz1, System.Drawing.Size sz2) { throw null; } public override string ToString() { throw null; } public static System.Drawing.Size Truncate(System.Drawing.SizeF value) { throw null; } } public partial class SizeConverter : System.ComponentModel.TypeConverter { public SizeConverter() { } public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { throw null; } public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { throw null; } public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { throw null; } public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { throw null; } public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary propertyValues) { throw null; } public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { throw null; } public override System.ComponentModel.PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributes) { throw null; } public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct SizeF { private object _dummy; public static readonly System.Drawing.SizeF Empty; public SizeF(System.Drawing.PointF pt) { throw null; } public SizeF(System.Drawing.SizeF size) { throw null; } public SizeF(float width, float height) { throw null; } public float Height { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] public bool IsEmpty { get { throw null; } } public float Width { get { throw null; } set { } } public static System.Drawing.SizeF Add(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public static System.Drawing.SizeF operator +(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; } public static bool operator ==(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; } public static explicit operator System.Drawing.PointF (System.Drawing.SizeF size) { throw null; } public static bool operator !=(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; } public static System.Drawing.SizeF operator -(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; } public static System.Drawing.SizeF Subtract(System.Drawing.SizeF sz1, System.Drawing.SizeF sz2) { throw null; } public System.Drawing.PointF ToPointF() { throw null; } public System.Drawing.Size ToSize() { throw null; } public override string ToString() { throw null; } } public partial class SizeFConverter : System.ComponentModel.TypeConverter { public SizeFConverter() { } public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { throw null; } public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { throw null; } public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { throw null; } public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { throw null; } public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary propertyValues) { throw null; } public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { throw null; } public override System.ComponentModel.PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributes) { throw null; } public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { throw null; } } public sealed partial class SystemColors { internal SystemColors() { } public static System.Drawing.Color ActiveBorder { get { throw null; } } public static System.Drawing.Color ActiveCaption { get { throw null; } } public static System.Drawing.Color ActiveCaptionText { get { throw null; } } public static System.Drawing.Color AppWorkspace { get { throw null; } } public static System.Drawing.Color ButtonFace { get { throw null; } } public static System.Drawing.Color ButtonHighlight { get { throw null; } } public static System.Drawing.Color ButtonShadow { get { throw null; } } public static System.Drawing.Color Control { get { throw null; } } public static System.Drawing.Color ControlDark { get { throw null; } } public static System.Drawing.Color ControlDarkDark { get { throw null; } } public static System.Drawing.Color ControlLight { get { throw null; } } public static System.Drawing.Color ControlLightLight { get { throw null; } } public static System.Drawing.Color ControlText { get { throw null; } } public static System.Drawing.Color Desktop { get { throw null; } } public static System.Drawing.Color GradientActiveCaption { get { throw null; } } public static System.Drawing.Color GradientInactiveCaption { get { throw null; } } public static System.Drawing.Color GrayText { get { throw null; } } public static System.Drawing.Color Highlight { get { throw null; } } public static System.Drawing.Color HighlightText { get { throw null; } } public static System.Drawing.Color HotTrack { get { throw null; } } public static System.Drawing.Color InactiveBorder { get { throw null; } } public static System.Drawing.Color InactiveCaption { get { throw null; } } public static System.Drawing.Color InactiveCaptionText { get { throw null; } } public static System.Drawing.Color Info { get { throw null; } } public static System.Drawing.Color InfoText { get { throw null; } } public static System.Drawing.Color Menu { get { throw null; } } public static System.Drawing.Color MenuBar { get { throw null; } } public static System.Drawing.Color MenuHighlight { get { throw null; } } public static System.Drawing.Color MenuText { get { throw null; } } public static System.Drawing.Color ScrollBar { get { throw null; } } public static System.Drawing.Color Window { get { throw null; } } public static System.Drawing.Color WindowFrame { get { throw null; } } public static System.Drawing.Color WindowText { get { throw null; } } } }
// Copyright (c) morrisjdev. All rights reserved. // Original copyright (c) .NET Foundation. All rights reserved. // Modified version by morrisjdev // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.Storage; namespace FileContextCore.Query.Internal { public partial class FileContextShapedQueryCompilingExpressionVisitor { private class CustomShaperCompilingExpressionVisitor : ExpressionVisitor { private readonly bool _tracking; public CustomShaperCompilingExpressionVisitor(bool tracking) { _tracking = tracking; } private static readonly MethodInfo _includeReferenceMethodInfo = typeof(CustomShaperCompilingExpressionVisitor).GetTypeInfo() .GetDeclaredMethod(nameof(IncludeReference)); private static readonly MethodInfo _includeCollectionMethodInfo = typeof(CustomShaperCompilingExpressionVisitor).GetTypeInfo() .GetDeclaredMethod(nameof(IncludeCollection)); private static readonly MethodInfo _materializeCollectionMethodInfo = typeof(CustomShaperCompilingExpressionVisitor).GetTypeInfo() .GetDeclaredMethod(nameof(MaterializeCollection)); private static readonly MethodInfo _materializeSingleResultMethodInfo = typeof(CustomShaperCompilingExpressionVisitor).GetTypeInfo() .GetDeclaredMethod(nameof(MaterializeSingleResult)); private static void SetIsLoadedNoTracking(object entity, INavigation navigation) => ((ILazyLoader)(navigation .DeclaringEntityType .GetServiceProperties() .FirstOrDefault(p => p.ClrType == typeof(ILazyLoader))) ?.GetGetter().GetClrValue(entity)) ?.SetLoaded(entity, navigation.Name); private static void IncludeReference<TEntity, TIncludingEntity, TIncludedEntity>( QueryContext queryContext, TEntity entity, TIncludedEntity relatedEntity, INavigation navigation, INavigation inverseNavigation, Action<TIncludingEntity, TIncludedEntity> fixup, bool trackingQuery) where TIncludingEntity : class, TEntity where TEntity : class where TIncludedEntity : class { if (entity is TIncludingEntity includingEntity) { if (trackingQuery && navigation.DeclaringEntityType.FindPrimaryKey() != null) { // For non-null relatedEntity StateManager will set the flag if (relatedEntity == null) { queryContext.SetNavigationIsLoaded(includingEntity, navigation); } } else { SetIsLoadedNoTracking(includingEntity, navigation); if (relatedEntity != null) { fixup(includingEntity, relatedEntity); if (inverseNavigation != null && !inverseNavigation.IsCollection()) { SetIsLoadedNoTracking(relatedEntity, inverseNavigation); } } } } } private static void IncludeCollection<TEntity, TIncludingEntity, TIncludedEntity>( QueryContext queryContext, IEnumerable<ValueBuffer> innerValueBuffers, Func<QueryContext, ValueBuffer, TIncludedEntity> innerShaper, TEntity entity, INavigation navigation, INavigation inverseNavigation, Action<TIncludingEntity, TIncludedEntity> fixup, bool trackingQuery) where TIncludingEntity : class, TEntity where TEntity : class where TIncludedEntity : class { if (entity is TIncludingEntity includingEntity) { var collectionAccessor = navigation.GetCollectionAccessor(); collectionAccessor.GetOrCreate(includingEntity, forMaterialization: true); if (trackingQuery) { queryContext.SetNavigationIsLoaded(entity, navigation); } else { SetIsLoadedNoTracking(entity, navigation); } foreach (var valueBuffer in innerValueBuffers) { var relatedEntity = innerShaper(queryContext, valueBuffer); if (!trackingQuery) { fixup(includingEntity, relatedEntity); if (inverseNavigation != null) { SetIsLoadedNoTracking(relatedEntity, inverseNavigation); } } } } } private static TCollection MaterializeCollection<TElement, TCollection>( QueryContext queryContext, IEnumerable<ValueBuffer> innerValueBuffers, Func<QueryContext, ValueBuffer, TElement> innerShaper, IClrCollectionAccessor clrCollectionAccessor) where TCollection : class, ICollection<TElement> { var collection = (TCollection)(clrCollectionAccessor?.Create() ?? new List<TElement>()); foreach (var valueBuffer in innerValueBuffers) { var element = innerShaper(queryContext, valueBuffer); collection.Add(element); } return collection; } private static TResult MaterializeSingleResult<TResult>( QueryContext queryContext, ValueBuffer valueBuffer, Func<QueryContext, ValueBuffer, TResult> innerShaper) => valueBuffer.IsEmpty ? default : innerShaper(queryContext, valueBuffer); protected override Expression VisitExtension(Expression extensionExpression) { if (extensionExpression is IncludeExpression includeExpression) { var entityClrType = includeExpression.EntityExpression.Type; var includingClrType = includeExpression.Navigation.DeclaringEntityType.ClrType; var inverseNavigation = includeExpression.Navigation.FindInverse(); var relatedEntityClrType = includeExpression.Navigation.GetTargetType().ClrType; if (includingClrType != entityClrType && includingClrType.IsAssignableFrom(entityClrType)) { includingClrType = entityClrType; } if (includeExpression.Navigation.IsCollection()) { var collectionShaper = (CollectionShaperExpression)includeExpression.NavigationExpression; return Expression.Call( _includeCollectionMethodInfo.MakeGenericMethod(entityClrType, includingClrType, relatedEntityClrType), QueryCompilationContext.QueryContextParameter, collectionShaper.Projection, Expression.Constant(((LambdaExpression)Visit(collectionShaper.InnerShaper)).Compile()), includeExpression.EntityExpression, Expression.Constant(includeExpression.Navigation), Expression.Constant(inverseNavigation, typeof(INavigation)), Expression.Constant( GenerateFixup( includingClrType, relatedEntityClrType, includeExpression.Navigation, inverseNavigation).Compile()), Expression.Constant(_tracking)); } return Expression.Call( _includeReferenceMethodInfo.MakeGenericMethod(entityClrType, includingClrType, relatedEntityClrType), QueryCompilationContext.QueryContextParameter, includeExpression.EntityExpression, includeExpression.NavigationExpression, Expression.Constant(includeExpression.Navigation), Expression.Constant(inverseNavigation, typeof(INavigation)), Expression.Constant( GenerateFixup( includingClrType, relatedEntityClrType, includeExpression.Navigation, inverseNavigation).Compile()), Expression.Constant(_tracking)); } if (extensionExpression is CollectionShaperExpression collectionShaperExpression) { var elementType = collectionShaperExpression.ElementType; var collectionType = collectionShaperExpression.Type; return Expression.Call( _materializeCollectionMethodInfo.MakeGenericMethod(elementType, collectionType), QueryCompilationContext.QueryContextParameter, collectionShaperExpression.Projection, Expression.Constant(((LambdaExpression)Visit(collectionShaperExpression.InnerShaper)).Compile()), Expression.Constant( collectionShaperExpression.Navigation?.GetCollectionAccessor(), typeof(IClrCollectionAccessor))); } if (extensionExpression is SingleResultShaperExpression singleResultShaperExpression) { return Expression.Call( _materializeSingleResultMethodInfo.MakeGenericMethod(singleResultShaperExpression.Type), QueryCompilationContext.QueryContextParameter, singleResultShaperExpression.Projection, Expression.Constant(((LambdaExpression)Visit(singleResultShaperExpression.InnerShaper)).Compile())); } return base.VisitExtension(extensionExpression); } private static LambdaExpression GenerateFixup( Type entityType, Type relatedEntityType, INavigation navigation, INavigation inverseNavigation) { var entityParameter = Expression.Parameter(entityType); var relatedEntityParameter = Expression.Parameter(relatedEntityType); var expressions = new List<Expression> { navigation.IsCollection() ? AddToCollectionNavigation(entityParameter, relatedEntityParameter, navigation) : AssignReferenceNavigation(entityParameter, relatedEntityParameter, navigation) }; if (inverseNavigation != null) { expressions.Add( inverseNavigation.IsCollection() ? AddToCollectionNavigation(relatedEntityParameter, entityParameter, inverseNavigation) : AssignReferenceNavigation(relatedEntityParameter, entityParameter, inverseNavigation)); } return Expression.Lambda(Expression.Block(typeof(void), expressions), entityParameter, relatedEntityParameter); } private static Expression AssignReferenceNavigation( ParameterExpression entity, ParameterExpression relatedEntity, INavigation navigation) { return entity.MakeMemberAccess(navigation.GetMemberInfo(forMaterialization: true, forSet: true)).Assign(relatedEntity); } private static Expression AddToCollectionNavigation( ParameterExpression entity, ParameterExpression relatedEntity, INavigation navigation) => Expression.Call( Expression.Constant(navigation.GetCollectionAccessor()), _collectionAccessorAddMethodInfo, entity, relatedEntity, Expression.Constant(true)); private static readonly MethodInfo _collectionAccessorAddMethodInfo = typeof(IClrCollectionAccessor).GetTypeInfo() .GetDeclaredMethod(nameof(IClrCollectionAccessor.Add)); } } }
using UnityEngine; using UnityEditor; using System; using System.Linq; using System.IO; using System.Collections.Generic; using System.Text.RegularExpressions; using UnityEngine.AssetGraph; using Model=UnityEngine.AssetGraph.DataModel.Version2; namespace UnityEngine.AssetGraph { [CustomNode("Assert/Assert Unwanted Assets In Bundle", 80)] public class AssertUnwantedAssetsInBundle : Node { public enum AssertionStyle : int { AllowOnlyAssetsUnderAssertionPath, // Only allows asssets under assertion path to be included ProhibitAssetsUnderAssertionPath // Prohibit assets under assertion path to be included } [SerializeField] private SerializableMultiTargetString m_path; [SerializeField] private AssertionStyle m_style; public override string ActiveStyle { get { return "node 7 on"; } } public override string InactiveStyle { get { return "node 7"; } } public override string Category { get { return "Assert"; } } public override Model.NodeOutputSemantics NodeInputType { get { return Model.NodeOutputSemantics.AssetBundleConfigurations; } } public override Model.NodeOutputSemantics NodeOutputType { get { return Model.NodeOutputSemantics.AssetBundleConfigurations; } } public override void Initialize(Model.NodeData data) { m_path = new SerializableMultiTargetString(); m_style = AssertionStyle.AllowOnlyAssetsUnderAssertionPath; data.AddDefaultInputPoint(); data.AddDefaultOutputPoint(); } public override Node Clone(Model.NodeData newData) { var newNode = new AssertUnwantedAssetsInBundle(); newNode.m_path = new SerializableMultiTargetString(m_path); newNode.m_style = m_style; newData.AddDefaultInputPoint(); newData.AddDefaultOutputPoint(); return newNode; } public override bool OnAssetsReimported( Model.NodeData nodeData, AssetReferenceStreamManager streamManager, BuildTarget target, AssetPostprocessorContext ctx, bool isBuilding) { return true; } public override void OnInspectorGUI(NodeGUI node, AssetReferenceStreamManager streamManager, NodeGUIEditor editor, Action onValueChanged) { EditorGUILayout.HelpBox("Assert Unwanted Assets In Bundle: Checks if unwanted assets are included in bundle configurations.", MessageType.Info); editor.UpdateNodeName(node); GUILayout.Space(10f); var newValue = (AssertionStyle)EditorGUILayout.EnumPopup("Assertion Style", m_style); if(newValue != m_style) { using(new RecordUndoScope("Change Assertion Style", node, true)) { m_style = newValue; onValueChanged(); } } GUILayout.Space(4f); //Show target configuration tab editor.DrawPlatformSelector(node); using (new EditorGUILayout.VerticalScope(GUI.skin.box)) { var disabledScope = editor.DrawOverrideTargetToggle(node, m_path.ContainsValueOf(editor.CurrentEditingGroup), (bool b) => { using(new RecordUndoScope("Remove Target Load Path Settings", node, true)) { if(b) { m_path[editor.CurrentEditingGroup] = m_path.DefaultValue; } else { m_path.Remove(editor.CurrentEditingGroup); } onValueChanged(); } }); using (disabledScope) { var path = m_path[editor.CurrentEditingGroup]; EditorGUILayout.LabelField("Assertion Path:"); string newLoadPath = null; newLoadPath = editor.DrawFolderSelector (Model.Settings.Path.ASSETS_PATH, "Select Asset Folder", path, FileUtility.PathCombine(Model.Settings.Path.ASSETS_PATH, path), (string folderSelected) => { var dataPath = Application.dataPath; if(dataPath == folderSelected) { folderSelected = string.Empty; } else { var index = folderSelected.IndexOf(dataPath); if(index >= 0 ) { folderSelected = folderSelected.Substring(dataPath.Length + index); if(folderSelected.IndexOf('/') == 0) { folderSelected = folderSelected.Substring(1); } } } return folderSelected; } ); if (newLoadPath != path) { using(new RecordUndoScope("Path Change", node, true)){ m_path[editor.CurrentEditingGroup] = newLoadPath; onValueChanged(); } } var dirPath = Path.Combine(Model.Settings.Path.ASSETS_PATH,newLoadPath); bool dirExists = Directory.Exists(dirPath); GUILayout.Space(10f); using (new EditorGUILayout.HorizontalScope()) { using(new EditorGUI.DisabledScope(string.IsNullOrEmpty(newLoadPath)||!dirExists)) { GUILayout.FlexibleSpace(); if(GUILayout.Button("Highlight in Project Window", GUILayout.Width(180f))) { // trailing is "/" not good for LoadMainAssetAtPath if(dirPath[dirPath.Length-1] == '/') { dirPath = dirPath.Substring(0, dirPath.Length-1); } var obj = AssetDatabase.LoadMainAssetAtPath(dirPath); EditorGUIUtility.PingObject(obj); } } } } } } /** * Prepare is called whenever graph needs update. */ public override void Prepare (BuildTarget target, Model.NodeData node, IEnumerable<PerformGraph.AssetGroups> incoming, IEnumerable<Model.ConnectionData> connectionsToOutput, PerformGraph.Output Output) { if(string.IsNullOrEmpty(m_path[target])) { throw new NodeException("Assertion Path is empty.", "Set a valid assertion path from inspector.",node); } // Pass incoming assets straight to Output if(Output != null) { var destination = (connectionsToOutput == null || !connectionsToOutput.Any())? null : connectionsToOutput.First(); if(incoming != null) { var checkPath = m_path[target]; var allow = m_style == AssertionStyle.AllowOnlyAssetsUnderAssertionPath; foreach(var ag in incoming) { foreach (var assets in ag.assetGroups.Values) { foreach(var a in assets) { if(allow != a.importFrom.Contains(checkPath)) { throw new NodeException("Unwanted asset '" + a.importFrom + "' found.", allow ? "Move this asset under " + checkPath : "Move this asset out from " + checkPath, node); } var dependencies = AssetDatabase.GetDependencies(new string[] { a.importFrom } ); foreach(var d in dependencies) { if(allow != d.Contains(checkPath)) { throw new NodeException("Unwanted asset found in dependency:'" + d + "' from following asset:" + a.importFrom, allow ? "Move this asset under " + checkPath : "Move this asset out from " + checkPath, node); } } } } Output(destination, ag.assetGroups); } } else { // Overwrite output with empty Dictionary when no there is incoming asset Output(destination, new Dictionary<string, List<AssetReference>>()); } } } } }
using System; using ChainUtils.BouncyCastle.Utilities; namespace ChainUtils.BouncyCastle.Crypto.Digests { /** * implementation of MD2 * as outlined in RFC1319 by B.Kaliski from RSA Laboratories April 1992 */ public class MD2Digest : IDigest, IMemoable { private const int DigestLength = 16; private const int BYTE_LENGTH = 16; /* X buffer */ private byte[] X = new byte[48]; private int xOff; /* M buffer */ private byte[] M = new byte[16]; private int mOff; /* check sum */ private byte[] C = new byte[16]; private int COff; public MD2Digest() { Reset(); } public MD2Digest(MD2Digest t) { CopyIn(t); } private void CopyIn(MD2Digest t) { Array.Copy(t.X, 0, X, 0, t.X.Length); xOff = t.xOff; Array.Copy(t.M, 0, M, 0, t.M.Length); mOff = t.mOff; Array.Copy(t.C, 0, C, 0, t.C.Length); COff = t.COff; } /** * return the algorithm name * * @return the algorithm name */ public string AlgorithmName { get { return "MD2"; } } public int GetDigestSize() { return DigestLength; } public int GetByteLength() { return BYTE_LENGTH; } /** * Close the digest, producing the final digest value. The doFinal * call leaves the digest reset. * * @param out the array the digest is to be copied into. * @param outOff the offset into the out array the digest is to start at. */ public int DoFinal(byte[] output, int outOff) { // add padding var paddingByte = (byte)(M.Length - mOff); for (var i=mOff;i<M.Length;i++) { M[i] = paddingByte; } //do final check sum ProcessChecksum(M); // do final block process ProcessBlock(M); ProcessBlock(C); Array.Copy(X, xOff, output, outOff, 16); Reset(); return DigestLength; } /** * reset the digest back to it's initial state. */ public void Reset() { xOff = 0; for (var i = 0; i != X.Length; i++) { X[i] = 0; } mOff = 0; for (var i = 0; i != M.Length; i++) { M[i] = 0; } COff = 0; for (var i = 0; i != C.Length; i++) { C[i] = 0; } } /** * update the message digest with a single byte. * * @param in the input byte to be entered. */ public void Update(byte input) { M[mOff++] = input; if (mOff == 16) { ProcessChecksum(M); ProcessBlock(M); mOff = 0; } } /** * update the message digest with a block of bytes. * * @param in the byte array containing the data. * @param inOff the offset into the byte array where the data starts. * @param len the length of the data. */ public void BlockUpdate(byte[] input, int inOff, int length) { // // fill the current word // while ((mOff != 0) && (length > 0)) { Update(input[inOff]); inOff++; length--; } // // process whole words. // while (length > 16) { Array.Copy(input,inOff,M,0,16); ProcessChecksum(M); ProcessBlock(M); length -= 16; inOff += 16; } // // load in the remainder. // while (length > 0) { Update(input[inOff]); inOff++; length--; } } internal void ProcessChecksum(byte[] m) { int L = C[15]; for (var i=0;i<16;i++) { C[i] ^= S[(m[i] ^ L) & 0xff]; L = C[i]; } } internal void ProcessBlock(byte[] m) { for (var i=0;i<16;i++) { X[i+16] = m[i]; X[i+32] = (byte)(m[i] ^ X[i]); } // encrypt block var t = 0; for (var j=0;j<18;j++) { for (var k=0;k<48;k++) { t = X[k] ^= S[t]; t = t & 0xff; } t = (t + j)%256; } } // 256-byte random permutation constructed from the digits of PI private static readonly byte[] S = { (byte)41,(byte)46,(byte)67,(byte)201,(byte)162,(byte)216,(byte)124, (byte)1,(byte)61,(byte)54,(byte)84,(byte)161,(byte)236,(byte)240, (byte)6,(byte)19,(byte)98,(byte)167,(byte)5,(byte)243,(byte)192, (byte)199,(byte)115,(byte)140,(byte)152,(byte)147,(byte)43,(byte)217, (byte)188,(byte)76,(byte)130,(byte)202,(byte)30,(byte)155,(byte)87, (byte)60,(byte)253,(byte)212,(byte)224,(byte)22,(byte)103,(byte)66, (byte)111,(byte)24,(byte)138,(byte)23,(byte)229,(byte)18,(byte)190, (byte)78,(byte)196,(byte)214,(byte)218,(byte)158,(byte)222,(byte)73, (byte)160,(byte)251,(byte)245,(byte)142,(byte)187,(byte)47,(byte)238, (byte)122,(byte)169,(byte)104,(byte)121,(byte)145,(byte)21,(byte)178, (byte)7,(byte)63,(byte)148,(byte)194,(byte)16,(byte)137,(byte)11, (byte)34,(byte)95,(byte)33,(byte)128,(byte)127,(byte)93,(byte)154, (byte)90,(byte)144,(byte)50,(byte)39,(byte)53,(byte)62,(byte)204, (byte)231,(byte)191,(byte)247,(byte)151,(byte)3,(byte)255,(byte)25, (byte)48,(byte)179,(byte)72,(byte)165,(byte)181,(byte)209,(byte)215, (byte)94,(byte)146,(byte)42,(byte)172,(byte)86,(byte)170,(byte)198, (byte)79,(byte)184,(byte)56,(byte)210,(byte)150,(byte)164,(byte)125, (byte)182,(byte)118,(byte)252,(byte)107,(byte)226,(byte)156,(byte)116, (byte)4,(byte)241,(byte)69,(byte)157,(byte)112,(byte)89,(byte)100, (byte)113,(byte)135,(byte)32,(byte)134,(byte)91,(byte)207,(byte)101, (byte)230,(byte)45,(byte)168,(byte)2,(byte)27,(byte)96,(byte)37, (byte)173,(byte)174,(byte)176,(byte)185,(byte)246,(byte)28,(byte)70, (byte)97,(byte)105,(byte)52,(byte)64,(byte)126,(byte)15,(byte)85, (byte)71,(byte)163,(byte)35,(byte)221,(byte)81,(byte)175,(byte)58, (byte)195,(byte)92,(byte)249,(byte)206,(byte)186,(byte)197,(byte)234, (byte)38,(byte)44,(byte)83,(byte)13,(byte)110,(byte)133,(byte)40, (byte)132, 9,(byte)211,(byte)223,(byte)205,(byte)244,(byte)65, (byte)129,(byte)77,(byte)82,(byte)106,(byte)220,(byte)55,(byte)200, (byte)108,(byte)193,(byte)171,(byte)250,(byte)36,(byte)225,(byte)123, (byte)8,(byte)12,(byte)189,(byte)177,(byte)74,(byte)120,(byte)136, (byte)149,(byte)139,(byte)227,(byte)99,(byte)232,(byte)109,(byte)233, (byte)203,(byte)213,(byte)254,(byte)59,(byte)0,(byte)29,(byte)57, (byte)242,(byte)239,(byte)183,(byte)14,(byte)102,(byte)88,(byte)208, (byte)228,(byte)166,(byte)119,(byte)114,(byte)248,(byte)235,(byte)117, (byte)75,(byte)10,(byte)49,(byte)68,(byte)80,(byte)180,(byte)143, (byte)237,(byte)31,(byte)26,(byte)219,(byte)153,(byte)141,(byte)51, (byte)159,(byte)17,(byte)131,(byte)20 }; public IMemoable Copy() { return new MD2Digest(this); } public void Reset(IMemoable other) { var d = (MD2Digest)other; CopyIn(d); } } }
using System; using System.Collections.Generic; using Fasterflect; using Playblack.EventSystem; using Playblack.EventSystem.Events; using Playblack.Pooling; using Playblack.Savegame; using UnityEngine; namespace Playblack.Csp { public delegate void SimpleSignal(); public delegate void ParameterSignal(string param); /// <summary> /// Tracks and manages signals coming in and out of the gameobject this handler is attached to. /// </summary> [DisallowMultipleComponent] [SaveableComponent] public class SignalProcessor : MonoBehaviour { /// <summary> /// When true, the FireOutput will, at the end of the execution, /// dump the traced signal processing chain into the console. /// </summary> [SerializeField] [SaveableField(SaveField.FIELD_PRIMITIVE)] public bool debug; /// <summary> /// Flag to indicate if an output is currently being processed. /// This is used to get correct debug output when a chain is running /// with multiple consecutive outputs and these are fired on the same signal processor. /// Otherwise it could lead to multiple outputs being dumped into the console. /// And that's weird. /// </summary> private bool outputChainActive; /// <summary> /// Next time a FireOutput is called, this trace is used, /// instead of a new one. This is useful when the fired output /// is a cause on an InputFunc /// </summary> private Trace currentTrace; /// <summary> /// Signals this Entity can receive and process. /// This list represents volatile information and needs to be rebuilt /// manually each time a signal processor is instantiated /// </summary> protected Dictionary<string, List<InputFunc>> inputFuncs; public Dictionary<string, List<InputFunc>> InputFuncs { get { if (this.inputFuncs == null || this.inputFuncs.Count == 0) { this.RebuildInputs(); } return this.inputFuncs; } } [SerializeField] [SaveableField(SaveField.FIELD_PROTOBUF_OBJECT)] protected List<OutputFunc> outputs; public List<OutputFunc> Outputs { get { if (this.outputs == null) { this.ReadOutputs(); } return this.outputs; } } /// <summary> /// This cache is used to speed up the lookups for input funcs on components by remembering /// their type and all attached attributes to it. /// </summary> private readonly GenericObjectPoolMap<Type, InputFuncAttribute[]> inputFuncCache = new GenericObjectPoolMap<Type, InputFuncAttribute[]>(10, 50); public InputFunc GetInputFunc(string name, string component) { if (inputFuncs == null || inputFuncs.Count == 0) { this.RebuildInputs(); } if (!inputFuncs.ContainsKey(component)) { Debug.Log("Component " + component + " is not part of this GameObject. No InputFunc for it can be found."); return null; } for (int i = 0; i < inputFuncs[component].Count; ++i) { if (inputFuncs[component][i].Name == name) { return inputFuncs[component][i]; } } return null; } /// <summary> /// Call this to rebuild the input funcs. /// This needs to be called everytime the signalprocessor object is instantiated. /// The data is used in OutputEvent. It will look in a SignalProcessors input-list /// for things to call when an output is fired. /// Also use this if you know that a new CSP component was added after the CSP /// and the InputFunc list is already populated. /// </summary> public void RebuildInputs() { inputFuncCache.SetIgnoreInUse(true); // Debug.Log("Rebuilding InputFunc cache on " + this.gameObject.outputName); var components = GetComponents<Component>(); if (inputFuncs == null) { inputFuncs = new Dictionary<string, List<InputFunc>>(); } else { inputFuncs.Clear(); } for (int i = 0; i < components.Length; ++i) { var type = components[i].GetType(); var methods = type.MethodsWith(Flags.InstancePublic, typeof(InputFuncAttribute)); InputFuncAttribute[] attribs = null; if (inputFuncCache.Has(type)) { attribs = inputFuncCache.Get(type); } else { var attribList = new List<InputFuncAttribute>(methods.Count / 2); // round about this number as init capacity for (int j = 0; j < methods.Count; ++j) { attribList.Add(methods[j].Attribute<InputFuncAttribute>()); } attribs = attribList.ToArray(); inputFuncCache.Add(type, attribs); // next time a processor sees this component, all the lookup reflection will be spared } if (attribs == null) { continue; } for (int j = 0; j < attribs.Length; ++j) { try { if (attribs[j].WithParameter) { var del = (ParameterSignal)Delegate.CreateDelegate(typeof(ParameterSignal), components[i], attribs[j].MethodName); DefineInputFunc(attribs[j].DisplayName, type.ToString(), del); } else { var del = (SimpleSignal)Delegate.CreateDelegate(typeof(SimpleSignal), components[i], attribs[j].MethodName); DefineInputFunc(attribs[j].DisplayName, type.ToString(), del); } } catch (Exception e) { Debug.LogError( "You defined an inputfunc (" + attribs[j].MethodName + ") on " + type + " that is not applicable to the CSP.\n" + e.Message + "\n" + e.StackTrace ); } } } } /// <summary> /// Reads all known outputs from all components on the game object. /// Beware: Calling this causes data loss on outputs that got renamed! /// Should be called from an editor only. /// </summary> public void ReadOutputs() { var newOutputList = new List<string>(); var components = GetComponents<Component>(); // First: Read out all outputs for (int i = 0; i < components.Length; ++i) { var t = components[i].GetType(); if (!t.IsDefined(typeof(OutputAwareAttribute), true)) { continue; } var attribs = (OutputAwareAttribute[])t.GetCustomAttributes(typeof(OutputAwareAttribute), true); for (int j = 0; j < attribs.Length; ++j) { newOutputList.AddRange(attribs[j].Outputs); } } if (outputs != null) { var toRemove = new List<OutputFunc>(); // Clear out things that do not exist anymore. for (int i = 0; i < outputs.Count; ++i) { if (!newOutputList.Contains(outputs[i].Name)) { // Doesn't exist anymore. toRemove.Add(outputs[i]); } } for (int i = 0; i < toRemove.Count; ++i) { outputs.Remove(toRemove[i]); } } else { outputs = new List<OutputFunc>(); } for (int i = 0; i < newOutputList.Count; ++i) { DefineOutput(newOutputList[i]); } } /// <summary> /// Links an editor callback outputName to a method inside this entity. /// This data is exposed for the I/O system. /// </summary> /// <param outputName="name">Name.</param> /// <param outputName = "component"></param> /// <param outputName="callback">Callback.</param> protected void DefineInputFunc(string name, string component, SimpleSignal callback) { if (!inputFuncs.ContainsKey(component)) { inputFuncs.Add(component, new List<InputFunc>(5)); } this.inputFuncs[component].Add(new SimpleInputFunc(name, callback)); } /// <summary> /// Links an editor callback outputName to a method inside this entity. /// This data is exposed for the I/O system. /// </summary> /// <param outputName="name">Name.</param> /// <param outputName = "component"></param> /// <param outputName="callback">Callback.</param> protected void DefineInputFunc(string name, string component, ParameterSignal callback) { if (!inputFuncs.ContainsKey(component)) { inputFuncs.Add(component, new List<InputFunc>(5)); } this.inputFuncs[component].Add(new ParameterInputFunc(name, callback)); } /// <summary> /// Declares an output event. /// InputFunc objects get attached to these events. They are identified by their names. /// Previously declared output events cannot be re-declared. /// </summary> /// <param outputName="name">Name.</param> protected void DefineOutput(string name) { for (int i = 0; i < outputs.Count; ++i) { if (outputs[i].Name == name) { Debug.LogWarning(name + " is already declared as output. Calls to it will be grouped into the existing version!"); return; } } this.outputs.Add(new OutputFunc(name)); } /// <summary> /// Makes the signal handler fire an output with the given outputName. /// This will trigger all outputs in all components filed under this outputName. /// This could reach deactivated game objects but it will not because it is invoked /// by an extension method that calls SendMessage and that only works on active objects. /// You could, for instance, turn a receiver on or off with this but you couldn't raise /// an Output directly on a disabled gameobject /// </summary> /// <param name="outputName">Name.</param> public void FireOutput(string outputName) { Trace localTrace; if (currentTrace != null && !currentTrace.HasReturnedToCaller) { localTrace = currentTrace; currentTrace = null; } else { localTrace = new Trace(this); } bool isActivator = !outputChainActive; if (isActivator) { outputChainActive = true; } for (int i = 0; i < outputs.Count; ++i) { if (outputs[i].Name == outputName) { outputs[i].Invoke(this, localTrace); break; } } if (isActivator) { outputChainActive = false; } if (debug && isActivator) { Debug.Log(localTrace.GetTraceAsStringBuilder().ToString()); } localTrace.HasReturnedToCaller = true; currentTrace = null; // Make sur we ain't holding on to this thing } /// <summary> /// Set a transient trace object. /// Next time a FireOutput is called, this trace is used, /// instead of a new one. This is useful when the fired output /// is a cause on an InputFunc /// </summary> /// <param name="trace"></param> public void SetTrace(Trace trace) { currentTrace = trace; } /// <summary> /// Runs through all known output signals and hooks up the linking information to real gameobjects in the scene. /// This usually must be called after loading a game or to clean up linking information. /// /// NOTE: On a clean / default scene this data gets fed in by unity and will be correct. /// This is only required after loading a save game. /// </summary> private void ConnectOutputSignals() { if (outputs == null) { outputs = new List<OutputFunc>(); return; } for (int i = 0; i < outputs.Count; ++i) { if (outputs[i].Listeners == null) { continue; } for (int j = 0; j < outputs[i].Listeners.Count; ++j) { // Finds and re-connects the inputs for signal handlers in the scene outputs[i].Listeners[j].FindTargetProcessors(this); } } } private void OnSaveGameLoaded(SaveGameLoadedEvent hook) { RebuildInputs(); ConnectOutputSignals(); } #region Unity Related public void Awake() { // SignalProcessorTracker.Instance.Track(this); EventDispatcher.Instance.Register<SaveGameLoadedEvent>(OnSaveGameLoaded); RebuildInputs(); } public void OnDestroy() { // SignalProcessorTracker.Instance.Untrack(this); EventDispatcher.Instance.Unregister<SaveGameLoadedEvent>(OnSaveGameLoaded); currentTrace = null; } #endregion Unity Related } }
/* * REST API Documentation for the MOTI School Bus Application * * The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus. * * OpenAPI spec version: v1 * * */ using System; using System.Text; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations.Schema; namespace SchoolBusAPI.Models { /// <summary> /// The users associated with a given group that has been defined in the application. /// </summary> [MetaDataExtension (Description = "The users associated with a given group that has been defined in the application.")] public partial class GroupMembership : AuditableEntity, IEquatable<GroupMembership> { /// <summary> /// Default constructor, required by entity framework /// </summary> public GroupMembership() { this.Id = 0; } /// <summary> /// Initializes a new instance of the <see cref="GroupMembership" /> class. /// </summary> /// <param name="Id">A system-generated unique identifier for a GroupMembership (required).</param> /// <param name="Active">A flag indicating the User is active in the group. Set false to remove the user from the designated group. (required).</param> /// <param name="Group">A foreign key reference to the system-generated unique identifier for a Group.</param> /// <param name="User">A foreign key reference to the system-generated unique identifier for a User.</param> public GroupMembership(int Id, bool Active, Group Group = null, User User = null) { this.Id = Id; this.Active = Active; this.Group = Group; this.User = User; } /// <summary> /// A system-generated unique identifier for a GroupMembership /// </summary> /// <value>A system-generated unique identifier for a GroupMembership</value> [MetaDataExtension (Description = "A system-generated unique identifier for a GroupMembership")] public int Id { get; set; } /// <summary> /// A flag indicating the User is active in the group. Set false to remove the user from the designated group. /// </summary> /// <value>A flag indicating the User is active in the group. Set false to remove the user from the designated group.</value> [MetaDataExtension (Description = "A flag indicating the User is active in the group. Set false to remove the user from the designated group.")] public bool Active { get; set; } /// <summary> /// A foreign key reference to the system-generated unique identifier for a Group /// </summary> /// <value>A foreign key reference to the system-generated unique identifier for a Group</value> [MetaDataExtension (Description = "A foreign key reference to the system-generated unique identifier for a Group")] public Group Group { get; set; } /// <summary> /// Foreign key for Group /// </summary> [ForeignKey("Group")] [JsonIgnore] [MetaDataExtension (Description = "A foreign key reference to the system-generated unique identifier for a Group")] public int? GroupId { get; set; } /// <summary> /// A foreign key reference to the system-generated unique identifier for a User /// </summary> /// <value>A foreign key reference to the system-generated unique identifier for a User</value> [MetaDataExtension (Description = "A foreign key reference to the system-generated unique identifier for a User")] public User User { get; set; } /// <summary> /// Foreign key for User /// </summary> [ForeignKey("User")] [JsonIgnore] [MetaDataExtension (Description = "A foreign key reference to the system-generated unique identifier for a User")] public int? UserId { 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 GroupMembership {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Active: ").Append(Active).Append("\n"); sb.Append(" Group: ").Append(Group).Append("\n"); sb.Append(" User: ").Append(User).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((GroupMembership)obj); } /// <summary> /// Returns true if GroupMembership instances are equal /// </summary> /// <param name="other">Instance of GroupMembership to be compared</param> /// <returns>Boolean</returns> public bool Equals(GroupMembership other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return ( this.Id == other.Id || this.Id.Equals(other.Id) ) && ( this.Active == other.Active || this.Active.Equals(other.Active) ) && ( this.Group == other.Group || this.Group != null && this.Group.Equals(other.Group) ) && ( this.User == other.User || this.User != null && this.User.Equals(other.User) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks hash = hash * 59 + this.Id.GetHashCode(); hash = hash * 59 + this.Active.GetHashCode(); if (this.Group != null) { hash = hash * 59 + this.Group.GetHashCode(); } if (this.User != null) { hash = hash * 59 + this.User.GetHashCode(); } return hash; } } #region Operators /// <summary> /// Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator ==(GroupMembership left, GroupMembership right) { return Equals(left, right); } /// <summary> /// Not Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator !=(GroupMembership left, GroupMembership right) { return !Equals(left, right); } #endregion Operators } }
using System; using System.Diagnostics; using System.Linq; using System.Numerics; using Nethereum.Hex.HexConvertors.Extensions; using Xunit; namespace Nethereum.ABI.UnitTests { public class IntEncodingTests { public enum TestEnum { Monkey, Elephant, Lion } public BigInteger ToTwosComplement(BigInteger value) { if (value.Sign < 0) return new BigInteger("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" .HexToByteArray()) + value + 1; return value; } public BigInteger FromTwosComplement(string value) { return new BigInteger(value.HexToByteArray().Reverse().ToArray()) - new BigInteger("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" .HexToByteArray()) - 1; } [Theory] [InlineData("-1000000000", "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffc4653600")] [InlineData("-124346577657532", "0xffffffffffffffffffffffffffffffffffffffffffffffffffff8ee84e68e144")] [InlineData("127979392992", "0x0000000000000000000000000000000000000000000000000000001dcc2a8fe0")] [InlineData("-37797598375987353", "0xffffffffffffffffffffffffffffffffffffffffffffffffff79b748d76fb767")] [InlineData("3457987492347979798742", "0x0000000000000000000000000000000000000000000000bb75377716692498d6")] public virtual void ShouldDecode(string expected, string hex) { var intType = new IntType("int"); var result = intType.Decode<BigInteger>(hex); Assert.Equal(expected, result.ToString()); } [Theory] [InlineData("-1000000000", "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffc4653600")] [InlineData("-124346577657532", "0xffffffffffffffffffffffffffffffffffffffffffffffffffff8ee84e68e144")] [InlineData("127979392992", "0x0000000000000000000000000000000000000000000000000000001dcc2a8fe0")] [InlineData("-37797598375987353", "0xffffffffffffffffffffffffffffffffffffffffffffffffff79b748d76fb767")] [InlineData("3457987492347979798742", "0x0000000000000000000000000000000000000000000000bb75377716692498d6")] public virtual void ShouldEncode(string value, string hexExpected) { var intType = new IntType("int"); var result = intType.Encode(BigInteger.Parse(value)); Assert.Equal(hexExpected, "0x" + result.ToHex()); } [Fact] public virtual void ShouldDecode0x989680() { var intType = new IntType("int"); var bytes = "0x00989680".HexToByteArray(); var result = intType.Decode<BigInteger>(bytes); Assert.Equal(new BigInteger(10000000), result); } [Fact] public virtual void ShouldDecodeByteArray() { var intType = new IntType("int"); var bytes = intType.Encode(100000569); var result = intType.Decode<BigInteger>(bytes); Assert.Equal(new BigInteger(100000569), result); } [Fact] public virtual void ShouldDecodeNegativeByteArray() { var intType = new IntType("int"); var bytes = intType.Encode(-100000569); var result = intType.Decode<BigInteger>(bytes); Assert.Equal(new BigInteger(-100000569), result); } [Fact] public virtual void ShouldDecodeNegativeIntString() { var intType = new IntType("int"); var result = intType.Decode<BigInteger>("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed2979"); Assert.Equal(new BigInteger(-1234567), result); } [Fact] public virtual void ShouldDecodeString() { var intType = new IntType("int"); var result = intType.Decode<BigInteger>("0x00000000000000000000000000000000000000000000000000000000000001e3"); Assert.Equal(new BigInteger(483), result); } [Fact] public virtual void ShouldDecodeStringLength() { var intType = new IntType("int"); var result = intType.Decode<BigInteger>("0x0000000000000000000000000000000000000000000000000000000000000020"); Assert.Equal(new BigInteger(32), result); } [Fact] public virtual void ShouldEncodeDecodeByte() { var intType = new IntType("uint8"); var result = intType.Encode(byte.MaxValue).ToHex(); var intresult = intType.Decode<byte>(result); Assert.Equal(byte.MaxValue, intresult); } [Fact] public virtual void ShouldEncodeDecodeEnum() { var intType = new IntType("int"); var result1 = intType.Encode(TestEnum.Monkey).ToHex(); var decresult1 = intType.Decode<TestEnum>(result1); Assert.Equal(TestEnum.Monkey, decresult1); var result2 = intType.Encode(TestEnum.Elephant).ToHex(); var decresult2 = intType.Decode<TestEnum>(result2); Assert.Equal(TestEnum.Elephant, decresult2); var result3 = intType.Encode(TestEnum.Lion).ToHex(); var decresult3 = intType.Decode<TestEnum>(result3); Assert.Equal(TestEnum.Lion, decresult3); } [Fact] public virtual void ShouldEncodeDecodeInt() { var intType = new IntType("int"); var result = intType.Encode(int.MaxValue).ToHex(); var intresult = intType.Decode<int>(result); Assert.Equal(int.MaxValue, intresult); } [Fact] public virtual void ShouldEncodeDecodeInt64() { var intType = new IntType("int64"); var result = intType.Encode(long.MaxValue).ToHex(); var intresult = intType.Decode<long>(result); Assert.Equal(long.MaxValue, intresult); } [Fact] public virtual void ShouldEncodeDecodeSByte() { var intType = new IntType("int8"); var result = intType.Encode(sbyte.MaxValue).ToHex(); var intresult = intType.Decode<sbyte>(result); Assert.Equal(sbyte.MaxValue, intresult); } [Fact] public virtual void ShouldEncodeDecodeShort() { var intType = new IntType("int16"); var result = intType.Encode(short.MaxValue).ToHex(); var intresult = intType.Decode<short>(result); Assert.Equal(short.MaxValue, intresult); } [Fact] public virtual void ShouldEncodeDecodeUInt64() { var intType = new IntType("uint64"); var result = intType.Encode(ulong.MaxValue).ToHex(); var intresult = intType.Decode<ulong>(result); Assert.Equal(ulong.MaxValue, intresult); } [Fact] public virtual void ShouldEncodeDecodeUShort() { var intType = new IntType("uint16"); var result = intType.Encode(ushort.MaxValue).ToHex(); var intresult = intType.Decode<ushort>(result); Assert.Equal(ushort.MaxValue, intresult); } [Fact] public virtual void ShouldEncodeInt() { var intType = new IntType("int"); var result = intType.Encode(69).ToHex(); Assert.Equal("0000000000000000000000000000000000000000000000000000000000000045", result); } [Fact] public virtual void ShouldEncodeNegativeInt() { var intType = new IntType("int"); var result = intType.Encode(-1234567).ToHex(); Assert.Equal("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed2979", result); } [Fact] public virtual void ShouldEncodeStrings() { var intType = new IntType("int"); var result2 = intType.Encode("1234567890abcdef1234567890abcdef12345678").ToHex(); Assert.Equal("0000000000000000000000001234567890abcdef1234567890abcdef12345678", result2); } [Fact] public virtual void ShouldEncodeUInt() { var intType = new IntType("uint"); uint given = 1234567; var result = intType.Encode(given).ToHex(); Assert.Equal("000000000000000000000000000000000000000000000000000000000012d687", result); } [Fact] public virtual void ShouldThrowErrorWhenEncodingExceedingUintMaxValue() { var intType = new IntType("uint"); var given = IntType.MAX_UINT256_VALUE + 1; var ex = Assert.Throws<ArgumentOutOfRangeException>("value", () => intType.Encode(given)); Assert.StartsWith("Unsigned SmartContract integer must not exceed maximum value for uint256", ex.Message); } [Fact] public virtual void ShouldThrowErrorWhenEncodingIsLessThanUintMaxValue() { var intType = new IntType("uint"); var given = IntType.MIN_UINT_VALUE - 1; var ex = Assert.Throws<ArgumentOutOfRangeException>("value", () => intType.Encode(given)); Assert.StartsWith("Unsigned SmartContract integer must not be less than the minimum value of uint:", ex.Message); } [Fact] public virtual void ShouldThrowErrorWhenEncodingExceedingIntMaxValue() { var intType = new IntType("int"); var given = IntType.MAX_INT256_VALUE + 1; var ex = Assert.Throws<ArgumentOutOfRangeException>("value", () => intType.Encode(given)); Assert.StartsWith("Signed SmartContract integer must not exceed maximum value for int256", ex.Message); } [Fact] public virtual void ShouldThrowErrorWhenEncodingIsLessThanIntMinValue() { var intType = new IntType("int"); var given = IntType.MIN_INT256_VALUE - 1; var ex = Assert.Throws<ArgumentOutOfRangeException>("value", () => intType.Encode(given)); Assert.StartsWith("Signed SmartContract integer must not be less than the minimum value for int256", ex.Message); } [Fact] public virtual void ShouldThrowErrorWhenValueIsNull() { var intType = new IntType("int"); object given = null; var ex = Assert.Throws<Exception>(() => intType.Encode(given)); Assert.Equal("Invalid value for type 'Nethereum.ABI.Encoders.IntTypeEncoder'. Value: null, ValueType: ()", ex.Message); } [Fact] public void Test() { Debug.WriteLine(ToTwosComplement(-37797598375987353).ToByteArray().Reverse().ToArray().ToHex()); Debug.WriteLine(FromTwosComplement("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffc4653600")); Debug.WriteLine(FromTwosComplement("0xffffffffffffffffffffffffffffffffffffffffffffffffffff8ee84e68e144")); Debug.WriteLine(FromTwosComplement("0xffffffffffffffffffffffffffffffffffffffffffffffffff79b748d76fb767")); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using ZipCodeFinal.Areas.HelpPage.ModelDescriptions; using ZipCodeFinal.Areas.HelpPage.Models; namespace ZipCodeFinal.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq.Expressions; using System.Reflection; namespace System.Threading.Tasks { using FluentValidation.Internal; internal static class TaskHelpersExtensions { private static readonly Type[] EmptyTypes = new Type[0]; private static readonly Task<AsyncVoid> DefaultCompleted = TaskHelpers.FromResult<AsyncVoid>(default(AsyncVoid)); private static readonly Action<Task> RethrowWithNoStackLossDelegate = GetRethrowWithNoStackLossDelegate(); // <summary> // Calls the given continuation, after the given task completes, if it ends in a faulted or canceled state. // Will not be called if the task did not fault or cancel (meaning, it will not be called if the task ran // to completion). Intended to roughly emulate C# 5's support for "try/catch" in // async methods. Note that this method allows you to return a Task, so that you can either return // a completed Task (indicating that you swallowed the exception) or a faulted task (indicating that // that the exception should be propagated). In C#, you cannot normally use await within a catch // block, so returning a real async task should never be done from Catch(). // </summary> internal static Task Catch(this Task task, Func<CatchInfo, CatchInfo.CatchResult> continuation, CancellationToken cancellationToken = default(CancellationToken)) { // Fast path for successful tasks, to prevent an extra TCS allocation if (task.Status == TaskStatus.RanToCompletion) { return task; } return task.CatchImpl(() => continuation(new CatchInfo(task, cancellationToken)).Task.ToTask<AsyncVoid>(), cancellationToken); } // <summary> // Calls the given continuation, after the given task completes, if it ends in a faulted or canceled state. // Will not be called if the task did not fault or cancel (meaning, it will not be called if the task ran // to completion). Intended to roughly emulate C# 5's support for "try/catch" in // async methods. Note that this method allows you to return a Task, so that you can either return // a completed Task (indicating that you swallowed the exception) or a faulted task (indicating that // that the exception should be propagated). In C#, you cannot normally use await within a catch // block, so returning a real async task should never be done from Catch(). // </summary> internal static Task<TResult> Catch<TResult>(this Task<TResult> task, Func<CatchInfo<TResult>, CatchInfo<TResult>.CatchResult> continuation, CancellationToken cancellationToken = default(CancellationToken)) { // Fast path for successful tasks, to prevent an extra TCS allocation if (task.Status == TaskStatus.RanToCompletion) { return task; } return task.CatchImpl(() => continuation(new CatchInfo<TResult>(task, cancellationToken)).Task, cancellationToken); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The caught exception type is reflected into a faulted task.")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "CatchInfo", Justification = "This is the name of a class.")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "TaskHelpersExtensions", Justification = "This is the name of a class.")] private static Task<TResult> CatchImpl<TResult>(this Task task, Func<Task<TResult>> continuation, CancellationToken cancellationToken) { // Stay on the same thread if we can if (task.IsCompleted) { if (task.IsFaulted || task.IsCanceled || cancellationToken.IsCancellationRequested) { try { Task<TResult> resultTask = continuation(); if (resultTask == null) { // Not a resource because this is an internal class, and this is a guard clause that's intended // to be thrown by us to us, never escaping out to end users. throw new InvalidOperationException("You must set the Task property of the CatchInfo returned from the TaskHelpersExtensions.Catch continuation."); } return resultTask; } catch (Exception ex) { return TaskHelpers.FromError<TResult>(ex); } } if (task.Status == TaskStatus.RanToCompletion) { TaskCompletionSource<TResult> tcs = new TaskCompletionSource<TResult>(); tcs.TrySetFromTask(task); return tcs.Task; } } // Split into a continuation method so that we don't create a closure unnecessarily return CatchImplContinuation(task, continuation); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The caught exception type is reflected into a faulted task.")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "TaskHelpersExtensions", Justification = "This is the name of a class.")] [SuppressMessage("Microsoft.Web.FxCop", "MW1201:DoNotCallProblematicMethodsOnTask", Justification = "The usages here are deemed safe, and provide the implementations that this rule relies upon.")] private static Task<TResult> CatchImplContinuation<TResult>(Task task, Func<Task<TResult>> continuation) { TaskCompletionSource<Task<TResult>> tcs = new TaskCompletionSource<Task<TResult>>(); // this runs only if the inner task did not fault task.ContinueWith(innerTask => tcs.TrySetFromTask(innerTask), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously); // this runs only if the inner task faulted task.ContinueWith(innerTask => { try { Task<TResult> resultTask = continuation(); if (resultTask == null) { throw new InvalidOperationException("You cannot return null from the TaskHelpersExtensions.Catch continuation. You must return a valid task or throw an exception."); } tcs.TrySetResult(resultTask); } catch (Exception ex) { tcs.TrySetException(ex); } }, TaskContinuationOptions.NotOnRanToCompletion); return tcs.Task.FastUnwrap(); } // <summary> // Upon completion of the task, copies its result into the given task completion source, regardless of the // completion state. This causes the original task to be fully observed, and the task that is returned by // this method will always successfully run to completion, regardless of the original task state. // Since this method consumes a task with no return value, you must provide the return value to be used // when the inner task ran to successful completion. // </summary> internal static Task CopyResultToCompletionSource<TResult>(this Task task, TaskCompletionSource<TResult> tcs, TResult completionResult) { return task.CopyResultToCompletionSourceImpl(tcs, innerTask => completionResult); } // <summary> // Upon completion of the task, copies its result into the given task completion source, regardless of the // completion state. This causes the original task to be fully observed, and the task that is returned by // this method will always successfully run to completion, regardless of the original task state. // </summary> [SuppressMessage("Microsoft.Web.FxCop", "MW1201:DoNotCallProblematicMethodsOnTask", Justification = "The usages here are deemed safe, and provide the implementations that this rule relies upon.")] internal static Task CopyResultToCompletionSource<TResult>(this Task<TResult> task, TaskCompletionSource<TResult> tcs) { return task.CopyResultToCompletionSourceImpl(tcs, innerTask => innerTask.Result); } private static Task CopyResultToCompletionSourceImpl<TTask, TResult>(this TTask task, TaskCompletionSource<TResult> tcs, Func<TTask, TResult> resultThunk) where TTask : Task { // Stay on the same thread if we can if (task.IsCompleted) { switch (task.Status) { case TaskStatus.Canceled: case TaskStatus.Faulted: TaskHelpers.TrySetFromTask(tcs, task); break; case TaskStatus.RanToCompletion: tcs.TrySetResult(resultThunk(task)); break; } return TaskHelpers.Completed(); } // Split into a continuation method so that we don't create a closure unnecessarily return CopyResultToCompletionSourceImplContinuation(task, tcs, resultThunk); } [SuppressMessage("Microsoft.Web.FxCop", "MW1201:DoNotCallProblematicMethodsOnTask", Justification = "The usages here are deemed safe, and provide the implementations that this rule relies upon.")] private static Task CopyResultToCompletionSourceImplContinuation<TTask, TResult>(TTask task, TaskCompletionSource<TResult> tcs, Func<TTask, TResult> resultThunk) where TTask : Task { return task.ContinueWith(innerTask => { switch (innerTask.Status) { case TaskStatus.Canceled: case TaskStatus.Faulted: TaskHelpers.TrySetFromTask(tcs, innerTask); break; case TaskStatus.RanToCompletion: tcs.TrySetResult(resultThunk(task)); break; } }, TaskContinuationOptions.ExecuteSynchronously); } // <summary> // Cast Task to Task of object // </summary> [SuppressMessage("Microsoft.Web.FxCop", "MW1201:DoNotCallProblematicMethodsOnTask", Justification = "The usages here are deemed safe, and provide the implementations that this rule relies upon.")] internal static Task<object> CastToObject(this Task task) { // Stay on the same thread if we can if (task.IsCompleted) { if (task.IsFaulted) { return TaskHelpers.FromErrors<object>(task.Exception.InnerExceptions); } if (task.IsCanceled) { return TaskHelpers.Canceled<object>(); } if (task.Status == TaskStatus.RanToCompletion) { return TaskHelpers.FromResult<object>((object)null); } } TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(); // schedule a synchronous task to cast: no need to worry about sync context or try/catch task.ContinueWith(innerTask => { if (innerTask.IsFaulted) { tcs.SetException(innerTask.Exception.InnerExceptions); } else if (innerTask.IsCanceled) { tcs.SetCanceled(); } else { tcs.SetResult((object)null); } }, TaskContinuationOptions.ExecuteSynchronously); return tcs.Task; } // <summary> // Cast Task of T to Task of object // </summary> [SuppressMessage("Microsoft.Web.FxCop", "MW1201:DoNotCallProblematicMethodsOnTask", Justification = "The usages here are deemed safe, and provide the implementations that this rule relies upon.")] internal static Task<object> CastToObject<T>(this Task<T> task) { // Stay on the same thread if we can if (task.IsCompleted) { if (task.IsFaulted) { return TaskHelpers.FromErrors<object>(task.Exception.InnerExceptions); } if (task.IsCanceled) { return TaskHelpers.Canceled<object>(); } if (task.Status == TaskStatus.RanToCompletion) { return TaskHelpers.FromResult<object>((object)task.Result); } } TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(); // schedule a synchronous task to cast: no need to worry about sync context or try/catch task.ContinueWith(innerTask => { if (innerTask.IsFaulted) { tcs.SetException(innerTask.Exception.InnerExceptions); } else if (innerTask.IsCanceled) { tcs.SetCanceled(); } else { tcs.SetResult((object)innerTask.Result); } }, TaskContinuationOptions.ExecuteSynchronously); return tcs.Task; } // <summary> // Cast Task of object to Task of T // </summary> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The caught exception type is reflected into a faulted task.")] [SuppressMessage("Microsoft.Web.FxCop", "MW1201:DoNotCallProblematicMethodsOnTask", Justification = "The usages here are deemed safe, and provide the implementations that this rule relies upon.")] internal static Task<TOuterResult> CastFromObject<TOuterResult>(this Task<object> task) { // Stay on the same thread if we can if (task.IsCompleted) { if (task.IsFaulted) { return TaskHelpers.FromErrors<TOuterResult>(task.Exception.InnerExceptions); } if (task.IsCanceled) { return TaskHelpers.Canceled<TOuterResult>(); } if (task.Status == TaskStatus.RanToCompletion) { try { return TaskHelpers.FromResult<TOuterResult>((TOuterResult)task.Result); } catch (Exception exception) { return TaskHelpers.FromError<TOuterResult>(exception); } } } TaskCompletionSource<TOuterResult> tcs = new TaskCompletionSource<TOuterResult>(); // schedule a synchronous task to cast: no need to worry about sync context or try/catch task.ContinueWith(innerTask => { if (innerTask.IsFaulted) { tcs.SetException(innerTask.Exception.InnerExceptions); } else if (innerTask.IsCanceled) { tcs.SetCanceled(); } else { try { tcs.SetResult((TOuterResult)innerTask.Result); } catch (Exception exception) { tcs.SetException(exception); } } }, TaskContinuationOptions.ExecuteSynchronously); return tcs.Task; } // <summary> // A version of task.Unwrap that is optimized to prevent unnecessarily capturing the // execution context when the antecedent task is already completed. // </summary> [SuppressMessage("Microsoft.Web.FxCop", "MW1202:DoNotUseProblematicTaskTypes", Justification = "The usages here are deemed safe, and provide the implementations that this rule relies upon.")] [SuppressMessage("Microsoft.Web.FxCop", "MW1201:DoNotCallProblematicMethodsOnTask", Justification = "The usages here are deemed safe, and provide the implementations that this rule relies upon.")] internal static Task FastUnwrap(this Task<Task> task) { Task innerTask = task.Status == TaskStatus.RanToCompletion ? task.Result : null; return innerTask ?? task.Unwrap(); } // <summary> // A version of task.Unwrap that is optimized to prevent unnecessarily capturing the // execution context when the antecedent task is already completed. // </summary> [SuppressMessage("Microsoft.Web.FxCop", "MW1202:DoNotUseProblematicTaskTypes", Justification = "The usages here are deemed safe, and provide the implementations that this rule relies upon.")] [SuppressMessage("Microsoft.Web.FxCop", "MW1201:DoNotCallProblematicMethodsOnTask", Justification = "The usages here are deemed safe, and provide the implementations that this rule relies upon.")] internal static Task<TResult> FastUnwrap<TResult>(this Task<Task<TResult>> task) { Task<TResult> innerTask = task.Status == TaskStatus.RanToCompletion ? task.Result : null; return innerTask ?? task.Unwrap(); } // <summary> // Calls the given continuation, after the given task has completed, regardless of the state // the task ended in. Intended to roughly emulate C# 5's support for "finally" in async methods. // </summary> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The caught exception type is reflected into a faulted task.")] internal static Task Finally(this Task task, Action continuation, bool runSynchronously = false) { // Stay on the same thread if we can if (task.IsCompleted) { try { continuation(); return task; } catch (Exception ex) { MarkExceptionsObserved(task); return TaskHelpers.FromError(ex); } } // Split into a continuation method so that we don't create a closure unnecessarily return FinallyImplContinuation<AsyncVoid>(task, continuation, runSynchronously); } // <summary> // Calls the given continuation, after the given task has completed, regardless of the state // the task ended in. Intended to roughly emulate C# 5's support for "finally" in async methods. // </summary> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The caught exception type is reflected into a faulted task.")] internal static Task<TResult> Finally<TResult>(this Task<TResult> task, Action continuation, bool runSynchronously = false) { // Stay on the same thread if we can if (task.IsCompleted) { try { continuation(); return task; } catch (Exception ex) { MarkExceptionsObserved(task); return TaskHelpers.FromError<TResult>(ex); } } // Split into a continuation method so that we don't create a closure unnecessarily return FinallyImplContinuation<TResult>(task, continuation, runSynchronously); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The caught exception type is reflected into a faulted task.")] [SuppressMessage("Microsoft.Web.FxCop", "MW1201:DoNotCallProblematicMethodsOnTask", Justification = "The usages here are deemed safe, and provide the implementations that this rule relies upon.")] private static Task<TResult> FinallyImplContinuation<TResult>(Task task, Action continuation, bool runSynchronously = false) { TaskCompletionSource<TResult> tcs = new TaskCompletionSource<TResult>(); task.ContinueWith(innerTask => { try { continuation(); tcs.TrySetFromTask(innerTask); } catch (Exception ex) { MarkExceptionsObserved(innerTask); tcs.TrySetException(ex); } }, runSynchronously ? TaskContinuationOptions.ExecuteSynchronously : TaskContinuationOptions.None); return tcs.Task; } [SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes", Justification = "This general exception is not intended to be seen by the user")] [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "This general exception is not intended to be seen by the user")] [SuppressMessage("Microsoft.Web.FxCop", "MW1201:DoNotCallProblematicMethodsOnTask", Justification = "The usages here are deemed safe, and provide the implementations that this rule relies upon.")] private static Action<Task> GetRethrowWithNoStackLossDelegate() { #if NETFX_CORE return task => task.GetAwaiter().GetResult(); #else MethodInfo getAwaiterMethod = typeof(Task).GetDeclaredMethod("GetAwaiter"); if (getAwaiterMethod != null) { // .NET 4.5 - dump the same code the 'await' keyword would have dumped // >> task.GetAwaiter().GetResult() // No-ops if the task completed successfully, else throws the originating exception complete with the correct call stack. var taskParameter = Expression.Parameter(typeof(Task)); var getAwaiterCall = Expression.Call(taskParameter, getAwaiterMethod); var getResultCall = Expression.Call(getAwaiterCall, "GetResult", EmptyTypes); var lambda = Expression.Lambda<Action<Task>>(getResultCall, taskParameter); return lambda.Compile(); } else { Func<Exception, Exception> prepForRemoting = null; #if !PORTABLE && !PORTABLE40 && !CoreCLR try { if (AppDomain.CurrentDomain.IsFullyTrusted) { // .NET 4 - do the same thing Lazy<T> does by calling Exception.PrepForRemoting // This is an internal method in mscorlib.dll, so pass a test Exception to it to make sure we can call it. var exceptionParameter = Expression.Parameter(typeof(Exception)); var prepForRemotingCall = Expression.Call(exceptionParameter, "PrepForRemoting", EmptyTypes); var lambda = Expression.Lambda<Func<Exception, Exception>>(prepForRemotingCall, exceptionParameter); var func = lambda.Compile(); func(new Exception()); // make sure the method call succeeds before assigning the 'prepForRemoting' local variable prepForRemoting = func; } } catch { } // If delegate creation fails (medium trust) we will simply throw the base exception. #endif return task => { try { task.Wait(); } catch (AggregateException ex) { Exception baseException = ex.GetBaseException(); if (prepForRemoting != null) { baseException = prepForRemoting(baseException); } throw baseException; } }; } #endif } // <summary> // Marks a Task as "exception observed". The Task is required to have been completed first. // </summary> // <remarks> // Useful for 'finally' clauses, as if the 'finally' action throws we'll propagate the new // exception and lose track of the inner exception. // </remarks> [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "unused", Justification = "We only call the property getter for its side effect; we don't care about the value.")] private static void MarkExceptionsObserved(this Task task) { #if !WIN10 Contract.Assert(task.IsCompleted); #endif Exception unused = task.Exception; } // <summary> // Calls the given continuation, after the given task has completed, if the task successfully ran // to completion (i.e., was not canceled and did not fault). // </summary> internal static Task Then(this Task task, Action continuation, CancellationToken cancellationToken = default(CancellationToken), bool runSynchronously = false) { return task.ThenImpl(t => ToAsyncVoidTask(continuation), cancellationToken, runSynchronously); } // <summary> // Calls the given continuation, after the given task has completed, if the task successfully ran // to completion (i.e., was not canceled and did not fault). // </summary> internal static Task<TOuterResult> Then<TOuterResult>(this Task task, Func<TOuterResult> continuation, CancellationToken cancellationToken = default(CancellationToken), bool runSynchronously = false) { return task.ThenImpl(t => TaskHelpers.FromResult(continuation()), cancellationToken, runSynchronously); } // <summary> // Calls the given continuation, after the given task has completed, if the task successfully ran // to completion (i.e., was not cancelled and did not fault). // </summary> internal static Task Then(this Task task, Func<Task> continuation, CancellationToken cancellationToken = default(CancellationToken), bool runSynchronously = false) { return task.Then(() => continuation().Then(() => default(AsyncVoid)), cancellationToken, runSynchronously); } // <summary> // Calls the given continuation, after the given task has completed, if the task successfully ran // to completion (i.e., was not cancelled and did not fault). // </summary> internal static Task<TOuterResult> Then<TOuterResult>(this Task task, Func<Task<TOuterResult>> continuation, CancellationToken cancellationToken = default(CancellationToken), bool runSynchronously = false) { return task.ThenImpl(t => continuation(), cancellationToken, runSynchronously); } // <summary> // Calls the given continuation, after the given task has completed, if the task successfully ran // to completion (i.e., was not cancelled and did not fault). The continuation is provided with the // result of the task as its sole parameter. // </summary> [SuppressMessage("Microsoft.Web.FxCop", "MW1201:DoNotCallProblematicMethodsOnTask", Justification = "The usages here are deemed safe, and provide the implementations that this rule relies upon.")] internal static Task Then<TInnerResult>(this Task<TInnerResult> task, Action<TInnerResult> continuation, CancellationToken cancellationToken = default(CancellationToken), bool runSynchronously = false) { return task.ThenImpl(t => ToAsyncVoidTask(() => continuation(t.Result)), cancellationToken, runSynchronously); } // <summary> // Calls the given continuation, after the given task has completed, if the task successfully ran // to completion (i.e., was not canceled and did not fault). The continuation is provided with the // result of the task as its sole parameter. // </summary> [SuppressMessage("Microsoft.Web.FxCop", "MW1201:DoNotCallProblematicMethodsOnTask", Justification = "The usages here are deemed safe, and provide the implementations that this rule relies upon.")] internal static Task<TOuterResult> Then<TInnerResult, TOuterResult>(this Task<TInnerResult> task, Func<TInnerResult, TOuterResult> continuation, CancellationToken cancellationToken = default(CancellationToken), bool runSynchronously = false) { return task.ThenImpl(t => TaskHelpers.FromResult(continuation(t.Result)), cancellationToken, runSynchronously); } // <summary> // Calls the given continuation, after the given task has completed, if the task successfully ran // to completion (i.e., was not canceled and did not fault). The continuation is provided with the // result of the task as its sole parameter. // </summary> [SuppressMessage("Microsoft.Web.FxCop", "MW1201:DoNotCallProblematicMethodsOnTask", Justification = "The usages here are deemed safe, and provide the implementations that this rule relies upon.")] internal static Task Then<TInnerResult>(this Task<TInnerResult> task, Func<TInnerResult, Task> continuation, CancellationToken token = default(CancellationToken), bool runSynchronously = false) { return task.ThenImpl(t => continuation(t.Result).ToTask<AsyncVoid>(), token, runSynchronously); } // <summary> // Calls the given continuation, after the given task has completed, if the task successfully ran // to completion (i.e., was not canceled and did not fault). The continuation is provided with the // result of the task as its sole parameter. // </summary> [SuppressMessage("Microsoft.Web.FxCop", "MW1201:DoNotCallProblematicMethodsOnTask", Justification = "The usages here are deemed safe, and provide the implementations that this rule relies upon.")] internal static Task<TOuterResult> Then<TInnerResult, TOuterResult>(this Task<TInnerResult> task, Func<TInnerResult, Task<TOuterResult>> continuation, CancellationToken cancellationToken = default(CancellationToken), bool runSynchronously = false) { return task.ThenImpl(t => continuation(t.Result), cancellationToken, runSynchronously); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The caught exception type is reflected into a faulted task.")] private static Task<TOuterResult> ThenImpl<TTask, TOuterResult>(this TTask task, Func<TTask, Task<TOuterResult>> continuation, CancellationToken cancellationToken, bool runSynchronously) where TTask : Task { // Stay on the same thread if we can if (task.IsCompleted) { if (task.IsFaulted) { return TaskHelpers.FromErrors<TOuterResult>(task.Exception.InnerExceptions); } if (task.IsCanceled || cancellationToken.IsCancellationRequested) { return TaskHelpers.Canceled<TOuterResult>(); } if (task.Status == TaskStatus.RanToCompletion) { try { return continuation(task); } catch (Exception ex) { return TaskHelpers.FromError<TOuterResult>(ex); } } } // Split into a continuation method so that we don't create a closure unnecessarily return ThenImplContinuation(task, continuation, cancellationToken, runSynchronously); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The caught exception type is reflected into a faulted task.")] [SuppressMessage("Microsoft.Web.FxCop", "MW1201:DoNotCallProblematicMethodsOnTask", Justification = "The usages here are deemed safe, and provide the implementations that this rule relies upon.")] private static Task<TOuterResult> ThenImplContinuation<TOuterResult, TTask>(TTask task, Func<TTask, Task<TOuterResult>> continuation, CancellationToken cancellationToken, bool runSynchronously = false) where TTask : Task { TaskCompletionSource<Task<TOuterResult>> tcs = new TaskCompletionSource<Task<TOuterResult>>(); task.ContinueWith(innerTask => { if (innerTask.IsFaulted) { tcs.TrySetException(innerTask.Exception.InnerExceptions); } else if (innerTask.IsCanceled || cancellationToken.IsCancellationRequested) { tcs.TrySetCanceled(); } else { tcs.TrySetResult(continuation(task)); } }, runSynchronously ? TaskContinuationOptions.ExecuteSynchronously : TaskContinuationOptions.None); return tcs.Task.FastUnwrap(); } // <summary> // Throws the first faulting exception for a task which is faulted. It attempts to preserve the original // stack trace when throwing the exception (which should always work in 4.5, and should also work in 4.0 // when running in full trust). Note: It is the caller's responsibility not to pass incomplete tasks to // this method, because it does degenerate into a call to the equivalent of .Wait() on the task when it // hasn't yet completed. // </summary> internal static void ThrowIfFaulted(this Task task) { RethrowWithNoStackLossDelegate(task); } // <summary> // Adapts any action into a Task (returning AsyncVoid, so that it's usable with Task{T} extension methods). // </summary> private static Task<AsyncVoid> ToAsyncVoidTask(Action action) { return TaskHelpers.RunSynchronously<AsyncVoid>(() => { action(); return DefaultCompleted; }); } // <summary> // Changes the return value of a task to the given result, if the task ends in the RanToCompletion state. // This potentially imposes an extra ContinueWith to convert a non-completed task, so use this with caution. // </summary> internal static Task<TResult> ToTask<TResult>(this Task task, CancellationToken cancellationToken = default(CancellationToken), TResult result = default(TResult)) { if (task == null) { return null; } // Stay on the same thread if we can if (task.IsCompleted) { if (task.IsFaulted) { return TaskHelpers.FromErrors<TResult>(task.Exception.InnerExceptions); } if (task.IsCanceled || cancellationToken.IsCancellationRequested) { return TaskHelpers.Canceled<TResult>(); } if (task.Status == TaskStatus.RanToCompletion) { return TaskHelpers.FromResult(result); } } // Split into a continuation method so that we don't create a closure unnecessarily return ToTaskContinuation(task, result); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The caught exception type is reflected into a faulted task.")] [SuppressMessage("Microsoft.Web.FxCop", "MW1201:DoNotCallProblematicMethodsOnTask", Justification = "The usages here are deemed safe, and provide the implementations that this rule relies upon.")] private static Task<TResult> ToTaskContinuation<TResult>(Task task, TResult result) { TaskCompletionSource<TResult> tcs = new TaskCompletionSource<TResult>(); task.ContinueWith(innerTask => { if (task.Status == TaskStatus.RanToCompletion) { tcs.TrySetResult(result); } else { tcs.TrySetFromTask(innerTask); } }, TaskContinuationOptions.ExecuteSynchronously); return tcs.Task; } // <summary> // Attempts to get the result value for the given task. If the task ran to completion, then // it will return true and set the result value; otherwise, it will return false. // </summary> [SuppressMessage("Microsoft.Web.FxCop", "MW1201:DoNotCallProblematicMethodsOnTask", Justification = "The usages here are deemed safe, and provide the implementations that this rule relies upon.")] internal static bool TryGetResult<TResult>(this Task<TResult> task, out TResult result) { if (task.Status == TaskStatus.RanToCompletion) { result = task.Result; return true; } result = default(TResult); return false; } // <summary> // Used as the T in a "conversion" of a Task into a Task{T} // </summary> private struct AsyncVoid { } } [SuppressMessage("Microsoft.StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleClass", Justification = "Packaged as one file to make it easy to link against")] internal abstract class CatchInfoBase<TTask> where TTask : Task { private Exception _exception; private TTask _task; protected CatchInfoBase(TTask task, CancellationToken cancellationToken) { #if !WIN10 Contract.Assert(task != null); #endif _task = task; if (task.IsFaulted) { _exception = _task.Exception.GetBaseException(); // Observe the exception early, to prevent tasks tearing down the app domain } else if (task.IsCanceled) { _exception = new TaskCanceledException(task); } else { System.Diagnostics.Debug.Assert(cancellationToken.IsCancellationRequested); _exception = new OperationCanceledException(cancellationToken); } } protected TTask Task { get { return _task; } } // <summary> // The exception that was thrown to cause the Catch block to execute. // </summary> public Exception Exception { get { return _exception; } } // <summary> // Represents a result to be returned from a Catch handler. // </summary> internal struct CatchResult { // <summary> // Gets or sets the task to be returned to the caller. // </summary> internal TTask Task { get; set; } } } [SuppressMessage("Microsoft.StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleClass", Justification = "Packaged as one file to make it easy to link against")] internal class CatchInfo : CatchInfoBase<Task> { private static CatchResult _completed = new CatchResult { Task = TaskHelpers.Completed() }; public CatchInfo(Task task, CancellationToken cancellationToken) : base(task, cancellationToken) { } // <summary> // Returns a CatchResult that returns a completed (non-faulted) task. // </summary> [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This would result in poor usability.")] public CatchResult Handled() { return _completed; } // <summary> // Returns a CatchResult that executes the given task and returns it, in whatever state it finishes. // </summary> // <param name="task">The task to return.</param> [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This would result in poor usability.")] public CatchResult Task(Task task) { return new CatchResult { Task = task }; } // <summary> // Returns a CatchResult that re-throws the original exception. // </summary> public CatchResult Throw() { if (base.Task.IsFaulted || base.Task.IsCanceled) { return new CatchResult { Task = base.Task }; } else { // Canceled via CancelationToken return new CatchResult { Task = TaskHelpers.Canceled() }; } } // <summary> // Returns a CatchResult that throws the given exception. // </summary> // <param name="ex">The exception to throw.</param> [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This would result in poor usability.")] public CatchResult Throw(Exception ex) { return new CatchResult { Task = TaskHelpers.FromError<object>(ex) }; } } [SuppressMessage("Microsoft.StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleClass", Justification = "Packaged as one file to make it easy to link against")] internal class CatchInfo<T> : CatchInfoBase<Task<T>> { public CatchInfo(Task<T> task, CancellationToken cancellationToken) : base(task, cancellationToken) { } // <summary> // Returns a CatchResult that returns a completed (non-faulted) task. // </summary> // <param name="returnValue">The return value of the task.</param> [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This would result in poor usability.")] public CatchResult Handled(T returnValue) { return new CatchResult { Task = TaskHelpers.FromResult(returnValue) }; } // <summary> // Returns a CatchResult that executes the given task and returns it, in whatever state it finishes. // </summary> // <param name="task">The task to return.</param> [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This would result in poor usability.")] public CatchResult Task(Task<T> task) { return new CatchResult { Task = task }; } // <summary> // Returns a CatchResult that re-throws the original exception. // </summary> public CatchResult Throw() { if (base.Task.IsFaulted || base.Task.IsCanceled) { return new CatchResult { Task = base.Task }; } else { // Canceled via CancelationToken return new CatchResult { Task = TaskHelpers.Canceled<T>() }; } } // <summary> // Returns a CatchResult that throws the given exception. // </summary> // <param name="ex">The exception to throw.</param> [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This would result in poor usability.")] public CatchResult Throw(Exception ex) { return new CatchResult { Task = TaskHelpers.FromError<T>(ex) }; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Net.Http.Headers; using Xunit; namespace System.Net.Http.Unit.Tests { public class RangeConditionHeaderValueTest { [Fact] public void Ctor_EntityTagOverload_MatchExpectation() { RangeConditionHeaderValue rangeCondition = new RangeConditionHeaderValue(new EntityTagHeaderValue("\"x\"")); Assert.Equal(new EntityTagHeaderValue("\"x\""), rangeCondition.EntityTag); Assert.Null(rangeCondition.Date); EntityTagHeaderValue input = null; Assert.Throws<ArgumentNullException>(() => { new RangeConditionHeaderValue(input); }); } [Fact] public void Ctor_EntityTagStringOverload_MatchExpectation() { RangeConditionHeaderValue rangeCondition = new RangeConditionHeaderValue("\"y\""); Assert.Equal(new EntityTagHeaderValue("\"y\""), rangeCondition.EntityTag); Assert.Null(rangeCondition.Date); Assert.Throws<ArgumentException>(() => { new RangeConditionHeaderValue((string)null); }); } [Fact] public void Ctor_DateOverload_MatchExpectation() { RangeConditionHeaderValue rangeCondition = new RangeConditionHeaderValue( new DateTimeOffset(2010, 7, 15, 12, 33, 57, TimeSpan.Zero)); Assert.Null(rangeCondition.EntityTag); Assert.Equal(new DateTimeOffset(2010, 7, 15, 12, 33, 57, TimeSpan.Zero), rangeCondition.Date); } [Fact] public void ToString_UseDifferentrangeConditions_AllSerializedCorrectly() { RangeConditionHeaderValue rangeCondition = new RangeConditionHeaderValue(new EntityTagHeaderValue("\"x\"")); Assert.Equal("\"x\"", rangeCondition.ToString()); rangeCondition = new RangeConditionHeaderValue(new DateTimeOffset(2010, 7, 15, 12, 33, 57, TimeSpan.Zero)); Assert.Equal("Thu, 15 Jul 2010 12:33:57 GMT", rangeCondition.ToString()); } [Fact] public void GetHashCode_UseSameAndDifferentrangeConditions_SameOrDifferentHashCodes() { RangeConditionHeaderValue rangeCondition1 = new RangeConditionHeaderValue("\"x\""); RangeConditionHeaderValue rangeCondition2 = new RangeConditionHeaderValue(new EntityTagHeaderValue("\"x\"")); RangeConditionHeaderValue rangeCondition3 = new RangeConditionHeaderValue( new DateTimeOffset(2010, 7, 15, 12, 33, 57, TimeSpan.Zero)); RangeConditionHeaderValue rangeCondition4 = new RangeConditionHeaderValue( new DateTimeOffset(2008, 8, 16, 13, 44, 10, TimeSpan.Zero)); RangeConditionHeaderValue rangeCondition5 = new RangeConditionHeaderValue( new DateTimeOffset(2010, 7, 15, 12, 33, 57, TimeSpan.Zero)); RangeConditionHeaderValue rangeCondition6 = new RangeConditionHeaderValue( new EntityTagHeaderValue("\"x\"", true)); Assert.Equal(rangeCondition1.GetHashCode(), rangeCondition2.GetHashCode()); Assert.NotEqual(rangeCondition1.GetHashCode(), rangeCondition3.GetHashCode()); Assert.NotEqual(rangeCondition3.GetHashCode(), rangeCondition4.GetHashCode()); Assert.Equal(rangeCondition3.GetHashCode(), rangeCondition5.GetHashCode()); Assert.NotEqual(rangeCondition1.GetHashCode(), rangeCondition6.GetHashCode()); } [Fact] public void Equals_UseSameAndDifferentRanges_EqualOrNotEqualNoExceptions() { RangeConditionHeaderValue rangeCondition1 = new RangeConditionHeaderValue("\"x\""); RangeConditionHeaderValue rangeCondition2 = new RangeConditionHeaderValue(new EntityTagHeaderValue("\"x\"")); RangeConditionHeaderValue rangeCondition3 = new RangeConditionHeaderValue( new DateTimeOffset(2010, 7, 15, 12, 33, 57, TimeSpan.Zero)); RangeConditionHeaderValue rangeCondition4 = new RangeConditionHeaderValue( new DateTimeOffset(2008, 8, 16, 13, 44, 10, TimeSpan.Zero)); RangeConditionHeaderValue rangeCondition5 = new RangeConditionHeaderValue( new DateTimeOffset(2010, 7, 15, 12, 33, 57, TimeSpan.Zero)); RangeConditionHeaderValue rangeCondition6 = new RangeConditionHeaderValue( new EntityTagHeaderValue("\"x\"", true)); Assert.False(rangeCondition1.Equals(null), "\"x\" vs. <null>"); Assert.True(rangeCondition1.Equals(rangeCondition2), "\"x\" vs. \"x\""); Assert.False(rangeCondition1.Equals(rangeCondition3), "\"x\" vs. date"); Assert.False(rangeCondition3.Equals(rangeCondition1), "date vs. \"x\""); Assert.False(rangeCondition3.Equals(rangeCondition4), "date vs. different date"); Assert.True(rangeCondition3.Equals(rangeCondition5), "date vs. date"); Assert.False(rangeCondition1.Equals(rangeCondition6), "\"x\" vs. W/\"x\""); } [Fact] public void Clone_Call_CloneFieldsMatchSourceFields() { RangeConditionHeaderValue source = new RangeConditionHeaderValue(new EntityTagHeaderValue("\"x\"")); RangeConditionHeaderValue clone = (RangeConditionHeaderValue)((ICloneable)source).Clone(); Assert.Equal(source.EntityTag, clone.EntityTag); Assert.Null(clone.Date); source = new RangeConditionHeaderValue(new DateTimeOffset(2010, 7, 15, 12, 33, 57, TimeSpan.Zero)); clone = (RangeConditionHeaderValue)((ICloneable)source).Clone(); Assert.Null(clone.EntityTag); Assert.Equal(source.Date, clone.Date); } [Fact] public void GetRangeConditionLength_DifferentValidScenarios_AllReturnNonZero() { RangeConditionHeaderValue result = null; CallGetRangeConditionLength(" W/ \"tag\" ", 1, 9, out result); Assert.Equal(new EntityTagHeaderValue("\"tag\"", true), result.EntityTag); Assert.Null(result.Date); CallGetRangeConditionLength(" w/\"tag\"", 1, 7, out result); Assert.Equal(new EntityTagHeaderValue("\"tag\"", true), result.EntityTag); Assert.Null(result.Date); CallGetRangeConditionLength("\"tag\"", 0, 5, out result); Assert.Equal(new EntityTagHeaderValue("\"tag\""), result.EntityTag); Assert.Null(result.Date); CallGetRangeConditionLength("Wed, 09 Nov 1994 08:49:37 GMT", 0, 29, out result); Assert.Null(result.EntityTag); Assert.Equal(new DateTimeOffset(1994, 11, 9, 8, 49, 37, TimeSpan.Zero), result.Date); CallGetRangeConditionLength("Sun, 06 Nov 1994 08:49:37 GMT", 0, 29, out result); Assert.Null(result.EntityTag); Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), result.Date); } [Fact] public void GetRangeConditionLength_DifferentInvalidScenarios_AllReturnZero() { CheckInvalidGetRangeConditionLength(" \"x\"", 0); // no leading whitespaces allowed CheckInvalidGetRangeConditionLength(" Wed 09 Nov 1994 08:49:37 GMT", 0); CheckInvalidGetRangeConditionLength("\"x", 0); CheckInvalidGetRangeConditionLength("Wed, 09 Nov", 0); CheckInvalidGetRangeConditionLength("W/Wed 09 Nov 1994 08:49:37 GMT", 0); CheckInvalidGetRangeConditionLength("\"x\",", 0); CheckInvalidGetRangeConditionLength("Wed 09 Nov 1994 08:49:37 GMT,", 0); CheckInvalidGetRangeConditionLength("", 0); CheckInvalidGetRangeConditionLength(null, 0); } [Fact] public void Parse_SetOfValidValueStrings_ParsedCorrectly() { CheckValidParse(" \"x\" ", new RangeConditionHeaderValue("\"x\"")); CheckValidParse(" Sun, 06 Nov 1994 08:49:37 GMT ", new RangeConditionHeaderValue(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero))); } [Fact] public void Parse_SetOfInvalidValueStrings_Throws() { CheckInvalidParse("\"x\" ,"); // no delimiter allowed CheckInvalidParse("Sun, 06 Nov 1994 08:49:37 GMT ,"); // no delimiter allowed CheckInvalidParse("\"x\" Sun, 06 Nov 1994 08:49:37 GMT"); CheckInvalidParse("Sun, 06 Nov 1994 08:49:37 GMT \"x\""); CheckInvalidParse(null); CheckInvalidParse(string.Empty); } [Fact] public void TryParse_SetOfValidValueStrings_ParsedCorrectly() { CheckValidTryParse(" \"x\" ", new RangeConditionHeaderValue("\"x\"")); CheckValidTryParse(" Sun, 06 Nov 1994 08:49:37 GMT ", new RangeConditionHeaderValue(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero))); } [Fact] public void TryParse_SetOfInvalidValueStrings_ReturnsFalse() { CheckInvalidTryParse("\"x\" ,"); // no delimiter allowed CheckInvalidTryParse("Sun, 06 Nov 1994 08:49:37 GMT ,"); // no delimiter allowed CheckInvalidTryParse("\"x\" Sun, 06 Nov 1994 08:49:37 GMT"); CheckInvalidTryParse("Sun, 06 Nov 1994 08:49:37 GMT \"x\""); CheckInvalidTryParse(null); CheckInvalidTryParse(string.Empty); } #region Helper methods private void CheckValidParse(string input, RangeConditionHeaderValue expectedResult) { RangeConditionHeaderValue result = RangeConditionHeaderValue.Parse(input); Assert.Equal(expectedResult, result); } private void CheckInvalidParse(string input) { Assert.Throws<FormatException>(() => { RangeConditionHeaderValue.Parse(input); }); } private void CheckValidTryParse(string input, RangeConditionHeaderValue expectedResult) { RangeConditionHeaderValue result = null; Assert.True(RangeConditionHeaderValue.TryParse(input, out result)); Assert.Equal(expectedResult, result); } private void CheckInvalidTryParse(string input) { RangeConditionHeaderValue result = null; Assert.False(RangeConditionHeaderValue.TryParse(input, out result)); Assert.Null(result); } private static void CallGetRangeConditionLength(string input, int startIndex, int expectedLength, out RangeConditionHeaderValue result) { object temp = null; Assert.Equal(expectedLength, RangeConditionHeaderValue.GetRangeConditionLength(input, startIndex, out temp)); result = temp as RangeConditionHeaderValue; } private static void CheckInvalidGetRangeConditionLength(string input, int startIndex) { object result = null; Assert.Equal(0, RangeConditionHeaderValue.GetRangeConditionLength(input, startIndex, out result)); Assert.Null(result); } #endregion } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagve = Google.Ads.GoogleAds.V9.Enums; using gagvr = Google.Ads.GoogleAds.V9.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V9.Services; namespace Google.Ads.GoogleAds.Tests.V9.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedCustomerManagerLinkServiceClientTest { [Category("Autogenerated")][Test] public void GetCustomerManagerLinkRequestObject() { moq::Mock<CustomerManagerLinkService.CustomerManagerLinkServiceClient> mockGrpcClient = new moq::Mock<CustomerManagerLinkService.CustomerManagerLinkServiceClient>(moq::MockBehavior.Strict); GetCustomerManagerLinkRequest request = new GetCustomerManagerLinkRequest { ResourceNameAsCustomerManagerLinkName = gagvr::CustomerManagerLinkName.FromCustomerManagerCustomerManagerLink("[CUSTOMER_ID]", "[MANAGER_CUSTOMER_ID]", "[MANAGER_LINK_ID]"), }; gagvr::CustomerManagerLink expectedResponse = new gagvr::CustomerManagerLink { ResourceNameAsCustomerManagerLinkName = gagvr::CustomerManagerLinkName.FromCustomerManagerCustomerManagerLink("[CUSTOMER_ID]", "[MANAGER_CUSTOMER_ID]", "[MANAGER_LINK_ID]"), Status = gagve::ManagerLinkStatusEnum.Types.ManagerLinkStatus.Inactive, ManagerCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"), ManagerLinkId = 1955158851327798968L, }; mockGrpcClient.Setup(x => x.GetCustomerManagerLink(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerManagerLinkServiceClient client = new CustomerManagerLinkServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerManagerLink response = client.GetCustomerManagerLink(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCustomerManagerLinkRequestObjectAsync() { moq::Mock<CustomerManagerLinkService.CustomerManagerLinkServiceClient> mockGrpcClient = new moq::Mock<CustomerManagerLinkService.CustomerManagerLinkServiceClient>(moq::MockBehavior.Strict); GetCustomerManagerLinkRequest request = new GetCustomerManagerLinkRequest { ResourceNameAsCustomerManagerLinkName = gagvr::CustomerManagerLinkName.FromCustomerManagerCustomerManagerLink("[CUSTOMER_ID]", "[MANAGER_CUSTOMER_ID]", "[MANAGER_LINK_ID]"), }; gagvr::CustomerManagerLink expectedResponse = new gagvr::CustomerManagerLink { ResourceNameAsCustomerManagerLinkName = gagvr::CustomerManagerLinkName.FromCustomerManagerCustomerManagerLink("[CUSTOMER_ID]", "[MANAGER_CUSTOMER_ID]", "[MANAGER_LINK_ID]"), Status = gagve::ManagerLinkStatusEnum.Types.ManagerLinkStatus.Inactive, ManagerCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"), ManagerLinkId = 1955158851327798968L, }; mockGrpcClient.Setup(x => x.GetCustomerManagerLinkAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerManagerLink>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerManagerLinkServiceClient client = new CustomerManagerLinkServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerManagerLink responseCallSettings = await client.GetCustomerManagerLinkAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CustomerManagerLink responseCancellationToken = await client.GetCustomerManagerLinkAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetCustomerManagerLink() { moq::Mock<CustomerManagerLinkService.CustomerManagerLinkServiceClient> mockGrpcClient = new moq::Mock<CustomerManagerLinkService.CustomerManagerLinkServiceClient>(moq::MockBehavior.Strict); GetCustomerManagerLinkRequest request = new GetCustomerManagerLinkRequest { ResourceNameAsCustomerManagerLinkName = gagvr::CustomerManagerLinkName.FromCustomerManagerCustomerManagerLink("[CUSTOMER_ID]", "[MANAGER_CUSTOMER_ID]", "[MANAGER_LINK_ID]"), }; gagvr::CustomerManagerLink expectedResponse = new gagvr::CustomerManagerLink { ResourceNameAsCustomerManagerLinkName = gagvr::CustomerManagerLinkName.FromCustomerManagerCustomerManagerLink("[CUSTOMER_ID]", "[MANAGER_CUSTOMER_ID]", "[MANAGER_LINK_ID]"), Status = gagve::ManagerLinkStatusEnum.Types.ManagerLinkStatus.Inactive, ManagerCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"), ManagerLinkId = 1955158851327798968L, }; mockGrpcClient.Setup(x => x.GetCustomerManagerLink(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerManagerLinkServiceClient client = new CustomerManagerLinkServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerManagerLink response = client.GetCustomerManagerLink(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCustomerManagerLinkAsync() { moq::Mock<CustomerManagerLinkService.CustomerManagerLinkServiceClient> mockGrpcClient = new moq::Mock<CustomerManagerLinkService.CustomerManagerLinkServiceClient>(moq::MockBehavior.Strict); GetCustomerManagerLinkRequest request = new GetCustomerManagerLinkRequest { ResourceNameAsCustomerManagerLinkName = gagvr::CustomerManagerLinkName.FromCustomerManagerCustomerManagerLink("[CUSTOMER_ID]", "[MANAGER_CUSTOMER_ID]", "[MANAGER_LINK_ID]"), }; gagvr::CustomerManagerLink expectedResponse = new gagvr::CustomerManagerLink { ResourceNameAsCustomerManagerLinkName = gagvr::CustomerManagerLinkName.FromCustomerManagerCustomerManagerLink("[CUSTOMER_ID]", "[MANAGER_CUSTOMER_ID]", "[MANAGER_LINK_ID]"), Status = gagve::ManagerLinkStatusEnum.Types.ManagerLinkStatus.Inactive, ManagerCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"), ManagerLinkId = 1955158851327798968L, }; mockGrpcClient.Setup(x => x.GetCustomerManagerLinkAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerManagerLink>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerManagerLinkServiceClient client = new CustomerManagerLinkServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerManagerLink responseCallSettings = await client.GetCustomerManagerLinkAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CustomerManagerLink responseCancellationToken = await client.GetCustomerManagerLinkAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetCustomerManagerLinkResourceNames() { moq::Mock<CustomerManagerLinkService.CustomerManagerLinkServiceClient> mockGrpcClient = new moq::Mock<CustomerManagerLinkService.CustomerManagerLinkServiceClient>(moq::MockBehavior.Strict); GetCustomerManagerLinkRequest request = new GetCustomerManagerLinkRequest { ResourceNameAsCustomerManagerLinkName = gagvr::CustomerManagerLinkName.FromCustomerManagerCustomerManagerLink("[CUSTOMER_ID]", "[MANAGER_CUSTOMER_ID]", "[MANAGER_LINK_ID]"), }; gagvr::CustomerManagerLink expectedResponse = new gagvr::CustomerManagerLink { ResourceNameAsCustomerManagerLinkName = gagvr::CustomerManagerLinkName.FromCustomerManagerCustomerManagerLink("[CUSTOMER_ID]", "[MANAGER_CUSTOMER_ID]", "[MANAGER_LINK_ID]"), Status = gagve::ManagerLinkStatusEnum.Types.ManagerLinkStatus.Inactive, ManagerCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"), ManagerLinkId = 1955158851327798968L, }; mockGrpcClient.Setup(x => x.GetCustomerManagerLink(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerManagerLinkServiceClient client = new CustomerManagerLinkServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerManagerLink response = client.GetCustomerManagerLink(request.ResourceNameAsCustomerManagerLinkName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCustomerManagerLinkResourceNamesAsync() { moq::Mock<CustomerManagerLinkService.CustomerManagerLinkServiceClient> mockGrpcClient = new moq::Mock<CustomerManagerLinkService.CustomerManagerLinkServiceClient>(moq::MockBehavior.Strict); GetCustomerManagerLinkRequest request = new GetCustomerManagerLinkRequest { ResourceNameAsCustomerManagerLinkName = gagvr::CustomerManagerLinkName.FromCustomerManagerCustomerManagerLink("[CUSTOMER_ID]", "[MANAGER_CUSTOMER_ID]", "[MANAGER_LINK_ID]"), }; gagvr::CustomerManagerLink expectedResponse = new gagvr::CustomerManagerLink { ResourceNameAsCustomerManagerLinkName = gagvr::CustomerManagerLinkName.FromCustomerManagerCustomerManagerLink("[CUSTOMER_ID]", "[MANAGER_CUSTOMER_ID]", "[MANAGER_LINK_ID]"), Status = gagve::ManagerLinkStatusEnum.Types.ManagerLinkStatus.Inactive, ManagerCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"), ManagerLinkId = 1955158851327798968L, }; mockGrpcClient.Setup(x => x.GetCustomerManagerLinkAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerManagerLink>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerManagerLinkServiceClient client = new CustomerManagerLinkServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerManagerLink responseCallSettings = await client.GetCustomerManagerLinkAsync(request.ResourceNameAsCustomerManagerLinkName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CustomerManagerLink responseCancellationToken = await client.GetCustomerManagerLinkAsync(request.ResourceNameAsCustomerManagerLinkName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateCustomerManagerLinkRequestObject() { moq::Mock<CustomerManagerLinkService.CustomerManagerLinkServiceClient> mockGrpcClient = new moq::Mock<CustomerManagerLinkService.CustomerManagerLinkServiceClient>(moq::MockBehavior.Strict); MutateCustomerManagerLinkRequest request = new MutateCustomerManagerLinkRequest { CustomerId = "customer_id3b3724cb", Operations = { new CustomerManagerLinkOperation(), }, ValidateOnly = true, }; MutateCustomerManagerLinkResponse expectedResponse = new MutateCustomerManagerLinkResponse { Results = { new MutateCustomerManagerLinkResult(), }, }; mockGrpcClient.Setup(x => x.MutateCustomerManagerLink(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerManagerLinkServiceClient client = new CustomerManagerLinkServiceClientImpl(mockGrpcClient.Object, null); MutateCustomerManagerLinkResponse response = client.MutateCustomerManagerLink(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateCustomerManagerLinkRequestObjectAsync() { moq::Mock<CustomerManagerLinkService.CustomerManagerLinkServiceClient> mockGrpcClient = new moq::Mock<CustomerManagerLinkService.CustomerManagerLinkServiceClient>(moq::MockBehavior.Strict); MutateCustomerManagerLinkRequest request = new MutateCustomerManagerLinkRequest { CustomerId = "customer_id3b3724cb", Operations = { new CustomerManagerLinkOperation(), }, ValidateOnly = true, }; MutateCustomerManagerLinkResponse expectedResponse = new MutateCustomerManagerLinkResponse { Results = { new MutateCustomerManagerLinkResult(), }, }; mockGrpcClient.Setup(x => x.MutateCustomerManagerLinkAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCustomerManagerLinkResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerManagerLinkServiceClient client = new CustomerManagerLinkServiceClientImpl(mockGrpcClient.Object, null); MutateCustomerManagerLinkResponse responseCallSettings = await client.MutateCustomerManagerLinkAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateCustomerManagerLinkResponse responseCancellationToken = await client.MutateCustomerManagerLinkAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateCustomerManagerLink() { moq::Mock<CustomerManagerLinkService.CustomerManagerLinkServiceClient> mockGrpcClient = new moq::Mock<CustomerManagerLinkService.CustomerManagerLinkServiceClient>(moq::MockBehavior.Strict); MutateCustomerManagerLinkRequest request = new MutateCustomerManagerLinkRequest { CustomerId = "customer_id3b3724cb", Operations = { new CustomerManagerLinkOperation(), }, }; MutateCustomerManagerLinkResponse expectedResponse = new MutateCustomerManagerLinkResponse { Results = { new MutateCustomerManagerLinkResult(), }, }; mockGrpcClient.Setup(x => x.MutateCustomerManagerLink(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerManagerLinkServiceClient client = new CustomerManagerLinkServiceClientImpl(mockGrpcClient.Object, null); MutateCustomerManagerLinkResponse response = client.MutateCustomerManagerLink(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateCustomerManagerLinkAsync() { moq::Mock<CustomerManagerLinkService.CustomerManagerLinkServiceClient> mockGrpcClient = new moq::Mock<CustomerManagerLinkService.CustomerManagerLinkServiceClient>(moq::MockBehavior.Strict); MutateCustomerManagerLinkRequest request = new MutateCustomerManagerLinkRequest { CustomerId = "customer_id3b3724cb", Operations = { new CustomerManagerLinkOperation(), }, }; MutateCustomerManagerLinkResponse expectedResponse = new MutateCustomerManagerLinkResponse { Results = { new MutateCustomerManagerLinkResult(), }, }; mockGrpcClient.Setup(x => x.MutateCustomerManagerLinkAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCustomerManagerLinkResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerManagerLinkServiceClient client = new CustomerManagerLinkServiceClientImpl(mockGrpcClient.Object, null); MutateCustomerManagerLinkResponse responseCallSettings = await client.MutateCustomerManagerLinkAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateCustomerManagerLinkResponse responseCancellationToken = await client.MutateCustomerManagerLinkAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MoveManagerLinkRequestObject() { moq::Mock<CustomerManagerLinkService.CustomerManagerLinkServiceClient> mockGrpcClient = new moq::Mock<CustomerManagerLinkService.CustomerManagerLinkServiceClient>(moq::MockBehavior.Strict); MoveManagerLinkRequest request = new MoveManagerLinkRequest { CustomerId = "customer_id3b3724cb", PreviousCustomerManagerLink = "previous_customer_manager_linkb33a0aa8", NewManager = "new_managerbf35b8c4", ValidateOnly = true, }; MoveManagerLinkResponse expectedResponse = new MoveManagerLinkResponse { ResourceName = "resource_name8cc2e687", }; mockGrpcClient.Setup(x => x.MoveManagerLink(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerManagerLinkServiceClient client = new CustomerManagerLinkServiceClientImpl(mockGrpcClient.Object, null); MoveManagerLinkResponse response = client.MoveManagerLink(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MoveManagerLinkRequestObjectAsync() { moq::Mock<CustomerManagerLinkService.CustomerManagerLinkServiceClient> mockGrpcClient = new moq::Mock<CustomerManagerLinkService.CustomerManagerLinkServiceClient>(moq::MockBehavior.Strict); MoveManagerLinkRequest request = new MoveManagerLinkRequest { CustomerId = "customer_id3b3724cb", PreviousCustomerManagerLink = "previous_customer_manager_linkb33a0aa8", NewManager = "new_managerbf35b8c4", ValidateOnly = true, }; MoveManagerLinkResponse expectedResponse = new MoveManagerLinkResponse { ResourceName = "resource_name8cc2e687", }; mockGrpcClient.Setup(x => x.MoveManagerLinkAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MoveManagerLinkResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerManagerLinkServiceClient client = new CustomerManagerLinkServiceClientImpl(mockGrpcClient.Object, null); MoveManagerLinkResponse responseCallSettings = await client.MoveManagerLinkAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MoveManagerLinkResponse responseCancellationToken = await client.MoveManagerLinkAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MoveManagerLink() { moq::Mock<CustomerManagerLinkService.CustomerManagerLinkServiceClient> mockGrpcClient = new moq::Mock<CustomerManagerLinkService.CustomerManagerLinkServiceClient>(moq::MockBehavior.Strict); MoveManagerLinkRequest request = new MoveManagerLinkRequest { CustomerId = "customer_id3b3724cb", PreviousCustomerManagerLink = "previous_customer_manager_linkb33a0aa8", NewManager = "new_managerbf35b8c4", }; MoveManagerLinkResponse expectedResponse = new MoveManagerLinkResponse { ResourceName = "resource_name8cc2e687", }; mockGrpcClient.Setup(x => x.MoveManagerLink(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerManagerLinkServiceClient client = new CustomerManagerLinkServiceClientImpl(mockGrpcClient.Object, null); MoveManagerLinkResponse response = client.MoveManagerLink(request.CustomerId, request.PreviousCustomerManagerLink, request.NewManager); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MoveManagerLinkAsync() { moq::Mock<CustomerManagerLinkService.CustomerManagerLinkServiceClient> mockGrpcClient = new moq::Mock<CustomerManagerLinkService.CustomerManagerLinkServiceClient>(moq::MockBehavior.Strict); MoveManagerLinkRequest request = new MoveManagerLinkRequest { CustomerId = "customer_id3b3724cb", PreviousCustomerManagerLink = "previous_customer_manager_linkb33a0aa8", NewManager = "new_managerbf35b8c4", }; MoveManagerLinkResponse expectedResponse = new MoveManagerLinkResponse { ResourceName = "resource_name8cc2e687", }; mockGrpcClient.Setup(x => x.MoveManagerLinkAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MoveManagerLinkResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerManagerLinkServiceClient client = new CustomerManagerLinkServiceClientImpl(mockGrpcClient.Object, null); MoveManagerLinkResponse responseCallSettings = await client.MoveManagerLinkAsync(request.CustomerId, request.PreviousCustomerManagerLink, request.NewManager, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MoveManagerLinkResponse responseCancellationToken = await client.MoveManagerLinkAsync(request.CustomerId, request.PreviousCustomerManagerLink, request.NewManager, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// IExpressionEvaluator.cs // // Author: // Lluis Sanchez Gual <lluis@novell.com> // // Copyright (c) 2008 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // using System; using System.Text; using System.Globalization; using System.Runtime.Serialization; using Mono.Debugging.Backend; using Mono.Debugging.Client; using System.Collections.Generic; namespace Mono.Debugging.Evaluation { public abstract class ExpressionEvaluator { public ValueReference Evaluate (EvaluationContext ctx, string exp) { return Evaluate (ctx, exp, null); } public virtual ValueReference Evaluate (EvaluationContext ctx, string exp, object expectedType) { foreach (ValueReference var in ctx.Adapter.GetLocalVariables (ctx)) if (var.Name == exp) return var; foreach (ValueReference var in ctx.Adapter.GetParameters (ctx)) if (var.Name == exp) return var; ValueReference thisVar = ctx.Adapter.GetThisReference (ctx); if (thisVar != null) { if (thisVar.Name == exp) return thisVar; foreach (ValueReference cv in thisVar.GetChildReferences (ctx.Options)) if (cv.Name == exp) return cv; } throw new EvaluatorException ("Invalid Expression: '{0}'", exp); } public virtual ValidationResult ValidateExpression (EvaluationContext ctx, string expression) { return new ValidationResult (true, null); } public string TargetObjectToString (EvaluationContext ctx, object obj) { object res = ctx.Adapter.TargetObjectToObject (ctx, obj); if (res == null) return null; if (res is EvaluationResult) return ((EvaluationResult)res).DisplayValue ?? ((EvaluationResult)res).Value; else return res.ToString (); } public EvaluationResult TargetObjectToExpression (EvaluationContext ctx, object obj) { return ToExpression (ctx, ctx.Adapter.TargetObjectToObject (ctx, obj)); } public virtual EvaluationResult ToExpression (EvaluationContext ctx, object obj) { if (obj == null) return new EvaluationResult ("null"); else if (obj is IntPtr) { IntPtr p = (IntPtr) obj; return new EvaluationResult ("0x" + p.ToInt64 ().ToString ("x")); } else if (obj is char) { char c = (char) obj; string str; if (c == '\'') str = @"'\''"; else if (c == '"') str = "'\"'"; else str = EscapeString ("'" + c + "'"); return new EvaluationResult (str, ((int) c) + " " + str); } else if (obj is string) return new EvaluationResult ("\"" + EscapeString ((string)obj) + "\""); else if (obj is bool) return new EvaluationResult (((bool)obj) ? "true" : "false"); else if (obj is decimal) return new EvaluationResult (((decimal)obj).ToString (System.Globalization.CultureInfo.InvariantCulture)); else if (obj is EvaluationResult) return (EvaluationResult) obj; if (ctx.Options.IntegerDisplayFormat == IntegerDisplayFormat.Hexadecimal) { string fval = null; if (obj is sbyte) fval = ((sbyte)obj).ToString ("x2"); else if (obj is int) fval = ((int)obj).ToString ("x4"); else if (obj is short) fval = ((short)obj).ToString ("x8"); else if (obj is long) fval = ((long)obj).ToString ("x16"); else if (obj is byte) fval = ((byte)obj).ToString ("x2"); else if (obj is uint) fval = ((uint)obj).ToString ("x4"); else if (obj is ushort) fval = ((ushort)obj).ToString ("x8"); else if (obj is ulong) fval = ((ulong)obj).ToString ("x16"); if (fval != null) return new EvaluationResult ("0x" + fval); } return new EvaluationResult (obj.ToString ()); } public static string EscapeString (string text) { StringBuilder sb = new StringBuilder (); for (int i = 0; i < text.Length; i++) { char c = text[i]; string txt; switch (c) { case '"': txt = "\\\""; break; case '\0': txt = @"\0"; break; case '\\': txt = @"\\"; break; case '\a': txt = @"\a"; break; case '\b': txt = @"\b"; break; case '\f': txt = @"\f"; break; case '\v': txt = @"\v"; break; case '\n': txt = @"\n"; break; case '\r': txt = @"\r"; break; case '\t': txt = @"\t"; break; default: if (char.GetUnicodeCategory (c) == UnicodeCategory.OtherNotAssigned) { sb.AppendFormat ("\\u{0:x4}", (int) c); } else { sb.Append (c); } continue; } sb.Append (txt); } return sb.ToString (); } public virtual bool CaseSensitive { get { return true; } } public abstract string Resolve (DebuggerSession session, SourceLocation location, string exp); public virtual IEnumerable<ValueReference> GetLocalVariables (EvaluationContext ctx) { return ctx.Adapter.GetLocalVariables (ctx); } public virtual ValueReference GetThisReference (EvaluationContext ctx) { return ctx.Adapter.GetThisReference (ctx); } public virtual IEnumerable<ValueReference> GetParameters (EvaluationContext ctx) { return ctx.Adapter.GetParameters (ctx); } public virtual ValueReference GetCurrentException (EvaluationContext ctx) { return ctx.Adapter.GetCurrentException (ctx); } } [Serializable] public class EvaluatorException: Exception { protected EvaluatorException (SerializationInfo info, StreamingContext context) : base (info, context) { } public EvaluatorException (string msg, params object[] args): base (string.Format (msg, args)) { } } [Serializable] public class EvaluatorAbortedException: EvaluatorException { protected EvaluatorAbortedException (SerializationInfo info, StreamingContext context) : base (info, context) { } public EvaluatorAbortedException () : base ("Aborted.") { } } [Serializable] public class NotSupportedExpressionException: EvaluatorException { protected NotSupportedExpressionException (SerializationInfo info, StreamingContext context) : base (info, context) { } public NotSupportedExpressionException () : base ("Expression not supported.") { } } [Serializable] public class ImplicitEvaluationDisabledException: EvaluatorException { protected ImplicitEvaluationDisabledException (SerializationInfo info, StreamingContext context) : base (info, context) { } public ImplicitEvaluationDisabledException () : base ("Implicit property and method evaluation is disabled.") { } } }
// **************************************************************** // This is free software licensed under the NUnit license. You // may obtain a copy of the license as well as information regarding // copyright ownership at http://nunit.org. // **************************************************************** using System; using System.IO; using System.Collections; using NUnit.Framework; namespace NUnit.Util.Tests { /// <summary> /// Summary description for ProjectConfigTests. /// </summary> [TestFixture] public class ProjectConfigTests { private ProjectConfig activeConfig; private ProjectConfig inactiveConfig; private NUnitProject project; [SetUp] public void SetUp() { activeConfig = new ProjectConfig( "Debug" ); inactiveConfig = new ProjectConfig("Release"); project = new NUnitProject( TestPath( "/test/myproject.nunit" ) ); project.Configs.Add( activeConfig ); project.Configs.Add(inactiveConfig); project.IsDirty = false; project.HasChangesRequiringReload = false; } /// <summary> /// Take a valid Linux path and make a valid windows path out of it /// if we are on Windows. Change slashes to backslashes and, if the /// path starts with a slash, add C: in front of it. /// </summary> private string TestPath(string path) { if (Path.DirectorySeparatorChar != '/') { path = path.Replace('/', Path.DirectorySeparatorChar); if (path[0] == Path.DirectorySeparatorChar) path = "C:" + path; } return path; } [Test] public void EmptyConfig() { Assert.AreEqual( "Debug", activeConfig.Name ); Assert.AreEqual( 0, activeConfig.Assemblies.Count ); } [Test] public void CanAddAssemblies() { string path1 = TestPath("/test/assembly1.dll"); string path2 = TestPath("/test/assembly2.dll"); activeConfig.Assemblies.Add(path1); activeConfig.Assemblies.Add( path2 ); Assert.AreEqual( 2, activeConfig.Assemblies.Count ); Assert.AreEqual( path1, activeConfig.Assemblies[0] ); Assert.AreEqual( path2, activeConfig.Assemblies[1] ); } [Test] public void ToArray() { string path1 = TestPath("/test/assembly1.dll"); string path2 = TestPath("/test/assembly2.dll"); activeConfig.Assemblies.Add( path1 ); activeConfig.Assemblies.Add( path2 ); string[] files = activeConfig.Assemblies.ToArray(); Assert.AreEqual( path1, files[0] ); Assert.AreEqual( path2, files[1] ); } [Test] public void AddToActiveConfigMarksProjectDirty() { activeConfig.Assemblies.Add(TestPath("/test/bin/debug/assembly1.dll")); Assert.IsTrue(project.IsDirty); } [Test] public void AddToActiveConfigRequiresReload() { activeConfig.Assemblies.Add(TestPath("/test/bin/debug/assembly1.dll")); Assert.IsTrue(project.HasChangesRequiringReload); } [Test] public void AddToInactiveConfigMarksProjectDirty() { inactiveConfig.Assemblies.Add(TestPath("/test/bin/release/assembly1.dll")); Assert.IsTrue(project.IsDirty); } [Test] public void AddToInactiveConfigDoesNotRequireReload() { inactiveConfig.Assemblies.Add(TestPath("/test/bin/release/assembly1.dll")); Assert.IsFalse(project.HasChangesRequiringReload); } [Test] public void AddingConfigMarksProjectDirty() { project.Configs.Add("New"); Assert.IsTrue(project.IsDirty); } [Test] public void AddingInitialConfigRequiresReload() { NUnitProject newProj = new NUnitProject("/junk"); newProj.HasChangesRequiringReload = false; newProj.Configs.Add("New"); Assert.That(newProj.HasChangesRequiringReload); } [Test] public void AddingSubsequentConfigDoesNotRequireReload() { project.Configs.Add("New"); Assert.IsFalse(project.HasChangesRequiringReload); } [Test] public void RenameActiveConfigMarksProjectDirty() { activeConfig.Name = "Renamed"; Assert.IsTrue(project.IsDirty); } [Test] public void RenameActiveConfigRequiresReload() { activeConfig.Name = "Renamed"; Assert.IsTrue(project.HasChangesRequiringReload); } [Test] public void RenameInctiveConfigMarksProjectDirty() { inactiveConfig.Name = "Renamed"; Assert.IsTrue(project.IsDirty); } [Test] public void RenameInactiveConfigDoesNotRequireReload() { inactiveConfig.Name = "Renamed"; Assert.IsFalse(project.HasChangesRequiringReload); } [Test] public void RemoveActiveConfigMarksProjectDirty() { string path1 = TestPath("/test/bin/debug/assembly1.dll"); activeConfig.Assemblies.Add(path1); project.IsDirty = false; activeConfig.Assemblies.Remove(path1); Assert.IsTrue(project.IsDirty); } [Test] public void RemoveActiveConfigRequiresReload() { string path1 = TestPath("/test/bin/debug/assembly1.dll"); activeConfig.Assemblies.Add(path1); project.IsDirty = false; activeConfig.Assemblies.Remove(path1); Assert.IsTrue(project.HasChangesRequiringReload); } [Test] public void RemoveInactiveConfigMarksProjectDirty() { string path1 = TestPath("/test/bin/debug/assembly1.dll"); inactiveConfig.Assemblies.Add(path1); project.IsDirty = false; inactiveConfig.Assemblies.Remove(path1); Assert.IsTrue(project.IsDirty); } [Test] public void RemoveInactiveConfigDoesNotRequireReload() { string path1 = TestPath("/test/bin/debug/assembly1.dll"); inactiveConfig.Assemblies.Add(path1); project.HasChangesRequiringReload = false; inactiveConfig.Assemblies.Remove(path1); Assert.IsFalse(project.HasChangesRequiringReload); } [Test] public void SettingActiveConfigApplicationBaseMarksProjectDirty() { activeConfig.BasePath = TestPath("/junk"); Assert.IsTrue(project.IsDirty); } [Test] public void SettingActiveConfigApplicationBaseRequiresReload() { activeConfig.BasePath = TestPath("/junk"); Assert.IsTrue(project.HasChangesRequiringReload); } [Test] public void SettingInactiveConfigApplicationBaseMarksProjectDirty() { inactiveConfig.BasePath = TestPath("/junk"); Assert.IsTrue(project.IsDirty); } [Test] public void SettingInactiveConfigApplicationBaseDoesNotRequireReload() { inactiveConfig.BasePath = TestPath("/junk"); Assert.IsFalse(project.HasChangesRequiringReload); } [Test] public void AbsoluteBasePath() { activeConfig.BasePath = TestPath("/junk"); string path1 = TestPath( "/junk/bin/debug/assembly1.dll" ); activeConfig.Assemblies.Add( path1 ); Assert.AreEqual( path1, activeConfig.Assemblies[0] ); } [Test] public void RelativeBasePath() { activeConfig.BasePath = @"junk"; string path1 = TestPath("/test/junk/bin/debug/assembly1.dll"); activeConfig.Assemblies.Add( path1 ); Assert.AreEqual( path1, activeConfig.Assemblies[0] ); } [Test] public void NoBasePathSet() { string path1 = TestPath( "/test/bin/debug/assembly1.dll" ); activeConfig.Assemblies.Add( path1 ); Assert.AreEqual( path1, activeConfig.Assemblies[0] ); } [Test] public void SettingActiveConfigConfigurationFileMarksProjectDirty() { activeConfig.ConfigurationFile = "MyProject.config"; Assert.IsTrue(project.IsDirty); } [Test] public void SettingActiveConfigConfigurationFileRequiresReload() { activeConfig.ConfigurationFile = "MyProject.config"; Assert.IsTrue(project.HasChangesRequiringReload); } [Test] public void SettingInactiveConfigConfigurationFileMarksProjectDirty() { inactiveConfig.ConfigurationFile = "MyProject.config"; Assert.IsTrue(project.IsDirty); } [Test] public void SettingInactiveConfigConfigurationFileDoesNotRequireReload() { inactiveConfig.ConfigurationFile = "MyProject.config"; Assert.IsFalse(project.HasChangesRequiringReload); } [Test] public void DefaultConfigurationFile() { Assert.AreEqual( "myproject.config", activeConfig.ConfigurationFile ); Assert.AreEqual( TestPath( "/test/myproject.config" ), activeConfig.ConfigurationFilePath ); } [Test] public void AbsoluteConfigurationFile() { string path1 = TestPath("/configs/myconfig.config"); activeConfig.ConfigurationFile = path1; Assert.AreEqual( path1, activeConfig.ConfigurationFilePath ); } [Test] public void RelativeConfigurationFile() { activeConfig.ConfigurationFile = "myconfig.config"; Assert.AreEqual( TestPath( "/test/myconfig.config" ), activeConfig.ConfigurationFilePath ); } [Test] public void SettingActiveConfigPrivateBinPathMarksProjectDirty() { activeConfig.PrivateBinPath = TestPath("/junk") + Path.PathSeparator + TestPath("/bin"); Assert.IsTrue(project.IsDirty); } [Test] public void SettingActiveConfigPrivateBinPathRequiresReload() { activeConfig.PrivateBinPath = TestPath("/junk") + Path.PathSeparator + TestPath("/bin"); Assert.IsTrue(project.HasChangesRequiringReload); } [Test] public void SettingInactiveConfigPrivateBinPathMarksProjectDirty() { inactiveConfig.PrivateBinPath = TestPath("/junk") + Path.PathSeparator + TestPath("/bin"); Assert.IsTrue(project.IsDirty); } [Test] public void SettingInactiveConfigPrivateBinPathDoesNotRequireReload() { inactiveConfig.PrivateBinPath = TestPath("/junk") + Path.PathSeparator + TestPath("/bin"); Assert.IsFalse(project.HasChangesRequiringReload); } [Test] public void SettingActiveConfigBinPathTypeMarksProjectDirty() { activeConfig.BinPathType = BinPathType.Manual; Assert.IsTrue(project.IsDirty); } [Test] public void SettingActiveConfigBinPathTypeRequiresReload() { activeConfig.BinPathType = BinPathType.Manual; Assert.IsTrue(project.HasChangesRequiringReload); } [Test] public void SettingInactiveConfigBinPathTypeMarksProjectDirty() { inactiveConfig.BinPathType = BinPathType.Manual; Assert.IsTrue(project.IsDirty); } [Test] public void SettingInactiveConfigBinPathTypeDoesNotRequireReload() { inactiveConfig.BinPathType = BinPathType.Manual; Assert.IsFalse(project.HasChangesRequiringReload); } [Test] public void NoPrivateBinPath() { activeConfig.Assemblies.Add( TestPath( "/bin/assembly1.dll" ) ); activeConfig.Assemblies.Add( TestPath( "/bin/assembly2.dll" ) ); activeConfig.BinPathType = BinPathType.None; Assert.IsNull( activeConfig.PrivateBinPath ); } [Test] public void ManualPrivateBinPath() { activeConfig.Assemblies.Add( TestPath( "/test/bin/assembly1.dll" ) ); activeConfig.Assemblies.Add( TestPath( "/test/bin/assembly2.dll" ) ); activeConfig.BinPathType = BinPathType.Manual; activeConfig.PrivateBinPath = TestPath( "/test" ); Assert.AreEqual( TestPath( "/test" ), activeConfig.PrivateBinPath ); } // TODO: Move to DomainManagerTests // [Test] // public void AutoPrivateBinPath() // { // config.Assemblies.Add( TestPath( "/test/bin/assembly1.dll" ) ); // config.Assemblies.Add( TestPath( "/test/bin/assembly2.dll" ) ); // config.BinPathType = BinPathType.Auto; // Assert.AreEqual( "bin", config.PrivateBinPath ); // } } }
// 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: This class represents settings specified by de jure or // de facto standards for a particular country/region. In // contrast to CultureInfo, the RegionInfo does not represent // preferences of the user and does not depend on the user's // language or culture. // // //////////////////////////////////////////////////////////////////////////// using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.Serialization; namespace System.Globalization { public class RegionInfo { //--------------------------------------------------------------------// // Internal Information // //--------------------------------------------------------------------// // // Variables. // // // Name of this region (ie: es-US): serialized, the field used for deserialization // internal String _name; // // The CultureData instance that we are going to read data from. // internal CultureData _cultureData; // // The RegionInfo for our current region // internal static volatile RegionInfo s_currentRegionInfo; //////////////////////////////////////////////////////////////////////// // // RegionInfo Constructors // // Note: We prefer that a region be created with a full culture name (ie: en-US) // because otherwise the native strings won't be right. // // In Silverlight we enforce that RegionInfos must be created with a full culture name // //////////////////////////////////////////////////////////////////////// public RegionInfo(String name) { if (name == null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0) //The InvariantCulture has no matching region { throw new ArgumentException(SR.Argument_NoRegionInvariantCulture, nameof(name)); } Contract.EndContractBlock(); // // For CoreCLR we only want the region names that are full culture names // _cultureData = CultureData.GetCultureDataForRegion(name, true); if (_cultureData == null) throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, SR.Argument_InvalidCultureName, name), nameof(name)); // Not supposed to be neutral if (_cultureData.IsNeutralCulture) throw new ArgumentException(SR.Format(SR.Argument_InvalidNeutralRegionName, name), nameof(name)); SetName(name); } public RegionInfo(int culture) { if (culture == CultureInfo.LOCALE_INVARIANT) //The InvariantCulture has no matching region { throw new ArgumentException(SR.Argument_NoRegionInvariantCulture); } if (culture == CultureInfo.LOCALE_NEUTRAL) { // Not supposed to be neutral throw new ArgumentException(SR.Format(SR.Argument_CultureIsNeutral, culture), nameof(culture)); } if (culture == CultureInfo.LOCALE_CUSTOM_DEFAULT) { // Not supposed to be neutral throw new ArgumentException(SR.Format(SR.Argument_CustomCultureCannotBePassedByNumber, culture), nameof(culture)); } _cultureData = CultureData.GetCultureData(culture, true); _name = _cultureData.SREGIONNAME; if (_cultureData.IsNeutralCulture) { // Not supposed to be neutral throw new ArgumentException(SR.Format(SR.Argument_CultureIsNeutral, culture), nameof(culture)); } } internal RegionInfo(CultureData cultureData) { _cultureData = cultureData; _name = _cultureData.SREGIONNAME; } private void SetName(string name) { // when creating region by culture name, we keep the region name as the culture name so regions // created by custom culture names can be differentiated from built in regions. this._name = name.Equals(_cultureData.SREGIONNAME, StringComparison.OrdinalIgnoreCase) ? _cultureData.SREGIONNAME : _cultureData.CultureName; } //////////////////////////////////////////////////////////////////////// // // GetCurrentRegion // // This instance provides methods based on the current user settings. // These settings are volatile and may change over the lifetime of the // thread. // //////////////////////////////////////////////////////////////////////// public static RegionInfo CurrentRegion { get { RegionInfo temp = s_currentRegionInfo; if (temp == null) { temp = new RegionInfo(CultureInfo.CurrentCulture._cultureData); // Need full name for custom cultures temp._name = temp._cultureData.SREGIONNAME; s_currentRegionInfo = temp; } return temp; } } //////////////////////////////////////////////////////////////////////// // // GetName // // Returns the name of the region (ie: en-US) // //////////////////////////////////////////////////////////////////////// public virtual String Name { get { Debug.Assert(_name != null, "Expected RegionInfo._name to be populated already"); return (_name); } } //////////////////////////////////////////////////////////////////////// // // GetEnglishName // // Returns the name of the region in English. (ie: United States) // //////////////////////////////////////////////////////////////////////// public virtual String EnglishName { get { return (_cultureData.SENGCOUNTRY); } } //////////////////////////////////////////////////////////////////////// // // GetDisplayName // // Returns the display name (localized) of the region. (ie: United States // if the current UI language is en-US) // //////////////////////////////////////////////////////////////////////// public virtual String DisplayName { get { return (_cultureData.SLOCALIZEDCOUNTRY); } } //////////////////////////////////////////////////////////////////////// // // GetNativeName // // Returns the native name of the region. (ie: Deutschland) // WARNING: You need a full locale name for this to make sense. // //////////////////////////////////////////////////////////////////////// public virtual String NativeName { get { return (_cultureData.SNATIVECOUNTRY); } } //////////////////////////////////////////////////////////////////////// // // TwoLetterISORegionName // // Returns the two letter ISO region name (ie: US) // //////////////////////////////////////////////////////////////////////// public virtual String TwoLetterISORegionName { get { return (_cultureData.SISO3166CTRYNAME); } } //////////////////////////////////////////////////////////////////////// // // ThreeLetterISORegionName // // Returns the three letter ISO region name (ie: USA) // //////////////////////////////////////////////////////////////////////// public virtual String ThreeLetterISORegionName { get { return (_cultureData.SISO3166CTRYNAME2); } } //////////////////////////////////////////////////////////////////////// // // ThreeLetterWindowsRegionName // // Returns the three letter windows region name (ie: USA) // //////////////////////////////////////////////////////////////////////// public virtual String ThreeLetterWindowsRegionName { get { // ThreeLetterWindowsRegionName is really same as ThreeLetterISORegionName return ThreeLetterISORegionName; } } //////////////////////////////////////////////////////////////////////// // // IsMetric // // Returns true if this region uses the metric measurement system // //////////////////////////////////////////////////////////////////////// public virtual bool IsMetric { get { int value = _cultureData.IMEASURE; return (value == 0); } } public virtual int GeoId { get { return (_cultureData.IGEOID); } } //////////////////////////////////////////////////////////////////////// // // CurrencyEnglishName // // English name for this region's currency, ie: Swiss Franc // //////////////////////////////////////////////////////////////////////// public virtual string CurrencyEnglishName { get { return (_cultureData.SENGLISHCURRENCY); } } //////////////////////////////////////////////////////////////////////// // // CurrencyNativeName // // Native name for this region's currency, ie: Schweizer Franken // WARNING: You need a full locale name for this to make sense. // //////////////////////////////////////////////////////////////////////// public virtual string CurrencyNativeName { get { return (_cultureData.SNATIVECURRENCY); } } //////////////////////////////////////////////////////////////////////// // // CurrencySymbol // // Currency Symbol for this locale, ie: Fr. or $ // //////////////////////////////////////////////////////////////////////// public virtual String CurrencySymbol { get { return (_cultureData.SCURRENCY); } } //////////////////////////////////////////////////////////////////////// // // ISOCurrencySymbol // // ISO Currency Symbol for this locale, ie: CHF // //////////////////////////////////////////////////////////////////////// public virtual String ISOCurrencySymbol { get { return (_cultureData.SINTLSYMBOL); } } //////////////////////////////////////////////////////////////////////// // // Equals // // Implements Object.Equals(). Returns a boolean indicating whether // or not object refers to the same RegionInfo as the current instance. // // RegionInfos are considered equal if and only if they have the same name // (ie: en-US) // //////////////////////////////////////////////////////////////////////// public override bool Equals(Object value) { RegionInfo that = value as RegionInfo; if (that != null) { return this.Name.Equals(that.Name); } return (false); } //////////////////////////////////////////////////////////////////////// // // GetHashCode // // Implements Object.GetHashCode(). Returns the hash code for the // CultureInfo. The hash code is guaranteed to be the same for RegionInfo // A and B where A.Equals(B) is true. // //////////////////////////////////////////////////////////////////////// public override int GetHashCode() { return (this.Name.GetHashCode()); } //////////////////////////////////////////////////////////////////////// // // ToString // // Implements Object.ToString(). Returns the name of the Region, ie: es-US // //////////////////////////////////////////////////////////////////////// public override String ToString() { return (Name); } } }
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE) using UnityEngine; using UnityEngine.Serialization; using System; using System.Collections; using System.Collections.Generic; namespace Fungus { /// <summary> /// Execution state of a Block. /// </summary> public enum ExecutionState { /// <summary> No command executing </summary> Idle, /// <summary> Executing a command </summary> Executing, } /// <summary> /// A container for a sequence of Fungus comands. /// </summary> [ExecuteInEditMode] [RequireComponent(typeof(Flowchart))] [AddComponentMenu("")] public class Block : Node { [SerializeField] protected int itemId = -1; // Invalid flowchart item id [FormerlySerializedAs("sequenceName")] [Tooltip("The name of the block node as displayed in the Flowchart window")] [SerializeField] protected string blockName = "New Block"; [TextArea(2, 5)] [Tooltip("Description text to display under the block node")] [SerializeField] protected string description = ""; [Tooltip("An optional Event Handler which can execute the block when an event occurs")] [SerializeField] protected EventHandler eventHandler; [SerializeField] protected List<Command> commandList = new List<Command>(); protected ExecutionState executionState; protected Command activeCommand; /// <summary> // Index of last command executed before the current one. // -1 indicates no previous command. /// </summary> protected int previousActiveCommandIndex = -1; protected int jumpToCommandIndex = -1; protected int executionCount; protected bool executionInfoSet = false; protected virtual void Awake() { SetExecutionInfo(); } /// <summary> /// Populate the command metadata used to control execution. /// </summary> protected virtual void SetExecutionInfo() { // Give each child command a reference back to its parent block // and tell each command its index in the list. int index = 0; for (int i = 0; i < commandList.Count; i++) { var command = commandList[i]; if (command == null) { continue; } command.ParentBlock = this; command.CommandIndex = index++; } // Ensure all commands are at their correct indent level // This should have already happened in the editor, but may be necessary // if commands are added to the Block at runtime. UpdateIndentLevels(); executionInfoSet = true; } #if UNITY_EDITOR // The user can modify the command list order while playing in the editor, // so we keep the command indices updated every frame. There's no need to // do this in player builds so we compile this bit out for those builds. protected virtual void Update() { int index = 0; for (int i = 0; i < commandList.Count; i++) { var command = commandList[i]; if (command == null)// Null entry will be deleted automatically later { continue; } command.CommandIndex = index++; } } #endif #region Public members /// <summary> /// The execution state of the Block. /// </summary> public virtual ExecutionState State { get { return executionState; } } /// <summary> /// Unique identifier for the Block. /// </summary> public virtual int ItemId { get { return itemId; } set { itemId = value; } } /// <summary> /// The name of the block node as displayed in the Flowchart window. /// </summary> public virtual string BlockName { get { return blockName; } set { blockName = value; } } /// <summary> /// Description text to display under the block node /// </summary> public virtual string Description { get { return description; } } /// <summary> /// An optional Event Handler which can execute the block when an event occurs. /// Note: Using the concrete class instead of the interface here because of weird editor behaviour. /// </summary> public virtual EventHandler _EventHandler { get { return eventHandler; } set { eventHandler = value; } } /// <summary> /// The currently executing command. /// </summary> public virtual Command ActiveCommand { get { return activeCommand; } } /// <summary> /// Timer for fading Block execution icon. /// </summary> public virtual float ExecutingIconTimer { get; set; } /// <summary> /// The list of commands in the sequence. /// </summary> public virtual List<Command> CommandList { get { return commandList; } } /// <summary> /// Controls the next command to execute in the block execution coroutine. /// </summary> public virtual int JumpToCommandIndex { set { jumpToCommandIndex = value; } } /// <summary> /// Returns the parent Flowchart for this Block. /// </summary> public virtual Flowchart GetFlowchart() { return GetComponent<Flowchart>(); } /// <summary> /// Returns true if the Block is executing a command. /// </summary> public virtual bool IsExecuting() { return (executionState == ExecutionState.Executing); } /// <summary> /// Returns the number of times this Block has executed. /// </summary> public virtual int GetExecutionCount() { return executionCount; } /// <summary> /// Start a coroutine which executes all commands in the Block. Only one running instance of each Block is permitted. /// </summary> public virtual void StartExecution() { StartCoroutine(Execute()); } /// <summary> /// A coroutine method that executes all commands in the Block. Only one running instance of each Block is permitted. /// </summary> /// <param name="commandIndex">Index of command to start execution at</param> /// <param name="onComplete">Delegate function to call when execution completes</param> public virtual IEnumerator Execute(int commandIndex = 0, Action onComplete = null) { if (executionState != ExecutionState.Idle) { yield break; } if (!executionInfoSet) { SetExecutionInfo(); } executionCount++; var flowchart = GetFlowchart(); executionState = ExecutionState.Executing; BlockSignals.DoBlockStart(this); #if UNITY_EDITOR // Select the executing block & the first command flowchart.SelectedBlock = this; if (commandList.Count > 0) { flowchart.ClearSelectedCommands(); flowchart.AddSelectedCommand(commandList[0]); } #endif jumpToCommandIndex = commandIndex; int i = 0; while (true) { // Executing commands specify the next command to skip to by setting jumpToCommandIndex using Command.Continue() if (jumpToCommandIndex > -1) { i = jumpToCommandIndex; jumpToCommandIndex = -1; } // Skip disabled commands, comments and labels while (i < commandList.Count && (!commandList[i].enabled || commandList[i].GetType() == typeof(Comment) || commandList[i].GetType() == typeof(Label))) { i = commandList[i].CommandIndex + 1; } if (i >= commandList.Count) { break; } // The previous active command is needed for if / else / else if commands if (activeCommand == null) { previousActiveCommandIndex = -1; } else { previousActiveCommandIndex = activeCommand.CommandIndex; } var command = commandList[i]; activeCommand = command; if (flowchart.IsActive()) { // Auto select a command in some situations if ((flowchart.SelectedCommands.Count == 0 && i == 0) || (flowchart.SelectedCommands.Count == 1 && flowchart.SelectedCommands[0].CommandIndex == previousActiveCommandIndex)) { flowchart.ClearSelectedCommands(); flowchart.AddSelectedCommand(commandList[i]); } } command.IsExecuting = true; // This icon timer is managed by the FlowchartWindow class, but we also need to // set it here in case a command starts and finishes execution before the next window update. command.ExecutingIconTimer = Time.realtimeSinceStartup + FungusConstants.ExecutingIconFadeTime; BlockSignals.DoCommandExecute(this, command, i, commandList.Count); command.Execute(); // Wait until the executing command sets another command to jump to via Command.Continue() while (jumpToCommandIndex == -1) { yield return null; } #if UNITY_EDITOR if (flowchart.StepPause > 0f) { yield return new WaitForSeconds(flowchart.StepPause); } #endif command.IsExecuting = false; } executionState = ExecutionState.Idle; activeCommand = null; BlockSignals.DoBlockEnd(this); if (onComplete != null) { onComplete(); } } /// <summary> /// Stop executing commands in this Block. /// </summary> public virtual void Stop() { // Tell the executing command to stop immediately if (activeCommand != null) { activeCommand.IsExecuting = false; activeCommand.OnStopExecuting(); } // This will cause the execution loop to break on the next iteration jumpToCommandIndex = int.MaxValue; } /// <summary> /// Returns a list of all Blocks connected to this one. /// </summary> public virtual List<Block> GetConnectedBlocks() { var connectedBlocks = new List<Block>(); for (int i = 0; i < commandList.Count; i++) { var command = commandList[i]; if (command != null) { command.GetConnectedBlocks(ref connectedBlocks); } } return connectedBlocks; } /// <summary> /// Returns the type of the previously executing command. /// </summary> /// <returns>The previous active command type.</returns> public virtual System.Type GetPreviousActiveCommandType() { if (previousActiveCommandIndex >= 0 && previousActiveCommandIndex < commandList.Count) { return commandList[previousActiveCommandIndex].GetType(); } return null; } /// <summary> /// Recalculate the indent levels for all commands in the list. /// </summary> public virtual void UpdateIndentLevels() { int indentLevel = 0; for (int i = 0; i < commandList.Count; i++) { var command = commandList[i]; if (command == null) { continue; } if (command.CloseBlock()) { indentLevel--; } // Negative indent level is not permitted indentLevel = Math.Max(indentLevel, 0); command.IndentLevel = indentLevel; if (command.OpenBlock()) { indentLevel++; } } } #endregion } }
using System.Collections.Specialized; namespace NetDimension.NanUI.HostWindow; using Vanara.PInvoke; using static Vanara.PInvoke.DwmApi; using static Vanara.PInvoke.User32; partial class _FackUnusedClass { } internal partial class BorderlessWindow { protected HWND hWnd { get; private set; } public BorderlessWindow() { AutoScaleMode = AutoScaleMode.None; //SetStyle( // ControlStyles.AllPaintingInWmPaint | // ControlStyles.UserPaint | // ControlStyles.OptimizedDoubleBuffer //, true); //DoubleBuffered = true; SetStyle(ControlStyles.ResizeRedraw, false); BackColor = Color.Black; Padding = Padding.Empty; Text = "NanUI Host Window"; InitializeReflectedFields(); } protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); DwmSetWindowAttribute(hWnd, DWMWINDOWATTRIBUTE.DWMWA_NCRENDERING_POLICY, DWMNCRENDERINGPOLICY.DWMNCRP_ENABLED); DwmExtendFrameIntoClientArea(hWnd, new MARGINS(0, this.Width, 0, this.Height)); hWnd = new HWND(Handle); DpiHelper.InitializeDpiHelper(); _deviceDpi = DpiHelper.DeviceDpi; UxTheme.SetWindowTheme(hWnd, string.Empty, string.Empty); DisableProcessWindowsGhosting(); ScaleFactor = DpiHelper.GetScaleFactorForWindow(Handle); if (DpiHelper.IsScalingRequirementMet && ScaleFactor != 1.0f) { Scale(new SizeF(ScaleFactor, ScaleFactor)); } SetWindowPos(hWnd, HWND.NULL, 0, 0, 0, 0, SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOOWNERZORDER | SetWindowPosFlags.SWP_NOMOVE | SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_FRAMECHANGED); var currentScreenScaleFactor = DpiHelper.GetDpiForWindow(Handle); var primaryScreenScaleFactor = DpiHelper.GetScreenDpi(Screen.PrimaryScreen) / 96f; if (primaryScreenScaleFactor != 1.0f) { Font = new Font(Font.FontFamily, (float)Math.Round(Font.Size / primaryScreenScaleFactor), Font.Style); } Font = new Font(Font.FontFamily, (float)Math.Round(Font.Size * currentScreenScaleFactor), Font.Style); SetWindowCenter(); _isLoaded = true; } protected override void OnCreateControl() { base.OnCreateControl(); } private void SetWindowCenter() { if (FormBorderStyle == FormBorderStyle.None) return; if (StartPosition == FormStartPosition.CenterParent && Owner != null) { Location = new Point(Owner.Location.X + Owner.Width / 2 - Width / 2, Owner.Location.Y + Owner.Height / 2 - Height / 2); } else if (StartPosition == FormStartPosition.CenterScreen || (StartPosition == FormStartPosition.CenterParent && Owner == null)) { var currentScreen = Screen.FromPoint(MousePosition); //var initScreen = Screen.FromHandle(Handle); var w = RealFormRectangle.Width; var h = RealFormRectangle.Height; var screenLeft = 0; var screenTop = 0; if (DpiHelper.IsPerMonitorV2Awareness) { var screenDpi = DpiHelper.GetScreenDpiFromPoint(MousePosition); var screenScaleFactor = (screenDpi / 96f) / ScaleFactor; var bounds = GetScaledBounds(RealFormRectangle, new SizeF(screenScaleFactor, screenScaleFactor), BoundsSpecified.Size); w = bounds.Width; h = bounds.Height; } screenLeft += currentScreen.WorkingArea.Left; screenTop += currentScreen.WorkingArea.Top; SetWindowPos(Handle, IntPtr.Zero, screenLeft + (currentScreen.WorkingArea.Width - w) / 2, screenTop + (currentScreen.WorkingArea.Height - h) / 2, RealFormRectangle.Width, RealFormRectangle.Height, SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_NOZORDER); } } protected override void OnLoad(EventArgs e) { InitializeDropShadows(); base.OnLoad(e); if (MinMaxState == FormWindowState.Normal) { EnableShadow(true); } else { EnableShadow(false); } } protected override void OnSizeChanged(EventArgs e) { PatchClientSize(); base.OnSizeChanged(e); } protected override void OnFormClosed(FormClosedEventArgs e) { DestroyShadows(); base.OnFormClosed(e); } protected override Rectangle GetScaledBounds(Rectangle bounds, SizeF factor, BoundsSpecified specified) { var rect = base.GetScaledBounds(bounds, factor, specified); var sz = SizeFromClientSize(Size.Empty); if (!GetStyle(ControlStyles.FixedWidth) && ((specified & BoundsSpecified.Width) != BoundsSpecified.None)) { var clientWidth = bounds.Width - sz.Width; rect.Width = ((int)Math.Round((double)(clientWidth * factor.Width))) + sz.Width; } if (!GetStyle(ControlStyles.FixedHeight) && ((specified & BoundsSpecified.Height) != BoundsSpecified.None)) { var clientHeight = bounds.Height - sz.Height; rect.Height = ((int)Math.Round((double)(clientHeight * factor.Height))) + sz.Height; } return rect; } protected override Size SizeFromClientSize(Size clientSize) { return clientSize; } protected Size ClientSizeFromSize(Size size) { if (size.IsEmpty) { return Size.Empty; } var sz = SizeFromClientSize(Size.Empty); var res = new Size(size.Width - sz.Width, size.Height - sz.Height); if (WindowState != FormWindowState.Maximized) return res; var ncBorders = GetNonClientAeraBorders(); return new Size(res.Width - ncBorders.Horizontal + sz.Width, res.Height - ncBorders.Bottom * 2 + sz.Height); } protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { if (_isBoundsChangingLocked) { return; } if (_shouldPerformMaximiazedState && WindowState != FormWindowState.Minimized) { if (y != Top) y = Top; if (x != Left) x = Left; _shouldPerformMaximiazedState = false; } var size = PatchWindowSizeInRestoreWindowBoundsIfNecessary(width, height); base.SetBoundsCore(x, y, size.Width, size.Height, specified); } protected override void SetClientSizeCore(int x, int y) { if (_clientWidthField != null && _clientHeightField != null && _formStateField != null && _formStateSetClientSizeField != null) { _clientWidthField.SetValue(this, x); _clientHeightField.SetValue(this, y); var section = (BitVector32.Section)_formStateSetClientSizeField.GetValue(this); var vector = (BitVector32)_formStateField.GetValue(this); vector[section] = 1; _formStateField.SetValue(this, vector); OnClientSizeChanged(EventArgs.Empty); vector[section] = 0; _formStateField.SetValue(this, vector); Size = SizeFromClientSize(new Size(x, y)); } else { base.SetClientSizeCore(x, y); } } }
// // $Id: Manager.cs 11022 2017-07-03 17:43:28Z chambm $ // // // Original author: Matt Chambers <matt.chambers .@. vanderbilt.edu> // // Copyright 2009 Vanderbilt University - Nashville, TN 37232 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Drawing; using System.IO; using System.Linq; using DigitalRune.Windows.Docking; using pwiz.CLI.cv; using pwiz.CLI.data; using pwiz.CLI.msdata; using pwiz.CLI.analysis; using pwiz.Common.Collections; using pwiz.MSGraph; using ZedGraph; using System.Diagnostics; using SpyTools; namespace seems { /// <summary> /// Maps the filepath of a data source to its associated ManagedDataSource object /// </summary> using DataSourceMap = Dictionary<string, ManagedDataSource>; using GraphInfoMap = Map<GraphItem, List<RefPair<DataGridViewRow, GraphForm>>>; using GraphInfoList = List<RefPair<DataGridViewRow, GraphForm>>; using GraphInfo = RefPair<DataGridViewRow, GraphForm>; public delegate void GraphFormGotFocusHandler (Manager sender, GraphForm graphForm); public delegate void LoadDataSourceProgressEventHandler (Manager sender, string status, int percentage, System.ComponentModel.CancelEventArgs e); /// <summary> /// Contains the associated spectrum and chromatogram lists for a data source /// </summary> public class ManagedDataSource : IComparable<ManagedDataSource> { public ManagedDataSource() { } public ManagedDataSource( SpectrumSource source ) { this.source = source; chromatogramListForm = new ChromatogramListForm(); chromatogramListForm.Text = source.Name + " chromatograms"; chromatogramListForm.TabText = source.Name + " chromatograms"; chromatogramListForm.ShowIcon = false; CVID nativeIdFormat = CVID.MS_scan_number_only_nativeID_format; foreach (SourceFile f in source.MSDataFile.fileDescription.sourceFiles) { // the first one in the list isn't necessarily useful - could be Agilent MSCalibration.bin or the like nativeIdFormat = f.cvParamChild(CVID.MS_native_spectrum_identifier_format).cvid; if (CVID.MS_no_nativeID_format != nativeIdFormat) break; } spectrumListForm = new SpectrumListForm( nativeIdFormat ); spectrumListForm.Text = source.Name + " spectra"; spectrumListForm.TabText = source.Name + " spectra"; spectrumListForm.ShowIcon = false; spectrumDataProcessing = new DataProcessing(); //chromatogramDataProcessing = new DataProcessing(); //graphInfoMap = new GraphInfoMap(); } private SpectrumSource source; public SpectrumSource Source { get { return source; } } private SpectrumListForm spectrumListForm; public SpectrumListForm SpectrumListForm { get { return spectrumListForm; } } private ChromatogramListForm chromatogramListForm; public ChromatogramListForm ChromatogramListForm { get { return chromatogramListForm; } } public DataProcessing spectrumDataProcessing; //public DataProcessing chromatogramDataProcessing; //private GraphInfoMap graphInfoMap; //public GraphInfoMap GraphInfoMap { get { return graphInfoMap; } } public Chromatogram GetChromatogram( int index ) { return GetChromatogram( index, source.MSDataFile.run.chromatogramList ); } public Chromatogram GetChromatogram( int index, ChromatogramList chromatogramList ) { return new Chromatogram( this, index, chromatogramList ); } public Chromatogram GetChromatogram( Chromatogram metaChromatogram, ChromatogramList chromatogramList ) { Chromatogram chromatogram = new Chromatogram( metaChromatogram, chromatogramList.chromatogram( metaChromatogram.Index, true ) ); return chromatogram; } public MassSpectrum GetMassSpectrum( int index ) { return GetMassSpectrum( index, source.MSDataFile.run.spectrumList ); } public MassSpectrum GetMassSpectrum( int index, SpectrumList spectrumList ) { return new MassSpectrum( this, index, spectrumList ); } public MassSpectrum GetMassSpectrum( MassSpectrum metaSpectrum, SpectrumList spectrumList ) { MassSpectrum spectrum = new MassSpectrum( metaSpectrum, spectrumList.spectrum( metaSpectrum.Index, true ) ); //MassSpectrum realMetaSpectrum = ( metaSpectrum.Tag as DataGridViewRow ).Tag as MassSpectrum; //realMetaSpectrum.Element.dataProcessing = spectrum.Element.dataProcessing; //realMetaSpectrum.Element.defaultArrayLength = spectrum.Element.defaultArrayLength; return spectrum; } public MassSpectrum GetMassSpectrum( MassSpectrum metaSpectrum, string[] spectrumListFilters ) { var tmp = source.MSDataFile.run.spectrumList; try { SpectrumListFactory.wrap(source.MSDataFile, spectrumListFilters); return GetMassSpectrum(metaSpectrum, source.MSDataFile.run.spectrumList); } finally { source.MSDataFile.run.spectrumList = tmp; } } public int CompareTo(ManagedDataSource other) { return String.Compare(source.CurrentFilepath, other.source.CurrentFilepath, StringComparison.Ordinal); } } /// <summary> /// Manages the application /// Tracks data sources, their spectrum/chromatogram lists, and any associated graph forms /// Handles events from sources, lists, and graph forms /// </summary> public class Manager { private DataSourceMap dataSourceMap; private DataProcessing spectrumGlobalDataProcessing; private SpectrumProcessingForm spectrumProcessingForm; public SpectrumProcessingForm SpectrumProcessingForm { get { return spectrumProcessingForm; } } private SpectrumAnnotationForm spectrumAnnotationForm; public SpectrumAnnotationForm SpectrumAnnotationForm { get { return spectrumAnnotationForm; } } private DockPanel dockPanel; public DockPanel DockPanel { get { return dockPanel; } } public bool ShowChromatogramListForNewSources { get; set; } public bool ShowSpectrumListForNewSources { get; set; } public bool OpenFileUsesCurrentGraphForm { get; set; } public bool OpenFileGivesFocus { get; set; } public ImmutableDictionary<string, ManagedDataSource> DataSourceMap { get { return new ImmutableDictionary<string, ManagedDataSource>(dataSourceMap); } } public GraphForm CurrentGraphForm { get { return (DockPanel.ActiveDocument is GraphForm ? (GraphForm) DockPanel.ActiveDocument : null); } } public IList<GraphForm> CurrentGraphFormList { get { List<GraphForm> graphFormList = new List<GraphForm>(); foreach( IDockableForm form in DockPanel.Contents ) { if( form is GraphForm ) graphFormList.Add( form as GraphForm ); } return graphFormList; } } public IList<DataPointTableForm> CurrentDataPointTableFormList { get { List<DataPointTableForm> tableList = new List<DataPointTableForm>(); foreach( IDockableForm form in DockPanel.Contents ) { if( form is DataPointTableForm ) tableList.Add( form as DataPointTableForm ); } return tableList; } } /// <summary> /// Occurs when a child GraphForm gets focus /// </summary> public event GraphFormGotFocusHandler GraphFormGotFocus; public event LoadDataSourceProgressEventHandler LoadDataSourceProgress; /// <summary> /// Sends a simple progress update with a free text status and an integral percentage. /// </summary> /// <returns>True if the event handlers have set the cancel property to true, otherwise false.</returns> protected bool OnLoadDataSourceProgress (string status, int percentage) { if (LoadDataSourceProgress != null) { var e = new System.ComponentModel.CancelEventArgs(); LoadDataSourceProgress(this, status, percentage, e); if (e.Cancel) return true; } return false; } public Manager( DockPanel dockPanel ) { this.dockPanel = dockPanel; dataSourceMap = new DataSourceMap(); DockPanel.ActivePaneChanged += new EventHandler( form_GotFocus ); spectrumProcessingForm = new SpectrumProcessingForm(); spectrumProcessingForm.ProcessingChanged += spectrumProcessingForm_ProcessingChanged; //spectrumProcessingForm.GlobalProcessingOverrideButton.Click += new EventHandler( processingOverrideButton_Click ); //spectrumProcessingForm.RunProcessingOverrideButton.Click += new EventHandler( processingOverrideButton_Click ); spectrumProcessingForm.GotFocus += new EventHandler( form_GotFocus ); spectrumProcessingForm.HideOnClose = true; spectrumAnnotationForm = new SpectrumAnnotationForm(); spectrumAnnotationForm.AnnotationChanged += new EventHandler( spectrumAnnotationForm_AnnotationChanged ); spectrumAnnotationForm.GotFocus += new EventHandler( form_GotFocus ); spectrumAnnotationForm.HideOnClose = true; spectrumGlobalDataProcessing = new DataProcessing(); ShowChromatogramListForNewSources = true; ShowSpectrumListForNewSources = true; OpenFileUsesCurrentGraphForm = false; OpenFileGivesFocus = true; LoadDefaultAnnotationSettings(); } public void OpenFile( string filepath ) { OpenFile( filepath, -1 ); } public void OpenFile( string filepath, int index ) { OpenFile( filepath, index, null ); } public void OpenFile( string filepath, string id ) { OpenFile( filepath, id, null ); } public void OpenFile (string filepath, object idOrIndex, IAnnotation annotation) { OpenFile(filepath, idOrIndex, annotation, ""); } public void OpenFile( string filepath, object idOrIndex, IAnnotation annotation, string spectrumListFilters ) { try { OnLoadDataSourceProgress("Opening data source: " + Path.GetFileNameWithoutExtension(filepath), 0); string[] spectrumListFilterList = spectrumListFilters.Split(';'); if (!dataSourceMap.ContainsKey(filepath)) { var newSource = new ManagedDataSource(new SpectrumSource(filepath)); dataSourceMap.Add(filepath, newSource); if (spectrumListFilters.Length > 0) SpectrumListFactory.wrap(newSource.Source.MSDataFile, spectrumListFilterList); initializeManagedDataSource( newSource, idOrIndex, annotation, spectrumListFilterList ); } else { GraphForm graph = OpenFileUsesCurrentGraphForm && CurrentGraphForm != null ? CurrentGraphForm : OpenGraph(OpenFileGivesFocus); ManagedDataSource source = dataSourceMap[filepath]; int index = -1; if( idOrIndex is int ) index = (int) idOrIndex; else if( idOrIndex is string ) { SpectrumList sl = source.Source.MSDataFile.run.spectrumList; int findIndex = sl.find( idOrIndex as string ); if( findIndex != sl.size() ) index = findIndex; } // conditionally load the spectrum at the specified index if( index > -1 ) { MassSpectrum spectrum = source.GetMassSpectrum( index ); if (spectrumListFilters.Length > 0) SpectrumListFactory.wrap(source.Source.MSDataFile, spectrumListFilterList); spectrum.AnnotationSettings = defaultScanAnnotationSettings; if( annotation != null ) spectrum.AnnotationList.Add( annotation ); if (source.Source.Spectra.Count < source.Source.MSDataFile.run.spectrumList.size() && source.SpectrumListForm.IndexOf(spectrum) < 0) { source.SpectrumListForm.Add(spectrum); source.Source.Spectra.Add(spectrum); } showData(graph, spectrum); } else { if( source.Source.Chromatograms.Count > 0 ) showData(graph, source.Source.Chromatograms[0]); else showData(graph, source.Source.Spectra[0]); } } } catch( Exception ex ) { string message = ex.Message; if( ex.InnerException != null ) message += "\n\nAdditional information: " + ex.InnerException.Message; MessageBox.Show( message, "Error opening source file", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0, false ); OnLoadDataSourceProgress("Failed to load data: " + ex.Message, 100); } } public GraphForm CreateGraph() { GraphForm graphForm = new GraphForm(this); graphForm.ZedGraphControl.PreviewKeyDown += new PreviewKeyDownEventHandler( graphForm_PreviewKeyDown ); graphForm.ItemGotFocus += new EventHandler( form_GotFocus ); return graphForm; } public GraphForm OpenGraph( bool giveFocus ) { GraphForm graphForm = new GraphForm(this); graphForm.ZedGraphControl.PreviewKeyDown += new PreviewKeyDownEventHandler( graphForm_PreviewKeyDown ); graphForm.ItemGotFocus += new EventHandler( form_GotFocus ); graphForm.Show( DockPanel, DockState.Document ); if( giveFocus ) graphForm.Activate(); return graphForm; } protected void OnGraphFormGotFocus (Manager sender, GraphForm graphForm) { if (GraphFormGotFocus != null) GraphFormGotFocus(sender, graphForm); } void form_GotFocus( object sender, EventArgs e ) { DockableForm form = sender as DockableForm; DockPanel panel = sender as DockPanel; if( form == null && panel != null && panel.ActivePane != null ) form = panel.ActiveContent as DockableForm; if( form is GraphForm ) { GraphForm graphForm = form as GraphForm; OnGraphFormGotFocus(this, graphForm); if( graphForm.FocusedPane != null && graphForm.FocusedItem.Tag is MassSpectrum ) { // if the focused pane has multiple items, and only one item has a processing or annotation, focus on that item instead var pane = graphForm.FocusedPane; var spectrum = graphForm.FocusedItem.Tag as MassSpectrum; if (pane.CurveList.Count > 1) { if (!spectrum.ProcessingList.Any()) { var processedSpectrum = pane.CurveList.Select(o => o.Tag as MassSpectrum).FirstOrDefault(o => o != null && o.ProcessingList.Any()) ?? spectrum; spectrumProcessingForm.UpdateProcessing(processedSpectrum); } else spectrumProcessingForm.UpdateProcessing(spectrum); if (!spectrum.AnnotationList.Any()) { var annotatedSpectrum = pane.CurveList.Select(o => o.Tag as MassSpectrum).FirstOrDefault(o => o != null && o.AnnotationList.Any()) ?? spectrum; spectrumAnnotationForm.UpdateAnnotations(annotatedSpectrum); } else spectrumAnnotationForm.UpdateAnnotations(spectrum); return; } spectrumProcessingForm.UpdateProcessing(spectrum); spectrumAnnotationForm.UpdateAnnotations(spectrum); } } else if( form is SpectrumListForm ) { //SpectrumListForm listForm = form as SpectrumListForm; //listForm.GetSpectrum(0).Source }// else //seemsForm.LogEvent( sender, e ); } private MassSpectrum getMetaSpectrum( MassSpectrum spectrum ) { return spectrum.OwningListForm.GetSpectrum( spectrum.OwningListForm.IndexOf( spectrum ) ); } private void initializeManagedDataSource( ManagedDataSource managedDataSource, object idOrIndex, IAnnotation annotation, string[] spectrumListFilters ) { try { SpectrumSource source = managedDataSource.Source; MSData msDataFile = source.MSDataFile; ChromatogramListForm chromatogramListForm = managedDataSource.ChromatogramListForm; SpectrumListForm spectrumListForm = managedDataSource.SpectrumListForm; chromatogramListForm.CellDoubleClick += new ChromatogramListCellDoubleClickHandler( chromatogramListForm_CellDoubleClick ); chromatogramListForm.CellClick += new ChromatogramListCellClickHandler( chromatogramListForm_CellClick ); chromatogramListForm.GotFocus += new EventHandler( form_GotFocus ); spectrumListForm.CellDoubleClick += new SpectrumListCellDoubleClickHandler( spectrumListForm_CellDoubleClick ); spectrumListForm.CellClick += new SpectrumListCellClickHandler( spectrumListForm_CellClick ); spectrumListForm.FilterChanged += new SpectrumListFilterChangedHandler( spectrumListForm_FilterChanged ); spectrumListForm.GotFocus += new EventHandler( form_GotFocus ); bool firstChromatogramLoaded = false; bool firstSpectrumLoaded = false; GraphForm firstGraph = null; ChromatogramList cl = msDataFile.run.chromatogramList; SpectrumList sl = msDataFile.run.spectrumList; //sl = new SpectrumList_Filter( sl, new SpectrumList_FilterAcceptSpectrum( acceptSpectrum ) ); if (sl.size()+cl.size() == 0) throw new Exception("Error loading metadata: no spectra or chromatograms"); Type indexType = typeof(MassSpectrum); int index = -1; if( idOrIndex is int ) index = (int) idOrIndex; else if( idOrIndex is string ) { int findIndex = sl.find(idOrIndex as string); if (findIndex != sl.size()) index = findIndex; if (index == -1) { indexType = typeof(Chromatogram); findIndex = cl.find(idOrIndex as string); if (findIndex != cl.size()) index = findIndex; } } // conditionally load the spectrum at the specified index first if( index > -1 ) { GraphItem item = null; if (indexType == typeof(MassSpectrum)) { MassSpectrum spectrum = managedDataSource.GetMassSpectrum(index); if (spectrumListFilters.Length > 0) spectrum = managedDataSource.GetMassSpectrum(spectrum, spectrumListFilters); spectrum.AnnotationSettings = defaultScanAnnotationSettings; spectrumListForm.Add(spectrum); source.Spectra.Add(spectrum); firstSpectrumLoaded = true; if (ShowSpectrumListForNewSources) { spectrumListForm.Show(DockPanel, DockState.DockBottom); Application.DoEvents(); } if (annotation != null) spectrum.AnnotationList.Add(annotation); item = spectrum; } else { Chromatogram chromatogram = managedDataSource.GetChromatogram(index); chromatogram.AnnotationSettings = defaultChromatogramAnnotationSettings; chromatogramListForm.Add(chromatogram); source.Chromatograms.Add(chromatogram); firstChromatogramLoaded = true; if (ShowChromatogramListForNewSources) { chromatogramListForm.Show(DockPanel, DockState.DockBottom); Application.DoEvents(); } item = chromatogram; } firstGraph = OpenFileUsesCurrentGraphForm && CurrentGraphForm != null ? CurrentGraphForm : OpenGraph(OpenFileGivesFocus); showData(firstGraph, item); return; } int ticIndex = cl.find( "TIC" ); if( ticIndex < cl.size() ) { pwiz.CLI.msdata.Chromatogram tic = cl.chromatogram( ticIndex ); Chromatogram ticChromatogram = managedDataSource.GetChromatogram( ticIndex ); ticChromatogram.AnnotationSettings = defaultChromatogramAnnotationSettings; chromatogramListForm.Add( ticChromatogram ); source.Chromatograms.Add( ticChromatogram ); if( !firstSpectrumLoaded ) { firstGraph = OpenGraph( true ); showData( firstGraph, ticChromatogram ); firstChromatogramLoaded = true; if (ShowChromatogramListForNewSources) { chromatogramListForm.Show(DockPanel, DockState.DockBottom); Application.DoEvents(); } } } // get spectrum type from fileContent if possible, otherwise from first spectrum CVParam spectrumType = msDataFile.fileDescription.fileContent.cvParamChild( CVID.MS_spectrum_type ); if( spectrumType.cvid == CVID.CVID_Unknown && sl.size() > 0 ) spectrumType = sl.spectrum( 0 ).cvParamChild( CVID.MS_spectrum_type ); // load the rest of the chromatograms for( int i = 0; i < cl.size(); ++i ) { if( i == ticIndex ) continue; Chromatogram chromatogram = managedDataSource.GetChromatogram( i ); if (OnLoadDataSourceProgress(String.Format("Loading chromatograms from {0} ({1} of {2})...", managedDataSource.Source.Name, (i + 1), cl.size()), (i + 1) * 100 / cl.size())) return; chromatogram.AnnotationSettings = defaultChromatogramAnnotationSettings; chromatogramListForm.Add( chromatogram ); source.Chromatograms.Add( chromatogram ); if( !firstSpectrumLoaded && !firstChromatogramLoaded ) { firstChromatogramLoaded = true; if (ShowChromatogramListForNewSources) { chromatogramListForm.Show(DockPanel, DockState.DockBottom); Application.DoEvents(); } firstGraph = OpenGraph( true ); showData(firstGraph, chromatogram ); } Application.DoEvents(); } // get first 100 scans by sequential access spectrumListForm.BeginBulkLoad(); if (OnLoadDataSourceProgress(String.Format("Loading first 100 spectra from {0}...", managedDataSource.Source.Name), 0)) return; for( int i = 0; i < Math.Min(100, sl.size()); ++i ) { if( i == index ) // skip the preloaded spectrum continue; MassSpectrum spectrum = managedDataSource.GetMassSpectrum( i ); spectrum.AnnotationSettings = defaultScanAnnotationSettings; spectrumListForm.Add( spectrum ); source.Spectra.Add( spectrum ); if( !firstSpectrumLoaded ) { firstSpectrumLoaded = true; if( firstChromatogramLoaded ) { GraphForm spectrumGraph = CreateGraph(); spectrumGraph.Show( firstGraph.Pane, DockPaneAlignment.Bottom, 0.5 ); showData(spectrumGraph, spectrum ); } else { firstGraph = OpenGraph( true ); showData(firstGraph, spectrum ); } } } spectrumListForm.EndBulkLoad(); spectrumListForm.Show(DockPanel, DockState.DockBottom); Application.DoEvents(); // get the rest of the scans by sequential access spectrumListForm.BeginBulkLoad(); for( int i = 100; i < sl.size(); ++i ) { if( i == index ) // skip the preloaded spectrum continue; if (((i + 1) % 1000) == 0 || (i + 1) == sl.size()) { if (OnLoadDataSourceProgress(String.Format("Loading spectra from {0} ({1} of {2})...", managedDataSource.Source.Name, (i + 1), sl.size()), (i + 1) * 100 / sl.size())) return; } MassSpectrum spectrum = managedDataSource.GetMassSpectrum( i ); spectrum.AnnotationSettings = defaultScanAnnotationSettings; spectrumListForm.Add( spectrum ); source.Spectra.Add( spectrum ); Application.DoEvents(); } spectrumListForm.EndBulkLoad(); Application.DoEvents(); var ionMobilityColumn = spectrumListForm.GridView.Columns["IonMobility"]; if (ionMobilityColumn != null && ionMobilityColumn.Visible) { var heatmapForm = new HeatmapForm(this, managedDataSource); heatmapForm.Show(DockPanel, DockState.Document); } OnLoadDataSourceProgress("Finished loading source metadata.", 100); } catch( Exception ex ) { string message = "SeeMS encountered an error reading metadata from \"" + managedDataSource.Source.CurrentFilepath + "\" (" + ex.ToString() + ")"; if( ex.InnerException != null ) message += "\n\nAdditional information: " + ex.InnerException.ToString(); MessageBox.Show( message, "Error reading source metadata", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0, false ); OnLoadDataSourceProgress("Failed to load data: " + ex.Message, 100); } } void chromatogramListForm_CellClick( object sender, ChromatogramListCellClickEventArgs e ) { if( e.Chromatogram == null || e.Button != MouseButtons.Right ) return; ChromatogramListForm chromatogramListForm = sender as ChromatogramListForm; List<GraphItem> selectedGraphItems = new List<GraphItem>(); Set<int> selectedRows = new Set<int>(); foreach( DataGridViewCell cell in chromatogramListForm.GridView.SelectedCells ) { if( selectedRows.Insert( cell.RowIndex ).WasInserted ) selectedGraphItems.Add( chromatogramListForm.GetChromatogram( cell.RowIndex ) as GraphItem ); } if( selectedRows.Count == 0 ) chromatogramListForm.GridView[e.ColumnIndex, e.RowIndex].Selected = true; ContextMenuStrip menu = new ContextMenuStrip(); if( CurrentGraphForm != null ) { if( selectedRows.Count == 1 ) { menu.Items.Add( "Show as Current Graph", null, new EventHandler( graphListForm_showAsCurrentGraph ) ); menu.Items.Add( "Overlay on Current Graph", null, new EventHandler( graphListForm_overlayOnCurrentGraph ) ); menu.Items.Add( "Stack on Current Graph", null, new EventHandler( graphListForm_stackOnCurrentGraph ) ); } else { menu.Items.Add( "Overlay All on Current Graph", null, new EventHandler( graphListForm_overlayAllOnCurrentGraph ) ); menu.Items.Add( "Stack All on Current Graph", null, new EventHandler( graphListForm_showAllAsStackOnCurrentGraph ) ); } } if( selectedRows.Count == 1 ) { menu.Items.Add( "Show as New Graph", null, new EventHandler( graphListForm_showAsNewGraph ) ); menu.Items.Add( "Show Table of Data Points", null, new EventHandler( graphListForm_showTableOfDataPoints ) ); menu.Items[0].Font = new Font( menu.Items[0].Font, FontStyle.Bold ); menu.Tag = e.Chromatogram; } else { menu.Items.Add( "Show All as New Graphs", null, new EventHandler( graphListForm_showAllAsNewGraph ) ); menu.Items.Add( "Overlay All on New Graph", null, new EventHandler( graphListForm_overlayAllOnNewGraph ) ); menu.Items.Add( "Stack All on New Graph", null, new EventHandler( graphListForm_showAllAsStackOnNewGraph ) ); menu.Tag = selectedGraphItems; } menu.Show( Form.MousePosition ); } void spectrumListForm_CellClick( object sender, SpectrumListCellClickEventArgs e ) { if( e.Spectrum == null || e.Button != MouseButtons.Right ) return; SpectrumListForm spectrumListForm = sender as SpectrumListForm; List<GraphItem> selectedGraphItems = new List<GraphItem>(); Set<int> selectedRows = new Set<int>(); foreach( DataGridViewCell cell in spectrumListForm.GridView.SelectedCells ) { if( selectedRows.Insert( cell.RowIndex ).WasInserted ) selectedGraphItems.Add( spectrumListForm.GetSpectrum( cell.RowIndex ) as GraphItem ); } if( selectedRows.Count == 0 ) spectrumListForm.GridView[e.ColumnIndex, e.RowIndex].Selected = true; ContextMenuStrip menu = new ContextMenuStrip(); if( CurrentGraphForm != null ) { if( selectedRows.Count == 1 ) { menu.Items.Add( "Show as Current Graph", null, new EventHandler( graphListForm_showAsCurrentGraph ) ); menu.Items.Add( "Overlay on Current Graph", null, new EventHandler( graphListForm_overlayOnCurrentGraph ) ); menu.Items.Add( "Stack on Current Graph", null, new EventHandler( graphListForm_stackOnCurrentGraph ) ); } else { menu.Items.Add( "Overlay All on Current Graph", null, new EventHandler( graphListForm_overlayAllOnCurrentGraph ) ); menu.Items.Add( "Stack All on Current Graph", null, new EventHandler( graphListForm_showAllAsStackOnCurrentGraph ) ); } } if( selectedRows.Count == 1 ) { menu.Items.Add( "Show as New Graph", null, new EventHandler( graphListForm_showAsNewGraph ) ); menu.Items.Add( "Show Table of Data Points", null, new EventHandler( graphListForm_showTableOfDataPoints ) ); menu.Items[0].Font = new Font( menu.Items[0].Font, FontStyle.Bold ); menu.Tag = e.Spectrum; } else { menu.Items.Add( "Show All as New Graphs", null, new EventHandler( graphListForm_showAllAsNewGraph ) ); menu.Items.Add( "Overlay All on New Graph", null, new EventHandler( graphListForm_overlayAllOnNewGraph ) ); menu.Items.Add( "Stack All on New Graph", null, new EventHandler( graphListForm_showAllAsStackOnNewGraph ) ); menu.Tag = selectedGraphItems; } menu.Show( Form.MousePosition ); } #region various methods to create graph forms private void showData( GraphForm hostGraph, GraphItem item ) { Pane pane; if( hostGraph.PaneList.Count == 0 || hostGraph.PaneList.Count > 1 ) { hostGraph.PaneList.Clear(); pane = new Pane(); hostGraph.PaneList.Add( pane ); } else { pane = hostGraph.PaneList[0]; pane.Clear(); } pane.Add( item ); hostGraph.Refresh(); } private void showDataOverlay(GraphForm hostGraph, GraphItem item ) { hostGraph.PaneList[0].Add( item ); hostGraph.Refresh(); } private void showDataStacked(GraphForm hostGraph, GraphItem item ) { Pane pane = new Pane(); pane.Add( item ); hostGraph.PaneList.Add( pane ); hostGraph.Refresh(); } void graphListForm_showAsCurrentGraph( object sender, EventArgs e ) { GraphForm currentGraphForm = CurrentGraphForm; if( currentGraphForm == null ) throw new Exception( "current graph should not be null" ); GraphItem g = ( ( sender as ToolStripMenuItem ).Owner as ContextMenuStrip ).Tag as GraphItem; currentGraphForm.PaneList.Clear(); Pane pane = new Pane(); pane.Add( g ); currentGraphForm.PaneList.Add( pane ); currentGraphForm.Refresh(); } void graphListForm_overlayOnCurrentGraph( object sender, EventArgs e ) { GraphForm currentGraphForm = CurrentGraphForm; if( currentGraphForm == null ) throw new Exception( "current graph should not be null" ); GraphItem g = ( ( sender as ToolStripMenuItem ).Owner as ContextMenuStrip ).Tag as GraphItem; currentGraphForm.PaneList[0].Add( g ); currentGraphForm.Refresh(); } void graphListForm_overlayAllOnCurrentGraph( object sender, EventArgs e ) { GraphForm currentGraphForm = CurrentGraphForm; if( currentGraphForm == null ) throw new Exception( "current graph should not be null" ); List<GraphItem> gList = ( ( sender as ToolStripMenuItem ).Owner as ContextMenuStrip ).Tag as List<GraphItem>; currentGraphForm.PaneList.Clear(); Pane pane = new Pane(); foreach( GraphItem g in gList ) { pane.Add( g ); } currentGraphForm.PaneList.Add( pane ); currentGraphForm.Refresh(); } void graphListForm_showAsNewGraph( object sender, EventArgs e ) { GraphForm newGraph = OpenGraph( true ); GraphItem g = ( ( sender as ToolStripMenuItem ).Owner as ContextMenuStrip ).Tag as GraphItem; Pane pane = new Pane(); pane.Add( g ); newGraph.PaneList.Add( pane ); newGraph.Refresh(); } void graphListForm_showAllAsNewGraph( object sender, EventArgs e ) { List<GraphItem> gList = ( ( sender as ToolStripMenuItem ).Owner as ContextMenuStrip ).Tag as List<GraphItem>; foreach( GraphItem g in gList ) { GraphForm newGraph = OpenGraph( true ); Pane pane = new Pane(); pane.Add( g ); newGraph.PaneList.Add( pane ); newGraph.Refresh(); } } void graphListForm_stackOnCurrentGraph( object sender, EventArgs e ) { GraphForm currentGraphForm = CurrentGraphForm; if( currentGraphForm == null ) throw new Exception( "current graph should not be null" ); GraphItem g = ( ( sender as ToolStripMenuItem ).Owner as ContextMenuStrip ).Tag as GraphItem; Pane pane = new Pane(); pane.Add( g ); currentGraphForm.PaneList.Add( pane ); currentGraphForm.Refresh(); } void graphListForm_showAllAsStackOnCurrentGraph( object sender, EventArgs e ) { GraphForm currentGraphForm = CurrentGraphForm; if( currentGraphForm == null ) throw new Exception( "current graph should not be null" ); List<GraphItem> gList = ( ( sender as ToolStripMenuItem ).Owner as ContextMenuStrip ).Tag as List<GraphItem>; currentGraphForm.PaneList.Clear(); foreach( GraphItem g in gList ) { Pane pane = new Pane(); pane.Add( g ); currentGraphForm.PaneList.Add( pane ); } currentGraphForm.Refresh(); } void graphListForm_overlayAllOnNewGraph( object sender, EventArgs e ) { List<GraphItem> gList = ( ( sender as ToolStripMenuItem ).Owner as ContextMenuStrip ).Tag as List<GraphItem>; GraphForm newGraph = OpenGraph( true ); Pane pane = new Pane(); foreach( GraphItem g in gList ) { pane.Add( g ); } newGraph.PaneList.Add( pane ); newGraph.Refresh(); } void graphListForm_showAllAsStackOnNewGraph( object sender, EventArgs e ) { List<GraphItem> gList = ( ( sender as ToolStripMenuItem ).Owner as ContextMenuStrip ).Tag as List<GraphItem>; GraphForm newGraph = OpenGraph( true ); foreach( GraphItem g in gList ) { Pane pane = new Pane(); pane.Add( g ); newGraph.PaneList.Add( pane ); } newGraph.Refresh(); } #endregion void graphListForm_showTableOfDataPoints( object sender, EventArgs e ) { GraphItem g = ( ( sender as ToolStripMenuItem ).Owner as ContextMenuStrip ).Tag as GraphItem; DataPointTableForm form = new DataPointTableForm( g ); form.Text = g.Id + " Data"; form.Show( DockPanel, DockState.Floating ); } public void ShowDataProcessing() { GraphForm currentGraphForm = CurrentGraphForm; if( currentGraphForm == null ) throw new Exception( "current graph should not be null" ); if( currentGraphForm.FocusedPane.CurrentItemType == MSGraphItemType.spectrum ) { spectrumProcessingForm.UpdateProcessing( currentGraphForm.FocusedItem.Tag as MassSpectrum ); DockPanel.DefaultFloatingWindowSize = spectrumProcessingForm.Size; /*spectrumProcessingForm.Show( DockPanel, DockState.Floating ); Rectangle r = new Rectangle( mainForm.Location.X + mainForm.Width / 2 - spectrumProcessingForm.Width / 2, mainForm.Location.Y + mainForm.Height / 2 - spectrumProcessingForm.Height / 2, spectrumProcessingForm.Width, spectrumProcessingForm.Height ); spectrumProcessingForm.FloatAt( r );*/ spectrumProcessingForm.Show( DockPanel, DockState.DockTop ); } } private AnnotationSettings defaultScanAnnotationSettings; private AnnotationSettings defaultChromatogramAnnotationSettings; public void LoadDefaultAnnotationSettings() { defaultScanAnnotationSettings = new AnnotationSettings(); defaultScanAnnotationSettings.ShowXValues = Properties.Settings.Default.ShowScanMzLabels; defaultScanAnnotationSettings.ShowYValues = Properties.Settings.Default.ShowScanIntensityLabels; defaultScanAnnotationSettings.ShowMatchedAnnotations = Properties.Settings.Default.ShowScanMatchedAnnotations; defaultScanAnnotationSettings.ShowUnmatchedAnnotations = Properties.Settings.Default.ShowScanUnmatchedAnnotations; defaultScanAnnotationSettings.MatchTolerance = Properties.Settings.Default.MzMatchTolerance; defaultScanAnnotationSettings.MatchToleranceOverride = Properties.Settings.Default.ScanMatchToleranceOverride; defaultScanAnnotationSettings.MatchToleranceUnit = (MatchToleranceUnits) Properties.Settings.Default.MzMatchToleranceUnit; // ms-product-label -> (label alias, known color) defaultScanAnnotationSettings.LabelToAliasAndColorMap["y"] = new Pair<string, Color>( "y", Color.Blue ); defaultScanAnnotationSettings.LabelToAliasAndColorMap["b"] = new Pair<string, Color>( "b", Color.Red ); defaultScanAnnotationSettings.LabelToAliasAndColorMap["y-NH3"] = new Pair<string, Color>( "y^", Color.Green ); defaultScanAnnotationSettings.LabelToAliasAndColorMap["y-H2O"] = new Pair<string, Color>( "y*", Color.Cyan ); defaultScanAnnotationSettings.LabelToAliasAndColorMap["b-NH3"] = new Pair<string, Color>( "b^", Color.Orange ); defaultScanAnnotationSettings.LabelToAliasAndColorMap["b-H2O"] = new Pair<string, Color>( "b*", Color.Violet ); defaultChromatogramAnnotationSettings = new AnnotationSettings(); defaultChromatogramAnnotationSettings.ShowXValues = Properties.Settings.Default.ShowChromatogramTimeLabels; defaultChromatogramAnnotationSettings.ShowYValues = Properties.Settings.Default.ShowChromatogramIntensityLabels; defaultChromatogramAnnotationSettings.ShowMatchedAnnotations = Properties.Settings.Default.ShowChromatogramMatchedAnnotations; defaultChromatogramAnnotationSettings.ShowUnmatchedAnnotations = Properties.Settings.Default.ShowChromatogramUnmatchedAnnotations; defaultChromatogramAnnotationSettings.MatchTolerance = Properties.Settings.Default.TimeMatchTolerance; defaultChromatogramAnnotationSettings.MatchToleranceOverride = Properties.Settings.Default.ChromatogramMatchToleranceOverride; defaultChromatogramAnnotationSettings.MatchToleranceUnit = (MatchToleranceUnits) Properties.Settings.Default.TimeMatchToleranceUnit; } public void ShowAnnotationForm() { GraphForm currentGraphForm = CurrentGraphForm; if( currentGraphForm == null ) throw new Exception( "current graph should not be null" ); if( currentGraphForm.FocusedPane.CurrentItemType == MSGraphItemType.spectrum ) { spectrumAnnotationForm.UpdateAnnotations( currentGraphForm.FocusedItem.Tag as MassSpectrum ); DockPanel.DefaultFloatingWindowSize = spectrumAnnotationForm.Size; /*spectrumAnnotationForm.Show( DockPanel, DockState.Floating ); Rectangle r = new Rectangle( mainForm.Location.X + mainForm.Width / 2 - spectrumAnnotationForm.Width / 2, mainForm.Location.Y + mainForm.Height / 2 - spectrumAnnotationForm.Height / 2, spectrumAnnotationForm.Width, spectrumAnnotationForm.Height ); spectrumAnnotationForm.FloatAt( r );*/ spectrumAnnotationForm.Show( DockPanel, DockState.DockTop ); DockPanel.DockTopPortion = 0.3; } } void spectrumAnnotationForm_AnnotationChanged( object sender, EventArgs e ) { if( sender is SpectrumAnnotationForm ) { foreach( GraphForm form in CurrentGraphFormList ) { bool refresh = false; foreach( Pane pane in form.PaneList ) for( int i = 0; i < pane.Count && !refresh; ++i ) { if( pane[i].IsMassSpectrum && pane[i].Id == spectrumAnnotationForm.CurrentSpectrum.Id ) { refresh = true; break; } } if( refresh ) form.Refresh(); } } } private void spectrumProcessingForm_ProcessingChanged( object sender, SpectrumProcessingForm.ProcessingChangedEventArgs e ) { if (!(sender is SpectrumProcessingForm)) return; SpectrumProcessingForm spf = sender as SpectrumProcessingForm; var sourcesToUpdate = new Set<ManagedDataSource>(); foreach( GraphForm form in CurrentGraphFormList ) { bool refresh = false; foreach( Pane pane in form.PaneList ) foreach (GraphItem graphItem in pane) { if (!graphItem.IsMassSpectrum) continue; var paneSpectrum = graphItem as MassSpectrum; if (e.ChangeScope == SpectrumProcessingForm.ProcessingChangedEventArgs.Scope.Spectrum && paneSpectrum.Id != e.Spectrum.Id) continue; if (e.ChangeScope == SpectrumProcessingForm.ProcessingChangedEventArgs.Scope.Run && paneSpectrum.Source != e.Spectrum.Source) continue; paneSpectrum.SpectrumList = spectrumProcessingForm.GetProcessingSpectrumList(paneSpectrum, paneSpectrum.Source.Source.MSDataFile.run.spectrumList); refresh = true; // for spectrum changes, the spectrumList only needs to update that row and we can stop looking at other panes if (e.ChangeScope == SpectrumProcessingForm.ProcessingChangedEventArgs.Scope.Spectrum) { graphItem.Source.SpectrumListForm.UpdateRow(paneSpectrum.Source.SpectrumListForm.IndexOf(spf.CurrentSpectrum), paneSpectrum.SpectrumList); break; } else if (e.ChangeScope == SpectrumProcessingForm.ProcessingChangedEventArgs.Scope.Run && graphItem.Source == e.Spectrum.Source || e.ChangeScope == SpectrumProcessingForm.ProcessingChangedEventArgs.Scope.Global) sourcesToUpdate.Add(paneSpectrum.Source); } if( refresh ) form.Refresh(); } // update all rows for this spectrum's run (Scope.Run) or all runs (Scope.Global) foreach (var source in sourcesToUpdate) source.SpectrumListForm.UpdateAllRows(); foreach( DataPointTableForm form in CurrentDataPointTableFormList ) { bool refresh = false; foreach( GraphItem item in form.DataItems ) if( item.IsMassSpectrum && item.Id == spf.CurrentSpectrum.Id ) { ( item as MassSpectrum ).SpectrumList = spectrumProcessingForm.GetProcessingSpectrumList(item as MassSpectrum, item.Source.Source.MSDataFile.run.spectrumList); refresh = true; break; } if( refresh ) form.Refresh(); } //getMetaSpectrum( spf.CurrentSpectrum ).DataProcessing = spf.datapro; } private void chromatogramListForm_CellDoubleClick( object sender, ChromatogramListCellDoubleClickEventArgs e ) { if( e.Chromatogram == null || e.Button != MouseButtons.Left ) return; GraphForm currentGraphForm = CurrentGraphForm; if( currentGraphForm == null ) currentGraphForm = OpenGraph( true ); showData(currentGraphForm, e.Chromatogram ); currentGraphForm.ZedGraphControl.Focus(); } private void spectrumListForm_CellDoubleClick( object sender, SpectrumListCellDoubleClickEventArgs e ) { if( e.Spectrum == null ) return; GraphForm currentGraphForm = CurrentGraphForm; if( currentGraphForm == null ) currentGraphForm = OpenGraph( true ); spectrumProcessingForm.UpdateProcessing( e.Spectrum ); spectrumAnnotationForm.UpdateAnnotations( e.Spectrum ); showData( currentGraphForm, e.Spectrum ); currentGraphForm.ZedGraphControl.Focus(); } private void spectrumListForm_FilterChanged( object sender, SpectrumListFilterChangedEventArgs e ) { if (e.Matches == e.Total) OnLoadDataSourceProgress("Filters reset to show all spectra.", 100); else OnLoadDataSourceProgress(String.Format("{0} of {1} spectra matched the filter settings.", e.Matches, e.Total), 100); } private void graphForm_PreviewKeyDown( object sender, PreviewKeyDownEventArgs e ) { if( !( sender is GraphForm ) && !( sender is pwiz.MSGraph.MSGraphControl ) ) throw new Exception( "Error processing keyboard input: unable to handle sender " + sender.ToString() ); GraphForm graphForm; if( sender is GraphForm ) graphForm = sender as GraphForm; else graphForm = ( sender as pwiz.MSGraph.MSGraphControl ).Parent as GraphForm; GraphItem graphItem = graphForm.FocusedItem.Tag as GraphItem; SpectrumSource source = graphItem.Source.Source; if( source == null || graphItem == null ) return; if (graphItem is Chromatogram && !(graphItem as Chromatogram).OwningListForm.Visible || graphItem is MassSpectrum && !(graphItem as MassSpectrum).OwningListForm.Visible) return; DataGridView gridView = graphItem.IsChromatogram ? ( graphItem as Chromatogram ).OwningListForm.GridView : ( graphItem as MassSpectrum ).OwningListForm.GridView; int rowIndex = graphItem.IsChromatogram ? ( graphItem as Chromatogram ).OwningListForm.IndexOf( graphItem as Chromatogram ) : ( graphItem as MassSpectrum ).OwningListForm.IndexOf( graphItem as MassSpectrum ); int columnIndex = gridView.CurrentCell == null ? 0 : gridView.CurrentCell.ColumnIndex; int key = (int) e.KeyCode; if( ( key == (int) Keys.Left || key == (int) Keys.Up ) && rowIndex > 0 ) gridView.CurrentCell = gridView[columnIndex, rowIndex - 1]; else if( ( key == (int) Keys.Right || key == (int) Keys.Down ) && rowIndex < gridView.RowCount - 1 ) gridView.CurrentCell = gridView[columnIndex, rowIndex + 1]; else return; if( graphItem.IsMassSpectrum ) // update spectrum processing form { MassSpectrum spectrum = ( graphItem as MassSpectrum ).OwningListForm.GetSpectrum( gridView.CurrentCellAddress.Y ); spectrumProcessingForm.UpdateProcessing( spectrum ); spectrumAnnotationForm.UpdateAnnotations( spectrum ); showData( graphForm, ( graphItem as MassSpectrum ).OwningListForm.GetSpectrum( gridView.CurrentCellAddress.Y ) ); } else { showData( graphForm, ( graphItem as Chromatogram ).OwningListForm.GetChromatogram( gridView.CurrentCellAddress.Y ) ); } gridView.Parent.Refresh(); // update chromatogram/spectrum list graphForm.Pane.Refresh(); // update tab text Application.DoEvents(); //CurrentGraphForm.ZedGraphControl.PreviewKeyDown -= new PreviewKeyDownEventHandler( GraphForm_PreviewKeyDown ); //Application.DoEvents(); //CurrentGraphForm.ZedGraphControl.PreviewKeyDown += new PreviewKeyDownEventHandler( GraphForm_PreviewKeyDown ); } public void ExportIntegration() { /*SaveFileDialog exportDialog = new SaveFileDialog(); string filepath = CurrentGraphForm.Sources[0].Source.CurrentFilepath; exportDialog.InitialDirectory = Path.GetDirectoryName( filepath ); exportDialog.OverwritePrompt = true; exportDialog.RestoreDirectory = true; exportDialog.FileName = Path.GetFileNameWithoutExtension( filepath ) + "-peaks.csv"; if( exportDialog.ShowDialog() == DialogResult.OK ) { StreamWriter writer = new StreamWriter( exportDialog.FileName ); writer.WriteLine( "Id,Area" ); foreach( DataGridViewRow row in dataSourceMap[filepath].ChromatogramListForm.GridView.Rows ) { GraphItem g = row.Tag as GraphItem; writer.WriteLine( "{0},{1}", g.Id, g.TotalIntegratedArea ); } writer.Close(); }*/ } public void ShowCurrentSourceAsMzML() { GraphForm currentGraphForm = CurrentGraphForm; if( currentGraphForm == null ) throw new Exception( "current graph should not be null" ); Form previewForm = new Form(); previewForm.StartPosition = FormStartPosition.CenterParent; previewForm.Text = "MzML preview of " + currentGraphForm.PaneList[0][0].Source.Source.CurrentFilepath; TextBox previewText = new TextBox(); previewText.Multiline = true; previewText.ReadOnly = true; previewText.Dock = DockStyle.Fill; previewForm.Controls.Add( previewText ); //previewForm.Show( mainForm ); //Application.DoEvents(); string tmp = Path.GetTempFileName(); System.Threading.ParameterizedThreadStart threadStart = new System.Threading.ParameterizedThreadStart( startWritePreviewMzML ); System.Threading.Thread writeThread = new System.Threading.Thread( threadStart ); writeThread.Start( new KeyValuePair<string, MSData>( tmp, currentGraphForm.PaneList[0][0].Source.Source.MSDataFile )); writeThread.Join( 1000 ); while( writeThread.IsAlive ) { FileStream tmpStream = File.Open( tmp, FileMode.Open, FileAccess.Read, FileShare.None ); previewText.Text = new StreamReader( tmpStream ).ReadToEnd(); writeThread.Join( 1000 ); } } private void startWritePreviewMzML( object threadArg ) { KeyValuePair<string, MSDataFile> sourcePair = (KeyValuePair<string, MSDataFile>) threadArg; sourcePair.Value.write( sourcePair.Key ); } } }
// 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.Data.Common; using System.Diagnostics; using System.Text; namespace System.Data.OleDb { sealed internal class Bindings { private readonly tagDBPARAMBINDINFO[] _bindInfo; private readonly tagDBBINDING[] _dbbindings; private readonly tagDBCOLUMNACCESS[] _dbcolumns; private OleDbParameter[] _parameters; private int _collectionChangeID; private OleDbDataReader _dataReader; private ColumnBinding[] _columnBindings; private RowBinding _rowBinding; private int _index; private int _count; private int _dataBufferSize; private bool _ifIRowsetElseIRow; private bool _forceRebind; private bool _needToReset; private Bindings(int count) { _count = count; _dbbindings = new tagDBBINDING[count]; for (int i = 0; i < _dbbindings.Length; ++i) { _dbbindings[i] = new tagDBBINDING(); } _dbcolumns = new tagDBCOLUMNACCESS[count]; } internal Bindings(OleDbParameter[] parameters, int collectionChangeID) : this(parameters.Length) { _bindInfo = new tagDBPARAMBINDINFO[parameters.Length]; _parameters = parameters; _collectionChangeID = collectionChangeID; _ifIRowsetElseIRow = true; } internal Bindings(OleDbDataReader dataReader, bool ifIRowsetElseIRow, int count) : this(count) { _dataReader = dataReader; _ifIRowsetElseIRow = ifIRowsetElseIRow; } internal tagDBPARAMBINDINFO[] BindInfo { get { return _bindInfo; } } internal tagDBCOLUMNACCESS[] DBColumnAccess { get { return _dbcolumns; } } internal int CurrentIndex { //get { return _index; } set { Debug.Assert((0 <= value) && (value < _count), "bad binding index"); _index = value; } } internal ColumnBinding[] ColumnBindings() { Debug.Assert(null != _columnBindings, "null ColumnBindings"); return _columnBindings; } internal OleDbParameter[] Parameters() { Debug.Assert(null != _parameters, "null Parameters"); return _parameters; } internal RowBinding RowBinding() { //Debug.Assert(null != _rowBinding, "null RowBinding"); return _rowBinding; } internal bool ForceRebind { get { return _forceRebind; } set { _forceRebind = value; } } // tagDBPARAMBINDINFO member access internal IntPtr DataSourceType { //get { return _bindInfo[_index].pwszDataSourceType; } set { _bindInfo[_index].pwszDataSourceType = value; } } internal IntPtr Name { //get { return _bindInfo[_index].pwszName; } set { _bindInfo[_index].pwszName = value; } } internal IntPtr ParamSize { get { if (null != _bindInfo) { return _bindInfo[_index].ulParamSize; } return IntPtr.Zero; } set { _bindInfo[_index].ulParamSize = value; } } internal int Flags { //get { return _bindInfo[_index].dwFlag; } set { _bindInfo[_index].dwFlags = value; } } // tagDBBINDING member access // internal IntPtr Ordinal { // iOrdinal //get { return _dbbindings[_index].iOrdinal.ToInt32(); } set { _dbbindings[_index].iOrdinal = value; } } #if DEBUG /*internal int ValueOffset { // obValue get { return _dbbindings[_index].obValue.ToInt32(); } } internal int LengthOffset { // obLength get { return _dbbindings[_index].obLength.ToInt32(); } } internal int StatusOffset { // obStatus get { return _dbbindings[_index].obStatus.ToInt32(); } }*/ #endif internal int Part { // dwPart #if DEBUG //get { return _dbbindings[_index].dwPart; } #endif set { _dbbindings[_index].dwPart = value; } } internal int ParamIO { // eParamIO #if DEBUG //get { return _dbbindings[_index].eParamIO; } #endif set { _dbbindings[_index].eParamIO = value; } } internal int MaxLen { // cbMaxLen //get { return (int) _dbbindings[_index].cbMaxLen; } set { Debug.Assert(0 <= value, "invalid MaxLen"); _dbbindings[_index].obStatus = (IntPtr)(_dataBufferSize + 0); _dbbindings[_index].obLength = (IntPtr)(_dataBufferSize + ADP.PtrSize); _dbbindings[_index].obValue = (IntPtr)(_dataBufferSize + ADP.PtrSize + ADP.PtrSize); _dataBufferSize += ADP.PtrSize + ADP.PtrSize; switch (DbType) { case (NativeDBType.BSTR): // ADP.PtrSize case (NativeDBType.HCHAPTER): // ADP.PtrSize case (NativeDBType.PROPVARIANT): // sizeof(PROPVARIANT) case (NativeDBType.VARIANT): // 16 or 24 (8 + ADP.PtrSize *2) case (NativeDBType.BYREF | NativeDBType.BYTES): // ADP.PtrSize case (NativeDBType.BYREF | NativeDBType.WSTR): // ADP.PtrSize // allocate extra space to cache original value for disposal _dataBufferSize += System.Data.OleDb.RowBinding.AlignDataSize(value * 2); _needToReset = true; break; default: _dataBufferSize += System.Data.OleDb.RowBinding.AlignDataSize(value); break; } _dbbindings[_index].cbMaxLen = (IntPtr)value; _dbcolumns[_index].cbMaxLen = (IntPtr)value; } } internal int DbType { // wType get { return _dbbindings[_index].wType; } set { _dbbindings[_index].wType = (short)value; _dbcolumns[_index].wType = (short)value; } } internal byte Precision { // bPrecision #if DEBUG //get { return _dbbindings[_index].bPrecision; } #endif set { if (null != _bindInfo) { _bindInfo[_index].bPrecision = value; } _dbbindings[_index].bPrecision = value; _dbcolumns[_index].bPrecision = value; } } internal byte Scale { // bScale #if DEBUG //get { return _dbbindings[_index].bScale; } #endif set { if (null != _bindInfo) { _bindInfo[_index].bScale = value; } _dbbindings[_index].bScale = value; _dbcolumns[_index].bScale = value; } } internal int AllocateForAccessor(OleDbDataReader dataReader, int indexStart, int indexForAccessor) { Debug.Assert(null == _rowBinding, "row binding already allocated"); Debug.Assert(null == _columnBindings, "column bindings already allocated"); RowBinding rowBinding = System.Data.OleDb.RowBinding.CreateBuffer(_count, _dataBufferSize, _needToReset); _rowBinding = rowBinding; ColumnBinding[] columnBindings = rowBinding.SetBindings(dataReader, this, indexStart, indexForAccessor, _parameters, _dbbindings, _ifIRowsetElseIRow); Debug.Assert(null != columnBindings, "null column bindings"); _columnBindings = columnBindings; if (!_ifIRowsetElseIRow) { Debug.Assert(columnBindings.Length == _dbcolumns.Length, "length mismatch"); for (int i = 0; i < columnBindings.Length; ++i) { _dbcolumns[i].pData = rowBinding.DangerousGetDataPtr(columnBindings[i].ValueOffset); // We are simply pointing at a location later in the buffer, so we're OK to not addref the buffer. } } #if DEBUG int index = -1; foreach (ColumnBinding binding in columnBindings) { Debug.Assert(index < binding.Index, "invaild index"); index = binding.Index; } #endif return (indexStart + columnBindings.Length); } internal void ApplyInputParameters() { ColumnBinding[] columnBindings = this.ColumnBindings(); OleDbParameter[] parameters = this.Parameters(); RowBinding().StartDataBlock(); for (int i = 0; i < parameters.Length; ++i) { if (ADP.IsDirection(parameters[i], ParameterDirection.Input)) { columnBindings[i].SetOffset(parameters[i].Offset); columnBindings[i].Value(parameters[i].GetCoercedValue()); } else { // always set ouput only and return value parameter values to null when executing parameters[i].Value = null; //columnBindings[i].SetValueEmpty(); } } } internal void ApplyOutputParameters() { ColumnBinding[] columnBindings = this.ColumnBindings(); OleDbParameter[] parameters = this.Parameters(); for (int i = 0; i < parameters.Length; ++i) { if (ADP.IsDirection(parameters[i], ParameterDirection.Output)) { parameters[i].Value = columnBindings[i].Value(); } } CleanupBindings(); } internal bool AreParameterBindingsInvalid(OleDbParameterCollection collection) { Debug.Assert(null != collection, "null parameter collection"); Debug.Assert(null != _parameters, "null parameters"); ColumnBinding[] columnBindings = this.ColumnBindings(); if (!ForceRebind && ((collection.ChangeID == _collectionChangeID) && (_parameters.Length == collection.Count))) { for (int i = 0; i < columnBindings.Length; ++i) { ColumnBinding binding = columnBindings[i]; Debug.Assert(null != binding, "null column binding"); Debug.Assert(binding.Parameter() == _parameters[i], "parameter mismatch"); if (binding.IsParameterBindingInvalid(collection[i])) { //Debug.WriteLine("ParameterBindingsInvalid"); return true; } } //Debug.WriteLine("ParameterBindingsValid"); return false; // collection and cached values are the same } //Debug.WriteLine("ParameterBindingsInvalid"); return true; } internal void CleanupBindings() { RowBinding rowBinding = this.RowBinding(); if (null != rowBinding) { rowBinding.ResetValues(); ColumnBinding[] columnBindings = this.ColumnBindings(); for (int i = 0; i < columnBindings.Length; ++i) { ColumnBinding binding = columnBindings[i]; if (null != binding) { binding.ResetValue(); } } } } internal void CloseFromConnection() { if (null != _rowBinding) { _rowBinding.CloseFromConnection(); } Dispose(); } internal OleDbHResult CreateAccessor(UnsafeNativeMethods.IAccessor iaccessor, int flags) { Debug.Assert(null != _rowBinding, "no row binding"); Debug.Assert(null != _columnBindings, "no column bindings"); return _rowBinding.CreateAccessor(iaccessor, flags, _columnBindings); } public void Dispose() { _parameters = null; _dataReader = null; _columnBindings = null; RowBinding rowBinding = _rowBinding; _rowBinding = null; if (null != rowBinding) { rowBinding.Dispose(); } } internal void GuidKindName(Guid guid, int eKind, IntPtr propid) { tagDBCOLUMNACCESS[] dbcolumns = DBColumnAccess; dbcolumns[_index].columnid.uGuid = guid; dbcolumns[_index].columnid.eKind = eKind; dbcolumns[_index].columnid.ulPropid = propid; } internal void ParameterStatus(StringBuilder builder) { ColumnBinding[] columnBindings = ColumnBindings(); for (int i = 0; i < columnBindings.Length; ++i) { ODB.CommandParameterStatus(builder, i, columnBindings[i].StatusValue()); } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.WebSites; using Microsoft.Azure.Management.WebSites.Models; using Microsoft.WindowsAzure; namespace Microsoft.Azure.Management.WebSites { /// <summary> /// The Windows Azure Web Sites management API provides a RESTful set of /// web services that interact with Windows Azure Web Sites service to /// manage your web sites. The API has entities that capture the /// relationship between an end user and the Windows Azure Web Sites /// service. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn166981.aspx for /// more information) /// </summary> public static partial class WebSiteManagementClientExtensions { /// <summary> /// Begins deleting a resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.WebSites.IWebSiteManagementClient. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse BeginDeletingResourceGroup(this IWebSiteManagementClient operations, string resourceGroupName) { return Task.Factory.StartNew((object s) => { return ((IWebSiteManagementClient)s).BeginDeletingResourceGroupAsync(resourceGroupName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begins deleting a resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.WebSites.IWebSiteManagementClient. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<OperationResponse> BeginDeletingResourceGroupAsync(this IWebSiteManagementClient operations, string resourceGroupName) { return operations.BeginDeletingResourceGroupAsync(resourceGroupName, CancellationToken.None); } /// <summary> /// Creates or updates the resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.WebSites.IWebSiteManagementClient. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the operation. /// </param> /// <returns> /// The Create or Update resource group operation response. /// </returns> public static ResourceGroupCreateOrUpdateResponse CreateOrUpdateResourceGroup(this IWebSiteManagementClient operations, string resourceGroupName, ResourceGroupCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IWebSiteManagementClient)s).CreateOrUpdateResourceGroupAsync(resourceGroupName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates or updates the resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.WebSites.IWebSiteManagementClient. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the operation. /// </param> /// <returns> /// The Create or Update resource group operation response. /// </returns> public static Task<ResourceGroupCreateOrUpdateResponse> CreateOrUpdateResourceGroupAsync(this IWebSiteManagementClient operations, string resourceGroupName, ResourceGroupCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateResourceGroupAsync(resourceGroupName, parameters, CancellationToken.None); } /// <summary> /// Gets all resource groups in the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.WebSites.IWebSiteManagementClient. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse GetResourceGroups(this IWebSiteManagementClient operations) { return Task.Factory.StartNew((object s) => { return ((IWebSiteManagementClient)s).GetResourceGroupsAsync(); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets all resource groups in the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.WebSites.IWebSiteManagementClient. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<OperationResponse> GetResourceGroupsAsync(this IWebSiteManagementClient operations) { return operations.GetResourceGroupsAsync(CancellationToken.None); } /// <summary> /// Register the resource provider with a subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.WebSites.IWebSiteManagementClient. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse RegisterResourceProvider(this IWebSiteManagementClient operations) { return Task.Factory.StartNew((object s) => { return ((IWebSiteManagementClient)s).RegisterResourceProviderAsync(); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Register the resource provider with a subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.WebSites.IWebSiteManagementClient. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<OperationResponse> RegisterResourceProviderAsync(this IWebSiteManagementClient operations) { return operations.RegisterResourceProviderAsync(CancellationToken.None); } /// <summary> /// Unregister the resource provider with a subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.WebSites.IWebSiteManagementClient. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse UnregisterResourceProvider(this IWebSiteManagementClient operations) { return Task.Factory.StartNew((object s) => { return ((IWebSiteManagementClient)s).UnregisterResourceProviderAsync(); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Unregister the resource provider with a subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.WebSites.IWebSiteManagementClient. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<OperationResponse> UnregisterResourceProviderAsync(this IWebSiteManagementClient operations) { return operations.UnregisterResourceProviderAsync(CancellationToken.None); } } }
// 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.Threading; using System.Threading.Tasks; using System.Diagnostics; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Xml; using Stress.Data; using DPStressHarness; using System.IO; namespace Stress.Data.SqlClient { public class SqlClientTestGroup : DataTestGroup { /// <summary> /// SqlNotificationRequest options string /// </summary> private static string s_notificationOptions; /// <summary> /// Connection string for SqlDependency.Start()/Stop() /// /// The connection string used for SqlDependency.Start() must always be exactly the same every time /// if you are connecting to the same database with the same user and same application domain, so /// don't randomise the connection string for calling SqlDependency.Start() /// </summary> private static string s_sqlDependencyConnString; /// <summary> /// A thread which randomly calls SqlConnection.ClearAllPools. /// This significantly increases the probability of hitting some bugs, such as: /// vstfdevdiv 674236 (SqlConnection.Open() throws InvalidOperationException for absolutely valid connection request) /// sqlbuvsts 328845 (InvalidOperationException: The requested operation cannot be completed because the connection has been broken.) (this is LSE QFE) /// However, calling ClearAllPools all the time might also significantly decrease the probability of hitting some other bug, /// so this thread will alternate between hammering on ClearAllPools for several minutes, and then doing nothing for several minutes. /// </summary> private static Thread s_clearAllPoolsThread; /// <summary> /// Call .Set() on this to cleanly stop the ClearAllPoolsThread. /// </summary> private static ManualResetEvent s_clearAllPoolsThreadStop = new ManualResetEvent(false); private static void ClearAllPoolsThreadFunc() { Random rnd = new TrackedRandom((int)Environment.TickCount); // Swap between calling ClearAllPools and doing nothing every 5 minutes. TimeSpan halfCycleTime = TimeSpan.FromMinutes(5); int minWait = 10; // milliseconds int maxWait = 1000; // milliseconds bool active = true; // Start active so we can hit vstfdevdiv 674236 asap Stopwatch stopwatch = Stopwatch.StartNew(); while (!s_clearAllPoolsThreadStop.WaitOne(rnd.Next(minWait, maxWait))) { if (stopwatch.Elapsed > halfCycleTime) { active = !active; stopwatch.Reset(); stopwatch.Start(); } if (active) { SqlConnection.ClearAllPools(); } } } public override void GlobalTestSetup() { base.GlobalTestSetup(); s_clearAllPoolsThread = new Thread(ClearAllPoolsThreadFunc); s_clearAllPoolsThread.Start(); // set the notification options for SqlNotificationRequest tests s_notificationOptions = "service=StressNotifications;local database=" + ((SqlServerDataSource)Source).Database; s_sqlDependencyConnString = Factory.CreateBaseConnectionString(null, DataStressFactory.ConnectionStringOptions.DisableMultiSubnetFailover); } public override void GlobalTestCleanup() { s_clearAllPoolsThreadStop.Set(); s_clearAllPoolsThread.Join(); SqlClientStressFactory factory = Factory as SqlClientStressFactory; if (factory != null) { factory.Terminate(); } base.GlobalTestCleanup(); } public override void GlobalExceptionHandler(Exception e) { base.GlobalExceptionHandler(e); } protected override DataStressFactory CreateFactory(ref string scenario, ref DataSource source) { SqlClientStressFactory factory = new SqlClientStressFactory(); factory.Initialize(ref scenario, ref source); return factory; } protected override bool IsCommandCancelledException(Exception e) { return base.IsCommandCancelledException(e) || ((e is SqlException || e is InvalidOperationException) && e.Message.ToLower().Contains("operation cancelled")) || (e is SqlException && e.Message.StartsWith("A severe error occurred on the current command.")) || (e is AggregateException && e.InnerException != null && IsCommandCancelledException(e.InnerException)) || (e is System.Reflection.TargetInvocationException && e.InnerException != null && IsCommandCancelledException(e.InnerException)); } protected override bool IsReaderClosedException(Exception e) { return e is TaskCanceledException || ( e is InvalidOperationException && ( (e.Message.StartsWith("Invalid attempt to call") && e.Message.EndsWith("when reader is closed.")) || e.Message.Equals("Invalid attempt to read when no data is present.") || e.Message.Equals("Invalid operation. The connection is closed.") ) ) || ( e is ObjectDisposedException && ( e.Message.Equals("Cannot access a disposed object.\r\nObject name: 'SqlSequentialStream'.") || e.Message.Equals("Cannot access a disposed object.\r\nObject name: 'SqlSequentialTextReader'.") ) ); } protected override bool AllowReaderCloseDuringReadAsync() { return true; } /// <summary> /// Utility function used by async tests /// </summary> /// <param name="com">SqlCommand to be executed.</param> /// <param name="query">Indicates if data is being queried</param> /// <param name="xml">Indicates if the query should be executed as an Xml</param> /// <param name="useBeginAPI"></param> /// <param name="cts">The Cancellation Token Source</param> /// <returns>The result of beginning of Async execution.</returns> private IAsyncResult SqlCommandBeginExecute(SqlCommand com, bool query, bool xml, bool useBeginAPI, CancellationTokenSource cts = null) { DataStressErrors.Assert(!(useBeginAPI && cts != null), "Cannot use begin api with CancellationTokenSource"); CancellationToken token = (cts != null) ? cts.Token : CancellationToken.None; if (xml) { com.CommandText = com.CommandText + " FOR XML AUTO"; return useBeginAPI ? null : com.ExecuteXmlReaderAsync(token); } else if (query) { return useBeginAPI ? null : com.ExecuteReaderAsync(token); } else { return useBeginAPI ? null : com.ExecuteNonQueryAsync(token); } } /// <summary> /// Utility function used by async tests /// </summary> /// <param name="rnd"> Used to randomize reader.Read() call, whether it should continue or break, and is passed down to ConsumeReaderAsync</param> /// <param name="result"> The Async result from Begin operation.</param> /// <param name="com"> The Sql Command to Execute</param> /// <param name="query">Indicates if data is being queried and where ExecuteQuery or Non-query to be used with the reader</param> /// <param name="xml">Indicates if the query should be executed as an Xml</param> /// <param name="cancelled">Indicates if command was cancelled and is used to throw exception if a Command cancellation related exception is encountered</param> /// <param name="cts">The Cancellation Token Source</param> private void SqlCommandEndExecute(Random rnd, IAsyncResult result, SqlCommand com, bool query, bool xml, bool cancelled, CancellationTokenSource cts = null) { try { bool closeReader = ShouldCloseDataReader(); if (xml) { XmlReader reader = null; if (result != null && result is Task<XmlReader>) { reader = AsyncUtils.GetResult<XmlReader>(result); } else { reader = AsyncUtils.ExecuteXmlReader(com); } while (reader.Read()) { if (rnd.Next(10) == 0) break; if (rnd.Next(2) == 0) continue; reader.ReadElementContentAsString(); } if (closeReader) reader.Dispose(); } else if (query) { DataStressReader reader = null; if (result != null && result is Task<SqlDataReader>) { reader = new DataStressReader(AsyncUtils.GetResult<SqlDataReader>(result)); } else { reader = new DataStressReader(AsyncUtils.ExecuteReader(com)); } CancellationToken token = (cts != null) ? cts.Token : CancellationToken.None; AsyncUtils.WaitAndUnwrapException(ConsumeReaderAsync(reader, false, token, rnd)); if (closeReader) reader.Close(); } else { if (result != null && result is Task<int>) { int temp = AsyncUtils.GetResult<int>(result); } else { AsyncUtils.ExecuteNonQuery(com); } } } catch (Exception e) { if (cancelled && IsCommandCancelledException(e)) { // expected exception, ignore } else { throw; } } } /// <summary> /// Utility function for tests /// </summary> /// <param name="rnd"></param> /// <param name="read"></param> /// <param name="poll"></param> /// <param name="handle"></param> /// <param name="xml"></param> private void TestSqlAsync(Random rnd, bool read, bool poll, bool handle, bool xml) { using (DataStressConnection conn = Factory.CreateConnection(rnd)) { if (!OpenConnection(conn)) return; DataStressFactory.TableMetadata table = Factory.GetRandomTable(rnd); SqlCommand com = (SqlCommand)Factory.GetCommand(rnd, table, conn, read, xml); bool useBeginAPI = rnd.NextBool(); IAsyncResult result = SqlCommandBeginExecute(com, read, xml, useBeginAPI); // Cancel 1/10 commands bool cancel = (rnd.Next(10) == 0); if (cancel) { if (com.Connection.State != ConnectionState.Closed) com.Cancel(); } if (result != null) WaitForAsyncOpToComplete(rnd, result, poll, handle); // At random end query or forget it if (rnd.Next(2) == 0) SqlCommandEndExecute(rnd, result, com, read, xml, cancel); // Randomly wait for the command to complete after closing the connection to verify devdiv bug 200550. // This was fixed for .NET 4.5 Task-based API, but not for the older Begin/End IAsyncResult API. conn.Close(); if (!useBeginAPI && rnd.NextBool()) result.AsyncWaitHandle.WaitOne(); } } private void WaitForAsyncOpToComplete(Random rnd, IAsyncResult result, bool poll, bool handle) { if (poll) { long ret = 0; bool wait = !result.IsCompleted; while (wait) { wait = !result.IsCompleted; Thread.Sleep(100); if (ret++ > 300) //30 second max wait time then exit wait = false; } } else if (handle) { WaitHandle wait = result.AsyncWaitHandle; wait.WaitOne(rnd.Next(1000)); } } /// <summary> /// SqlClient Async Non-blocking Read Test /// </summary> [StressTest("TestSqlAsyncNonBlockingRead", Weight = 10)] public void TestSqlAsyncNonBlockingRead() { Random rnd = RandomInstance; TestSqlAsync(rnd, read: true, poll: false, handle: false, xml: false); } /// <summary> /// SqlClient Async Non-blocking Write Test /// </summary> [StressTest("TestSqlAsyncNonBlockingWrite", Weight = 10)] public void TestSqlAsyncNonBlockingWrite() { Random rnd = RandomInstance; TestSqlAsync(rnd, read: false, poll: false, handle: false, xml: false); } /// <summary> /// SqlClient Async Polling Read Test /// </summary> [StressTest("TestSqlAsyncPollingRead", Weight = 10)] public void TestSqlAsyncPollingRead() { Random rnd = RandomInstance; TestSqlAsync(rnd, read: true, poll: true, handle: false, xml: false); } /// <summary> /// SqlClient Async Polling Write Test /// </summary> [StressTest("TestSqlAsyncPollingWrite", Weight = 10)] public void TestSqlAsyncPollingWrite() { Random rnd = RandomInstance; TestSqlAsync(rnd, read: false, poll: true, handle: false, xml: false); } /// <summary> /// SqlClient Async Event Read Test /// </summary> [StressTest("TestSqlAsyncEventRead", Weight = 10)] public void TestSqlAsyncEventRead() { Random rnd = RandomInstance; TestSqlAsync(rnd, read: true, poll: false, handle: true, xml: false); } /// <summary> /// SqlClient Async Event Write Test /// </summary> [StressTest("TestSqlAsyncEventWrite", Weight = 10)] public void TestSqlAsyncEventWrite() { Random rnd = RandomInstance; TestSqlAsync(rnd, read: false, poll: false, handle: true, xml: false); } /// <summary> /// SqlClient Async Xml Non-blocking Read Test /// </summary> [StressTest("TestSqlXmlAsyncNonBlockingRead", Weight = 10)] public void TestSqlXmlAsyncNonBlockingRead() { Random rnd = RandomInstance; TestSqlAsync(rnd, read: true, poll: false, handle: false, xml: true); } /// <summary> /// SqlClient Async Xml Polling Read Test /// </summary> [StressTest("TestSqlXmlAsyncPollingRead", Weight = 10)] public void TestSqlXmlAsyncPollingRead() { Random rnd = RandomInstance; TestSqlAsync(rnd, read: true, poll: true, handle: false, xml: true); } /// <summary> /// SqlClient Async Xml Event Read Test /// </summary> [StressTest("TestSqlXmlAsyncEventRead", Weight = 10)] public void TestSqlXmlAsyncEventRead() { Random rnd = RandomInstance; TestSqlAsync(rnd, read: true, poll: false, handle: true, xml: true); } [StressTest("TestSqlXmlCommandReader", Weight = 10)] public void TestSqlXmlCommandReader() { Random rnd = RandomInstance; using (DataStressConnection conn = Factory.CreateConnection(rnd)) { if (!OpenConnection(conn)) return; DataStressFactory.TableMetadata table = Factory.GetRandomTable(rnd); SqlCommand com = (SqlCommand)Factory.GetCommand(rnd, table, conn, query: true, isXml: true); com.CommandText = com.CommandText + " FOR XML AUTO"; // Cancel 1/10 commands bool cancel = rnd.Next(10) == 0; if (cancel) { ThreadPool.QueueUserWorkItem(new WaitCallback(CommandCancel), com); } try { XmlReader reader = com.ExecuteXmlReader(); while (reader.Read()) { if (rnd.Next(10) == 0) break; if (rnd.Next(2) == 0) continue; reader.ReadElementContentAsString(); } if (rnd.Next(10) != 0) reader.Dispose(); } catch (Exception ex) { if (cancel && IsCommandCancelledException(ex)) { // expected, ignore } else { throw; } } } } /// <summary> /// Utility function used for testing cancellation on Execute*Async APIs. /// </summary> private void TestSqlAsyncCancellation(Random rnd, bool read, bool xml) { using (DataStressConnection conn = Factory.CreateConnection(rnd)) { if (!OpenConnection(conn)) return; DataStressFactory.TableMetadata table = Factory.GetRandomTable(rnd); SqlCommand com = (SqlCommand)Factory.GetCommand(rnd, table, conn, read, xml); CancellationTokenSource cts = new CancellationTokenSource(); Task t = (Task)SqlCommandBeginExecute(com, read, xml, false, cts); cts.CancelAfter(rnd.Next(2000)); SqlCommandEndExecute(rnd, (IAsyncResult)t, com, read, xml, true, cts); } } /// <summary> /// SqlClient Async Xml Event Read Test /// </summary> [StressTest("TestExecuteXmlReaderAsyncCancellation", Weight = 10)] public void TestExecuteXmlReaderAsyncCancellation() { Random rnd = RandomInstance; TestSqlAsyncCancellation(rnd, true, true); } /// <summary> /// SqlClient Async Xml Event Read Test /// </summary> [StressTest("TestExecuteReaderAsyncCancellation", Weight = 10)] public void TestExecuteReaderAsyncCancellation() { Random rnd = RandomInstance; TestSqlAsyncCancellation(rnd, true, false); } /// <summary> /// SqlClient Async Xml Event Read Test /// </summary> [StressTest("TestExecuteNonQueryAsyncCancellation", Weight = 10)] public void TestExecuteNonQueryAsyncCancellation() { Random rnd = RandomInstance; TestSqlAsyncCancellation(rnd, false, false); } private class MARSCommand { internal SqlCommand cmd; internal IAsyncResult result; internal bool query; internal bool xml; } [StressTest("TestSqlAsyncMARS", Weight = 10)] public void TestSqlAsyncMARS() { const int MaxCmds = 11; Random rnd = RandomInstance; using (DataStressConnection conn = Factory.CreateConnection(rnd, DataStressFactory.ConnectionStringOptions.EnableMars)) { if (!OpenConnection(conn)) return; DataStressFactory.TableMetadata table = Factory.GetRandomTable(rnd); // MARS session cache is by default 10. // This is documented here: https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/enabling-multiple-active-result-sets // We want to stress test this by allowing 11 concurrent commands. Hence the max in rnd.Next below is 12. MARSCommand[] cmds = new MARSCommand[rnd.Next(5, MaxCmds + 1)]; for (int i = 0; i < cmds.Length; i++) { cmds[i] = new MARSCommand(); // Make every 3rd query xml reader if (i % 3 == 0) { cmds[i].query = true; cmds[i].xml = true; } else { cmds[i].query = rnd.NextBool(); cmds[i].xml = false; } cmds[i].cmd = (SqlCommand)Factory.GetCommand(rnd, table, conn, cmds[i].query, cmds[i].xml); cmds[i].result = SqlCommandBeginExecute(cmds[i].cmd, cmds[i].query, cmds[i].xml, rnd.NextBool()); if (cmds[i].result != null) WaitForAsyncOpToComplete(rnd, cmds[i].result, true, false); } // After all commands have been launched, wait for them to complete now. for (int i = 0; i < cmds.Length; i++) { SqlCommandEndExecute(rnd, cmds[i].result, cmds[i].cmd, cmds[i].query, cmds[i].xml, false); } } } [StressTest("TestStreamInputParameter", Weight = 10)] public void TestStreamInputParameter() { Random rnd = RandomInstance; int dataSize = 100000; byte[] data = new byte[dataSize]; rnd.NextBytes(data); using (DataStressConnection conn = Factory.CreateConnection(rnd)) { if (!OpenConnection(conn)) return; SqlCommand cmd = (SqlCommand)conn.CreateCommand(); cmd.CommandText = "SELECT @blob"; SqlParameter param = cmd.Parameters.Add("@blob", SqlDbType.VarBinary, dataSize); param.Direction = ParameterDirection.Input; param.Value = new MemoryStream(data); CommandExecute(rnd, cmd, true); } } [StressTest("TestTextReaderInputParameter", Weight = 10)] public void TestTextReaderInputParameter() { Random rnd = RandomInstance; int dataSize = 100000; string data = new string('a', dataSize); using (DataStressConnection conn = Factory.CreateConnection(rnd)) { if (!OpenConnection(conn)) return; SqlCommand cmd = (SqlCommand)conn.CreateCommand(); cmd.CommandText = "SELECT @blob"; SqlParameter param = cmd.Parameters.Add("@blob", SqlDbType.VarChar, dataSize); param.Direction = ParameterDirection.Input; param.Value = new StringReader(data); CommandExecute(rnd, cmd, true); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Brew; using Brew.TypeConverters; namespace Brew.Webforms.Widgets { /// <summary> /// Extend a Control with the jQuery UI Sortable behavior http://api.jqueryui.com/sortable/ /// </summary> public class Sortable : Widget { public Sortable() : base("sortable") { } public override List<WidgetEvent> GetEvents() { return new List<WidgetEvent>() { new WidgetEvent("create"), new WidgetEvent("start"), new WidgetEvent("sort"), new WidgetEvent("change"), new WidgetEvent("beforeStop"), new WidgetEvent("update"), new WidgetEvent("over"), new WidgetEvent("out"), new WidgetEvent("activate"), new WidgetEvent("deactivate"), new WidgetEvent("stop") { CausesPostBack = true }, new WidgetEvent("receive") { CausesPostBack = true }, new WidgetEvent("remove") { CausesPostBack = true } }; } public override List<WidgetOption> GetOptions() { return new List<WidgetOption>() { new WidgetOption { Name = "appendTo", DefaultValue = "parent" }, new WidgetOption { Name = "axis", DefaultValue = false }, new WidgetOption { Name = "cancel", DefaultValue = ":input,button" }, new WidgetOption { Name = "connectWith", DefaultValue = false }, new WidgetOption { Name = "containment", DefaultValue = false }, new WidgetOption { Name = "cursor", DefaultValue = "auto" }, new WidgetOption { Name = "cursorAt", DefaultValue = "{}" }, new WidgetOption { Name = "delay", DefaultValue = 0 }, new WidgetOption { Name = "distance", DefaultValue = 1 }, new WidgetOption { Name = "dropOnEmpty", DefaultValue = true }, new WidgetOption { Name = "forceHelperSize", DefaultValue = false }, new WidgetOption { Name = "forcePlaceholderSize", DefaultValue = false }, new WidgetOption { Name = "grid", DefaultValue = null }, new WidgetOption { Name = "handle", DefaultValue = false }, new WidgetOption { Name = "helper", DefaultValue = "original" }, new WidgetOption { Name = "items", DefaultValue = "> *" }, new WidgetOption { Name = "opacity", DefaultValue = 1 }, new WidgetOption { Name = "placeholder", DefaultValue = false }, new WidgetOption { Name = "revert", DefaultValue = false }, new WidgetOption { Name = "scroll", DefaultValue = true }, new WidgetOption { Name = "scrollSensitivity", DefaultValue = 20 }, new WidgetOption { Name = "scrollSpeed", DefaultValue = 20 }, new WidgetOption { Name = "tolerance", DefaultValue = "intersect" }, new WidgetOption { Name = "zIndex", DefaultValue = 1000 } }; } /// <summary> /// This event is triggered when sorting has stopped. /// Reference: http://api.jqueryui.com/sortable/#event-stop /// </summary> [Category("Action")] [Description("This event is triggered when sorting has stopped.")] public event EventHandler Stop; /// <summary> /// This event is triggered when a connected sortable list has received an item from another list. /// Reference: http://api.jqueryui.com/sortable/#event-receive /// </summary> [Category("Action")] [Description("This event is triggered when a connected sortable list has received an item from another list.")] public event EventHandler Receive; /// <summary> /// This event is triggered when a sortable item has been dragged out from the list and into another. /// Reference: http://api.jqueryui.com/sortable/#event-remove /// </summary> [Category("Action")] [Description("This event is triggered when a sortable item has been dragged out from the list and into another.")] public event EventHandler Remove; #region Widget Options /// <summary> /// Defines where the helper that moves with the mouse is being appended to during the drag (for example, to resolve overlap/zIndex issues). /// Reference: http://api.jqueryui.com/sortable/#option-appendTo /// </summary> [Category("Behavior")] [DefaultValue("parent")] [Description("Defines where the helper that moves with the mouse is being appended to during the drag (for example, to resolve overlap/zIndex issues).")] public string AppendTo { get; set; } /// <summary> /// If defined, the items can be dragged only horizontally or vertically. Possible values:'x', 'y'. /// Reference: http://api.jqueryui.com/sortable/#option-axis /// </summary> [Category("Behavior")] [DefaultValue(false)] [Description("If defined, the items can be dragged only horizontally or vertically. Possible values:'x', 'y'.")] [TypeConverter(typeof(StringToObjectConverter))] public dynamic Axis { get; set; } /// <summary> /// Prevents sorting if you start on elements matching the selector. /// Reference: http://api.jqueryui.com/sortable/#option-cancel /// </summary> [Category("Behavior")] [DefaultValue(":input,button")] [Description("Prevents sorting if you start on elements matching the selector.")] public string Cancel { get; set; } /// <summary> /// Takes a jQuery selector with items that also have sortables applied. If used, the sortable is now connected to the other one-way, so you can drag from this sortable to the other. /// Reference: http://api.jqueryui.com/sortable/#option-connectWith /// </summary> [Category("Behavior")] [DefaultValue(false)] [Description("Takes a jQuery selector with items that also have sortables applied. If used, the sortable is now connected to the other one-way, so you can drag from this sortable to the other.")] [TypeConverter(typeof(StringToObjectConverter))] public dynamic ConnectWith { get; set; } /// <summary> /// Constrains dragging to within the bounds of the specified element - can be a DOM element, 'parent', 'document', 'window', or a jQuery selector. /// Note: the element specified for containment must have a calculated width and height (though it need not be explicit), so for example, if you have float:left sortable children and specify containment:'parent' be sure to have float:left on the sortable/parent container as well or it will have height: 0, causing undefined behavior. /// Reference: http://api.jqueryui.com/sortable/#option-containment /// </summary> [Category("Behavior")] [DefaultValue(false)] [Description("Constrains dragging to within the bounds of the specified element - can be a DOM element, 'parent', 'document', 'window', or a jQuery selector. \nNote: the element specified for containment must have a calculated width and height (though it need not be explicit), so for example, if you have float:left sortable children and specify containment:'parent' be sure to have float:left on the sortable/parent container as well or it will have height: 0, causing undefined behavior.")] [TypeConverter(typeof(StringToObjectConverter))] public dynamic Containment { get; set; } /// <summary> /// Defines the cursor that is being shown while sorting. /// Reference: http://api.jqueryui.com/sortable/#option-cursor /// </summary> [Category("Appearance")] [DefaultValue("auto")] [Description("Defines the cursor that is being shown while sorting.")] public string Cursor { get; set; } /// <summary> /// Moves the sorting element or helper so the cursor always appears to drag from the same position. Coordinates can be given as a hash using a combination of one or two keys: { top, left, right, bottom }. /// Reference: http://api.jqueryui.com/sortable/#option-cursorAt /// </summary> [Category("Behavior")] [DefaultValue("{}")] [Description("Moves the sorting element or helper so the cursor always appears to drag from the same position. Coordinates can be given as a hash using a combination of one or two keys: { top, left, right, bottom }.")] public string CursorAt { get; set; } /// <summary> /// Time in milliseconds to define when the sorting should start. It helps preventing unwanted drags when clicking on an element. /// Reference: http://api.jqueryui.com/sortable/#option-delay /// </summary> [Category("Behavior")] [DefaultValue(0)] [Description("Time in milliseconds to define when the sorting should start. It helps preventing unwanted drags when clicking on an element.")] public int Delay { get; set; } /// <summary> /// Tolerance, in pixels, for when sorting should start. If specified, sorting will not start until after mouse is dragged beyond distance. Can be used to allow for clicks on elements within a handle. /// Reference: http://api.jqueryui.com/sortable/#option-distance /// </summary> [Category("Behavior")] [DefaultValue(1)] [Description("Tolerance, in pixels, for when sorting should start. If specified, sorting will not start until after mouse is dragged beyond distance. Can be used to allow for clicks on elements within a handle.")] public int Distance { get; set; } /// <summary> /// If false items from this sortable can't be dropped to an empty linked sortable. /// Reference: http://api.jqueryui.com/sortable/#option-dropOnEmpty /// </summary> [Category("Behavior")] [DefaultValue(true)] [Description("If false items from this sortable can't be dropped to an empty linked sortable.")] public bool DropOnEmpty { get; set; } /// <summary> /// If true, forces the helper to have a size. /// Reference: http://api.jqueryui.com/sortable/#option-forceHelperSize /// </summary> [Category("Behavior")] [DefaultValue(false)] [Description("If true, forces the helper to have a size.")] public bool ForceHelperSize { get; set; } /// <summary> /// If true, forces the placeholder to have a size. /// Reference: http://api.jqueryui.com/sortable/#option-forcePlaceholderSize /// </summary> [Category("Behavior")] [DefaultValue(false)] [Description("If true, forces the placeholder to have a size.")] public bool ForcePlaceholderSize { get; set; } /// <summary> /// Snaps the sorting element or helper to a grid, every x and y pixels. Array values: [x, y] /// Reference: http://api.jqueryui.com/sortable/#option-grid /// </summary> [TypeConverter(typeof(Int32ArrayConverter))] [Category("Behavior")] [DefaultValue(null)] [Description("Snaps the sorting element or helper to a grid, every x and y pixels. Array values: [x, y]")] public int[] Grid { get; set; } /// <summary> /// Restricts sort start click to the specified element. /// Reference: http://api.jqueryui.com/sortable/#option-handle /// </summary> [Category("Behavior")] [DefaultValue(false)] [Description("Restricts sort start click to the specified element.")] [TypeConverter(typeof(StringToObjectConverter))] public dynamic Handle { get; set; } /// <summary> /// Allows for a helper element to be used for dragging display. Possible values: 'original', 'clone' /// Reference: http://api.jqueryui.com/sortable/#option-helper /// </summary> [Category("Behavior")] [DefaultValue("original")] [Description("Allows for a helper element to be used for dragging display. Possible values: 'original', 'clone'")] public string Helper { get; set; } /// <summary> /// Specifies which items inside the element should be sortable. /// Reference: http://api.jqueryui.com/sortable/#option-items /// </summary> [Category("Behavior")] [DefaultValue("> *")] [Description("Specifies which items inside the element should be sortable.")] public string Items { get; set; } /// <summary> /// Defines the opacity of the helper while sorting. From 0.01 to 1 /// Reference: http://api.jqueryui.com/sortable/#option-opacity /// </summary> [Category("Appearance")] [DefaultValue(1)] [Description("Defines the opacity of the helper while sorting. From 0.01 to 1")] public float Opacity { get; set; } /// <summary> /// Class that gets applied to the otherwise white space. /// Reference: http://api.jqueryui.com/sortable/#option-placeholder /// </summary> [Category("Appearance")] [DefaultValue(false)] [Description("Class that gets applied to the otherwise white space.")] [TypeConverter(typeof(StringToObjectConverter))] public dynamic Placeholder { get; set; } /// <summary> /// If set to true, the item will be reverted to its new DOM position with a smooth animation. Optionally, it can also be set to a number that controls the duration of the animation in ms. /// Reference: http://api.jqueryui.com/sortable/#option-revert /// </summary> [Category("Behavior")] [DefaultValue(false)] [Description("If set to true, the item will be reverted to its new DOM position with a smooth animation. Optionally, it can also be set to a number that controls the duration of the animation in ms.")] [TypeConverter(typeof(StringToObjectConverter))] public dynamic Revert { get; set; } /// <summary> /// If set to true, the page scrolls when coming to an edge. /// Reference: http://api.jqueryui.com/sortable/#option-scroll /// </summary> [Category("Behavior")] [DefaultValue(true)] [Description("If set to true, the page scrolls when coming to an edge.")] public bool Scroll { get; set; } /// <summary> /// Defines how near the mouse must be to an edge to start scrolling. /// Reference: http://api.jqueryui.com/sortable/#option-scrollSensitivity /// </summary> [Category("Behavior")] [DefaultValue(20)] [Description("Defines how near the mouse must be to an edge to start scrolling.")] public int ScrollSensitivity { get; set; } /// <summary> /// The speed at which the window should scroll once the mouse pointer gets within the scrollSensitivity distance. /// Reference: http://api.jqueryui.com/sortable/#option-scrollSpeed /// </summary> [Category("Behavior")] [DefaultValue(20)] [Description("The speed at which the window should scroll once the mouse pointer gets within the scrollSensitivity distance.")] public int ScrollSpeed { get; set; } /// <summary> /// This is the way the reordering behaves during drag. Possible values: 'intersect', 'pointer'. In some setups, 'pointer' is more natural. /// Reference: http://api.jqueryui.com/sortable/#option-tolerance /// </summary> [Category("Behavior")] [DefaultValue("intersect")] [Description("This is the way the reordering behaves during drag. Possible values: 'intersect', 'pointer'. In some setups, 'pointer' is more natural.")] public string Tolerance { get; set; } /// <summary> /// Z-index for element/helper while being sorted. /// Reference: http://api.jqueryui.com/sortable/#option-zIndex /// </summary> [Category("Layout")] [DefaultValue(1000)] [Description("Z-index for element/helper while being sorted.")] public int ZIndex { get; set; } #endregion } }
#region Copyright // // This framework is based on log4j see http://jakarta.apache.org/log4j // Copyright (C) The Apache Software Foundation. All rights reserved. // // This software is published under the terms of the Apache Software // License version 1.1, a copy of which has been included with this // distribution in the LICENSE.txt file. // #endregion using System; using System.Collections; namespace log4net.Plugin { /// <summary> /// A strongly-typed collection of <see cref="IPlugin"/> objects. /// </summary> #if !NETCF [Serializable] #endif public class PluginCollection : ICollection, IList, IEnumerable, ICloneable { #region Interfaces /// <summary> /// Supports type-safe iteration over a <see cref="PluginCollection"/>. /// </summary> public interface IPluginCollectionEnumerator { /// <summary> /// Gets the current element in the collection. /// </summary> IPlugin Current {get;} /// <summary> /// Advances the enumerator to the next element in the collection. /// </summary> /// <exception cref="InvalidOperationException"> /// The collection was modified after the enumerator was created. /// </exception> /// <returns> /// <c>true</c> if the enumerator was successfully advanced to the next element; /// <c>false</c> if the enumerator has passed the end of the collection. /// </returns> bool MoveNext(); /// <summary> /// Sets the enumerator to its initial position, before the first element in the collection. /// </summary> void Reset(); } #endregion Interfaces private const int DEFAULT_CAPACITY = 16; #region Implementation (data) private IPlugin[] m_array; private int m_count = 0; #if !NETCF [NonSerialized] #endif private int m_version = 0; #endregion Implementation (data) #region Static Wrappers /// <summary> /// Creates a synchronized (thread-safe) wrapper for a /// <c>PluginCollection</c> instance. /// </summary> /// <returns> /// A <c>PluginCollection</c> wrapper that is synchronized (thread-safe). /// </returns> public static PluginCollection Synchronized(PluginCollection list) { if(list == null) { throw new ArgumentNullException("list"); } return new SyncPluginCollection(list); } /// <summary> /// Creates a read-only wrapper for a /// <c>PluginCollection</c> instance. /// </summary> /// <returns> /// A <c>PluginCollection</c> wrapper that is read-only. /// </returns> public static PluginCollection ReadOnly(PluginCollection list) { if(list == null) { throw new ArgumentNullException("list"); } return new ReadOnlyPluginCollection(list); } #endregion #region Construction /// <summary> /// Initializes a new instance of the <c>PluginCollection</c> class /// that is empty and has the default initial capacity. /// </summary> public PluginCollection() { m_array = new IPlugin[DEFAULT_CAPACITY]; } /// <summary> /// Initializes a new instance of the <c>PluginCollection</c> class /// that has the specified initial capacity. /// </summary> /// <param name="capacity"> /// The number of elements that the new <c>PluginCollection</c> is initially capable of storing. /// </param> public PluginCollection(int capacity) { m_array = new IPlugin[capacity]; } /// <summary> /// Initializes a new instance of the <c>PluginCollection</c> class /// that contains elements copied from the specified <c>PluginCollection</c>. /// </summary> /// <param name="c">The <c>PluginCollection</c> whose elements are copied to the new collection.</param> public PluginCollection(PluginCollection c) { m_array = new IPlugin[c.Count]; AddRange(c); } /// <summary> /// Initializes a new instance of the <c>PluginCollection</c> class /// that contains elements copied from the specified <see cref="IPlugin"/> array. /// </summary> /// <param name="a">The <see cref="IPlugin"/> array whose elements are copied to the new list.</param> public PluginCollection(IPlugin[] a) { m_array = new IPlugin[a.Length]; AddRange(a); } /// <summary> /// Initializes a new instance of the <c>PluginCollection</c> class /// that contains elements copied from the specified <see cref="IPlugin"/> collection. /// </summary> /// <param name="col">The <see cref="IPlugin"/> collection whose elements are copied to the new list.</param> public PluginCollection(ICollection col) { m_array = new IPlugin[col.Count]; AddRange(col); } /// <summary> /// Type visible only to our subclasses /// Used to access protected constructor /// </summary> protected enum Tag { /// <summary> /// A value /// </summary> Default } /// <summary> /// Allow subclasses to avoid our default constructors /// </summary> /// <param name="t"></param> protected PluginCollection(Tag t) { m_array = null; } #endregion #region Operations (type-safe ICollection) /// <summary> /// Gets the number of elements actually contained in the <c>PluginCollection</c>. /// </summary> public virtual int Count { get { return m_count; } } /// <summary> /// Copies the entire <c>PluginCollection</c> to a one-dimensional /// <see cref="IPlugin"/> array. /// </summary> /// <param name="array">The one-dimensional <see cref="IPlugin"/> array to copy to.</param> public virtual void CopyTo(IPlugin[] array) { this.CopyTo(array, 0); } /// <summary> /// Copies the entire <c>PluginCollection</c> to a one-dimensional /// <see cref="IPlugin"/> array, starting at the specified index of the target array. /// </summary> /// <param name="array">The one-dimensional <see cref="IPlugin"/> array to copy to.</param> /// <param name="start">The zero-based index in <paramref name="array"/> at which copying begins.</param> public virtual void CopyTo(IPlugin[] array, int start) { if (m_count > array.GetUpperBound(0) + 1 - start) throw new System.ArgumentException("Destination array was not long enough."); Array.Copy(m_array, 0, array, start, m_count); } /// <summary> /// Gets a value indicating whether access to the collection is synchronized (thread-safe). /// </summary> /// <returns>true if access to the ICollection is synchronized (thread-safe); otherwise, false.</returns> public virtual bool IsSynchronized { get { return m_array.IsSynchronized; } } /// <summary> /// Gets an object that can be used to synchronize access to the collection. /// </summary> /// <value> /// An object that can be used to synchronize access to the collection. /// </value> public virtual object SyncRoot { get { return m_array.SyncRoot; } } #endregion #region Operations (type-safe IList) /// <summary> /// Gets or sets the <see cref="IPlugin"/> at the specified index. /// </summary> /// <value> /// The <see cref="IPlugin"/> at the specified index. /// </value> /// <param name="index">The zero-based index of the element to get or set.</param> /// <exception cref="ArgumentOutOfRangeException"> /// <para><paramref name="index"/> is less than zero.</para> /// <para>-or-</para> /// <para><paramref name="index"/> is equal to or greater than <see cref="PluginCollection.Count"/>.</para> /// </exception> public virtual IPlugin this[int index] { get { ValidateIndex(index); // throws return m_array[index]; } set { ValidateIndex(index); // throws ++m_version; m_array[index] = value; } } /// <summary> /// Adds a <see cref="IPlugin"/> to the end of the <c>PluginCollection</c>. /// </summary> /// <param name="item">The <see cref="IPlugin"/> to be added to the end of the <c>PluginCollection</c>.</param> /// <returns>The index at which the value has been added.</returns> public virtual int Add(IPlugin item) { if (m_count == m_array.Length) EnsureCapacity(m_count + 1); m_array[m_count] = item; m_version++; return m_count++; } /// <summary> /// Removes all elements from the <c>PluginCollection</c>. /// </summary> public virtual void Clear() { ++m_version; m_array = new IPlugin[DEFAULT_CAPACITY]; m_count = 0; } /// <summary> /// Creates a shallow copy of the <see cref="PluginCollection"/>. /// </summary> public virtual object Clone() { PluginCollection newColl = new PluginCollection(m_count); Array.Copy(m_array, 0, newColl.m_array, 0, m_count); newColl.m_count = m_count; newColl.m_version = m_version; return newColl; } /// <summary> /// Determines whether a given <see cref="IPlugin"/> is in the <c>PluginCollection</c>. /// </summary> /// <param name="item">The <see cref="IPlugin"/> to check for.</param> /// <returns><c>true</c> if <paramref name="item"/> is found in the <c>PluginCollection</c>; otherwise, <c>false</c>.</returns> public virtual bool Contains(IPlugin item) { for (int i=0; i != m_count; ++i) if (m_array[i].Equals(item)) return true; return false; } /// <summary> /// Returns the zero-based index of the first occurrence of a <see cref="IPlugin"/> /// in the <c>PluginCollection</c>. /// </summary> /// <param name="item">The <see cref="IPlugin"/> to locate in the <c>PluginCollection</c>.</param> /// <returns> /// The zero-based index of the first occurrence of <paramref name="item"/> /// in the entire <c>PluginCollection</c>, if found; otherwise, -1. /// </returns> public virtual int IndexOf(IPlugin item) { for (int i=0; i != m_count; ++i) if (m_array[i].Equals(item)) return i; return -1; } /// <summary> /// Inserts an element into the <c>PluginCollection</c> at the specified index. /// </summary> /// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param> /// <param name="item">The <see cref="IPlugin"/> to insert.</param> /// <exception cref="ArgumentOutOfRangeException"> /// <para><paramref name="index"/> is less than zero</para> /// <para>-or-</para> /// <para><paramref name="index"/> is equal to or greater than <see cref="PluginCollection.Count"/>.</para> /// </exception> public virtual void Insert(int index, IPlugin item) { ValidateIndex(index, true); // throws if (m_count == m_array.Length) EnsureCapacity(m_count + 1); if (index < m_count) { Array.Copy(m_array, index, m_array, index + 1, m_count - index); } m_array[index] = item; m_count++; m_version++; } /// <summary> /// Removes the first occurrence of a specific <see cref="IPlugin"/> from the <c>PluginCollection</c>. /// </summary> /// <param name="item">The <see cref="IPlugin"/> to remove from the <c>PluginCollection</c>.</param> /// <exception cref="ArgumentException"> /// The specified <see cref="IPlugin"/> was not found in the <c>PluginCollection</c>. /// </exception> public virtual void Remove(IPlugin item) { int i = IndexOf(item); if (i < 0) { throw new System.ArgumentException("Cannot remove the specified item because it was not found in the specified Collection."); } ++m_version; RemoveAt(i); } /// <summary> /// Removes the element at the specified index of the <c>PluginCollection</c>. /// </summary> /// <param name="index">The zero-based index of the element to remove.</param> /// <exception cref="ArgumentOutOfRangeException"> /// <para><paramref name="index"/> is less than zero.</para> /// <para>-or-</para> /// <para><paramref name="index"/> is equal to or greater than <see cref="PluginCollection.Count"/>.</para> /// </exception> public virtual void RemoveAt(int index) { ValidateIndex(index); // throws m_count--; if (index < m_count) { Array.Copy(m_array, index + 1, m_array, index, m_count - index); } // We can't set the deleted entry equal to null, because it might be a value type. // Instead, we'll create an empty single-element array of the right type and copy it // over the entry we want to erase. IPlugin[] temp = new IPlugin[1]; Array.Copy(temp, 0, m_array, m_count, 1); m_version++; } /// <summary> /// Gets a value indicating whether the collection has a fixed size. /// </summary> /// <value><c>true</c> if the collection has a fixed size; otherwise, <c>false</c>. The default is <c>false</c>.</value> public virtual bool IsFixedSize { get { return false; } } /// <summary> /// Gets a value indicating whether the IList is read-only. /// </summary> /// <value><c>true</c> if the collection is read-only; otherwise, <c>false</c>. The default is <c>false</c>.</value> public virtual bool IsReadOnly { get { return false; } } #endregion #region Operations (type-safe IEnumerable) /// <summary> /// Returns an enumerator that can iterate through the <c>PluginCollection</c>. /// </summary> /// <returns>An <see cref="Enumerator"/> for the entire <c>PluginCollection</c>.</returns> public virtual IPluginCollectionEnumerator GetEnumerator() { return new Enumerator(this); } #endregion #region Public helpers (just to mimic some nice features of ArrayList) /// <summary> /// Gets or sets the number of elements the <c>PluginCollection</c> can contain. /// </summary> /// <value> /// The number of elements the <c>PluginCollection</c> can contain. /// </value> public virtual int Capacity { get { return m_array.Length; } set { if (value < m_count) value = m_count; if (value != m_array.Length) { if (value > 0) { IPlugin[] temp = new IPlugin[value]; Array.Copy(m_array, 0, temp, 0, m_count); m_array = temp; } else { m_array = new IPlugin[DEFAULT_CAPACITY]; } } } } /// <summary> /// Adds the elements of another <c>PluginCollection</c> to the current <c>PluginCollection</c>. /// </summary> /// <param name="x">The <c>PluginCollection</c> whose elements should be added to the end of the current <c>PluginCollection</c>.</param> /// <returns>The new <see cref="PluginCollection.Count"/> of the <c>PluginCollection</c>.</returns> public virtual int AddRange(PluginCollection x) { if (m_count + x.Count >= m_array.Length) EnsureCapacity(m_count + x.Count); Array.Copy(x.m_array, 0, m_array, m_count, x.Count); m_count += x.Count; m_version++; return m_count; } /// <summary> /// Adds the elements of a <see cref="IPlugin"/> array to the current <c>PluginCollection</c>. /// </summary> /// <param name="x">The <see cref="IPlugin"/> array whose elements should be added to the end of the <c>PluginCollection</c>.</param> /// <returns>The new <see cref="PluginCollection.Count"/> of the <c>PluginCollection</c>.</returns> public virtual int AddRange(IPlugin[] x) { if (m_count + x.Length >= m_array.Length) EnsureCapacity(m_count + x.Length); Array.Copy(x, 0, m_array, m_count, x.Length); m_count += x.Length; m_version++; return m_count; } /// <summary> /// Adds the elements of a <see cref="IPlugin"/> collection to the current <c>PluginCollection</c>. /// </summary> /// <param name="col">The <see cref="IPlugin"/> collection whose elements should be added to the end of the <c>PluginCollection</c>.</param> /// <returns>The new <see cref="PluginCollection.Count"/> of the <c>PluginCollection</c>.</returns> public virtual int AddRange(ICollection col) { if (m_count + col.Count >= m_array.Length) EnsureCapacity(m_count + col.Count); foreach(object item in col) { Add((IPlugin)item); } return m_count; } /// <summary> /// Sets the capacity to the actual number of elements. /// </summary> public virtual void TrimToSize() { this.Capacity = m_count; } #endregion #region Implementation (helpers) /// <exception cref="ArgumentOutOfRangeException"> /// <para><paramref name="index"/> is less than zero.</para> /// <para>-or-</para> /// <para><paramref name="index"/> is equal to or greater than <see cref="PluginCollection.Count"/>.</para> /// </exception> private void ValidateIndex(int i) { ValidateIndex(i, false); } /// <exception cref="ArgumentOutOfRangeException"> /// <para><paramref name="index"/> is less than zero.</para> /// <para>-or-</para> /// <para><paramref name="index"/> is equal to or greater than <see cref="PluginCollection.Count"/>.</para> /// </exception> private void ValidateIndex(int i, bool allowEqualEnd) { int max = (allowEqualEnd)?(m_count):(m_count-1); if (i < 0 || i > max) throw new System.ArgumentOutOfRangeException("Index was out of range. Must be non-negative and less than the size of the collection. [" + (object)i + "] Specified argument was out of the range of valid values."); } private void EnsureCapacity(int min) { int newCapacity = ((m_array.Length == 0) ? DEFAULT_CAPACITY : m_array.Length * 2); if (newCapacity < min) newCapacity = min; this.Capacity = newCapacity; } #endregion #region Implementation (ICollection) void ICollection.CopyTo(Array array, int start) { Array.Copy(m_array, 0, array, start, m_count); } #endregion #region Implementation (IList) object IList.this[int i] { get { return (object)this[i]; } set { this[i] = (IPlugin)value; } } int IList.Add(object x) { return this.Add((IPlugin)x); } bool IList.Contains(object x) { return this.Contains((IPlugin)x); } int IList.IndexOf(object x) { return this.IndexOf((IPlugin)x); } void IList.Insert(int pos, object x) { this.Insert(pos, (IPlugin)x); } void IList.Remove(object x) { this.Remove((IPlugin)x); } void IList.RemoveAt(int pos) { this.RemoveAt(pos); } #endregion #region Implementation (IEnumerable) IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator)(this.GetEnumerator()); } #endregion Implementation (IEnumerable) #region Nested enumerator class /// <summary> /// Supports simple iteration over a <see cref="PluginCollection"/>. /// </summary> private class Enumerator : IEnumerator, IPluginCollectionEnumerator { #region Implementation (data) private PluginCollection m_collection; private int m_index; private int m_version; #endregion Implementation (data) #region Construction /// <summary> /// Initializes a new instance of the <c>Enumerator</c> class. /// </summary> /// <param name="tc"></param> internal Enumerator(PluginCollection tc) { m_collection = tc; m_index = -1; m_version = tc.m_version; } #endregion #region Operations (type-safe IEnumerator) /// <summary> /// Gets the current element in the collection. /// </summary> /// <value> /// The current element in the collection. /// </value> public IPlugin Current { get { return m_collection[m_index]; } } /// <summary> /// Advances the enumerator to the next element in the collection. /// </summary> /// <exception cref="InvalidOperationException"> /// The collection was modified after the enumerator was created. /// </exception> /// <returns> /// <c>true</c> if the enumerator was successfully advanced to the next element; /// <c>false</c> if the enumerator has passed the end of the collection. /// </returns> public bool MoveNext() { if (m_version != m_collection.m_version) throw new System.InvalidOperationException("Collection was modified; enumeration operation may not execute."); ++m_index; return (m_index < m_collection.Count) ? true : false; } /// <summary> /// Sets the enumerator to its initial position, before the first element in the collection. /// </summary> public void Reset() { m_index = -1; } #endregion #region Implementation (IEnumerator) object IEnumerator.Current { get { return (object)(this.Current); } } #endregion } #endregion #region Nested Syncronized Wrapper class private class SyncPluginCollection : PluginCollection { #region Implementation (data) private PluginCollection m_collection; private object m_root; #endregion #region Construction internal SyncPluginCollection(PluginCollection list) : base(Tag.Default) { m_root = list.SyncRoot; m_collection = list; } #endregion #region Type-safe ICollection public override void CopyTo(IPlugin[] array) { lock(this.m_root) m_collection.CopyTo(array); } public override void CopyTo(IPlugin[] array, int start) { lock(this.m_root) m_collection.CopyTo(array,start); } public override int Count { get { lock(this.m_root) return m_collection.Count; } } public override bool IsSynchronized { get { return true; } } public override object SyncRoot { get { return this.m_root; } } #endregion #region Type-safe IList public override IPlugin this[int i] { get { lock(this.m_root) return m_collection[i]; } set { lock(this.m_root) m_collection[i] = value; } } public override int Add(IPlugin x) { lock(this.m_root) return m_collection.Add(x); } public override void Clear() { lock(this.m_root) m_collection.Clear(); } public override bool Contains(IPlugin x) { lock(this.m_root) return m_collection.Contains(x); } public override int IndexOf(IPlugin x) { lock(this.m_root) return m_collection.IndexOf(x); } public override void Insert(int pos, IPlugin x) { lock(this.m_root) m_collection.Insert(pos,x); } public override void Remove(IPlugin x) { lock(this.m_root) m_collection.Remove(x); } public override void RemoveAt(int pos) { lock(this.m_root) m_collection.RemoveAt(pos); } public override bool IsFixedSize { get {return m_collection.IsFixedSize;} } public override bool IsReadOnly { get {return m_collection.IsReadOnly;} } #endregion #region Type-safe IEnumerable public override IPluginCollectionEnumerator GetEnumerator() { lock(m_root) return m_collection.GetEnumerator(); } #endregion #region Public Helpers // (just to mimic some nice features of ArrayList) public override int Capacity { get { lock(this.m_root) return m_collection.Capacity; } set { lock(this.m_root) m_collection.Capacity = value; } } public override int AddRange(PluginCollection x) { lock(this.m_root) return m_collection.AddRange(x); } public override int AddRange(IPlugin[] x) { lock(this.m_root) return m_collection.AddRange(x); } #endregion } #endregion #region Nested Read Only Wrapper class private class ReadOnlyPluginCollection : PluginCollection { #region Implementation (data) private PluginCollection m_collection; #endregion #region Construction internal ReadOnlyPluginCollection(PluginCollection list) : base(Tag.Default) { m_collection = list; } #endregion #region Type-safe ICollection public override void CopyTo(IPlugin[] array) { m_collection.CopyTo(array); } public override void CopyTo(IPlugin[] array, int start) { m_collection.CopyTo(array,start); } public override int Count { get {return m_collection.Count;} } public override bool IsSynchronized { get { return m_collection.IsSynchronized; } } public override object SyncRoot { get { return this.m_collection.SyncRoot; } } #endregion #region Type-safe IList public override IPlugin this[int i] { get { return m_collection[i]; } set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } } public override int Add(IPlugin x) { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } public override void Clear() { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } public override bool Contains(IPlugin x) { return m_collection.Contains(x); } public override int IndexOf(IPlugin x) { return m_collection.IndexOf(x); } public override void Insert(int pos, IPlugin x) { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } public override void Remove(IPlugin x) { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } public override void RemoveAt(int pos) { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } public override bool IsFixedSize { get { return true; } } public override bool IsReadOnly { get { return true; } } #endregion #region Type-safe IEnumerable public override IPluginCollectionEnumerator GetEnumerator() { return m_collection.GetEnumerator(); } #endregion #region Public Helpers // (just to mimic some nice features of ArrayList) public override int Capacity { get { return m_collection.Capacity; } set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } } public override int AddRange(PluginCollection x) { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } public override int AddRange(IPlugin[] x) { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); } #endregion } #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 XorInt32() { var test = new SimpleBinaryOpTest__XorInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__XorInt32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Int32> _fld1; public Vector256<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__XorInt32 testClass) { var result = Avx2.Xor(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__XorInt32 testClass) { fixed (Vector256<Int32>* pFld1 = &_fld1) fixed (Vector256<Int32>* pFld2 = &_fld2) { var result = Avx2.Xor( Avx.LoadVector256((Int32*)(pFld1)), Avx.LoadVector256((Int32*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector256<Int32> _clsVar1; private static Vector256<Int32> _clsVar2; private Vector256<Int32> _fld1; private Vector256<Int32> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__XorInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); } public SimpleBinaryOpTest__XorInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.Xor( Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.Xor( Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.Xor( Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Xor), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Xor), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Xor), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.Xor( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Int32>* pClsVar1 = &_clsVar1) fixed (Vector256<Int32>* pClsVar2 = &_clsVar2) { var result = Avx2.Xor( Avx.LoadVector256((Int32*)(pClsVar1)), Avx.LoadVector256((Int32*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr); var result = Avx2.Xor(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)); var result = Avx2.Xor(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)); var result = Avx2.Xor(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__XorInt32(); var result = Avx2.Xor(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__XorInt32(); fixed (Vector256<Int32>* pFld1 = &test._fld1) fixed (Vector256<Int32>* pFld2 = &test._fld2) { var result = Avx2.Xor( Avx.LoadVector256((Int32*)(pFld1)), Avx.LoadVector256((Int32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.Xor(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Int32>* pFld1 = &_fld1) fixed (Vector256<Int32>* pFld2 = &_fld2) { var result = Avx2.Xor( Avx.LoadVector256((Int32*)(pFld1)), Avx.LoadVector256((Int32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.Xor(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx2.Xor( Avx.LoadVector256((Int32*)(&test._fld1)), Avx.LoadVector256((Int32*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Int32> op1, Vector256<Int32> op2, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((int)(left[0] ^ right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((int)(left[i] ^ right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Xor)}<Int32>(Vector256<Int32>, Vector256<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Text; using System.Diagnostics; using System.Threading; using Microsoft.DotNet.Cli.Build.Framework; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; using static Microsoft.DotNet.Cli.Build.Framework.BuildHelpers; using System.Threading.Tasks; namespace Microsoft.DotNet.Cli.Build { public class AzurePublisher { private static readonly string s_dotnetBlobRootUrl = "https://dotnetcli.blob.core.windows.net/dotnet/"; private static readonly string s_dotnetBlobContainerName = "dotnet"; private Task _leaseRenewalTask = null; private CancellationTokenSource _cancellationTokenSource = null; private string _connectionString { get; set; } private CloudBlobContainer _blobContainer { get; set; } public AzurePublisher() { _connectionString = EnvVars.EnsureVariable("CONNECTION_STRING").Trim('"'); _blobContainer = GetDotnetBlobContainer(_connectionString); } private CloudBlobContainer GetDotnetBlobContainer(string connectionString) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); return blobClient.GetContainerReference(s_dotnetBlobContainerName); } public void PublishInstallerFile(string installerFile, string channel, string version) { var installerFileBlob = CalculateInstallerBlob(installerFile, channel, version); PublishFile(installerFileBlob, installerFile); } public void PublishArchive(string archiveFile, string channel, string version) { var archiveFileBlob = CalculateArchiveBlob(archiveFile, channel, version); PublishFile(archiveFileBlob, archiveFile); } public void PublishFile(string blob, string file) { Console.WriteLine($"Publishing file '{file}' to '{blob}'"); CloudBlockBlob blockBlob = _blobContainer.GetBlockBlobReference(blob); blockBlob.UploadFromFileAsync( file, AccessCondition.GenerateIfNotExistsCondition(), options: null, operationContext: null).Wait(); SetBlobPropertiesBasedOnFileType(blockBlob); } public void PublishStringToBlob(string blob, string content) { CloudBlockBlob blockBlob = _blobContainer.GetBlockBlobReference(blob); blockBlob.UploadTextAsync(content).Wait(); blockBlob.Properties.ContentType = "text/plain"; blockBlob.SetPropertiesAsync().Wait(); } public void CopyBlob(string sourceBlob, string targetBlob) { Console.WriteLine($"Copying blob '{sourceBlob}' to '{targetBlob}'"); CloudBlockBlob source = _blobContainer.GetBlockBlobReference(sourceBlob); CloudBlockBlob target = _blobContainer.GetBlockBlobReference(targetBlob); // Create the empty blob using (MemoryStream ms = new MemoryStream()) { target.UploadFromStreamAsync(ms).Wait(); } // Copy actual blob data target.StartCopyAsync(source).Wait(); } private void SetBlobPropertiesBasedOnFileType(CloudBlockBlob blockBlob) { if (Path.GetExtension(blockBlob.Uri.AbsolutePath.ToLower()) == ".svg") { blockBlob.Properties.ContentType = "image/svg+xml"; blockBlob.Properties.CacheControl = "no-cache"; blockBlob.SetPropertiesAsync().Wait(); } else if (Path.GetExtension(blockBlob.Uri.AbsolutePath.ToLower()) == ".version") { blockBlob.Properties.ContentType = "text/plain"; blockBlob.SetPropertiesAsync().Wait(); } } public IEnumerable<string> ListBlobs(string virtualDirectory) { CloudBlobDirectory blobDir = _blobContainer.GetDirectoryReference(virtualDirectory); BlobContinuationToken continuationToken = new BlobContinuationToken(); var blobFiles = blobDir.ListBlobsSegmentedAsync(continuationToken).Result; return blobFiles.Results.Select(bf => bf.Uri.PathAndQuery); } public string AcquireLeaseOnBlob( string blob, TimeSpan? maxWaitDefault=null, TimeSpan? delayDefault=null) { TimeSpan maxWait = maxWaitDefault ?? TimeSpan.FromSeconds(1800); TimeSpan delay = delayDefault ?? TimeSpan.FromMilliseconds(500); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); // This will throw an exception with HTTP code 409 when we cannot acquire the lease // But we should block until we can get this lease, with a timeout (maxWaitSeconds) while (stopWatch.ElapsedMilliseconds < maxWait.TotalMilliseconds) { try { CloudBlockBlob cloudBlob = _blobContainer.GetBlockBlobReference(blob); System.Threading.Tasks.Task<string> task = cloudBlob.AcquireLeaseAsync(TimeSpan.FromMinutes(1), null); task.Wait(); string leaseID = task.Result; // Create a cancelabble task that will auto-renew the lease until the lease is released _cancellationTokenSource = new CancellationTokenSource(); _leaseRenewalTask = Task.Run(() => { AutoRenewLease(this, blob, leaseID); }, _cancellationTokenSource.Token); return leaseID; } catch (Exception e) { Console.WriteLine($"Retrying lease acquisition on {blob}, {e.Message}"); Thread.Sleep(delay); } } ResetLeaseRenewalTaskState(); throw new Exception($"Unable to acquire lease on {blob}"); } private void ResetLeaseRenewalTaskState() { // Cancel the lease renewal task if it was created if (_leaseRenewalTask != null) { _cancellationTokenSource.Cancel(); // Block until the task ends. It can throw if we cancelled it before it completed. try { _leaseRenewalTask.Wait(); } catch(Exception) { // Ignore the caught exception as it will be expected. } _leaseRenewalTask = null; } } private static void AutoRenewLease(AzurePublisher instance, string blob, string leaseId) { // We will renew the lease every 45 seconds TimeSpan maxWait = TimeSpan.FromSeconds(45); TimeSpan delay = TimeSpan.FromMilliseconds(500); TimeSpan waitFor = maxWait; CancellationToken token = instance._cancellationTokenSource.Token; while (true) { // If the task has been requested to be cancelled, then do so. token.ThrowIfCancellationRequested(); try { CloudBlockBlob cloudBlob = instance._blobContainer.GetBlockBlobReference(blob); AccessCondition ac = new AccessCondition() { LeaseId = leaseId }; cloudBlob.RenewLeaseAsync(ac).Wait(); waitFor = maxWait; } catch (Exception e) { Console.WriteLine($"Retrying lease renewal on {blob}, {e.Message}"); waitFor = delay; } // If the task has been requested to be cancelled, then do so. token.ThrowIfCancellationRequested(); Thread.Sleep(waitFor); } } public void ReleaseLeaseOnBlob(string blob, string leaseId) { // Cancel the lease renewal task since we are about to release the lease. ResetLeaseRenewalTaskState(); CloudBlockBlob cloudBlob = _blobContainer.GetBlockBlobReference(blob); AccessCondition ac = new AccessCondition() { LeaseId = leaseId }; cloudBlob.ReleaseLeaseAsync(ac).Wait(); } public bool IsLatestSpecifiedVersion(string version) { System.Threading.Tasks.Task<bool> task = _blobContainer.GetBlockBlobReference(version).ExistsAsync(); task.Wait(); return task.Result; } public void DropLatestSpecifiedVersion(string version) { CloudBlockBlob blob = _blobContainer.GetBlockBlobReference(version); using (MemoryStream ms = new MemoryStream()) { blob.UploadFromStreamAsync(ms).Wait(); } } public void CreateBlobIfNotExists(string path) { System.Threading.Tasks.Task<bool> task = _blobContainer.GetBlockBlobReference(path).ExistsAsync(); task.Wait(); if (!task.Result) { CloudBlockBlob blob = _blobContainer.GetBlockBlobReference(path); using (MemoryStream ms = new MemoryStream()) { blob.UploadFromStreamAsync(ms).Wait(); } } } public bool TryDeleteBlob(string path) { try { DeleteBlob(path); return true; } catch (Exception e) { Console.WriteLine($"Deleting blob {path} failed with \r\n{e.Message}"); return false; } } public void DeleteBlob(string path) { _blobContainer.GetBlockBlobReference(path).DeleteAsync().Wait(); } public string CalculateInstallerUploadUrl(string installerFile, string channel, string version) { return $"{s_dotnetBlobRootUrl}{CalculateInstallerBlob(installerFile, channel, version)}"; } public static string CalculateInstallerBlob(string installerFile, string channel, string version) { return $"{channel}/Installers/{version}/{Path.GetFileName(installerFile)}"; } public static string CalculateArchiveBlob(string archiveFile, string channel, string version) { return $"{channel}/Binaries/{version}/{Path.GetFileName(archiveFile)}"; } public static async Task DownloadFile(string blobFilePath, string localDownloadPath) { var blobUrl = $"{s_dotnetBlobRootUrl}{blobFilePath}"; using (var client = new HttpClient()) { var request = new HttpRequestMessage(HttpMethod.Get, blobUrl); var sendTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); var response = sendTask.Result.EnsureSuccessStatusCode(); var httpStream = await response.Content.ReadAsStreamAsync(); using (var fileStream = File.Create(localDownloadPath)) using (var reader = new StreamReader(httpStream)) { httpStream.CopyTo(fileStream); fileStream.Flush(); } } } public void DownloadFilesWithExtension(string blobVirtualDirectory, string fileExtension, string localDownloadPath) { CloudBlobDirectory blobDir = _blobContainer.GetDirectoryReference(blobVirtualDirectory); BlobContinuationToken continuationToken = new BlobContinuationToken(); var blobFiles = blobDir.ListBlobsSegmentedAsync(continuationToken).Result; foreach (var blobFile in blobFiles.Results.OfType<CloudBlockBlob>()) { if (Path.GetExtension(blobFile.Uri.AbsoluteUri) == fileExtension) { string localBlobFile = Path.Combine(localDownloadPath, Path.GetFileName(blobFile.Uri.AbsoluteUri)); Console.WriteLine($"Downloading {blobFile.Uri.AbsoluteUri} to {localBlobFile}..."); blobFile.DownloadToFileAsync(localBlobFile, FileMode.Create).Wait(); } } } } }
// 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.Diagnostics; using System.Runtime.InteropServices; using System.Security.Cryptography; using Internal.Cryptography; using Microsoft.Win32.SafeHandles; using ErrorCode = Interop.NCrypt.ErrorCode; namespace System.Security.Cryptography { internal static class CngKeyLite { internal static class KeyPropertyName { internal const string Algorithm = "Algorithm Name"; // NCRYPT_ALGORITHM_PROPERTY internal const string AlgorithmGroup = "Algorithm Group"; // NCRYPT_ALGORITHM_GROUP_PROPERTY internal const string ECCCurveName = "ECCCurveName"; // NCRYPT_ECC_CURVE_NAME internal const string ECCParameters = "ECCParameters"; // BCRYPT_ECC_PARAMETERS internal const string ExportPolicy = "Export Policy"; // NCRYPT_EXPORT_POLICY_PROPERTY internal const string Length = "Length"; // NCRYPT_LENGTH_PROPERTY internal const string PublicKeyLength = "PublicKeyLength"; // NCRYPT_PUBLIC_KEY_LENGTH (Win10+) } private static readonly SafeNCryptProviderHandle s_microsoftSoftwareProviderHandle = OpenNCryptProvider("Microsoft Software Key Storage Provider"); // MS_KEY_STORAGE_PROVIDER internal static unsafe SafeNCryptKeyHandle ImportKeyBlob( string blobType, ReadOnlySpan<byte> keyBlob, bool encrypted = false, ReadOnlySpan<char> password = default) { SafeNCryptKeyHandle keyHandle; ErrorCode errorCode; if (encrypted) { using (var stringHandle = new SafeUnicodeStringHandle(password)) { Interop.NCrypt.NCryptBuffer* buffers = stackalloc Interop.NCrypt.NCryptBuffer[1]; buffers[0] = new Interop.NCrypt.NCryptBuffer { BufferType = Interop.NCrypt.BufferType.PkcsSecret, cbBuffer = checked(2 * (password.Length + 1)), pvBuffer = stringHandle.DangerousGetHandle(), }; if (buffers[0].pvBuffer == IntPtr.Zero) { buffers[0].cbBuffer = 0; } Interop.NCrypt.NCryptBufferDesc desc = new Interop.NCrypt.NCryptBufferDesc { cBuffers = 1, pBuffers = (IntPtr)buffers, ulVersion = 0, }; errorCode = Interop.NCrypt.NCryptImportKey( s_microsoftSoftwareProviderHandle, IntPtr.Zero, blobType, ref desc, out keyHandle, ref MemoryMarshal.GetReference(keyBlob), keyBlob.Length, 0); } } else { errorCode = Interop.NCrypt.NCryptImportKey( s_microsoftSoftwareProviderHandle, IntPtr.Zero, blobType, IntPtr.Zero, out keyHandle, ref MemoryMarshal.GetReference(keyBlob), keyBlob.Length, 0); } if (errorCode != ErrorCode.ERROR_SUCCESS) { throw errorCode.ToCryptographicException(); } Debug.Assert(keyHandle != null); SetExportable(keyHandle); return keyHandle; } internal static SafeNCryptKeyHandle ImportKeyBlob(string blobType, byte[] keyBlob, string curveName) { SafeNCryptKeyHandle keyHandle; keyHandle = ECCng.ImportKeyBlob(blobType, keyBlob, curveName, s_microsoftSoftwareProviderHandle); Debug.Assert(keyHandle != null); SetExportable(keyHandle); return keyHandle; } internal static byte[] ExportKeyBlob(SafeNCryptKeyHandle keyHandle, string blobType) { Debug.Assert(!keyHandle.IsInvalid); int numBytesNeeded; ErrorCode errorCode = Interop.NCrypt.NCryptExportKey( keyHandle, IntPtr.Zero, blobType, IntPtr.Zero, null, 0, out numBytesNeeded, 0); if (errorCode != ErrorCode.ERROR_SUCCESS) { throw errorCode.ToCryptographicException(); } if (numBytesNeeded == 0) { // This is rather unlikely, but prevents an error from ref buffer[0]. return Array.Empty<byte>(); } byte[] buffer = new byte[numBytesNeeded]; errorCode = Interop.NCrypt.NCryptExportKey( keyHandle, IntPtr.Zero, blobType, IntPtr.Zero, ref buffer[0], buffer.Length, out numBytesNeeded, 0); if (errorCode != ErrorCode.ERROR_SUCCESS) { throw errorCode.ToCryptographicException(); } if (buffer.Length != numBytesNeeded) { Span<byte> writtenPortion = buffer.AsSpan(0, numBytesNeeded); byte[] tmp = writtenPortion.ToArray(); CryptographicOperations.ZeroMemory(writtenPortion); return tmp; } return buffer; } internal static bool TryExportKeyBlob( SafeNCryptKeyHandle keyHandle, string blobType, Span<byte> destination, out int bytesWritten) { if (destination.IsEmpty) { bytesWritten = 0; return false; } // Sanity check the current bounds Span<byte> empty = default; ErrorCode errorCode = Interop.NCrypt.NCryptExportKey( keyHandle, IntPtr.Zero, blobType, IntPtr.Zero, ref MemoryMarshal.GetReference(empty), empty.Length, out int written, 0); if (errorCode != ErrorCode.ERROR_SUCCESS) { throw errorCode.ToCryptographicException(); } if (written > destination.Length) { bytesWritten = 0; return false; } if (written == 0) { bytesWritten = 0; return true; } errorCode = Interop.NCrypt.NCryptExportKey( keyHandle, IntPtr.Zero, blobType, IntPtr.Zero, ref MemoryMarshal.GetReference(destination), destination.Length, out written, 0); if (errorCode != ErrorCode.ERROR_SUCCESS) { throw errorCode.ToCryptographicException(); } bytesWritten = written; return true; } internal static byte[] ExportPkcs8KeyBlob( SafeNCryptKeyHandle keyHandle, ReadOnlySpan<char> password, int kdfCount) { bool ret = ExportPkcs8KeyBlob( true, keyHandle, password, kdfCount, Span<byte>.Empty, out _, out byte[] allocated); Debug.Assert(ret); return allocated; } internal static bool TryExportPkcs8KeyBlob( SafeNCryptKeyHandle keyHandle, ReadOnlySpan<char> password, int kdfCount, Span<byte> destination, out int bytesWritten) { return ExportPkcs8KeyBlob( false, keyHandle, password, kdfCount, destination, out bytesWritten, out _); } // The Windows APIs for OID strings are ASCII-only private static readonly byte[] s_pkcs12TripleDesOidBytes = System.Text.Encoding.ASCII.GetBytes("1.2.840.113549.1.12.1.3\0"); internal static unsafe bool ExportPkcs8KeyBlob( bool allocate, SafeNCryptKeyHandle keyHandle, ReadOnlySpan<char> password, int kdfCount, Span<byte> destination, out int bytesWritten, out byte[] allocated) { using (SafeUnicodeStringHandle stringHandle = new SafeUnicodeStringHandle(password)) { fixed (byte* oidPtr = s_pkcs12TripleDesOidBytes) { Interop.NCrypt.NCryptBuffer* buffers = stackalloc Interop.NCrypt.NCryptBuffer[3]; Interop.NCrypt.PBE_PARAMS pbeParams = new Interop.NCrypt.PBE_PARAMS(); Span<byte> salt = new Span<byte>(pbeParams.rgbSalt, Interop.NCrypt.PBE_PARAMS.RgbSaltSize); RandomNumberGenerator.Fill(salt); pbeParams.Params.cbSalt = salt.Length; pbeParams.Params.iIterations = kdfCount; buffers[0] = new Interop.NCrypt.NCryptBuffer { BufferType = Interop.NCrypt.BufferType.PkcsSecret, cbBuffer = checked(2 * (password.Length + 1)), pvBuffer = stringHandle.DangerousGetHandle(), }; if (buffers[0].pvBuffer == IntPtr.Zero) { buffers[0].cbBuffer = 0; } buffers[1] = new Interop.NCrypt.NCryptBuffer { BufferType = Interop.NCrypt.BufferType.PkcsAlgOid, cbBuffer = s_pkcs12TripleDesOidBytes.Length, pvBuffer = (IntPtr)oidPtr, }; buffers[2] = new Interop.NCrypt.NCryptBuffer { BufferType = Interop.NCrypt.BufferType.PkcsAlgParam, cbBuffer = sizeof(Interop.NCrypt.PBE_PARAMS), pvBuffer = (IntPtr)(&pbeParams), }; Interop.NCrypt.NCryptBufferDesc desc = new Interop.NCrypt.NCryptBufferDesc { cBuffers = 3, pBuffers = (IntPtr)buffers, ulVersion = 0, }; Span<byte> empty = default; ErrorCode errorCode = Interop.NCrypt.NCryptExportKey( keyHandle, IntPtr.Zero, Interop.NCrypt.NCRYPT_PKCS8_PRIVATE_KEY_BLOB, ref desc, ref MemoryMarshal.GetReference(empty), 0, out int numBytesNeeded, 0); if (errorCode != ErrorCode.ERROR_SUCCESS) { throw errorCode.ToCryptographicException(); } allocated = null; if (allocate) { allocated = new byte[numBytesNeeded]; destination = allocated; } else if (numBytesNeeded > destination.Length) { bytesWritten = 0; return false; } errorCode = Interop.NCrypt.NCryptExportKey( keyHandle, IntPtr.Zero, Interop.NCrypt.NCRYPT_PKCS8_PRIVATE_KEY_BLOB, ref desc, ref MemoryMarshal.GetReference(destination), destination.Length, out numBytesNeeded, 0); if (errorCode != ErrorCode.ERROR_SUCCESS) { throw errorCode.ToCryptographicException(); } if (allocate && numBytesNeeded != destination.Length) { byte[] trimmed = new byte[numBytesNeeded]; destination.Slice(0, numBytesNeeded).CopyTo(trimmed); CryptographicOperations.ZeroMemory(allocated.AsSpan(0, numBytesNeeded)); allocated = trimmed; } bytesWritten = numBytesNeeded; return true; } } } internal static SafeNCryptKeyHandle GenerateNewExportableKey(string algorithm, int keySize) { // Despite the function being create "persisted" key, since we pass a null name it's // actually ephemeral. SafeNCryptKeyHandle keyHandle; ErrorCode errorCode = Interop.NCrypt.NCryptCreatePersistedKey( s_microsoftSoftwareProviderHandle, out keyHandle, algorithm, null, 0, CngKeyCreationOptions.None); if (errorCode != ErrorCode.ERROR_SUCCESS) { throw errorCode.ToCryptographicException(); } Debug.Assert(!keyHandle.IsInvalid); SetExportable(keyHandle); SetKeyLength(keyHandle, keySize); errorCode = Interop.NCrypt.NCryptFinalizeKey(keyHandle, 0); if (errorCode != ErrorCode.ERROR_SUCCESS) { throw errorCode.ToCryptographicException(); } return keyHandle; } internal static SafeNCryptKeyHandle GenerateNewExportableKey(string algorithm, string curveName) { // Despite the function being create "persisted" key, since we pass a null name it's // actually ephemeral. SafeNCryptKeyHandle keyHandle; ErrorCode errorCode = Interop.NCrypt.NCryptCreatePersistedKey( s_microsoftSoftwareProviderHandle, out keyHandle, algorithm, null, 0, CngKeyCreationOptions.None); if (errorCode != ErrorCode.ERROR_SUCCESS) { throw errorCode.ToCryptographicException(); } Debug.Assert(!keyHandle.IsInvalid); SetExportable(keyHandle); SetCurveName(keyHandle, curveName); errorCode = Interop.NCrypt.NCryptFinalizeKey(keyHandle, 0); if (errorCode != ErrorCode.ERROR_SUCCESS) { throw errorCode.ToCryptographicException(); } return keyHandle; } internal static SafeNCryptKeyHandle GenerateNewExportableKey(string algorithm, ref ECCurve explicitCurve) { // Despite the function being create "persisted" key, since we pass a null name it's // actually ephemeral. SafeNCryptKeyHandle keyHandle; ErrorCode errorCode = Interop.NCrypt.NCryptCreatePersistedKey( s_microsoftSoftwareProviderHandle, out keyHandle, algorithm, null, 0, CngKeyCreationOptions.None); if (errorCode != ErrorCode.ERROR_SUCCESS) { throw errorCode.ToCryptographicException(); } Debug.Assert(!keyHandle.IsInvalid); SetExportable(keyHandle); byte[] parametersBlob = ECCng.GetPrimeCurveParameterBlob(ref explicitCurve); SetProperty(keyHandle, KeyPropertyName.ECCParameters, parametersBlob); errorCode = Interop.NCrypt.NCryptFinalizeKey(keyHandle, 0); if (errorCode != ErrorCode.ERROR_SUCCESS) { throw errorCode.ToCryptographicException(); } return keyHandle; } private static void SetExportable(SafeNCryptKeyHandle keyHandle) { Debug.Assert(!keyHandle.IsInvalid); CngExportPolicies exportPolicy = CngExportPolicies.AllowPlaintextExport; unsafe { ErrorCode errorCode = Interop.NCrypt.NCryptSetProperty( keyHandle, KeyPropertyName.ExportPolicy, &exportPolicy, sizeof(CngExportPolicies), CngPropertyOptions.Persist); if (errorCode != ErrorCode.ERROR_SUCCESS) { throw errorCode.ToCryptographicException(); } } } private static void SetKeyLength(SafeNCryptKeyHandle keyHandle, int keySize) { Debug.Assert(!keyHandle.IsInvalid); unsafe { ErrorCode errorCode = Interop.NCrypt.NCryptSetProperty( keyHandle, KeyPropertyName.Length, &keySize, sizeof(int), CngPropertyOptions.Persist); if (errorCode != ErrorCode.ERROR_SUCCESS) { throw errorCode.ToCryptographicException(); } } } internal static unsafe int GetKeyLength(SafeNCryptKeyHandle keyHandle) { Debug.Assert(!keyHandle.IsInvalid); int keySize = 0; // Attempt to use PublicKeyLength first as it returns the correct value for ECC keys ErrorCode errorCode = Interop.NCrypt.NCryptGetIntProperty( keyHandle, KeyPropertyName.PublicKeyLength, ref keySize); if (errorCode != ErrorCode.ERROR_SUCCESS) { // Fall back to Length (< Windows 10) errorCode = Interop.NCrypt.NCryptGetIntProperty( keyHandle, KeyPropertyName.Length, ref keySize); } if (errorCode != ErrorCode.ERROR_SUCCESS) { throw errorCode.ToCryptographicException(); } return keySize; } private static SafeNCryptProviderHandle OpenNCryptProvider(string providerName) { SafeNCryptProviderHandle providerHandle; ErrorCode errorCode = Interop.NCrypt.NCryptOpenStorageProvider(out providerHandle, providerName, 0); if (errorCode != ErrorCode.ERROR_SUCCESS) { throw errorCode.ToCryptographicException(); } Debug.Assert(!providerHandle.IsInvalid); return providerHandle; } /// <summary> /// Returns a CNG key property. /// </summary> /// <returns> /// null - if property not defined on key. /// throws - for any other type of error. /// </returns> private static byte[] GetProperty(SafeNCryptHandle ncryptHandle, string propertyName, CngPropertyOptions options) { Debug.Assert(!ncryptHandle.IsInvalid); unsafe { int numBytesNeeded; ErrorCode errorCode = Interop.NCrypt.NCryptGetProperty(ncryptHandle, propertyName, null, 0, out numBytesNeeded, options); if (errorCode == ErrorCode.NTE_NOT_FOUND) return null; if (errorCode != ErrorCode.ERROR_SUCCESS) throw errorCode.ToCryptographicException(); byte[] propertyValue = new byte[numBytesNeeded]; fixed (byte* pPropertyValue = propertyValue) { errorCode = Interop.NCrypt.NCryptGetProperty(ncryptHandle, propertyName, pPropertyValue, propertyValue.Length, out numBytesNeeded, options); } if (errorCode == ErrorCode.NTE_NOT_FOUND) return null; if (errorCode != ErrorCode.ERROR_SUCCESS) throw errorCode.ToCryptographicException(); Array.Resize(ref propertyValue, numBytesNeeded); return propertyValue; } } /// <summary> /// Retrieve a well-known CNG string property. (Note: desktop compat: this helper likes to return special values rather than throw exceptions for missing /// or ill-formatted property values. Only use it for well-known properties that are unlikely to be ill-formatted.) /// </summary> internal static string GetPropertyAsString(SafeNCryptHandle ncryptHandle, string propertyName, CngPropertyOptions options) { Debug.Assert(!ncryptHandle.IsInvalid); byte[] value = GetProperty(ncryptHandle, propertyName, options); if (value == null) return null; // Desktop compat: return null if key not present. if (value.Length == 0) return string.Empty; // Desktop compat: return empty if property value is 0-length. unsafe { fixed (byte* pValue = &value[0]) { string valueAsString = Marshal.PtrToStringUni((IntPtr)pValue); return valueAsString; } } } internal static string GetCurveName(SafeNCryptHandle ncryptHandle) { Debug.Assert(!ncryptHandle.IsInvalid); return GetPropertyAsString(ncryptHandle, KeyPropertyName.ECCCurveName, CngPropertyOptions.None); } internal static void SetCurveName(SafeNCryptHandle keyHandle, string curveName) { unsafe { byte[] curveNameBytes = new byte[(curveName.Length + 1) * sizeof(char)]; // +1 to add trailing null System.Text.Encoding.Unicode.GetBytes(curveName, 0, curveName.Length, curveNameBytes, 0); SetProperty(keyHandle, KeyPropertyName.ECCCurveName, curveNameBytes); } } private static void SetProperty(SafeNCryptHandle ncryptHandle, string propertyName, byte[] value) { Debug.Assert(!ncryptHandle.IsInvalid); unsafe { fixed (byte* pBlob = value) { ErrorCode errorCode = Interop.NCrypt.NCryptSetProperty( ncryptHandle, propertyName, pBlob, value.Length, CngPropertyOptions.None); if (errorCode != ErrorCode.ERROR_SUCCESS) { throw errorCode.ToCryptographicException(); } } } } } // Limited version of CngExportPolicies from the Cng contract. [Flags] internal enum CngPropertyOptions : int { None = 0, Persist = unchecked((int)0x80000000), //NCRYPT_PERSIST_FLAG (The property should be persisted.) } // Limited version of CngKeyCreationOptions from the Cng contract. [Flags] internal enum CngKeyCreationOptions : int { None = 0x00000000, } // Limited version of CngKeyOpenOptions from the Cng contract. [Flags] internal enum CngKeyOpenOptions : int { None = 0x00000000, } // Limited version of CngExportPolicies from the Cng contract. [Flags] internal enum CngExportPolicies : int { None = 0x00000000, AllowPlaintextExport = 0x00000002, // NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG } } // Internal, lightweight versions of the SafeNCryptHandle types which are public in CNG. namespace Microsoft.Win32.SafeHandles { internal class SafeNCryptHandle : SafeHandle { public SafeNCryptHandle() : base(IntPtr.Zero, ownsHandle: true) { } protected override bool ReleaseHandle() { ErrorCode errorCode = Interop.NCrypt.NCryptFreeObject(handle); bool success = (errorCode == ErrorCode.ERROR_SUCCESS); Debug.Assert(success); handle = IntPtr.Zero; return success; } public override bool IsInvalid { get { return handle == IntPtr.Zero; } } } internal class SafeNCryptKeyHandle : SafeNCryptHandle { } internal class SafeNCryptProviderHandle : SafeNCryptHandle { } internal class SafeNCryptSecretHandle : SafeNCryptHandle { } internal class DuplicateSafeNCryptKeyHandle : SafeNCryptKeyHandle { public DuplicateSafeNCryptKeyHandle(SafeNCryptKeyHandle original) : base() { bool success = false; original.DangerousAddRef(ref success); if (!success) throw new CryptographicException(); // DangerousAddRef() never actually sets success to false, so no need to expend a resource string here. SetHandle(original.DangerousGetHandle()); _original = original; } protected override bool ReleaseHandle() { _original.DangerousRelease(); SetHandle(IntPtr.Zero); return true; } private readonly SafeNCryptKeyHandle _original; } }
using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; namespace Igor { public class EntityBox<EntityType> : InspectableObject where EntityType : LinkedEntity<EntityType>, new() { public GraphWindow<EntityType> Owner; protected LinkedEntity<EntityType> WrappedInstance; protected string BoxTitle; protected List<Anchor<EntityType>> Inputs = new List<Anchor<EntityType>>(); protected List<Anchor<EntityType>> Outputs = new List<Anchor<EntityType>>(); protected Vector2 Position; protected Vector2 Size; protected bool bDirty = true; protected int AnchorBoxSize = 10; protected int AnchorLabelGap = 7; protected int AnchorSubtextGap = 3; protected int InputOutputGap = 5; protected int WindowBorder = 5; protected int BlurbVerticalOffset = 5; protected bool bHoveringAnchor = false; protected bool bReadOnlyTitle = false; protected bool bReadOnlyInputList = false; protected bool bReadOnlyOutputList = false; protected Color SelectionColor = Color.red; protected float SelectionWidth = 2.0f; protected float SelectionOffset = 1.0f; protected Texture2D OriginalBackgroundTexture = null; protected Texture2D ErrorBackgroundTexture = null; protected Texture2D ActiveOriginalBackgroundTexture = null; protected Texture2D ActiveErrorBackgroundTexture = null; protected bool bErrorInNode = false; public EntityBox(GraphWindow<EntityType> InOwner, LinkedEntity<EntityType> InWrappedInstance) { Owner = InOwner; WrappedInstance = InWrappedInstance; UpdateAnchors(); } public virtual void InitializeNewBox() { } public override object GetInspectorInstance() { return WrappedInstance; } public override string GetTypeName() { return "LinkedEntity"; } public virtual void ConditionalInitBackgroundTextures() { if(OriginalBackgroundTexture == null) { OriginalBackgroundTexture = CreateBackgroundTexture(GUI.skin.window.normal.background, Color.white, 0.0f); ActiveOriginalBackgroundTexture = CreateBackgroundTexture(GUI.skin.window.onNormal.background, Color.white, 0.0f); CreateErrorBackgroundTextures(); } } public virtual void CreateErrorBackgroundTextures() { ErrorBackgroundTexture = CreateBackgroundTexture(GUI.skin.window.normal.background, Color.red, 0.3f); ActiveErrorBackgroundTexture = CreateBackgroundTexture(GUI.skin.window.onNormal.background, Color.red, 0.3f); } public virtual Texture2D CreateBackgroundTexture(Texture2D Original, Color ColorToBlend, float ColorOpacity) { Texture2D BackgroundTex = Original; if(Original != null) { RenderTexture TempRenderTexture = new RenderTexture(Original.width, Original.height, 32); Graphics.Blit(Original, TempRenderTexture); RenderTexture.active = TempRenderTexture; BackgroundTex = new Texture2D(Original.width, Original.height); BackgroundTex.ReadPixels(new Rect(0.0f, 0.0f, Original.width, Original.height), 0, 0); RenderTexture.active = null; for(int CurrentX = 0; CurrentX < Original.width; ++CurrentX) { for(int CurrentY = 0; CurrentY < Original.height; ++CurrentY) { Color OriginalColor = BackgroundTex.GetPixel(CurrentX, CurrentY); Color NewColor = new Color((ColorToBlend.r*ColorOpacity) + (OriginalColor.r*(1.0f-ColorOpacity)), (ColorToBlend.g*ColorOpacity) + (OriginalColor.g*(1.0f-ColorOpacity)), (ColorToBlend.b*ColorOpacity) + (OriginalColor.b*(1.0f-ColorOpacity)), OriginalColor.a); BackgroundTex.SetPixel(CurrentX, CurrentY, NewColor); } } BackgroundTex.Apply(); } return BackgroundTex; } public virtual GUIStyle GetWindowStyle() { ConditionalInitBackgroundTextures(); GUIStyle WindowStyle = new GUIStyle(GUI.skin.window); if(bErrorInNode) { WindowStyle.normal.background = ErrorBackgroundTexture; WindowStyle.onNormal.background = ActiveErrorBackgroundTexture; } else { WindowStyle.normal.background = OriginalBackgroundTexture; WindowStyle.onNormal.background = ActiveOriginalBackgroundTexture; } return WindowStyle; } public virtual int GetBoxID(int BaseIndex) { return (BaseIndex*2) + (bErrorInNode ? 1 : 0); } public virtual bool IsHoveringAnyAnchors() { return bHoveringAnchor; } public virtual bool IsInsideDragArea(Rect DragArea) { return VisualScriptingDrawing.RectOverlapsRect(DragArea, new Rect(Position.x, Position.y, Size.x, Size.y)); } public virtual void InspectorGUIList<ListType>(string ListName, string EntryPrefix, ref List<ListType> CurrentList, bool bReadOnly = false) where ListType : EntityLink<EntityType>, new() { if(!InspectorArrayExpanded.ContainsKey(ListName)) { InspectorArrayExpanded.Add(ListName, false); } bool bArrayExpanded = InspectorArrayExpanded[ListName]; bArrayExpanded = EditorGUILayout.Foldout(bArrayExpanded, ListName); InspectorArrayExpanded[ListName] = bArrayExpanded; if(bArrayExpanded) { string PreviousString = ""; EditorGUI.indentLevel += 1; int NewArrayCount = CurrentList.Count; int OldListCount = NewArrayCount; bool bCountActuallyChanged = false; if(bReadOnly) { EditorGUILayout.LabelField("Count", CurrentList.Count.ToString()); } else { bCountActuallyChanged = InspectorGUIIntWaitForEnter(ListName + "Count", "Count", OldListCount, out NewArrayCount); } if(bCountActuallyChanged && NewArrayCount != CurrentList.Count) { bInspectorHasChangedProperty = true; if(NewArrayCount > CurrentList.Count) { for(int CurrentElement = CurrentList.Count; CurrentElement < NewArrayCount; ++CurrentElement) { CurrentList.Add(new ListType()); } } else { for(int CurrentElement = CurrentList.Count; CurrentElement > NewArrayCount; --CurrentElement) { CurrentList.RemoveAt(CurrentElement-1); } } } int SmallestSize = OldListCount > NewArrayCount ? NewArrayCount : OldListCount; for(int CurrentElement = 0; CurrentElement < SmallestSize; ++CurrentElement) { if(CurrentList[CurrentElement] != null) { PreviousString = CurrentList[CurrentElement].Name; if(bReadOnly) { EditorGUILayout.LabelField(EntryPrefix + " " + CurrentElement, PreviousString); } else { CurrentList[CurrentElement].Name = EditorGUILayout.TextField(EntryPrefix + " " + CurrentElement, PreviousString); } if(CurrentList[CurrentElement].Name != PreviousString) { bInspectorHasChangedProperty = true; } } else { if(bReadOnly) { EditorGUILayout.LabelField(EntryPrefix + " " + CurrentElement, ""); } else { CurrentList[CurrentElement].Name = EditorGUILayout.TextField(EntryPrefix + " " + CurrentElement, ""); } if(CurrentList[CurrentElement].Name != "") { bInspectorHasChangedProperty = true; } } } EditorGUI.indentLevel -= 1; } } public virtual void InspectorGUIStringList(string ListName, string EntryPrefix, ref List<string> CurrentList, bool bReadOnly = false) { if(!InspectorArrayExpanded.ContainsKey(ListName)) { InspectorArrayExpanded.Add(ListName, false); } bool bArrayExpanded = InspectorArrayExpanded[ListName]; bArrayExpanded = EditorGUILayout.Foldout(bArrayExpanded, ListName); InspectorArrayExpanded[ListName] = bArrayExpanded; if(bArrayExpanded) { string PreviousString = ""; EditorGUI.indentLevel += 1; int NewArrayCount = CurrentList.Count; int OldListCount = NewArrayCount; bool bCountActuallyChanged = false; if(bReadOnly) { EditorGUILayout.LabelField("Count", CurrentList.Count.ToString()); } else { bCountActuallyChanged = InspectorGUIIntWaitForEnter(ListName + "Count", "Count", OldListCount, out NewArrayCount); } if(bCountActuallyChanged && NewArrayCount != CurrentList.Count) { bInspectorHasChangedProperty = true; if(NewArrayCount > CurrentList.Count) { for(int CurrentElement = CurrentList.Count; CurrentElement < NewArrayCount; ++CurrentElement) { CurrentList.Add(""); } } else { for(int CurrentElement = CurrentList.Count; CurrentElement > NewArrayCount; --CurrentElement) { CurrentList.RemoveAt(CurrentElement-1); } } } int SmallestSize = OldListCount > NewArrayCount ? NewArrayCount : OldListCount; for(int CurrentElement = 0; CurrentElement < SmallestSize; ++CurrentElement) { if(CurrentList[CurrentElement] != null) { PreviousString = CurrentList[CurrentElement]; if(bReadOnly) { EditorGUILayout.LabelField(EntryPrefix + " " + CurrentElement, PreviousString); } else { CurrentList[CurrentElement] = EditorGUILayout.TextField(EntryPrefix + " " + CurrentElement, PreviousString); } if(CurrentList[CurrentElement] != PreviousString) { bInspectorHasChangedProperty = true; } } else { if(bReadOnly) { EditorGUILayout.LabelField(EntryPrefix + " " + CurrentElement, ""); } else { CurrentList[CurrentElement] = EditorGUILayout.TextField(EntryPrefix + " " + CurrentElement, ""); } if(CurrentList[CurrentElement] != "") { bInspectorHasChangedProperty = true; } } } EditorGUI.indentLevel -= 1; } } public virtual string GetClassTypeSaveString() { return "Save LinkedEntity"; } public override void EntityDrawInspectorWidgets(object Instance) { base.EntityDrawInspectorWidgets(Instance); EntityType EntityInst = (EntityType)Instance; OnInspectorGUIDrawSaveButton(GetClassTypeSaveString()); InspectorGUIString("Title", ref EntityInst.Title, bReadOnlyTitle); InspectorGUIListEmbedded<EntityLink<EntityType>>("Inputs", "Link", ref WrappedInstance.InputEvents, InspectEntityLink, bReadOnlyInputList, bReadOnlyInputList); InspectorGUIListEmbedded<EntityLink<EntityType>>("Outputs", "Link", ref WrappedInstance.OutputEvents, InspectEntityLink, bReadOnlyOutputList, bReadOnlyOutputList); } public virtual bool InspectEntityLink(ref EntityLink<EntityType> CurrentLink) { InspectorGUIString("Name", ref CurrentLink.Name); InspectorGUIOrderedListEmbedded<EntityLink<EntityType>>("Linked Elements", "Link", ref CurrentLink.LinkedEntities, InspectEntityPerLinkDetails); return false; } public virtual bool InspectEntityPerLinkDetails(ref EntityLink<EntityType> CurrentLink) { InspectorGUIString("Name", ref CurrentLink.Name, true); return false; } public override void EntityPostDrawInspectorWidgets(object Instance) { base.EntityPostDrawInspectorWidgets(Instance); if(bInspectorHasChangedProperty) { UpdateAnchors(); Owner.Repaint(); } } public virtual bool IsDirty() { return bDirty; } public virtual void CleanedUp() { bDirty = false; } public virtual string GetBoxTitle() { return BoxTitle; } public virtual string GetBoxKey() { return WrappedInstance.GetFilename(); } public virtual void MoveBoxTo(Vector2 NewPosition) { Position = NewPosition; } public virtual void HandleDrag(Rect NewRect) { if(Position.x != NewRect.x || Position.y != NewRect.y) { Position.x = NewRect.x; Position.y = NewRect.y; bDirty = true; } } public virtual void HandleDoubleClick() { } public virtual void CanConnectNodes(Anchor<EntityType> InputNode, Anchor<EntityType> OutputNode) { } public virtual void UpdateBoxBounds() { if(Size == Vector2.zero) { Size = new Vector2(100.0f, 100.0f); } } public virtual void DrawBox() { DrawAnchors(new Vector2(0.0f, 20.0f)); if(!bHoveringAnchor) { GUI.DragWindow(); } } public virtual void DrawSelectedOutline() { Rect BoxBounds = GetBoxBounds(); // Top line VisualScriptingDrawing.DrawLine(new Vector2(-SelectionOffset - (BoxBounds.width * 0.5f), -SelectionOffset), new Vector2(SelectionOffset + (BoxBounds.width * 0.5f), -SelectionOffset), SelectionColor, SelectionWidth, false); // Right line VisualScriptingDrawing.DrawLine(new Vector2(SelectionOffset + BoxBounds.width, -SelectionOffset), new Vector2(SelectionOffset + BoxBounds.width, SelectionOffset + BoxBounds.height), SelectionColor, SelectionWidth, false); // Bottom line VisualScriptingDrawing.DrawLine(new Vector2(-SelectionOffset - (BoxBounds.width * 0.5f), SelectionOffset + BoxBounds.height), new Vector2(SelectionOffset + (BoxBounds.width * 0.5f), SelectionOffset + BoxBounds.height), SelectionColor, SelectionWidth, false); // Left line VisualScriptingDrawing.DrawLine(new Vector2(-SelectionOffset, -SelectionOffset), new Vector2(-SelectionOffset, SelectionOffset + BoxBounds.height), SelectionColor, SelectionWidth, false); } public enum TypeOfAnchor { Anchor_Normal } public virtual TypeOfAnchor GetAnchorTypeForIndex(bool bIsInputList, int Index) { return TypeOfAnchor.Anchor_Normal; } public virtual void DrawAnchorContent(Anchor<EntityType> CurrentAnchor, int CurrentAnchorIndex, ref Vector2 Origin, ref float WidestLabel, ref Rect WholeAnchorRect, bool bIsHovered, bool bJustCalculateSize, TypeOfAnchor AnchorType, bool bLeftAlign) { string LabelTitle = CurrentAnchor.GetLabelDescription(); Vector2 LabelSize = GetLabelSize(LabelTitle); Rect LabelRect = new Rect(Origin.x + WidestLabel - AnchorBoxSize - LabelSize.x, Origin.y, LabelSize.x, LabelSize.y); WholeAnchorRect = new Rect(LabelRect.x, LabelRect.y, LabelSize.x + (2*AnchorBoxSize), LabelSize.y); if(bLeftAlign) { LabelRect = new Rect(Origin.x + AnchorBoxSize, Origin.y, LabelSize.x, LabelSize.y); WholeAnchorRect = new Rect(Origin.x, Origin.y, LabelSize.x + (2*AnchorBoxSize), LabelSize.y); } if(!bJustCalculateSize) { if(bIsHovered) { GUI.color = Color.red; Owner.HandleHoveredAnchor(CurrentAnchor); } else { GUI.color = Color.white; } GUI.Label(LabelRect, LabelTitle); GUI.color = Color.white; Origin.y += WholeAnchorRect.height; } WidestLabel = WholeAnchorRect.width > WidestLabel ? WholeAnchorRect.width : WidestLabel; } public virtual void DrawAnchor(Anchor<EntityType> CurrentAnchor, int CurrentAnchorIndex, ref Vector2 Origin, ref bool bAnyAnchorsHovered, ref float WidestAnchor, bool bJustCalculateSize, TypeOfAnchor AnchorType, bool bLeftAlign) { Vector2 WindowOffset = Owner.GetWindowOffset(); Rect WholeAnchorRect = new Rect(0.0f, 0.0f, 0.0f, 0.0f); bool bIsHovered = false; DrawAnchorContent(CurrentAnchor, CurrentAnchorIndex, ref Origin, ref WidestAnchor, ref WholeAnchorRect, bIsHovered, true, AnchorType, bLeftAlign); if(!bJustCalculateSize) { bIsHovered = WholeAnchorRect.Contains(InputState.GetLocalMousePosition(Owner, new Vector2(Position.x - Owner.GetWindowOffset().x, Position.y+10.0f - Owner.GetWindowOffset().y))); if(bIsHovered) { bAnyAnchorsHovered = true; } DrawAnchorContent(CurrentAnchor, CurrentAnchorIndex, ref Origin, ref WidestAnchor, ref WholeAnchorRect, bIsHovered, false, AnchorType, bLeftAlign); CurrentAnchor.LastRect = new Rect(Position.x + WholeAnchorRect.x - WindowOffset.x, Position.y + WholeAnchorRect.y - WindowOffset.y + 5.0f, WholeAnchorRect.width, WholeAnchorRect.height); Origin.y += AnchorLabelGap; } } public virtual void DrawAnchors(Vector2 Origin) { float InputMinWidth = 0.0f; float OutputMinWidth = 0.0f; DrawAnchors(ref Origin, ref InputMinWidth, ref OutputMinWidth, false); } public virtual void DrawAnchors(ref Vector2 Origin, ref float InputMinWidth, ref float OutputMinWidth, bool bJustCalculateSize, float MinHeight = 0.0f) { Vector2 OriginalOrigin = Origin; float TallestColumn = 0.0f; bool bAnyAnchorsHovered = false; int CurrentAnchorIndex = 0; Vector2 BlurbSize = DrawBlurb(ref Origin, bJustCalculateSize); for(CurrentAnchorIndex = 0; CurrentAnchorIndex < Inputs.Count; ++CurrentAnchorIndex) { DrawAnchor(Inputs[CurrentAnchorIndex], CurrentAnchorIndex, ref Origin, ref bAnyAnchorsHovered, ref InputMinWidth, bJustCalculateSize, GetAnchorTypeForIndex(true, CurrentAnchorIndex), true); } TallestColumn = Origin.y; if(!bJustCalculateSize) { Origin = new Vector2(InputMinWidth + InputOutputGap, OriginalOrigin.y + BlurbSize.y); } CurrentAnchorIndex = 0; for(CurrentAnchorIndex = 0; CurrentAnchorIndex < Outputs.Count; ++CurrentAnchorIndex) { DrawAnchor(Outputs[CurrentAnchorIndex], CurrentAnchorIndex, ref Origin, ref bAnyAnchorsHovered, ref OutputMinWidth, true, GetAnchorTypeForIndex(false, CurrentAnchorIndex), false); } if(!bJustCalculateSize) { CurrentAnchorIndex = 0; for(CurrentAnchorIndex = 0; CurrentAnchorIndex < Outputs.Count; ++CurrentAnchorIndex) { DrawAnchor(Outputs[CurrentAnchorIndex], CurrentAnchorIndex, ref Origin, ref bAnyAnchorsHovered, ref OutputMinWidth, false, GetAnchorTypeForIndex(false, CurrentAnchorIndex), false); } } TallestColumn = TallestColumn > Origin.y ? TallestColumn : Origin.y; Vector2 NewSize = new Vector2(InputMinWidth + InputOutputGap + OutputMinWidth + (2*WindowBorder), TallestColumn + (2*WindowBorder)); Vector2 TitleLabelSize = Vector2.zero; if(WrappedInstance != null) { TitleLabelSize = GetLabelSize(WrappedInstance.Title); } float MinWidth = TitleLabelSize.x > 50.0f ? TitleLabelSize.x : 50.0f; if(NewSize.x < MinWidth) { NewSize.x = MinWidth; } if(NewSize.x < BlurbSize.x) { NewSize.x = BlurbSize.x; } MinHeight = MinHeight > 50.0f ? MinHeight : 50.0f; if(NewSize.y < MinHeight) { NewSize.y = MinHeight; } if(NewSize != Size) { Size = NewSize; bDirty = true; } bHoveringAnchor = bAnyAnchorsHovered; } public virtual void DrawAnchorBox(Vector2 Origin, bool bHovering) { } public virtual string GetBlurb() { return ""; } public virtual string MakeMultiline(string OriginalText, int CharacterMax) { string NewText = OriginalText; if(NewText != null) { for(int CurrentChar = CharacterMax; CurrentChar < OriginalText.Length && CurrentChar > 0; ) { if(NewText[CurrentChar] == ' ') { NewText = NewText.Substring(0, CurrentChar) + "\n" + NewText.Substring(CurrentChar+1); CurrentChar += CharacterMax; } else { --CurrentChar; } } } return NewText; } public virtual Vector2 DrawBlurb(ref Vector2 Origin, bool bJustCalculateSize) { string BlurbString = MakeMultiline(GetBlurb(), 30); Vector2 BlurbSize = Vector2.zero; if(BlurbString != "") { BlurbSize = GetLabelSize(BlurbString); Rect BlurbRect = new Rect(Origin.x, Origin.y, BlurbSize.x, BlurbSize.y); BlurbSize.y += BlurbVerticalOffset; if(!bJustCalculateSize) { Origin.y += BlurbSize.y; GUI.Label(BlurbRect, BlurbString); } } return BlurbSize; } public virtual Vector2 GetLabelSize(string Label) { GUIContent TempLabel = new GUIContent(Label); return GUI.skin.label.CalcSize(TempLabel); } public virtual Rect GetBoxBounds() { return new Rect(Position.x, Position.y, Size.x, Size.y); } public virtual Vector2 GetPosition() { return Position; } public virtual void SetPosition(Vector2 NewPosition) { Position = NewPosition; } public virtual bool HandleContextMenu(GenericMenu GenericContextMenu) { GenericContextMenu.AddItem(new GUIContent("Duplicate " + GetTypeName()), false, DuplicateBox); GenericContextMenu.AddItem(new GUIContent("Remove " + GetTypeName()), false, RemoveBox); GenericContextMenu.AddSeparator(""); GenericContextMenu.AddItem(new GUIContent("Create save at node"), false, CreateSaveAtNode); GenericContextMenu.AddItem(new GUIContent("Play from node"), false, PlayFromNode); GenericContextMenu.AddSeparator(""); return true; } public virtual void CreateSaveAtNode() { /* EntityID CurrentNodeID = WrappedInstance.GenerateEntityIDForEvent(); GameSaveManager.SetCurrentSaveSlot(0); GameSave FirstSave = GameSaveManager.GetActiveSave(); FirstSave.Checkpoints = new List<GameSave.CheckpointData>(); GameSave.CheckpointData NewCheckpoint = new GameSave.CheckpointData(); NewCheckpoint.LastEntity = CurrentNodeID; FirstSave.Checkpoints.Add(NewCheckpoint); GameSaveManager.SaveAllGameSaves();*/ } public virtual void PlayFromNode() { CreateSaveAtNode(); EditorApplication.isPlaying = true; } public virtual void DuplicateBox() { } public virtual void RemoveBox() { Owner.RemoveBox(this); RemoveEntity(); } public virtual void RemoveEntity() { } public virtual string GetAnchorText(EntityLink<EntityType> Link) { return Link.Name; } public virtual void UpdateAnchors() { if(WrappedInstance != null) { WrappedInstance.CreateStaticNodesIfNotPresent(); } List<Anchor<EntityType>> DeletedList = new List<Anchor<EntityType>>(); DeletedList.AddRange(Inputs); foreach(EntityLink<EntityType> InputLink in GetInputEvents()) { bool bHasAnchor = false; foreach(Anchor<EntityType> CurrentAnchor in Inputs) { if(CurrentAnchor.GetLabelText() == InputLink.Name) { bHasAnchor = true; DeletedList.Remove(CurrentAnchor); } } if(!bHasAnchor) { Anchor<EntityType> InputAnchor = new Anchor<EntityType>(InputLink.Name, GetAnchorText(InputLink), new Anchor<EntityType>.AnchorType(true), this); Inputs.Add(InputAnchor); } } foreach(Anchor<EntityType> DeletedItem in DeletedList) { DeletedItem.CleanupBeforeRemoval(); Owner.BreakAllConnectionsForAnchor(DeletedItem); Inputs.Remove(DeletedItem); } DeletedList.Clear(); DeletedList.AddRange(Outputs); foreach(EntityLink<EntityType> OutputLink in GetOutputEvents()) { bool bHasAnchor = false; foreach(Anchor<EntityType> CurrentAnchor in Outputs) { if(CurrentAnchor.GetLabelText() == OutputLink.Name) { bHasAnchor = true; DeletedList.Remove(CurrentAnchor); } } if(!bHasAnchor) { Anchor<EntityType> OutputAnchor = new Anchor<EntityType>(OutputLink.Name, GetAnchorText(OutputLink), new Anchor<EntityType>.AnchorType(false), this); Outputs.Add(OutputAnchor); } } foreach(Anchor<EntityType> DeletedItem in DeletedList) { DeletedItem.CleanupBeforeRemoval(); Owner.BreakAllConnectionsForAnchor(DeletedItem); Outputs.Remove(DeletedItem); } DeletedList.Clear(); } public virtual void OnConnectedAnchors(Anchor<EntityType> LocalAnchor, Anchor<EntityType> RemoteAnchor) { EntityBox<EntityType> RemoteBox = RemoteAnchor.Owner; string LocalAnchorName = ""; string RemoteAnchorName = ""; if(Inputs.Contains(LocalAnchor)) { LocalAnchorName = "Input"; } else { LocalAnchorName = "Output"; } LocalAnchorName += LocalAnchor.GetLabelText(); if(RemoteBox.Inputs.Contains(RemoteAnchor)) { RemoteAnchorName = "Input"; } else { RemoteAnchorName = "Output"; } RemoteAnchorName += RemoteAnchor.GetLabelText(); EntityLink<EntityType> LocalLink = GetLinkByName(LocalAnchorName); EntityLink<EntityType> RemoteLink = RemoteBox.GetLinkByName(RemoteAnchorName); if(LocalLink != null && RemoteLink != null) { LocalLink.EstablishLink(RemoteLink); } } public virtual void OnDisconnectedAnchors(Anchor<EntityType> LocalAnchor, Anchor<EntityType> RemoteAnchor) { EntityBox<EntityType> RemoteBox = RemoteAnchor.Owner; string LocalAnchorName = ""; string RemoteAnchorName = ""; if(Inputs.Contains(LocalAnchor)) { LocalAnchorName = "Input"; } else { LocalAnchorName = "Output"; } LocalAnchorName += LocalAnchor.GetLabelText(); if(RemoteBox.Inputs.Contains(RemoteAnchor)) { RemoteAnchorName = "Input"; } else { RemoteAnchorName = "Output"; } RemoteAnchorName += RemoteAnchor.GetLabelText(); EntityLink<EntityType> LocalLink = GetLinkByName(LocalAnchorName); EntityLink<EntityType> RemoteLink = RemoteBox.GetLinkByName(RemoteAnchorName); if(LocalLink != null && RemoteLink != null) { LocalLink.BreakLink(RemoteLink); } } public virtual EntityLink<EntityType> GetLinkByName(string AnchorName) { return WrappedInstance.GetLinkByName(AnchorName); } public override void OnInspectorGUIClickedSaveButton() { base.OnInspectorGUIClickedSaveButton(); if(WrappedInstance.GetFilename().Length == 0 && WrappedInstance.Title.Length > 0) { string UniqueName = GetUniqueFilename(WrappedInstance.Title); WrappedInstance.EditorSetFilename(UniqueName); } SaveEntities(); Owner.SerializeBoxMetadata(true); } public virtual string GetUniqueFilename(string OriginalFilename) { return OriginalFilename; } public virtual void SaveEntities() { } public virtual void CleanUpBeforeRemoval() { } public virtual List<EntityLink<EntityType>> GetInputEvents() { return WrappedInstance.InputEvents; } public virtual List<EntityLink<EntityType>> GetOutputEvents() { return WrappedInstance.OutputEvents; } public virtual void BuildConnectionsFromSourceData() { List<EntityLink<EntityType>> InputEvents = GetInputEvents(); foreach(EntityLink<EntityType> CurrentLink in InputEvents) { Anchor<EntityType> LocalAnchor = GetAnchor("Input" + CurrentLink.Name); if(LocalAnchor != null) { foreach(EntityLink<EntityType> CurrentRemoteLink in CurrentLink.LinkedEntities) { if(CurrentRemoteLink.GetOwner() != null && CurrentRemoteLink.GetOwner().OutputEvents.Contains(CurrentRemoteLink)) { EntityBox<EntityType> RemoteBox = Owner.GetEntityBoxForEntity(CurrentRemoteLink.GetOwner()); if(RemoteBox != null) { Anchor<EntityType> RemoteAnchor = RemoteBox.GetAnchor("Output" + CurrentRemoteLink.Name); if(RemoteAnchor != null) { Owner.ConnectInputToOutput(LocalAnchor, RemoteAnchor); } } } } } } } public virtual bool WrapsInstance(LinkedEntity<EntityType> InstToCheck) { return WrappedInstance.GetFilename() == InstToCheck.GetFilename(); } public Anchor<EntityType> GetAnchor(string LinkToMatch) { if(LinkToMatch.StartsWith("Input")) { string LinkName = LinkToMatch.Substring(5); foreach(Anchor<EntityType> CurrentAnchor in Inputs) { if(CurrentAnchor.GetLabelText() == LinkName) { return CurrentAnchor; } } } else if(LinkToMatch.StartsWith("Output")) { string LinkName = LinkToMatch.Substring(6); foreach(Anchor<EntityType> CurrentAnchor in Outputs) { if(CurrentAnchor.GetLabelText() == LinkName) { return CurrentAnchor; } } } return null; } public virtual List< Anchor<EntityType> > GetAllAnchors() { List< Anchor<EntityType> > FullList = new List< Anchor<EntityType> >(); FullList.AddRange(Inputs); FullList.AddRange(Outputs); return FullList; } public virtual void RunChecks(EditorTypeUtils.EntityTestType TestType) { bErrorInNode = false; switch(TestType) { case EditorTypeUtils.EntityTestType.FixOneWayLinks: FixOneWayLinks(); break; } } public virtual void FixOneWayLinks() { if(WrappedInstance == null) { Debug.LogError("Somehow we are running this check on objects that don't exist?"); return; } foreach(EntityLink<EntityType> CurrentConnector in WrappedInstance.InputEvents) { foreach(EntityLink<EntityType> RemoteConnector in CurrentConnector.LinkedEntities) { bool bFound = false; foreach(EntityLink<EntityType> RemoteRemoteConnector in RemoteConnector.LinkedEntities) { if(RemoteRemoteConnector.GetOwner() == CurrentConnector.GetOwner() && RemoteRemoteConnector.Name == CurrentConnector.Name) { bFound = true; break; } } if(!bFound) { bErrorInNode = true; } } } foreach(EntityLink<EntityType> CurrentConnector in WrappedInstance.OutputEvents) { foreach(EntityLink<EntityType> RemoteConnector in CurrentConnector.LinkedEntities) { bool bFound = false; foreach(EntityLink<EntityType> RemoteRemoteConnector in RemoteConnector.LinkedEntities) { if(RemoteRemoteConnector.GetOwner() == CurrentConnector.GetOwner() && RemoteRemoteConnector.Name == CurrentConnector.Name) { bFound = true; break; } } if(!bFound) { bErrorInNode = true; } } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Sandbox.Common; using Sandbox.Common.Components; using Sandbox.Common.ObjectBuilders; using Sandbox.Definitions; using Sandbox.Engine; using Sandbox.Game; using Sandbox.ModAPI; //using Sandbox.ModAPI.Ingame; using Sandbox.ModAPI.Interfaces; using VRageMath; using IMyCubeBlock = Sandbox.ModAPI.IMyCubeBlock; namespace BreachCharge { [MyEntityComponentDescriptor(typeof(MyObjectBuilder_Warhead))] class BreachCharge : MyGameLogicComponent { MyObjectBuilder_EntityBase m_objectBuilder; private string SubTypeNameLarge = "BreachCharge"; private bool _didInit = false; IMyCubeBlock block; public override void Close() { if (block == null) return; if (block.BlockDefinition.SubtypeName == SubTypeNameLarge) { if (_didInit == true) { //MyLogger.Default.WriteLine("Close was called"); block.OnMarkForClose -= OnMarkForClose; } } else { return; } } public override void Init(MyObjectBuilder_EntityBase objectBuilder) { base.Init(objectBuilder); NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME; m_objectBuilder = objectBuilder; //MyLogger.Default.ToScreen = true; //MyLogger.Default.WriteLine("Initting a warhead"); } public override void UpdateOnceBeforeFrame() { base.UpdateOnceBeforeFrame(); DoInit(); } void DoInit() { //MyLogger.Default.WriteLine("Got inside doinit"); if (_didInit) return; _didInit = true; if (Entity == null) { //MyLogger.Default.WriteLine("Block was null! bailin"); _didInit = false; return; } //MyLogger.Default.ToScreen = true; //MyLogger.Default.WriteLine("Initting a warhead"); block = (IMyCubeBlock)Entity; if (block.BlockDefinition.SubtypeName == SubTypeNameLarge) { //MyLogger.Default.WriteLine("Just Placed a breach charge"); block.OnMarkForClose += OnMarkForClose; } else { return; } } private void OnMarkForClose(IMyEntity myEntity) { if (MyAPIGateway.Players.Count == 0) return; if (Entity == null) { //MyLogger.Default.WriteLine("Bailin!"); return; } var position = Entity.GetPosition(); var range = 200.0; var sphere = new BoundingSphereD(position, range); var grids = MyAPIGateway.Entities.GetEntitiesInSphere(ref sphere).OfType<IMyCubeGrid>(); var affectedBlocks = new List<IMySlimBlock>(); foreach (var grid in grids) { //MyLogger.Default.WriteLine("Finding other breach charges"); grid.GetBlocks(affectedBlocks, x => x.FatBlock != null && x.FatBlock.BlockDefinition.SubtypeName==SubTypeNameLarge && x.FatBlock.GetIntersectionWithSphere(ref sphere)); } //MyLogger.Default.WriteLine("found"+affectedBlocks.Count+ " charges"); foreach (var blk in affectedBlocks) { //MyLogger.Default.WriteLine("detonating other charges"); if (blk != null) { var cube = (IMyTerminalBlock)blk.FatBlock; cube.GetActionWithName("Detonate").Apply(cube); } } } public override MyObjectBuilder_EntityBase GetObjectBuilder(bool copy = false) { return m_objectBuilder; } } [MySessionComponentDescriptor(MyUpdateOrder.NoUpdate)] public class LoggerSession : MySessionComponentBase { protected override void UnloadData() { base.UnloadData(); MyLogger.DefaultClose(); } } /// <summary> /// Borrowed and modified from official API sample mission mod. Thanks! /// </summary> class MyLogger { private System.IO.TextWriter m_writer; private int m_indent; private StringBuilder m_cache = new StringBuilder(); private bool _isFileOpen; private bool _isClosed; private string _fileName; public bool ToScreen { get; set; } private static MyLogger _sDefault; public static MyLogger Default { get { return _sDefault ?? (_sDefault = new MyLogger("DefaultLog.txt")); } } public static void DefaultClose() { if (_sDefault != null) _sDefault.Close(); } public MyLogger(string logFile) { _fileName = logFile; ReadyFile(); } private bool ReadyFile() { if (_isFileOpen) return true; if (MyAPIGateway.Utilities != null) { m_writer = MyAPIGateway.Utilities.WriteFileInLocalStorage(_fileName, typeof(MyLogger)); _isFileOpen = true; } return _isFileOpen; } public void IncreaseIndent() { m_indent++; } public void DecreaseIndent() { if (m_indent > 0) m_indent--; } public void WriteLine(string text) { if (ToScreen && MyAPIGateway.Utilities != null) { MyAPIGateway.Utilities.ShowMessage("Log", text); } if (_isClosed) return; if (!ReadyFile()) { m_cache.Append(text); return; } if (m_cache.Length > 0) m_writer.WriteLine(m_cache); m_cache.Clear(); m_cache.Append(DateTime.Now.ToString("[HH:mm:ss] ")); for (int i = 0; i < m_indent; i++) m_cache.Append("\t"); m_writer.WriteLine(m_cache.Append(text)); m_writer.Flush(); m_cache.Clear(); } public void Write(string text) { if (ToScreen) { MyAPIGateway.Utilities.ShowMessage("Log", text); } m_cache.Append(text); } internal void Close() { _isClosed = true; if (m_cache.Length > 0) m_writer.WriteLine(m_cache); m_writer.Flush(); m_writer.Close(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; using System.Reflection.Emit; namespace System.Linq.Expressions.Compiler { internal static class ILGen { internal static void Emit(this ILGenerator il, OpCode opcode, MethodBase methodBase) { Debug.Assert(methodBase is MethodInfo || methodBase is ConstructorInfo); var ctor = methodBase as ConstructorInfo; if ((object)ctor != null) { il.Emit(opcode, ctor); } else { il.Emit(opcode, (MethodInfo)methodBase); } } #region Instruction helpers internal static void EmitLoadArg(this ILGenerator il, int index) { Debug.Assert(index >= 0); switch (index) { case 0: il.Emit(OpCodes.Ldarg_0); break; case 1: il.Emit(OpCodes.Ldarg_1); break; case 2: il.Emit(OpCodes.Ldarg_2); break; case 3: il.Emit(OpCodes.Ldarg_3); break; default: if (index <= Byte.MaxValue) { il.Emit(OpCodes.Ldarg_S, (byte)index); } else { il.Emit(OpCodes.Ldarg, index); } break; } } internal static void EmitLoadArgAddress(this ILGenerator il, int index) { Debug.Assert(index >= 0); if (index <= Byte.MaxValue) { il.Emit(OpCodes.Ldarga_S, (byte)index); } else { il.Emit(OpCodes.Ldarga, index); } } internal static void EmitStoreArg(this ILGenerator il, int index) { Debug.Assert(index >= 0); if (index <= Byte.MaxValue) { il.Emit(OpCodes.Starg_S, (byte)index); } else { il.Emit(OpCodes.Starg, index); } } /// <summary> /// Emits a Ldind* instruction for the appropriate type /// </summary> internal static void EmitLoadValueIndirect(this ILGenerator il, Type type) { ContractUtils.RequiresNotNull(type, "type"); if (type.GetTypeInfo().IsValueType) { if (type == typeof(int)) { il.Emit(OpCodes.Ldind_I4); } else if (type == typeof(uint)) { il.Emit(OpCodes.Ldind_U4); } else if (type == typeof(short)) { il.Emit(OpCodes.Ldind_I2); } else if (type == typeof(ushort)) { il.Emit(OpCodes.Ldind_U2); } else if (type == typeof(long) || type == typeof(ulong)) { il.Emit(OpCodes.Ldind_I8); } else if (type == typeof(char)) { il.Emit(OpCodes.Ldind_I2); } else if (type == typeof(bool)) { il.Emit(OpCodes.Ldind_I1); } else if (type == typeof(float)) { il.Emit(OpCodes.Ldind_R4); } else if (type == typeof(double)) { il.Emit(OpCodes.Ldind_R8); } else { il.Emit(OpCodes.Ldobj, type); } } else { il.Emit(OpCodes.Ldind_Ref); } } /// <summary> /// Emits a Stind* instruction for the appropriate type. /// </summary> internal static void EmitStoreValueIndirect(this ILGenerator il, Type type) { ContractUtils.RequiresNotNull(type, "type"); if (type.GetTypeInfo().IsValueType) { if (type == typeof(int)) { il.Emit(OpCodes.Stind_I4); } else if (type == typeof(short)) { il.Emit(OpCodes.Stind_I2); } else if (type == typeof(long) || type == typeof(ulong)) { il.Emit(OpCodes.Stind_I8); } else if (type == typeof(char)) { il.Emit(OpCodes.Stind_I2); } else if (type == typeof(bool)) { il.Emit(OpCodes.Stind_I1); } else if (type == typeof(float)) { il.Emit(OpCodes.Stind_R4); } else if (type == typeof(double)) { il.Emit(OpCodes.Stind_R8); } else { il.Emit(OpCodes.Stobj, type); } } else { il.Emit(OpCodes.Stind_Ref); } } // Emits the Ldelem* instruction for the appropriate type internal static void EmitLoadElement(this ILGenerator il, Type type) { ContractUtils.RequiresNotNull(type, "type"); if (!type.GetTypeInfo().IsValueType) { il.Emit(OpCodes.Ldelem_Ref); } else if (type.GetTypeInfo().IsEnum) { il.Emit(OpCodes.Ldelem, type); } else { switch (type.GetTypeCode()) { case TypeCode.Boolean: case TypeCode.SByte: il.Emit(OpCodes.Ldelem_I1); break; case TypeCode.Byte: il.Emit(OpCodes.Ldelem_U1); break; case TypeCode.Int16: il.Emit(OpCodes.Ldelem_I2); break; case TypeCode.Char: case TypeCode.UInt16: il.Emit(OpCodes.Ldelem_U2); break; case TypeCode.Int32: il.Emit(OpCodes.Ldelem_I4); break; case TypeCode.UInt32: il.Emit(OpCodes.Ldelem_U4); break; case TypeCode.Int64: case TypeCode.UInt64: il.Emit(OpCodes.Ldelem_I8); break; case TypeCode.Single: il.Emit(OpCodes.Ldelem_R4); break; case TypeCode.Double: il.Emit(OpCodes.Ldelem_R8); break; default: il.Emit(OpCodes.Ldelem, type); break; } } } /// <summary> /// Emits a Stelem* instruction for the appropriate type. /// </summary> internal static void EmitStoreElement(this ILGenerator il, Type type) { ContractUtils.RequiresNotNull(type, "type"); if (type.GetTypeInfo().IsEnum) { il.Emit(OpCodes.Stelem, type); return; } switch (type.GetTypeCode()) { case TypeCode.Boolean: case TypeCode.SByte: case TypeCode.Byte: il.Emit(OpCodes.Stelem_I1); break; case TypeCode.Char: case TypeCode.Int16: case TypeCode.UInt16: il.Emit(OpCodes.Stelem_I2); break; case TypeCode.Int32: case TypeCode.UInt32: il.Emit(OpCodes.Stelem_I4); break; case TypeCode.Int64: case TypeCode.UInt64: il.Emit(OpCodes.Stelem_I8); break; case TypeCode.Single: il.Emit(OpCodes.Stelem_R4); break; case TypeCode.Double: il.Emit(OpCodes.Stelem_R8); break; default: if (type.GetTypeInfo().IsValueType) { il.Emit(OpCodes.Stelem, type); } else { il.Emit(OpCodes.Stelem_Ref); } break; } } internal static void EmitType(this ILGenerator il, Type type) { ContractUtils.RequiresNotNull(type, "type"); il.Emit(OpCodes.Ldtoken, type); il.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle")); } #endregion #region Fields, properties and methods internal static void EmitFieldAddress(this ILGenerator il, FieldInfo fi) { ContractUtils.RequiresNotNull(fi, "fi"); if (fi.IsStatic) { il.Emit(OpCodes.Ldsflda, fi); } else { il.Emit(OpCodes.Ldflda, fi); } } internal static void EmitFieldGet(this ILGenerator il, FieldInfo fi) { ContractUtils.RequiresNotNull(fi, "fi"); if (fi.IsStatic) { il.Emit(OpCodes.Ldsfld, fi); } else { il.Emit(OpCodes.Ldfld, fi); } } internal static void EmitFieldSet(this ILGenerator il, FieldInfo fi) { ContractUtils.RequiresNotNull(fi, "fi"); if (fi.IsStatic) { il.Emit(OpCodes.Stsfld, fi); } else { il.Emit(OpCodes.Stfld, fi); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] internal static void EmitNew(this ILGenerator il, ConstructorInfo ci) { ContractUtils.RequiresNotNull(ci, "ci"); if (ci.DeclaringType.GetTypeInfo().ContainsGenericParameters) { throw Error.IllegalNewGenericParams(ci.DeclaringType); } il.Emit(OpCodes.Newobj, ci); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] internal static void EmitNew(this ILGenerator il, Type type, Type[] paramTypes) { ContractUtils.RequiresNotNull(type, "type"); ContractUtils.RequiresNotNull(paramTypes, "paramTypes"); ConstructorInfo ci = type.GetConstructor(paramTypes); if (ci == null) throw Error.TypeDoesNotHaveConstructorForTheSignature(); il.EmitNew(ci); } #endregion #region Constants internal static void EmitNull(this ILGenerator il) { il.Emit(OpCodes.Ldnull); } internal static void EmitString(this ILGenerator il, string value) { ContractUtils.RequiresNotNull(value, "value"); il.Emit(OpCodes.Ldstr, value); } internal static void EmitBoolean(this ILGenerator il, bool value) { if (value) { il.Emit(OpCodes.Ldc_I4_1); } else { il.Emit(OpCodes.Ldc_I4_0); } } internal static void EmitChar(this ILGenerator il, char value) { il.EmitInt(value); il.Emit(OpCodes.Conv_U2); } internal static void EmitByte(this ILGenerator il, byte value) { il.EmitInt(value); il.Emit(OpCodes.Conv_U1); } internal static void EmitSByte(this ILGenerator il, sbyte value) { il.EmitInt(value); il.Emit(OpCodes.Conv_I1); } internal static void EmitShort(this ILGenerator il, short value) { il.EmitInt(value); il.Emit(OpCodes.Conv_I2); } internal static void EmitUShort(this ILGenerator il, ushort value) { il.EmitInt(value); il.Emit(OpCodes.Conv_U2); } internal static void EmitInt(this ILGenerator il, int value) { OpCode c; switch (value) { case -1: c = OpCodes.Ldc_I4_M1; break; case 0: c = OpCodes.Ldc_I4_0; break; case 1: c = OpCodes.Ldc_I4_1; break; case 2: c = OpCodes.Ldc_I4_2; break; case 3: c = OpCodes.Ldc_I4_3; break; case 4: c = OpCodes.Ldc_I4_4; break; case 5: c = OpCodes.Ldc_I4_5; break; case 6: c = OpCodes.Ldc_I4_6; break; case 7: c = OpCodes.Ldc_I4_7; break; case 8: c = OpCodes.Ldc_I4_8; break; default: if (value >= -128 && value <= 127) { il.Emit(OpCodes.Ldc_I4_S, (sbyte)value); } else { il.Emit(OpCodes.Ldc_I4, value); } return; } il.Emit(c); } internal static void EmitUInt(this ILGenerator il, uint value) { il.EmitInt((int)value); il.Emit(OpCodes.Conv_U4); } internal static void EmitLong(this ILGenerator il, long value) { il.Emit(OpCodes.Ldc_I8, value); // // Now, emit convert to give the constant type information. // // Otherwise, it is treated as unsigned and overflow is not // detected if it's used in checked ops. // il.Emit(OpCodes.Conv_I8); } internal static void EmitULong(this ILGenerator il, ulong value) { il.Emit(OpCodes.Ldc_I8, (long)value); il.Emit(OpCodes.Conv_U8); } internal static void EmitDouble(this ILGenerator il, double value) { il.Emit(OpCodes.Ldc_R8, value); } internal static void EmitSingle(this ILGenerator il, float value) { il.Emit(OpCodes.Ldc_R4, value); } // matches TryEmitConstant internal static bool CanEmitConstant(object value, Type type) { if (value == null || CanEmitILConstant(type)) { return true; } Type t = value as Type; if (t != null && ShouldLdtoken(t)) { return true; } MethodBase mb = value as MethodBase; if (mb != null && ShouldLdtoken(mb)) { return true; } return false; } // matches TryEmitILConstant private static bool CanEmitILConstant(Type type) { switch (type.GetTypeCode()) { case TypeCode.Boolean: case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Char: case TypeCode.Byte: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: case TypeCode.Decimal: case TypeCode.String: return true; } return false; } internal static void EmitConstant(this ILGenerator il, object value) { Debug.Assert(value != null); EmitConstant(il, value, value.GetType()); } // // Note: we support emitting more things as IL constants than // Linq does internal static void EmitConstant(this ILGenerator il, object value, Type type) { if (value == null) { // Smarter than the Linq implementation which uses the initobj // pattern for all value types (works, but requires a local and // more IL) il.EmitDefault(type); return; } // Handle the easy cases if (il.TryEmitILConstant(value, type)) { return; } // Check for a few more types that we support emitting as constants Type t = value as Type; if (t != null && ShouldLdtoken(t)) { il.EmitType(t); if (type != typeof(Type)) { il.Emit(OpCodes.Castclass, type); } return; } MethodBase mb = value as MethodBase; if (mb != null && ShouldLdtoken(mb)) { il.Emit(OpCodes.Ldtoken, mb); Type dt = mb.DeclaringType; if (dt != null && dt.GetTypeInfo().IsGenericType) { il.Emit(OpCodes.Ldtoken, dt); il.Emit(OpCodes.Call, typeof(MethodBase).GetMethod("GetMethodFromHandle", new Type[] { typeof(RuntimeMethodHandle), typeof(RuntimeTypeHandle) })); } else { il.Emit(OpCodes.Call, typeof(MethodBase).GetMethod("GetMethodFromHandle", new Type[] { typeof(RuntimeMethodHandle) })); } if (type != typeof(MethodBase)) { il.Emit(OpCodes.Castclass, type); } return; } throw ContractUtils.Unreachable; } internal static bool ShouldLdtoken(Type t) { return t.GetTypeInfo() is TypeBuilder || t.IsGenericParameter || t.GetTypeInfo().IsVisible; } internal static bool ShouldLdtoken(MethodBase mb) { // Can't ldtoken on a DynamicMethod if (mb is DynamicMethod) { return false; } Type dt = mb.DeclaringType; return dt == null || ShouldLdtoken(dt); } private static bool TryEmitILConstant(this ILGenerator il, object value, Type type) { switch (type.GetTypeCode()) { case TypeCode.Boolean: il.EmitBoolean((bool)value); return true; case TypeCode.SByte: il.EmitSByte((sbyte)value); return true; case TypeCode.Int16: il.EmitShort((short)value); return true; case TypeCode.Int32: il.EmitInt((int)value); return true; case TypeCode.Int64: il.EmitLong((long)value); return true; case TypeCode.Single: il.EmitSingle((float)value); return true; case TypeCode.Double: il.EmitDouble((double)value); return true; case TypeCode.Char: il.EmitChar((char)value); return true; case TypeCode.Byte: il.EmitByte((byte)value); return true; case TypeCode.UInt16: il.EmitUShort((ushort)value); return true; case TypeCode.UInt32: il.EmitUInt((uint)value); return true; case TypeCode.UInt64: il.EmitULong((ulong)value); return true; case TypeCode.Decimal: il.EmitDecimal((decimal)value); return true; case TypeCode.String: il.EmitString((string)value); return true; default: return false; } } #endregion #region Linq Conversions internal static void EmitConvertToType(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { if (TypeUtils.AreEquivalent(typeFrom, typeTo)) { return; } if (typeFrom == typeof(void) || typeTo == typeof(void)) { throw ContractUtils.Unreachable; } bool isTypeFromNullable = TypeUtils.IsNullableType(typeFrom); bool isTypeToNullable = TypeUtils.IsNullableType(typeTo); Type nnExprType = TypeUtils.GetNonNullableType(typeFrom); Type nnType = TypeUtils.GetNonNullableType(typeTo); if (typeFrom.GetTypeInfo().IsInterface || // interface cast typeTo.GetTypeInfo().IsInterface || typeFrom == typeof(object) || // boxing cast typeTo == typeof(object) || typeFrom == typeof(System.Enum) || typeFrom == typeof(System.ValueType) || TypeUtils.IsLegalExplicitVariantDelegateConversion(typeFrom, typeTo)) { il.EmitCastToType(typeFrom, typeTo); } else if (isTypeFromNullable || isTypeToNullable) { il.EmitNullableConversion(typeFrom, typeTo, isChecked); } else if (!(TypeUtils.IsConvertible(typeFrom) && TypeUtils.IsConvertible(typeTo)) // primitive runtime conversion && (nnExprType.IsAssignableFrom(nnType) || // down cast nnType.IsAssignableFrom(nnExprType))) // up cast { il.EmitCastToType(typeFrom, typeTo); } else if (typeFrom.IsArray && typeTo.IsArray) { // See DevDiv Bugs #94657. il.EmitCastToType(typeFrom, typeTo); } else { il.EmitNumericConversion(typeFrom, typeTo, isChecked); } } private static void EmitCastToType(this ILGenerator il, Type typeFrom, Type typeTo) { if (!typeFrom.GetTypeInfo().IsValueType && typeTo.GetTypeInfo().IsValueType) { il.Emit(OpCodes.Unbox_Any, typeTo); } else if (typeFrom.GetTypeInfo().IsValueType && !typeTo.GetTypeInfo().IsValueType) { il.Emit(OpCodes.Box, typeFrom); if (typeTo != typeof(object)) { il.Emit(OpCodes.Castclass, typeTo); } } else if (!typeFrom.GetTypeInfo().IsValueType && !typeTo.GetTypeInfo().IsValueType) { il.Emit(OpCodes.Castclass, typeTo); } else { throw Error.InvalidCast(typeFrom, typeTo); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] private static void EmitNumericConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { bool isFromUnsigned = TypeUtils.IsUnsigned(typeFrom); bool isFromFloatingPoint = TypeUtils.IsFloatingPoint(typeFrom); if (typeTo == typeof(Single)) { if (isFromUnsigned) il.Emit(OpCodes.Conv_R_Un); il.Emit(OpCodes.Conv_R4); } else if (typeTo == typeof(Double)) { if (isFromUnsigned) il.Emit(OpCodes.Conv_R_Un); il.Emit(OpCodes.Conv_R8); } else { TypeCode tc = typeTo.GetTypeCode(); if (isChecked) { // Overflow checking needs to know if the source value on the IL stack is unsigned or not. if (isFromUnsigned) { switch (tc) { case TypeCode.SByte: il.Emit(OpCodes.Conv_Ovf_I1_Un); break; case TypeCode.Int16: il.Emit(OpCodes.Conv_Ovf_I2_Un); break; case TypeCode.Int32: il.Emit(OpCodes.Conv_Ovf_I4_Un); break; case TypeCode.Int64: il.Emit(OpCodes.Conv_Ovf_I8_Un); break; case TypeCode.Byte: il.Emit(OpCodes.Conv_Ovf_U1_Un); break; case TypeCode.UInt16: case TypeCode.Char: il.Emit(OpCodes.Conv_Ovf_U2_Un); break; case TypeCode.UInt32: il.Emit(OpCodes.Conv_Ovf_U4_Un); break; case TypeCode.UInt64: il.Emit(OpCodes.Conv_Ovf_U8_Un); break; default: throw Error.UnhandledConvert(typeTo); } } else { switch (tc) { case TypeCode.SByte: il.Emit(OpCodes.Conv_Ovf_I1); break; case TypeCode.Int16: il.Emit(OpCodes.Conv_Ovf_I2); break; case TypeCode.Int32: il.Emit(OpCodes.Conv_Ovf_I4); break; case TypeCode.Int64: il.Emit(OpCodes.Conv_Ovf_I8); break; case TypeCode.Byte: il.Emit(OpCodes.Conv_Ovf_U1); break; case TypeCode.UInt16: case TypeCode.Char: il.Emit(OpCodes.Conv_Ovf_U2); break; case TypeCode.UInt32: il.Emit(OpCodes.Conv_Ovf_U4); break; case TypeCode.UInt64: il.Emit(OpCodes.Conv_Ovf_U8); break; default: throw Error.UnhandledConvert(typeTo); } } } else { switch (tc) { case TypeCode.SByte: il.Emit(OpCodes.Conv_I1); break; case TypeCode.Byte: il.Emit(OpCodes.Conv_U1); break; case TypeCode.Int16: il.Emit(OpCodes.Conv_I2); break; case TypeCode.UInt16: case TypeCode.Char: il.Emit(OpCodes.Conv_U2); break; case TypeCode.Int32: il.Emit(OpCodes.Conv_I4); break; case TypeCode.UInt32: il.Emit(OpCodes.Conv_U4); break; case TypeCode.Int64: if (isFromUnsigned) { il.Emit(OpCodes.Conv_U8); } else { il.Emit(OpCodes.Conv_I8); } break; case TypeCode.UInt64: if (isFromUnsigned || isFromFloatingPoint) { il.Emit(OpCodes.Conv_U8); } else { il.Emit(OpCodes.Conv_I8); } break; default: throw Error.UnhandledConvert(typeTo); } } } } private static void EmitNullableToNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { Debug.Assert(TypeUtils.IsNullableType(typeFrom)); Debug.Assert(TypeUtils.IsNullableType(typeTo)); Label labIfNull = default(Label); Label labEnd = default(Label); LocalBuilder locFrom = null; LocalBuilder locTo = null; locFrom = il.DeclareLocal(typeFrom); il.Emit(OpCodes.Stloc, locFrom); locTo = il.DeclareLocal(typeTo); // test for null il.Emit(OpCodes.Ldloca, locFrom); il.EmitHasValue(typeFrom); labIfNull = il.DefineLabel(); il.Emit(OpCodes.Brfalse_S, labIfNull); il.Emit(OpCodes.Ldloca, locFrom); il.EmitGetValueOrDefault(typeFrom); Type nnTypeFrom = TypeUtils.GetNonNullableType(typeFrom); Type nnTypeTo = TypeUtils.GetNonNullableType(typeTo); il.EmitConvertToType(nnTypeFrom, nnTypeTo, isChecked); // construct result type ConstructorInfo ci = typeTo.GetConstructor(new Type[] { nnTypeTo }); il.Emit(OpCodes.Newobj, ci); il.Emit(OpCodes.Stloc, locTo); labEnd = il.DefineLabel(); il.Emit(OpCodes.Br_S, labEnd); // if null then create a default one il.MarkLabel(labIfNull); il.Emit(OpCodes.Ldloca, locTo); il.Emit(OpCodes.Initobj, typeTo); il.MarkLabel(labEnd); il.Emit(OpCodes.Ldloc, locTo); } private static void EmitNonNullableToNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { Debug.Assert(!TypeUtils.IsNullableType(typeFrom)); Debug.Assert(TypeUtils.IsNullableType(typeTo)); LocalBuilder locTo = null; locTo = il.DeclareLocal(typeTo); Type nnTypeTo = TypeUtils.GetNonNullableType(typeTo); il.EmitConvertToType(typeFrom, nnTypeTo, isChecked); ConstructorInfo ci = typeTo.GetConstructor(new Type[] { nnTypeTo }); il.Emit(OpCodes.Newobj, ci); il.Emit(OpCodes.Stloc, locTo); il.Emit(OpCodes.Ldloc, locTo); } private static void EmitNullableToNonNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { Debug.Assert(TypeUtils.IsNullableType(typeFrom)); Debug.Assert(!TypeUtils.IsNullableType(typeTo)); if (typeTo.GetTypeInfo().IsValueType) il.EmitNullableToNonNullableStructConversion(typeFrom, typeTo, isChecked); else il.EmitNullableToReferenceConversion(typeFrom); } private static void EmitNullableToNonNullableStructConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { Debug.Assert(TypeUtils.IsNullableType(typeFrom)); Debug.Assert(!TypeUtils.IsNullableType(typeTo)); Debug.Assert(typeTo.GetTypeInfo().IsValueType); LocalBuilder locFrom = null; locFrom = il.DeclareLocal(typeFrom); il.Emit(OpCodes.Stloc, locFrom); il.Emit(OpCodes.Ldloca, locFrom); il.EmitGetValue(typeFrom); Type nnTypeFrom = TypeUtils.GetNonNullableType(typeFrom); il.EmitConvertToType(nnTypeFrom, typeTo, isChecked); } private static void EmitNullableToReferenceConversion(this ILGenerator il, Type typeFrom) { Debug.Assert(TypeUtils.IsNullableType(typeFrom)); // We've got a conversion from nullable to Object, ValueType, Enum, etc. Just box it so that // we get the nullable semantics. il.Emit(OpCodes.Box, typeFrom); } private static void EmitNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { bool isTypeFromNullable = TypeUtils.IsNullableType(typeFrom); bool isTypeToNullable = TypeUtils.IsNullableType(typeTo); Debug.Assert(isTypeFromNullable || isTypeToNullable); if (isTypeFromNullable && isTypeToNullable) il.EmitNullableToNullableConversion(typeFrom, typeTo, isChecked); else if (isTypeFromNullable) il.EmitNullableToNonNullableConversion(typeFrom, typeTo, isChecked); else il.EmitNonNullableToNullableConversion(typeFrom, typeTo, isChecked); } internal static void EmitHasValue(this ILGenerator il, Type nullableType) { MethodInfo mi = nullableType.GetMethod("get_HasValue", BindingFlags.Instance | BindingFlags.Public); Debug.Assert(nullableType.GetTypeInfo().IsValueType); il.Emit(OpCodes.Call, mi); } internal static void EmitGetValue(this ILGenerator il, Type nullableType) { MethodInfo mi = nullableType.GetMethod("get_Value", BindingFlags.Instance | BindingFlags.Public); Debug.Assert(nullableType.GetTypeInfo().IsValueType); il.Emit(OpCodes.Call, mi); } internal static void EmitGetValueOrDefault(this ILGenerator il, Type nullableType) { MethodInfo mi = nullableType.GetMethod("GetValueOrDefault", System.Type.EmptyTypes); Debug.Assert(nullableType.GetTypeInfo().IsValueType); il.Emit(OpCodes.Call, mi); } #endregion #region Arrays /// <summary> /// Emits an array of constant values provided in the given list. /// The array is strongly typed. /// </summary> internal static void EmitArray<T>(this ILGenerator il, IList<T> items) { ContractUtils.RequiresNotNull(items, "items"); il.EmitInt(items.Count); il.Emit(OpCodes.Newarr, typeof(T)); for (int i = 0; i < items.Count; i++) { il.Emit(OpCodes.Dup); il.EmitInt(i); il.EmitConstant(items[i], typeof(T)); il.EmitStoreElement(typeof(T)); } } /// <summary> /// Emits an array of values of count size. The items are emitted via the callback /// which is provided with the current item index to emit. /// </summary> internal static void EmitArray(this ILGenerator il, Type elementType, int count, Action<int> emit) { ContractUtils.RequiresNotNull(elementType, "elementType"); ContractUtils.RequiresNotNull(emit, "emit"); if (count < 0) throw Error.CountCannotBeNegative(); il.EmitInt(count); il.Emit(OpCodes.Newarr, elementType); for (int i = 0; i < count; i++) { il.Emit(OpCodes.Dup); il.EmitInt(i); emit(i); il.EmitStoreElement(elementType); } } /// <summary> /// Emits an array construction code. /// The code assumes that bounds for all dimensions /// are already emitted. /// </summary> internal static void EmitArray(this ILGenerator il, Type arrayType) { ContractUtils.RequiresNotNull(arrayType, "arrayType"); if (!arrayType.IsArray) throw Error.ArrayTypeMustBeArray(); int rank = arrayType.GetArrayRank(); if (rank == 1) { il.Emit(OpCodes.Newarr, arrayType.GetElementType()); } else { Type[] types = new Type[rank]; for (int i = 0; i < rank; i++) { types[i] = typeof(int); } il.EmitNew(arrayType, types); } } #endregion #region Support for emitting constants internal static void EmitDecimal(this ILGenerator il, decimal value) { if (Decimal.Truncate(value) == value) { if (Int32.MinValue <= value && value <= Int32.MaxValue) { int intValue = Decimal.ToInt32(value); il.EmitInt(intValue); il.EmitNew(typeof(Decimal).GetConstructor(new Type[] { typeof(int) })); } else if (Int64.MinValue <= value && value <= Int64.MaxValue) { long longValue = Decimal.ToInt64(value); il.EmitLong(longValue); il.EmitNew(typeof(Decimal).GetConstructor(new Type[] { typeof(long) })); } else { il.EmitDecimalBits(value); } } else { il.EmitDecimalBits(value); } } private static void EmitDecimalBits(this ILGenerator il, decimal value) { int[] bits = Decimal.GetBits(value); il.EmitInt(bits[0]); il.EmitInt(bits[1]); il.EmitInt(bits[2]); il.EmitBoolean((bits[3] & 0x80000000) != 0); il.EmitByte((byte)(bits[3] >> 16)); il.EmitNew(typeof(decimal).GetConstructor(new Type[] { typeof(int), typeof(int), typeof(int), typeof(bool), typeof(byte) })); } /// <summary> /// Emits default(T) /// Semantics match C# compiler behavior /// </summary> internal static void EmitDefault(this ILGenerator il, Type type) { switch (type.GetTypeCode()) { case TypeCode.Object: case TypeCode.DateTime: if (type.GetTypeInfo().IsValueType) { // Type.GetTypeCode on an enum returns the underlying // integer TypeCode, so we won't get here. Debug.Assert(!type.GetTypeInfo().IsEnum); // This is the IL for default(T) if T is a generic type // parameter, so it should work for any type. It's also // the standard pattern for structs. LocalBuilder lb = il.DeclareLocal(type); il.Emit(OpCodes.Ldloca, lb); il.Emit(OpCodes.Initobj, type); il.Emit(OpCodes.Ldloc, lb); } else { il.Emit(OpCodes.Ldnull); } break; case TypeCode.Empty: case TypeCode.String: il.Emit(OpCodes.Ldnull); break; case TypeCode.Boolean: case TypeCode.Char: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: il.Emit(OpCodes.Ldc_I4_0); break; case TypeCode.Int64: case TypeCode.UInt64: il.Emit(OpCodes.Ldc_I4_0); il.Emit(OpCodes.Conv_I8); break; case TypeCode.Single: il.Emit(OpCodes.Ldc_R4, default(Single)); break; case TypeCode.Double: il.Emit(OpCodes.Ldc_R8, default(Double)); break; case TypeCode.Decimal: il.Emit(OpCodes.Ldc_I4_0); il.Emit(OpCodes.Newobj, typeof(Decimal).GetConstructor(new Type[] { typeof(int) })); break; default: throw ContractUtils.Unreachable; } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; namespace Adform.AdServing.AhoCorasickTree.Sandbox.V10 { public class AhoCorasickTree { private byte[] _data; internal AhoCorasickTreeNode Root { get; set; } public AhoCorasickTree(IEnumerable<string> keywords) { Root = new AhoCorasickTreeNode(); if (keywords != null) { foreach (var p in keywords) { AddPatternToTree(p); } SetFailureNodes(); // needed for offsets ;) SetOffsets(); CreateArray(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe char GetKey(byte* currentNodePtr, int ind) { return *(char*)(currentNodePtr + sizeof(int) + sizeof(int) + ind * (sizeof(char) + sizeof(int))); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe byte* GetNext(byte* b, byte* currentNodePtr, int ind) { return b + *(int*)(currentNodePtr + (sizeof(int) + sizeof(int) + ind * (sizeof(char) + sizeof(int)) + sizeof(char))); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe byte* GetFailure(byte* b, byte* currentNodePtr) { return b + *(int*)(currentNodePtr + sizeof(int)); } public unsafe bool Contains(string text) { fixed (byte* b = _data) fixed (char* p = text) { char c1, c2, c3, c4; int len = text.Length * 2; long* lptr = (long*)p; long l; byte* currentNodePtr = b; int size; int ind; char key; int count = len / 8; len -= (len / 8) * 8; while (count > 0) { count--; l = *lptr; c1 = (char)(l & 0xffff); c2 = (char)(l >> 16); c3 = (char)(l >> 32); c4 = (char)(l >> 48); lptr++; C1: size = *(int*)currentNodePtr; ind = c1 & (size - 1); key = GetKey(currentNodePtr, ind); if (key == c1) { var nextPtr = GetNext(b, currentNodePtr, ind); if (nextPtr == b) return true; currentNodePtr = nextPtr; } else { currentNodePtr = GetFailure(b, currentNodePtr); if (currentNodePtr != b) goto C1; } C2: size = *(int*)currentNodePtr; ind = c2 & (size - 1); key = GetKey(currentNodePtr, ind); if (key == c2) { var nextPtr = GetNext(b, currentNodePtr, ind); if (nextPtr == b) return true; currentNodePtr = nextPtr; } else { currentNodePtr = GetFailure(b, currentNodePtr); if (currentNodePtr != b) goto C2; } C3: size = *(int*)currentNodePtr; ind = c3 & (size - 1); key = GetKey(currentNodePtr, ind); if (key == c3) { var nextPtr = GetNext(b, currentNodePtr, ind); if (nextPtr == b) return true; currentNodePtr = nextPtr; } else { currentNodePtr = GetFailure(b, currentNodePtr); if (currentNodePtr != b) goto C3; } C4: size = *(int*)currentNodePtr; ind = c4 & (size - 1); key = GetKey(currentNodePtr, ind); if (key == c4) { var nextPtr = GetNext(b, currentNodePtr, ind); if (nextPtr == b) return true; currentNodePtr = nextPtr; } else { currentNodePtr = GetFailure(b, currentNodePtr); if (currentNodePtr != b) goto C4; } } var cptr = (char*)lptr; while (len > 0) { c1 = *cptr; cptr++; len -= 2; C1: size = *(int*)currentNodePtr; ind = c1 & (size - 1); key = GetKey(currentNodePtr, ind); if (key == c1) { var nextPtr = GetNext(b, currentNodePtr, ind); if (nextPtr == b) return true; currentNodePtr = nextPtr; } else { currentNodePtr = GetFailure(b, currentNodePtr); if (currentNodePtr != b) goto C1; } } } return false; } public bool ContainsThatStart(string text) { return Contains(text, true); } private bool Contains(string text, bool onlyStarts) { var pointer = Root; for (var i = 0; i < text.Length; i++) { AhoCorasickTreeNode transition = null; while (transition == null) { transition = pointer.GetTransition(text[i]); if (pointer == Root) break; if (transition == null) pointer = pointer.Failure; } if (transition != null) pointer = transition; else if (onlyStarts) return false; if (pointer.Results.Count > 0) return true; } return false; } public IEnumerable<string> FindAll(string text) { var pointer = Root; foreach (var c in text) { var transition = GetTransition(c, ref pointer); if (transition != null) pointer = transition; foreach (var result in pointer.Results) yield return result; } } private AhoCorasickTreeNode GetTransition(char c, ref AhoCorasickTreeNode pointer) { AhoCorasickTreeNode transition = null; while (transition == null) { transition = pointer.GetTransition(c); if (pointer == Root) break; if (transition == null) pointer = pointer.Failure; } return transition; } private void SetFailureNodes() { var nodes = FailToRootNode(); FailUsingBFS(nodes); Root.Failure = Root; } private void AddPatternToTree(string pattern) { var node = Root; foreach (var c in pattern) { node = node.GetTransition(c) ?? node.AddTransition(c); } node.AddResult(pattern); node.IsWord = true; } private List<AhoCorasickTreeNode> FailToRootNode() { var nodes = new List<AhoCorasickTreeNode>(); foreach (var node in Root.Transitions) { node.Failure = Root; nodes.AddRange(node.Transitions); } return nodes; } private void FailUsingBFS(List<AhoCorasickTreeNode> nodes) { while (nodes.Count != 0) { var newNodes = new List<AhoCorasickTreeNode>(); foreach (var node in nodes) { var failure = node.ParentFailure; var value = node.Value; while (failure != null && !failure.ContainsTransition(value)) { failure = failure.Failure; } if (failure == null) { node.Failure = Root; } else { node.Failure = failure.GetTransition(value); node.AddResults(node.Failure.Results); if (!node.IsWord) { node.IsWord = failure.IsWord; } } newNodes.AddRange(node.Transitions); } nodes = newNodes; } } private void CreateArray() { var data = new List<byte>(); var queue = new Queue<AhoCorasickTreeNode>(); queue.Enqueue(Root); while (queue.Count > 0) { var currentNode = queue.Dequeue(); if (currentNode._entries.Length == 0) continue; data.AddRange(BitConverter.GetBytes(currentNode._entries.Length)); data.AddRange(BitConverter.GetBytes(currentNode.Failure.Offset)); if (currentNode._entries.Length > 0) { foreach (var entry in currentNode._entries.Where(x => x.Key != 0)) { queue.Enqueue(entry.Value); data.AddRange(BitConverter.GetBytes(entry.Key)); data.AddRange(entry.Value.IsWord ? BitConverter.GetBytes(0) : BitConverter.GetBytes(entry.Value.Offset)); } } } _data = data.ToArray(); } private void SetOffsets() { var roots = 0; var elements = 0; var queue = new Queue<AhoCorasickTreeNode>(); queue.Enqueue(Root); while (queue.Count > 0) { var currentNode = queue.Dequeue(); if (currentNode._entries.Length == 0) continue; currentNode.Offset = calcOffset(roots, elements); roots++; foreach (var entry in currentNode._entries.Where(x => x.Key != 0)) { queue.Enqueue(entry.Value); elements++; } } } private int calcOffset(int roots, int childs) { return roots * (sizeof(int) + sizeof(int)) + childs * (sizeof(char) + sizeof(int)); } } }
using System; using System.Collections; using System.Data; using System.Data.SqlClient; using System.Security.Principal; using System.Text; using System.Web; using System.Web.Security; using Appleseed.Framework.Settings; using Appleseed.Framework.Site.Configuration; using Appleseed.Framework.Site.Data; using Appleseed.Framework.Users.Data; using System.Collections.Generic; using Appleseed.Framework.Providers.AppleseedRoleProvider; using System.Diagnostics; namespace Appleseed.Framework.Security { /// <summary> /// The PortalSecurity class encapsulates two helper methods that enable /// developers to easily check the role status of the current browser client. /// </summary> [History("jminond", "2004/09/29", "added killsession method mimic of sign out, as well as modified sign on to use cookieexpire in Appleseed.config")] [History("gman3001", "2004/09/29", "Call method for recording the user's last visit date on successful signon")] [History("jviladiu@portalServices.net", "2004/09/23", "Get users & roles from true portal if UseSingleUserBase=true")] [History("jviladiu@portalServices.net", "2004/08/23", "Deleted repeated code in HasxxxPermissions and GetxxxPermissions")] [History("cisakson@yahoo.com", "2003/04/28", "Changed the IsInRole function so it support's a custom setting for Windows portal admins!")] [History("Geert.Audenaert@Syntegra.Com", "2003/03/26", "Changed the IsInRole function so it support's users to in case of windowsauthentication!")] [History("Thierry (tiptopweb)", "2003/04/12", "Migrate shopping cart in SignOn for E-Commerce")] public class PortalSecurity { const string strPortalSettings = "PortalSettings"; // [Flags] // public enum SecurityPermission : uint // { // NoAccess = 0x0000, // View = 0x0001, // Add = 0x0002, // Edit = 0x0004, // Delete = 0x0008 // } /// <summary> /// PortalSecurity.IsInRole() Method /// The IsInRole method enables developers to easily check the role /// status of the current browser client. /// </summary> /// <param name="role">The role.</param> /// <returns> /// <c>true</c> if [is in role] [the specified role]; otherwise, <c>false</c>. /// </returns> public static bool IsInRole(string role) { // Check if integrated windows authentication is used ? bool useNTLM = HttpContext.Current.User is WindowsPrincipal; // Check if the user is in the Admins role. if (useNTLM && role.Trim() == "Admins") { // Obtain PortalSettings from Current Context // WindowsAdmins added 28.4.2003 Cory Isakson PortalSettings portalSettings = (PortalSettings)HttpContext.Current.Items[strPortalSettings]; StringBuilder winRoles = new StringBuilder(); winRoles.Append(portalSettings.CustomSettings["WindowsAdmins"]); winRoles.Append(";"); //jes1111 - winRoles.Append(ConfigurationSettings.AppSettings["ADAdministratorGroup"]); winRoles.Append(Config.ADAdministratorGroup); return IsInRoles(winRoles.ToString()); } // Allow giving access to users if (useNTLM && role == HttpContext.Current.User.Identity.Name) return true; else { return HttpContext.Current.User.IsInRole(role); } } /// <summary> /// The IsInRoles method enables developers to easily check the role /// status of the current browser client against an array of roles /// </summary> /// <param name="roles">The roles.</param> /// <returns> /// <c>true</c> if [is in roles] [the specified roles]; otherwise, <c>false</c>. /// </returns> public static bool IsInRoles(string roles) { HttpContext context = HttpContext.Current; //MembershipUser user; //if ((user = Membership.GetUser(context.User.Identity.Name)) != null) //{ if (roles != null) { foreach (string splitRole in roles.Split(new char[] { ';' })) { string role = splitRole.Trim(); if (role != null && role.Length != 0 && ((role == "All Users") || (IsInRole(role)))) { return true; } // Authenticated user role added // 15 nov 2002 - by manudea if ((role == "Authenticated Users") && (context.Request.IsAuthenticated)) { return true; } // end authenticated user role added // Unauthenticated user role added // 30/01/2003 - by manudea if ((role == "Unauthenticated Users") && (!context.Request.IsAuthenticated)) { return true; } // end Unauthenticated user role added } } return false; // } //else //{ // ErrorHandler.Publish(LogLevel.Debug, "User es null: " + context.User.Identity.Name); // ErrorHandler.Publish(LogLevel.Debug, "User no autenticado: " + context.User.Identity.Name); // PortalSecurity.SignOut(); //} // return false; } #region Current user permissions /// <summary> /// Determines whether the specified module ID has permissions. /// </summary> /// <param name="moduleID">The module ID.</param> /// <param name="procedureName">Name of the procedure.</param> /// <param name="parameterRol">The parameter rol.</param> /// <returns> /// <c>true</c> if the specified module ID has permissions; otherwise, <c>false</c>. /// </returns> private static bool hasPermissions(int moduleID, string procedureName, string parameterRol) { if (RecyclerDB.ModuleIsInRecycler(moduleID)) procedureName = procedureName + "Recycler"; if (moduleID <= 0) return false; // Obtain PortalSettings from Current Context PortalSettings portalSettings = (PortalSettings)HttpContext.Current.Items[strPortalSettings]; int portalID = portalSettings.PortalID; // jviladiu@portalServices.net: Get users & roles from true portal (2004/09/23) if (Config.UseSingleUserBase) portalID = 0; // Create Instance of Connection and Command Object using (SqlConnection myConnection = Config.SqlConnectionString) { using (SqlCommand myCommand = new SqlCommand(procedureName, myConnection)) { // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4); parameterModuleID.Value = moduleID; myCommand.Parameters.Add(parameterModuleID); SqlParameter parameterPortalID = new SqlParameter("@PortalID", SqlDbType.Int, 4); parameterPortalID.Value = portalID; myCommand.Parameters.Add(parameterPortalID); // Add out parameters to Sproc SqlParameter parameterAccessRoles = new SqlParameter("@AccessRoles", SqlDbType.NVarChar, 256); parameterAccessRoles.Direction = ParameterDirection.Output; myCommand.Parameters.Add(parameterAccessRoles); SqlParameter parameterRoles = new SqlParameter(parameterRol, SqlDbType.NVarChar, 256); parameterRoles.Direction = ParameterDirection.Output; myCommand.Parameters.Add(parameterRoles); // Open the database connection and execute the command myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } return IsInRoles(parameterAccessRoles.Value.ToString()) && IsInRoles(parameterRoles.Value.ToString()); } } } /// <summary> /// The HasEditPermissions method enables developers to easily check /// whether the current browser client has access to edit the settings /// of a specified portal module. /// </summary> /// <param name="moduleID">The module ID.</param> /// <returns> /// <c>true</c> if [has edit permissions] [the specified module ID]; otherwise, <c>false</c>. /// </returns> public static bool HasEditPermissions(int moduleID) { // if (RecyclerDB.ModuleIsInRecycler(moduleID)) // return hasPermissions (moduleID, "rb_GetAuthEditRolesRecycler", "@EditRoles"); // else return hasPermissions(moduleID, "rb_GetAuthEditRoles", "@EditRoles"); } /// <summary> /// The HasViewPermissions method enables developers to easily check /// whether the current browser client has access to view the /// specified portal module /// </summary> /// <param name="moduleID">The module ID.</param> /// <returns> /// <c>true</c> if [has view permissions] [the specified module ID]; otherwise, <c>false</c>. /// </returns> [History("JB - john@bowenweb.com", "2005/06/11", "Added support for module Recycle Bin")] public static bool HasViewPermissions(int moduleID) { return hasPermissions(moduleID, "rb_GetAuthViewRoles", "@ViewRoles"); } /// <summary> /// The HasAddPermissions method enables developers to easily check /// whether the current browser client has access to Add the /// specified portal module /// </summary> /// <param name="moduleID">The module ID.</param> /// <returns> /// <c>true</c> if [has add permissions] [the specified module ID]; otherwise, <c>false</c>. /// </returns> public static bool HasAddPermissions(int moduleID) { return hasPermissions(moduleID, "rb_GetAuthAddRoles", "@AddRoles"); } /// <summary> /// The HasDeletePermissions method enables developers to easily check /// whether the current browser client has access to Delete the /// specified portal module /// </summary> /// <param name="moduleID">The module ID.</param> /// <returns> /// <c>true</c> if [has delete permissions] [the specified module ID]; otherwise, <c>false</c>. /// </returns> public static bool HasDeletePermissions(int moduleID) { return hasPermissions(moduleID, "rb_GetAuthDeleteRoles", "@DeleteRoles"); } /// <summary> /// The HasPropertiesPermissions method enables developers to easily check /// whether the current browser client has access to Properties the /// specified portal module /// </summary> /// <param name="moduleID">The module ID.</param> /// <returns> /// <c>true</c> if [has properties permissions] [the specified module ID]; otherwise, <c>false</c>. /// </returns> public static bool HasPropertiesPermissions(int moduleID) { return hasPermissions(moduleID, "rb_GetAuthPropertiesRoles", "@PropertiesRoles"); } /// <summary> /// The HasApprovePermissions method enables developers to easily check /// whether the current browser client has access to Approve the /// specified portal module /// </summary> /// <param name="moduleID">The module ID.</param> /// <returns> /// <c>true</c> if [has approve permissions] [the specified module ID]; otherwise, <c>false</c>. /// </returns> public static bool HasApprovePermissions(int moduleID) { return hasPermissions(moduleID, "rb_GetAuthApproveRoles", "@ApproveRoles"); } /// <summary> /// The HasPublishPermissions method enables developers to easily check /// whether the current browser client has access to Approve the /// specified portal module /// </summary> /// <param name="moduleID">The module ID.</param> /// <returns> /// <c>true</c> if [has publish permissions] [the specified module ID]; otherwise, <c>false</c>. /// </returns> public static bool HasPublishPermissions(int moduleID) { return hasPermissions(moduleID, "rb_GetAuthPublishingRoles", "@PublishingRoles"); } #endregion #region GetRoleList Methods - Added by John Mandia (www.whitelightsolutions.com) 15/08/04 private static string getPermissions(int moduleID, string procedureName, string parameterRol) { // Obtain PortalSettings from Current Context PortalSettings portalSettings = (PortalSettings)HttpContext.Current.Items[strPortalSettings]; int portalID = portalSettings.PortalID; // jviladiu@portalServices.net: Get users & roles from true portal (2004/09/23) if (Config.UseSingleUserBase) portalID = 0; // Create Instance of Connection and Command Object using (SqlConnection myConnection = Config.SqlConnectionString) { using (SqlCommand myCommand = new SqlCommand(procedureName, myConnection)) { // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4); parameterModuleID.Value = moduleID; myCommand.Parameters.Add(parameterModuleID); SqlParameter parameterPortalID = new SqlParameter("@PortalID", SqlDbType.Int, 4); parameterPortalID.Value = portalID; myCommand.Parameters.Add(parameterPortalID); // Add out parameters to Sproc SqlParameter parameterAccessRoles = new SqlParameter("@AccessRoles", SqlDbType.NVarChar, 256); parameterAccessRoles.Direction = ParameterDirection.Output; myCommand.Parameters.Add(parameterAccessRoles); SqlParameter parameterRoles = new SqlParameter(parameterRol, SqlDbType.NVarChar, 256); parameterRoles.Direction = ParameterDirection.Output; myCommand.Parameters.Add(parameterRoles); // Open the database connection and execute the command myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } return parameterRoles.Value.ToString(); } } } /// <summary> /// The GetEditPermissions method enables developers to easily retrieve /// a list of roles that have Edit Permissions /// of a specified portal module. /// </summary> /// <param name="moduleID"></param> /// <returns>A list of roles that have Edit permissions seperated by ;</returns> public static string GetEditPermissions(int moduleID) { return getPermissions(moduleID, "rb_GetAuthEditRoles", "@EditRoles"); } /// <summary> /// The GetViewPermissions method enables developers to easily retrieve /// a list of roles that have View permissions for the /// specified portal module /// </summary> /// <param name="moduleID"></param> /// <returns>A list of roles that have View permissions for the specified module seperated by ;</returns> public static string GetViewPermissions(int moduleID) { return getPermissions(moduleID, "rb_GetAuthViewRoles", "@ViewRoles"); } /// <summary> /// The GetAddPermissions method enables developers to easily retrieve /// a list of roles that have Add permissions for the /// specified portal module /// </summary> /// <param name="moduleID"></param> /// <returns>A list of roles that have Add permissions for the specified module seperated by ;</returns> public static string GetAddPermissions(int moduleID) { return getPermissions(moduleID, "rb_GetAuthAddRoles", "@AddRoles"); } /// <summary> /// The GetDeletePermissions method enables developers to easily retrieve /// a list of roles that have access to Delete the /// specified portal module /// </summary> /// <param name="moduleID"></param> /// <returns>A list of roles that have delete permissions for the specified module seperated by ;</returns> public static string GetDeletePermissions(int moduleID) { return getPermissions(moduleID, "rb_GetAuthDeleteRoles", "@DeleteRoles"); } /// <summary> /// The GetPropertiesPermissions method enables developers to easily retrieve /// a list of roles that have access to Properties for the /// specified portal module /// </summary> /// <param name="moduleID"></param> /// <returns>A list of roles that have Properties permission for the specified module seperated by ;</returns> public static string GetPropertiesPermissions(int moduleID) { return getPermissions(moduleID, "rb_GetAuthPropertiesRoles", "@PropertiesRoles"); } /// <summary> /// The GetMoveModulePermissions method enables developers to easily retrieve /// a list of roles that have access to move specified portal moduleModule. /// </summary> /// <param name="moduleID"></param> /// <returns>A list of roles that have move module permission for the specified module seperated by ;</returns> public static string GetMoveModulePermissions(int moduleID) { return getPermissions(moduleID, "rb_GetAuthMoveModuleRoles", "@MoveModuleRoles"); } /// <summary> /// The GetDeleteModulePermissions method enables developers to easily retrieve /// a list of roles that have access to delete specified portal moduleModule. /// </summary> /// <param name="moduleID"></param> /// <returns>A list of roles that have delete module permission for the specified module seperated by ;</returns> public static string GetDeleteModulePermissions(int moduleID) { return getPermissions(moduleID, "rb_GetAuthDeleteModuleRoles", "@DeleteModuleRoles"); } /// <summary> /// The GetApprovePermissions method enables developers to easily retrieve /// a list of roles that have Approve permissions for the /// specified portal module /// </summary> /// <param name="moduleID">The module ID.</param> /// <returns> /// A string of roles that have approve permissions seperated by ; /// </returns> public static string GetApprovePermissions(int moduleID) { return getPermissions(moduleID, "rb_GetAuthApproveRoles", "@ApproveRoles"); } /// <summary> /// The GetPublishPermissions method enables developers to easily retrieve /// the list of roles that have Publish Permissions. /// </summary> /// <param name="moduleID">The module ID.</param> /// <returns> /// A list of roles that has Publish Permissions seperated by ; /// </returns> public static string GetPublishPermissions(int moduleID) { return getPermissions(moduleID, "rb_GetAuthPublishingRoles", "@PublishingRoles"); } #endregion #region Sign methods /// <summary> /// Single point for logging on an user, not persistent. /// </summary> /// <param name="user">Username or email</param> /// <param name="password">Password</param> /// <returns></returns> public static string SignOn(string user, string password) { return SignOn(user, password, false); } /// <summary> /// Single point for logging on an user. /// </summary> /// <param name="user">Username or email</param> /// <param name="password">Password</param> /// <param name="persistent">Use a cookie to make it persistent</param> /// <returns></returns> public static string SignOn(string user, string password, bool persistent) { return SignOn(user, password, persistent, null); } /// <summary> /// Single point for logging on an user. /// </summary> /// <param name="user">Username or email</param> /// <param name="password">Password</param> /// <param name="persistent">Use a cookie to make it persistent</param> /// <param name="redirectPage">The redirect page.</param> /// <returns></returns> [History("bja@reedtek.com", "2003/05/16", "Support for collapsable")] public static string SignOn(string user, string password, bool persistent, string redirectPage) { // Obtain PortalSettings from Current Context PortalSettings portalSettings = (PortalSettings)HttpContext.Current.Items[strPortalSettings]; MembershipUser usr; UsersDB accountSystem = new UsersDB(); // Attempt to Validate User Credentials using UsersDB usr = accountSystem.Login(user, password, portalSettings.PortalAlias); // Thierry (tiptopweb), 12 Apr 2003: Save old ShoppingCartID // ShoppingCartDB shoppingCart = new ShoppingCartDB(); // string tempCartID = ShoppingCartDB.GetCurrentShoppingCartID(); if (usr != null) { // Ender, 31 July 2003: Support for the monitoring module by Paul Yarrow if (Config.EnableMonitoring) { try { Monitoring.LogEntry((Guid)usr.ProviderUserKey, portalSettings.PortalID, -1, "Logon", string.Empty); } catch { ErrorHandler.Publish(LogLevel.Info, "Cannot monitoring login user " + usr.UserName); } } // Use security system to set the UserID within a client-side Cookie FormsAuthentication.SetAuthCookie(usr.ToString(), persistent); // Appleseed Security cookie Required if we are sharing a single domain // with portal Alias in the URL // Set a cookie to persist authentication for each portal // so user can be reauthenticated // automatically if they chose to Remember Login HttpCookie hck = HttpContext.Current.Response.Cookies["Appleseed_" + portalSettings.PortalAlias.ToLower()]; hck.Value = usr.ToString(); //Fill all data: name + email + id hck.Path = "/"; if (persistent) // Keep the cookie? { hck.Expires = DateTime.Now.AddYears(50); } else { //jminond - option to kill cookie after certain time always // jes1111 // if(ConfigurationSettings.AppSettings["CookieExpire"] != null) // { // int minuteAdd = int.Parse(ConfigurationSettings.AppSettings["CookieExpire"]); int minuteAdd = Config.CookieExpire; DateTime time = DateTime.Now; TimeSpan span = new TimeSpan(0, 0, minuteAdd, 0, 0); hck.Expires = time.Add(span); // } } if (redirectPage == null || redirectPage.Length == 0) { // Redirect browser back to originating page if (HttpContext.Current.Request.UrlReferrer != null) { HttpContext.Current.Response.Redirect(HttpContext.Current.Request.UrlReferrer.ToString()); } else { HttpContext.Current.Response.Redirect(Path.ApplicationRoot); } return usr.Email; } else { HttpContext.Current.Response.Redirect(redirectPage); } } return null; } /// <summary> /// ExtendCookie /// </summary> /// <param name="portalSettings">The portal settings.</param> /// <param name="minuteAdd">The minute add.</param> public static void ExtendCookie(PortalSettings portalSettings, int minuteAdd) { DateTime time = DateTime.Now; TimeSpan span = new TimeSpan(0, 0, minuteAdd, 0, 0); HttpContext.Current.Response.Cookies["Appleseed_" + portalSettings.PortalAlias].Expires = time.Add(span); return; } /// <summary> /// ExtendCookie /// </summary> /// <param name="portalSettings">The portal settings.</param> public static void ExtendCookie(PortalSettings portalSettings) { int minuteAdd = Config.CookieExpire; ExtendCookie(portalSettings, minuteAdd); return; } /// <summary> /// Single point logoff /// </summary> public static void SignOut() { SignOut(HttpUrlBuilder.BuildUrl("~/Default.aspx"), true); } /// <summary> /// Kills session after timeout /// jminond - fix kill session after timeout. /// </summary> public static void KillSession() { SignOut(HttpUrlBuilder.BuildUrl("~/DesktopModules/CoreModules/Admin/Logon.aspx"), true); //HttpContext.Current.Response.Redirect(urlToRedirect); //PortalSecurity.AccessDenied(); } /// <summary> /// Single point logoff /// </summary> public static void SignOut(string urlToRedirect, bool removeLogin) { StackTrace st = new StackTrace(new StackFrame(2, true)); var frames = st.GetFrames(); string stackString = string.Empty; foreach (var frame in frames) { stackString+= "> " + frame.GetMethod().Name; } ErrorHandler.Publish(LogLevel.Info, "Hago signout: " + stackString); // Log User Off from Cookie Authentication System FormsAuthentication.SignOut(); // Invalidate roles token HttpCookie hck = HttpContext.Current.Response.Cookies["portalroles"]; hck.Value = null; hck.Expires = new DateTime(1999, 10, 12); hck.Path = "/"; if (removeLogin) { // Obtain PortalSettings from Current Context PortalSettings portalSettings = (PortalSettings)HttpContext.Current.Items[strPortalSettings]; // Invalidate Portal Alias Cookie security HttpCookie xhck = HttpContext.Current.Response.Cookies["Appleseed_" + portalSettings.PortalAlias.ToLower()]; xhck.Value = null; xhck.Expires = new DateTime(1999, 10, 12); xhck.Path = "/"; } // [START] bja@reedtek.com remove user window information // User Information // valid user if (HttpContext.Current.User != null) { // Obtain PortalSettings from Current Context //Ender 4 July 2003: Added to support the Monitoring module by Paul Yarrow PortalSettings portalSettings = (PortalSettings)HttpContext.Current.Items[strPortalSettings]; // User Information UsersDB users = new UsersDB(); MembershipUser user = users.GetSingleUser(HttpContext.Current.User.Identity.Name, portalSettings.PortalAlias); if (user != null) { // get user id Guid uid = (Guid)user.ProviderUserKey; if (!uid.Equals(Guid.Empty)) { try { if (Config.EnableMonitoring) { Monitoring.LogEntry(uid, portalSettings.PortalID, -1, "Logoff", string.Empty); } } catch { } } } } // [END ] bja@reedtek.com remove user window information //Redirect user back to the Portal Home Page if (urlToRedirect.Length > 0) HttpContext.Current.Response.Redirect(urlToRedirect); } #endregion /// <summary> /// Redirect user back to the Portal Home Page. /// Mainily used after a succesfull login. /// </summary> public static void PortalHome() { HttpContext.Current.Response.Redirect(HttpUrlBuilder.BuildUrl("~/Default.aspx")); } /// <summary> /// Single point access deny. /// Called when there is an unauthorized access attempt. /// </summary> public static void AccessDenied() { if (HttpContext.Current.User.Identity.IsAuthenticated) throw new HttpException(403, "Access Denied", 2); else HttpContext.Current.Response.Redirect(HttpUrlBuilder.BuildUrl("~/DesktopModules/CoreModules/Admin/Logon.aspx")); } /// <summary> /// Single point edit access deny. /// Called when there is an unauthorized access attempt to an edit page. /// </summary> public static void AccessDeniedEdit() { if (HttpContext.Current.User.Identity.IsAuthenticated) throw new HttpException(403, "Access Denied Edit", 3); else HttpContext.Current.Response.Redirect(HttpUrlBuilder.BuildUrl("~/DesktopModules/CoreModules/Admin/Logon.aspx")); } /// <summary> /// Single point edit access deny from the Secure server (SSL) /// Called when there is an unauthorized access attempt to an edit page. /// </summary> public static void SecureAccessDenied() { throw new HttpException(403, "Secure Access Denied", 3); } /// <summary> /// Single point get roles /// </summary> public static IList<AppleseedRole> GetRoles() { // Obtain PortalSettings from Current Context PortalSettings portalSettings = (PortalSettings)HttpContext.Current.Items[strPortalSettings]; int portalID = portalSettings.PortalID; // john.mandia@whitelightsolutions.com: 29th May 2004 When retrieving/editing/adding roles or users etc then portalID should be 0 if it is shared // But I commented this out as this check is done in UsersDB.GetRoles Anyway //if (Config.UseSingleUserBase) portalID = 0; IList<AppleseedRole> roles; // TODO: figure out if we could persist role Guid in cookies //// Create the roles cookie if it doesn't exist yet for this session. //if ((HttpContext.Current.Request.Cookies["portalroles"] == null) || (HttpContext.Current.Request.Cookies["portalroles"].Value == string.Empty) || (HttpContext.Current.Request.Cookies["portalroles"].Expires < DateTime.Now)) //{ try { // Get roles from UserRoles table, and add to cookie UsersDB accountSystem = new UsersDB(); MembershipUser u = accountSystem.GetSingleUser(HttpContext.Current.User.Identity.Name, portalSettings.PortalAlias); roles = accountSystem.GetRoles(u.Email, portalSettings.PortalAlias); } catch (Exception exc) { ErrorHandler.Publish(LogLevel.Error, exc); //no roles roles = new List<AppleseedRole>(); } // // Create a string to persist the roles // string roleStr = string.Empty; // foreach ( AppleseedRole role in roles ) // { // roleStr += role.Name; // roleStr += ";"; // } // // Create a cookie authentication ticket. // FormsAuthenticationTicket ticket = new FormsAuthenticationTicket // ( // 1, // version // HttpContext.Current.User.Identity.Name, // user name // DateTime.Now, // issue time // DateTime.Now.AddHours(1), // expires every hour // false, // don't persist cookie // roleStr // roles // ); // // Encrypt the ticket // string cookieStr = FormsAuthentication.Encrypt(ticket); // // Send the cookie to the client // HttpContext.Current.Response.Cookies["portalroles"].Value = cookieStr; // HttpContext.Current.Response.Cookies["portalroles"].Path = "/"; // HttpContext.Current.Response.Cookies["portalroles"].Expires = DateTime.Now.AddMinutes(1); //} //else //{ // // Get roles from roles cookie // FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(HttpContext.Current.Request.Cookies["portalroles"].Value); // //convert the string representation of the role data into a string array // ArrayList userRoles = new ArrayList(); // //by Jes // string _ticket = ticket.UserData.TrimEnd(new char[] {';'}); // foreach (string role in _ticket.Split(new char[] {';'} )) // { // userRoles.Add(role + ";"); // } // roles = (string[]) userRoles.ToArray(typeof(string)); //} return roles; } } }
/* This file is licensed 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.Collections.Generic; using System.Linq; using System.Xml; using NUnit.Framework.Constraints; using Org.XmlUnit.Builder; using Org.XmlUnit.Diff; namespace Org.XmlUnit.Constraints { /// <summary> /// Constraint that compares two XML sources with each other. /// </summary> public class CompareConstraint : Constraint, IDifferenceEngineConfigurer<CompareConstraint> { private readonly DiffBuilder diffBuilder; private ComparisonResult checkFor; private bool formatXml; private IComparisonFormatter comparisonFormatter = new DefaultComparisonFormatter(); private CompareConstraint(object control) { diffBuilder = DiffBuilder.Compare(control); } /// <summary> /// Create a CompareConstraint which compares the /// test-Object with the given control Object for identity. /// </summary> public static CompareConstraint IsIdenticalTo(object control) { return new CompareConstraint(control).CheckForIdentical(); } /// <summary> /// Create a CompareConstraint which compares the /// test-Object with the given control Object for similarity. /// </summary> /// <remarks> /// <para> /// Example for Similar: The XML node /// "&lt;a&gt;Text&lt;/a&gt;" and /// "&lt;a&gt;&lt;![CDATA[Text]]&gt;&lt;/a&gt;" are /// similar and the Test will not fail. /// </para> /// </remarks> public static CompareConstraint IsSimilarTo(object control) { return new CompareConstraint(control).CheckForSimilar(); } private CompareConstraint CheckForSimilar() { diffBuilder.CheckForSimilar(); checkFor = ComparisonResult.SIMILAR; return this; } private CompareConstraint CheckForIdentical() { diffBuilder.CheckForIdentical(); checkFor = ComparisonResult.EQUAL; return this; } /// <summary> /// Ignore whitespace differences. /// </summary> public CompareConstraint IgnoreWhitespace() { formatXml = true; diffBuilder.IgnoreWhitespace(); return this; } /// <summary> /// Ignore element content whitespace differences. /// </summary> /// <remarks> /// <para> /// since XMLUnit 2.6.0 /// </para> /// </remarks> public CompareConstraint IgnoreElementContentWhitespace() { diffBuilder.IgnoreElementContentWhitespace(); return this; } /// <summary> /// Normalize whitespace before comparing. /// </summary> public CompareConstraint NormalizeWhitespace() { formatXml = true; diffBuilder.NormalizeWhitespace(); return this; } /// <summary> /// Ignore comments. /// </summary> public CompareConstraint IgnoreComments() { diffBuilder.IgnoreComments(); return this; } /// <summary> /// Ignore comments. /// </summary> /// <remarks> /// <para> /// since XMLUnit 2.5.0 /// </para> /// </remarks> /// <param name="xsltVersion">use this version for the stylesheet</param> public CompareConstraint IgnoreCommentsUsingXSLTVersion(string xsltVersion) { diffBuilder.IgnoreCommentsUsingXSLTVersion(xsltVersion); return this; } /// <summary> /// Use the given <see cref="INodeMatcher"/> when comparing. /// </summary> /// <param name="nodeMatcher">INodeMatcher to use</param> public CompareConstraint WithNodeMatcher(INodeMatcher nodeMatcher) { diffBuilder.WithNodeMatcher(nodeMatcher); return this; } /// <summary> /// Use the given <see cref="DifferenceEvaluator"/> when comparing. /// </summary> /// <param name="differenceEvaluator">DifferenceEvaluator to use</param> public CompareConstraint WithDifferenceEvaluator(DifferenceEvaluator differenceEvaluator) { diffBuilder.WithDifferenceEvaluator(differenceEvaluator); return this; } /// <summary> /// Use the given <see cref="ComparisonListener"/>s when comparing. /// </summary> /// <param name="comparisonListeners">ComparisonListeners to use</param> public CompareConstraint WithComparisonListeners(params ComparisonListener[] comparisonListeners) { diffBuilder.WithComparisonListeners(comparisonListeners); return this; } /// <summary> /// Use the given <see cref="ComparisonListener"/>s as difference listeners when comparing. /// </summary> /// <param name="comparisonListeners">ComparisonListeners to use</param> public CompareConstraint WithDifferenceListeners(params ComparisonListener[] comparisonListeners) { diffBuilder.WithDifferenceListeners(comparisonListeners); return this; } /// <summary> /// Use a custom Formatter for the Error Messages. The defaultFormatter is DefaultComparisonFormatter. /// </summary> public CompareConstraint WithComparisonFormatter(IComparisonFormatter comparisonFormatter) { this.comparisonFormatter = comparisonFormatter; return this; } /// <summary> /// Registers a filter for attributes. /// </summary> /// <remarks> /// <para> /// Only attributes for which the predicate returns true are /// part of the comparison. By default all attributes are /// considered. /// </para> /// <para> /// The "special" namespace, namespace-location and /// schema-instance-type attributes can not be ignored this way. /// If you want to suppress comparison of them you'll need to /// implement <see cref="DifferenceEvaluator"/> /// </para> /// </remarks> public CompareConstraint WithAttributeFilter(Predicate<XmlAttribute> attributeFilter) { diffBuilder.WithAttributeFilter(attributeFilter); return this; } /// <summary> /// Registers a filter for nodes. /// </summary> /// <remarks> /// <para> /// Only nodes for which the predicate returns true are part /// of the comparison. By default nodes that are neither /// document types nor XML declarations are considered. /// </para> /// </remarks> public CompareConstraint WithNodeFilter(Predicate<XmlNode> nodeFilter) { diffBuilder.WithNodeFilter(nodeFilter); return this; } /// <summary> /// Establish a namespace context mapping from prefix to URI /// that will be used in Comparison.Detail.XPath. /// </summary> /// <remarks> /// Without a namespace context (or with an empty context) the /// XPath expressions will only use local names for elements and /// attributes. /// </remarks> public CompareConstraint WithNamespaceContext(IDictionary<string, string> ctx) { diffBuilder.WithNamespaceContext(ctx); return this; } /// <summary> /// Throws an exception as you the ComparisonController is /// completely determined by the factory method used. /// </summary> /// <remarks> /// <para> /// since XMLUnit 2.5.1 /// </para> /// </remarks> public CompareConstraint WithComparisonController(ComparisonController cc) { throw new NotImplementedException("Can't set ComparisonController with CompareConstraint"); } /// <inheritdoc/> public override ConstraintResult ApplyTo<TActual>(TActual actual) { if (checkFor == ComparisonResult.EQUAL) { diffBuilder.WithComparisonController(ComparisonControllers.StopWhenSimilar); } else if (checkFor == ComparisonResult.SIMILAR) { diffBuilder.WithComparisonController(ComparisonControllers.StopWhenDifferent); } Diff.Diff diffResult = diffBuilder.WithTest(actual).Build(); Description = "is " + (checkFor == ComparisonResult.EQUAL ? "equal" : "similar") + " to the control document"; return new CompareConstraintResult(this, actual, diffResult); } /// <summary> /// Result of a CompareConstraint. /// </summary> public class CompareConstraintResult : ConstraintResult { private readonly CompareConstraint constraint; private readonly Diff.Diff diffResult; /// <summary> /// Creates the result. /// </summary> public CompareConstraintResult(CompareConstraint constraint, object actualValue, Diff.Diff diffResult) : base(constraint, actualValue, !diffResult.HasDifferences()) { this.constraint = constraint; this.diffResult = diffResult; } /// <inheritdoc/> public override void WriteMessageTo(MessageWriter writer) { Comparison c = diffResult.Differences.First().Comparison; writer.WriteMessageLine(constraint.comparisonFormatter.GetDescription(c)); if (diffResult.TestSource.SystemId != null || diffResult.ControlSource.SystemId != null) { writer.WriteMessageLine(string.Format("comparing {0} to {1}", diffResult.TestSource.SystemId, diffResult.ControlSource.SystemId)); } writer.DisplayDifferences(GetDetails(c.ControlDetails, c.Type), GetDetails(c.TestDetails, c.Type)); } private string GetDetails(Comparison.Detail detail, ComparisonType type) { return constraint.comparisonFormatter.GetDetails(detail, type, constraint.formatXml); } } } }
using System; using System.Text; using System.Reflection; using System.IO; using System.Collections.Generic; using Decal.Adapter; namespace PhatACUtil { [FriendlyName("PhatACUtil")] public partial class PluginCore : PluginBase { static string log_path; static string model_path; internal static Decal.Adapter.Wrappers.PluginHost MyHost; internal static Dictionary<int, string> models; internal static List<string> towns; protected override void Startup() { log_path = Path.ToString() + "\\error.txt"; MyHost = Host; // Init views etc try { // Load data models = LoadModels(); towns = new List<string>() { "Aerlinthe Island", "Ahurenga", "Al-Arqas", "Al-Jalima", "Arwic", "Ayan Baqur", "Baishi", "Bandit Castle", "Beach Fort", "Bluespire", "Candeth Keep", "Cragstone", "Mt Esper-Crater Village", "Danby's Outpost", "Dryreach", "Eastham", "Fort Tethana", "Glenden Wood", "Greenspire", "Hebian-to", "Holtburg", "Kara", "Khayyaban", "Kryst", "Lin", "Linvak Tukal", "Lytelthorpe", "MacNiall's Freehold", "Mayoi", "Nanto", "Neydisa", "Oolutanga's Refuge", "Plateau Village", "Qalaba'r", "Redspire", "Rithwic", "Samsur", "Sawato", "Shoushi", "Singularity Caul Island", "Stonehold", "Timaru", "Tou-Tou", "Tufa", "Underground City", "Uziz", "Wai Jhou", "Xarabydun", "Yanshi", "Yaraq", "Zaikhal", "Picture Room 1", "Cheese Room", "Picture Room 2", "Campfire room", "Picture Room 3", "AdminLS", "Shadow Spire" }; // Set up views MainView.ViewInit(); } catch (Exception ex) { LogError(ex); } } protected override void Shutdown() { try { MainView.ViewDestroy(); models = null; } catch (Exception ex) { LogError(ex); } MyHost = null; } public static void LogMessage(String msg) { try { StreamWriter sw = new StreamWriter(log_path, true); sw.WriteLine(msg); sw.Close(); } catch (Exception ex) { LogError(ex); } } public static void LogError(Exception ex) { try { StreamWriter sw = new StreamWriter(log_path, true); sw.WriteLine("============================================================================"); sw.WriteLine(DateTime.Now.ToString()); sw.WriteLine("Error: " + ex.Message); sw.WriteLine("Source: " + ex.Source); sw.WriteLine("Stack: " + ex.StackTrace); if (ex.InnerException != null) { sw.WriteLine("Inner: " + ex.InnerException.Message); sw.WriteLine("Inner Stack: " + ex.InnerException.StackTrace); } sw.WriteLine("============================================================================"); sw.WriteLine(""); sw.Close(); } catch (Exception exc) { } } static void Chat(String msg) { try { MyHost.Actions.AddChatText(msg, 0, 1); } catch (Exception ex) { LogError(ex); } } static Dictionary<int, string> LoadModels() { Assembly assembly = Assembly.GetExecutingAssembly(); Dictionary<int, string> models = new Dictionary<int, string>(); StreamReader sr = new StreamReader(assembly.GetManifestResourceStream("PhatACUtil.Data.models.csv")); String[] tokens; string line; string name; try { while ((line = sr.ReadLine()) != null) { tokens = line.Split(','); name = tokens[1].Replace("\"", ""); models.Add(int.Parse(tokens[0], System.Globalization.NumberStyles.HexNumber),name ); } } catch (Exception ex) { LogError(ex); } return models; } public static void ChatMessage(string message) { MyHost.Actions.AddChatText(message, 1); } public static void ChatCommand(string command, params string[] tokens) { StringBuilder sb = new StringBuilder(); sb.Append("@"); sb.Append(command); sb.Append(" "); foreach (string token in tokens) { sb.Append(token.Trim()); sb.Append(' '); } try { ChatMessage(sb.ToString()); PluginCore.MyHost.Actions.InvokeChatParser(sb.ToString()); } catch (Exception ex) { PluginCore.LogError(ex); } } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public sealed class DelegationCache { class Entry { // // State // System.Reflection.MethodInfo m_source; Delegate m_dlg; AbstractHandlerAttribute m_context; PhaseFilterAttribute[] m_phaseFilters; // // Constructor Methods // internal Entry( System.Reflection.MethodInfo source , Delegate dlg , AbstractHandlerAttribute context ) { m_source = source; m_dlg = dlg; m_context = context; m_phaseFilters = ReflectionHelper.GetAttributes< PhaseFilterAttribute >( source, false ); } // // Helper Methods // internal bool ShouldProcess( PhaseDriver phase , int pass ) { if(pass == 0) { foreach(PhaseFilterAttribute pf in m_phaseFilters) { if(pf.Target == phase.GetType()) { return true; } } } else { if(m_phaseFilters.Length == 0) { // // No filter => always on. But process after any entry that has a filter. // return true; } } return false; } // // Access Methods // internal System.Reflection.MethodInfo Source { get { return m_source; } } internal PhaseDriver.Notification DelegateForPhase { get { return (PhaseDriver.Notification)m_dlg; } } internal PhaseExecution.NotificationOfTransformation DelegateForPhaseExecution { get { return (PhaseExecution.NotificationOfTransformation)m_dlg; } } internal PhaseExecution.NotificationOfTransformationForAttribute DelegateForPhaseExecutionForAttribute { get { return (PhaseExecution.NotificationOfTransformationForAttribute)m_dlg; } } internal ComputeCallsClosure.Notification DelegateForCallClosure { get { return (ComputeCallsClosure.Notification)m_dlg; } } internal AbstractHandlerAttribute Context { get { return m_context; } } } // // State // private readonly TypeSystemForCodeTransformation m_typeSystem; private List< Entry > m_entries; // // Constructor Methods // public DelegationCache( TypeSystemForCodeTransformation typeSystem ) { m_typeSystem = typeSystem; m_entries = new List< Entry >(); } // // Helper Methods // public void Register( object instance ) { Type t = instance.GetType(); while(t != null) { foreach(var mi in t.GetMethods( System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic )) { HookCustomAttributeNotifications( mi, instance ); HookNewEntityNotifications ( mi, instance ); CreateHandlers ( mi, instance ); } var cfgProv = m_typeSystem.GetEnvironmentService< IConfigurationProvider >(); if(cfgProv != null) { foreach(var mi in ReflectionHelper.GetAllFields( t )) { foreach(var attr in ReflectionHelper.GetAttributes< Runtime.ConfigurationOptionAttribute >( mi, false )) { object val; if(cfgProv.GetValue( attr.Name, out val )) { if(mi.IsStatic) { mi.SetValue( null, val ); } else { mi.SetValue( instance, val ); } } } } } t = t.BaseType; } } private void CreateHandlers( System.Reflection.MethodInfo mi , object instance ) { foreach(AbstractHandlerAttribute attrib in ReflectionHelper.GetAttributes< AbstractHandlerAttribute >( mi, false )) { try { Type type; if(attrib is CallClosureHandlerAttribute) { type = typeof(ComputeCallsClosure.Notification); } else if(attrib is PrePhaseHandlerAttribute || attrib is PostPhaseHandlerAttribute ) { type = typeof(PhaseDriver.Notification); } else if(attrib is CustomAttributeHandlerAttribute) { type = typeof(PhaseExecution.NotificationOfTransformationForAttribute); } else { type = typeof(PhaseExecution.NotificationOfTransformation); } Entry en = new Entry( mi, CreateNotification( type, mi, instance ), attrib ); m_entries.Add( en ); } catch(Exception ex) { throw TypeConsistencyErrorException.Create( "Got the following error while trying to create a notification handler for {0}:\n{1}", attrib, ex.ToString() ); } } } private void HookNewEntityNotifications( System.Reflection.MethodInfo mi , object instance ) { if(ReflectionHelper.HasAttribute< CompilationSteps.NewEntityNotificationAttribute >( mi, false )) { System.Reflection.ParameterInfo[] parameters = mi.GetParameters(); if(parameters != null && parameters.Length == 1) { Type paramEntity = parameters[0].ParameterType; if(paramEntity == typeof(TypeRepresentation)) { var dlg = (TypeSystem.NotificationOfNewType)CreateNotification( typeof(TypeSystem.NotificationOfNewType), mi, instance ); m_typeSystem.RegisterForNewType( dlg ); return; } if(paramEntity == typeof(FieldRepresentation)) { var dlg = (TypeSystem.NotificationOfNewField)CreateNotification( typeof(TypeSystem.NotificationOfNewField), mi, instance ); m_typeSystem.RegisterForNewField( dlg ); return; } if(paramEntity == typeof(MethodRepresentation)) { var dlg = (TypeSystem.NotificationOfNewMethod)CreateNotification( typeof(TypeSystem.NotificationOfNewMethod), mi, instance ); m_typeSystem.RegisterForNewMethod( dlg ); return; } } throw TypeConsistencyErrorException.Create( "Method '{0}' cannot be used for new entity notification", mi ); } } //--// private void HookCustomAttributeNotifications( System.Reflection.MethodInfo mi , object instance ) { foreach(var attrib in ReflectionHelper.GetAttributes< CompilationSteps.CustomAttributeNotificationAttribute >( mi, false )) { TypeRepresentation td = m_typeSystem.GetWellKnownTypeNoThrow( attrib.Target ); if(td == null) { throw TypeConsistencyErrorException.Create( "Failed to create custom attribute notification because type '{0}' is not well-known", attrib.Target ); } System.Reflection.ParameterInfo[] parameters = mi.GetParameters(); if(parameters != null && parameters.Length >= 3) { Type paramTypeKeep = parameters[0].ParameterType; Type paramTypeCa = parameters[1].ParameterType; Type paramTypeOwner = parameters[2].ParameterType; if(paramTypeKeep.IsByRef && paramTypeKeep.GetElementType() == typeof(bool) && paramTypeCa == typeof(CustomAttributeRepresentation) ) { if(paramTypeOwner == typeof(BaseRepresentation) && parameters.Length == 3) { var dlg = (TypeSystem.NotificationOfAttributeOnGeneric)CreateNotification( typeof(TypeSystem.NotificationOfAttributeOnGeneric), mi, instance ); m_typeSystem.RegisterForNotificationOfAttributeOnGeneric( td, dlg ); continue; } if(paramTypeOwner == typeof(TypeRepresentation) && parameters.Length == 3) { var dlg = (TypeSystem.NotificationOfAttributeOnType)CreateNotification( typeof(TypeSystem.NotificationOfAttributeOnType), mi, instance ); m_typeSystem.RegisterForNotificationOfAttributeOnType( td, dlg ); continue; } if(paramTypeOwner == typeof(FieldRepresentation) && parameters.Length == 3) { var dlg = (TypeSystem.NotificationOfAttributeOnField)CreateNotification( typeof(TypeSystem.NotificationOfAttributeOnField), mi, instance ); m_typeSystem.RegisterForNotificationOfAttributeOnField( td, dlg ); continue; } if(paramTypeOwner == typeof(MethodRepresentation)) { if(parameters.Length == 3) { var dlg = (TypeSystem.NotificationOfAttributeOnMethod)CreateNotification( typeof(TypeSystem.NotificationOfAttributeOnMethod), mi, instance ); m_typeSystem.RegisterForNotificationOfAttributeOnMethod( td, dlg ); continue; } if(parameters.Length == 4 && parameters[3].ParameterType == typeof(int)) { var dlg = (TypeSystem.NotificationOfAttributeOnParam)CreateNotification( typeof(TypeSystem.NotificationOfAttributeOnParam), mi, instance ); m_typeSystem.RegisterForNotificationOfAttributeOnParam( td, dlg ); continue; } } } } throw TypeConsistencyErrorException.Create( "Method '{0}' cannot be used for custom attribute notification", mi ); } } //--// public void HookNotifications( TypeSystemForCodeTransformation typeSystem , PhaseDriver phase ) { for(int pass = 0; pass < 2; pass++) { foreach(Entry en in m_entries) { if(en.ShouldProcess( phase, pass )) { if(en.Context is PrePhaseHandlerAttribute) { phase.RegisterForNotification( en.DelegateForPhase, true ); } if(en.Context is PostPhaseHandlerAttribute) { phase.RegisterForNotification( en.DelegateForPhase, false ); } } } } } public void HookNotifications( TypeSystemForCodeTransformation typeSystem , PhaseExecution pe , PhaseDriver phase ) { for(int pass = 0; pass < 2; pass++) { foreach(Entry en in m_entries) { if(en.ShouldProcess( phase, pass )) { if(en.Context is OptimizationHandlerAttribute) { OptimizationHandlerAttribute ca = (OptimizationHandlerAttribute)en.Context; pe.RegisterForNotificationOfOptimization( ca, en.DelegateForPhaseExecution ); } if(en.Context is PreFlowGraphHandlerAttribute) { pe.RegisterForNotificationOfFlowGraph( en.DelegateForPhaseExecution, true ); } if(en.Context is PostFlowGraphHandlerAttribute) { pe.RegisterForNotificationOfFlowGraph( en.DelegateForPhaseExecution, false ); } if(en.Context is OperatorHandlerAttribute) { OperatorHandlerAttribute ca = (OperatorHandlerAttribute)en.Context; pe.RegisterForNotificationOfOperatorsByType( ca.Target, en.DelegateForPhaseExecution ); } if(en.Context is OperatorArgumentHandlerAttribute) { OperatorArgumentHandlerAttribute ca = (OperatorArgumentHandlerAttribute)en.Context; pe.RegisterForNotificationOfOperatorByTypeOfArguments( ca.Target, en.DelegateForPhaseExecution ); } if(en.Context is WellKnownTypeHandlerAttribute) { WellKnownTypeHandlerAttribute ca = (WellKnownTypeHandlerAttribute)en.Context; pe.RegisterForNotificationOfOperatorByEntities( typeSystem.GetWellKnownTypeNoThrow( ca.Target ), en.DelegateForPhaseExecution ); } if(en.Context is WellKnownFieldHandlerAttribute) { WellKnownFieldHandlerAttribute ca = (WellKnownFieldHandlerAttribute)en.Context; pe.RegisterForNotificationOfOperatorByEntities( typeSystem.GetWellKnownFieldNoThrow( ca.Target ), en.DelegateForPhaseExecution ); } if(en.Context is WellKnownMethodHandlerAttribute) { WellKnownMethodHandlerAttribute ca = (WellKnownMethodHandlerAttribute)en.Context; pe.RegisterForNotificationOfOperatorByEntities( typeSystem.GetWellKnownMethodNoThrow( ca.Target ), en.DelegateForPhaseExecution ); } if(en.Context is CallToWellKnownMethodHandlerAttribute) { CallToWellKnownMethodHandlerAttribute ca = (CallToWellKnownMethodHandlerAttribute)en.Context; pe.RegisterForNotificationOfCallOperatorByEntities( typeSystem.GetWellKnownMethodNoThrow( ca.Target ), en.DelegateForPhaseExecution ); } if(en.Context is CustomAttributeHandlerAttribute) { CustomAttributeHandlerAttribute ca = (CustomAttributeHandlerAttribute)en.Context; TypeRepresentation targetType = typeSystem.GetWellKnownTypeNoThrow( ca.FieldName ); if(targetType != null) { var dlg = en.DelegateForPhaseExecutionForAttribute; typeSystem.EnumerateCustomAttributes( delegate( CustomAttributeAssociationRepresentation caa ) { if(caa.CustomAttribute.Constructor.OwnerType == targetType) { BaseRepresentation bdTarget = caa.Target; if(bdTarget != null) { pe.RegisterForNotificationOfOperatorByEntities( bdTarget, nc => dlg( nc, caa.CustomAttribute ) ); } } } ); } } } } } } internal void HookNotifications( TypeSystemForCodeTransformation typeSystem , ComputeCallsClosure cc , PhaseDriver phase ) { for(int pass = 0; pass < 2; pass++) { foreach(Entry en in m_entries) { if(en.ShouldProcess( phase, pass )) { if(en.Context is CallClosureHandlerAttribute) { CallClosureHandlerAttribute ca = (CallClosureHandlerAttribute)en.Context; cc.RegisterForNotification( ca.Target, en.DelegateForCallClosure ); } } } } } //--// private static Delegate CreateNotification( Type type , System.Reflection.MethodInfo mi , object instance ) { try { if(mi.IsStatic) { return Delegate.CreateDelegate( type, mi, true ); } else { return Delegate.CreateDelegate( type, instance, mi, true ); } } catch(Exception ex) { throw TypeConsistencyErrorException.Create( "Got the following error while trying to create a notification handler for {0}:\n{1}", mi, ex.ToString() ); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using WebApiCors2.Areas.HelpPage.Models; namespace WebApiCors2.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Collections.Generic; using System.Data.SqlTypes; using System.Data.Common; namespace System.Data { internal sealed class DataExpression : IFilter { internal string _originalExpression = null; // original, unoptimized string private readonly bool _parsed = false; private bool _bound = false; private ExpressionNode _expr = null; private DataTable _table = null; private readonly StorageType _storageType; private readonly Type _dataType; // This set if the expression is part of ExpressionCoulmn private DataColumn[] _dependency = Array.Empty<DataColumn>(); internal DataExpression(DataTable table, string expression) : this(table, expression, null) { } internal DataExpression(DataTable table, string expression, Type type) { ExpressionParser parser = new ExpressionParser(table); parser.LoadExpression(expression); _originalExpression = expression; _expr = null; if (expression != null) { _storageType = DataStorage.GetStorageType(type); if (_storageType == StorageType.BigInteger) { throw ExprException.UnsupportedDataType(type); } _dataType = type; _expr = parser.Parse(); _parsed = true; if (_expr != null && table != null) { Bind(table); } else { _bound = false; } } } internal string Expression { get { return (_originalExpression != null ? _originalExpression : ""); // CONSIDER: return optimized expression here (if bound) } } internal ExpressionNode ExpressionNode { get { return _expr; } } internal bool HasValue { get { return (null != _expr); } } internal void Bind(DataTable table) { _table = table; if (table == null) return; if (_expr != null) { Debug.Assert(_parsed, "Invalid calling order: Bind() before Parse()"); List<DataColumn> list = new List<DataColumn>(); _expr.Bind(table, list); _expr = _expr.Optimize(); _table = table; _bound = true; _dependency = list.ToArray(); } } internal bool DependsOn(DataColumn column) { if (_expr != null) { return _expr.DependsOn(column); } else { return false; } } internal object Evaluate() { return Evaluate((DataRow)null, DataRowVersion.Default); } internal object Evaluate(DataRow row, DataRowVersion version) { object result; if (!_bound) { Bind(_table); } if (_expr != null) { result = _expr.Eval(row, version); // if the type is a SqlType (StorageType.Uri < _storageType), convert DBNull values. if (result != DBNull.Value || StorageType.Uri < _storageType) { // we need to convert the return value to the column.Type; try { if (StorageType.Object != _storageType) { result = SqlConvert.ChangeType2(result, _storageType, _dataType, _table.FormatProvider); } } catch (Exception e) when (ADP.IsCatchableExceptionType(e)) { ExceptionBuilder.TraceExceptionForCapture(e); throw ExprException.DatavalueConvertion(result, _dataType, e); } } } else { result = null; } return result; } internal object Evaluate(DataRow[] rows) { return Evaluate(rows, DataRowVersion.Default); } internal object Evaluate(DataRow[] rows, DataRowVersion version) { if (!_bound) { Bind(_table); } if (_expr != null) { List<int> recordList = new List<int>(); foreach (DataRow row in rows) { if (row.RowState == DataRowState.Deleted) continue; if (version == DataRowVersion.Original && row._oldRecord == -1) continue; recordList.Add(row.GetRecordFromVersion(version)); } int[] records = recordList.ToArray(); return _expr.Eval(records); } else { return DBNull.Value; } } public bool Invoke(DataRow row, DataRowVersion version) { if (_expr == null) return true; if (row == null) { throw ExprException.InvokeArgument(); } object val = _expr.Eval(row, version); bool result; try { result = ToBoolean(val); } catch (EvaluateException) { throw ExprException.FilterConvertion(Expression); } return result; } internal DataColumn[] GetDependency() { Debug.Assert(_dependency != null, "GetDependencies: null, we should have created an empty list"); return _dependency; } internal bool IsTableAggregate() { if (_expr != null) return _expr.IsTableConstant(); else return false; } internal static bool IsUnknown(object value) { return DataStorage.IsObjectNull(value); } internal bool HasLocalAggregate() { if (_expr != null) return _expr.HasLocalAggregate(); else return false; } internal bool HasRemoteAggregate() { if (_expr != null) return _expr.HasRemoteAggregate(); else return false; } internal static bool ToBoolean(object value) { if (IsUnknown(value)) return false; if (value is bool) return (bool)value; if (value is SqlBoolean) { return (((SqlBoolean)value).IsTrue); } //check for SqlString is not added, value for true and false should be given with String, not with SqlString if (value is string) { try { return bool.Parse((string)value); } catch (Exception e) when (ADP.IsCatchableExceptionType(e)) { ExceptionBuilder.TraceExceptionForCapture(e); throw ExprException.DatavalueConvertion(value, typeof(bool), e); } } throw ExprException.DatavalueConvertion(value, typeof(bool), 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. /****************************************************************************** * 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.Reflection; 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 ConvertToVector256Int64Int32() { var test = new SimpleUnaryOpTest__ConvertToVector256Int64Int32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates basic functionality works, using the pointer overload test.RunBasicScenario_Ptr(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates calling via reflection works, using the pointer overload test.RunReflectionScenario_Ptr(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local 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 SimpleUnaryOpTest__ConvertToVector256Int64Int32 { private const int VectorSize = 32; private const int Op1ElementCount = 16 / sizeof(Int32); private const int RetElementCount = VectorSize / sizeof(Int64); private static Int32[] _data = new Int32[Op1ElementCount]; private static Vector128<Int32> _clsVar; private Vector128<Int32> _fld; private SimpleUnaryOpTest__DataTable<Int64, Int32> _dataTable; static SimpleUnaryOpTest__ConvertToVector256Int64Int32() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), 16); } public SimpleUnaryOpTest__ConvertToVector256Int64Int32() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), 16); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } _dataTable = new SimpleUnaryOpTest__DataTable<Int64, Int32>(_data, new Int64[RetElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.ConvertToVector256Int64( Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Ptr() { var result = Avx2.ConvertToVector256Int64( (Int32*)(_dataTable.inArrayPtr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.ConvertToVector256Int64( Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.ConvertToVector256Int64( Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ConvertToVector256Int64), new Type[] { typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Ptr() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ConvertToVector256Int64), new Type[] { typeof(Int32*) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArrayPtr, typeof(Int32*)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ConvertToVector256Int64), new Type[] { typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ConvertToVector256Int64), new Type[] { typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.ConvertToVector256Int64( _clsVar ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr); var result = Avx2.ConvertToVector256Int64(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)); var result = Avx2.ConvertToVector256Int64(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)); var result = Avx2.ConvertToVector256Int64(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__ConvertToVector256Int64Int32(); var result = Avx2.ConvertToVector256Int64(test._fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.ConvertToVector256Int64(_fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Int32> firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), 16); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int32[] firstOp, Int64[] result, [CallerMemberName] string method = "") { if (result[0] != firstOp[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != firstOp[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.ConvertToVector256Int64)}<Int64>(Vector128<Int32>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Nop.Core; using Nop.Core.Data; using Nop.Core.Domain.Catalog; using Nop.Core.Domain.Orders; using Nop.Core.Domain.Payments; using Nop.Core.Domain.Shipping; using Nop.Services.Catalog; using Nop.Services.Helpers; namespace Nop.Services.Orders { /// <summary> /// Order report service /// </summary> public partial class OrderReportService : IOrderReportService { #region Fields private readonly IRepository<Order> _orderRepository; private readonly IRepository<OrderItem> _orderItemRepository; private readonly IRepository<Product> _productRepository; private readonly IDateTimeHelper _dateTimeHelper; private readonly IProductService _productService; #endregion #region Ctor /// <summary> /// Ctor /// </summary> /// <param name="orderRepository">Order repository</param> /// <param name="orderItemRepository">Order item repository</param> /// <param name="productRepository">Product repository</param> /// <param name="dateTimeHelper">Datetime helper</param> /// <param name="productService">Product service</param> public OrderReportService(IRepository<Order> orderRepository, IRepository<OrderItem> orderItemRepository, IRepository<Product> productRepository, IDateTimeHelper dateTimeHelper, IProductService productService) { this._orderRepository = orderRepository; this._orderItemRepository = orderItemRepository; this._productRepository = productRepository; this._dateTimeHelper = dateTimeHelper; this._productService = productService; } #endregion #region Methods /// <summary> /// Get "order by country" report /// </summary> /// <param name="storeId">Store identifier</param> /// <param name="os">Order status</param> /// <param name="ps">Payment status</param> /// <param name="ss">Shipping status</param> /// <param name="startTimeUtc">Start date</param> /// <param name="endTimeUtc">End date</param> /// <returns>Result</returns> public virtual IList<OrderByCountryReportLine> GetCountryReport(int storeId, OrderStatus? os, PaymentStatus? ps, ShippingStatus? ss, DateTime? startTimeUtc, DateTime? endTimeUtc) { int? orderStatusId = null; if (os.HasValue) orderStatusId = (int)os.Value; int? paymentStatusId = null; if (ps.HasValue) paymentStatusId = (int)ps.Value; int? shippingStatusId = null; if (ss.HasValue) shippingStatusId = (int)ss.Value; var query = _orderRepository.Table; query = query.Where(o => !o.Deleted); if (storeId > 0) query = query.Where(o => o.StoreId == storeId); if (orderStatusId.HasValue) query = query.Where(o => o.OrderStatusId == orderStatusId.Value); if (paymentStatusId.HasValue) query = query.Where(o => o.PaymentStatusId == paymentStatusId.Value); if (shippingStatusId.HasValue) query = query.Where(o => o.ShippingStatusId == shippingStatusId.Value); if (startTimeUtc.HasValue) query = query.Where(o => startTimeUtc.Value <= o.CreatedOnUtc); if (endTimeUtc.HasValue) query = query.Where(o => endTimeUtc.Value >= o.CreatedOnUtc); var report = (from oq in query group oq by oq.BillingAddress.CountryId into result select new { CountryId = result.Key, TotalOrders = result.Count(), SumOrders = result.Sum(o => o.OrderTotal) } ) .OrderByDescending(x => x.SumOrders) .Select(r => new OrderByCountryReportLine() { CountryId = r.CountryId, TotalOrders = r.TotalOrders, SumOrders = r.SumOrders }) .ToList(); return report; } /// <summary> /// Get order average report /// </summary> /// <param name="storeId">Store identifier</param> /// <param name="vendorId">Vendor identifier</param> /// <param name="os">Order status</param> /// <param name="ps">Payment status</param> /// <param name="ss">Shipping status</param> /// <param name="startTimeUtc">Start date</param> /// <param name="endTimeUtc">End date</param> /// <param name="billingEmail">Billing email. Leave empty to load all records.</param> /// <param name="ignoreCancelledOrders">A value indicating whether to ignore cancelled orders</param> /// <returns>Result</returns> public virtual OrderAverageReportLine GetOrderAverageReportLine(int storeId, int vendorId, OrderStatus? os, PaymentStatus? ps, ShippingStatus? ss, DateTime? startTimeUtc, DateTime? endTimeUtc, string billingEmail, bool ignoreCancelledOrders = false) { int? orderStatusId = null; if (os.HasValue) orderStatusId = (int)os.Value; int? paymentStatusId = null; if (ps.HasValue) paymentStatusId = (int)ps.Value; int? shippingStatusId = null; if (ss.HasValue) shippingStatusId = (int)ss.Value; var query = _orderRepository.Table; query = query.Where(o => !o.Deleted); if (storeId > 0) query = query.Where(o => o.StoreId == storeId); if (vendorId > 0) { query = query .Where(o => o.OrderItems .Any(orderItem => orderItem.Product.VendorId == vendorId)); } if (ignoreCancelledOrders) { int cancelledOrderStatusId = (int)OrderStatus.Cancelled; query = query.Where(o => o.OrderStatusId != cancelledOrderStatusId); } if (orderStatusId.HasValue) query = query.Where(o => o.OrderStatusId == orderStatusId.Value); if (paymentStatusId.HasValue) query = query.Where(o => o.PaymentStatusId == paymentStatusId.Value); if (shippingStatusId.HasValue) query = query.Where(o => o.ShippingStatusId == shippingStatusId.Value); if (startTimeUtc.HasValue) query = query.Where(o => startTimeUtc.Value <= o.CreatedOnUtc); if (endTimeUtc.HasValue) query = query.Where(o => endTimeUtc.Value >= o.CreatedOnUtc); if (!String.IsNullOrEmpty(billingEmail)) query = query.Where(o => o.BillingAddress != null && !String.IsNullOrEmpty(o.BillingAddress.Email) && o.BillingAddress.Email.Contains(billingEmail)); var item = (from oq in query group oq by 1 into result select new { OrderCount = result.Count(), OrderShippingExclTaxSum = result.Sum(o => o.OrderShippingExclTax), OrderTaxSum = result.Sum(o => o.OrderTax), OrderTotalSum = result.Sum(o => o.OrderTotal) } ).Select(r => new OrderAverageReportLine() { CountOrders = r.OrderCount, SumShippingExclTax = r.OrderShippingExclTaxSum, SumTax = r.OrderTaxSum, SumOrders = r.OrderTotalSum }) .FirstOrDefault(); item = item ?? new OrderAverageReportLine() { CountOrders = 0, SumShippingExclTax = decimal.Zero, SumTax = decimal.Zero, SumOrders = decimal.Zero, }; return item; } /// <summary> /// Get order average report /// </summary> /// <param name="storeId">Store identifier</param> /// <param name="os">Order status</param> /// <returns>Result</returns> public virtual OrderAverageReportLineSummary OrderAverageReport(int storeId, OrderStatus os) { var item = new OrderAverageReportLineSummary(); item.OrderStatus = os; DateTime nowDt = _dateTimeHelper.ConvertToUserTime(DateTime.Now); TimeZoneInfo timeZone = _dateTimeHelper.CurrentTimeZone; //today DateTime t1 = new DateTime(nowDt.Year, nowDt.Month, nowDt.Day); if (!timeZone.IsInvalidTime(t1)) { DateTime? startTime1 = _dateTimeHelper.ConvertToUtcTime(t1, timeZone); DateTime? endTime1 = null; var todayResult = GetOrderAverageReportLine(storeId, 0, os, null,null, startTime1, endTime1, null); item.SumTodayOrders = todayResult.SumOrders; item.CountTodayOrders = todayResult.CountOrders; } //week DayOfWeek fdow = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek; DateTime today = new DateTime(nowDt.Year, nowDt.Month, nowDt.Day); DateTime t2 = today.AddDays(-(today.DayOfWeek - fdow)); if (!timeZone.IsInvalidTime(t2)) { DateTime? startTime2 = _dateTimeHelper.ConvertToUtcTime(t2, timeZone); DateTime? endTime2 = null; var weekResult = GetOrderAverageReportLine(storeId, 0, os, null, null, startTime2, endTime2, null); item.SumThisWeekOrders = weekResult.SumOrders; item.CountThisWeekOrders = weekResult.CountOrders; } //month DateTime t3 = new DateTime(nowDt.Year, nowDt.Month, 1); if (!timeZone.IsInvalidTime(t3)) { DateTime? startTime3 = _dateTimeHelper.ConvertToUtcTime(t3, timeZone); DateTime? endTime3 = null; var monthResult = GetOrderAverageReportLine(storeId, 0, os, null, null, startTime3, endTime3, null); item.SumThisMonthOrders = monthResult.SumOrders; item.CountThisMonthOrders = monthResult.CountOrders; } //year DateTime t4 = new DateTime(nowDt.Year, 1, 1); if (!timeZone.IsInvalidTime(t4)) { DateTime? startTime4 = _dateTimeHelper.ConvertToUtcTime(t4, timeZone); DateTime? endTime4 = null; var yearResult = GetOrderAverageReportLine(storeId, 0, os, null, null, startTime4, endTime4, null); item.SumThisYearOrders = yearResult.SumOrders; item.CountThisYearOrders = yearResult.CountOrders; } //all time DateTime? startTime5 = null; DateTime? endTime5 = null; var allTimeResult = GetOrderAverageReportLine(storeId, 0, os, null, null, startTime5, endTime5, null); item.SumAllTimeOrders = allTimeResult.SumOrders; item.CountAllTimeOrders = allTimeResult.CountOrders; return item; } /// <summary> /// Get best sellers report /// </summary> /// <param name="storeId">Store identifier; 0 to load all records</param> /// <param name="vendorId">Vendor identifier; 0 to load all records</param> /// <param name="categoryId">Category identifier; 0 to load all records</param> /// <param name="manufacturerId">Manufacturer identifier; 0 to load all records</param> /// <param name="createdFromUtc">Order created date from (UTC); null to load all records</param> /// <param name="createdToUtc">Order created date to (UTC); null to load all records</param> /// <param name="os">Order status; null to load all records</param> /// <param name="ps">Order payment status; null to load all records</param> /// <param name="ss">Shipping status; null to load all records</param> /// <param name="billingCountryId">Billing country identifier; 0 to load all records</param> /// <param name="orderBy">1 - order by quantity, 2 - order by total amount</param> /// <param name="pageIndex">Page index</param> /// <param name="pageSize">Page size</param> /// <param name="showHidden">A value indicating whether to show hidden records</param> /// <returns>Result</returns> public virtual IPagedList<BestsellersReportLine> BestSellersReport( int categoryId = 0, int manufacturerId = 0, int storeId = 0, int vendorId = 0, DateTime? createdFromUtc = null, DateTime? createdToUtc = null, OrderStatus? os = null, PaymentStatus? ps = null, ShippingStatus? ss = null, int billingCountryId = 0, int orderBy = 1, int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false) { int? orderStatusId = null; if (os.HasValue) orderStatusId = (int)os.Value; int? paymentStatusId = null; if (ps.HasValue) paymentStatusId = (int)ps.Value; int? shippingStatusId = null; if (ss.HasValue) shippingStatusId = (int)ss.Value; var query1 = from orderItem in _orderItemRepository.Table join o in _orderRepository.Table on orderItem.OrderId equals o.Id join p in _productRepository.Table on orderItem.ProductId equals p.Id //join pc in _productCategoryRepository.Table on p.Id equals pc.ProductId into p_pc from pc in p_pc.DefaultIfEmpty() //join pm in _productManufacturerRepository.Table on p.Id equals pm.ProductId into p_pm from pm in p_pm.DefaultIfEmpty() where (storeId == 0 || storeId == o.StoreId) && (!createdFromUtc.HasValue || createdFromUtc.Value <= o.CreatedOnUtc) && (!createdToUtc.HasValue || createdToUtc.Value >= o.CreatedOnUtc) && (!orderStatusId.HasValue || orderStatusId == o.OrderStatusId) && (!paymentStatusId.HasValue || paymentStatusId == o.PaymentStatusId) && (!shippingStatusId.HasValue || shippingStatusId == o.ShippingStatusId) && (!o.Deleted) && (!p.Deleted) && (vendorId == 0 || p.VendorId == vendorId) && //(categoryId == 0 || pc.CategoryId == categoryId) && //(manufacturerId == 0 || pm.ManufacturerId == manufacturerId) && (categoryId == 0 || p.ProductCategories.Count(pc => pc.CategoryId == categoryId) > 0) && (manufacturerId == 0 || p.ProductManufacturers.Count(pm => pm.ManufacturerId == manufacturerId) > 0) && (billingCountryId == 0 || o.BillingAddress.CountryId == billingCountryId) && (showHidden || p.Published) select orderItem; IQueryable<BestsellersReportLine> query2 = //group by products from orderItem in query1 group orderItem by orderItem.ProductId into g select new BestsellersReportLine() { ProductId = g.Key, TotalAmount = g.Sum(x => x.PriceExclTax), TotalQuantity = g.Sum(x => x.Quantity), } ; switch (orderBy) { case 1: { query2 = query2.OrderByDescending(x => x.TotalQuantity); } break; case 2: { query2 = query2.OrderByDescending(x => x.TotalAmount); } break; default: throw new ArgumentException("Wrong orderBy parameter", "orderBy"); } var result = new PagedList<BestsellersReportLine>(query2, pageIndex, pageSize); return result; } /// <summary> /// Gets a list of products (identifiers) purchased by other customers who purchased a specified product /// </summary> /// <param name="storeId">Store identifier</param> /// <param name="productId">Product identifier</param> /// <param name="recordsToReturn">Records to return</param> /// <param name="showHidden">A value indicating whether to show hidden records</param> /// <returns>Products</returns> public virtual int[] GetAlsoPurchasedProductsIds(int storeId, int productId, int recordsToReturn = 5, bool showHidden = false) { if (productId == 0) throw new ArgumentException("Product ID is not specified"); //this inner query should retrieve all orders that contains a specified product ID var query1 = from orderItem in _orderItemRepository.Table where orderItem.ProductId == productId select orderItem.OrderId; var query2 = from orderItem in _orderItemRepository.Table join p in _productRepository.Table on orderItem.ProductId equals p.Id where (query1.Contains(orderItem.OrderId)) && (p.Id != productId) && (showHidden || p.Published) && (!orderItem.Order.Deleted) && (storeId == 0 || orderItem.Order.StoreId == storeId) && (!p.Deleted) && (showHidden || p.Published) select new { orderItem, p }; var query3 = from orderItem_p in query2 group orderItem_p by orderItem_p.p.Id into g select new { ProductId = g.Key, ProductsPurchased = g.Sum(x => x.orderItem.Quantity), }; query3 = query3.OrderByDescending(x => x.ProductsPurchased); if (recordsToReturn > 0) query3 = query3.Take(recordsToReturn); var report = query3.ToList(); var ids = new List<int>(); foreach (var reportLine in report) ids.Add(reportLine.ProductId); return ids.ToArray(); } /// <summary> /// Gets a list of products that were never sold /// </summary> /// <param name="vendorId">Vendor identifier</param> /// <param name="createdFromUtc">Order created date from (UTC); null to load all records</param> /// <param name="createdToUtc">Order created date to (UTC); null to load all records</param> /// <param name="pageIndex">Page index</param> /// <param name="pageSize">Page size</param> /// <param name="showHidden">A value indicating whether to show hidden records</param> /// <returns>Products</returns> public virtual IPagedList<Product> ProductsNeverSold(int vendorId, DateTime? createdFromUtc, DateTime? createdToUtc, int pageIndex, int pageSize, bool showHidden = false) { //this inner query should retrieve all purchased order product varint identifiers var query1 = (from orderItem in _orderItemRepository.Table join o in _orderRepository.Table on orderItem.OrderId equals o.Id where (!createdFromUtc.HasValue || createdFromUtc.Value <= o.CreatedOnUtc) && (!createdToUtc.HasValue || createdToUtc.Value >= o.CreatedOnUtc) && (!o.Deleted) select orderItem.ProductId).Distinct(); int simpleProductTypeId = (int)ProductType.SimpleProduct; var query2 = from p in _productRepository.Table orderby p.Name where (!query1.Contains(p.Id)) && //include only simple products (p.ProductTypeId == simpleProductTypeId) && (!p.Deleted) && (vendorId == 0 || p.VendorId == vendorId) && (showHidden || p.Published) select p; var products = new PagedList<Product>(query2, pageIndex, pageSize); return products; } /// <summary> /// Get profit report /// </summary> /// <param name="storeId">Store identifier</param> /// <param name="vendorId">Vendor identifier</param> /// <param name="startTimeUtc">Start date</param> /// <param name="endTimeUtc">End date</param> /// <param name="os">Order status; null to load all records</param> /// <param name="ps">Order payment status; null to load all records</param> /// <param name="ss">Shipping status; null to load all records</param> /// <param name="billingEmail">Billing email. Leave empty to load all records.</param> /// <returns>Result</returns> public virtual decimal ProfitReport(int storeId, int vendorId, OrderStatus? os, PaymentStatus? ps, ShippingStatus? ss, DateTime? startTimeUtc, DateTime? endTimeUtc, string billingEmail) { int? orderStatusId = null; if (os.HasValue) orderStatusId = (int)os.Value; int? paymentStatusId = null; if (ps.HasValue) paymentStatusId = (int)ps.Value; int? shippingStatusId = null; if (ss.HasValue) shippingStatusId = (int)ss.Value; //We cannot use String.IsNullOrEmpty(billingEmail) in SQL Compact bool dontSearchEmail = String.IsNullOrEmpty(billingEmail); var query = from orderItem in _orderItemRepository.Table join o in _orderRepository.Table on orderItem.OrderId equals o.Id where (storeId == 0 || storeId == o.StoreId) && (!startTimeUtc.HasValue || startTimeUtc.Value <= o.CreatedOnUtc) && (!endTimeUtc.HasValue || endTimeUtc.Value >= o.CreatedOnUtc) && (!orderStatusId.HasValue || orderStatusId == o.OrderStatusId) && (!paymentStatusId.HasValue || paymentStatusId == o.PaymentStatusId) && (!shippingStatusId.HasValue || shippingStatusId == o.ShippingStatusId) && (!o.Deleted) && (vendorId == 0 || orderItem.Product.VendorId == vendorId) && //we do not ignore deleted products when calculating order reports //(!p.Deleted) && //(!pv.Deleted) && (dontSearchEmail || (o.BillingAddress != null && !String.IsNullOrEmpty(o.BillingAddress.Email) && o.BillingAddress.Email.Contains(billingEmail))) select orderItem; var productCost = Convert.ToDecimal(query.Sum(orderItem => (decimal?)orderItem.OriginalProductCost * orderItem.Quantity)); var reportSummary = GetOrderAverageReportLine(storeId, vendorId, os, ps, ss, startTimeUtc, endTimeUtc, billingEmail); var profit = reportSummary.SumOrders - reportSummary.SumShippingExclTax - reportSummary.SumTax - productCost; return profit; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Concurrent; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.IO.Pipelines.Tests { public class SchedulerFacts { [Fact] public async Task ReadAsyncCallbackRunsOnReaderScheduler() { using (var factory = new PipeFactory()) { using (var scheduler = new ThreadScheduler()) { var pipe = factory.Create(new PipeOptions { ReaderScheduler = scheduler }); Func<Task> doRead = async () => { var oid = Thread.CurrentThread.ManagedThreadId; var result = await pipe.Reader.ReadAsync(); Assert.NotEqual(oid, Thread.CurrentThread.ManagedThreadId); Assert.Equal(Thread.CurrentThread.ManagedThreadId, scheduler.Thread.ManagedThreadId); pipe.Reader.Advance(result.Buffer.End, result.Buffer.End); pipe.Reader.Complete(); }; var reading = doRead(); var buffer = pipe.Writer.Alloc(); buffer.Write(Encoding.UTF8.GetBytes("Hello World")); await buffer.FlushAsync(); await reading; } } } [Fact] public async Task FlushCallbackRunsOnWriterScheduler() { using (var factory = new PipeFactory()) { using (var scheduler = new ThreadScheduler()) { var pipe = factory.Create(new PipeOptions { MaximumSizeLow = 32, MaximumSizeHigh = 64, WriterScheduler = scheduler }); var writableBuffer = pipe.Writer.Alloc(64); writableBuffer.Advance(64); var flushAsync = writableBuffer.FlushAsync(); Assert.False(flushAsync.IsCompleted); Func<Task> doWrite = async () => { var oid = Thread.CurrentThread.ManagedThreadId; await flushAsync; Assert.NotEqual(oid, Thread.CurrentThread.ManagedThreadId); pipe.Writer.Complete(); Assert.Equal(Thread.CurrentThread.ManagedThreadId, scheduler.Thread.ManagedThreadId); }; var writing = doWrite(); var result = await pipe.Reader.ReadAsync(); pipe.Reader.Advance(result.Buffer.End, result.Buffer.End); pipe.Reader.Complete(); await writing; } } } [Fact] public async Task DefaultReaderSchedulerRunsInline() { using (var factory = new PipeFactory()) { var pipe = factory.Create(); var id = 0; Func<Task> doRead = async () => { var result = await pipe.Reader.ReadAsync(); Assert.Equal(Thread.CurrentThread.ManagedThreadId, id); pipe.Reader.Advance(result.Buffer.End, result.Buffer.End); pipe.Reader.Complete(); }; var reading = doRead(); id = Thread.CurrentThread.ManagedThreadId; var buffer = pipe.Writer.Alloc(); buffer.Write(Encoding.UTF8.GetBytes("Hello World")); await buffer.FlushAsync(); pipe.Writer.Complete(); await reading; } } [Fact] public async Task DefaultWriterSchedulerRunsInline() { using (var factory = new PipeFactory()) { var pipe = factory.Create(new PipeOptions { MaximumSizeLow = 32, MaximumSizeHigh = 64 }); var writableBuffer = pipe.Writer.Alloc(64); writableBuffer.Advance(64); var flushAsync = writableBuffer.FlushAsync(); Assert.False(flushAsync.IsCompleted); int id = 0; Func<Task> doWrite = async () => { await flushAsync; pipe.Writer.Complete(); Assert.Equal(Thread.CurrentThread.ManagedThreadId, id); }; var writing = doWrite(); var result = await pipe.Reader.ReadAsync(); id = Thread.CurrentThread.ManagedThreadId; pipe.Reader.Advance(result.Buffer.End, result.Buffer.End); pipe.Reader.Complete(); await writing; } } private class ThreadScheduler : IScheduler, IDisposable { private BlockingCollection<Action> _work = new BlockingCollection<Action>(); public Thread Thread { get; } public ThreadScheduler() { Thread = new Thread(Work) { IsBackground = true }; Thread.Start(); } public void Schedule(Action action) { _work.Add(action); } private void Work(object state) { foreach (var callback in _work.GetConsumingEnumerable()) { callback(); } } public void Dispose() { _work.CompleteAdding(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using AonWeb.FluentHttp.Handlers.Caching; using AonWeb.FluentHttp.Helpers; namespace AonWeb.FluentHttp.Caching { public class CacheManager : ICacheManager { private readonly ICacheProvider _cache; private readonly IUriInfoProvider _uriInfo; private readonly IVaryByProvider _varyBy; private readonly ResponseSerializer _serializer; public CacheManager(ICacheProvider cache, IVaryByProvider varyBy, IUriInfoProvider uriInfo, ResponseSerializer serializer) { _varyBy = varyBy; _cache = cache; _uriInfo = uriInfo; _serializer = serializer; } public async Task<CacheEntry> Get(ICacheContext context) { var key = await GetKey(context); var cacheEntry = await _cache.Get<CacheEntry>(key); if (cacheEntry == null) return CacheEntry.Empty; var validation = context.ResponseValidator(context, cacheEntry.Metadata); if (validation == ResponseValidationResult.Stale && !context.AllowStaleResultValidator(context, cacheEntry.Metadata)) return CacheEntry.Empty; if (validation != ResponseValidationResult.OK && validation != ResponseValidationResult.Stale && validation != ResponseValidationResult.MustRevalidate) return CacheEntry.Empty; object result; if (cacheEntry.IsHttpResponseMessage) { var responseBuffer = cacheEntry.Value as byte[]; result = await _serializer.Deserialize(responseBuffer, context.Token); } else { result = cacheEntry.Value; } return new CacheEntry(result, cacheEntry.Metadata) { IsHttpResponseMessage = cacheEntry.IsHttpResponseMessage }; } public async Task Put(ICacheContext context, CacheEntry newCacheEntry) { var key = await GetKey(context); var isHttpResponseMessage = newCacheEntry.IsHttpResponseMessage; CacheEntry cacheEntry = null; var temp = await _cache.Get<CacheEntry>(key); if (temp != null && context.ResponseValidator(context, temp.Metadata) == ResponseValidationResult.OK) cacheEntry = temp; var response = newCacheEntry.Value as HttpResponseMessage; if (cacheEntry == null) { object value; if (response != null) { value = await _serializer.Serialize(response, context.Token); isHttpResponseMessage = true; } else { value = newCacheEntry.Value; } cacheEntry = new CacheEntry(newCacheEntry.Metadata) { Value = value, IsHttpResponseMessage = isHttpResponseMessage }; } else { cacheEntry.Metadata.Merge(newCacheEntry.Metadata); } // TODO: this may not be the place for this, I'd like to provide some ability to control jitter var duration = CachingHelpers.GetCacheDuration(cacheEntry.Metadata); await Task.WhenAll( _cache.Put(key, cacheEntry, duration), _varyBy.Put(context.Uri, newCacheEntry.Metadata.VaryHeaders, duration), _uriInfo.Put(context.Uri, key, duration) ); } public async Task<IList<Uri>> Delete(ICacheContext context, IEnumerable<Uri> additionalDependentUris) { var key = await GetKey(context); var uris = new List<Uri>(); if (key == CacheKey.Empty) return uris; var cacheEntry = await _cache.Get<CacheEntry>(key); if (cacheEntry == null) return uris; var deleteTask = _cache.Delete(key); var deleteUriTask = _uriInfo.DeleteKey(context.Uri, key); await Task.WhenAll(deleteTask, deleteUriTask); if (!deleteTask.Result) return uris; if (context.Uri != null) uris.Add(context.Uri); var relatedUris = await DeleteDependentUris(cacheEntry, context, additionalDependentUris); uris.AddRange(relatedUris); return uris; } public Task<IList<Uri>> Delete(Uri uri) { return DeleteDependentUris(new[] { uri }); } public Task DeleteAll() { return Task.WhenAll( _cache.DeleteAll(), _varyBy.DeleteAll(), _uriInfo.DeleteAll() ); } private Task<IList<Uri>> DeleteDependentUris(CacheEntry cacheEntry, ICacheMetadata metadata, IEnumerable<Uri> additionalDependentUris) { var uris = metadata.DependentUris ?? Enumerable.Empty<Uri>(); if (cacheEntry?.Metadata != null) uris = uris.Concat(cacheEntry.Metadata.DependentUris ?? Enumerable.Empty<Uri>()); uris = uris.Concat(additionalDependentUris ?? Enumerable.Empty<Uri>()); return DeleteDependentUris(uris); } private async Task<IList<Uri>> DeleteDependentUris(IEnumerable<Uri> uris) { //this could probably be made more efficient by batching and providing a some type of batching interface for the cache provider var removed = new List<Uri>(); foreach (var uri in uris.Where(u => u != null).Distinct()) { var uriInfo = await _uriInfo.Get(uri); if (uriInfo == null) continue; await _uriInfo.Delete(uri); var keys = uriInfo.CacheKeys.ToList(); foreach (var key in keys) { var cacheEntry = await _cache.Get<CacheEntry>(key); if (cacheEntry == null) continue; removed.Add(cacheEntry.Metadata.Uri); var deleteTask = _cache.Delete(key); var relatedRemovedTask = DeleteDependentUris(cacheEntry.Metadata.DependentUris); await Task.WhenAll(deleteTask, relatedRemovedTask); removed.AddRange(relatedRemovedTask.Result); } } return removed; } private Task<CacheKey> GetKey(ICacheContext context) { return GetKey(context.ResultType, context.Uri, context.DefaultVaryByHeaders, context.Request?.Headers); } private async Task<CacheKey> GetKey(Type resultType, Uri uri, IEnumerable<string> defaultVaryByHeaders, HttpRequestHeaders headers) { var builder = new StringBuilder(); var isHttpResponseMessage = typeof(HttpResponseMessage).IsAssignableFrom(resultType); builder.Append(isHttpResponseMessage ? "Http" : "Typed") .Append("-") .Append(uri?.ToString() ?? "uri://unknown"); if (!isHttpResponseMessage) return builder.ToString(); var varyBy = await GetVaryByHeaders(uri, defaultVaryByHeaders); foreach (var header in headers.Where(h => varyBy.Any(v => v.Equals(h.Key, StringComparison.OrdinalIgnoreCase))).OrderBy(h => h.Key)) { builder.Append(";"); builder.Append(UriHelpers.NormalizeHeader(header.Key)).Append(":"); builder.Append(string.Join(",", header.Value.OrderBy(v => v).Select(UriHelpers.NormalizeHeader).Distinct())); } return builder.ToString(); } private async Task<IEnumerable<string>> GetVaryByHeaders(Uri uri, IEnumerable<string> defaultVaryByHeaders) { var headers = await _varyBy.Get(uri); return defaultVaryByHeaders.ToSet(headers); } } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; namespace EarLab.Dialogs.Analysis { /// <summary> /// Summary description for IntervalDialog. /// </summary> public class IntervalDialog : System.Windows.Forms.Form { private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Button okButton; private System.Windows.Forms.Button cancelButton; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox bincountTextBox; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox maxintervalTextBox; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public IntervalDialog() { InitializeComponent(); EarLab.Utilities.EnableVisualStyles.EnableControl(this); this.okButton.Enabled = false; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.okButton = new System.Windows.Forms.Button(); this.cancelButton = new System.Windows.Forms.Button(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.bincountTextBox = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.maxintervalTextBox = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // okButton // this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK; this.okButton.Location = new System.Drawing.Point(104, 96); this.okButton.Name = "okButton"; this.okButton.Size = new System.Drawing.Size(40, 23); this.okButton.TabIndex = 1; this.okButton.Text = "OK"; // // cancelButton // this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.Location = new System.Drawing.Point(152, 96); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(56, 23); this.cancelButton.TabIndex = 2; this.cancelButton.Text = "Cancel"; // // groupBox1 // this.groupBox1.Controls.Add(this.bincountTextBox); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Controls.Add(this.maxintervalTextBox); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Location = new System.Drawing.Point(8, 8); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(200, 80); this.groupBox1.TabIndex = 0; this.groupBox1.TabStop = false; this.groupBox1.Text = "User Parameters"; // // bincountTextBox // this.bincountTextBox.Location = new System.Drawing.Point(80, 48); this.bincountTextBox.Name = "bincountTextBox"; this.bincountTextBox.Size = new System.Drawing.Size(56, 20); this.bincountTextBox.TabIndex = 1; this.bincountTextBox.Text = ""; this.bincountTextBox.TextChanged += new System.EventHandler(this.bincountTextBox_TextChanged); // // label1 // this.label1.Location = new System.Drawing.Point(8, 24); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(72, 16); this.label1.TabIndex = 1; this.label1.Text = "Max Interval:"; this.label1.TextAlign = System.Drawing.ContentAlignment.BottomLeft; // // maxintervalTextBox // this.maxintervalTextBox.Location = new System.Drawing.Point(80, 24); this.maxintervalTextBox.Name = "maxintervalTextBox"; this.maxintervalTextBox.Size = new System.Drawing.Size(56, 20); this.maxintervalTextBox.TabIndex = 0; this.maxintervalTextBox.Text = ""; this.maxintervalTextBox.TextChanged += new System.EventHandler(this.maxintervalTextBox_TextChanged); // // label3 // this.label3.Location = new System.Drawing.Point(8, 48); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(64, 16); this.label3.TabIndex = 4; this.label3.Text = "Bin Count:"; this.label3.TextAlign = System.Drawing.ContentAlignment.BottomLeft; // // label2 // this.label2.Location = new System.Drawing.Point(144, 24); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(48, 16); this.label2.TabIndex = 2; this.label2.Text = "seconds"; this.label2.TextAlign = System.Drawing.ContentAlignment.BottomLeft; // // IntervalDialog // this.AcceptButton = this.okButton; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.CancelButton = this.cancelButton; this.ClientSize = new System.Drawing.Size(218, 128); this.ControlBox = false; this.Controls.Add(this.groupBox1); this.Controls.Add(this.cancelButton); this.Controls.Add(this.okButton); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Name = "IntervalDialog"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Interval Analysis Question"; this.groupBox1.ResumeLayout(false); this.ResumeLayout(false); } #endregion private void maxintervalTextBox_TextChanged(object sender, System.EventArgs e) { double maxInterval; if (double.TryParse(this.maxintervalTextBox.Text, System.Globalization.NumberStyles.AllowDecimalPoint, null, out maxInterval)) this.okButton.Enabled = true; else this.okButton.Enabled = false; } private void bincountTextBox_TextChanged(object sender, System.EventArgs e) { double binCount; if (double.TryParse(this.bincountTextBox.Text, System.Globalization.NumberStyles.None, null, out binCount)) { if (binCount > 0) this.okButton.Enabled = true; else this.okButton.Enabled = false; } else this.okButton.Enabled = false; } public double MaxInterval { get { double maxInterval; if (double.TryParse(this.maxintervalTextBox.Text, System.Globalization.NumberStyles.AllowDecimalPoint, null, out maxInterval)) { return maxInterval; } else return 0; } } public int BinCount { get { double binCount; if (double.TryParse(this.bincountTextBox.Text, System.Globalization.NumberStyles.None, null, out binCount)) { return (int)binCount; } else return 0; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // using System; using System.Runtime; using System.Security; using System.Collections; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime { // This is a set of stub methods implementing the support for the IList interface on WinRT // objects that support IBindableVector. Used by the interop mashaling infrastructure. // // The methods on this class must be written VERY carefully to avoid introducing security holes. // That's because they are invoked with special "this"! The "this" object // for all of these methods are not BindableVectorToListAdapter objects. Rather, they are // of type IBindableVector. No actual BindableVectorToListAdapter object is ever instantiated. // Thus, you will see a lot of expressions that cast "this" to "IBindableVector". internal sealed class BindableVectorToListAdapter { private BindableVectorToListAdapter() { Contract.Assert(false, "This class is never instantiated"); } // object this[int index] { get } [SecurityCritical] internal object Indexer_Get(int index) { if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this); return GetAt(_this, (uint)index); } // object this[int index] { set } [SecurityCritical] internal void Indexer_Set(int index, object value) { if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this); SetAt(_this, (uint)index, value); } // int Add(object value) [SecurityCritical] internal int Add(object value) { IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this); _this.Append(value); uint size = _this.Size; if (((uint)Int32.MaxValue) < size) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingListTooLarge")); } return (int)(size - 1); } // bool Contains(object item) [SecurityCritical] internal bool Contains(object item) { IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this); uint index; return _this.IndexOf(item, out index); } // void Clear() [SecurityCritical] internal void Clear() { IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this); _this.Clear(); } // bool IsFixedSize { get } [Pure] [SecurityCritical] internal bool IsFixedSize() { return false; } // bool IsReadOnly { get } [Pure] [SecurityCritical] internal bool IsReadOnly() { return false; } // int IndexOf(object item) [SecurityCritical] internal int IndexOf(object item) { IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this); uint index; bool exists = _this.IndexOf(item, out index); if (!exists) return -1; if (((uint)Int32.MaxValue) < index) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingListTooLarge")); } return (int)index; } // void Insert(int index, object item) [SecurityCritical] internal void Insert(int index, object item) { if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this); InsertAtHelper(_this, (uint)index, item); } // bool Remove(object item) [SecurityCritical] internal void Remove(object item) { IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this); uint index; bool exists = _this.IndexOf(item, out index); if (exists) { if (((uint)Int32.MaxValue) < index) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingListTooLarge")); } RemoveAtHelper(_this, index); } } // void RemoveAt(int index) [SecurityCritical] internal void RemoveAt(int index) { if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this); RemoveAtHelper(_this, (uint)index); } // Helpers: private static object GetAt(IBindableVector _this, uint index) { try { return _this.GetAt(index); // We delegate bounds checking to the underlying collection and if it detected a fault, // we translate it to the right exception: } catch (Exception ex) { if (__HResults.E_BOUNDS == ex._HResult) throw new ArgumentOutOfRangeException(nameof(index)); throw; } } private static void SetAt(IBindableVector _this, uint index, object value) { try { _this.SetAt(index, value); // We delegate bounds checking to the underlying collection and if it detected a fault, // we translate it to the right exception: } catch (Exception ex) { if (__HResults.E_BOUNDS == ex._HResult) throw new ArgumentOutOfRangeException(nameof(index)); throw; } } private static void InsertAtHelper(IBindableVector _this, uint index, object item) { try { _this.InsertAt(index, item); // We delegate bounds checking to the underlying collection and if it detected a fault, // we translate it to the right exception: } catch (Exception ex) { if (__HResults.E_BOUNDS == ex._HResult) throw new ArgumentOutOfRangeException(nameof(index)); throw; } } private static void RemoveAtHelper(IBindableVector _this, uint index) { try { _this.RemoveAt(index); // We delegate bounds checking to the underlying collection and if it detected a fault, // we translate it to the right exception: } catch (Exception ex) { if (__HResults.E_BOUNDS == ex._HResult) throw new ArgumentOutOfRangeException(nameof(index)); throw; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Internal.Runtime.CompilerServices; namespace System.Buffers { public readonly partial struct ReadOnlySequence<T> { [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool TryGetBuffer(in SequencePosition position, out ReadOnlyMemory<T> memory, out SequencePosition next) { object positionObject = position.GetObject(); next = default; if (positionObject == null) { memory = default; return false; } SequenceType type = GetSequenceType(); object endObject = _endObject; int startIndex = GetIndex(position); int endIndex = GetIndex(_endInteger); if (type == SequenceType.MultiSegment) { Debug.Assert(positionObject is ReadOnlySequenceSegment<T>); ReadOnlySequenceSegment<T> startSegment = (ReadOnlySequenceSegment<T>)positionObject; if (startSegment != endObject) { ReadOnlySequenceSegment<T> nextSegment = startSegment.Next; if (nextSegment == null) ThrowHelper.ThrowInvalidOperationException_EndPositionNotReached(); next = new SequencePosition(nextSegment, 0); memory = startSegment.Memory.Slice(startIndex); } else { memory = startSegment.Memory.Slice(startIndex, endIndex - startIndex); } } else { if (positionObject != endObject) ThrowHelper.ThrowInvalidOperationException_EndPositionNotReached(); if (type == SequenceType.Array) { Debug.Assert(positionObject is T[]); memory = new ReadOnlyMemory<T>((T[])positionObject, startIndex, endIndex - startIndex); } else if (typeof(T) == typeof(char) && type == SequenceType.String) { Debug.Assert(positionObject is string); memory = (ReadOnlyMemory<T>)(object)((string)positionObject).AsMemory(startIndex, endIndex - startIndex); } else // type == SequenceType.MemoryManager { Debug.Assert(type == SequenceType.MemoryManager); Debug.Assert(positionObject is MemoryManager<T>); memory = ((MemoryManager<T>)positionObject).Memory.Slice(startIndex, endIndex - startIndex); } } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private ReadOnlyMemory<T> GetFirstBuffer() { object startObject = _startObject; if (startObject == null) return default; int startIndex = _startInteger; int endIndex = _endInteger; bool isMultiSegment = startObject != _endObject; // The highest bit of startIndex and endIndex are used to infer the sequence type // The code below is structured this way for performance reasons and is equivalent to the following: // SequenceType type = GetSequenceType(); // if (type == SequenceType.MultiSegment) { ... } // else if (type == SequenceType.Array) { ... } // else if (type == SequenceType.String){ ... } // else if (type == SequenceType.MemoryManager) { ... } // Highest bit of startIndex: A = startIndex >> 31 // Highest bit of endIndex: B = endIndex >> 31 // A == 0 && B == 0 means SequenceType.MultiSegment // Equivalent to startIndex >= 0 && endIndex >= 0 if ((startIndex | endIndex) >= 0) { ReadOnlyMemory<T> memory = ((ReadOnlySequenceSegment<T>)startObject).Memory; if (isMultiSegment) { return memory.Slice(startIndex); } return memory.Slice(startIndex, endIndex - startIndex); } else { return GetFirstBufferSlow(startObject, isMultiSegment); } } [MethodImpl(MethodImplOptions.NoInlining)] private ReadOnlyMemory<T> GetFirstBufferSlow(object startObject, bool isMultiSegment) { if (isMultiSegment) ThrowHelper.ThrowInvalidOperationException_EndPositionNotReached(); int startIndex = _startInteger; int endIndex = _endInteger; Debug.Assert(startIndex < 0 || endIndex < 0); // A == 0 && B == 1 means SequenceType.Array if (startIndex >= 0) { Debug.Assert(endIndex < 0); return new ReadOnlyMemory<T>((T[])startObject, startIndex, (endIndex & ReadOnlySequence.IndexBitMask) - startIndex); } else { // The type == char check here is redundant. However, we still have it to allow // the JIT to see when that the code is unreachable and eliminate it. // A == 1 && B == 1 means SequenceType.String if (typeof(T) == typeof(char) && endIndex < 0) { // No need to remove the FlagBitMask since (endIndex - startIndex) == (endIndex & ReadOnlySequence.IndexBitMask) - (startIndex & ReadOnlySequence.IndexBitMask) return (ReadOnlyMemory<T>)(object)((string)startObject).AsMemory(startIndex & ReadOnlySequence.IndexBitMask, endIndex - startIndex); } else // endIndex >= 0, A == 1 && B == 0 means SequenceType.MemoryManager { startIndex &= ReadOnlySequence.IndexBitMask; return ((MemoryManager<T>)startObject).Memory.Slice(startIndex, endIndex - startIndex); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal SequencePosition Seek(long offset, ExceptionArgument exceptionArgument = ExceptionArgument.offset) { object startObject = _startObject; object endObject = _endObject; int startIndex = GetIndex(_startInteger); int endIndex = GetIndex(_endInteger); if (startObject != endObject) { Debug.Assert(startObject != null); var startSegment = (ReadOnlySequenceSegment<T>)startObject; int currentLength = startSegment.Memory.Length - startIndex; // Position in start segment, defer to single segment seek if (currentLength > offset) goto IsSingleSegment; if (currentLength < 0) ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); // End of segment. Move to start of next. return SeekMultiSegment(startSegment.Next, endObject, endIndex, offset - currentLength, exceptionArgument); } Debug.Assert(startObject == endObject); if (endIndex - startIndex < offset) ThrowHelper.ThrowArgumentOutOfRangeException(exceptionArgument); // Single segment Seek IsSingleSegment: return new SequencePosition(startObject, startIndex + (int)offset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private SequencePosition Seek(in SequencePosition start, long offset) { object startObject = start.GetObject(); object endObject = _endObject; int startIndex = GetIndex(start); int endIndex = GetIndex(_endInteger); if (startObject != endObject) { Debug.Assert(startObject != null); var startSegment = (ReadOnlySequenceSegment<T>)startObject; int currentLength = startSegment.Memory.Length - startIndex; // Position in start segment, defer to single segment seek if (currentLength > offset) goto IsSingleSegment; if (currentLength < 0) ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); // End of segment. Move to start of next. return SeekMultiSegment(startSegment.Next, endObject, endIndex, offset - currentLength, ExceptionArgument.offset); } Debug.Assert(startObject == endObject); if (endIndex - startIndex < offset) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.offset); // Single segment Seek IsSingleSegment: return new SequencePosition(startObject, startIndex + (int)offset); } [MethodImpl(MethodImplOptions.NoInlining)] private static SequencePosition SeekMultiSegment(ReadOnlySequenceSegment<T> currentSegment, object endObject, int endIndex, long offset, ExceptionArgument argument) { Debug.Assert(currentSegment != null); Debug.Assert(offset >= 0); while (currentSegment != null && currentSegment != endObject) { int memoryLength = currentSegment.Memory.Length; // Fully contained in this segment if (memoryLength > offset) goto FoundSegment; // Move to next offset -= memoryLength; currentSegment = currentSegment.Next; } // Hit the end of the segments but didn't reach the count if (currentSegment == null || endIndex < offset) ThrowHelper.ThrowArgumentOutOfRangeException(argument); FoundSegment: return new SequencePosition(currentSegment, (int)offset); } private void BoundsCheck(in SequencePosition position) { uint sliceStartIndex = (uint)GetIndex(position); object startObject = _startObject; object endObject = _endObject; uint startIndex = (uint)GetIndex(_startInteger); uint endIndex = (uint)GetIndex(_endInteger); // Single-Segment Sequence if (startObject == endObject) { if (!InRange(sliceStartIndex, startIndex, endIndex)) { ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); } } else { // Multi-Segment Sequence // Storing this in a local since it is used twice within InRange() ulong startRange = (ulong)(((ReadOnlySequenceSegment<T>)startObject).RunningIndex + startIndex); if (!InRange( (ulong)(((ReadOnlySequenceSegment<T>)position.GetObject()).RunningIndex + sliceStartIndex), startRange, (ulong)(((ReadOnlySequenceSegment<T>)endObject).RunningIndex + endIndex))) { ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); } } } private void BoundsCheck(uint sliceStartIndex, object sliceStartObject, uint sliceEndIndex, object sliceEndObject) { object startObject = _startObject; object endObject = _endObject; uint startIndex = (uint)GetIndex(_startInteger); uint endIndex = (uint)GetIndex(_endInteger); // Single-Segment Sequence if (startObject == endObject) { if (sliceStartObject != sliceEndObject || sliceStartObject != startObject || sliceStartIndex > sliceEndIndex || sliceStartIndex < startIndex || sliceEndIndex > endIndex) { ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); } } else { // Multi-Segment Sequence // This optimization works because we know sliceStartIndex, sliceEndIndex, startIndex, and endIndex are all >= 0 Debug.Assert(sliceStartIndex >= 0 && startIndex >= 0 && endIndex >= 0); ulong sliceStartRange = (ulong)(((ReadOnlySequenceSegment<T>)sliceStartObject).RunningIndex + sliceStartIndex); ulong sliceEndRange = (ulong)(((ReadOnlySequenceSegment<T>)sliceEndObject).RunningIndex + sliceEndIndex); if (sliceStartRange > sliceEndRange) ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); if (sliceStartRange < (ulong)(((ReadOnlySequenceSegment<T>)startObject).RunningIndex + startIndex) || sliceEndRange > (ulong)(((ReadOnlySequenceSegment<T>)endObject).RunningIndex + endIndex)) { ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); } } } private static SequencePosition GetEndPosition(ReadOnlySequenceSegment<T> startSegment, object startObject, int startIndex, object endObject, int endIndex, long length) { int currentLength = startSegment.Memory.Length - startIndex; if (currentLength > length) { return new SequencePosition(startObject, startIndex + (int)length); } if (currentLength < 0) ThrowHelper.ThrowArgumentOutOfRangeException_PositionOutOfRange(); return SeekMultiSegment(startSegment.Next, endObject, endIndex, length - currentLength, ExceptionArgument.length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private SequenceType GetSequenceType() { // We take high order bits of two indexes and move them // to a first and second position to convert to SequenceType // if (start < 0 and end < 0) // start >> 31 = -1, end >> 31 = -1 // 2 * (-1) + (-1) = -3, result = (SequenceType)3 // if (start < 0 and end >= 0) // start >> 31 = -1, end >> 31 = 0 // 2 * (-1) + 0 = -2, result = (SequenceType)2 // if (start >= 0 and end >= 0) // start >> 31 = 0, end >> 31 = 0 // 2 * 0 + 0 = 0, result = (SequenceType)0 // if (start >= 0 and end < 0) // start >> 31 = 0, end >> 31 = -1 // 2 * 0 + (-1) = -1, result = (SequenceType)1 return (SequenceType)(-(2 * (_startInteger >> 31) + (_endInteger >> 31))); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int GetIndex(in SequencePosition position) => position.GetInteger() & ReadOnlySequence.IndexBitMask; [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int GetIndex(int Integer) => Integer & ReadOnlySequence.IndexBitMask; [MethodImpl(MethodImplOptions.AggressiveInlining)] private ReadOnlySequence<T> SliceImpl(in SequencePosition start, in SequencePosition end) { // In this method we reset high order bits from indices // of positions that were passed in // and apply type bits specific for current ReadOnlySequence type return new ReadOnlySequence<T>( start.GetObject(), GetIndex(start) | (_startInteger & ReadOnlySequence.FlagBitMask), end.GetObject(), GetIndex(end) | (_endInteger & ReadOnlySequence.FlagBitMask) ); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private ReadOnlySequence<T> SliceImpl(in SequencePosition start) { // In this method we reset high order bits from indices // of positions that were passed in // and apply type bits specific for current ReadOnlySequence type return new ReadOnlySequence<T>( start.GetObject(), GetIndex(start) | (_startInteger & ReadOnlySequence.FlagBitMask), _endObject, _endInteger ); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private long GetLength() { object startObject = _startObject; object endObject = _endObject; int startIndex = GetIndex(_startInteger); int endIndex = GetIndex(_endInteger); if (startObject != endObject) { var startSegment = (ReadOnlySequenceSegment<T>)startObject; var endSegment = (ReadOnlySequenceSegment<T>)endObject; // (End offset) - (start offset) return (endSegment.RunningIndex + endIndex) - (startSegment.RunningIndex + startIndex); } // Single segment length return endIndex - startIndex; } internal bool TryGetReadOnlySequenceSegment(out ReadOnlySequenceSegment<T> startSegment, out int startIndex, out ReadOnlySequenceSegment<T> endSegment, out int endIndex) { object startObject = _startObject; // Default or not MultiSegment if (startObject == null || GetSequenceType() != SequenceType.MultiSegment) { startSegment = null; startIndex = 0; endSegment = null; endIndex = 0; return false; } Debug.Assert(_endObject != null); startSegment = (ReadOnlySequenceSegment<T>)startObject; startIndex = GetIndex(_startInteger); endSegment = (ReadOnlySequenceSegment<T>)_endObject; endIndex = GetIndex(_endInteger); return true; } internal bool TryGetArray(out ArraySegment<T> segment) { if (GetSequenceType() != SequenceType.Array) { segment = default; return false; } Debug.Assert(_startObject != null); int startIndex = GetIndex(_startInteger); segment = new ArraySegment<T>((T[])_startObject, startIndex, GetIndex(_endInteger) - startIndex); return true; } internal bool TryGetString(out string text, out int start, out int length) { if (typeof(T) != typeof(char) || GetSequenceType() != SequenceType.String) { start = 0; length = 0; text = null; return false; } Debug.Assert(_startObject != null); start = GetIndex(_startInteger); length = GetIndex(_endInteger) - start; text = (string)_startObject; return true; } private static bool InRange(uint value, uint start, uint end) { // _sequenceStart and _sequenceEnd must be well-formed Debug.Assert(start <= int.MaxValue); Debug.Assert(end <= int.MaxValue); Debug.Assert(start <= end); // The case, value > int.MaxValue, is invalid, and hence it shouldn't be in the range. // If value > int.MaxValue, it is invariably greater than both 'start' and 'end'. // In that case, the experession simplifies to value <= end, which will return false. // The case, value < start, is invalid. // In that case, (value - start) would underflow becoming larger than int.MaxValue. // (end - start) can never underflow and hence must be within 0 and int.MaxValue. // So, we will correctly return false. // The case, value > end, is invalid. // In that case, the expression simplifies to value <= end, which will return false. // This is because end > start & value > end implies value > start as well. // In all other cases, value is valid, and we return true. // Equivalent to: return (start <= value && value <= start) return (value - start) <= (end - start); } private static bool InRange(ulong value, ulong start, ulong end) { // _sequenceStart and _sequenceEnd must be well-formed Debug.Assert(start <= long.MaxValue); Debug.Assert(end <= long.MaxValue); Debug.Assert(start <= end); // The case, value > long.MaxValue, is invalid, and hence it shouldn't be in the range. // If value > long.MaxValue, it is invariably greater than both 'start' and 'end'. // In that case, the experession simplifies to value <= end, which will return false. // The case, value < start, is invalid. // In that case, (value - start) would underflow becoming larger than long.MaxValue. // (end - start) can never underflow and hence must be within 0 and long.MaxValue. // So, we will correctly return false. // The case, value > end, is invalid. // In that case, the expression simplifies to value <= end, which will return false. // This is because end > start & value > end implies value > start as well. // In all other cases, value is valid, and we return true. // Equivalent to: return (start <= value && value <= start) return (value - start) <= (end - start); } /// <summary> /// Helper to efficiently prepare the <see cref="SequenceReader{T}"/> /// </summary> /// <param name="first">The first span in the sequence.</param> /// <param name="next">The next position.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void GetFirstSpan(out ReadOnlySpan<T> first, out SequencePosition next) { first = default; next = default; object startObject = _startObject; int startIndex = _startInteger; if (startObject != null) { bool hasMultipleSegments = startObject != _endObject; int endIndex = _endInteger; if (startIndex >= 0) { if (endIndex >= 0) { // Positive start and end index == ReadOnlySequenceSegment<T> ReadOnlySequenceSegment<T> segment = (ReadOnlySequenceSegment<T>)startObject; next = new SequencePosition(segment.Next, 0); first = segment.Memory.Span; if (hasMultipleSegments) { first = first.Slice(startIndex); } else { first = first.Slice(startIndex, endIndex - startIndex); } } else { // Positive start and negative end index == T[] if (hasMultipleSegments) ThrowHelper.ThrowInvalidOperationException_EndPositionNotReached(); first = new ReadOnlySpan<T>((T[])startObject, startIndex, (endIndex & ReadOnlySequence.IndexBitMask) - startIndex); } } else { first = GetFirstSpanSlow(startObject, startIndex, endIndex, hasMultipleSegments); } } } [MethodImpl(MethodImplOptions.NoInlining)] private static ReadOnlySpan<T> GetFirstSpanSlow(object startObject, int startIndex, int endIndex, bool hasMultipleSegments) { Debug.Assert(startIndex < 0); if (hasMultipleSegments) ThrowHelper.ThrowInvalidOperationException_EndPositionNotReached(); // The type == char check here is redundant. However, we still have it to allow // the JIT to see when that the code is unreachable and eliminate it. if (typeof(T) == typeof(char) && endIndex < 0) { // Negative start and negative end index == string ReadOnlySpan<char> spanOfChar = ((string)startObject).AsSpan(startIndex & ReadOnlySequence.IndexBitMask, endIndex - startIndex); return MemoryMarshal.CreateReadOnlySpan(ref Unsafe.As<char, T>(ref MemoryMarshal.GetReference(spanOfChar)), spanOfChar.Length); } else { // Negative start and positive end index == MemoryManager<T> startIndex &= ReadOnlySequence.IndexBitMask; return ((MemoryManager<T>)startObject).Memory.Span.Slice(startIndex, endIndex - startIndex); } } } }
using System; using NUnit.Framework; using Mono.Addins; using System.IO; using SimpleApp; using System.Xml.Serialization; namespace UnitTests { [TestFixture()] public class TestLoadUnload: TestBase { void ResetStatus (bool enable) { Addin ainfo; ainfo = AddinManager.Registry.GetAddin ("SimpleApp.HelloWorldExtension"); ainfo.Enabled = enable; ainfo = AddinManager.Registry.GetAddin ("SimpleApp.FileContentExtension"); ainfo.Enabled = enable; ainfo = AddinManager.Registry.GetAddin ("SimpleApp.SystemInfoExtension"); ainfo.Enabled = enable; ainfo = AddinManager.Registry.GetAddin ("SimpleApp.CommandExtension"); ainfo.Enabled = enable; } [Test()] public void TestDisable () { Addin ainfo; Assert.AreEqual (4, AddinManager.GetExtensionNodes ("/SimpleApp/Writers").Count, "count 1"); ainfo = AddinManager.Registry.GetAddin ("SimpleApp.HelloWorldExtension"); Assert.IsNotNull (ainfo, "t1"); Assert.IsTrue (ainfo.Enabled, "t1.1"); ainfo.Enabled = false; Assert.IsFalse (ainfo.Enabled, "t1.2"); Assert.AreEqual (3, AddinManager.GetExtensionNodes ("/SimpleApp/Writers").Count, "count 2"); ainfo = AddinManager.Registry.GetAddin ("SimpleApp.FileContentExtension"); Assert.IsNotNull (ainfo, "t3"); Assert.IsTrue (ainfo.Enabled, "t3.1"); ainfo.Enabled = false; Assert.IsFalse (ainfo.Enabled, "t3.2"); Assert.AreEqual (2, AddinManager.GetExtensionNodes ("/SimpleApp/Writers").Count, "count 3"); ainfo = AddinManager.Registry.GetAddin ("SimpleApp.SystemInfoExtension"); Assert.IsNotNull (ainfo, "t5"); Assert.IsTrue (ainfo.Enabled, "t5.1"); ainfo.Enabled = false; Assert.IsFalse (ainfo.Enabled, "t5.2"); Assert.AreEqual (0, AddinManager.GetExtensionNodes ("/SimpleApp/Writers").Count, "count 4"); ainfo = AddinManager.Registry.GetAddin ("SimpleApp.CommandExtension"); Assert.IsNotNull (ainfo, "t2"); Assert.IsTrue (ainfo.Enabled, "t2.1"); ainfo.Enabled = false; Assert.IsFalse (ainfo.Enabled, "t2.2"); Assert.AreEqual (0, AddinManager.GetExtensionNodes ("/SimpleApp/Writers").Count, "count 5"); ResetStatus (true); } [Test()] public void TestEnable () { ResetStatus (false); Assert.AreEqual (0, AddinManager.GetExtensionNodes ("/SimpleApp/Writers").Count, "count 1"); Assert.IsFalse (AddinManager.Registry.IsAddinEnabled ("SimpleApp.HelloWorldExtension"), "t1"); AddinManager.Registry.EnableAddin ("SimpleApp.HelloWorldExtension,0.1.0"); Assert.IsTrue (AddinManager.Registry.IsAddinEnabled ("SimpleApp.HelloWorldExtension"), "t1.1"); // CommandExtenion is a dep of HelloWorldExtension Assert.IsTrue(AddinManager.Registry.IsAddinEnabled("SimpleApp.CommandExtension"), "t2"); Assert.AreEqual (1, AddinManager.GetExtensionNodes ("/SimpleApp/Writers").Count, "count 2"); Assert.AreEqual (1, AddinManager.GetExtensionNodes ("/SimpleApp/Writers").Count, "count 3"); Assert.IsFalse (AddinManager.Registry.IsAddinEnabled ("SimpleApp.SystemInfoExtension"), "t3"); AddinManager.Registry.EnableAddin ("SimpleApp.SystemInfoExtension,0.1.0"); Assert.IsTrue (AddinManager.Registry.IsAddinEnabled ("SimpleApp.SystemInfoExtension"), "t3.1"); Assert.AreEqual (3, AddinManager.GetExtensionNodes ("/SimpleApp/Writers").Count, "count 4"); Assert.IsFalse (AddinManager.Registry.IsAddinEnabled ("SimpleApp.FileContentExtension"), "t4"); AddinManager.Registry.EnableAddin ("SimpleApp.FileContentExtension,0.1.0"); Assert.IsTrue (AddinManager.Registry.IsAddinEnabled ("SimpleApp.FileContentExtension"), "t4.1"); Assert.AreEqual (4, AddinManager.GetExtensionNodes ("/SimpleApp/Writers").Count, "count 5"); ResetStatus (true); } [Test()] public void TestDisableWithDeps () { Addin ainfo; Assert.AreEqual (4, AddinManager.GetExtensionNodes ("/SimpleApp/Writers").Count, "count 1"); ainfo = AddinManager.Registry.GetAddin ("SimpleApp.HelloWorldExtension"); Assert.IsNotNull (ainfo, "t1"); Assert.IsTrue (ainfo.Enabled, "t1.1"); ainfo.Enabled = false; Assert.IsFalse (ainfo.Enabled, "t1.2"); Assert.AreEqual (3, AddinManager.GetExtensionNodes ("/SimpleApp/Writers").Count, "count 2"); ainfo = AddinManager.Registry.GetAddin ("SimpleApp.CommandExtension"); Assert.IsNotNull (ainfo, "t2"); Assert.IsTrue (ainfo.Enabled, "t2.1"); ainfo.Enabled = false; Assert.IsFalse (ainfo.Enabled, "t2.2"); // SystemInfoExtension depends on CommandExtension, so it should be disabled after disabling CommandExtension Assert.AreEqual (1, AddinManager.GetExtensionNodes ("/SimpleApp/Writers").Count, "count 3"); ainfo = AddinManager.Registry.GetAddin ("SimpleApp.SystemInfoExtension"); Assert.IsNotNull (ainfo, "t4"); Assert.IsFalse (ainfo.Enabled, "t4.1"); // FileContentExtension depends on SystemInfoExtension, but the dependency is optional ainfo = AddinManager.Registry.GetAddin ("SimpleApp.FileContentExtension"); Assert.IsNotNull (ainfo, "t5"); Assert.IsTrue (ainfo.Enabled, "t5.1"); ainfo.Enabled = false; Assert.IsFalse (ainfo.Enabled, "t5.2"); Assert.AreEqual (0, AddinManager.GetExtensionNodes ("/SimpleApp/Writers").Count, "count 4"); ResetStatus (true); } [Test()] public void TestEnableWithDeps () { ResetStatus (false); Addin ainfo; Assert.AreEqual (0, AddinManager.GetExtensionNodes ("/SimpleApp/Writers").Count, "count 1"); ainfo = AddinManager.Registry.GetAddin ("SimpleApp.HelloWorldExtension"); Assert.IsNotNull (ainfo, "t1"); Assert.IsFalse (ainfo.Enabled, "t1.1"); ainfo.Enabled = true; Assert.IsTrue (ainfo.Enabled, "t1.2"); Assert.AreEqual (1, AddinManager.GetExtensionNodes ("/SimpleApp/Writers").Count, "count 2"); ainfo = AddinManager.Registry.GetAddin ("SimpleApp.FileContentExtension"); Assert.IsNotNull (ainfo, "t3"); Assert.IsFalse (ainfo.Enabled, "t3.1"); ainfo.Enabled = true; Assert.IsTrue (ainfo.Enabled, "t3.2"); Assert.AreEqual (2, AddinManager.GetExtensionNodes ("/SimpleApp/Writers").Count, "count 3"); ainfo = AddinManager.Registry.GetAddin ("SimpleApp.SystemInfoExtension"); Assert.IsNotNull (ainfo, "t5"); Assert.IsFalse (ainfo.Enabled, "t5.1"); ainfo.Enabled = true; Assert.IsTrue (ainfo.Enabled, "t5.2"); Assert.AreEqual (4, AddinManager.GetExtensionNodes ("/SimpleApp/Writers").Count, "count 4"); ainfo = AddinManager.Registry.GetAddin ("SimpleApp.CommandExtension"); Assert.IsNotNull (ainfo, "t2"); Assert.IsTrue (ainfo.Enabled, "t2.1"); ResetStatus (true); } [Test()] public void TestCurrentAddin () { InstanceExtensionNode node = (InstanceExtensionNode) AddinManager.GetExtensionNode ("/SimpleApp/Writers/HelloWorldExtension.HelloWorldWriter"); Assert.IsNotNull (node, "t1"); // Assembly load happens only after the node was created. Assert.AreEqual ("SimpleApp.Core,0.1.0", AddinManager.CurrentAddin.ToString ()); IWriter w = (IWriter) node.CreateInstance (); Assert.AreEqual ("SimpleApp.HelloWorldExtension,0.1.0", w.Test ("currentAddin")); } public class TestClass { public string Value; } [Test] public void TestAddinAssemblyLoading () { // Test for bug 672858 - Mono.Addins causes error in XML serializer Environment.SetEnvironmentVariable ("MONO_XMLSERIALIZER_THS","0"); XmlSerializer ser = new XmlSerializer (typeof(TestClass)); ser.Serialize (new StringWriter (), new TestClass ()); } [Test()] public void TestLoadLatestVersion () { ExtensionNodeList list = AddinManager.GetExtensionNodes ("/SimpleApp/InstallUninstallTest"); Assert.AreEqual (1, list.Count); Assert.AreEqual ("10.2", ((ItemSetNode)list[0]).Label); } } }
using System; using System.Linq; using System.Media; using System.Windows.Forms; using System.Collections.Generic; using System.Reflection; using PKHeX.Core; using PKHeX.WinForms.Properties; using PKHeX.WinForms.AutoLegality; namespace PKHeX.WinForms.Controls { public partial class PKMEditor : UserControl { /// <summary> /// Helper function to print out a byte array as a string that can be used within code /// </summary> /// <param name="bytes">byte array</param> public void PrintByteArray(byte[] bytes) { var sb = new System.Text.StringBuilder("new byte[] { "); foreach (var b in bytes) { sb.Append(b + ", "); } sb.Append("}"); Console.WriteLine(sb.ToString()); } /// <summary> /// Accessible method to lead Fields from PKM /// The Loading is done in WinForms /// </summary> /// <param name="pk">The PKM file</param> /// <param name="focus">Set input focus to control</param> /// <param name="skipConversionCheck">Default this to true</param> public void LoadFieldsFromPKM2(PKM pk, bool focus = true, bool skipConversionCheck = true) { if (pk == null) { WinFormsUtil.Error("Attempted to load a null file."); return; } if (focus) Tab_Main.Focus(); if (!skipConversionCheck && !PKMConverter.TryMakePKMCompatible(pk, CurrentPKM, out string c, out pk)) { WinFormsUtil.Alert(c); return; } bool oldInit = FieldsInitialized; FieldsInitialized = FieldsLoaded = false; pkm = pk.Clone(); try { GetFieldsfromPKM(); } finally { FieldsInitialized = oldInit; } Stats.UpdateIVs(null, null); UpdatePKRSInfected(null, null); UpdatePKRSCured(null, null); if (HaX) // Load original values from pk not pkm { MT_Level.Text = (pk.Stat_HPMax != 0 ? pk.Stat_Level : PKX.GetLevel(pk.EXP, pk.Species, pk.AltForm)).ToString(); TB_EXP.Text = pk.EXP.ToString(); MT_Form.Text = pk.AltForm.ToString(); if (pk.Stat_HPMax != 0) // stats present { Stats.LoadPartyStats(pk); } } FieldsLoaded = true; SetMarkings(); UpdateLegality(); UpdateSprite(); LastData = PreparePKM()?.Data; } /// <summary> /// Load PKM from byte array. The output is a boolean, which is true if a byte array is loaded into WinForms, else false /// </summary> /// <param name="input">Byte array input correlating to the PKM</param> /// <param name="path">Path to the file itself</param> /// <param name="ext">Extension of the file</param> /// <param name="SAV">Type of save file</param> /// <returns></returns> private bool TryLoadPKM(byte[] input, string path, string ext, SaveFile SAV) { var temp = PKMConverter.GetPKMfromBytes(input, prefer: ext.Length > 0 ? (ext.Last() - 0x30) & 7 : SAV.Generation); if (temp == null) return false; var type = CurrentPKM.GetType(); PKM pk = PKMConverter.ConvertToType(temp, type, out string c); if (pk == null) { return false; } if (SAV.Generation < 3 && ((pk as PK1)?.Japanese ?? ((PK2)pk).Japanese) != SAV.Japanese) { var strs = new[] { "International", "Japanese" }; var val = SAV.Japanese ? 0 : 1; WinFormsUtil.Alert($"Cannot load {strs[val]} {pk.GetType().Name}s to {strs[val ^ 1]} saves."); return false; } PopulateFields(pk); Console.WriteLine(c); return true; } /// <summary> /// Set Country, SubRegion and Console in WinForms /// </summary> /// <param name="Country">String denoting the exact country</param> /// <param name="SubRegion">String denoting the exact sub region</param> /// <param name="ConsoleRegion">String denoting the exact console region</param> public void SetRegions(string Country, string SubRegion, string ConsoleRegion, PKM pk) { pk.Country = Util.GetCBList("countries", "en").FirstOrDefault(z => z.Text == Country).Value; pk.Region = Util.GetCBList($"sr_{pk.Country:000}", "en").FirstOrDefault(z => z.Text == SubRegion).Value; pk.ConsoleRegion = Util.GetUnsortedCBList("regions3ds").FirstOrDefault(z => z.Text == ConsoleRegion).Value; } /// <summary> /// Set Country, SubRegion and ConsoleRegion in a PKM directly /// </summary> /// <param name="Country">INT value corresponding to the index of the Country</param> /// <param name="SubRegion">INT value corresponding to the index of the sub region</param> /// <param name="ConsoleRegion">INT value corresponding to the index of the console region</param> /// <param name="pk"></param> /// <returns></returns> public PKM SetPKMRegions(int Country, int SubRegion, int ConsoleRegion, PKM pk) { pk.Country = Country; pk.Region = SubRegion; pk.ConsoleRegion = ConsoleRegion; return pk; } /// <summary> /// Set TID, SID and OT /// </summary> /// <param name="OT">string value of OT name</param> /// <param name="TID">INT value of TID</param> /// <param name="SID">INT value of SID</param> /// <param name="pk"></param> /// <returns></returns> public PKM SetTrainerData(string OT, int TID, int SID, int gender, PKM pk, bool APILegalized = false) { if (APILegalized) { if ((pk.TID == 12345 && pk.OT_Name == "PKHeX") || (pk.TID == 34567 && pk.SID == 0 && pk.OT_Name == "TCD")) { bool Shiny = pk.IsShiny; pk.TID = TID; pk.SID = SID; pk.OT_Name = OT; pk.OT_Gender = gender; AutoLegalityModMain.AutoLegalityMod.SetShinyBoolean(pk, Shiny); } return pk; } pk.TID = TID; pk.SID = SID; pk.OT_Name = OT; return pk; } /// <summary> /// Check the mode for trainerdata.json /// </summary> /// <param name="jsonstring">string form of trainerdata.json</param> /// <returns></returns> public string checkMode(string jsonstring = "") { if(jsonstring != "") { string mode = "save"; if (jsonstring.Contains("mode")) mode = jsonstring.Split(new string[] { "\"mode\"" }, StringSplitOptions.None)[1].Split('"')[1].ToLower(); if (mode != "game" && mode != "save" && mode != "auto") mode = "save"; // User Mistake or for some reason this exists as a value of some other key return mode; } else { if (!System.IO.File.Exists(System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\trainerdata.json")) { return "save"; // Default trainerdata.txt handling } jsonstring = System.IO.File.ReadAllText(System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\trainerdata.json", System.Text.Encoding.UTF8); if (jsonstring != "") return checkMode(jsonstring); else { WinFormsUtil.Alert("Empty trainerdata.json file"); return "save"; } } } /// <summary> /// check if the game exists in the json file. If not handle via trainerdata.txt method /// </summary> /// <param name="jsonstring">Complete trainerdata.json string</param> /// <param name="Game">int value of the game</param> /// <param name="jsonvalue">internal json: trainerdata[Game]</param> /// <returns></returns> public bool checkIfGameExists(string jsonstring, int Game, out string jsonvalue) { jsonvalue = ""; if (checkMode(jsonstring) == "auto") { jsonvalue = "auto"; return false; } if (!jsonstring.Contains("\"" + Game.ToString() + "\"")) return false; foreach (string s in jsonstring.Split(new string[] { "\"" + Game.ToString() + "\"" }, StringSplitOptions.None)) { if (s.Trim()[0] == ':') { int index = jsonstring.IndexOf(s); jsonvalue = jsonstring.Substring(index).Split('{')[1].Split('}')[0].Trim(); return true; } } return false; } /// <summary> /// String parse key to find value from final json /// </summary> /// <param name="key"></param> /// <param name="finaljson"></param> /// <returns></returns> public string getValueFromKey(string key, string finaljson) { return finaljson.Split(new string[] { key }, StringSplitOptions.None)[1].Split('"')[2].Trim(); } /// <summary> /// Convert TID7 and SID7 back to the conventional TID, SID /// </summary> /// <param name="tid7">TID7 value</param> /// <param name="sid7">SID7 value</param> /// <returns></returns> public int[] ConvertTIDSID7toTIDSID(int tid7, int sid7) { var repack = (long)sid7 * 1_000_000 + tid7; int sid = (ushort)(repack >> 16); int tid = (ushort)repack; return new int[] { tid, sid }; } /// <summary> /// Function to extract trainerdata values from trainerdata.json /// </summary> /// <param name="C_SAV">Current Save Editor</param> /// <param name="Game">optional Game value in case of mode being game</param> /// <returns></returns> public string[] parseTrainerJSON(SAVEditor C_SAV, int Game = -1) { if (!System.IO.File.Exists(System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\trainerdata.json")) { return parseTrainerData(C_SAV); // Default trainerdata.txt handling } string jsonstring = System.IO.File.ReadAllText(System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\trainerdata.json", System.Text.Encoding.UTF8); if (Game == -1) Game = C_SAV.SAV.Game; if(!checkIfGameExists(jsonstring, Game, out string finaljson)) return parseTrainerData(C_SAV, finaljson == "auto"); string TID = getValueFromKey("TID", finaljson); string SID = getValueFromKey("SID", finaljson); string OT = getValueFromKey("OT", finaljson); string Gender = getValueFromKey("Gender", finaljson); string Country = getValueFromKey("Country", finaljson); string SubRegion = getValueFromKey("SubRegion", finaljson); string ConsoleRegion = getValueFromKey("3DSRegion", finaljson); if (TID.Length == 6 && SID.Length == 4) { if(new List<int> { 33, 32, 31, 30 }.IndexOf(Game) == -1) WinFormsUtil.Alert("Force Converting G7TID/G7SID to TID/SID"); int[] tidsid = ConvertTIDSID7toTIDSID(int.Parse(TID), int.Parse(SID)); TID = tidsid[0].ToString(); SID = tidsid[1].ToString(); } return new string[] { TID, SID, OT, Gender, Country, SubRegion, ConsoleRegion }; } /// <summary> /// Parser for auto and preset trainerdata.txt files /// </summary> /// <param name="C_SAV">SAVEditor of the current save file</param> /// <returns></returns> public string[] parseTrainerData(SAVEditor C_SAV, bool auto = false) { // Defaults string TID = "23456"; string SID = "34567"; string OT = "Archit"; string Gender = "M"; string Country = "Canada"; string SubRegion = "Alberta"; string ConsoleRegion = "Americas (NA/SA)"; if (!System.IO.File.Exists(System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\trainerdata.txt")) { return new string[] { TID, SID, OT, Gender, Country, SubRegion, ConsoleRegion}; // Default No trainerdata.txt handling } string[] trainerdataLines = System.IO.File.ReadAllText(System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\trainerdata.txt", System.Text.Encoding.UTF8) .Split(new string[] { Environment.NewLine }, StringSplitOptions.None); List<string> lstlines = trainerdataLines.OfType<string>().ToList(); int count = lstlines.Count; for (int i =0; i < count; i++) { string item = lstlines[0]; if (item.TrimEnd() == "" || item.TrimEnd() == "auto") continue; string key = item.Split(':')[0].TrimEnd(); string value = item.Split(':')[1].TrimEnd(); lstlines.RemoveAt(0); if (key == "TID") TID = value; else if (key == "SID") SID = value; else if (key == "OT") OT = value; else if (key == "Gender") Gender = value; else if (key == "Country") Country = value; else if (key == "SubRegion") SubRegion = value; else if (key == "3DSRegion") ConsoleRegion = value; else continue; } // Automatic loading if (trainerdataLines[0] == "auto" || auto) { try { int ct = PKMConverter.Country; int sr = PKMConverter.Region; int cr = PKMConverter.ConsoleRegion; if (C_SAV.SAV.Gender == 1) Gender = "F"; return new string[] { C_SAV.SAV.TID.ToString("00000"), C_SAV.SAV.SID.ToString("00000"), C_SAV.SAV.OT, Gender, ct.ToString(), sr.ToString(), cr.ToString()}; } catch { return new string[] { TID, SID, OT, Gender, Country, SubRegion, ConsoleRegion }; } } if (TID.Length == 6 && SID.Length == 4) { int[] tidsid = ConvertTIDSID7toTIDSID(int.Parse(TID), int.Parse(SID)); TID = tidsid[0].ToString(); SID = tidsid[1].ToString(); } return new string[] { TID, SID, OT, Gender, Country, SubRegion, ConsoleRegion }; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Suppression; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions { [Export(typeof(ISuggestedActionsSourceProvider))] [VisualStudio.Utilities.ContentType(ContentTypeNames.RoslynContentType)] [VisualStudio.Utilities.Name("Roslyn Code Fix")] [VisualStudio.Utilities.Order] internal class SuggestedActionsSourceProvider : ISuggestedActionsSourceProvider { private static readonly Guid s_CSharpSourceGuid = new Guid("b967fea8-e2c3-4984-87d4-71a38f49e16a"); private static readonly Guid s_visualBasicSourceGuid = new Guid("4de30e93-3e0c-40c2-a4ba-1124da4539f6"); private const int InvalidSolutionVersion = -1; private readonly ICodeRefactoringService _codeRefactoringService; private readonly IDiagnosticAnalyzerService _diagnosticService; private readonly ICodeFixService _codeFixService; private readonly ICodeActionEditHandlerService _editHandler; private readonly IAsynchronousOperationListener _listener; [ImportingConstructor] public SuggestedActionsSourceProvider( ICodeRefactoringService codeRefactoringService, IDiagnosticAnalyzerService diagnosticService, ICodeFixService codeFixService, ICodeActionEditHandlerService editHandler, [ImportMany] IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> asyncListeners) { _codeRefactoringService = codeRefactoringService; _diagnosticService = diagnosticService; _codeFixService = codeFixService; _editHandler = editHandler; _listener = new AggregateAsynchronousOperationListener(asyncListeners, FeatureAttribute.LightBulb); } public ISuggestedActionsSource CreateSuggestedActionsSource(ITextView textView, ITextBuffer textBuffer) { Contract.ThrowIfNull(textView); Contract.ThrowIfNull(textBuffer); return new Source(this, textView, textBuffer); } private class Source : ForegroundThreadAffinitizedObject, ISuggestedActionsSource { // state that will be only reset when source is disposed. private SuggestedActionsSourceProvider _owner; private ITextView _textView; private ITextBuffer _subjectBuffer; private WorkspaceRegistration _registration; // mutable state private Workspace _workspace; private int _lastSolutionVersionReported; public Source(SuggestedActionsSourceProvider owner, ITextView textView, ITextBuffer textBuffer) { _owner = owner; _textView = textView; _textView.Closed += OnTextViewClosed; _subjectBuffer = textBuffer; _registration = Workspace.GetWorkspaceRegistration(textBuffer.AsTextContainer()); _lastSolutionVersionReported = InvalidSolutionVersion; var updateSource = (IDiagnosticUpdateSource)_owner._diagnosticService; updateSource.DiagnosticsUpdated += OnDiagnosticsUpdated; if (_registration.Workspace != null) { _workspace = _registration.Workspace; _workspace.DocumentActiveContextChanged += OnActiveContextChanged; } _registration.WorkspaceChanged += OnWorkspaceChanged; } public event EventHandler<EventArgs> SuggestedActionsChanged; public bool TryGetTelemetryId(out Guid telemetryId) { telemetryId = default(Guid); var workspace = _workspace; if (workspace == null || _subjectBuffer == null) { return false; } var documentId = workspace.GetDocumentIdInCurrentContext(_subjectBuffer.AsTextContainer()); if (documentId == null) { return false; } var project = workspace.CurrentSolution.GetProject(documentId.ProjectId); if (project == null) { return false; } switch (project.Language) { case LanguageNames.CSharp: telemetryId = s_CSharpSourceGuid; return true; case LanguageNames.VisualBasic: telemetryId = s_visualBasicSourceGuid; return true; default: return false; } } public IEnumerable<SuggestedActionSet> GetSuggestedActions(ISuggestedActionCategorySet requestedActionCategories, SnapshotSpan range, CancellationToken cancellationToken) { AssertIsForeground(); using (Logger.LogBlock(FunctionId.SuggestedActions_GetSuggestedActions, cancellationToken)) { var documentAndSnapshot = GetMatchingDocumentAndSnapshotAsync(range.Snapshot, cancellationToken).WaitAndGetResult(cancellationToken); if (!documentAndSnapshot.HasValue) { // this is here to fail test and see why it is failed. Trace.WriteLine("given range is not current"); return null; } var document = documentAndSnapshot.Value.Item1; var workspace = document.Project.Solution.Workspace; var supportsFeatureService = workspace.Services.GetService<IDocumentSupportsFeatureService>(); var fixes = GetCodeFixes(supportsFeatureService, requestedActionCategories, workspace, document, range, cancellationToken); var refactorings = GetRefactorings(supportsFeatureService, requestedActionCategories, workspace, document, range, cancellationToken); var result = fixes == null ? refactorings : refactorings == null ? fixes : fixes.Concat(refactorings); if (result == null) { return null; } var allActionSets = result.ToList(); allActionSets = InlineActionSetsIfDesirable(allActionSets); return allActionSets; } } private List<SuggestedActionSet> InlineActionSetsIfDesirable(List<SuggestedActionSet> allActionSets) { // If we only have a single set of items, and that set only has three max suggestion // offered. Then we can consider inlining any nested actions into the top level list. // (but we only do this if the parent of the nested actions isn't invokable itself). if (allActionSets.Sum(a => a.Actions.Count()) > 3) { return allActionSets; } return allActionSets.Select(InlineActions).ToList(); } private bool IsInlineable(ISuggestedAction action) { var suggestedAction = action as SuggestedAction; return suggestedAction != null && !suggestedAction.CodeAction.IsInvokable && suggestedAction.CodeAction.HasCodeActions; } private SuggestedActionSet InlineActions(SuggestedActionSet actionSet) { if (!actionSet.Actions.Any(IsInlineable)) { return actionSet; } var newActions = new List<ISuggestedAction>(); foreach (var action in actionSet.Actions) { if (IsInlineable(action)) { // Looks like something we can inline. var childActionSets = ((SuggestedAction)action).GetActionSets(); if (childActionSets.Length != 1) { return actionSet; } newActions.AddRange(childActionSets[0].Actions); } newActions.Add(action); } return new SuggestedActionSet(newActions, actionSet.Title, actionSet.Priority, actionSet.ApplicableToSpan); } private IEnumerable<SuggestedActionSet> GetCodeFixes( IDocumentSupportsFeatureService supportsFeatureService, ISuggestedActionCategorySet requestedActionCategories, Workspace workspace, Document document, SnapshotSpan range, CancellationToken cancellationToken) { if (_owner._codeFixService != null && supportsFeatureService.SupportsCodeFixes(document) && requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.CodeFix)) { // We only include suppressions if lightbulb is asking for everything. // If the light bulb is only asking for code fixes, then we don't include suppressions. var includeSuppressionFixes = requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.Any); var fixes = Task.Run( async () => await _owner._codeFixService.GetFixesAsync( document, range.Span.ToTextSpan(), includeSuppressionFixes, cancellationToken).ConfigureAwait(false), cancellationToken).WaitAndGetResult(cancellationToken); return OrganizeFixes(workspace, fixes, hasSuppressionFixes: includeSuppressionFixes); } return null; } /// <summary> /// Arrange fixes into groups based on the issue (diagnostic being fixed) and prioritize these groups. /// </summary> private IEnumerable<SuggestedActionSet> OrganizeFixes(Workspace workspace, IEnumerable<CodeFixCollection> fixCollections, bool hasSuppressionFixes) { var map = ImmutableDictionary.CreateBuilder<DiagnosticData, IList<SuggestedAction>>(); var order = ImmutableArray.CreateBuilder<DiagnosticData>(); // First group fixes by issue (diagnostic). GroupFixes(workspace, fixCollections, map, order, hasSuppressionFixes); // Then prioritize between the groups. return PrioritizeFixGroups(map.ToImmutable(), order.ToImmutable()); } /// <summary> /// Groups fixes by the diagnostic being addressed by each fix. /// </summary> private void GroupFixes(Workspace workspace, IEnumerable<CodeFixCollection> fixCollections, IDictionary<DiagnosticData, IList<SuggestedAction>> map, IList<DiagnosticData> order, bool hasSuppressionFixes) { foreach (var fixCollection in fixCollections) { var fixes = fixCollection.Fixes; var fixCount = fixes.Length; Func<CodeAction, SuggestedActionSet> getFixAllSuggestedActionSet = codeAction => CodeFixSuggestedAction.GetFixAllSuggestedActionSet(codeAction, fixCount, fixCollection.FixAllContext, workspace, _subjectBuffer, _owner._editHandler); foreach (var fix in fixes) { // Suppression fixes are handled below. if (!(fix.Action is SuppressionCodeAction)) { SuggestedAction suggestedAction; if (fix.Action.HasCodeActions) { var nestedActions = new List<SuggestedAction>(); foreach (var nestedAction in fix.Action.GetCodeActions()) { nestedActions.Add(new CodeFixSuggestedAction(workspace, _subjectBuffer, _owner._editHandler, fix, nestedAction, fixCollection.Provider, getFixAllSuggestedActionSet(nestedAction))); } var diag = fix.PrimaryDiagnostic; var set = new SuggestedActionSet(nestedActions, SuggestedActionSetPriority.Medium, diag.Location.SourceSpan.ToSpan()); suggestedAction = new SuggestedAction(workspace, _subjectBuffer, _owner._editHandler, fix.Action, fixCollection.Provider, new[] { set }); } else { suggestedAction = new CodeFixSuggestedAction(workspace, _subjectBuffer, _owner._editHandler, fix, fix.Action, fixCollection.Provider, getFixAllSuggestedActionSet(fix.Action)); } AddFix(fix, suggestedAction, map, order); } } if (hasSuppressionFixes) { // Add suppression fixes to the end of a given SuggestedActionSet so that they always show up last in a group. foreach (var fix in fixes) { if (fix.Action is SuppressionCodeAction) { SuggestedAction suggestedAction; if (fix.Action.HasCodeActions) { suggestedAction = new SuppressionSuggestedAction(workspace, _subjectBuffer, _owner._editHandler, fix, fixCollection.Provider, getFixAllSuggestedActionSet); } else { suggestedAction = new CodeFixSuggestedAction(workspace, _subjectBuffer, _owner._editHandler, fix, fix.Action, fixCollection.Provider, getFixAllSuggestedActionSet(fix.Action)); } AddFix(fix, suggestedAction, map, order); } } } } } private static void AddFix(CodeFix fix, SuggestedAction suggestedAction, IDictionary<DiagnosticData, IList<SuggestedAction>> map, IList<DiagnosticData> order) { var diag = fix.GetPrimaryDiagnosticData(); if (!map.ContainsKey(diag)) { // Remember the order of the keys for the 'map' dictionary. order.Add(diag); map[diag] = ImmutableArray.CreateBuilder<SuggestedAction>(); } map[diag].Add(suggestedAction); } /// <summary> /// Return prioritized set of fix groups such that fix group for suppression always show up at the bottom of the list. /// </summary> /// <remarks> /// Fix groups are returned in priority order determined based on <see cref="ExtensionOrderAttribute"/>. /// Priority for all <see cref="SuggestedActionSet"/>s containing fixes is set to <see cref="SuggestedActionSetPriority.Medium"/> by default. /// The only exception is the case where a <see cref="SuggestedActionSet"/> only contains suppression fixes - /// the priority of such <see cref="SuggestedActionSet"/>s is set to <see cref="SuggestedActionSetPriority.None"/> so that suppression fixes /// always show up last after all other fixes (and refactorings) for the selected line of code. /// </remarks> private static IEnumerable<SuggestedActionSet> PrioritizeFixGroups(IDictionary<DiagnosticData, IList<SuggestedAction>> map, IList<DiagnosticData> order) { var sets = ImmutableArray.CreateBuilder<SuggestedActionSet>(); foreach (var diag in order) { var fixes = map[diag]; var priority = fixes.All(s => s is SuppressionSuggestedAction) ? SuggestedActionSetPriority.None : SuggestedActionSetPriority.Medium; // diagnostic from things like build shouldn't reach here since we don't support LB for those diagnostics Contract.Requires(diag.HasTextSpan); sets.Add(new SuggestedActionSet(fixes, priority, diag.TextSpan.ToSpan())); } return sets.ToImmutable(); } private IEnumerable<SuggestedActionSet> GetRefactorings( IDocumentSupportsFeatureService supportsFeatureService, ISuggestedActionCategorySet requestedActionCategories, Workspace workspace, Document document, SnapshotSpan range, CancellationToken cancellationToken) { var optionService = workspace.Services.GetService<IOptionService>(); if (optionService.GetOption(EditorComponentOnOffOptions.CodeRefactorings) && _owner._codeRefactoringService != null && supportsFeatureService.SupportsRefactorings(document) && requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.Refactoring)) { // Get the selection while on the UI thread. var selection = TryGetCodeRefactoringSelection(_subjectBuffer, _textView, range); if (!selection.HasValue) { // this is here to fail test and see why it is failed. Trace.WriteLine("given range is not current"); return null; } var refactorings = Task.Run( async () => await _owner._codeRefactoringService.GetRefactoringsAsync( document, selection.Value, cancellationToken).ConfigureAwait(false), cancellationToken).WaitAndGetResult(cancellationToken); return refactorings.Select(r => OrganizeRefactorings(workspace, r)); } return null; } /// <summary> /// Arrange refactorings into groups. /// </summary> /// <remarks> /// Refactorings are returned in priority order determined based on <see cref="ExtensionOrderAttribute"/>. /// Priority for all <see cref="SuggestedActionSet"/>s containing refactorings is set to <see cref="SuggestedActionSetPriority.Low"/> /// and should show up after fixes but before suppression fixes in the light bulb menu. /// </remarks> private SuggestedActionSet OrganizeRefactorings(Workspace workspace, CodeRefactoring refactoring) { var refactoringSuggestedActions = ImmutableArray.CreateBuilder<SuggestedAction>(); foreach (var a in refactoring.Actions) { refactoringSuggestedActions.Add( new CodeRefactoringSuggestedAction( workspace, _subjectBuffer, _owner._editHandler, a, refactoring.Provider)); } return new SuggestedActionSet(refactoringSuggestedActions.ToImmutable(), SuggestedActionSetPriority.Low); } public async Task<bool> HasSuggestedActionsAsync(ISuggestedActionCategorySet requestedActionCategories, SnapshotSpan range, CancellationToken cancellationToken) { // Explicitly hold onto below fields in locals and use these locals throughout this code path to avoid crashes // if these fields happen to be cleared by Dispose() below. This is required since this code path involves // code that can run asynchronously from background thread. var view = _textView; var buffer = _subjectBuffer; var provider = _owner; if (view == null || buffer == null || provider == null) { return false; } using (var asyncToken = provider._listener.BeginAsyncOperation("HasSuggestedActionsAsync")) { var documentAndSnapshot = await GetMatchingDocumentAndSnapshotAsync(range.Snapshot, cancellationToken).ConfigureAwait(false); if (!documentAndSnapshot.HasValue) { // this is here to fail test and see why it is failed. Trace.WriteLine("given range is not current"); return false; } var document = documentAndSnapshot.Value.Item1; var workspace = document.Project.Solution.Workspace; var supportsFeatureService = workspace.Services.GetService<IDocumentSupportsFeatureService>(); return await HasFixesAsync( supportsFeatureService, requestedActionCategories, provider, document, range, cancellationToken).ConfigureAwait(false) || await HasRefactoringsAsync( supportsFeatureService, requestedActionCategories, provider, document, buffer, view, range, cancellationToken).ConfigureAwait(false); } } private async Task<bool> HasFixesAsync( IDocumentSupportsFeatureService supportsFeatureService, ISuggestedActionCategorySet requestedActionCategories, SuggestedActionsSourceProvider provider, Document document, SnapshotSpan range, CancellationToken cancellationToken) { if (provider._codeFixService != null && supportsFeatureService.SupportsCodeFixes(document) && requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.CodeFix)) { // We only consider suppressions if lightbulb is asking for everything. // If the light bulb is only asking for code fixes, then we don't consider suppressions. var considerSuppressionFixes = requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.Any); var result = await Task.Run( async () => await provider._codeFixService.GetFirstDiagnosticWithFixAsync( document, range.Span.ToTextSpan(), considerSuppressionFixes, cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false); if (result.HasFix) { Logger.Log(FunctionId.SuggestedActions_HasSuggestedActionsAsync); return true; } if (result.PartialResult) { // reset solution version number so that we can raise suggested action changed event Volatile.Write(ref _lastSolutionVersionReported, InvalidSolutionVersion); return false; } } return false; } private async Task<bool> HasRefactoringsAsync( IDocumentSupportsFeatureService supportsFeatureService, ISuggestedActionCategorySet requestedActionCategories, SuggestedActionsSourceProvider provider, Document document, ITextBuffer buffer, ITextView view, SnapshotSpan range, CancellationToken cancellationToken) { var optionService = document.Project.Solution.Workspace.Services.GetService<IOptionService>(); if (optionService.GetOption(EditorComponentOnOffOptions.CodeRefactorings) && provider._codeRefactoringService != null && supportsFeatureService.SupportsRefactorings(document) && requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.Refactoring)) { TextSpan? selection = null; if (IsForeground()) { // This operation needs to happen on UI thread because it needs to access textView.Selection. selection = TryGetCodeRefactoringSelection(buffer, view, range); } else { await InvokeBelowInputPriority(() => { // This operation needs to happen on UI thread because it needs to access textView.Selection. selection = TryGetCodeRefactoringSelection(buffer, view, range); }).ConfigureAwait(false); } if (!selection.HasValue) { // this is here to fail test and see why it is failed. Trace.WriteLine("given range is not current"); return false; } return await Task.Run( async () => await provider._codeRefactoringService.HasRefactoringsAsync( document, selection.Value, cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false); } return false; } private static TextSpan? TryGetCodeRefactoringSelection(ITextBuffer buffer, ITextView view, SnapshotSpan range) { var selectedSpans = view.Selection.SelectedSpans .SelectMany(ss => view.BufferGraph.MapDownToBuffer(ss, SpanTrackingMode.EdgeExclusive, buffer)) .Where(ss => !view.IsReadOnlyOnSurfaceBuffer(ss)) .ToList(); // We only support refactorings when there is a single selection in the document. if (selectedSpans.Count != 1) { return null; } var translatedSpan = selectedSpans[0].TranslateTo(range.Snapshot, SpanTrackingMode.EdgeInclusive); // We only support refactorings when selected span intersects with the span that the light bulb is asking for. if (!translatedSpan.IntersectsWith(range)) { return null; } return translatedSpan.Span.ToTextSpan(); } private static async Task<ValueTuple<Document, ITextSnapshot>?> GetMatchingDocumentAndSnapshotAsync(ITextSnapshot givenSnapshot, CancellationToken cancellationToken) { var buffer = givenSnapshot.TextBuffer; if (buffer == null) { return null; } var workspace = buffer.GetWorkspace(); if (workspace == null) { return null; } var documentId = workspace.GetDocumentIdInCurrentContext(buffer.AsTextContainer()); if (documentId == null) { return null; } var document = workspace.CurrentSolution.GetDocument(documentId); if (document == null) { return null; } var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var snapshot = sourceText.FindCorrespondingEditorTextSnapshot(); if (snapshot == null || snapshot.Version.ReiteratedVersionNumber != givenSnapshot.Version.ReiteratedVersionNumber) { return null; } return ValueTuple.Create(document, snapshot); } private void OnTextViewClosed(object sender, EventArgs e) { Dispose(); } private void OnWorkspaceChanged(object sender, EventArgs e) { // REVIEW: this event should give both old and new workspace as argument so that // one doesnt need to hold onto workspace in field. // remove existing event registration if (_workspace != null) { _workspace.DocumentActiveContextChanged -= OnActiveContextChanged; } // REVIEW: why one need to get new workspace from registration? why not just pass in the new workspace? // add new event registration _workspace = _registration.Workspace; if (_workspace != null) { _workspace.DocumentActiveContextChanged += OnActiveContextChanged; } } private void OnActiveContextChanged(object sender, DocumentEventArgs e) { // REVIEW: it would be nice for changed event to pass in both old and new document. OnSuggestedActionsChanged(e.Document.Project.Solution.Workspace, e.Document.Id, e.Document.Project.Solution.WorkspaceVersion); } private void OnDiagnosticsUpdated(object sender, DiagnosticsUpdatedArgs e) { // document removed case. no reason to raise event if (e.Solution == null) { return; } OnSuggestedActionsChanged(e.Workspace, e.DocumentId, e.Solution.WorkspaceVersion); } private void OnSuggestedActionsChanged(Workspace currentWorkspace, DocumentId currentDocumentId, int solutionVersion, DiagnosticsUpdatedArgs args = null) { // Explicitly hold onto the _subjectBuffer field in a local and use this local in this function to avoid crashes // if this field happens to be cleared by Dispose() below. This is required since this code path involves code // that can run on background thread. var buffer = _subjectBuffer; if (buffer == null) { return; } var workspace = buffer.GetWorkspace(); // workspace is not ready, nothing to do. if (workspace == null || workspace != currentWorkspace) { return; } if (currentDocumentId != workspace.GetDocumentIdInCurrentContext(buffer.AsTextContainer()) || solutionVersion == Volatile.Read(ref _lastSolutionVersionReported)) { return; } // make sure we only raise event once for same solution version. // light bulb controller will call us back to find out new information var changed = this.SuggestedActionsChanged; if (changed != null) { changed(this, EventArgs.Empty); } Volatile.Write(ref _lastSolutionVersionReported, solutionVersion); } public void Dispose() { if (_owner != null) { var updateSource = (IDiagnosticUpdateSource)_owner._diagnosticService; updateSource.DiagnosticsUpdated -= OnDiagnosticsUpdated; _owner = null; } if (_workspace != null) { _workspace.DocumentActiveContextChanged -= OnActiveContextChanged; _workspace = null; } if (_registration != null) { _registration.WorkspaceChanged -= OnWorkspaceChanged; _registration = null; } if (_textView != null) { _textView.Closed -= OnTextViewClosed; _textView = null; } if (_subjectBuffer != null) { _subjectBuffer = null; } } } } }
/* * UltraCart Rest API V2 * * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: support@ultracart.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter; namespace com.ultracart.admin.v2.Model { /// <summary> /// CustomerLoyaltyLedger /// </summary> [DataContract] public partial class CustomerLoyaltyLedger : IEquatable<CustomerLoyaltyLedger>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="CustomerLoyaltyLedger" /> class. /// </summary> /// <param name="createdBy">Created By.</param> /// <param name="createdDts">Created date.</param> /// <param name="description">Description.</param> /// <param name="email">Email.</param> /// <param name="itemId">Item Id.</param> /// <param name="itemIndex">Item Index.</param> /// <param name="ledgerDts">Ledger date.</param> /// <param name="loyaltyCampaignOid">Loyalty campaign oid.</param> /// <param name="loyaltyLedgerOid">Loyalty ledger oid.</param> /// <param name="loyaltyPoints">Loyalty points.</param> /// <param name="modifiedBy">Modified By.</param> /// <param name="modifiedDts">Modified date.</param> /// <param name="orderId">Order Id.</param> /// <param name="quantity">Quantity.</param> /// <param name="vestingDts">Vesting date.</param> public CustomerLoyaltyLedger(string createdBy = default(string), string createdDts = default(string), string description = default(string), string email = default(string), string itemId = default(string), int? itemIndex = default(int?), string ledgerDts = default(string), int? loyaltyCampaignOid = default(int?), int? loyaltyLedgerOid = default(int?), int? loyaltyPoints = default(int?), string modifiedBy = default(string), string modifiedDts = default(string), string orderId = default(string), int? quantity = default(int?), string vestingDts = default(string)) { this.CreatedBy = createdBy; this.CreatedDts = createdDts; this.Description = description; this.Email = email; this.ItemId = itemId; this.ItemIndex = itemIndex; this.LedgerDts = ledgerDts; this.LoyaltyCampaignOid = loyaltyCampaignOid; this.LoyaltyLedgerOid = loyaltyLedgerOid; this.LoyaltyPoints = loyaltyPoints; this.ModifiedBy = modifiedBy; this.ModifiedDts = modifiedDts; this.OrderId = orderId; this.Quantity = quantity; this.VestingDts = vestingDts; } /// <summary> /// Created By /// </summary> /// <value>Created By</value> [DataMember(Name="created_by", EmitDefaultValue=false)] public string CreatedBy { get; set; } /// <summary> /// Created date /// </summary> /// <value>Created date</value> [DataMember(Name="created_dts", EmitDefaultValue=false)] public string CreatedDts { get; set; } /// <summary> /// Description /// </summary> /// <value>Description</value> [DataMember(Name="description", EmitDefaultValue=false)] public string Description { get; set; } /// <summary> /// Email /// </summary> /// <value>Email</value> [DataMember(Name="email", EmitDefaultValue=false)] public string Email { get; set; } /// <summary> /// Item Id /// </summary> /// <value>Item Id</value> [DataMember(Name="item_id", EmitDefaultValue=false)] public string ItemId { get; set; } /// <summary> /// Item Index /// </summary> /// <value>Item Index</value> [DataMember(Name="item_index", EmitDefaultValue=false)] public int? ItemIndex { get; set; } /// <summary> /// Ledger date /// </summary> /// <value>Ledger date</value> [DataMember(Name="ledger_dts", EmitDefaultValue=false)] public string LedgerDts { get; set; } /// <summary> /// Loyalty campaign oid /// </summary> /// <value>Loyalty campaign oid</value> [DataMember(Name="loyalty_campaign_oid", EmitDefaultValue=false)] public int? LoyaltyCampaignOid { get; set; } /// <summary> /// Loyalty ledger oid /// </summary> /// <value>Loyalty ledger oid</value> [DataMember(Name="loyalty_ledger_oid", EmitDefaultValue=false)] public int? LoyaltyLedgerOid { get; set; } /// <summary> /// Loyalty points /// </summary> /// <value>Loyalty points</value> [DataMember(Name="loyalty_points", EmitDefaultValue=false)] public int? LoyaltyPoints { get; set; } /// <summary> /// Modified By /// </summary> /// <value>Modified By</value> [DataMember(Name="modified_by", EmitDefaultValue=false)] public string ModifiedBy { get; set; } /// <summary> /// Modified date /// </summary> /// <value>Modified date</value> [DataMember(Name="modified_dts", EmitDefaultValue=false)] public string ModifiedDts { get; set; } /// <summary> /// Order Id /// </summary> /// <value>Order Id</value> [DataMember(Name="order_id", EmitDefaultValue=false)] public string OrderId { get; set; } /// <summary> /// Quantity /// </summary> /// <value>Quantity</value> [DataMember(Name="quantity", EmitDefaultValue=false)] public int? Quantity { get; set; } /// <summary> /// Vesting date /// </summary> /// <value>Vesting date</value> [DataMember(Name="vesting_dts", EmitDefaultValue=false)] public string VestingDts { 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 CustomerLoyaltyLedger {\n"); sb.Append(" CreatedBy: ").Append(CreatedBy).Append("\n"); sb.Append(" CreatedDts: ").Append(CreatedDts).Append("\n"); sb.Append(" Description: ").Append(Description).Append("\n"); sb.Append(" Email: ").Append(Email).Append("\n"); sb.Append(" ItemId: ").Append(ItemId).Append("\n"); sb.Append(" ItemIndex: ").Append(ItemIndex).Append("\n"); sb.Append(" LedgerDts: ").Append(LedgerDts).Append("\n"); sb.Append(" LoyaltyCampaignOid: ").Append(LoyaltyCampaignOid).Append("\n"); sb.Append(" LoyaltyLedgerOid: ").Append(LoyaltyLedgerOid).Append("\n"); sb.Append(" LoyaltyPoints: ").Append(LoyaltyPoints).Append("\n"); sb.Append(" ModifiedBy: ").Append(ModifiedBy).Append("\n"); sb.Append(" ModifiedDts: ").Append(ModifiedDts).Append("\n"); sb.Append(" OrderId: ").Append(OrderId).Append("\n"); sb.Append(" Quantity: ").Append(Quantity).Append("\n"); sb.Append(" VestingDts: ").Append(VestingDts).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 virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as CustomerLoyaltyLedger); } /// <summary> /// Returns true if CustomerLoyaltyLedger instances are equal /// </summary> /// <param name="input">Instance of CustomerLoyaltyLedger to be compared</param> /// <returns>Boolean</returns> public bool Equals(CustomerLoyaltyLedger input) { if (input == null) return false; return ( this.CreatedBy == input.CreatedBy || (this.CreatedBy != null && this.CreatedBy.Equals(input.CreatedBy)) ) && ( this.CreatedDts == input.CreatedDts || (this.CreatedDts != null && this.CreatedDts.Equals(input.CreatedDts)) ) && ( this.Description == input.Description || (this.Description != null && this.Description.Equals(input.Description)) ) && ( this.Email == input.Email || (this.Email != null && this.Email.Equals(input.Email)) ) && ( this.ItemId == input.ItemId || (this.ItemId != null && this.ItemId.Equals(input.ItemId)) ) && ( this.ItemIndex == input.ItemIndex || (this.ItemIndex != null && this.ItemIndex.Equals(input.ItemIndex)) ) && ( this.LedgerDts == input.LedgerDts || (this.LedgerDts != null && this.LedgerDts.Equals(input.LedgerDts)) ) && ( this.LoyaltyCampaignOid == input.LoyaltyCampaignOid || (this.LoyaltyCampaignOid != null && this.LoyaltyCampaignOid.Equals(input.LoyaltyCampaignOid)) ) && ( this.LoyaltyLedgerOid == input.LoyaltyLedgerOid || (this.LoyaltyLedgerOid != null && this.LoyaltyLedgerOid.Equals(input.LoyaltyLedgerOid)) ) && ( this.LoyaltyPoints == input.LoyaltyPoints || (this.LoyaltyPoints != null && this.LoyaltyPoints.Equals(input.LoyaltyPoints)) ) && ( this.ModifiedBy == input.ModifiedBy || (this.ModifiedBy != null && this.ModifiedBy.Equals(input.ModifiedBy)) ) && ( this.ModifiedDts == input.ModifiedDts || (this.ModifiedDts != null && this.ModifiedDts.Equals(input.ModifiedDts)) ) && ( this.OrderId == input.OrderId || (this.OrderId != null && this.OrderId.Equals(input.OrderId)) ) && ( this.Quantity == input.Quantity || (this.Quantity != null && this.Quantity.Equals(input.Quantity)) ) && ( this.VestingDts == input.VestingDts || (this.VestingDts != null && this.VestingDts.Equals(input.VestingDts)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.CreatedBy != null) hashCode = hashCode * 59 + this.CreatedBy.GetHashCode(); if (this.CreatedDts != null) hashCode = hashCode * 59 + this.CreatedDts.GetHashCode(); if (this.Description != null) hashCode = hashCode * 59 + this.Description.GetHashCode(); if (this.Email != null) hashCode = hashCode * 59 + this.Email.GetHashCode(); if (this.ItemId != null) hashCode = hashCode * 59 + this.ItemId.GetHashCode(); if (this.ItemIndex != null) hashCode = hashCode * 59 + this.ItemIndex.GetHashCode(); if (this.LedgerDts != null) hashCode = hashCode * 59 + this.LedgerDts.GetHashCode(); if (this.LoyaltyCampaignOid != null) hashCode = hashCode * 59 + this.LoyaltyCampaignOid.GetHashCode(); if (this.LoyaltyLedgerOid != null) hashCode = hashCode * 59 + this.LoyaltyLedgerOid.GetHashCode(); if (this.LoyaltyPoints != null) hashCode = hashCode * 59 + this.LoyaltyPoints.GetHashCode(); if (this.ModifiedBy != null) hashCode = hashCode * 59 + this.ModifiedBy.GetHashCode(); if (this.ModifiedDts != null) hashCode = hashCode * 59 + this.ModifiedDts.GetHashCode(); if (this.OrderId != null) hashCode = hashCode * 59 + this.OrderId.GetHashCode(); if (this.Quantity != null) hashCode = hashCode * 59 + this.Quantity.GetHashCode(); if (this.VestingDts != null) hashCode = hashCode * 59 + this.VestingDts.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
// Copyright (c) 2015, Outercurve Foundation. // 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 the Outercurve Foundation 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.DirectoryServices.ActiveDirectory; using System.IO; using System.Management; using WebsitePanel.Providers.OS; using WebsitePanel.Providers.Utils; using WebsitePanel.Providers.Utils.LogParser; using WebsitePanel.Server.Utils; using Microsoft.Win32; namespace WebsitePanel.Providers.FTP { public class MsFTP : HostingServiceProviderBase, IFtpServer { #region Properties protected string SiteId { get { return ProviderSettings["SiteId"]; } } protected string FtpGroupName { get { return ProviderSettings["FtpGroupName"]; } } protected string UsersOU { get { return ProviderSettings["ADUsersOU"]; } } protected string GroupsOU { get { return ProviderSettings["ADGroupsOU"]; } } #endregion // constants public const string FTP_SERVICE_ID = "MSFTPSVC"; // private fields private WmiHelper wmi = null; public MsFTP() { if (IsInstalled()) { // instantiate WMI helper wmi = new WmiHelper("root\\MicrosoftIISv2"); } } #region Sites public virtual bool SiteExists(string siteId) { return (wmi.ExecuteQuery( String.Format("SELECT * FROM IIsFtpServerSetting WHERE Name='{0}'", siteId)).Count > 0); } public virtual FtpSite[] GetSites() { List<FtpSite> sites = new List<FtpSite>(); // get all sites ManagementObjectCollection objSites = wmi.ExecuteQuery("SELECT * FROM IIsFtpServerSetting"); foreach (ManagementObject objSite in objSites) { FtpSite site = new FtpSite(); // fill site properties FillFtpSiteFromWmiObject(site, objSite); sites.Add(site); } return sites.ToArray(); } public virtual FtpSite GetSite(string siteId) { FtpSite site = new FtpSite(); ManagementObject objSite = wmi.GetObject( String.Format("IIsFtpServerSetting='{0}'", siteId)); // fill properties FillFtpSiteFromWmiObject(site, objSite); return site; } public virtual string CreateSite(FtpSite site) { // create folder if nessesary //if(!Directory.Exists(site.ContentPath)) // Directory.CreateDirectory(site.ContentPath); // create anonymous user account if required // blah blah blah // set account permissions // blah blah blah // check server bindings CheckFtpServerBindings(site.Bindings); // create FTP site ManagementObject objService = wmi.GetObject(String.Format("IIsFtpService='{0}'", FTP_SERVICE_ID)); ManagementBaseObject methodParams = objService.GetMethodParameters("CreateNewSite"); // create server bindings ManagementClass clsBinding = wmi.GetClass("ServerBinding"); ManagementObject[] objBinings = new ManagementObject[site.Bindings.Length]; for (int i = 0; i < objBinings.Length; i++) { objBinings[i] = clsBinding.CreateInstance(); objBinings[i]["Hostname"] = site.Bindings[i].Host; objBinings[i]["IP"] = site.Bindings[i].IP; objBinings[i]["Port"] = site.Bindings[i].Port; } methodParams["ServerBindings"] = objBinings; methodParams["ServerComment"] = site.Name; methodParams["PathOfRootVirtualDir"] = site.ContentPath; ManagementBaseObject objSite = objService.InvokeMethod("CreateNewSite", methodParams, new InvokeMethodOptions()); // get FTP settings string siteId = ((string)objSite["returnValue"]).Remove(0, "IIsFtpServer='".Length).Replace("'", ""); // update site properties ManagementObject objSettings = wmi.GetObject( String.Format("IIsFtpServerSetting='{0}'", siteId)); FillWmiObjectFromFtpSite(objSettings, site); // start FTP site ChangeSiteState(siteId, ServerState.Started); return siteId; } public virtual void UpdateSite(FtpSite site) { // check server bindings CheckFtpServerBindings(site.Bindings); // update site properties ManagementObject objSettings = wmi.GetObject( String.Format("IIsFtpServerSetting='{0}'", site.SiteId)); FillWmiObjectFromFtpSite(objSettings, site); // update server bindings ManagementClass clsBinding = wmi.GetClass("ServerBinding"); ManagementObject[] objBinings = new ManagementObject[site.Bindings.Length]; for (int i = 0; i < objBinings.Length; i++) { objBinings[i] = clsBinding.CreateInstance(); objBinings[i]["Hostname"] = site.Bindings[i].Host; objBinings[i]["IP"] = site.Bindings[i].IP; objBinings[i]["Port"] = site.Bindings[i].Port; } objSettings.Properties["ServerBindings"].Value = objBinings; // save object objSettings.Put(); } public virtual void DeleteSite(string siteId) { ManagementObject objSite = wmi.GetObject(String.Format("IIsFtpServer='{0}'", siteId)); objSite.Delete(); } public virtual void ChangeSiteState(string siteId, ServerState state) { ManagementObject objSite = wmi.GetObject(String.Format("IIsFtpServer='{0}'", siteId)); string methodName = "Continue"; switch (state) { case ServerState.Started: methodName = "Start"; break; case ServerState.Stopped: methodName = "Stop"; break; case ServerState.Paused: methodName = "Pause"; break; case ServerState.Continuing: methodName = "Continue"; break; default: methodName = "Start"; break; } // invoke method objSite.InvokeMethod(methodName, null); } public virtual ServerState GetSiteState(string siteId) { ManagementObject objSite = wmi.GetObject(String.Format("IIsFtpServer='{0}'", siteId)); return (ServerState)objSite.Properties["ServerState"].Value; } #endregion #region Accounts public virtual bool AccountExists(string accountName) { bool ftpExists = (wmi.ExecuteQuery( String.Format("SELECT * FROM IIsFtpVirtualDirSetting" + " WHERE Name='{0}'", GetAccountPath(SiteId, accountName))).Count > 0); bool systemExists = SecurityUtils.UserExists(accountName, ServerSettings, UsersOU); return (ftpExists || systemExists); } public virtual FtpAccount[] GetAccounts() { List<FtpAccount> accounts = new List<FtpAccount>(); ManagementObjectCollection objAccounts = wmi.ExecuteQuery( String.Format("SELECT * FROM IIsFtpVirtualDirSetting" + " WHERE Name LIKE '{0}%'", SiteId)); foreach (ManagementObject objAccount in objAccounts) { string rootName = GetAccountPath(SiteId, ""); string name = (string)objAccount.Properties["Name"].Value; if (String.Compare(rootName, name, true) != 0) { FtpAccount acc = new FtpAccount(); acc.Name = name.Substring(rootName.Length + 1); acc.Folder = (string)objAccount.Properties["Path"].Value; acc.CanRead = (bool)objAccount.Properties["AccessRead"].Value; acc.CanWrite = (bool)objAccount.Properties["AccessWrite"].Value; accounts.Add(acc); } } return accounts.ToArray(); } public virtual FtpAccount GetAccount(string accountName) { FtpAccount acc = new FtpAccount(); ManagementObject objAccount = wmi.GetObject( String.Format("IIsFtpVirtualDirSetting='{0}'", GetAccountPath(SiteId, accountName))); acc.Name = accountName; acc.Folder = (string)objAccount.Properties["Path"].Value; acc.CanRead = (bool)objAccount.Properties["AccessRead"].Value; acc.CanWrite = (bool)objAccount.Properties["AccessWrite"].Value; // load user account SystemUser user = SecurityUtils.GetUser(accountName, ServerSettings, UsersOU); if (user != null) { acc.Enabled = !user.AccountDisabled; } return acc; } public virtual void CreateAccount(FtpAccount account) { // create user account SystemUser user = new SystemUser(); user.Name = account.Name; user.FullName = account.Name; if (user.FullName.Length > 20) { Exception ex = new Exception("WEBSITEPANEL_ERROR@FTP_USERNAME_MAX_LENGTH_EXCEEDED@"); throw ex; } user.Description = "WebsitePanel System Account"; user.MemberOf = new string[] { FtpGroupName }; user.Password = account.Password; user.PasswordCantChange = true; user.PasswordNeverExpires = true; user.AccountDisabled = !account.Enabled; user.System = true; // create in the system SecurityUtils.CreateUser(user, ServerSettings, UsersOU, GroupsOU); // prepare home folder EnsureUserHomeFolderExists(account.Folder, account.Name, account.CanRead, account.CanWrite); // create account in FTP ManagementObject objDir = wmi.GetClass("IIsFtpVirtualDir").CreateInstance(); ManagementObject objDirSetting = wmi.GetClass("IIsFtpVirtualDirSetting").CreateInstance(); string accId = GetAccountPath(SiteId, account.Name); objDir.Properties["Name"].Value = accId; objDirSetting.Properties["Name"].Value = accId; objDirSetting.Properties["Path"].Value = account.Folder; objDirSetting.Properties["AccessRead"].Value = account.CanRead; objDirSetting.Properties["AccessWrite"].Value = account.CanWrite; objDirSetting.Properties["AccessScript"].Value = false; objDirSetting.Properties["AccessSource"].Value = false; objDirSetting.Properties["AccessExecute"].Value = false; // UNC Path (Connect As) FillWmiObjectUNCFromFtpAccount(objDirSetting, account); // save account objDir.Put(); objDirSetting.Put(); } private void EnsureUserHomeFolderExists(string folder, string accountName, bool allowRead, bool allowWrite) { // create folder if (!FileUtils.DirectoryExists(folder)) FileUtils.CreateDirectory(folder); if (!allowRead && !allowWrite) return; NTFSPermission permissions = allowRead ? NTFSPermission.Read : NTFSPermission.Write; if (allowRead && allowWrite) permissions = NTFSPermission.Modify; // set permissions SecurityUtils.GrantNtfsPermissions(folder, accountName, permissions, true, true, ServerSettings, UsersOU, GroupsOU); } public virtual void UpdateAccount(FtpAccount account) { ManagementObject objAccount = wmi.GetObject( String.Format("IIsFtpVirtualDirSetting='{0}'", GetAccountPath(SiteId, account.Name))); // remove permissions of required string origPath = (string)objAccount.Properties["Path"].Value; if (String.Compare(origPath, account.Folder, true) != 0) RemoveFtpFolderPermissions(origPath, account.Name); // set new permissions EnsureUserHomeFolderExists(account.Folder, account.Name, account.CanRead, account.CanWrite); //objDirSetting.Properties["Name"].Value = accId; objAccount.Properties["Path"].Value = account.Folder; objAccount.Properties["AccessRead"].Value = account.CanRead; objAccount.Properties["AccessWrite"].Value = account.CanWrite; objAccount.Properties["AccessScript"].Value = false; objAccount.Properties["AccessSource"].Value = false; objAccount.Properties["AccessExecute"].Value = false; // UNC Path (Connect As) FillWmiObjectUNCFromFtpAccount(objAccount, account); // save account objAccount.Put(); // change user account state // and password (if required) SystemUser user = SecurityUtils.GetUser(account.Name, ServerSettings, UsersOU); user.Password = account.Password; user.AccountDisabled = !account.Enabled; SecurityUtils.UpdateUser(user, ServerSettings, UsersOU, GroupsOU); } public virtual void DeleteAccount(string accountName) { ManagementObject objAccount = wmi.GetObject(String.Format("IIsFtpVirtualDirSetting='{0}'", GetAccountPath(SiteId, accountName))); string origPath = (string)objAccount.Properties["Path"].Value; objAccount.Delete(); // remove permissions RemoveFtpFolderPermissions(origPath, accountName); // delete system user account if (SecurityUtils.UserExists(accountName, ServerSettings, UsersOU)) SecurityUtils.DeleteUser(accountName, ServerSettings, UsersOU); } private void RemoveFtpFolderPermissions(string path, string accountName) { if (!FileUtils.DirectoryExists(path)) return; // anonymous account SecurityUtils.RemoveNtfsPermissions(path, accountName, ServerSettings, UsersOU, GroupsOU); } #endregion #region IHostingServiceProvier methods public override string[] Install() { List<string> messages = new List<string>(); try { SecurityUtils.EnsureOrganizationalUnitsExist(ServerSettings, UsersOU, GroupsOU); } catch (Exception ex) { messages.Add(String.Format("Could not check/create Organizational Units: {0}", ex.Message)); return messages.ToArray(); } // create folder if it not exists if (String.IsNullOrEmpty(SiteId)) { messages.Add("Please, select FTP site to create accounts on"); } else { // create FTP group name if (String.IsNullOrEmpty(FtpGroupName)) { messages.Add("FTP Group can not be blank"); } else { try { // create group if (!SecurityUtils.GroupExists(FtpGroupName, ServerSettings, GroupsOU)) { SystemGroup group = new SystemGroup(); group.Name = FtpGroupName; group.Members = new string[] { }; group.Description = "WebsitePanel System Group"; SecurityUtils.CreateGroup(group, ServerSettings, UsersOU, GroupsOU); } } catch (Exception ex) { messages.Add(String.Format("There was an error while adding '{0}' group: {1}", FtpGroupName, ex.Message)); return messages.ToArray(); } } FtpSite site = GetSite(SiteId); try { // set permissions on the site root SecurityUtils.GrantNtfsPermissions(site.ContentPath, FtpGroupName, NTFSPermission.Read, true, true, ServerSettings, UsersOU, GroupsOU); } catch (Exception ex) { messages.Add(String.Format("Can not set permissions on '{0}' folder: {1}", site.ContentPath, ex.Message)); return messages.ToArray(); } } return messages.ToArray(); } public override void ChangeServiceItemsState(ServiceProviderItem[] items, bool enabled) { foreach (ServiceProviderItem item in items) { if (item is FtpAccount) { try { // make FTP account read-only FtpAccount account = GetAccount(item.Name); account.Enabled = enabled; UpdateAccount(account); } catch (Exception ex) { Log.WriteError(String.Format("Error switching '{0}' {1}", item.Name, item.GetType().Name), ex); } } } } public override void DeleteServiceItems(ServiceProviderItem[] items) { foreach (ServiceProviderItem item in items) { if (item is FtpAccount) { try { // delete FTP account from default FTP site DeleteAccount(item.Name); } catch (Exception ex) { Log.WriteError(String.Format("Error deleting '{0}' {1}", item.Name, item.GetType().Name), ex); } } } } public override ServiceProviderItemBandwidth[] GetServiceItemsBandwidth(ServiceProviderItem[] items, DateTime since) { ServiceProviderItemBandwidth[] itemsBandwidth = new ServiceProviderItemBandwidth[items.Length]; // calculate bandwidth for Default FTP Site FtpSite fptSite = GetSite(SiteId); string siteId = SiteId.Replace("/", ""); string logsPath = Path.Combine(fptSite.LogFileDirectory, siteId); // create parser object // and update statistics LogParser parser = new LogParser("Ftp", siteId, logsPath, "s-sitename", "cs-username"); parser.ParseLogs(); // update items with diskspace for (int i = 0; i < items.Length; i++) { ServiceProviderItem item = items[i]; // create new bandwidth object itemsBandwidth[i] = new ServiceProviderItemBandwidth(); itemsBandwidth[i].ItemId = item.Id; itemsBandwidth[i].Days = new DailyStatistics[0]; if (item is FtpAccount) { try { // get daily statistics itemsBandwidth[i].Days = parser.GetDailyStatistics(since, new string[] { siteId, item.Name }); } catch (Exception ex) { Log.WriteError(ex); } } } return itemsBandwidth; } #endregion #region private helper methods private void CheckFtpServerBindings(ServerBinding[] bindings) { if (bindings == null || bindings.Length == 0) throw new ArgumentException("Provide FTP site server bindings", "FtpSite.Bindings"); // check for server bindings ManagementObjectCollection objSites = wmi.ExecuteQuery("SELECT * FROM IIsFtpServerSetting"); foreach (ManagementObject objProbSite in objSites) { string probSiteId = (string)objProbSite.Properties["Name"].Value; string probSiteComment = (string)objProbSite.Properties["ServerComment"].Value; // check server bindings ManagementBaseObject[] objProbBinings = (ManagementBaseObject[])objProbSite.Properties["ServerBindings"].Value; if (objProbBinings != null) { // check this binding against provided ones foreach (ManagementBaseObject objProbBinding in objProbBinings) { string siteIP = (string)objProbBinding.Properties["IP"].Value; string sitePort = (string)objProbBinding.Properties["Port"].Value; for (int i = 0; i < bindings.Length; i++) { if (siteIP == bindings[i].IP && sitePort == bindings[i].Port) throw new Exception(String.Format("The FTP site '{0}' ({1}) already uses provided IP and port.", probSiteComment, probSiteId)); } } } } } private string GetAccountPath(string siteId, string accountName) { string path = siteId + "/ROOT"; if (accountName != null && accountName != "") path += "/" + accountName; return path; } private void FillFtpSiteFromWmiObject(FtpSite site, ManagementBaseObject obj) { site.SiteId = (string)obj.Properties["Name"].Value; site.Name = (string)obj.Properties["ServerComment"].Value; site.AllowReadAccess = (bool)obj.Properties["AccessRead"].Value; site.AllowScriptAccess = (bool)obj.Properties["AccessScript"].Value; site.AllowSourceAccess = (bool)obj.Properties["AccessSource"].Value; site.AllowWriteAccess = (bool)obj.Properties["AccessWrite"].Value; site.AllowExecuteAccess = (bool)obj.Properties["AccessExecute"].Value; site.AnonymousUsername = (string)obj.Properties["AnonymousUserName"].Value; site.AnonymousUserPassword = (string)obj.Properties["AnonymousUserPass"].Value; site.AllowAnonymous = (bool)obj.Properties["AllowAnonymous"].Value; site.AnonymousOnly = (bool)obj.Properties["AnonymousOnly"].Value; site.LogFileDirectory = (string)obj.Properties["LogFileDirectory"].Value; // get server bindings ManagementBaseObject[] objBindings = ((ManagementBaseObject[])obj.Properties["ServerBindings"].Value); if (objBindings != null) { site.Bindings = new ServerBinding[objBindings.Length]; for (int i = 0; i < objBindings.Length; i++) { site.Bindings[i] = new ServerBinding( (string)objBindings[i].Properties["IP"].Value, (string)objBindings[i].Properties["Port"].Value, (string)objBindings[i].Properties["Hostname"].Value); } } ManagementObject objVDir = wmi.GetObject( String.Format("IIsFtpVirtualDirSetting='{0}'", GetAccountPath(site.SiteId, ""))); // determine root content folder site.ContentPath = (string)objVDir.Properties["Path"].Value; ; } private void FillWmiObjectFromFtpSite(ManagementBaseObject obj, FtpSite site) { obj.Properties["ServerComment"].Value = site.Name; obj.Properties["AccessRead"].Value = site.AllowReadAccess; obj.Properties["AccessScript"].Value = site.AllowScriptAccess; obj.Properties["AccessSource"].Value = site.AllowSourceAccess; obj.Properties["AccessWrite"].Value = site.AllowWriteAccess; obj.Properties["AccessExecute"].Value = site.AllowExecuteAccess; obj.Properties["AnonymousUserName"].Value = site.AnonymousUsername; obj.Properties["AnonymousUserPass"].Value = site.AnonymousUserPassword; obj.Properties["AllowAnonymous"].Value = site.AllowAnonymous; obj.Properties["AnonymousOnly"].Value = site.AnonymousOnly; obj.Properties["LogFileDirectory"].Value = site.LogFileDirectory; } private void FillWmiObjectUNCFromFtpAccount(ManagementBaseObject obj, FtpAccount account) { if (account.Folder.StartsWith(@"\\") && !String.IsNullOrEmpty(account.Name) && !String.IsNullOrEmpty(account.Password)) { // obj.SetPropertyValue("UNCUserName", GetQualifiedAccountName(account.Name)); obj.SetPropertyValue("UNCPassword", account.Password); } } protected string GetQualifiedAccountName(string accountName) { if (!ServerSettings.ADEnabled) return accountName; if (accountName.IndexOf("\\") != -1) return accountName; // already has domain information // DO IT FOR ACTIVE DIRECTORY MODE ONLY string domainName = null; try { DirectoryContext objContext = new DirectoryContext(DirectoryContextType.Domain, ServerSettings.ADRootDomain); Domain objDomain = Domain.GetDomain(objContext); domainName = objDomain.Name; } catch (Exception ex) { Log.WriteError("Get domain name error", ex); } return domainName != null ? domainName + "\\" + accountName : accountName; } #endregion public override bool IsInstalled() { int value = 0; RegistryKey root = Registry.LocalMachine; RegistryKey rk = root.OpenSubKey("SOFTWARE\\Microsoft\\InetStp"); if (rk != null) { value = (int)rk.GetValue("MajorVersion", null); rk.Close(); } RegistryKey ftp = root.OpenSubKey("SYSTEM\\CurrentControlSet\\Services\\MSFTPSVC"); bool res = value == 6 && ftp != null; if (ftp != null) ftp.Close(); return res; } } }
using UnityEngine; using UnityEngine.Serialization; using System; using System.Collections; using System.Collections.Generic; namespace Fungus { public class CommandInfoAttribute : Attribute { /** * Metadata atribute for the Command class. * @param category The category to place this command in. * @param commandName The display name of the command. * @param helpText Help information to display in the inspector. * @param priority If two command classes have the same name, the one with highest priority is listed. Negative priority removess the command from the list. */ public CommandInfoAttribute(string category, string commandName, string helpText, int priority = 0) { this.Category = category; this.CommandName = commandName; this.HelpText = helpText; this.Priority = priority; } public string Category { get; set; } public string CommandName { get; set; } public string HelpText { get; set; } public int Priority { get; set; } } public class Command : MonoBehaviour { [FormerlySerializedAs("commandId")] [HideInInspector] public int itemId = -1; // Invalid flowchart item id [HideInInspector] public string errorMessage = ""; [HideInInspector] public int indentLevel; [NonSerialized] public int commandIndex; /** * Set to true by the parent block while the command is executing. */ [NonSerialized] public bool isExecuting; /** * Timer used to control appearance of executing icon in inspector. */ [NonSerialized] public float executingIconTimer; /** * Reference to the Block object that this command belongs to. * This reference is only populated at runtime and in the editor when the * block is selected. */ [NonSerialized] public Block parentBlock; public virtual Flowchart GetFlowchart() { Flowchart flowchart = GetComponent<Flowchart>(); if (flowchart == null && transform.parent != null) { flowchart = transform.parent.GetComponent<Flowchart>(); } return flowchart; } public virtual void Execute() { OnEnter(); } public virtual void Continue() { // This is a noop if the Block has already been stopped if (isExecuting) { Continue(commandIndex + 1); } } public virtual void Continue(int nextCommandIndex) { OnExit(); if (parentBlock != null) { parentBlock.jumpToCommandIndex = nextCommandIndex; } } public virtual void StopParentBlock() { OnExit(); if (parentBlock != null) { parentBlock.Stop(); } } /** * Called when the parent block has been requested to stop executing, and * this command is the currently executing command. * Use this callback to terminate any asynchronous operations and * cleanup state so that the command is ready to execute again later on. */ public virtual void OnStopExecuting() {} /** * Called when the new command is added to a block in the editor. */ public virtual void OnCommandAdded(Block parentBlock) {} /** * Called when the command is deleted from a block in the editor. */ public virtual void OnCommandRemoved(Block parentBlock) {} public virtual void OnEnter() {} public virtual void OnExit() {} public virtual void OnReset() {} public virtual void GetConnectedBlocks(ref List<Block> connectedBlocks) {} public virtual bool HasReference(Variable variable) { return false; } public virtual string GetSummary() { return ""; } public virtual string GetHelpText() { return ""; } /** * This command starts a block of commands. */ public virtual bool OpenBlock() { return false; } /** * This command ends a block of commands. */ public virtual bool CloseBlock() { return false; } /** * Return the color for the command background in inspector. */ public virtual Color GetButtonColor() { return Color.white; } /** * Returns true if the specified property should be displayed in the inspector. * This is useful for hiding certain properties based on the value of another property. */ public virtual bool IsPropertyVisible(string propertyName) { return true; } /** * Returns true if the specified property should be displayed as a reorderable list in the inspector. * This only applies for array properties and has no effect for non-array properties. */ public virtual bool IsReorderableArray(string propertyName) { return false; } /** * Returns the localization id for the Flowchart that contains this command. */ public virtual string GetFlowchartLocalizationId() { // If no localization id has been set then use the Flowchart name Flowchart flowchart = GetFlowchart(); if (flowchart == null) { return ""; } string localizationId = GetFlowchart().localizationId; if (localizationId.Length == 0) { localizationId = flowchart.name; } return localizationId; } } }
namespace ClosedXML.Excel { using System; using System.Linq; internal class XLRangeRow : XLRangeBase, IXLRangeRow { #region Constructor public XLRangeRow(XLRangeParameters rangeParameters, bool quickLoad) : base(rangeParameters.RangeAddress) { RangeParameters = rangeParameters; if (quickLoad) return; if (!RangeParameters.IgnoreEvents) { SubscribeToShiftedRows((range, rowsShifted) => this.WorksheetRangeShiftedRows(range, rowsShifted)); SubscribeToShiftedColumns((range, columnsShifted) => this.WorksheetRangeShiftedColumns(range, columnsShifted)); } SetStyle(rangeParameters.DefaultStyle); } #endregion public XLRangeParameters RangeParameters { get; private set; } #region IXLRangeRow Members public IXLCell Cell(int column) { return Cell(1, column); } public new IXLCell Cell(string column) { return Cell(1, column); } public void Delete() { Delete(XLShiftDeletedCells.ShiftCellsUp); } public IXLCells InsertCellsAfter(int numberOfColumns) { return InsertCellsAfter(numberOfColumns, true); } public IXLCells InsertCellsAfter(int numberOfColumns, bool expandRange) { return InsertColumnsAfter(numberOfColumns, expandRange).Cells(); } public IXLCells InsertCellsBefore(int numberOfColumns) { return InsertCellsBefore(numberOfColumns, false); } public IXLCells InsertCellsBefore(int numberOfColumns, bool expandRange) { return InsertColumnsBefore(numberOfColumns, expandRange).Cells(); } public new IXLCells Cells(string cellsInRow) { var retVal = new XLCells(false, false); var rangePairs = cellsInRow.Split(','); foreach (string pair in rangePairs) retVal.Add(Range(pair.Trim()).RangeAddress); return retVal; } public IXLCells Cells(int firstColumn, int lastColumn) { return Cells(firstColumn + ":" + lastColumn); } public IXLCells Cells(string firstColumn, string lastColumn) { return Cells(XLHelper.GetColumnNumberFromLetter(firstColumn) + ":" + XLHelper.GetColumnNumberFromLetter(lastColumn)); } public int CellCount() { return RangeAddress.LastAddress.ColumnNumber - RangeAddress.FirstAddress.ColumnNumber + 1; } public new IXLRangeRow Sort() { return SortLeftToRight(); } public new IXLRangeRow SortLeftToRight(XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true) { base.SortLeftToRight(sortOrder, matchCase, ignoreBlanks); return this; } public new IXLRangeRow CopyTo(IXLCell target) { base.CopyTo(target); int lastRowNumber = target.Address.RowNumber + RowCount() - 1; if (lastRowNumber > XLHelper.MaxRowNumber) lastRowNumber = XLHelper.MaxRowNumber; int lastColumnNumber = target.Address.ColumnNumber + ColumnCount() - 1; if (lastColumnNumber > XLHelper.MaxColumnNumber) lastColumnNumber = XLHelper.MaxColumnNumber; return target.Worksheet.Range( target.Address.RowNumber, target.Address.ColumnNumber, lastRowNumber, lastColumnNumber) .Row(1); } public new IXLRangeRow CopyTo(IXLRangeBase target) { base.CopyTo(target); int lastRowNumber = target.RangeAddress.FirstAddress.RowNumber + RowCount() - 1; if (lastRowNumber > XLHelper.MaxRowNumber) lastRowNumber = XLHelper.MaxRowNumber; int lastColumnNumber = target.RangeAddress.LastAddress.ColumnNumber + ColumnCount() - 1; if (lastColumnNumber > XLHelper.MaxColumnNumber) lastColumnNumber = XLHelper.MaxColumnNumber; return target.Worksheet.Range( target.RangeAddress.FirstAddress.RowNumber, target.RangeAddress.LastAddress.ColumnNumber, lastRowNumber, lastColumnNumber) .Row(1); } public IXLRangeRow Row(int start, int end) { return Range(1, start, 1, end).Row(1); } public IXLRangeRow Row(IXLCell start, IXLCell end) { return Row(start.Address.ColumnNumber, end.Address.ColumnNumber); } public IXLRangeRows Rows(string rows) { var retVal = new XLRangeRows(); var columnPairs = rows.Split(','); foreach (string trimmedPair in columnPairs.Select(pair => pair.Trim())) { string firstColumn; string lastColumn; if (trimmedPair.Contains(':') || trimmedPair.Contains('-')) { var columnRange = trimmedPair.Contains('-') ? trimmedPair.Replace('-', ':').Split(':') : trimmedPair.Split(':'); firstColumn = columnRange[0]; lastColumn = columnRange[1]; } else { firstColumn = trimmedPair; lastColumn = trimmedPair; } retVal.Add(Range(firstColumn, lastColumn).FirstRow()); } return retVal; } public IXLRangeRow SetDataType(XLCellValues dataType) { DataType = dataType; return this; } public IXLRow WorksheetRow() { return Worksheet.Row(RangeAddress.FirstAddress.RowNumber); } #endregion private void WorksheetRangeShiftedColumns(XLRange range, int columnsShifted) { ShiftColumns(RangeAddress, range, columnsShifted); } private void WorksheetRangeShiftedRows(XLRange range, int rowsShifted) { ShiftRows(RangeAddress, range, rowsShifted); } public IXLRange Range(int firstColumn, int lastColumn) { return Range(1, firstColumn, 1, lastColumn); } public override XLRange Range(string rangeAddressStr) { string rangeAddressToUse; if (rangeAddressStr.Contains(':') || rangeAddressStr.Contains('-')) { if (rangeAddressStr.Contains('-')) rangeAddressStr = rangeAddressStr.Replace('-', ':'); var arrRange = rangeAddressStr.Split(':'); string firstPart = arrRange[0]; string secondPart = arrRange[1]; rangeAddressToUse = FixRowAddress(firstPart) + ":" + FixRowAddress(secondPart); } else rangeAddressToUse = FixRowAddress(rangeAddressStr); var rangeAddress = new XLRangeAddress(Worksheet, rangeAddressToUse); return Range(rangeAddress); } public int CompareTo(XLRangeRow otherRow, IXLSortElements columnsToSort) { foreach (IXLSortElement e in columnsToSort) { var thisCell = (XLCell)Cell(e.ElementNumber); var otherCell = (XLCell)otherRow.Cell(e.ElementNumber); int comparison; bool thisCellIsBlank = thisCell.IsEmpty(); bool otherCellIsBlank = otherCell.IsEmpty(); if (e.IgnoreBlanks && (thisCellIsBlank || otherCellIsBlank)) { if (thisCellIsBlank && otherCellIsBlank) comparison = 0; else { if (thisCellIsBlank) comparison = e.SortOrder == XLSortOrder.Ascending ? 1 : -1; else comparison = e.SortOrder == XLSortOrder.Ascending ? -1 : 1; } } else { if (thisCell.DataType == otherCell.DataType) { if (thisCell.DataType == XLCellValues.Text) { comparison = e.MatchCase ? thisCell.InnerText.CompareTo(otherCell.InnerText) : String.Compare(thisCell.InnerText, otherCell.InnerText, true); } else if (thisCell.DataType == XLCellValues.TimeSpan) comparison = thisCell.GetTimeSpan().CompareTo(otherCell.GetTimeSpan()); else comparison = Double.Parse(thisCell.InnerText, XLHelper.NumberStyle, XLHelper.ParseCulture).CompareTo(Double.Parse(otherCell.InnerText, XLHelper.NumberStyle, XLHelper.ParseCulture)); } else if (e.MatchCase) comparison = String.Compare(thisCell.GetString(), otherCell.GetString(), true); else comparison = thisCell.GetString().CompareTo(otherCell.GetString()); } if (comparison != 0) return e.SortOrder == XLSortOrder.Ascending ? comparison : comparison * -1; } return 0; } private XLRangeRow RowShift(Int32 rowsToShift) { Int32 rowNum = RowNumber() + rowsToShift; var range = Worksheet.Range( rowNum, RangeAddress.FirstAddress.ColumnNumber, rowNum, RangeAddress.LastAddress.ColumnNumber); var result = range.FirstRow(); range.Dispose(); return result; } #region XLRangeRow Above IXLRangeRow IXLRangeRow.RowAbove() { return RowAbove(); } IXLRangeRow IXLRangeRow.RowAbove(Int32 step) { return RowAbove(step); } public XLRangeRow RowAbove() { return RowAbove(1); } public XLRangeRow RowAbove(Int32 step) { return RowShift(step * -1); } #endregion #region XLRangeRow Below IXLRangeRow IXLRangeRow.RowBelow() { return RowBelow(); } IXLRangeRow IXLRangeRow.RowBelow(Int32 step) { return RowBelow(step); } public XLRangeRow RowBelow() { return RowBelow(1); } public XLRangeRow RowBelow(Int32 step) { return RowShift(step); } #endregion public new IXLRangeRow Clear(XLClearOptions clearOptions = XLClearOptions.ContentsAndFormats) { base.Clear(clearOptions); return this; } public IXLRangeRow RowUsed(Boolean includeFormats = false) { return Row(FirstCellUsed(includeFormats), LastCellUsed(includeFormats)); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Runtime.Versioning; using NuGet.Resources; namespace NuGet { public class UninstallWalker : PackageWalker, IPackageOperationResolver { private readonly IDictionary<IPackage, IEnumerable<IPackage>> _forcedRemoved = new Dictionary<IPackage, IEnumerable<IPackage>>(PackageEqualityComparer.IdAndVersion); private readonly IDictionary<IPackage, IEnumerable<IPackage>> _skippedPackages = new Dictionary<IPackage, IEnumerable<IPackage>>(PackageEqualityComparer.IdAndVersion); private readonly bool _removeDependencies; // this ctor is used for unit tests internal UninstallWalker(IPackageRepository repository, IDependentsResolver dependentsResolver, ILogger logger, bool removeDependencies, bool forceRemove) : this(repository, dependentsResolver, null, logger, removeDependencies, forceRemove) { } public UninstallWalker(IPackageRepository repository, IDependentsResolver dependentsResolver, FrameworkName targetFramework, ILogger logger, bool removeDependencies, bool forceRemove) : base(targetFramework) { if (dependentsResolver == null) { throw new ArgumentNullException("dependentsResolver"); } if (repository == null) { throw new ArgumentNullException("repository"); } if (logger == null) { throw new ArgumentNullException("logger"); } Logger = logger; Repository = repository; DependentsResolver = dependentsResolver; Force = forceRemove; ThrowOnConflicts = true; Operations = new Stack<PackageOperation>(); _removeDependencies = removeDependencies; } protected ILogger Logger { get; private set; } protected IPackageRepository Repository { get; private set; } protected override bool IgnoreDependencies { get { return !_removeDependencies; } } protected override bool SkipDependencyResolveError { get { return true; } } internal bool DisableWalkInfo { get; set; } protected override bool IgnoreWalkInfo { get { return DisableWalkInfo ? true : base.IgnoreWalkInfo; } } private Stack<PackageOperation> Operations { get; set; } public bool Force { get; private set; } public bool ThrowOnConflicts { get; set; } protected IDependentsResolver DependentsResolver { get; private set; } protected override void OnBeforePackageWalk(IPackage package) { // Before choosing to uninstall a package we need to figure out if it is in use IEnumerable<IPackage> dependents = GetDependents(package); if (dependents.Any()) { if (Force) { // We're going to uninstall this package even though other packages depend on it _forcedRemoved[package] = dependents; } else if (ThrowOnConflicts) { // We're not ignoring dependents so raise an error telling the user what the dependents are throw CreatePackageHasDependentsException(package, dependents); } } } protected override bool OnAfterResolveDependency(IPackage package, IPackage dependency) { if (!Force) { IEnumerable<IPackage> dependents = GetDependents(dependency); // If this isn't a force remove and other packages depend on this dependency // then skip this entire dependency tree if (dependents.Any()) { _skippedPackages[dependency] = dependents; // Don't look any further return false; } } return true; } protected override void OnAfterPackageWalk(IPackage package) { Operations.Push(new PackageOperation(package, PackageAction.Uninstall)); } protected override IPackage ResolveDependency(PackageDependency dependency) { return Repository.ResolveDependency(dependency, allowPrereleaseVersions: true, preferListedPackages: false); } protected virtual void WarnRemovingPackageBreaksDependents(IPackage package, IEnumerable<IPackage> dependents) { Logger.Log(MessageLevel.Warning, NuGetResources.Warning_UninstallingPackageWillBreakDependents, package.GetFullName(), String.Join(", ", dependents.Select(d => d.GetFullName()))); } protected virtual InvalidOperationException CreatePackageHasDependentsException(IPackage package, IEnumerable<IPackage> dependents) { if (dependents.Count() == 1) { return new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, NuGetResources.PackageHasDependent, package.GetFullName(), dependents.Single().GetFullName())); } return new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, NuGetResources.PackageHasDependents, package.GetFullName(), String.Join(", ", dependents.Select(d => d.GetFullName())))); } protected override void OnDependencyResolveError(IPackage package, PackageDependency dependency) { Logger.Log(MessageLevel.Warning, NuGetResources.UnableToLocateDependency, dependency); } public IEnumerable<PackageOperation> ResolveOperations(IPackage package) { Operations.Clear(); Marker.Clear(); Walk(package); // Log warnings for packages that were forcibly removed foreach (var pair in _forcedRemoved) { Logger.Log(MessageLevel.Warning, NuGetResources.Warning_UninstallingPackageWillBreakDependents, pair.Key, String.Join(", ", pair.Value.Select(p => p.GetFullName()))); } // Log warnings for dependencies that were skipped foreach (var pair in _skippedPackages) { Logger.Log(MessageLevel.Warning, NuGetResources.Warning_PackageSkippedBecauseItIsInUse, pair.Key, String.Join(", ", pair.Value.Select(p => p.GetFullName()))); } return Operations.Reduce(); } private IEnumerable<IPackage> GetDependents(IPackage package) { // REVIEW: Perf? return from p in DependentsResolver.GetDependents(package) where !IsConnected(p) select p; } private bool IsConnected(IPackage package) { // We could cache the results of this lookup if (Marker.Contains(package)) { return true; } IEnumerable<IPackage> dependents = DependentsResolver.GetDependents(package); return dependents.Any() && dependents.All(IsConnected); } } }
// // AudioHeader.cs: Provides information about an ADTS AAC audio stream. // // Copyright (C) 2009 Patrick Dehne // // This library is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License version // 2.1 as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 // USA // using System; namespace TagLib.Aac { /// <summary> /// This structure implements <see cref="IAudioCodec" /> and provides /// information about an ADTS AAC audio stream. /// </summary> public class AudioHeader : IAudioCodec { #region Private Static Value Arrays /// <summary> /// Contains a sample rate table for ADTS AAC audio. /// </summary> private static readonly int[] sample_rates = new int[13] { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350 }; /// <summary> /// Contains a channel table for ADTS AAC audio. /// </summary> private static readonly int[] channels = new int[8] { 0, 1, 2, 3, 4, 5, 6, 8 }; #endregion #region Private Properties /// <summary> /// Contains the audio stream length. /// </summary> private long stream_length; /// <summary> /// Contains the audio stream duration. /// </summary> private TimeSpan duration; /// <summary> /// Contains the number of channels in the audio /// </summary> private int audiochannels; /// <summary> /// Contains the bitrate of the audio stream /// </summary> private int audiobitrate; /// <summary> /// Contains the samplerate of the audio stream /// </summary> private int audiosamplerate; #endregion #region Public Fields /// <summary> /// An empty and unset header. /// </summary> public static readonly AudioHeader Unknown = new AudioHeader(); #endregion #region Constructors /// <summary> /// Constructs and initializes a new empty instance of <see /// cref="AudioHeader" /> /// </summary> private AudioHeader() { this.stream_length = 0; this.duration = TimeSpan.Zero; this.audiochannels = 0; this.audiobitrate = 0; this.audiosamplerate = 0; } /// <summary> /// Constructs and initializes a new instance of <see /// cref="AudioHeader" /> by populating it with specified /// values. /// </summary> /// <param name="channels"> /// A <see cref="int" /> value indicating the number /// of channels in the audio stream /// </param> /// <param name="bitrate"> /// A <see cref="int" /> value indicating the bitrate /// of the audio stream /// </param> /// <param name="samplerate"> /// A <see cref="int" /> value indicating the samplerate /// of the audio stream /// </param> /// <param name="numberofsamples"> /// A <see cref="int" /> value indicating the number /// of samples in the audio stream /// </param> /// <param name="numberofframes"> /// A <see cref="int" /> value indicating the number /// of frames in the audio stream /// </param> private AudioHeader(int channels, int bitrate, int samplerate, int numberofsamples, int numberofframes) { this.duration = TimeSpan.Zero; this.stream_length = 0; this.audiochannels = channels; this.audiobitrate = bitrate; this.audiosamplerate = samplerate; } #endregion #region Public Properties /// <summary> /// Gets a text description of the media represented by the /// current instance. /// </summary> /// <value> /// A <see cref="string" /> object containing a description /// of the media represented by the current instance. /// </value> public string Description { get { return "ADTS AAC"; } } /// <summary> /// Gets the types of media represented by the current /// instance. /// </summary> /// <value> /// Always <see cref="MediaTypes.Audio" />. /// </value> public MediaTypes MediaTypes { get { return MediaTypes.Audio; } } /// <summary> /// Gets the duration of the media represented by the current /// instance. /// </summary> /// <value> /// A <see cref="TimeSpan" /> containing the duration of the /// media represented by the current instance. /// </value> /// <remarks> /// If <see cref="SetStreamLength" /> has not been called, this /// value will not be correct. /// </remarks> public TimeSpan Duration { get { return duration; } } /// <summary> /// Gets the bitrate of the audio represented by the current /// instance. /// </summary> /// <value> /// A <see cref="int" /> value containing a bitrate of the /// audio represented by the current instance. /// </value> public int AudioBitrate { get { return audiobitrate; } } /// <summary> /// Gets the sample rate of the audio represented by the /// current instance. /// </summary> /// <value> /// A <see cref="int" /> value containing the sample rate of /// the audio represented by the current instance. /// </value> public int AudioSampleRate { get { return audiosamplerate; } } /// <summary> /// Gets the number of channels in the audio represented by /// the current instance. /// </summary> /// <value> /// A <see cref="int" /> value containing the number of /// channels in the audio represented by the current /// instance. /// </value> public int AudioChannels { get { return audiochannels; } } #endregion #region Public Methods /// <summary> /// Sets the length of the audio stream represented by the /// current instance. /// </summary> /// <param name="streamLength"> /// A <see cref="long" /> value specifying the length in /// bytes of the audio stream represented by the current /// instance. /// </param> /// <remarks> /// The this value has been set, <see cref="Duration" /> will /// return an incorrect value. /// </remarks> public void SetStreamLength(long streamLength) { this.stream_length = streamLength; duration = TimeSpan.FromSeconds(((double)this.stream_length) * 8.0 / ((double)this.audiobitrate)); } #endregion #region Public Static Methods /// <summary> /// Searches for an audio header in a <see cref="TagLib.File" /// /> starting at a specified position and searching through /// a specified number of bytes. /// </summary> /// <param name="header"> /// A <see cref="AudioHeader" /> object in which the found /// header will be stored. /// </param> /// <param name="file"> /// A <see cref="TagLib.File" /> object to search. /// </param> /// <param name="position"> /// A <see cref="long" /> value specifying the seek position /// in <paramref name="file" /> at which to start searching. /// </param> /// <param name="length"> /// A <see cref="int" /> value specifying the maximum number /// of bytes to search before aborting. /// </param> /// <returns> /// A <see cref="bool" /> value indicating whether or not a /// header was found. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="file" /> is <see langword="null" />. /// </exception> public static bool Find(out AudioHeader header, TagLib.File file, long position, int length) { if (file == null) throw new ArgumentNullException("file"); long end = position + length; header = AudioHeader.Unknown; file.Seek(position); ByteVector buffer = file.ReadBlock(3); if (buffer.Count < 3) return false; do { file.Seek(position + 3); buffer = buffer.Mid(buffer.Count - 3); buffer.Add(file.ReadBlock( (int)File.BufferSize)); for (int i = 0; i < buffer.Count - 3 && (length < 0 || position + i < end); i++) if (buffer[i] == 0xFF && buffer[i+1] >= 0xF0) // 0xFFF try { BitStream bits = new BitStream(buffer.Mid(i, 7).Data); // 12 bits sync header bits.ReadInt32(12); // 1 bit mpeg 2/4 bits.ReadInt32(1); // 2 bits layer bits.ReadInt32(2); // 1 bit protection absent bits.ReadInt32(1); // 2 bits profile object type bits.ReadInt32(2); // 4 bits sampling frequency index int samplerateindex = bits.ReadInt32(4); if(samplerateindex >= sample_rates.Length) return false; long samplerate = sample_rates[samplerateindex]; // 1 bit private bit bits.ReadInt32(1); // 3 bits channel configuration int channelconfigindex = bits.ReadInt32(3); if (channelconfigindex >= channels.Length) return false; // 4 copyright bits bits.ReadInt32(4); // 13 bits frame length long framelength = bits.ReadInt32(13); // double check framelength if (framelength < 7) return false; // 11 bits buffer fullness bits.ReadInt32(11); // 2 bits number of raw data blocks in frame int numberofframes = bits.ReadInt32(2) + 1; long numberofsamples = numberofframes * 1024; long bitrate = framelength * 8 * samplerate / numberofsamples; header = new AudioHeader(channels[channelconfigindex], (int)bitrate, (int)samplerate, (int)numberofsamples, numberofframes); return true; } catch (CorruptFileException) { } position += File.BufferSize; } while (buffer.Count > 3 && (length < 0 || position < end)); return false; } /// <summary> /// Searches for an audio header in a <see cref="TagLib.File" /// /> starting at a specified position and searching to the /// end of the file. /// </summary> /// <param name="header"> /// A <see cref="AudioHeader" /> object in which the found /// header will be stored. /// </param> /// <param name="file"> /// A <see cref="TagLib.File" /> object to search. /// </param> /// <param name="position"> /// A <see cref="long" /> value specifying the seek position /// in <paramref name="file" /> at which to start searching. /// </param> /// <returns> /// A <see cref="bool" /> value indicating whether or not a /// header was found. /// </returns> /// <remarks> /// Searching to the end of the file can be very, very slow /// especially for corrupt or non-MPEG files. It is /// recommended to use <see /// cref="Find(AudioHeader,TagLib.File,long,int)" /> /// instead. /// </remarks> public static bool Find(out AudioHeader header, TagLib.File file, long position) { return Find(out header, file, position, -1); } #endregion } }
/*! * CSharpVerbalExpressions v0.1 * https://github.com/VerbalExpressions/CSharpVerbalExpressions * * @psoholt * * Date: 2013-07-26 * * Additions and Refactoring * @alexpeta * * Date: 2013-08-06 */ using System; using System.Text; using System.Linq; using System.Text.RegularExpressions; namespace CSharpVerbalExpressions { public class VerbalExpressions { #region Statics /// <summary> /// Returns a default instance of VerbalExpressions /// having the Multiline option enabled /// </summary> public static VerbalExpressions DefaultExpression { get { return new VerbalExpressions(); } } #endregion Statics #region Private Members private readonly RegexCache regexCache = new RegexCache(); private StringBuilder prefixes = new StringBuilder(); private StringBuilder source = new StringBuilder(); private StringBuilder suffixes = new StringBuilder(); private RegexOptions modifiers = RegexOptions.Multiline; #endregion Private Members #region Private Properties private string RegexString { get { return new StringBuilder().Append(prefixes).Append(source).Append(suffixes).ToString();} } private Regex PatternRegex { get { return regexCache.Get(this.RegexString, modifiers); } } #endregion Private Properties #region Public Methods #region Helpers public string Sanitize(string value) { if (string.IsNullOrEmpty(value)) { throw new ArgumentNullException("value"); } return Regex.Escape(value); } public bool Test(string toTest) { return IsMatch(toTest); } public bool IsMatch(string toTest) { return PatternRegex.IsMatch(toTest); } public Regex ToRegex() { return PatternRegex; } public override string ToString() { return PatternRegex.ToString(); } public string Capture(string toTest, string groupName) { if (!Test(toTest)) return null; var match = PatternRegex.Match(toTest); return match.Groups[groupName].Value; } #endregion Helpers #region Expression Modifiers public VerbalExpressions Add(string value) { if (object.ReferenceEquals(value, null)) { throw new ArgumentNullException("value"); } return Add(value, true); } public VerbalExpressions Add(CommonRegex commonRegex) { return Add(commonRegex.Name, false); } public VerbalExpressions Add(string value, bool sanitize = true) { if (value == null) throw new ArgumentNullException("value must be provided"); value = sanitize ? Sanitize(value) : value; source.Append(value); return this; } public VerbalExpressions StartOfLine(bool enable = true) { prefixes.Append(enable ? "^" : String.Empty); return this; } public VerbalExpressions EndOfLine(bool enable = true) { suffixes.Append(enable ? "$" : String.Empty); return this; } public VerbalExpressions Then(string value, bool sanitize = true) { var sanitizedValue = sanitize ? Sanitize(value) : value; value = string.Format("({0})", sanitizedValue); return Add(value, false); } public VerbalExpressions Then(CommonRegex commonRegex) { return Then(commonRegex.Name, false); } public VerbalExpressions Find(string value) { return Then(value); } public VerbalExpressions Maybe(string value, bool sanitize = true) { value = sanitize ? Sanitize(value) : value; value = string.Format("({0})?", value); return Add(value, false); } public VerbalExpressions Maybe(CommonRegex commonRegex) { return Maybe(commonRegex.Name, sanitize: false); } public VerbalExpressions Anything() { return Add("(.*)", false); } public VerbalExpressions AnythingBut(string value, bool sanitize = true) { value = sanitize ? Sanitize(value) : value; value = string.Format("([^{0}]*)", value); return Add(value, false); } public VerbalExpressions Something() { return Add("(.+)", false); } public VerbalExpressions SomethingBut(string value, bool sanitize = true) { value = sanitize ? Sanitize(value) : value; value = string.Format("([^" + value + "]+)"); return Add(value, false); } public VerbalExpressions Replace(string value) { string whereToReplace = PatternRegex.ToString(); if (whereToReplace.Length != 0) { source.Replace(whereToReplace, value); } return this; } public VerbalExpressions LineBreak() { return Add(@"(\n|(\r\n))", false); } public VerbalExpressions Br() { return LineBreak(); } public VerbalExpressions Tab() { return Add(@"\t"); } public VerbalExpressions Word() { return Add(@"\w+", false); } public VerbalExpressions AnyOf(string value, bool sanitize = true) { if (string.IsNullOrEmpty(value)) { throw new ArgumentNullException("value"); } value = sanitize ? Sanitize(value) : value; value = string.Format("[{0}]", value); return Add(value, false); } public VerbalExpressions Any(string value) { return AnyOf(value); } public VerbalExpressions Range(params object[] arguments) { if (object.ReferenceEquals(arguments, null)) { throw new ArgumentNullException("arguments"); } if (arguments.Length == 1) { throw new ArgumentOutOfRangeException("arguments"); } string[] sanitizedStrings = arguments.Select(argument => { if (object.ReferenceEquals(argument, null)) { return string.Empty; } string casted = argument.ToString(); if (string.IsNullOrEmpty(casted)) { return string.Empty; } else { return Sanitize(casted); } }) .Where(sanitizedString => !string.IsNullOrEmpty(sanitizedString)) .OrderBy(s => s) .ToArray(); if (sanitizedStrings.Length > 3) { throw new ArgumentOutOfRangeException("arguments"); } if (!sanitizedStrings.Any()) { return this; } bool hasOddNumberOfParams = (sanitizedStrings.Length % 2) > 0; StringBuilder sb = new StringBuilder("["); for (int _from = 0; _from < sanitizedStrings.Length; _from += 2) { int _to = _from + 1; if (sanitizedStrings.Length <= _to) { break; } sb.AppendFormat("{0}-{1}", sanitizedStrings[_from], sanitizedStrings[_to]); } sb.Append("]"); if (hasOddNumberOfParams) { sb.AppendFormat("|{0}", sanitizedStrings.Last()); } return Add(sb.ToString(), false); } public VerbalExpressions Multiple(string value, bool sanitize = true) { if (string.IsNullOrEmpty(value)) { throw new ArgumentNullException("value"); } value = sanitize ? this.Sanitize(value) : value; value = string.Format(@"({0})+", value); return Add(value, false); } public VerbalExpressions Or(CommonRegex commonRegex) { return Or(commonRegex.Name, false); } public VerbalExpressions Or(string value, bool sanitize = true) { prefixes.Append("("); suffixes.Insert(0, ")"); source.Append(")|("); return Add(value, sanitize); } public VerbalExpressions BeginCapture() { return Add("(", false); } public VerbalExpressions BeginCapture(string groupName) { return Add("(?<", false).Add(groupName, true).Add(">", false); } public VerbalExpressions EndCapture() { return Add(")", false); } public VerbalExpressions RepeatPrevious(int n) { return Add("{" + n + "}", false); } public VerbalExpressions RepeatPrevious(int n, int m) { return Add("{" + n + "," + m + "}", false); } #endregion Expression Modifiers #region Expression Options Modifiers public VerbalExpressions AddModifier(char modifier) { switch (modifier) { case 'i': modifiers |= RegexOptions.IgnoreCase; break; case 'x': modifiers |= RegexOptions.IgnorePatternWhitespace; break; case 'm': modifiers |= RegexOptions.Multiline; break; case 's': modifiers |= RegexOptions.Singleline; break; } return this; } public VerbalExpressions RemoveModifier(char modifier) { switch (modifier) { case 'i': modifiers &= ~RegexOptions.IgnoreCase; break; case 'x': modifiers &= ~RegexOptions.IgnorePatternWhitespace; break; case 'm': modifiers &= ~RegexOptions.Multiline; break; case 's': modifiers &= ~RegexOptions.Singleline; break; } return this; } public VerbalExpressions WithAnyCase(bool enable = true) { if (enable) { AddModifier('i'); } else { RemoveModifier('i'); } return this; } public VerbalExpressions UseOneLineSearchOption(bool enable) { if (enable) { RemoveModifier('m'); } else { AddModifier('m'); } return this; } public VerbalExpressions WithOptions(RegexOptions options) { this.modifiers = options; return this; } #endregion Expression Options Modifiers #endregion Public Methods } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Box.V2.Managers; using Box.V2.Models; using Box.V2.Models.Request; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; namespace Box.V2.Test { [TestClass] public class BoxSignRequestsManagerTest : BoxResourceManagerTest { private readonly BoxSignRequestsManager _signRequestsManager; public BoxSignRequestsManagerTest() { _signRequestsManager = new BoxSignRequestsManager(Config.Object, Service, Converter, AuthRepository); } [TestMethod] [TestCategory("CI-UNIT-TEST")] public async Task CreateSignRequest_RequiredParams_Success() { /*** Arrange ***/ IBoxRequest boxRequest = null; Handler.Setup(h => h.ExecuteAsync<BoxSignRequest>(It.IsAny<IBoxRequest>())) .Returns(Task.FromResult<IBoxResponse<BoxSignRequest>>(new BoxResponse<BoxSignRequest>() { Status = ResponseStatus.Success, ContentString = LoadFixtureFromJson("Fixtures/BoxSignRequest/CreateSignRequest200.json") })) .Callback<IBoxRequest>(r => boxRequest = r); ; var sourceFiles = new List<BoxSignRequestCreateSourceFile> { new BoxSignRequestCreateSourceFile() { Id = "12345" } }; var signers = new List<BoxSignRequestSignerCreate> { new BoxSignRequestSignerCreate() { Email = "example@gmail.com" } }; var parentFolder = new BoxRequestEntity() { Id = "12345", Type = BoxType.folder }; var request = new BoxSignRequestCreateRequest { SourceFiles = sourceFiles, Signers = signers, ParentFolder = parentFolder, }; /*** Act ***/ var response = await _signRequestsManager.CreateSignRequestAsync(request); /*** Assert ***/ // Request check Assert.IsNotNull(boxRequest); Assert.AreEqual(RequestMethod.Post, boxRequest.Method); Assert.AreEqual(new Uri("https://api.box.com/2.0/sign_requests"), boxRequest.AbsoluteUri); // Response check Assert.AreEqual(1, response.SourceFiles.Count); Assert.AreEqual("12345", response.SourceFiles[0].Id); Assert.AreEqual(1, response.Signers.Count); Assert.AreEqual("example@gmail.com", response.Signers[0].Email); Assert.AreEqual("12345", response.ParentFolder.Id); } [TestMethod] [TestCategory("CI-UNIT-TEST")] public async Task CreateSignRequest_OptionalParams_Success() { /*** Arrange ***/ IBoxRequest boxRequest = null; Handler.Setup(h => h.ExecuteAsync<BoxSignRequest>(It.IsAny<IBoxRequest>())) .Returns(Task.FromResult<IBoxResponse<BoxSignRequest>>(new BoxResponse<BoxSignRequest>() { Status = ResponseStatus.Success, ContentString = LoadFixtureFromJson("Fixtures/BoxSignRequest/CreateSignRequest200.json") })) .Callback<IBoxRequest>(r => boxRequest = r); ; var sourceFiles = new List<BoxSignRequestCreateSourceFile> { new BoxSignRequestCreateSourceFile() { Id = "12345" } }; var signers = new List<BoxSignRequestSignerCreate> { new BoxSignRequestSignerCreate() { Email = "example@gmail.com" } }; var parentFolder = new BoxRequestEntity() { Id = "12345", Type = BoxType.folder }; var request = new BoxSignRequestCreateRequest { IsDocumentPreparationNeeded = true, AreRemindersEnabled = true, AreTextSignaturesEnabled = true, DaysValid = 2, EmailMessage = "Hello! Please sign the document below", EmailSubject = "Sign Request from Acme", ExternalId = "123", SourceFiles = sourceFiles, Signers = signers, ParentFolder = parentFolder, PrefillTags = new List<BoxSignRequestPrefillTag> { new BoxSignRequestPrefillTag ( "1234", "text" ) } }; /*** Act ***/ var response = await _signRequestsManager.CreateSignRequestAsync(request); /*** Assert ***/ // Request check Assert.IsNotNull(boxRequest); Assert.AreEqual(RequestMethod.Post, boxRequest.Method); Assert.AreEqual(new Uri("https://api.box.com/2.0/sign_requests"), boxRequest.AbsoluteUri); // Response check Assert.AreEqual(1, response.SourceFiles.Count); Assert.AreEqual("12345", response.SourceFiles[0].Id); Assert.AreEqual(1, response.Signers.Count); Assert.AreEqual("example@gmail.com", response.Signers[0].Email); Assert.AreEqual("12345", response.ParentFolder.Id); Assert.IsTrue(response.IsDocumentPreparationNeeded); Assert.IsTrue(response.AreRemindersEnabled); Assert.IsTrue(response.AreTextSignaturesEnabled); Assert.AreEqual(2, response.DaysValid); Assert.AreEqual("Hello! Please sign the document below", response.EmailMessage); Assert.AreEqual("Sign Request from Acme", response.EmailSubject); Assert.AreEqual("123", response.ExternalId); Assert.AreEqual(1, response.PrefillTags.Count); Assert.AreEqual("1234", response.PrefillTags[0].DocumentTagId); Assert.AreEqual("text", response.PrefillTags[0].TextValue); Assert.AreEqual(DateTimeOffset.Parse("2021-04-26T08:12:13.982Z"), response.PrefillTags[0].DateValue); } [TestMethod] [TestCategory("CI-UNIT-TEST")] public async Task GetSignRequest_Success() { /*** Arrange ***/ IBoxRequest boxRequest = null; Handler.Setup(h => h.ExecuteAsync<BoxCollectionMarkerBased<BoxSignRequest>>(It.IsAny<IBoxRequest>())) .Returns(Task.FromResult<IBoxResponse<BoxCollectionMarkerBased<BoxSignRequest>>>(new BoxResponse<BoxCollectionMarkerBased<BoxSignRequest>>() { Status = ResponseStatus.Success, ContentString = LoadFixtureFromJson("Fixtures/BoxSignRequest/GetAllSignRequests200.json") })) .Callback<IBoxRequest>(r => boxRequest = r); /*** Act ***/ BoxCollectionMarkerBased<BoxSignRequest> response = await _signRequestsManager.GetSignRequestsAsync(1000, "JV9IRGZmieiBasejOG9yDCRNgd2ymoZIbjsxbJMjIs3kioVii"); /*** Assert ***/ // Request check Assert.IsNotNull(boxRequest); Assert.AreEqual(RequestMethod.Get, boxRequest.Method); Assert.AreEqual(new Uri("https://api.box.com/2.0/sign_requests?limit=1000&marker=JV9IRGZmieiBasejOG9yDCRNgd2ymoZIbjsxbJMjIs3kioVii"), boxRequest.AbsoluteUri); // Response check Assert.AreEqual(1, response.Entries[0].SourceFiles.Count); Assert.AreEqual("12345", response.Entries[0].SourceFiles[0].Id); Assert.AreEqual(1, response.Entries[0].Signers.Count); Assert.AreEqual("example@gmail.com", response.Entries[0].Signers[0].Email); Assert.AreEqual("12345", response.Entries[0].ParentFolder.Id); Assert.IsTrue(response.Entries[0].IsDocumentPreparationNeeded); Assert.IsTrue(response.Entries[0].AreRemindersEnabled); Assert.IsTrue(response.Entries[0].AreTextSignaturesEnabled); Assert.AreEqual(2, response.Entries[0].DaysValid); Assert.AreEqual("Hello! Please sign the document below", response.Entries[0].EmailMessage); Assert.AreEqual("Sign Request from Acme", response.Entries[0].EmailSubject); Assert.AreEqual("123", response.Entries[0].ExternalId); Assert.AreEqual(1, response.Entries[0].PrefillTags.Count); Assert.AreEqual("1234", response.Entries[0].PrefillTags[0].DocumentTagId); Assert.AreEqual("text", response.Entries[0].PrefillTags[0].TextValue); Assert.IsTrue(response.Entries[0].PrefillTags[0].CheckboxValue.Value); Assert.AreEqual(DateTimeOffset.Parse("2021-04-26T08:12:13.982Z"), response.Entries[0].PrefillTags[0].DateValue); } [TestMethod] [TestCategory("CI-UNIT-TEST")] public async Task GetSignRequestById_Success() { /*** Arrange ***/ IBoxRequest boxRequest = null; Handler.Setup(h => h.ExecuteAsync<BoxSignRequest>(It.IsAny<IBoxRequest>())) .Returns(Task.FromResult<IBoxResponse<BoxSignRequest>>(new BoxResponse<BoxSignRequest>() { Status = ResponseStatus.Success, ContentString = LoadFixtureFromJson("Fixtures/BoxSignRequest/GetSignRequest200.json") })) .Callback<IBoxRequest>(r => boxRequest = r); /*** Act ***/ BoxSignRequest response = await _signRequestsManager.GetSignRequestByIdAsync("12345"); /*** Assert ***/ // Request check Assert.IsNotNull(boxRequest); Assert.AreEqual(RequestMethod.Get, boxRequest.Method); Assert.AreEqual(new Uri("https://api.box.com/2.0/sign_requests/12345"), boxRequest.AbsoluteUri); // Response check Assert.AreEqual(1, response.SourceFiles.Count); Assert.AreEqual("12345", response.SourceFiles[0].Id); Assert.AreEqual(1, response.Signers.Count); Assert.AreEqual("example@gmail.com", response.Signers[0].Email); Assert.AreEqual("12345", response.ParentFolder.Id); Assert.IsTrue(response.IsDocumentPreparationNeeded); Assert.IsTrue(response.AreRemindersEnabled); Assert.IsTrue(response.AreTextSignaturesEnabled); Assert.AreEqual(2, response.DaysValid); Assert.AreEqual("Hello! Please sign the document below", response.EmailMessage); Assert.AreEqual("Sign Request from Acme", response.EmailSubject); Assert.AreEqual("123", response.ExternalId); Assert.AreEqual(1, response.PrefillTags.Count); Assert.AreEqual("1234", response.PrefillTags[0].DocumentTagId); Assert.AreEqual("text", response.PrefillTags[0].TextValue); Assert.IsTrue(response.PrefillTags[0].CheckboxValue.Value); Assert.AreEqual(DateTimeOffset.Parse("2021-04-26T08:12:13.982Z"), response.PrefillTags[0].DateValue); } [TestMethod] [TestCategory("CI-UNIT-TEST")] public async Task CancelSignRequest_Success() { /*** Arrange ***/ IBoxRequest boxRequest = null; Handler.Setup(h => h.ExecuteAsync<BoxSignRequest>(It.IsAny<IBoxRequest>())) .Returns(Task.FromResult<IBoxResponse<BoxSignRequest>>(new BoxResponse<BoxSignRequest>() { Status = ResponseStatus.Success, ContentString = LoadFixtureFromJson("Fixtures/BoxSignRequest/CancelSignRequest200.json") })) .Callback<IBoxRequest>(r => boxRequest = r); /*** Act ***/ BoxSignRequest response = await _signRequestsManager.CancelSignRequestAsync("12345"); /*** Assert ***/ // Request check Assert.IsNotNull(boxRequest); Assert.AreEqual(RequestMethod.Post, boxRequest.Method); Assert.AreEqual(new Uri("https://api.box.com/2.0/sign_requests/12345/cancel"), boxRequest.AbsoluteUri); // Response check Assert.AreEqual("12345", response.Id); Assert.AreEqual(BoxSignRequestStatus.cancelled, response.Status); } [TestMethod] [TestCategory("CI-UNIT-TEST")] public async Task ResendSignRequest_Success() { /*** Arrange ***/ IBoxRequest boxRequest = null; Handler.Setup(h => h.ExecuteAsync<object>(It.IsAny<IBoxRequest>())) .Returns(Task.FromResult<IBoxResponse<object>>(new BoxResponse<object>() { Status = ResponseStatus.Success, })) .Callback<IBoxRequest>(r => boxRequest = r); /*** Act ***/ await _signRequestsManager.ResendSignRequestAsync("12345"); /*** Assert ***/ // Request check Assert.IsNotNull(boxRequest); Assert.AreEqual(RequestMethod.Post, boxRequest.Method); Assert.AreEqual(new Uri("https://api.box.com/2.0/sign_requests/12345/resend"), boxRequest.AbsoluteUri); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; using IdentityServer4.Services; using IdentityServer4.Validation; using Nether.Data.Identity; using Nether.Web.Features.Identity.Configuration; using Nether.Common.DependencyInjection; using Nether.Data.Sql.Identity; using Microsoft.Extensions.Logging; using Microsoft.EntityFrameworkCore; using System.Linq; using IdentityServer4.Models; using System.Collections.Generic; using Nether.Integration.Identity; using Microsoft.AspNetCore.Builder; using System.IdentityModel.Tokens.Jwt; namespace Nether.Web.Features.Identity { public static class IdentityServiceExtensions { public static void EnsureInitialAdminUser(this IApplicationBuilder app, IConfiguration configuration, ILogger logger) { try { var serviceProvider = app.ApplicationServices; logger.LogInformation("Identity:Store: Checking user store..."); // construct a context to test if we have a user var identityContext = serviceProvider.GetRequiredService<IdentityContextBase>(); bool gotUsers = identityContext.Users.Any(u => u.Role == RoleNames.Admin); if (gotUsers) { logger.LogInformation("Identity:Store: users exist - no action"); } else { logger.LogInformation("Identity:Store: Adding initial admin user..."); // Create an initial admin var passwordHasher = serviceProvider.GetRequiredService<IPasswordHasher>(); var password = configuration["Identity:InitialSetup:AdminPassword"]; var user = new UserEntity { Role = RoleNames.Admin, IsActive = true, Logins = new List<LoginEntity> { new LoginEntity { ProviderType = LoginProvider.UserNamePassword, ProviderId = "netheradmin", ProviderData = passwordHasher.HashPassword(password) } } }; user.Logins[0].User = user; identityContext.Users.Add(user); identityContext.SaveChanges(); logger.LogInformation("Identity:Store: Adding initial admin user... complete"); } } catch (Exception ex) { logger.LogCritical("Identity:Store: Adding initial admin user, exception: {0}", ex); } } public static IServiceCollection AddIdentityServices( this IServiceCollection services, IConfiguration configuration, ILogger logger, IHostingEnvironment hostingEnvironment) { ConfigureIdentityPlayerMangementClient(services, configuration, logger); ConfigureIdentityServer(services, configuration, logger, hostingEnvironment); ConfigureIdentityStore(services, configuration, logger); return services; } private static void ConfigureIdentityPlayerMangementClient( IServiceCollection services, IConfiguration configuration, ILogger logger) { if (configuration.Exists("Identity:PlayerManagementClient:wellKnown")) { // register using well-known type var wellKnownType = configuration["Identity:PlayerManagementClient:wellknown"]; var scopedConfiguration = configuration.GetSection("Identity:PlayerManagementClient:properties"); switch (wellKnownType) { case "default": var identityBaseUri = scopedConfiguration["IdentityBaseUrl"]; var apiBaseUri = scopedConfiguration["ApiBaseUrl"]; logger.LogInformation("Identity:PlayerManagementClient: using 'default' client with IdentityBaseUrl '{0}', ApiBaseUrl '{1}'", identityBaseUri, apiBaseUri); // could simplify this by requiring the client secret in the properties for PlayerManagementClient, but that duplicates config var clientSource = new ConfigurationBasedClientSource(logger); var clientSecret = clientSource.GetClientSecret(configuration.GetSection("Identity:Clients"), "nether-identity"); if (string.IsNullOrEmpty(clientSecret)) { throw new Exception("Unable to determine the client secret for nether-identity"); } services.AddSingleton<IIdentityPlayerManagementClient, DefaultIdentityPlayerManagementClient>(serviceProvider => { return new DefaultIdentityPlayerManagementClient( identityBaseUri, apiBaseUri, clientSecret, serviceProvider.GetRequiredService<ILogger<DefaultIdentityPlayerManagementClient>>() ); }); break; default: throw new Exception($"Unhandled 'wellKnown' type for Identity:PlayerManagementClient: '{wellKnownType}'"); } } else { // fall back to generic "factory"/"implementation" configuration services.AddServiceFromConfiguration<IUserStore>(configuration, logger, "Identity:PlayerManagementClient"); } } private static void ConfigureIdentityServer( IServiceCollection services, IConfiguration configuration, ILogger logger, IHostingEnvironment hostingEnvironment) { if (hostingEnvironment.EnvironmentName != "Development") { throw new NotSupportedException($"The Identity Server configuration is currently only intended for Development environments. Current environment: '{hostingEnvironment.EnvironmentName}'"); } var clientSource = new ConfigurationBasedClientSource(logger); var clients = clientSource.LoadClients(configuration.GetSection("Identity:Clients")) .ToList(); var identityServerBuilder = services.AddIdentityServer(options => { options.Endpoints.EnableAuthorizeEndpoint = true; options.Endpoints.EnableTokenEndpoint = true; options.UserInteraction.ErrorUrl = "/account/error"; }) .AddTemporarySigningCredential() // using inbuilt signing cert, but we are explicitly a dev-only service at this point ;-) .AddInMemoryClients(clients) .AddInMemoryIdentityResources(Scopes.GetIdentityResources()) .AddInMemoryApiResources(Scopes.GetApiResources()) ; var facebookUserAccessTokenEnabled = bool.Parse(configuration["Identity:SignInMethods:FacebookUserAccessToken:Enabled"] ?? "false"); if (facebookUserAccessTokenEnabled) { identityServerBuilder.AddExtensionGrantValidator<FacebookUserAccessTokenExtensionGrantValidator>(); } services.AddTransient<IPasswordHasher, PasswordHasher>(); services.AddTransient<IProfileService, StoreBackedProfileService>(); services.AddTransient<IResourceOwnerPasswordValidator, StoreBackedResourceOwnerPasswordValidator>(); services.AddTransient<UserClaimsProvider>(); } private static void ConfigureIdentityStore(IServiceCollection services, IConfiguration configuration, ILogger logger) { if (configuration.Exists("Identity:Store:wellKnown")) { // register using well-known type var wellKnownType = configuration["Identity:Store:wellknown"]; var scopedConfiguration = configuration.GetSection("Identity:Store:properties"); switch (wellKnownType) { case "in-memory": logger.LogInformation("Identity:Store: using 'in-memory' store"); services.AddTransient<IUserStore, EntityFrameworkUserStore>(); services.AddTransient<IdentityContextBase, InMemoryIdentityContext>(); break; case "sql": logger.LogInformation("Identity:Store: using 'Sql' store"); string connectionString = scopedConfiguration["ConnectionString"]; services.AddTransient<IUserStore, EntityFrameworkUserStore>(); // Add IdentityContextOptions to configure for SQL Server services.AddSingleton(new SqlIdentityContextOptions { ConnectionString = connectionString }); services.AddTransient<IdentityContextBase, SqlIdentityContext>(); break; default: throw new Exception($"Unhandled 'wellKnown' type for Identity:Store: '{wellKnownType}'"); } } else { // fall back to generic "factory"/"implementation" configuration services.AddServiceFromConfiguration<IUserStore>(configuration, logger, "Identity:Store"); } } private static T GetServiceFromCollection<T>(IServiceCollection services) { return (T)services .LastOrDefault(d => d.ServiceType == typeof(T)) ?.ImplementationInstance; } } }
// Market.cs // // Copyright (c) 2013 Brent Knowles (http://www.brentknowles.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. // // Review documentation at http://www.yourothermind.com for updated implementation notes, license updates // or other general information/ // // Author information available at http://www.brentknowles.com or http://www.amazon.com/Brent-Knowles/e/B0035WW7OW // Full source code: https://github.com/BrentKnowles/YourOtherMind //### using System; using System.ComponentModel; using System.Xml.Serialization; using CoreUtilities; using System.Data; using System.Reflection; using Layout; using MefAddIns; namespace Submissions { public class Market { #region constants private const string MARKETDETAILS = "Market Details"; private const string MARKETPAY = "Market Details - Payment"; #endregion private bool retired = false; [CategoryAttribute(MARKETDETAILS)] public bool Retired { get { return retired; } set { retired = value; } } private string caption = Loc.Instance.GetString ("New Market"); [CategoryAttribute(MARKETDETAILS)] public string Caption { get { return caption; } set { caption = value; } } private string guid = Constants.BLANK; [ReadOnly(true)] [CategoryAttribute("Advanced")] public string Guid { get { return guid; } set { guid = value; } } private string mEditor=Loc.Instance.GetString ("Editor"); private string mAddress; private string mCity; private string mProvince; private string mPostalCode; private string mCountry; private string mWorkPhone; private string mFaxPhone; private string mEmail; private string mWeb; private bool mUnsolicited; private bool mSimultaneous; private bool mMultiple; private bool mQuery; private bool mOnHiatus; private bool mAcceptEmail; private int mAvgRespTime; private double mPayment; private int mMinimumWord; private int mMaximumWord; private DateTime mReadingDateStart; private DateTime mReadingDateEnd; private DateTime mLastUpdate; private bool bHasReadingPeriod; private bool bIsAnthology; private double mMinimumPay; private double mMaximumPay; bool mGeneralAudienceWarning; private bool bAcceptReprints; /// <summary> /// returns the amount of a psosible sale, taking into consideration the min and max /// </summary> /// <param name="words"></param> /// <returns></returns> public decimal GetPossibleSale(int words) { double basevalue = this.Payment * words; if (mMinimumPay != 0 && (basevalue < mMinimumPay)) basevalue = mMinimumPay; if (mMaximumPay != 0 && (basevalue > mMaximumPay)) basevalue = mMaximumPay; return (decimal)basevalue; } [CategoryAttribute(MARKETPAY)] [DescriptionAttribute("If this markets has a minimum payment amount, enter it here.")] [DisplayName("Minimum Payment")] public double MinPayment { get { return mMinimumPay; } set { mMinimumPay = value; } } [CategoryAttribute(MARKETPAY)] [DescriptionAttribute("If this markets has a maximum payment amount, enter it here.")] [DisplayName("Maximum Payment")] public double MaxPayment { get { return mMaximumPay; } set { mMaximumPay = value; } } [CategoryAttribute(MARKETDETAILS)] [TypeConverter(typeof(YesNoTypeConverter))] [DescriptionAttribute("Set to true if this market if you want a warning before submitting this market to remind you to reduce profanity and violence.")] [DisplayName("Profanity Warning?")] public bool ProfanityWarning { get { return mGeneralAudienceWarning; } set { mGeneralAudienceWarning = value; } } [CategoryAttribute(MARKETDETAILS)] [TypeConverter(typeof(YesNoTypeConverter))] [DescriptionAttribute("Does this market publish reprints?")] [DisplayName("Accepts Reprints?")] public bool AcceptReprints { get { return bAcceptReprints; } set { bAcceptReprints = value; } } /// <summary> /// returns true if the market is able to be submitted to /// (not on hiatus or a reading period) /// /// June 2009 - Logic error /// I was returning false if we were IN a reading period /// </summary> /// <returns></returns> public bool Reading() { if (OnHiatus == true) { return false; } if ( (HasReadingPeriod == true) && (ReadingPeriodStart <= DateTime.Today) && (ReadingPeriodEnd>=DateTime.Today)) { return true; } else //outside reading period if ((HasReadingPeriod == true) && ((ReadingPeriodStart > DateTime.Today) || (ReadingPeriodEnd < DateTime.Today))) { return false; } return true; } const string ADDRESS = "Market Address"; const string CONTACT = "Market Contact Information"; /////////////////////////////////////////////// // Property Grid View /////////////////////////////////////////////// const string ADRESSS = "Market Address"; const string DATES = "Market Dates"; [CategoryAttribute(DATES)] [DescriptionAttribute("When does the reading period for this market open?")] [DisplayName("Reading Period, Start")] public DateTime ReadingPeriodStart { get { return mReadingDateStart; } set { mReadingDateStart = value; } } [CategoryAttribute(DATES)] [DescriptionAttribute("Does this market have a reading period? If so, specify the dates when it accepts submissions.")] [DisplayName("Reading Period?")] [TypeConverter(typeof(YesNoTypeConverter))] public bool HasReadingPeriod { get { return bHasReadingPeriod; } set { bHasReadingPeriod = value; } } [CategoryAttribute(DATES)] [DescriptionAttribute("When does the reading period for this market end?")] [DisplayName("Reading Period, End")] public DateTime ReadingPeriodEnd { get { return mReadingDateEnd; } set { mReadingDateEnd = value; } } [CategoryAttribute(CONTACT)] [DescriptionAttribute("Enter the name of the editor, if known.")] [DisplayName("Editor")] public string Editor { get { return mEditor; } set { mEditor = value; } } [CategoryAttribute(ADDRESS)] [DescriptionAttribute("Enter the street address or box number.")] [DisplayName("Address")] public string Address { get { return mAddress; } set { mAddress = value; } } [CategoryAttribute(ADDRESS)] [DescriptionAttribute("Enter the city portion of the market's address.")] [DisplayName("City")] public string City { get { return mCity; } set { mCity = value; } } [CategoryAttribute(ADDRESS)] [DescriptionAttribute("Enter the state or province for the market.")] [DisplayName("State or Province")] public string Province { get { return mProvince; } set { mProvince = value; } } [CategoryAttribute(ADDRESS)] [DescriptionAttribute("Enter the ZIP or Postal Code for the market.")] [DisplayName("ZIP or Postal Code")] public string PostalCode { get { return mPostalCode; } set { mPostalCode = value; } } [CategoryAttribute(ADDRESS)] [DescriptionAttribute("Enter the country portion of the market's address.")] [DisplayName("Country")] public string Country { get { return mCountry; } set { mCountry = value; } } [CategoryAttribute(CONTACT)] [DescriptionAttribute("Enter the phone number.")] [DisplayName("Phone#, Work")] public string WorkPhone { get { return mWorkPhone; } set { mWorkPhone = value; } } [CategoryAttribute(CONTACT)] [DescriptionAttribute("Enter the fax number.")] [DisplayName("Fax#")] public string FaxPhone { get { return mFaxPhone; } set { mFaxPhone = value; } } [CategoryAttribute(CONTACT)] [DescriptionAttribute("The e-mail address for this market.")] [DisplayName("E-mail")] public string Email { get { return mEmail; } set { mEmail = value; } } [CategoryAttribute(CONTACT)] [DescriptionAttribute("Enter the URL for the market's web-site.")] [DisplayName("URL")] public string Web { get { return mWeb; } set { mWeb = value; } } [CategoryAttribute(MARKETDETAILS)] [TypeConverter(typeof(YesNoTypeConverter))] [DescriptionAttribute("Is this market an anthology?")] [DisplayName("Is Anthology?")] public bool IsAnthology { get { return bIsAnthology; } set { bIsAnthology = value; } } [CategoryAttribute(MARKETDETAILS)] [TypeConverter(typeof(YesNoTypeConverter))] [DescriptionAttribute("Does this market accept unsolicited submissions?")] [DisplayName("Accepts Unsolicited")] public bool Unsolicited { get { return mUnsolicited; } set { mUnsolicited = value; } } [CategoryAttribute(MARKETDETAILS)] [TypeConverter(typeof(YesNoTypeConverter))] [DescriptionAttribute("Does this market allow submissions to be sent to it while the same submission has been submitted to another market?")] [DisplayName("Accepts Simultaneous")] public bool Simultaneous { get { return mSimultaneous; } set { mSimultaneous = value; } } [CategoryAttribute(MARKETDETAILS)] [TypeConverter(typeof(YesNoTypeConverter))] [DescriptionAttribute("Does this market accept multiple submissions at the same time?")] [DisplayName("Accepts Multiple")] public bool Multiple { get { return mMultiple; } set { mMultiple = value; } } [CategoryAttribute(MARKETDETAILS)] [TypeConverter(typeof(YesNoTypeConverter))] [DescriptionAttribute("Does this market accept/encourage queries?")] [DisplayName("Accepts Queries")] public bool Query { get { return mQuery; } set { mQuery = value; } } [CategoryAttribute(MARKETDETAILS)] [TypeConverter(typeof(YesNoTypeConverter))] [DescriptionAttribute("Does this market accept electronic submissions (e-mail or form)?")] [DisplayName("Accepts electronic submissions")] public bool AcceptsEmail { get { return mAcceptEmail; } set { mAcceptEmail = value; } } [CategoryAttribute(MARKETDETAILS)] [TypeConverter(typeof(YesNoTypeConverter))] [DescriptionAttribute("Is this market current on hiatus (not accepting submissions)?")] [DisplayName("On Hiatus")] public bool OnHiatus { get { return mOnHiatus; } set { mOnHiatus = value; } } [CategoryAttribute(MARKETDETAILS)] [DescriptionAttribute("The average number of days to receive a response.")] [DisplayName("Average Response Time")] public int AverageResponeTime { get { return mAvgRespTime; } set { mAvgRespTime = value; } } [CategoryAttribute(MARKETPAY)] [DescriptionAttribute("How much per word will you be paid when the market accepts your submission.")] [DisplayName("Payment per word")] public double Payment { get { return mPayment; } set { mPayment = value; } } [CategoryAttribute(MARKETDETAILS)] [DescriptionAttribute("What is the minimum sized submission the market considers?")] [DisplayName("Words, Minimum")] public int MinimumWord { get { return mMinimumWord; } set { mMinimumWord = value; } } [CategoryAttribute(MARKETDETAILS)] [DescriptionAttribute("What is the maximum sized submission the market considers?")] [DisplayName("Words, Maximum")] public int MaximumWord { get { return mMaximumWord; } set { mMaximumWord = value; } } [CategoryAttribute(DATES)] [DescriptionAttribute("When was this market last updated by you? This field is set automatically.")] [DisplayName("Last Updated On...")] public DateTime LastUpdate { get { return mLastUpdate; } set { mLastUpdate = value; } } private string publishtype; [CategoryAttribute(MARKETDETAILS)] // [System.ComponentModel.TypeConverter(typeof(CoreUtilities.EnumDescConverter))] [TypeConverter(typeof(PublishTypeListConverter))] [DisplayName("Publishing Type")] [DescriptionAttribute("Indicate whether this ia print or online magazine")] public string PublishType { get { return publishtype; } set { publishtype = value; } } private string markettype; [CategoryAttribute(MARKETDETAILS)] // [System.ComponentModel.TypeConverter(typeof(CoreUtilities.EnumDescConverter))] [TypeConverter(typeof(MarketTypeListConverter))] [DisplayName("Pay Category/Market Type")] [DescriptionAttribute("Indicate the type of market")] public string MarketType { get { return markettype; } set { markettype = value; } } private string notes = Constants.BLANK; [Browsable(false)] public string Notes { get { return notes; } set { notes = value; } } public Market () { } public Market (DataRow DataBaseRow) { // creates a Market object based on the contents of a databaserow // this.Caption = DataBaseRow["Caption"].ToString() ; // this.GetType ().InvokeMember (field, // BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty, // Type.DefaultBinder, this, DataBaseRow [field]); foreach (DataColumn column in (DataBaseRow.Table.Columns )){ //foreach (DataColumn column in ((DataView)DataBaseRow.DataView).Table.Columns ){ string field = column.ColumnName; //"Caption"; Type type = this.GetType (); PropertyInfo prop = type.GetProperty (field); try { object setter = DataBaseRow [field]; if (prop.GetType () == typeof(float)) { float test = 0.0f; if (float.TryParse (setter.ToString (), out test) == false) { // failed parse, default to 0 setter = 0.0f; } } if (prop.GetType () == typeof(bool)) { bool test = false; if (bool.TryParse(setter.ToString (), out test) == false) { // failed parse, default to false setter = false; } } if (null != prop) { prop.SetValue (this, DataBaseRow [field], null); } } catch (Exception) { // the Market Add/Edit form should prevent data issues but if the user // modified by hand we might end up with invalid values. } } } public static Market DefaultMarket() { Market defaultMarket = new Market(); defaultMarket.Guid = System.Guid.NewGuid().ToString (); defaultMarket.PublishType = LayoutDetails.Instance.TableLayout.GetListOfStringsFromSystemTable(Addin_Submissions.SYSTEM_PUBLISHTYPES,1)[0]; defaultMarket.MarketType = LayoutDetails.Instance.TableLayout.GetListOfStringsFromSystemTable(Addin_Submissions.SYSTEM_MARKETTYPES,1)[0];; defaultMarket.MinimumWord = 1000; defaultMarket.MaximumWord = 5000; defaultMarket.AcceptReprints = false; defaultMarket.AcceptsEmail = true; defaultMarket.LastUpdate = DateTime.Now; defaultMarket.ProfanityWarning = false; defaultMarket.Web="www.brentknowles.com"; defaultMarket.Payment = 0.05; return defaultMarket; } } }
//----------------------------------------------------------------------- // <copyright file="TimeoutsSpec.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.Collections.Generic; using System.Linq; using System.Threading; using Akka.Streams.Dsl; using Akka.Streams.TestKit; using Akka.Streams.TestKit.Tests; using Akka.TestKit; using FluentAssertions; using Xunit; using Xunit.Abstractions; namespace Akka.Streams.Tests.Implementation { public class TimeoutsSpec : AkkaSpec { private ActorMaterializer Materializer { get; } public TimeoutsSpec(ITestOutputHelper helper = null) : base(helper) { Materializer = ActorMaterializer.Create(Sys); } [Fact] public void InitialTimeout_must_pass_through_elements_unmodified() { this.AssertAllStagesStopped(() => { var t = Source.From(Enumerable.Range(1, 100)) .InitialTimeout(TimeSpan.FromSeconds(2)).Grouped(200) .RunWith(Sink.First<IEnumerable<int>>(), Materializer); t.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); t.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 100)); }, Materializer); } [Fact] public void InitialTimeout_must_pass_through_error_unmodified() { this.AssertAllStagesStopped(() => { var task = Source.From(Enumerable.Range(1, 100)) .Concat(Source.Failed<int>(new TestException("test"))) .InitialTimeout(TimeSpan.FromSeconds(2)).Grouped(200) .RunWith(Sink.First<IEnumerable<int>>(), Materializer); task.Invoking(t => t.Wait(TimeSpan.FromSeconds(3))) .ShouldThrow<TestException>().WithMessage("test"); }, Materializer); } [Fact] public void InitialTimeout_must_fail_if_no_initial_element_passes_until_timeout() { this.AssertAllStagesStopped(() => { var downstreamProbe = this.CreateSubscriberProbe<int>(); Source.Maybe<int>() .InitialTimeout(TimeSpan.FromSeconds(1)) .RunWith(Sink.FromSubscriber(downstreamProbe), Materializer); downstreamProbe.ExpectSubscription(); downstreamProbe.ExpectNoMsg(TimeSpan.FromMilliseconds(500)); var ex = downstreamProbe.ExpectError(); ex.Message.Should().Be($"The first element has not yet passed through in {TimeSpan.FromSeconds(1)}."); }, Materializer); } [Fact] public void CompletionTimeout_must_pass_through_elements_unmodified() { this.AssertAllStagesStopped(() => { var t = Source.From(Enumerable.Range(1, 100)) .CompletionTimeout(TimeSpan.FromSeconds(2)).Grouped(200) .RunWith(Sink.First<IEnumerable<int>>(), Materializer); t.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); t.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 100)); }, Materializer); } [Fact] public void CompletionTimeout_must_pass_through_error_unmodified() { this.AssertAllStagesStopped(() => { var task = Source.From(Enumerable.Range(1, 100)) .Concat(Source.Failed<int>(new TestException("test"))) .CompletionTimeout(TimeSpan.FromSeconds(2)).Grouped(200) .RunWith(Sink.First<IEnumerable<int>>(), Materializer); task.Invoking(t => t.Wait(TimeSpan.FromSeconds(3))) .ShouldThrow<TestException>().WithMessage("test"); }, Materializer); } [Fact] public void CompletionTimeout_must_fail_if_not_completed_until_timeout() { this.AssertAllStagesStopped(() => { var upstreamProbe = this.CreatePublisherProbe<int>(); var downstreamProbe = this.CreateSubscriberProbe<int>(); Source.FromPublisher(upstreamProbe) .CompletionTimeout(TimeSpan.FromSeconds(2)) .RunWith(Sink.FromSubscriber(downstreamProbe), Materializer); upstreamProbe.SendNext(1); downstreamProbe.RequestNext(1); downstreamProbe.ExpectNoMsg(TimeSpan.FromMilliseconds(500)); // No timeout yet upstreamProbe.SendNext(2); downstreamProbe.RequestNext(2); downstreamProbe.ExpectNoMsg(TimeSpan.FromMilliseconds(500)); // No timeout yet var ex = downstreamProbe.ExpectError(); ex.Message.Should().Be($"The stream has not been completed in {TimeSpan.FromSeconds(2)}."); }, Materializer); } [Fact] public void IdleTimeout_must_pass_through_elements_unmodified() { this.AssertAllStagesStopped(() => { var t = Source.From(Enumerable.Range(1, 100)) .IdleTimeout(TimeSpan.FromSeconds(2)).Grouped(200) .RunWith(Sink.First<IEnumerable<int>>(), Materializer); t.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); t.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 100)); }, Materializer); } [Fact] public void IdleTimeout_must_pass_through_error_unmodified() { this.AssertAllStagesStopped(() => { var task = Source.From(Enumerable.Range(1, 100)) .Concat(Source.Failed<int>(new TestException("test"))) .IdleTimeout(TimeSpan.FromSeconds(2)).Grouped(200) .RunWith(Sink.First<IEnumerable<int>>(), Materializer); task.Invoking(t => t.Wait(TimeSpan.FromSeconds(3))) .ShouldThrow<TestException>().WithMessage("test"); }, Materializer); } [Fact] public void IdleTimeout_must_fail_if_time_between_elements_is_too_large() { this.AssertAllStagesStopped(() => { var upstreamProbe = this.CreatePublisherProbe<int>(); var downstreamProbe = this.CreateSubscriberProbe<int>(); Source.FromPublisher(upstreamProbe) .IdleTimeout(TimeSpan.FromSeconds(1)) .RunWith(Sink.FromSubscriber(downstreamProbe), Materializer); // Two seconds in overall, but won't timeout until time between elements is large enough // (i.e. this works differently from completionTimeout) for (var i = 1; i <= 4; i++) { upstreamProbe.SendNext(1); downstreamProbe.RequestNext(1); downstreamProbe.ExpectNoMsg(TimeSpan.FromMilliseconds(500)); // No timeout yet } var ex = downstreamProbe.ExpectError(); ex.Message.Should().Be($"No elements passed in the last {TimeSpan.FromSeconds(1)}."); }, Materializer); } [Fact] public void BackpressureTimeout_must_pass_through_elements_unmodified() { this.AssertAllStagesStopped(() => { Source.From(Enumerable.Range(1, 100)) .BackpressureTimeout(TimeSpan.FromSeconds(1)) .Grouped(200) .RunWith(Sink.First<IEnumerable<int>>(), Materializer) .AwaitResult() .ShouldAllBeEquivalentTo(Enumerable.Range(1, 100)); }, Materializer); } [Fact] public void BackpressureTimeout_must_succeed_if_subscriber_demand_arrives() { this.AssertAllStagesStopped(() => { var subscriber = this.CreateSubscriberProbe<int>(); Source.From(new[] { 1, 2, 3, 4 }) .BackpressureTimeout(TimeSpan.FromSeconds(1)) .RunWith(Sink.FromSubscriber(subscriber), Materializer); for (var i = 1; i < 4; i++) { subscriber.RequestNext(i); subscriber.ExpectNoMsg(TimeSpan.FromMilliseconds(250)); } subscriber.RequestNext(4); subscriber.ExpectComplete(); }, Materializer); } [Fact] public void BackpressureTimeout_must_not_throw_if_publisher_is_less_frequent_than_timeout() { this.AssertAllStagesStopped(() => { var publisher = this.CreatePublisherProbe<string>(); var subscriber = this.CreateSubscriberProbe<string>(); Source.FromPublisher(publisher) .BackpressureTimeout(TimeSpan.FromSeconds(1)) .RunWith(Sink.FromSubscriber(subscriber), Materializer); subscriber.Request(2).ExpectNoMsg(TimeSpan.FromSeconds(1)); publisher.SendNext("Quick Msg"); subscriber.ExpectNext("Quick Msg"); subscriber.ExpectNoMsg(TimeSpan.FromSeconds(3)); publisher.SendNext("Slow Msg"); subscriber.ExpectNext("Slow Msg"); publisher.SendComplete(); subscriber.ExpectComplete(); }, Materializer); } [Fact] public void BackpressureTimeout_must_not_throw_if_publisher_wont_perform_emission_ever() { this.AssertAllStagesStopped(() => { var publisher = this.CreatePublisherProbe<string>(); var subscriber = this.CreateSubscriberProbe<string>(); Source.FromPublisher(publisher) .BackpressureTimeout(TimeSpan.FromSeconds(1)) .RunWith(Sink.FromSubscriber(subscriber), Materializer); subscriber.Request(16).ExpectNoMsg(TimeSpan.FromSeconds(2)); publisher.SendComplete(); subscriber.ExpectComplete(); }, Materializer); } [Fact] public void BackpressureTimeout_must_throw_if_subscriber_wont_generate_demand_on_time() { this.AssertAllStagesStopped(() => { var publisher = this.CreatePublisherProbe<int>(); var subscriber = this.CreateSubscriberProbe<int>(); Source.FromPublisher(publisher) .BackpressureTimeout(TimeSpan.FromSeconds(1)) .RunWith(Sink.FromSubscriber(subscriber), Materializer); subscriber.Request(1); publisher.SendNext(1); subscriber.ExpectNext(1); Thread.Sleep(3000); subscriber.ExpectError().Message.Should().Be("No demand signalled in the last 00:00:01."); }, Materializer); } [Fact] public void BackpressureTimeout_must_throw_if_subscriber_never_generate_demand() { this.AssertAllStagesStopped(() => { var publisher = this.CreatePublisherProbe<int>(); var subscriber = this.CreateSubscriberProbe<int>(); Source.FromPublisher(publisher) .BackpressureTimeout(TimeSpan.FromSeconds(1)) .RunWith(Sink.FromSubscriber(subscriber), Materializer); subscriber.ExpectSubscription(); Thread.Sleep(3000); subscriber.ExpectError().Message.Should().Be("No demand signalled in the last 00:00:01."); }, Materializer); } [Fact] public void BackpressureTimeout_must_not_throw_if_publisher_completes_without_fulfilling_subscribers_demand() { this.AssertAllStagesStopped(() => { var publisher = this.CreatePublisherProbe<int>(); var subscriber = this.CreateSubscriberProbe<int>(); Source.FromPublisher(publisher) .BackpressureTimeout(TimeSpan.FromSeconds(1)) .RunWith(Sink.FromSubscriber(subscriber), Materializer); subscriber.Request(2); publisher.SendNext(1); subscriber.ExpectNext(1); subscriber.ExpectNoMsg(TimeSpan.FromSeconds(2)); publisher.SendComplete(); subscriber.ExpectComplete(); }, Materializer); } [Fact] public void IdleTimeoutBidi_must_not_signal_error_in_simple_loopback_case_and_pass_through_elements_unmodified() { this.AssertAllStagesStopped(() => { var timeoutIdentity = BidiFlow.BidirectionalIdleTimeout<int, int>(TimeSpan.FromSeconds(2)).Join(Flow.Create<int>()); var t = Source.From(Enumerable.Range(1, 100)) .Via(timeoutIdentity).Grouped(200) .RunWith(Sink.First<IEnumerable<int>>(), Materializer); t.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); t.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 100)); }, Materializer); } [Fact] public void IdleTimeoutBidi_must_not_signal_error_if_traffic_is_one_way() { this.AssertAllStagesStopped(() => { var upstreamWriter = this.CreatePublisherProbe<int>(); var downstreamWriter = this.CreatePublisherProbe<string>(); var upstream = Flow.FromSinkAndSource(Sink.Ignore<string>(), Source.FromPublisher(upstreamWriter), Keep.Left); var downstream = Flow.FromSinkAndSource(Sink.Ignore<int>(), Source.FromPublisher(downstreamWriter), Keep.Left); var assembly = upstream.JoinMaterialized( BidiFlow.BidirectionalIdleTimeout<int, string>(TimeSpan.FromSeconds(2)), Keep.Left).JoinMaterialized(downstream, Keep.Both); var r = assembly.Run(Materializer); var upFinished = r.Item1; var downFinished = r.Item2; upstreamWriter.SendNext(1); Thread.Sleep(1000); upstreamWriter.SendNext(1); Thread.Sleep(1000); upstreamWriter.SendNext(1); Thread.Sleep(1000); upstreamWriter.SendComplete(); downstreamWriter.SendComplete(); upFinished.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); downFinished.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); }, Materializer); } [Fact] public void IdleTimeoutBidi_must_be_able_to_signal_timeout_once_no_traffic_on_either_sides() { this.AssertAllStagesStopped(() => { var upWrite = this.CreatePublisherProbe<string>(); var upRead = this.CreateSubscriberProbe<int>(); var downWrite = this.CreatePublisherProbe<int>(); var downRead = this.CreateSubscriberProbe<string>(); RunnableGraph.FromGraph(GraphDsl.Create(b => { var timeoutStage = b.Add(BidiFlow.BidirectionalIdleTimeout<string, int>(TimeSpan.FromSeconds(2))); b.From(Source.FromPublisher(upWrite)).To(timeoutStage.Inlet1); b.From(timeoutStage.Outlet1).To(Sink.FromSubscriber(downRead)); b.From(timeoutStage.Outlet2).To(Sink.FromSubscriber(upRead)); b.From(Source.FromPublisher(downWrite)).To(timeoutStage.Inlet2); return ClosedShape.Instance; })).Run(Materializer); // Request enough for the whole test upRead.Request(100); downRead.Request(100); upWrite.SendNext("DATA1"); downRead.ExpectNext("DATA1"); Thread.Sleep(1500); downWrite.SendNext(1); upRead.ExpectNext(1); Thread.Sleep(1500); upWrite.SendNext("DATA2"); downRead.ExpectNext("DATA2"); Thread.Sleep(1000); downWrite.SendNext(2); upRead.ExpectNext(2); upRead.ExpectNoMsg(TimeSpan.FromMilliseconds(500)); var error1 = upRead.ExpectError(); var error2 = downRead.ExpectError(); error1.Should().BeOfType<TimeoutException>(); error1.Message.Should().Be($"No elements passed in the last {TimeSpan.FromSeconds(2)}."); error2.ShouldBeEquivalentTo(error1); upWrite.ExpectCancellation(); downWrite.ExpectCancellation(); }, Materializer); } [Fact] public void IdleTimeoutBidi_must_signal_error_to_all_outputs() { this.AssertAllStagesStopped(() => { var upWrite = this.CreatePublisherProbe<string>(); var upRead = this.CreateSubscriberProbe<int>(); var downWrite = this.CreatePublisherProbe<int>(); var downRead = this.CreateSubscriberProbe<string>(); RunnableGraph.FromGraph(GraphDsl.Create(b => { var timeoutStage = b.Add(BidiFlow.BidirectionalIdleTimeout<string, int>(TimeSpan.FromSeconds(2))); b.From(Source.FromPublisher(upWrite)).To(timeoutStage.Inlet1); b.From(timeoutStage.Outlet1).To(Sink.FromSubscriber(downRead)); b.From(timeoutStage.Outlet2).To(Sink.FromSubscriber(upRead)); b.From(Source.FromPublisher(downWrite)).To(timeoutStage.Inlet2); return ClosedShape.Instance; })).Run(Materializer); var te = new TestException("test"); upWrite.SendError(te); upRead.ExpectSubscriptionAndError().ShouldBeEquivalentTo(te); downRead.ExpectSubscriptionAndError().ShouldBeEquivalentTo(te); downWrite.ExpectCancellation(); }, Materializer); } } }
using System; using System.Collections; using System.IO; using System.Text; using NUnit.Framework; using Org.BouncyCastle.Bcpg.Attr; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Generators; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Math; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.Utilities.IO; using Org.BouncyCastle.Utilities.Test; namespace Org.BouncyCastle.Bcpg.OpenPgp.Tests { [TestFixture] public class PgpRsaTest : SimpleTest { private static readonly byte[] testPubKey = Base64.Decode( "mIsEPz2nJAEEAOTVqWMvqYE693qTgzKv/TJpIj3hI8LlYPC6m1dk0z3bDLwVVk9F" + "FAB+CWS8RdFOWt/FG3tEv2nzcoNdRvjv9WALyIGNawtae4Ml6oAT06/511yUzXHO" + "k+9xK3wkXN5jdzUhf4cA2oGpLSV/pZlocsIDL+jCUQtumUPwFodmSHhzAAYptC9F" + "cmljIEVjaGlkbmEgKHRlc3Qga2V5KSA8ZXJpY0Bib3VuY3ljYXN0bGUub3JnPoi4" + "BBMBAgAiBQI/PackAhsDBQkAg9YABAsHAwIDFQIDAxYCAQIeAQIXgAAKCRA1WGFG" + "/fPzc8WMA/9BbjuB8E48QAlxoiVf9U8SfNelrz/ONJA/bMvWr/JnOGA9PPmFD5Uc" + "+kV/q+i94dEMjsC5CQ1moUHWSP2xlQhbOzBP2+oPXw3z2fBs9XJgnTH6QWMAAvLs" + "3ug9po0loNHLobT/D/XdXvcrb3wvwvPT2FptZqrtonH/OdzT9JdfrA=="); private static readonly byte[] testPrivKey = Base64.Decode( "lQH8BD89pyQBBADk1aljL6mBOvd6k4Myr/0yaSI94SPC5WDwuptXZNM92wy8FVZP" + "RRQAfglkvEXRTlrfxRt7RL9p83KDXUb47/VgC8iBjWsLWnuDJeqAE9Ov+ddclM1x" + "zpPvcSt8JFzeY3c1IX+HANqBqS0lf6WZaHLCAy/owlELbplD8BaHZkh4cwAGKf4D" + "AwKbLeIOVYTEdWD5v/YgW8ERs0pDsSIfBTvsJp2qA798KeFuED6jGsHUzdi1M990" + "6PRtplQgnoYmYQrzEc6DXAiAtBR4Kuxi4XHx0ZR2wpVlVxm2Ypgz7pbBNWcWqzvw" + "33inl7tR4IDsRdJOY8cFlN+1tSCf16sDidtKXUVjRjZNYJytH18VfSPlGXMeYgtw" + "3cSGNTERwKaq5E/SozT2MKTiORO0g0Mtyz+9MEB6XVXFavMun/mXURqbZN/k9BFb" + "z+TadpkihrLD1xw3Hp+tpe4CwPQ2GdWKI9KNo5gEnbkJgLrSMGgWalPhknlNHRyY" + "bSq6lbIMJEE3LoOwvYWwweR1+GrV9farJESdunl1mDr5/d6rKru+FFDwZM3na1IF" + "4Ei4FpqhivZ4zG6pN5XqLy+AK85EiW4XH0yAKX1O4YlbmDU4BjxhiwTdwuVMCjLO" + "5++jkz5BBQWdFX8CCMA4FJl36G70IbGzuFfOj07ly7QvRXJpYyBFY2hpZG5hICh0" + "ZXN0IGtleSkgPGVyaWNAYm91bmN5Y2FzdGxlLm9yZz6IuAQTAQIAIgUCPz2nJAIb" + "AwUJAIPWAAQLBwMCAxUCAwMWAgECHgECF4AACgkQNVhhRv3z83PFjAP/QW47gfBO" + "PEAJcaIlX/VPEnzXpa8/zjSQP2zL1q/yZzhgPTz5hQ+VHPpFf6voveHRDI7AuQkN" + "ZqFB1kj9sZUIWzswT9vqD18N89nwbPVyYJ0x+kFjAALy7N7oPaaNJaDRy6G0/w/1" + "3V73K298L8Lz09habWaq7aJx/znc0/SXX6w="); private static readonly byte[] testPubKeyV3 = Base64.Decode( "mQCNAz+zvlEAAAEEAMS22jgXbOZ/D3xWgM2kauSdzrwlU7Ms5hDW05ObqQyO" + "FfQoKKMhfupyoa7J3x04VVBKu6Eomvr1es+VImH0esoeWFFahNOYq/I+jRRB" + "woOhAGZ5UB2/hRd7rFmxqp6sCXi8wmLO2tAorlTzAiNNvl7xF4cQZpc0z56F" + "wdi2fBUJAAURtApGSVhDSVRZX1FBiQCVAwUQP7O+UZ6Fwdi2fBUJAQFMwwQA" + "qRnFsdg4xQnB8Y5d4cOpXkIn9AZgYS3cxtuSJB84vG2CgC39nfv4c+nlLkWP" + "4puG+mZuJNgVoE84cuAF4I//1anKjlU7q1M6rFQnt5S4uxPyG3dFXmgyU1b4" + "PBOnA0tIxjPzlIhJAMsPCGGA5+5M2JP0ad6RnzqzE3EENMX+GqY="); private static readonly byte[] testPrivKeyV3 = Base64.Decode( "lQHfAz+zvlEAAAEEAMS22jgXbOZ/D3xWgM2kauSdzrwlU7Ms5hDW05ObqQyO" + "FfQoKKMhfupyoa7J3x04VVBKu6Eomvr1es+VImH0esoeWFFahNOYq/I+jRRB" + "woOhAGZ5UB2/hRd7rFmxqp6sCXi8wmLO2tAorlTzAiNNvl7xF4cQZpc0z56F" + "wdi2fBUJAAURAXWwRBZQHNikA/f0ScLLjrXi4s0hgQecg+dkpDow94eu5+AR" + "0DzZnfurpgfUJCNiDi5W/5c3Zj/xyrfMAgkbCgJ1m6FZqAQh7Mq73l7Kfu4/" + "XIkyDF3tDgRuZNezB+JuElX10tV03xumHepp6M6CfhXqNJ15F33F99TA5hXY" + "CPYD7SiSOpIhQkCOAgDAA63imxbpuKE2W7Y4I1BUHB7WQi8ZdkZd04njNTv+" + "rFUuOPapQVfbWG0Vq8ld3YmJB4QWsa2mmqn+qToXbwufAgBpXkjvqK5yPiHF" + "Px2QbFc1VqoCJB6PO5JRIqEiUZBFGdDlLxt3VSyqz7IZ/zEnxZq+tPCGGGSm" + "/sAGiMvENcHVAfy0kTXU42TxEAYJyyNyqjXOobDJpEV1mKhFskRXt7tbMfOS" + "Yf91oX8f6xw6O2Nal+hU8dS0Bmfmk5/enHmvRLHQocO0CkZJWENJVFlfUUE="); private static readonly byte[] sig1 = Base64.Decode( "owGbwMvMwMRoGpHo9vfz52LGNTJJnBmpOTn5eiUVJfb23JvAHIXy/KKcFEWuToap" + "zKwMIGG4Bqav0SwMy3yParsEKi2LMGI9xhh65sBxb05n5++ZLcWNJ/eLFKdWbm95" + "tHbDV7GMwj/tUctUpFUXWPYFCLdNsDiVNuXbQvZtdXV/5xzY+9w1nCnijH9JoNiJ" + "22n2jo0zo30/TZLo+jDl2vTzIvPeLEsPM3ZUE/1Ytqs4SG2TxIQbH7xf3uzcYXq2" + "5Fw9AA=="); // private static readonly byte[] sig1crc = Base64.Decode("+3i0"); private static readonly byte[] subKey = Base64.Decode( "lQH8BD89pyQBBADk1aljL6mBOvd6k4Myr/0yaSI94SPC5WDwuptXZNM92wy8FVZP" + "RRQAfglkvEXRTlrfxRt7RL9p83KDXUb47/VgC8iBjWsLWnuDJeqAE9Ov+ddclM1x" + "zpPvcSt8JFzeY3c1IX+HANqBqS0lf6WZaHLCAy/owlELbplD8BaHZkh4cwAGKf4D" + "AwKt6ZC7iqsQHGDNn2ZAuhS+ZwiFC+BToW9Vq6rwggWjgM/SThv55rfDk7keiXUT" + "MyUcZVeYBe4Jttb4fAAm83hNztFu6Jvm9ITcm7YvnasBtVQjppaB+oYZgsTtwK99" + "LGC3mdexnriCLxPN6tDFkGhzdOcYZfK6py4Ska8Dmq9nOZU9Qtv7Pm3qa5tuBvYw" + "myTxeaJYifZTu/sky3Gj+REb8WonbgAJX/sLNBPUt+vYko+lxU8uqZpVEMU//hGG" + "Rns2gIHdbSbIe1vGgIRUEd7Z0b7jfVQLUwqHDyfh5DGvAUhvtJogjUyFIXZzpU+E" + "9ES9t7LZKdwNZSIdNUjM2eaf4g8BpuQobBVkj/GUcotKyeBjwvKxHlRefL4CCw28" + "DO3SnLRKxd7uBSqeOGUKxqasgdekM/xIFOrJ85k7p89n6ncLQLHCPGVkzmVeRZro" + "/T7zE91J57qBGZOUAP1vllcYLty1cs9PCc5oWnj3XbQvRXJpYyBFY2hpZG5hICh0" + "ZXN0IGtleSkgPGVyaWNAYm91bmN5Y2FzdGxlLm9yZz6IuAQTAQIAIgUCPz2nJAIb" + "AwUJAIPWAAQLBwMCAxUCAwMWAgECHgECF4AACgkQNVhhRv3z83PFjAP/QW47gfBO" + "PEAJcaIlX/VPEnzXpa8/zjSQP2zL1q/yZzhgPTz5hQ+VHPpFf6voveHRDI7AuQkN" + "ZqFB1kj9sZUIWzswT9vqD18N89nwbPVyYJ0x+kFjAALy7N7oPaaNJaDRy6G0/w/1" + "3V73K298L8Lz09habWaq7aJx/znc0/SXX6y0JEVyaWMgRWNoaWRuYSA8ZXJpY0Bi" + "b3VuY3ljYXN0bGUub3JnPoi4BBMBAgAiBQI/RxQNAhsDBQkAg9YABAsHAwIDFQID" + "AxYCAQIeAQIXgAAKCRA1WGFG/fPzc3O6A/49tXFCiiP8vg77OXvnmbnzPBA1G6jC" + "RZNP1yIXusOjpHqyLN5K9hw6lq/o4pNiCuiq32osqGRX3lv/nDduJU1kn2Ow+I2V" + "ci+ojMXdCGdEqPwZfv47jHLwRrIUJ22OOoWsORtgvSeRUd4Izg8jruaFM7ufr5hr" + "jEl1cuLW1Hr8Lp0B/AQ/RxxQAQQA0J2BIdqb8JtDGKjvYxrju0urJVVzyI1CnCjA" + "p7CtLoHQJUQU7PajnV4Jd12ukfcoK7MRraYydQEjxh2MqPpuQgJS3dgQVrxOParD" + "QYBFrZNd2tZxOjYakhErvUmRo6yWFaxChwqMgl8XWugBNg1Dva+/YcoGQ+ly+Jg4" + "RWZoH88ABin+AwMCldD/2v8TyT1ghK70IuFs4MZBhdm6VgyGR8DQ/Ago6IAjA4BY" + "Sol3lJb7+IIGsZaXwEuMRUvn6dWfa3r2I0p1t75vZb1Ng1YK32RZ5DNzl4Xb3L8V" + "D+1Fiz9mHO8wiplAwDudB+RmQMlth3DNi/UsjeCTdEJAT+TTC7D40DiHDb1bR86Y" + "2O5Y7MQ3SZs3/x0D/Ob6PStjfQ1kiqbruAMROKoavG0zVgxvspkoKN7h7BapnwJM" + "6yf4qN/aByhAx9sFvADxu6z3SVcxiFw3IgAmabyWYb85LP8AsTYAG/HBoC6yob47" + "Mt+GEDeyPifzzGXBWYIH4heZbSQivvA0eRwY5VZsMsBkbY5VR0FLVWgplbuO21bS" + "rPS1T0crC+Zfj7FQBAkTfsg8RZQ8MPaHng01+gnFd243DDFvTAHygvm6a2X2fiRw" + "5epAST4wWfY/BZNOxmfSKH6QS0oQMRscw79He6vGTB7vunLrKQYD4veInwQYAQIA" + "CQUCP0ccUAIbDAAKCRA1WGFG/fPzczmFA/wMg5HhN5NkqmjnHUFfeXNXdHzmekyw" + "38RnuCMKmfc43AiDs+FtJ62gpQ6PEsZF4o9S5fxcjVk3VSg00XMDtQ/0BsKBc5Gx" + "hJTq7G+/SoeM433WG19uoS0+5Lf/31wNoTnpv6npOaYpcTQ7L9LCnzwAF4H0hJPE" + "6bhmW2CMcsE/IZUB4QQ/Rwc1EQQAs5MUQlRiYOfi3fQ1OF6Z3eCwioDKu2DmOxot" + "BICvdoG2muvs0KEBas9bbd0FJqc92FZJv8yxEgQbQtQAiFxoIFHRTFK+SPO/tQm+" + "r83nwLRrfDeVVdRfzF79YCc+Abuh8sS/53H3u9Y7DYWr9IuMgI39nrVhY+d8yukf" + "jo4OR+sAoKS/f7V1Xxj/Eqhb8qzf+N+zJRUlBACDd1eo/zFJZcq2YJa7a9vkViME" + "axvwApqxeoU7oDpeHEMWg2DXJ7V24ZU5SbPTMY0x98cc8pcoqwsqux8xicWc0reh" + "U3odQxWM4Se0LmEdca0nQOmNJlL9IsQ+QOJzx47qUOUAqhxnkXxQ/6B8w+M6gZya" + "fwSdy70OumxESZipeQP+Lo9x6FcaW9L78hDX0aijJhgSEsnGODKB+bln29txX37E" + "/a/Si+pyeLMi82kUdIL3G3I5HPWd3qSO4K94062+HfFj8bA20/1tbb/WxvxB2sKJ" + "i3IobblFOvFHo+v8GaLdVyartp0JZLue/jP1dl9ctulSrIqaJT342uLsgTjsr2z+" + "AwMCAyAU8Vo5AhhgFkDto8vQk7yxyRKEzu5qB66dRcTlaUPIiR8kamcy5ZTtujs4" + "KIW4j2M/LvagrpWfV5+0M0VyaWMgRWNoaWRuYSAoRFNBIFRlc3QgS2V5KSA8ZXJp" + "Y0Bib3VuY3ljYXN0bGUub3JnPohZBBMRAgAZBQI/Rwc1BAsHAwIDFQIDAxYCAQIe" + "AQIXgAAKCRDNI/XpxMo0QwJcAJ40447eezSiIMspuzkwsMyFN8YBaQCdFTuZuT30" + "CphiUYWnsC0mQ+J15B4="); private static readonly byte[] enc1 = Base64.Decode( "hIwDKwfQexPJboABA/4/7prhYYMORTiQ5avQKx0XYpCLujzGefYjnyuWZnx3Iev8" + "Pmsguumm+OLLvtXhhkXQmkJRXbIg6Otj2ubPYWflRPgpJSgOrNOreOl5jeABOrtw" + "bV6TJb9OTtZuB7cTQSCq2gmYiSZkluIiDjNs3R3mEanILbYzOQ3zKSggKpzlv9JQ" + "AZUqTyDyJ6/OUbJF5fI5uiv76DCsw1zyMWotUIu5/X01q+AVP5Ly3STzI7xkWg/J" + "APz4zUHism7kSYz2viAQaJx9/bNnH3AM6qm1Fuyikl4="); // private static readonly byte[] enc1crc = Base64.Decode("lv4o"); // private static readonly byte[] enc2 = Base64.Decode( // "hIwDKwfQexPJboABBAC62jcJH8xKnKb1neDVmiovYON04+7VQ2v4BmeHwJrdag1g" // + "Ya++6PeBlQ2Q9lSGBwLobVuJmQ7cOnPUJP727JeSGWlMyFtMbBSHekOaTenT5lj7" // + "Zk7oRHxMp/hByzlMacIDzOn8LPSh515RHM57eDLCOwqnAxGQwk67GRl8f5dFH9JQ" // + "Aa7xx8rjCqPbiIQW6t5LqCNvPZOiSCmftll6+se1XJhFEuq8WS4nXtPfTiJ3vib4" // + "3soJdHzGB6AOs+BQ6aKmmNTVAxa5owhtSt1Z/6dfSSk="); private static readonly byte[] subPubKey = Base64.Decode( "mIsEPz2nJAEEAOTVqWMvqYE693qTgzKv/TJpIj3hI8LlYPC6m1dk0z3bDLwVVk9F" + "FAB+CWS8RdFOWt/FG3tEv2nzcoNdRvjv9WALyIGNawtae4Ml6oAT06/511yUzXHO" + "k+9xK3wkXN5jdzUhf4cA2oGpLSV/pZlocsIDL+jCUQtumUPwFodmSHhzAAYptC9F" + "cmljIEVjaGlkbmEgKHRlc3Qga2V5KSA8ZXJpY0Bib3VuY3ljYXN0bGUub3JnPoi4" + "BBMBAgAiBQI/PackAhsDBQkAg9YABAsHAwIDFQIDAxYCAQIeAQIXgAAKCRA1WGFG" + "/fPzc8WMA/9BbjuB8E48QAlxoiVf9U8SfNelrz/ONJA/bMvWr/JnOGA9PPmFD5Uc" + "+kV/q+i94dEMjsC5CQ1moUHWSP2xlQhbOzBP2+oPXw3z2fBs9XJgnTH6QWMAAvLs" + "3ug9po0loNHLobT/D/XdXvcrb3wvwvPT2FptZqrtonH/OdzT9JdfrIhMBBARAgAM" + "BQI/RxooBYMAemL8AAoJEM0j9enEyjRDiBgAn3RcLK+gq90PvnQFTw2DNqdq7KA0" + "AKCS0EEIXCzbV1tfTdCUJ3hVh3btF7QkRXJpYyBFY2hpZG5hIDxlcmljQGJvdW5j" + "eWNhc3RsZS5vcmc+iLgEEwECACIFAj9HFA0CGwMFCQCD1gAECwcDAgMVAgMDFgIB" + "Ah4BAheAAAoJEDVYYUb98/Nzc7oD/j21cUKKI/y+Dvs5e+eZufM8EDUbqMJFk0/X" + "Ihe6w6OkerIs3kr2HDqWr+jik2IK6KrfaiyoZFfeW/+cN24lTWSfY7D4jZVyL6iM" + "xd0IZ0So/Bl+/juMcvBGshQnbY46haw5G2C9J5FR3gjODyOu5oUzu5+vmGuMSXVy" + "4tbUevwuiEwEEBECAAwFAj9HGigFgwB6YvwACgkQzSP16cTKNEPwBQCdHm0Amwza" + "NmVmDHm3rmqI7rp2oQ0An2YbiP/H/kmBNnmTeH55kd253QOhuIsEP0ccUAEEANCd" + "gSHam/CbQxio72Ma47tLqyVVc8iNQpwowKewrS6B0CVEFOz2o51eCXddrpH3KCuz" + "Ea2mMnUBI8YdjKj6bkICUt3YEFa8Tj2qw0GARa2TXdrWcTo2GpIRK71JkaOslhWs" + "QocKjIJfF1roATYNQ72vv2HKBkPpcviYOEVmaB/PAAYpiJ8EGAECAAkFAj9HHFAC" + "GwwACgkQNVhhRv3z83M5hQP8DIOR4TeTZKpo5x1BX3lzV3R85npMsN/EZ7gjCpn3" + "ONwIg7PhbSetoKUOjxLGReKPUuX8XI1ZN1UoNNFzA7UP9AbCgXORsYSU6uxvv0qH" + "jON91htfbqEtPuS3/99cDaE56b+p6TmmKXE0Oy/Swp88ABeB9ISTxOm4ZltgjHLB" + "PyGZAaIEP0cHNREEALOTFEJUYmDn4t30NThemd3gsIqAyrtg5jsaLQSAr3aBtprr" + "7NChAWrPW23dBSanPdhWSb/MsRIEG0LUAIhcaCBR0UxSvkjzv7UJvq/N58C0a3w3" + "lVXUX8xe/WAnPgG7ofLEv+dx97vWOw2Fq/SLjICN/Z61YWPnfMrpH46ODkfrAKCk" + "v3+1dV8Y/xKoW/Ks3/jfsyUVJQQAg3dXqP8xSWXKtmCWu2vb5FYjBGsb8AKasXqF" + "O6A6XhxDFoNg1ye1duGVOUmz0zGNMffHHPKXKKsLKrsfMYnFnNK3oVN6HUMVjOEn" + "tC5hHXGtJ0DpjSZS/SLEPkDic8eO6lDlAKocZ5F8UP+gfMPjOoGcmn8Encu9Drps" + "REmYqXkD/i6PcehXGlvS+/IQ19GooyYYEhLJxjgygfm5Z9vbcV9+xP2v0ovqcniz" + "IvNpFHSC9xtyORz1nd6kjuCveNOtvh3xY/GwNtP9bW2/1sb8QdrCiYtyKG25RTrx" + "R6Pr/Bmi3Vcmq7adCWS7nv4z9XZfXLbpUqyKmiU9+Nri7IE47K9stDNFcmljIEVj" + "aGlkbmEgKERTQSBUZXN0IEtleSkgPGVyaWNAYm91bmN5Y2FzdGxlLm9yZz6IWQQT" + "EQIAGQUCP0cHNQQLBwMCAxUCAwMWAgECHgECF4AACgkQzSP16cTKNEMCXACfauui" + "bSwyG59Yrm8hHCDuCPmqwsQAni+dPl08FVuWh+wb6kOgJV4lcYae"); // private static readonly byte[] subPubCrc = Base64.Decode("rikt"); private static readonly byte[] pgp8Key = Base64.Decode( "lQIEBEBXUNMBBADScQczBibewnbCzCswc/9ut8R0fwlltBRxMW0NMdKJY2LF" + "7k2COeLOCIU95loJGV6ulbpDCXEO2Jyq8/qGw1qD3SCZNXxKs3GS8Iyh9Uwd" + "VL07nMMYl5NiQRsFB7wOb86+94tYWgvikVA5BRP5y3+O3GItnXnpWSJyREUy" + "6WI2QQAGKf4JAwIVmnRs4jtTX2DD05zy2mepEQ8bsqVAKIx7lEwvMVNcvg4Y" + "8vFLh9Mf/uNciwL4Se/ehfKQ/AT0JmBZduYMqRU2zhiBmxj4cXUQ0s36ysj7" + "fyDngGocDnM3cwPxaTF1ZRBQHSLewP7dqE7M73usFSz8vwD/0xNOHFRLKbsO" + "RqDlLA1Cg2Yd0wWPS0o7+qqk9ndqrjjSwMM8ftnzFGjShAdg4Ca7fFkcNePP" + "/rrwIH472FuRb7RbWzwXA4+4ZBdl8D4An0dwtfvAO+jCZSrLjmSpxEOveJxY" + "GduyR4IA4lemvAG51YHTHd4NXheuEqsIkn1yarwaaj47lFPnxNOElOREMdZb" + "nkWQb1jfgqO24imEZgrLMkK9bJfoDnlF4k6r6hZOp5FSFvc5kJB4cVo1QJl4" + "pwCSdoU6luwCggrlZhDnkGCSuQUUW45NE7Br22NGqn4/gHs0KCsWbAezApGj" + "qYUCfX1bcpPzUMzUlBaD5rz2vPeO58CDtBJ0ZXN0ZXIgPHRlc3RAdGVzdD6I" + "sgQTAQIAHAUCQFdQ0wIbAwQLBwMCAxUCAwMWAgECHgECF4AACgkQs8JyyQfH" + "97I1QgP8Cd+35maM2cbWV9iVRO+c5456KDi3oIUSNdPf1NQrCAtJqEUhmMSt" + "QbdiaFEkPrORISI/2htXruYn0aIpkCfbUheHOu0sef7s6pHmI2kOQPzR+C/j" + "8D9QvWsPOOso81KU2axUY8zIer64Uzqc4szMIlLw06c8vea27RfgjBpSCryw" + "AgAA"); private static readonly char[] pgp8Pass = "2002 Buffalo Sabres".ToCharArray(); private static readonly char[] pass = "hello world".ToCharArray(); private static readonly byte[] fingerprintKey = Base64.Decode( "mQEPA0CiJdUAAAEIAMI+znDlPd2kQoEcnxqxLcRz56Z7ttFKHpnYp0UkljZdquVc" + "By1jMfXGVV64xN1IvMcyenLXUE0IUeUBCQs6tHunFRAPSeCxJ3FdFe1B5MpqQG8A" + "BnEpAds/hAUfRDZD5y/lolk1hjvFMrRh6WXckaA/QQ2t00NmTrJ1pYUpkw9tnVQb" + "LUjWJhfZDBBcN0ADtATzgkugxMtcDxR6I5x8Ndn+IilqIm23kxGIcmMd/BHOec4c" + "jRwJXXDb7u8tl+2knAf9cwhPHp3+Zy4uGSQPdzQnXOhBlA+4WDa0RROOevWgq8uq" + "8/9Xp/OlTVL+OoIzjsI6mJP1Joa4qmqAnaHAmXcAEQEAAbQoQk9BM1JTS1kgPEJP" + "QSBNb25pdG9yaW5nIEAgODg4LTI2OS01MjY2PokBFQMFEECiJdWqaoCdocCZdwEB" + "0RsH/3HPxoUZ3G3K7T3jgOnJUckTSHWU3XspHzMVgqOxjTrcexi5IsAM5M+BulfW" + "T2aO+Kqf5w8cKTKgW02DNpHUiPjHx0nzDE+Do95zbIErGeK+Twkc4O/aVsvU9GGO" + "81VFI6WMvDQ4CUAUnAdk03MRrzI2nAuhn4NJ5LQS+uJrnqUJ4HmFAz6CQZQKd/kS" + "Xgq+A6i7aI1LG80YxWa9ooQgaCrb9dwY/kPQ+yC22zQ3FExtv+Fv3VtAKTilO3vn" + "BA4Y9uTHuObHfI+1yxUS2PrlRUX0m48ZjpIX+cEN3QblGBJudI/A1QSd6P0LZeBr" + "7F1Z1aF7ZDo0KzgiAIBvgXkeTpw="); // private static readonly byte[] fingerprintCheck = Base64.Decode("CTv2"); private static readonly byte[] jpegImage = Base64.Decode( "/9j/4AAQSkZJRgABAQEASABIAAD/4QAWRXhpZgAATU0AKgAAAAgAAAAAAAD/2wBDAAUDBAQEAwUE" + "BAQFBQUGBwwIBwcHBw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/" + "wAALCAA6AFABASIA/8QAHAAAAgMAAwEAAAAAAAAAAAAABQcABAYBAggD/8QAMRAAAgEDBAEDAwME" + "AQUAAAAAAQIDBAURAAYSITEHIkETFFEjYXEVMkKRCCUzQ4Gh/9oACAEBAAA/APX1TdKCmlaOoqoo" + "WXzzbiP9nWaS71lXuA2tqrgopBOxpyGyWLAEEd4GAf3+fOjLPXoVaOcNzYAhl8HskADwAPz37f3z" + "opSvI9Mjypwcr7l/B1XuFwSmoTVooljB9xDYAH51Vor191F9dKGb6Py3yo4huwcHwf8AYP7ZLIyu" + "gZSGBGQQejrnU1NKn1EqVi3sZJOBCwxxIp9xzksfb5PR+Mdga+ljqIKje1TNBBNToYYgU4477HwQ" + "Bn9z8/nW6mqxLR0NzpJkMLx8lJUkOGAIx4I/0f41lJ93UkkrRxVKvNKVjZfpSe6RyqhCp7wCSD89" + "EEDRWppEkgqKdYohGcoZAjAlSMMcZ+PHH/3odsG6VLW2qaoqV+nTyFZpHOFQL0Sc9ADGTnHWtZap" + "EpoamJm/TgYkfgJ5H/zGuKieVJIGkqCgmfCJFFy64s3Z+Oh58fHyNfGavipIJ2BrZcKXA+mzEd9Y" + "OCcHI/gDV62SzvBGKhQHaNWzj8jvP750oN/xM3qkshLPEstOhj7IVyvkY+f7Nd7hf9vbc9QbVb7n" + "dadLldqc00FMCwlmZnCrgL2v/cAySPBPwSD+/wC+3HbWx3rLbaqW81CVHOWnetMZjRm9h7VvClcj" + "oDB7PymPTvem+a6roxvC10sd3ScmlucdEyUtRADxdice9wY3PQGRgj4OnHU3u5RW+op6imo4q+KA" + "1UKGQ/bzrnt0biWxkgFOJK9ZyCCVX6f3T1Rh9RawbltdQNv18CGe2wxBDQyvGrowIJd15HEnHvP+" + "OBjXoGzS0tNTpQipFTIw48Xn5SSBVUMw5e5wMgZ/j86yVNvvZ9TeDR1c9XSV0bl443dmYZXiCSCR" + "jvxkjR1L1b46iWpStpIRLOWkCqyniP8AJjxPIniBjr+etFdu11DVu321WZiFHRjZcA/gsO+seNYf" + "fVpq6n1Eo5KNATIYmb5Bx7csP4z/AKz8aX1N6Q7W3FuWWrS1TRzi+tXSutUESQhCGiVAvJVRgfcc" + "HkeidM6tSmTbps9RHIH4KoqC8j/VC8R0+CSScZLdknPZGgNfYpUUUzfewxxcWpopWbhL715KgBIQ" + "MCQc4A84+dD963X7ywQ0NIVW60qqzkzIfoszAMGUNyUHORkDrHxo3sSaOhtX2hnp3uNRF9b7hqtO" + "DxM3Rcj3dMCPHXLGfOkLuPddp9R/ViOa62KppqK3Vctvsz0UylKtWfgXy3+L8WIZFBGRhs407rTT" + "bcuFDRWmtsNGIZ1MMEU9GPqRorKPcJEzhich8Anz350Wk2zs2OsT7D7RZJpChMEk0MoypJZWVwM9" + "ZzjWw2lbKaioFjQy/U9shLyu7Esi5JLEnsgnQlaSqhqayWSRZ5JaiSSNPoBCiq54jPuJyA2W+QfA" + "+FrSXq4bdulZHRpWRzpArPK0SSNUExh14qB4c5X9ipz41Zud0juVouVooHN6rrZKVaoek/VhYgqE" + "4v7cZPTfPHwT7tZX0e2NVUV5rK2ku9TeY6aFZJ6GuLALKzNnizE4CsqHIyBxJCk4AYFNt2wSUExm" + "pP1lqgq1zkfXUtIgkiOFHQCsCM/kfOtZU7GsNZU1FFc1lrqCSNSlFOQ8SJk8kC4/tJx1rMwbWt0V" + "CW21VW+krVoFTCRrPC0bf+NF8ocqMcT/AIg6EVF5/p9U6zPXLVFGpoKlSpMiEkniSCcqVY+eQIPW" + "NULf/UNxJNS0dhklu8SK9Lco6pUcEr0JOu1HQ7z+R5OndaI5leWV0VQ54kA5KlWIx/Gqd2t6vcqe" + "FIXNJMs71SoCMsQuG5jsN8AAjyTnrGlt6mVlqswtS0SG71NTXpSiCQFpogckll6Y4wvyD/OToVd7" + "3tLedda4Nr3iRK2mqJhW1K0qxSSGJf1OTOAwwVADLkA9fPV2W77msVfPTClNRUyJCla0SqS5dR5J" + "b2kluKlQc5BbHnWu2xTS0G4qmjvSq6RwrPHJUMHkkYDhzJHXIhmBAHnxpaL6j3il3D6g1VLuSz1k" + "1ht//S6SZQ4KoTI6MyMOb9hR85HedM/0wqn3RsC0bhgq/pQV9J9WELEFaNWGARg+04xkd95xjQTe" + "df6c7U+ysl3mtMFJe5JYGkkmAVKgKZCZGzlVbBySemA/OgvpZUQxvaqitgoqSsiX6XKh5RwVCBP0" + "8KCTIoU8VJyDjIA8Bs2e5CprDTR8VXi8pRgyyZMh8qQMDHz850ZOlVv30RsW5blcL5S3a626+1cq" + "TirFQ0qJIgAQCNjgIMeFKn9wQCMA3o2vprca/ctp29Jv6/3aoZ4IRRx08dC5D8nWQv7FJYHByeuv" + "zo5SWn1Z2ttahutFZqbcG6JK5ZLu1TNEzzUq5ASNyVw6pxUMc5Oc5znR6KyXffldUVW4rBcbAqos" + "EUq1qrUzUkwy8bFB+m4ZI2IBbAJAbOdau0+nmybJYqe027atvNHTRlYomhVz+Tln8knyScn50j/+" + "SOyd3VO2oDtmPcNPYqJgDt23xKtOIiTy6gYO/Z5YOcAHGsJ/x39NgbzuDc+0bNt6/wAySmltbXGv" + "flaT8ST07xBjIR30RjsL+dex9uwT/wBKo6i5UtPFdHp4/u/pgECTiOQDYBIByB+w0RVEVmZUUM39" + "xA7P867ampqampqaq09BQwV9RWwUVNFU1AUTTJEoeQLnHJgMnGTjP51a1Nf/2Q=="); private static readonly byte[] embeddedJPEGKey = Base64.Decode( "mI0ER0JXuwEEAKNqsXwLU6gu6P2Q/HJqEJVt3A7Kp1yucn8HWVeJF9JLAKVjVU8jrvz9Bw4NwaRJ" + "NGYEAgdRq8Hx3WP9FXFCIVfCdi+oQrphcHWzzBFul8sykUGT+LmcBdqQGU9WaWSJyCOmUht4j7t0" + "zk/IXX0YxGmkqR+no5rTj9LMDG8AQQrFABEBAAG0P0VyaWMgSCBFY2hpZG5hIChpbWFnZSB0ZXN0" + "IGtleSkgPGVyaWMuZWNoaWRuYUBib3VuY3ljYXN0bGUub3JnPoi2BBMBAgAgBQJHQle7AhsDBgsJ" + "CAcDAgQVAggDBBYCAwECHgECF4AACgkQ1+RWqFFpjMTKtgP+Okqkn0gVpQyNYXM/hWX6f3UQcyXk" + "2Sd/fWW0XG+LBjhhBo+lXRWK0uYF8OMdZwsSl9HimpgYD5/kNs0Seh417DioP1diOgxkgezyQgMa" + "+ODZfNnIvVaBr1pHLPLeqIBxBVMWBfa4wDXnLLGu8018uvI2yBhz5vByB1ntxwgKMXCwAgAD0cf3" + "x/UBEAABAQAAAAAAAAAAAAAAAP/Y/+AAEEpGSUYAAQEBAEgASAAA/+EAFkV4aWYAAE1NACoAAAAI" + "AAAAAAAA/9sAQwAFAwQEBAMFBAQEBQUFBgcMCAcHBwcPCwsJDBEPEhIRDxERExYcFxMUGhURERgh" + "GBodHR8fHxMXIiQiHiQcHh8e/8AACwgAOgBQAQEiAP/EABwAAAIDAAMBAAAAAAAAAAAAAAUHAAQG" + "AQIIA//EADEQAAIBAwQBAwMDBAEFAAAAAAECAwQFEQAGEiExByJBExRRI2FxFTJCkQglM0OBof/a" + "AAgBAQAAPwD19U3SgppWjqKqKFl8824j/Z1mku9ZV7gNraq4KKQTsachsliwBBHeBgH9/nzoyz16" + "FWjnDc2AIZfB7JAA8AD89+3986KUryPTI8qcHK+5fwdV7hcEpqE1aKJYwfcQ2AB+dVaK9fdRfXSh" + "m+j8t8qOIbsHB8H/AGD+2SyMroGUhgRkEHo651NTSp9RKlYt7GSTgQsMcSKfcc5LH2+T0fjHYGvp" + "Y6iCo3tUzQQTU6GGIFOOO+x8EAZ/c/P51upqsS0dDc6SZDC8fJSVJDhgCMeCP9H+NZSfd1JJK0cV" + "SrzSlY2X6UnukcqoQqe8Akg/PRBA0VqaRJIKinWKIRnKGQIwJUjDHGfjxx/96HbBulS1tqmqKlfp" + "08hWaRzhUC9EnPQAxk5x1rWWqRKaGpiZv04GJH4CeR/8xrionlSSBpKgoJnwiRRcuuLN2fjoefHx" + "8jXxmr4qSCdga2XClwPpsxHfWDgnByP4A1etks7wRioUB2jVs4/I7z++dKDf8TN6pLISzxLLToY+" + "yFcr5GPn+zXe4X/b23PUG1W+53WnS5XanNNBTAsJZmZwq4C9r/3AMkjwT8Eg/v8Avtx21sd6y22q" + "lvNQlRzlp3rTGY0ZvYe1bwpXI6Awez8pj073pvmuq6MbwtdLHd0nJpbnHRMlLUQA8XYnHvcGNz0B" + "kYI+Dpx1N7uUVvqKeopqOKvigNVChkP28657dG4lsZIBTiSvWcgglV+n909UYfUWsG5bXUDb9fAh" + "ntsMQQ0Mrxq6MCCXdeRxJx7z/jgY16Bs0tLTU6UIqRUyMOPF5+UkgVVDMOXucDIGf4/OslTb72fU" + "3g0dXPV0ldG5eON3ZmGV4gkgkY78ZI0dS9W+OolqUraSESzlpAqsp4j/ACY8TyJ4gY6/nrRXbtdQ" + "1bt9tVmYhR0Y2XAP4LDvrHjWH31aaup9RKOSjQEyGJm+Qce3LD+M/wCs/Gl9TekO1txbllq0tU0c" + "4vrV0rrVBEkIQholQLyVUYH3HB5HonTOrUpk26bPURyB+CqKgvI/1QvEdPgkknGS3ZJz2RoDX2KV" + "FFM33sMcXFqaKVm4S+9eSoASEDAkHOAPOPnQ/et1+8sENDSFVutKqs5MyH6LMwDBlDclBzkZA6x8" + "aN7EmjobV9oZ6d7jURfW+4arTg8TN0XI93TAjx1yxnzpC7j3XafUf1Yjmutiqaait1XLb7M9FMpS" + "rVn4F8t/i/FiGRQRkYbONO60023LhQ0VprbDRiGdTDBFPRj6kaKyj3CRM4YnIfAJ89+dFpNs7Njr" + "E+w+0WSaQoTBJNDKMqSWVlcDPWc41sNpWymoqBY0Mv1PbIS8ruxLIuSSxJ7IJ0JWkqoamslkkWeS" + "WokkjT6AQoqueIz7icgNlvkHwPha0l6uG3bpWR0aVkc6QKzytEkjVBMYdeKgeHOV/Yqc+NWbndI7" + "laLlaKBzeq62SlWqHpP1YWIKhOL+3GT03zx8E+7WV9HtjVVFeaytpLvU3mOmhWSehriwCyszZ4sx" + "OArKhyMgcSQpOAGBTbdsElBMZqT9ZaoKtc5H11LSIJIjhR0ArAjP5HzrWVOxrDWVNRRXNZa6gkjU" + "pRTkPEiZPJAuP7ScdazMG1rdFQlttVVvpK1aBUwkazwtG3/jRfKHKjHE/wCIOhFRef6fVOsz1y1R" + "RqaCpUqTIhJJ4kgnKlWPnkCD1jVC3/1DcSTUtHYZJbvEivS3KOqVHBK9CTrtR0O8/keTp3WiOZXl" + "ldFUOeJAOSpViMfxqndrer3KnhSFzSTLO9UqAjLELhuY7DfAAI8k56xpbeplZarMLUtEhu9TU16U" + "ogkBaaIHJJZemOML8g/zk6FXe97S3nXWuDa94kStpqiYVtStKsUkhiX9TkzgMMFQAy5APXz1dlu+" + "5rFXz0wpTUVMiQpWtEqkuXUeSW9pJbipUHOQWx51rtsU0tBuKpo70qukcKzxyVDB5JGA4cyR1yIZ" + "gQB58aWi+o94pdw+oNVS7ks9ZNYbf/0ukmUOCqEyOjMjDm/YUfOR3nTP9MKp90bAtG4YKv6UFfSf" + "VhCxBWjVhgEYPtOMZHfecY0E3nX+nO1PsrJd5rTBSXuSWBpJJgFSoCmQmRs5VWwcknpgPzoL6WVE" + "Mb2qorYKKkrIl+lyoeUcFQgT9PCgkyKFPFScg4yAPAbNnuQqaw00fFV4vKUYMsmTIfKkDAx8/OdG" + "TpVb99EbFuW5XC+Ut2utuvtXKk4qxUNKiSIAEAjY4CDHhSp/cEAjAN6Nr6a3Gv3LadvSb+v92qGe" + "CEUcdPHQuQ/J1kL+xSWBwcnrr86OUlp9WdrbWobrRWam3BuiSuWS7tUzRM81KuQEjclcOqcVDHOT" + "nOc50eisl335XVFVuKwXGwKqLBFKtaq1M1JMMvGxQfpuGSNiAWwCQGznWrtPp5smyWKntNu2rbzR" + "00ZWKJoVc/k5Z/JJ8knJ+dI//kjsnd1TtqA7Zj3DT2KiYA7dt8SrTiIk8uoGDv2eWDnABxrCf8d/" + "TYG87g3PtGzbev8AMkppbW1xr35Wk/Ek9O8QYyEd9EY7C/nXsfbsE/8ASqOouVLTxXR6eP7v6YBA" + "k4jkA2ASAcgfsNEVRFZmVFDN/cQOz/Ou2pqampqamqtPQUMFfUVsFFTRVNQFE0yRKHkC5xyYDJxk" + "4z+dWtTX/9mItgQTAQIAIAUCR0JYkAIbAwYLCQgHAwIEFQIIAwQWAgMBAh4BAheAAAoJENfkVqhR" + "aYzEAPYD/iHdLOAE8r8HHF3F4z28vtIT8iiRB9aPC/YH0xqV1qeEKG8+VosBaQAOCEquONtRWsww" + "gO3XB0d6VAq2kMOKc2YiB4ZtZcFvvmP9KdmVIZxVjpa9ozjP5j9zFso1HOpFcsn/VDBEqy5TvsNx" + "Qvmtc8X7lqK/zLRVkSSBItik2IIhsAIAAw=="); private void FingerPrintTest() { // // version 3 // PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(fingerprintKey); PgpPublicKey pubKey = pgpPub.GetPublicKey(); if (!Arrays.AreEqual(pubKey.GetFingerprint(), Hex.Decode("4FFB9F0884266C715D1CEAC804A3BBFA"))) { Fail("version 3 fingerprint test failed"); } // // version 4 // pgpPub = new PgpPublicKeyRing(testPubKey); pubKey = pgpPub.GetPublicKey(); if (!Arrays.AreEqual(pubKey.GetFingerprint(), Hex.Decode("3062363c1046a01a751946bb35586146fdf3f373"))) { Fail("version 4 fingerprint test failed"); } } private void MixedTest( PgpPrivateKey pgpPrivKey, PgpPublicKey pgpPubKey) { byte[] text = Encoding.ASCII.GetBytes("hello world!\n"); // // literal data // MemoryStream bOut = new MemoryStream(); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); Stream lOut = lGen.Open( bOut, PgpLiteralData.Binary, PgpLiteralData.Console, text.Length, DateTime.UtcNow); lOut.Write(text, 0, text.Length); lGen.Close(); byte[] bytes = bOut.ToArray(); PgpObjectFactory f = new PgpObjectFactory(bytes); CheckLiteralData((PgpLiteralData)f.NextPgpObject(), text); MemoryStream bcOut = new MemoryStream(); PgpEncryptedDataGenerator encGen = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Aes128, true, new SecureRandom()); encGen.AddMethod(pgpPubKey); encGen.AddMethod("password".ToCharArray()); Stream cOut = encGen.Open(bcOut, bytes.Length); cOut.Write(bytes, 0, bytes.Length); cOut.Close(); byte[] encData = bcOut.ToArray(); // // asymmetric // PgpObjectFactory pgpF = new PgpObjectFactory(encData); PgpEncryptedDataList encList = (PgpEncryptedDataList) pgpF.NextPgpObject(); PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0]; Stream clear = encP.GetDataStream(pgpPrivKey); PgpObjectFactory pgpFact = new PgpObjectFactory(clear); CheckLiteralData((PgpLiteralData)pgpFact.NextPgpObject(), text); // // PBE // pgpF = new PgpObjectFactory(encData); encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); PgpPbeEncryptedData encPbe = (PgpPbeEncryptedData) encList[1]; clear = encPbe.GetDataStream("password".ToCharArray()); pgpF = new PgpObjectFactory(clear); CheckLiteralData((PgpLiteralData) pgpF.NextPgpObject(), text); } private void CheckLiteralData( PgpLiteralData ld, byte[] data) { if (!ld.FileName.Equals(PgpLiteralData.Console)) throw new Exception("wrong filename in packet"); Stream inLd = ld.GetDataStream(); byte[] bytes = Streams.ReadAll(inLd); if (!AreEqual(bytes, data)) { Fail("wrong plain text in decrypted packet"); } } private void ExistingEmbeddedJpegTest() { PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(embeddedJPEGKey); PgpPublicKey pubKey = pgpPub.GetPublicKey(); int count = 0; foreach (PgpUserAttributeSubpacketVector attributes in pubKey.GetUserAttributes()) { int sigCount = 0; foreach (PgpSignature sig in pubKey.GetSignaturesForUserAttribute(attributes)) { sig.InitVerify(pubKey); if (!sig.VerifyCertification(attributes, pubKey)) { Fail("signature failed verification"); } sigCount++; } if (sigCount != 1) { Fail("Failed user attributes signature check"); } count++; } if (count != 1) { Fail("didn't find user attributes"); } } private void EmbeddedJpegTest() { PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(testPubKey); PgpSecretKeyRing pgpSec = new PgpSecretKeyRing(testPrivKey); PgpPublicKey pubKey = pgpPub.GetPublicKey(); PgpUserAttributeSubpacketVectorGenerator vGen = new PgpUserAttributeSubpacketVectorGenerator(); vGen.SetImageAttribute(ImageAttrib.Format.Jpeg, jpegImage); PgpUserAttributeSubpacketVector uVec = vGen.Generate(); PgpSignatureGenerator sGen = new PgpSignatureGenerator( PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.PositiveCertification, pgpSec.GetSecretKey().ExtractPrivateKey(pass)); PgpSignature sig = sGen.GenerateCertification(uVec, pubKey); PgpPublicKey nKey = PgpPublicKey.AddCertification(pubKey, uVec, sig); int count = 0; foreach (PgpUserAttributeSubpacketVector attributes in nKey.GetUserAttributes()) { int sigCount = 0; foreach (PgpSignature s in nKey.GetSignaturesForUserAttribute(attributes)) { s.InitVerify(pubKey); if (!s.VerifyCertification(attributes, pubKey)) { Fail("added signature failed verification"); } sigCount++; } if (sigCount != 1) { Fail("Failed added user attributes signature check"); } count++; } if (count != 1) { Fail("didn't find added user attributes"); } nKey = PgpPublicKey.RemoveCertification(nKey, uVec); if (nKey.GetUserAttributes().GetEnumerator().MoveNext()) { Fail("found attributes where none expected"); } } public override void PerformTest() { // // Read the public key // PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(testPubKey); AsymmetricKeyParameter pubKey = pgpPub.GetPublicKey().GetKey(); IEnumerator enumerator = pgpPub.GetPublicKey().GetUserIds().GetEnumerator(); enumerator.MoveNext(); string uid = (string) enumerator.Current; enumerator = pgpPub.GetPublicKey().GetSignaturesForId(uid).GetEnumerator(); enumerator.MoveNext(); PgpSignature sig = (PgpSignature) enumerator.Current; sig.InitVerify(pgpPub.GetPublicKey()); if (!sig.VerifyCertification(uid, pgpPub.GetPublicKey())) { Fail("failed to verify certification"); } // // write a public key // MemoryStream bOut = new UncloseableMemoryStream(); BcpgOutputStream pOut = new BcpgOutputStream(bOut); pgpPub.Encode(pOut); if (!Arrays.AreEqual(bOut.ToArray(), testPubKey)) { Fail("public key rewrite failed"); } // // Read the public key // PgpPublicKeyRing pgpPubV3 = new PgpPublicKeyRing(testPubKeyV3); AsymmetricKeyParameter pubKeyV3 = pgpPub.GetPublicKey().GetKey(); // // write a V3 public key // bOut = new UncloseableMemoryStream(); pOut = new BcpgOutputStream(bOut); pgpPubV3.Encode(pOut); // // Read a v3 private key // char[] passP = "FIXCITY_QA".ToCharArray(); #if INCLUDE_IDEA { PgpSecretKeyRing pgpPriv2 = new PgpSecretKeyRing(testPrivKeyV3); PgpSecretKey pgpPrivSecretKey = pgpPriv2.GetSecretKey(); PgpPrivateKey pgpPrivKey2 = pgpPrivSecretKey.ExtractPrivateKey(passP); // // write a v3 private key // bOut = new UncloseableMemoryStream(); pOut = new BcpgOutputStream(bOut); pgpPriv2.Encode(pOut); byte[] result = bOut.ToArray(); if (!Arrays.AreEqual(result, testPrivKeyV3)) { Fail("private key V3 rewrite failed"); } } #endif // // Read the private key // PgpSecretKeyRing pgpPriv = new PgpSecretKeyRing(testPrivKey); PgpPrivateKey pgpPrivKey = pgpPriv.GetSecretKey().ExtractPrivateKey(pass); // // write a private key // bOut = new UncloseableMemoryStream(); pOut = new BcpgOutputStream(bOut); pgpPriv.Encode(pOut); if (!Arrays.AreEqual(bOut.ToArray(), testPrivKey)) { Fail("private key rewrite failed"); } // // test encryption // IBufferedCipher c = CipherUtilities.GetCipher("RSA"); // c.Init(Cipher.ENCRYPT_MODE, pubKey); c.Init(true, pubKey); byte[] inBytes = Encoding.ASCII.GetBytes("hello world"); byte[] outBytes = c.DoFinal(inBytes); // c.Init(Cipher.DECRYPT_MODE, pgpPrivKey.GetKey()); c.Init(false, pgpPrivKey.Key); outBytes = c.DoFinal(outBytes); if (!Arrays.AreEqual(inBytes, outBytes)) { Fail("decryption failed."); } // // test signature message // PgpObjectFactory pgpFact = new PgpObjectFactory(sig1); PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); PgpOnePassSignature ops = p1[0]; PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject(); Stream dIn = p2.GetInputStream(); ops.InitVerify(pgpPub.GetPublicKey(ops.KeyId)); int ch; while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed signature check"); } // // encrypted message - read subkey // pgpPriv = new PgpSecretKeyRing(subKey); // // encrypted message // byte[] text = Encoding.ASCII.GetBytes("hello world!\n"); PgpObjectFactory pgpF = new PgpObjectFactory(enc1); PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0]; pgpPrivKey = pgpPriv.GetSecretKey(encP.KeyId).ExtractPrivateKey(pass); Stream clear = encP.GetDataStream(pgpPrivKey); pgpFact = new PgpObjectFactory(clear); c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); PgpLiteralData ld = (PgpLiteralData)pgpFact.NextPgpObject(); if (!ld.FileName.Equals("test.txt")) { throw new Exception("wrong filename in packet"); } Stream inLd = ld.GetDataStream(); byte[] bytes = Streams.ReadAll(inLd); if (!Arrays.AreEqual(bytes, text)) { Fail("wrong plain text in decrypted packet"); } // // encrypt - short message // byte[] shortText = { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o' }; MemoryStream cbOut = new UncloseableMemoryStream(); PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, new SecureRandom()); PgpPublicKey puK = pgpPriv.GetSecretKey(encP.KeyId).PublicKey; cPk.AddMethod(puK); Stream cOut = cPk.Open(new UncloseableStream(cbOut), shortText.Length); cOut.Write(shortText, 0, shortText.Length); cOut.Close(); pgpF = new PgpObjectFactory(cbOut.ToArray()); encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); encP = (PgpPublicKeyEncryptedData)encList[0]; pgpPrivKey = pgpPriv.GetSecretKey(encP.KeyId).ExtractPrivateKey(pass); if (encP.GetSymmetricAlgorithm(pgpPrivKey) != SymmetricKeyAlgorithmTag.Cast5) { Fail("symmetric algorithm mismatch"); } clear = encP.GetDataStream(pgpPrivKey); outBytes = Streams.ReadAll(clear); if (!Arrays.AreEqual(outBytes, shortText)) { Fail("wrong plain text in generated short text packet"); } // // encrypt // cbOut = new UncloseableMemoryStream(); cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, new SecureRandom()); puK = pgpPriv.GetSecretKey(encP.KeyId).PublicKey; cPk.AddMethod(puK); cOut = cPk.Open(new UncloseableStream(cbOut), text.Length); cOut.Write(text, 0, text.Length); cOut.Close(); pgpF = new PgpObjectFactory(cbOut.ToArray()); encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); encP = (PgpPublicKeyEncryptedData)encList[0]; pgpPrivKey = pgpPriv.GetSecretKey(encP.KeyId).ExtractPrivateKey(pass); clear = encP.GetDataStream(pgpPrivKey); outBytes = Streams.ReadAll(clear); if (!Arrays.AreEqual(outBytes, text)) { Fail("wrong plain text in generated packet"); } // // read public key with sub key. // pgpF = new PgpObjectFactory(subPubKey); object o; while ((o = pgpFact.NextPgpObject()) != null) { // TODO Should something be tested here? // Console.WriteLine(o); } // // key pair generation - CAST5 encryption // char[] passPhrase = "hello".ToCharArray(); IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("RSA"); RsaKeyGenerationParameters genParam = new RsaKeyGenerationParameters( BigInteger.ValueOf(0x10001), new SecureRandom(), 1024, 25); kpg.Init(genParam); AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair(); PgpSecretKey secretKey = new PgpSecretKey( PgpSignature.DefaultCertification, PublicKeyAlgorithmTag.RsaGeneral, kp.Public, kp.Private, DateTime.UtcNow, "fred", SymmetricKeyAlgorithmTag.Cast5, passPhrase, null, null, new SecureRandom() ); PgpPublicKey key = secretKey.PublicKey; enumerator = key.GetUserIds().GetEnumerator(); enumerator.MoveNext(); uid = (string) enumerator.Current; enumerator = key.GetSignaturesForId(uid).GetEnumerator(); enumerator.MoveNext(); sig = (PgpSignature) enumerator.Current; sig.InitVerify(key); if (!sig.VerifyCertification(uid, key)) { Fail("failed to verify certification"); } pgpPrivKey = secretKey.ExtractPrivateKey(passPhrase); key = PgpPublicKey.RemoveCertification(key, uid, sig); if (key == null) { Fail("failed certification removal"); } byte[] keyEnc = key.GetEncoded(); key = PgpPublicKey.AddCertification(key, uid, sig); keyEnc = key.GetEncoded(); PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.KeyRevocation, secretKey.ExtractPrivateKey(passPhrase)); sig = sGen.GenerateCertification(key); key = PgpPublicKey.AddCertification(key, sig); keyEnc = key.GetEncoded(); PgpPublicKeyRing tmpRing = new PgpPublicKeyRing(keyEnc); key = tmpRing.GetPublicKey(); IEnumerator sgEnum = key.GetSignaturesOfType(PgpSignature.KeyRevocation).GetEnumerator(); sgEnum.MoveNext(); sig = (PgpSignature) sgEnum.Current; sig.InitVerify(key); if (!sig.VerifyCertification(key)) { Fail("failed to verify revocation certification"); } // // use of PgpKeyPair // PgpKeyPair pgpKp = new PgpKeyPair(PublicKeyAlgorithmTag.RsaGeneral, kp.Public, kp.Private, DateTime.UtcNow); PgpPublicKey k1 = pgpKp.PublicKey; PgpPrivateKey k2 = pgpKp.PrivateKey; k1.GetEncoded(); MixedTest(k2, k1); // // key pair generation - AES_256 encryption. // kp = kpg.GenerateKeyPair(); secretKey = new PgpSecretKey(PgpSignature.DefaultCertification, PublicKeyAlgorithmTag.RsaGeneral, kp.Public, kp.Private, DateTime.UtcNow, "fred", SymmetricKeyAlgorithmTag.Aes256, passPhrase, null, null, new SecureRandom()); secretKey.ExtractPrivateKey(passPhrase); secretKey.Encode(new UncloseableMemoryStream()); // // secret key password changing. // const string newPass = "newPass"; secretKey = PgpSecretKey.CopyWithNewPassword(secretKey, passPhrase, newPass.ToCharArray(), secretKey.KeyEncryptionAlgorithm, new SecureRandom()); secretKey.ExtractPrivateKey(newPass.ToCharArray()); secretKey.Encode(new UncloseableMemoryStream()); key = secretKey.PublicKey; key.Encode(new UncloseableMemoryStream()); enumerator = key.GetUserIds().GetEnumerator(); enumerator.MoveNext(); uid = (string) enumerator.Current; enumerator = key.GetSignaturesForId(uid).GetEnumerator(); enumerator.MoveNext(); sig = (PgpSignature) enumerator.Current; sig.InitVerify(key); if (!sig.VerifyCertification(uid, key)) { Fail("failed to verify certification"); } pgpPrivKey = secretKey.ExtractPrivateKey(newPass.ToCharArray()); // // signature generation // const string data = "hello world!"; byte[] dataBytes = Encoding.ASCII.GetBytes(data); bOut = new UncloseableMemoryStream(); MemoryStream testIn = new MemoryStream(dataBytes, false); sGen = new PgpSignatureGenerator( PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey); PgpCompressedDataGenerator cGen = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); BcpgOutputStream bcOut = new BcpgOutputStream(cGen.Open(new UncloseableStream(bOut))); sGen.GenerateOnePassVersion(false).Encode(bcOut); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); DateTime testDateTime = new DateTime(1973, 7, 27); Stream lOut = lGen.Open(new UncloseableStream(bcOut), PgpLiteralData.Binary, "_CONSOLE", dataBytes.Length, testDateTime); // TODO Need a stream object to automatically call Update? // (via ISigner implementation of PgpSignatureGenerator) while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte)ch); sGen.Update((byte)ch); } lOut.Close(); sGen.Generate().Encode(bcOut); bcOut.Close(); // // verify generated signature // pgpFact = new PgpObjectFactory(bOut.ToArray()); c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); ops = p1[0]; p2 = (PgpLiteralData)pgpFact.NextPgpObject(); if (!p2.ModificationTime.Equals(testDateTime)) { Fail("Modification time not preserved"); } dIn = p2.GetInputStream(); ops.InitVerify(secretKey.PublicKey); // TODO Need a stream object to automatically call Update? // (via ISigner implementation of PgpSignatureGenerator) while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } p3 = (PgpSignatureList)pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed generated signature check"); } // // signature generation - version 3 // bOut = new UncloseableMemoryStream(); testIn = new MemoryStream(dataBytes); PgpV3SignatureGenerator sGenV3 = new PgpV3SignatureGenerator( PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey); cGen = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip); bcOut = new BcpgOutputStream(cGen.Open(new UncloseableStream(bOut))); sGen.GenerateOnePassVersion(false).Encode(bcOut); lGen = new PgpLiteralDataGenerator(); lOut = lGen.Open( new UncloseableStream(bcOut), PgpLiteralData.Binary, "_CONSOLE", dataBytes.Length, testDateTime); // TODO Need a stream object to automatically call Update? // (via ISigner implementation of PgpSignatureGenerator) while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte) ch); sGen.Update((byte)ch); } lOut.Close(); sGen.Generate().Encode(bcOut); bcOut.Close(); // // verify generated signature // pgpFact = new PgpObjectFactory(bOut.ToArray()); c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); ops = p1[0]; p2 = (PgpLiteralData)pgpFact.NextPgpObject(); if (!p2.ModificationTime.Equals(testDateTime)) { Fail("Modification time not preserved"); } dIn = p2.GetInputStream(); ops.InitVerify(secretKey.PublicKey); // TODO Need a stream object to automatically call Update? // (via ISigner implementation of PgpSignatureGenerator) while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } p3 = (PgpSignatureList)pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed v3 generated signature check"); } // // extract PGP 8 private key // pgpPriv = new PgpSecretKeyRing(pgp8Key); secretKey = pgpPriv.GetSecretKey(); pgpPrivKey = secretKey.ExtractPrivateKey(pgp8Pass); // // other sig tests // PerformTestSig(HashAlgorithmTag.Sha256, secretKey.PublicKey, pgpPrivKey); PerformTestSig(HashAlgorithmTag.Sha384, secretKey.PublicKey, pgpPrivKey); PerformTestSig(HashAlgorithmTag.Sha512, secretKey.PublicKey, pgpPrivKey); FingerPrintTest(); ExistingEmbeddedJpegTest(); EmbeddedJpegTest(); } private void PerformTestSig( HashAlgorithmTag hashAlgorithm, PgpPublicKey pubKey, PgpPrivateKey privKey) { const string data = "hello world!"; byte[] dataBytes = Encoding.ASCII.GetBytes(data); MemoryStream bOut = new UncloseableMemoryStream(); MemoryStream testIn = new MemoryStream(dataBytes, false); PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.RsaGeneral, hashAlgorithm); sGen.InitSign(PgpSignature.BinaryDocument, privKey); PgpCompressedDataGenerator cGen = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip); BcpgOutputStream bcOut = new BcpgOutputStream(cGen.Open(new UncloseableStream(bOut))); sGen.GenerateOnePassVersion(false).Encode(bcOut); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); DateTime testDateTime = new DateTime(1973, 7, 27); Stream lOut = lGen.Open( new UncloseableStream(bcOut), PgpLiteralData.Binary, "_CONSOLE", dataBytes.Length, testDateTime); // TODO Need a stream object to automatically call Update? // (via ISigner implementation of PgpSignatureGenerator) int ch; while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte)ch); sGen.Update((byte)ch); } lOut.Close(); sGen.Generate().Encode(bcOut); bcOut.Close(); // // verify generated signature // PgpObjectFactory pgpFact = new PgpObjectFactory(bOut.ToArray()); PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); PgpOnePassSignature ops = p1[0]; PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject(); if (!p2.ModificationTime.Equals(testDateTime)) { Fail("Modification time not preserved"); } Stream dIn = p2.GetInputStream(); ops.InitVerify(pubKey); // TODO Need a stream object to automatically call Update? // (via ISigner implementation of PgpSignatureGenerator) while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed generated signature check - " + hashAlgorithm); } } private class UncloseableMemoryStream : MemoryStream { public override void Close() { throw new Exception("Close() called on underlying stream"); } } public override string Name { get { return "PGPRSATest"; } } public static void Main( string[] args) { RunTest(new PgpRsaTest()); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: booking/groups/group_booking_ext.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 HOLMS.Types.Booking.Groups { /// <summary>Holder for reflection information generated from booking/groups/group_booking_ext.proto</summary> public static partial class GroupBookingExtReflection { #region Descriptor /// <summary>File descriptor for booking/groups/group_booking_ext.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static GroupBookingExtReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiZib29raW5nL2dyb3Vwcy9ncm91cF9ib29raW5nX2V4dC5wcm90bxIaaG9s", "bXMudHlwZXMuYm9va2luZy5ncm91cHMaImJvb2tpbmcvZ3JvdXBzL2dyb3Vw", "X2Jvb2tpbmcucHJvdG8aNWJvb2tpbmcvZ3JvdXBzL2dyb3VwX2Jvb2tpbmdf", "cm9vbV90eXBlX3F1YW50aXR5LnByb3RvGhtjcm0vZ3JvdXBzL2dyb3VwX3R5", "cGUucHJvdG8aMnRlbmFuY3lfY29uZmlnL2luZGljYXRvcnMvcHJvcGVydHlf", "aW5kaWNhdG9yLnByb3RvIusCCg9Hcm91cEJvb2tpbmdFeHQSOQoHYm9va2lu", "ZxgBIAEoCzIoLmhvbG1zLnR5cGVzLmJvb2tpbmcuZ3JvdXBzLkdyb3VwQm9v", "a2luZxISCgpncm91cF9uYW1lGAIgASgJEhQKDGdyb3VwX251bWJlchgDIAEo", "CRIaChJncm91cF9jb250YWN0X25hbWUYBCABKAkSNQoKZ3JvdXBfdHlwZRgF", "IAEoDjIhLmhvbG1zLnR5cGVzLmNybS5ncm91cHMuR3JvdXBUeXBlElIKEGJv", "b2tpbmdfcHJvcGVydHkYBiABKAsyOC5ob2xtcy50eXBlcy50ZW5hbmN5X2Nv", "bmZpZy5pbmRpY2F0b3JzLlByb3BlcnR5SW5kaWNhdG9yEkwKCnF1YW50aXRp", "ZXMYByADKAsyOC5ob2xtcy50eXBlcy5ib29raW5nLmdyb3Vwcy5Hcm91cEJv", "b2tpbmdSb29tVHlwZVF1YW50aXR5Qi1aDmJvb2tpbmcvZ3JvdXBzqgIaSE9M", "TVMuVHlwZXMuQm9va2luZy5Hcm91cHNiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.Booking.Groups.GroupBookingReflection.Descriptor, global::HOLMS.Types.Booking.Groups.GroupBookingRoomTypeQuantityReflection.Descriptor, global::HOLMS.Types.CRM.Groups.GroupTypeReflection.Descriptor, global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicatorReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.Groups.GroupBookingExt), global::HOLMS.Types.Booking.Groups.GroupBookingExt.Parser, new[]{ "Booking", "GroupName", "GroupNumber", "GroupContactName", "GroupType", "BookingProperty", "Quantities" }, null, null, null) })); } #endregion } #region Messages public sealed partial class GroupBookingExt : pb::IMessage<GroupBookingExt> { private static readonly pb::MessageParser<GroupBookingExt> _parser = new pb::MessageParser<GroupBookingExt>(() => new GroupBookingExt()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<GroupBookingExt> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Booking.Groups.GroupBookingExtReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GroupBookingExt() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GroupBookingExt(GroupBookingExt other) : this() { Booking = other.booking_ != null ? other.Booking.Clone() : null; groupName_ = other.groupName_; groupNumber_ = other.groupNumber_; groupContactName_ = other.groupContactName_; groupType_ = other.groupType_; BookingProperty = other.bookingProperty_ != null ? other.BookingProperty.Clone() : null; quantities_ = other.quantities_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GroupBookingExt Clone() { return new GroupBookingExt(this); } /// <summary>Field number for the "booking" field.</summary> public const int BookingFieldNumber = 1; private global::HOLMS.Types.Booking.Groups.GroupBooking booking_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Booking.Groups.GroupBooking Booking { get { return booking_; } set { booking_ = value; } } /// <summary>Field number for the "group_name" field.</summary> public const int GroupNameFieldNumber = 2; private string groupName_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string GroupName { get { return groupName_; } set { groupName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "group_number" field.</summary> public const int GroupNumberFieldNumber = 3; private string groupNumber_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string GroupNumber { get { return groupNumber_; } set { groupNumber_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "group_contact_name" field.</summary> public const int GroupContactNameFieldNumber = 4; private string groupContactName_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string GroupContactName { get { return groupContactName_; } set { groupContactName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "group_type" field.</summary> public const int GroupTypeFieldNumber = 5; private global::HOLMS.Types.CRM.Groups.GroupType groupType_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.CRM.Groups.GroupType GroupType { get { return groupType_; } set { groupType_ = value; } } /// <summary>Field number for the "booking_property" field.</summary> public const int BookingPropertyFieldNumber = 6; private global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator bookingProperty_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator BookingProperty { get { return bookingProperty_; } set { bookingProperty_ = value; } } /// <summary>Field number for the "quantities" field.</summary> public const int QuantitiesFieldNumber = 7; private static readonly pb::FieldCodec<global::HOLMS.Types.Booking.Groups.GroupBookingRoomTypeQuantity> _repeated_quantities_codec = pb::FieldCodec.ForMessage(58, global::HOLMS.Types.Booking.Groups.GroupBookingRoomTypeQuantity.Parser); private readonly pbc::RepeatedField<global::HOLMS.Types.Booking.Groups.GroupBookingRoomTypeQuantity> quantities_ = new pbc::RepeatedField<global::HOLMS.Types.Booking.Groups.GroupBookingRoomTypeQuantity>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::HOLMS.Types.Booking.Groups.GroupBookingRoomTypeQuantity> Quantities { get { return quantities_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as GroupBookingExt); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(GroupBookingExt other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Booking, other.Booking)) return false; if (GroupName != other.GroupName) return false; if (GroupNumber != other.GroupNumber) return false; if (GroupContactName != other.GroupContactName) return false; if (GroupType != other.GroupType) return false; if (!object.Equals(BookingProperty, other.BookingProperty)) return false; if(!quantities_.Equals(other.quantities_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (booking_ != null) hash ^= Booking.GetHashCode(); if (GroupName.Length != 0) hash ^= GroupName.GetHashCode(); if (GroupNumber.Length != 0) hash ^= GroupNumber.GetHashCode(); if (GroupContactName.Length != 0) hash ^= GroupContactName.GetHashCode(); if (GroupType != 0) hash ^= GroupType.GetHashCode(); if (bookingProperty_ != null) hash ^= BookingProperty.GetHashCode(); hash ^= quantities_.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 (booking_ != null) { output.WriteRawTag(10); output.WriteMessage(Booking); } if (GroupName.Length != 0) { output.WriteRawTag(18); output.WriteString(GroupName); } if (GroupNumber.Length != 0) { output.WriteRawTag(26); output.WriteString(GroupNumber); } if (GroupContactName.Length != 0) { output.WriteRawTag(34); output.WriteString(GroupContactName); } if (GroupType != 0) { output.WriteRawTag(40); output.WriteEnum((int) GroupType); } if (bookingProperty_ != null) { output.WriteRawTag(50); output.WriteMessage(BookingProperty); } quantities_.WriteTo(output, _repeated_quantities_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (booking_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Booking); } if (GroupName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(GroupName); } if (GroupNumber.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(GroupNumber); } if (GroupContactName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(GroupContactName); } if (GroupType != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) GroupType); } if (bookingProperty_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(BookingProperty); } size += quantities_.CalculateSize(_repeated_quantities_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(GroupBookingExt other) { if (other == null) { return; } if (other.booking_ != null) { if (booking_ == null) { booking_ = new global::HOLMS.Types.Booking.Groups.GroupBooking(); } Booking.MergeFrom(other.Booking); } if (other.GroupName.Length != 0) { GroupName = other.GroupName; } if (other.GroupNumber.Length != 0) { GroupNumber = other.GroupNumber; } if (other.GroupContactName.Length != 0) { GroupContactName = other.GroupContactName; } if (other.GroupType != 0) { GroupType = other.GroupType; } if (other.bookingProperty_ != null) { if (bookingProperty_ == null) { bookingProperty_ = new global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator(); } BookingProperty.MergeFrom(other.BookingProperty); } quantities_.Add(other.quantities_); } [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: { if (booking_ == null) { booking_ = new global::HOLMS.Types.Booking.Groups.GroupBooking(); } input.ReadMessage(booking_); break; } case 18: { GroupName = input.ReadString(); break; } case 26: { GroupNumber = input.ReadString(); break; } case 34: { GroupContactName = input.ReadString(); break; } case 40: { groupType_ = (global::HOLMS.Types.CRM.Groups.GroupType) input.ReadEnum(); break; } case 50: { if (bookingProperty_ == null) { bookingProperty_ = new global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator(); } input.ReadMessage(bookingProperty_); break; } case 58: { quantities_.AddEntriesFrom(input, _repeated_quantities_codec); break; } } } } } #endregion } #endregion Designer generated code
//--------------------------------------------------------------------- // <copyright file="EdmConstants.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- namespace System.Data.Metadata.Edm { internal static class EdmConstants { // Namespace for all the system types internal const string EdmNamespace = "Edm"; internal const string ClrPrimitiveTypeNamespace = "System"; internal const string TransientNamespace = "Transient"; // max number of primitive types internal const int NumPrimitiveTypes = (int)System.Data.Metadata.Edm.PrimitiveTypeKind.DateTimeOffset + 1; // max number of primitive types internal const int NumBuiltInTypes = (int)BuiltInTypeKind.TypeUsage + 1; // MaxLength for the string types: Name, Namespace, Version internal const int MaxLength = 256; // Name of the built in types internal const string AssociationEnd = "AssociationEnd"; internal const string AssociationSetType = "AssocationSetType"; internal const string AssociationSetEndType = "AssociationSetEndType"; internal const string AssociationType = "AssociationType"; internal const string BaseEntitySetType = "BaseEntitySetType"; internal const string CollectionType = "CollectionType"; internal const string ComplexType = "ComplexType"; internal const string DeleteAction = "DeleteAction"; internal const string DeleteBehavior = "DeleteBehavior"; internal const string Documentation = "Documentation"; internal const string EdmType = "EdmType"; internal const string ElementType = "ElementType"; internal const string EntityContainerType = "EntityContainerType"; internal const string EntitySetType = "EntitySetType"; internal const string EntityType = "EntityType"; internal const string EnumerationMember = "EnumMember"; internal const string EnumerationType = "EnumType"; internal const string Facet = "Facet"; internal const string Function = "EdmFunction"; internal const string FunctionParameter = "FunctionParameter"; internal const string GlobalItem = "GlobalItem"; internal const string ItemAttribute = "MetadataProperty"; internal const string ItemType = "ItemType"; internal const string Member = "EdmMember"; internal const string NavigationProperty = "NavigationProperty"; internal const string OperationBehavior = "OperationBehavior"; internal const string OperationBehaviors = "OperationBehaviors"; internal const string ParameterMode = "ParameterMode"; internal const string PrimitiveType = "PrimitiveType"; internal const string PrimitiveTypeKind = "PrimitiveTypeKind"; internal const string Property = "EdmProperty"; internal const string ProviderManifest = "ProviderManifest"; internal const string ReferentialConstraint = "ReferentialConstraint"; internal const string RefType = "RefType"; internal const string RelationshipEnd = "RelationshipEnd"; internal const string RelationshipMultiplicity = "RelationshipMultiplicity"; internal const string RelationshipSet = "RelationshipSet"; internal const string RelationshipType = "RelationshipType"; internal const string ReturnParameter = "ReturnParameter"; internal const string Role = "Role"; internal const string RowType = "RowType"; internal const string SimpleType = "SimpleType"; internal const string StructuralType = "StructuralType"; internal const string TypeUsage = "TypeUsage"; //Enum value of date time kind internal const string Utc = "Utc"; internal const string Unspecified = "Unspecified"; internal const string Local = "Local"; //Enum value of multiplicity kind internal const string One = "One"; internal const string ZeroToOne = "ZeroToOne"; internal const string Many = "Many"; //Enum value of Parameter Mode internal const string In = "In"; internal const string Out = "Out"; internal const string InOut = "InOut"; //Enum value of DeleteAction Mode internal const string None = "None"; internal const string Cascade = "Cascade"; internal const string Restrict = "Restrict"; //Enum Value of CollectionKind internal const string NoneCollectionKind = "None"; internal const string ListCollectionKind = "List"; internal const string BagCollectionKind = "Bag"; //Enum Value of MaxLength (max length can be a single enum value, or a positive integer) internal const string MaxMaxLength = "Max"; // Members of the built in types internal const string AssociationSetEnds = "AssociationSetEnds"; internal const string Child = "Child"; internal const string DefaultValue = "DefaultValue"; internal const string Ends = "Ends"; internal const string EntitySet = "EntitySet"; internal const string AssociationSet = "AssociationSet"; internal const string EntitySets = "EntitySets"; internal const string Facets = "Facets"; internal const string FromProperties = "FromProperties"; internal const string FromRole = "FromRole"; internal const string IsParent = "IsParent"; internal const string KeyMembers = "KeyMembers"; internal const string Members = "Members"; internal const string Mode = "Mode"; internal const string Nullable = "Nullable"; internal const string Parameters = "Parameters"; internal const string Parent = "Parent"; internal const string Properties = "Properties"; internal const string ToProperties = "ToProperties"; internal const string ToRole = "ToRole"; internal const string ReferentialConstraints = "ReferentialConstraints"; internal const string RelationshipTypeName = "RelationshipTypeName"; internal const string ReturnType = "ReturnType"; internal const string ToEndMemberName = "ToEndMemberName"; internal const string CollectionKind = "CollectionKind"; // Name of the primitive types internal const string Binary = "Binary"; internal const string Boolean = "Boolean"; internal const string Byte = "Byte"; internal const string DateTime = "DateTime"; internal const string Decimal = "Decimal"; internal const string Double = "Double"; internal const string Guid = "Guid"; internal const string Single = "Single"; internal const string SByte = "SByte"; internal const string Int16 = "Int16"; internal const string Int32 = "Int32"; internal const string Int64 = "Int64"; internal const string Money = "Money"; internal const string Null = "Null"; internal const string String = "String"; internal const string DateTimeOffset = "DateTimeOffset"; internal const string Time = "Time"; internal const string UInt16 = "UInt16"; internal const string UInt32 = "UInt32"; internal const string UInt64 = "UInt64"; internal const string Xml = "Xml"; // Name of the system defined attributes on edm type internal const string Name = "Name"; internal const string Namespace = "Namespace"; internal const string Abstract = "Abstract"; internal const string BaseType = "BaseType"; internal const string Sealed = "Sealed"; internal const string ItemAttributes = "MetadataProperties"; internal const string Type = "Type"; // Name of SSDL specifc attributes for SQL Gen internal const string Schema = "Schema"; internal const string Table = "Table"; // Name of the additional system defined attributes on item attribute internal const string FacetType = "FacetType"; internal const string Value = "Value"; // Name of the additional system defined attributes on enum types internal const string EnumMembers = "EnumMembers"; // // Provider Manifest EdmFunction Attributes // internal const string BuiltInAttribute = "BuiltInAttribute"; internal const string StoreFunctionNamespace = "StoreFunctionNamespace"; internal const string ParameterTypeSemanticsAttribute = "ParameterTypeSemanticsAttribute"; internal const string ParameterTypeSemantics = "ParameterTypeSemantics"; internal const string NiladicFunctionAttribute = "NiladicFunctionAttribute"; internal const string IsComposableFunctionAttribute = "IsComposable"; internal const string CommandTextFunctionAttribyte = "CommandText"; internal const string StoreFunctionNameAttribute = "StoreFunctionNameAttribute"; /// <summary> /// Used to denote application home directory in a Web/ASP.NET context /// </summary> internal const string WebHomeSymbol = "~"; // Name of Properties belonging to EDM's Documentation construct internal const string Summary = "Summary"; internal const string LongDescription = "LongDescription"; internal static readonly Unbounded UnboundedValue = Unbounded.Instance; internal class Unbounded { static readonly Unbounded _instance = new Unbounded(); private Unbounded() { } static internal Unbounded Instance { get { return _instance; } } public override string ToString() { return MaxMaxLength; } } } }
//------------------------------------------------------------------------------ // <copyright file="LinkButton.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls { using System; using System.ComponentModel; using System.Drawing.Design; using System.Web; using System.Web.UI; using System.Web.Util; /// <devdoc> /// <para>Interacts with the parser to build a <see cref='System.Web.UI.WebControls.LinkButton'/> control.</para> /// </devdoc> public class LinkButtonControlBuilder : ControlBuilder { /// <internalonly/> /// <devdoc> /// <para>Specifies whether white space literals are allowed.</para> /// </devdoc> public override bool AllowWhitespaceLiterals() { return false; } } /// <devdoc> /// <para>Constructs a link button and defines its properties.</para> /// </devdoc> [ ControlBuilderAttribute(typeof(LinkButtonControlBuilder)), DataBindingHandler("System.Web.UI.Design.TextDataBindingHandler, " + AssemblyRef.SystemDesign), DefaultEvent("Click"), DefaultProperty("Text"), ToolboxData("<{0}:LinkButton runat=\"server\">LinkButton</{0}:LinkButton>"), Designer("System.Web.UI.Design.WebControls.LinkButtonDesigner, " + AssemblyRef.SystemDesign), ParseChildren(false), SupportsEventValidation ] public class LinkButton : WebControl, IButtonControl, IPostBackEventHandler { private bool _textSetByAddParsedSubObject = false; private static readonly object EventClick = new object(); private static readonly object EventCommand = new object(); /// <devdoc> /// <para>Initializes a new instance of the <see cref='System.Web.UI.WebControls.LinkButton'/> class.</para> /// </devdoc> public LinkButton() : base(HtmlTextWriterTag.A) { } /// <devdoc> /// <para>Specifies the command name that is propagated in the /// <see cref='System.Web.UI.WebControls.LinkButton.Command'/>event along with the associated <see cref='System.Web.UI.WebControls.LinkButton.CommandArgument'/> /// property.</para> /// </devdoc> [ DefaultValue(""), Themeable(false), WebCategory("Behavior"), WebSysDescription(SR.WebControl_CommandName) ] public string CommandName { get { string s = (string)ViewState["CommandName"]; return((s == null) ? String.Empty : s); } set { ViewState["CommandName"] = value; } } /// <devdoc> /// <para>Specifies the command argument that is propagated in the /// <see langword='Command '/>event along with the associated <see cref='System.Web.UI.WebControls.LinkButton.CommandName'/> /// property.</para> /// </devdoc> [ Bindable(true), DefaultValue(""), Themeable(false), WebCategory("Behavior"), WebSysDescription(SR.WebControl_CommandArgument) ] public string CommandArgument { get { string s = (string)ViewState["CommandArgument"]; return((s == null) ? String.Empty : s); } set { ViewState["CommandArgument"] = value; } } /// <devdoc> /// <para>Gets or sets whether pressing the button causes page validation to fire. This defaults to True so that when /// using validation controls, the validation state of all controls are updated when the button is clicked, both /// on the client and the server. Setting this to False is useful when defining a cancel or reset button on a page /// that has validators.</para> /// </devdoc> [ DefaultValue(true), Themeable(false), WebCategory("Behavior"), WebSysDescription(SR.Button_CausesValidation) ] public virtual bool CausesValidation { get { object b = ViewState["CausesValidation"]; return((b == null) ? true : (bool)b); } set { ViewState["CausesValidation"] = value; } } /// <devdoc> /// The script that is executed on a client-side click. /// </devdoc> [ DefaultValue(""), Themeable(false), WebCategory("Behavior"), WebSysDescription(SR.Button_OnClientClick) ] public virtual string OnClientClick { get { string s = (string)ViewState["OnClientClick"]; if (s == null) { return String.Empty; } return s; } set { ViewState["OnClientClick"] = value; } } public override bool SupportsDisabledAttribute { get { return RenderingCompatibility < VersionUtil.Framework40; } } internal override bool RequiresLegacyRendering { get { return true; } } /// <devdoc> /// <para>Gets or sets the text display for the link button.</para> /// </devdoc> [ Localizable(true), Bindable(true), WebCategory("Appearance"), DefaultValue(""), WebSysDescription(SR.LinkButton_Text), PersistenceMode(PersistenceMode.InnerDefaultProperty) ] public virtual string Text { get { object o = ViewState["Text"]; return((o == null) ? String.Empty : (string)o); } set { if (HasControls()) { Controls.Clear(); } ViewState["Text"] = value; } } [ DefaultValue(""), Editor("System.Web.UI.Design.UrlEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), Themeable(false), UrlProperty("*.aspx"), WebCategory("Behavior"), WebSysDescription(SR.Button_PostBackUrl) ] public virtual string PostBackUrl { get { string s = (string)ViewState["PostBackUrl"]; return s == null? String.Empty : s; } set { ViewState["PostBackUrl"] = value; } } [ WebCategory("Behavior"), Themeable(false), DefaultValue(""), WebSysDescription(SR.PostBackControl_ValidationGroup) ] public virtual string ValidationGroup { get { string s = (string)ViewState["ValidationGroup"]; return((s == null) ? String.Empty : s); } set { ViewState["ValidationGroup"] = value; } } /// <devdoc> /// <para>Occurs when the link button is clicked.</para> /// </devdoc> [ WebCategory("Action"), WebSysDescription(SR.LinkButton_OnClick) ] public event EventHandler Click { add { Events.AddHandler(EventClick, value); } remove { Events.RemoveHandler(EventClick, value); } } /// <devdoc> /// <para>Occurs when any item is clicked within the <see cref='System.Web.UI.WebControls.LinkButton'/> control tree.</para> /// </devdoc> [ WebCategory("Action"), WebSysDescription(SR.Button_OnCommand) ] public event CommandEventHandler Command { add { Events.AddHandler(EventCommand, value); } remove { Events.RemoveHandler(EventCommand, value); } } /// <internalonly/> /// <devdoc> /// Render the attributes on the begin tag. /// </devdoc> protected override void AddAttributesToRender(HtmlTextWriter writer) { // Make sure we are in a form tag with runat=server. if (Page != null) { Page.VerifyRenderingInServerForm(this); } // Need to merge the onclick attribute with the OnClientClick string onClick = Util.EnsureEndWithSemiColon(OnClientClick); if (HasAttributes) { string userOnClick = Attributes["onclick"]; if (userOnClick != null) { // We don't use Util.MergeScript because OnClientClick or // onclick attribute are set by page developer directly. We // should preserve the value without adding javascript prefix. onClick += Util.EnsureEndWithSemiColon(userOnClick); Attributes.Remove("onclick"); } } if (onClick.Length > 0) { writer.AddAttribute(HtmlTextWriterAttribute.Onclick, onClick); } bool effectiveEnabled = IsEnabled; if (Enabled && !effectiveEnabled && SupportsDisabledAttribute) { // We need to do the cascade effect on the server, because the browser // only renders as disabled, but doesn't disable the functionality. writer.AddAttribute(HtmlTextWriterAttribute.Disabled, "disabled"); } base.AddAttributesToRender(writer); if (effectiveEnabled && Page != null) { // PostBackOptions options = GetPostBackOptions(); string postBackEventReference = null; if (options != null) { postBackEventReference = Page.ClientScript.GetPostBackEventReference(options, true); } // If the postBackEventReference is empty, use a javascript no-op instead, since // <a href="" /> is a link to the root of the current directory. if (String.IsNullOrEmpty(postBackEventReference)) { postBackEventReference = "javascript:void(0)"; } writer.AddAttribute(HtmlTextWriterAttribute.Href, postBackEventReference); } } /// <internalonly/> /// <devdoc> /// </devdoc> protected override void AddParsedSubObject(object obj) { if (HasControls()) { base.AddParsedSubObject(obj); } else { if (obj is LiteralControl) { if (_textSetByAddParsedSubObject) { Text += ((LiteralControl)obj).Text; } else { Text = ((LiteralControl)obj).Text; } _textSetByAddParsedSubObject = true; } else { string currentText = Text; if (currentText.Length != 0) { Text = String.Empty; base.AddParsedSubObject(new LiteralControl(currentText)); } base.AddParsedSubObject(obj); } } } // Returns the client post back options. protected virtual PostBackOptions GetPostBackOptions() { PostBackOptions options = new PostBackOptions(this, String.Empty); options.RequiresJavaScriptProtocol = true; if (!String.IsNullOrEmpty(PostBackUrl)) { // VSWhidbey 424614: Since the url is embedded as javascript in attribute, // we should match the same encoding as done on HyperLink.NavigateUrl value. options.ActionUrl = HttpUtility.UrlPathEncode(ResolveClientUrl(PostBackUrl)); // Also, there is a specific behavior in IE that when the script // is triggered in href attribute, the whole string will be // decoded once before the code is run. This doesn't happen to // onclick or other event attributes. So here we do an extra // encoding to compensate the weird behavior on IE. if (!DesignMode && Page != null && String.Equals(Page.Request.Browser.Browser, "IE", StringComparison.OrdinalIgnoreCase)) { options.ActionUrl = Util.QuoteJScriptString(options.ActionUrl, true); } } if (CausesValidation && Page.GetValidators(ValidationGroup).Count > 0) { options.PerformValidation = true; options.ValidationGroup = ValidationGroup; } return options; } /// <internalonly/> /// <devdoc> /// Load previously saved state. /// Overridden to synchronize Text property with LiteralContent. /// </devdoc> protected override void LoadViewState(object savedState) { if (savedState != null) { base.LoadViewState(savedState); string s = (string)ViewState["Text"]; // Dev10 703061 If Text is set, we want to clear out any child controls, but not dirty viewstate if (s != null && HasControls()) { Controls.Clear(); } } } /// <devdoc> /// <para>Raises the <see langword='Click '/> event.</para> /// </devdoc> protected virtual void OnClick(EventArgs e) { EventHandler onClickHandler = (EventHandler)Events[EventClick]; if (onClickHandler != null) onClickHandler(this,e); } /// <devdoc> /// <para>Raises the <see langword='Command'/> event.</para> /// </devdoc> protected virtual void OnCommand(CommandEventArgs e) { CommandEventHandler onCommandHandler = (CommandEventHandler)Events[EventCommand]; if (onCommandHandler != null) onCommandHandler(this,e); // Command events are bubbled up the control heirarchy RaiseBubbleEvent(this, e); } /// <internalonly/> /// <devdoc> /// <para>Raises a <see langword='Click '/>event upon postback /// to the server, and a <see langword='Command'/> event if the <see cref='System.Web.UI.WebControls.LinkButton.CommandName'/> /// is defined.</para> /// </devdoc> void IPostBackEventHandler.RaisePostBackEvent(string eventArgument) { RaisePostBackEvent(eventArgument); } /// <internalonly/> /// <devdoc> /// <para>Raises a <see langword='Click '/>event upon postback /// to the server, and a <see langword='Command'/> event if the <see cref='System.Web.UI.WebControls.LinkButton.CommandName'/> /// is defined.</para> /// </devdoc> protected virtual void RaisePostBackEvent(string eventArgument) { ValidateEvent(this.UniqueID, eventArgument); if (CausesValidation) { Page.Validate(ValidationGroup); } OnClick(EventArgs.Empty); OnCommand(new CommandEventArgs(CommandName, CommandArgument)); } /// <internalonly/> protected internal override void OnPreRender(EventArgs e) { base.OnPreRender(e); if (Page != null && Enabled) { Page.RegisterPostBackScript(); if ((CausesValidation && Page.GetValidators(ValidationGroup).Count > 0) || !String.IsNullOrEmpty(PostBackUrl)) { Page.RegisterWebFormsScript(); // VSWhidbey 489577 } } } /// <internalonly/> /// <devdoc> /// </devdoc> protected internal override void RenderContents(HtmlTextWriter writer) { if (HasRenderingData()) { base.RenderContents(writer); } else { writer.Write(Text); } } } }
using System; using Mono.Unix; using Gtk; using Tasque; namespace Gtk.Extras { public delegate void DateEditedHandler (CellRendererDate renderer, string path); public class CellRendererDate : Gtk.CellRenderer { DateTime date; bool editable; bool show_time; Window popup; Calendar cal; string path; // The following variable is set during StartEditing () // and this is kind of a hack, but it "works". The widget // that is passed-in to StartEditing() is the TreeView. // This is used to position the calendar popup. Gtk.TreeView tree; private const uint CURRENT_TIME = 0; #region Constructors /// <summary> /// <param name="parent">The parent window where this CellRendererDate /// will be used from. This is needed to access the Gdk.Screen so the /// Calendar will popup in the proper location.</param> /// </summary> public CellRendererDate() { date = DateTime.MinValue; editable = false; popup = null; show_time = true; } protected CellRendererDate (System.IntPtr ptr) : base (ptr) { } #endregion // Constructors #region Public Properties public DateTime Date { get { return date; } set { date = value; } } /// <summary> /// If the renderer is editable, a date picker widget will appear when /// the user attempts to edit the cell. /// </summary> public bool Editable { get { return editable; } set { editable = value; if (editable) Mode = CellRendererMode.Editable; else Mode = CellRendererMode.Inert; } } /// <summary> /// If true, both the date and time will be shown. If false, the time /// will be omitted. The default is true. /// </summary> public bool ShowTime { get { return show_time; } set { show_time = value; } } #endregion // Public Properties #region Public Methods public override void GetSize (Widget widget, ref Gdk.Rectangle cell_area, out int x_offset, out int y_offset, out int width, out int height) { Pango.Layout layout = GetLayout (widget); // FIXME: If this code is ever built into its own library, // the call to Tomboy will definitely have to change layout.SetText (Utilities.GetPrettyPrintDate (date, show_time)); CalculateSize (layout, out x_offset, out y_offset, out width, out height); } public override CellEditable StartEditing (Gdk.Event evnt, Widget widget, string path, Gdk.Rectangle background_area, Gdk.Rectangle cell_area, CellRendererState flags) { this.path = path; this.tree = widget as Gtk.TreeView; ShowCalendar(); return null; } #endregion #region Public Events public event DateEditedHandler Edited; #endregion // Public Events #region Private Methods protected override void Render (Gdk.Drawable drawable, Widget widget, Gdk.Rectangle background_area, Gdk.Rectangle cell_area, Gdk.Rectangle expose_area, CellRendererState flags) { Pango.Layout layout = GetLayout (widget); // FIXME: If this code is ever built into its own library, // the call to Tomboy will definitely have to change layout.SetText (Utilities.GetPrettyPrintDate (date, show_time)); int x, y, w, h; CalculateSize (layout, out x, out y, out w, out h); StateType state = RendererStateToWidgetState(flags); Gdk.GC gc; if (state.Equals(StateType.Selected)) { // Use the proper Gtk.StateType so text appears properly when selected gc = new Gdk.GC(drawable); gc.Copy(widget.Style.TextGC(state)); gc.RgbFgColor = widget.Style.Foreground(state); } else gc = widget.Style.TextGC(Gtk.StateType.Normal); drawable.DrawLayout ( gc, cell_area.X + (int)Xalign + (int)Xpad, cell_area.Y + ((cell_area.Height - h) / 2), layout); } Pango.Layout GetLayout (Gtk.Widget widget) { return widget.CreatePangoLayout (string.Empty); } void CalculateSize (Pango.Layout layout, out int x, out int y, out int width, out int height) { int w, h; layout.GetPixelSize (out w, out h); x = 0; y = 0; width = w + ((int) Xpad) * 2; height = h + ((int) Ypad) * 2; } private void ShowCalendar() { popup = new Window(WindowType.Popup); popup.Screen = tree.Screen; Frame frame = new Frame(); frame.Shadow = ShadowType.Out; frame.Show(); popup.Add(frame); VBox box = new VBox(false, 0); box.Show(); frame.Add(box); cal = new Calendar(); cal.DisplayOptions = CalendarDisplayOptions.ShowHeading | CalendarDisplayOptions.ShowDayNames | CalendarDisplayOptions.ShowWeekNumbers; cal.KeyPressEvent += OnCalendarKeyPressed; popup.ButtonPressEvent += OnButtonPressed; cal.Show(); Alignment calAlignment = new Alignment(0.0f, 0.0f, 1.0f, 1.0f); calAlignment.Show(); calAlignment.SetPadding(4, 4, 4, 4); calAlignment.Add(cal); box.PackStart(calAlignment, false, false, 0); // FIXME: Make the popup appear directly below the date Gdk.Rectangle allocation = tree.Allocation; // Gtk.Requisition req = tree.SizeRequest (); int x = 0, y = 0; tree.GdkWindow.GetOrigin(out x, out y); // popup.Move(x + allocation.X, y + allocation.Y + req.Height + 3); popup.Move(x + allocation.X, y + allocation.Y); popup.Show(); popup.GrabFocus(); Grab.Add(popup); Gdk.GrabStatus grabbed = Gdk.Pointer.Grab(popup.GdkWindow, true, Gdk.EventMask.ButtonPressMask | Gdk.EventMask.ButtonReleaseMask | Gdk.EventMask.PointerMotionMask, null, null, CURRENT_TIME); if (grabbed == Gdk.GrabStatus.Success) { grabbed = Gdk.Keyboard.Grab(popup.GdkWindow, true, CURRENT_TIME); if (grabbed != Gdk.GrabStatus.Success) { Grab.Remove(popup); popup.Destroy(); popup = null; } } else { Grab.Remove(popup); popup.Destroy(); popup = null; } cal.DaySelectedDoubleClick += OnCalendarDaySelected; cal.ButtonPressEvent += OnCalendarButtonPressed; cal.Date = date == DateTime.MinValue ? DateTime.Now : date; } public void HideCalendar(bool update) { if (popup != null) { Grab.Remove(popup); Gdk.Pointer.Ungrab(CURRENT_TIME); Gdk.Keyboard.Ungrab(CURRENT_TIME); popup.Destroy(); popup = null; } if (update) { date = cal.GetDate(); if (Edited != null) Edited (this, path); } } private StateType RendererStateToWidgetState(CellRendererState flags) { StateType state = StateType.Normal; if ((CellRendererState.Selected & flags).Equals( CellRendererState.Selected)) state = StateType.Selected; return state; } #endregion #region Event Handlers private void OnButtonPressed(object o, ButtonPressEventArgs args) { if (popup != null) HideCalendar(false); } private void OnCalendarDaySelected(object o, EventArgs args) { HideCalendar(true); } private void OnCalendarButtonPressed(object o, ButtonPressEventArgs args) { args.RetVal = true; } private void OnCalendarKeyPressed(object o, KeyPressEventArgs args) { switch (args.Event.Key) { case Gdk.Key.Escape: HideCalendar(false); break; case Gdk.Key.KP_Enter: case Gdk.Key.ISO_Enter: case Gdk.Key.Key_3270_Enter: case Gdk.Key.Return: case Gdk.Key.space: case Gdk.Key.KP_Space: HideCalendar(true); break; default: break; } } #endregion // Event Handlers } }
using UnityEditor.Experimental.GraphView; using UnityEngine; using System.Collections.Generic; using System.Linq; using System; using Branch = UnityEditor.VFX.Operator.VFXOperatorDynamicBranch; namespace UnityEditor.VFX.UI { class VFXOperatorController : VFXNodeController { protected override VFXDataAnchorController AddDataAnchor(VFXSlot slot, bool input, bool hidden) { VFXOperatorAnchorController anchor; if (input) { anchor = new VFXInputOperatorAnchorController(slot, this, hidden); } else { anchor = new VFXOutputOperatorAnchorController(slot, this, hidden); } anchor.portType = slot.property.type; return anchor; } public VFXOperatorController(VFXModel model, VFXViewController viewController) : base(model, viewController) { } public new VFXOperator model { get { return base.model as VFXOperator; } } public virtual bool isEditable { get {return false; } } public void ConvertToParameter() { var desc = VFXLibrary.GetParameters().FirstOrDefault(t => t.model.type == (model as VFXInlineOperator).type); if (desc == null) return; var param = viewController.AddVFXParameter(Vector2.zero, desc); // parameters should have zero for position, position is help by the nodes VFXSlot.CopyLinks(param.GetOutputSlot(0), model.GetOutputSlot(0), false); param.CreateDefaultNode(position); viewController.LightApplyChanges(); var paramController = viewController.GetParameterController(param); paramController.value = inputPorts[0].value; var paramNodeController = paramController.nodes.FirstOrDefault(); if (paramNodeController == null) return; viewController.PutInSameGroupNodeAs(paramNodeController, this); viewController.RemoveElement(this); } } class VFXVariableOperatorController : VFXOperatorController { public VFXVariableOperatorController(VFXModel model, VFXViewController viewController) : base(model, viewController) { } public new VFXOperatorDynamicOperand model { get { return base.model as VFXOperatorDynamicOperand; } } protected override bool CouldLinkMyInputTo(VFXDataAnchorController myInput, VFXDataAnchorController otherOutput, VFXDataAnchorController.CanLinkCache cache) { if (otherOutput.direction == myInput.direction) return false; if (!myInput.CanLinkToNode(otherOutput.sourceNode, cache)) return false; return model.GetBestAffinityType(otherOutput.portType) != null; } public override bool isEditable { get {return true; } } } class VFXUnifiedOperatorControllerBase<T> : VFXVariableOperatorController where T : VFXOperatorNumeric, IVFXOperatorNumericUnified { public VFXUnifiedOperatorControllerBase(VFXModel model, VFXViewController viewController) : base(model, viewController) { } public new T model { get { return base.model as T; } } public override void WillCreateLink(ref VFXSlot myInput, ref VFXSlot otherOutput) { if (!myInput.IsMasterSlot()) return; var bestAffinityType = model.GetBestAffinityType(otherOutput.property.type); if (bestAffinityType != null) { int index = model.GetSlotIndex(myInput); model.SetOperandType(index, bestAffinityType); myInput = model.GetInputSlot(index); } } } class VFXUnifiedOperatorController : VFXUnifiedOperatorControllerBase<VFXOperatorNumericUnified> { public VFXUnifiedOperatorController(VFXModel model, VFXViewController viewController) : base(model, viewController) { } } class VFXUnifiedConstraintOperatorController : VFXUnifiedOperatorController { public VFXUnifiedConstraintOperatorController(VFXModel model, VFXViewController viewController) : base(model, viewController) { } protected override bool CouldLinkMyInputTo(VFXDataAnchorController myInput, VFXDataAnchorController otherOutput, VFXDataAnchorController.CanLinkCache cache) { if (!myInput.model.IsMasterSlot()) return false; if (otherOutput.direction == myInput.direction) return false; if (!myInput.CanLinkToNode(otherOutput.sourceNode, cache)) return false; int inputIndex = model.GetSlotIndex(myInput.model); IVFXOperatorNumericUnifiedConstrained constraintInterface = model as IVFXOperatorNumericUnifiedConstrained; var bestAffinityType = model.GetBestAffinityType(otherOutput.portType); if (bestAffinityType == null) return false; if (constraintInterface.slotIndicesThatCanBeScalar.Contains(inputIndex)) { if (VFXTypeUtility.GetComponentCount(otherOutput.model) != 0) // If it is a vector or float type, then conversion to float exists return true; } return model.GetBestAffinityType(otherOutput.portType) != null; } public static Type GetMatchingScalar(Type otherType) { return VFXExpression.GetMatchingScalar(otherType); } public override void WillCreateLink(ref VFXSlot myInput, ref VFXSlot otherOutput) { if (!myInput.IsMasterSlot()) return; int inputIndex = model.GetSlotIndex(myInput); IVFXOperatorNumericUnifiedConstrained constraintInterface = model as IVFXOperatorNumericUnifiedConstrained; if (!constraintInterface.slotIndicesThatMustHaveSameType.Contains(inputIndex)) { base.WillCreateLink(ref myInput, ref otherOutput); return; } bool scalar = constraintInterface.slotIndicesThatCanBeScalar.Contains(inputIndex); if (scalar) { var bestAffinityType = model.GetBestAffinityType(otherOutput.property.type); VFXSlot otherSlotWithConstraint = model.inputSlots.Where((t, i) => constraintInterface.slotIndicesThatMustHaveSameType.Contains(i)).FirstOrDefault(); if (otherSlotWithConstraint == null || otherSlotWithConstraint.property.type == bestAffinityType) { model.SetOperandType(inputIndex, bestAffinityType); myInput = model.GetInputSlot(inputIndex); } else if (!myInput.CanLink(otherOutput) || !otherOutput.CanLink(myInput)) // if the link is invalid if we don't change the type, change the type to the matching scalar { var bestScalarAffinityType = model.GetBestAffinityType(GetMatchingScalar(otherOutput.property.type)); if (bestScalarAffinityType != null) { model.SetOperandType(inputIndex, bestScalarAffinityType); myInput = model.GetInputSlot(inputIndex); } } return; // never change the type of other constraint if the linked slot is scalar } VFXSlot input = myInput; bool hasLinks = model.inputSlots.Where((t, i) => t != input && t.HasLink(true) && constraintInterface.slotIndicesThatMustHaveSameType.Contains(i) && !constraintInterface.slotIndicesThatCanBeScalar.Contains(i)).Count() > 0; bool linkPossible = myInput.CanLink(otherOutput) && otherOutput.CanLink(myInput); if (!hasLinks || !linkPossible) //Change the type if other type having the same constraint have no link or if the link will fail if we don't { var bestAffinityType = model.GetBestAffinityType(otherOutput.property.type); if (bestAffinityType != null) { foreach (int slotIndex in constraintInterface.slotIndicesThatMustHaveSameType) { if (!constraintInterface.slotIndicesThatCanBeScalar.Contains(slotIndex) || GetMatchingScalar(bestAffinityType) != model.GetInputSlot(slotIndex).property.type) model.SetOperandType(slotIndex, bestAffinityType); } myInput = model.GetInputSlot(inputIndex); } } } } class VFXCascadedOperatorController : VFXUnifiedOperatorControllerBase<VFXOperatorNumericCascadedUnified> { public VFXCascadedOperatorController(VFXModel model, VFXViewController viewController) : base(model, viewController) { } VFXUpcommingDataAnchorController m_UpcommingDataAnchor; protected override void NewInputSet(List<VFXDataAnchorController> newInputs) { if (m_UpcommingDataAnchor == null) { m_UpcommingDataAnchor = new VFXUpcommingDataAnchorController(this, false); } newInputs.Add(m_UpcommingDataAnchor); } public override void OnEdgeGoingToBeRemoved(VFXDataAnchorController myInput) { base.OnEdgeGoingToBeRemoved(myInput); RemoveOperand(myInput); } public bool CanRemove() { return model.operandCount > model.MinimalOperandCount; } public void RemoveOperand(VFXDataAnchorController myInput) { var slotIndex = model.GetSlotIndex(myInput.model); if (slotIndex != -1) RemoveOperand(slotIndex); } public void RemoveOperand(int index) { if (CanRemove()) { model.RemoveOperand(index); } } } class VFXUniformOperatorController<T> : VFXVariableOperatorController where T : VFXOperatorDynamicOperand, IVFXOperatorUniform { public VFXUniformOperatorController(VFXModel model, VFXViewController viewController) : base(model, viewController) { } public new T model { get { return base.model as T; } } public override void WillCreateLink(ref VFXSlot myInput, ref VFXSlot otherOutput) { if (!myInput.IsMasterSlot()) return; //Since every input will change at the same time the metric to change is : // if we have no input links yet var myInputCopy = myInput; bool hasLink = inputPorts.Any(t => t.model != myInputCopy && t.model.HasLink()); int index = model.GetSlotIndex(myInput); if (model.staticSlotIndex.Contains(index)) return; // The new link is impossible if we don't change (case of a vector3 trying to be linked to a vector4) bool linkImpossibleNow = !myInput.CanLink(otherOutput) || !otherOutput.CanLink(myInput); var bestAffinity = model.GetBestAffinityType(otherOutput.property.type); if ((!hasLink || linkImpossibleNow) && bestAffinity != null) { model.SetOperandType(bestAffinity); myInput = model.GetInputSlot(index); } } } class VFXNumericUniformOperatorController : VFXUniformOperatorController<VFXOperatorNumericUniform> { public VFXNumericUniformOperatorController(VFXModel model, VFXViewController viewController) : base(model, viewController) { } } class VFXBranchOperatorController : VFXUniformOperatorController<Branch> { public VFXBranchOperatorController(VFXModel model, VFXViewController viewController) : base(model, viewController) { } } }
using System; using System.IO; using System.Linq; using System.Reflection; using System.Security.Cryptography; using ToolKit.Cryptography; using Xunit; namespace UnitTests.Cryptography { [System.Diagnostics.CodeAnalysis.SuppressMessage( "StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Test Suites do not need XML Documentation.")] [System.Diagnostics.CodeAnalysis.SuppressMessage( "SonarCube.UnusedLocalVariables", "S1481", Justification = "Unused local variables should be removed")] public class ASymmetricEncryptionTests { private readonly string _assemblyPath; private readonly RsaPrivateKey _privateKey; private readonly RsaPublicKey _publicKey; private readonly EncryptionData _targetData; private readonly string _targetString; public ASymmetricEncryptionTests() { var fullPath = Assembly.GetAssembly(typeof(ASymmetricEncryptionTests)).Location; var pathDirectory = Path.GetDirectoryName(fullPath); var separator = Path.DirectorySeparatorChar; _assemblyPath = $"{pathDirectory}{separator}"; _targetString = "Did you know that some of the most famous inventions would " + "never have been made if the inventors had stopped at their " + "first failure? For instance, Thomas Edison, inventor of " + "the light bulb had 1,000 failed attempts at creating one " + "light bulb that worked properly. - Vee Freir"; _targetData = new EncryptionData(_targetString); _privateKey = RsaPrivateKey.LoadFromCertificateFile( $"{_assemblyPath}ASymmetricEncryption.pfx", "password"); _publicKey = RsaPublicKey.LoadFromCertificateFile( $"{_assemblyPath}ASymmetricEncryption.pfx", "password"); } [Fact] public void Constructor_Should_InitializeProperly_When_RSAPrivateKeyIsProvided() { // Arrange & Act var e1 = new ASymmetricEncryption(_privateKey); // Assert Assert.NotNull(e1); } [Fact] public void Constructor_Should_InitializeProperly_When_RSAPublicKeyAndPasswordProvided() { // Arrange var password = new EncryptionData("password"); // Act var e1 = new ASymmetricEncryption(_publicKey, password); // Assert Assert.NotNull(e1); } [Fact] public void Constructor_Should_InitializeProperly_When_RSAPublicKeyIsProvided() { // Arrange & Act var e1 = new ASymmetricEncryption(_publicKey); // Assert Assert.NotNull(e1); } [Fact] public void Constructor_Should_ThrowArgumentOutOfRangeException_When_PasswordGreaterThan32Characters() { // Arrange var password = new EncryptionData("123456789012345678901234567890123"); // Act & Assert Assert.Throws<ArgumentOutOfRangeException>( () => { var e1 = new ASymmetricEncryption(_publicKey, password); }); } [Fact] public void Constructor_Should_ThrowException_When_RSAPrivateKeyIsNotProvided() { // Arrange RsaPrivateKey key = null; // Act & Assert Assert.Throws<ArgumentNullException>( () => { var e1 = new ASymmetricEncryption(key); }); } [Fact] public void Constructor_Should_ThrowExceptionWhenNoRSAPublicKeyIsProvidedButPasswordIs() { // Arrange RsaPublicKey key = null; var password = new EncryptionData("password"); // Act & Assert Assert.Throws<ArgumentNullException>( () => { var e1 = new ASymmetricEncryption(key, password); }); } [Fact] public void Constructor_Should_ThrowExceptionWhenRSAPublicKeyIsNotProvided() { // Arrange RsaPublicKey key = null; // Act & Assert Assert.Throws<ArgumentNullException>(() => { var e1 = new ASymmetricEncryption(key); }); } [Fact] public void Constructor_Should_ThrowExceptionWhenRSAPublicKeyIsProvidedButNoPassword() { // Arrange var password = new EncryptionData(); // Act & Assert Assert.Throws<ArgumentNullException>( () => { var e1 = new ASymmetricEncryption(_publicKey, password); }); } [Fact] public void Decrypt_Should_ReturnExpectedResult_When_ProvidedCorrectPrivateKey() { // Arrange var e1 = new ASymmetricEncryption(_publicKey); var e2 = new ASymmetricEncryption(_privateKey); // Act var encrypted = e1.Encrypt(_targetData); var decrypted = e2.Decrypt(encrypted); // Assert Assert.True(_targetData.Text == decrypted.Text); } [Fact] public void Decrypt_Should_ReturnExpectedResult_When_ProvidedCorrectPrivateKeyAndUsingStream() { // Arrange var e1 = new ASymmetricEncryption(_publicKey); var e2 = new ASymmetricEncryption(_privateKey); // Act var encrypted = e1.Encrypt(_targetData); EncryptionData decrypted; using (var stream = new MemoryStream(encrypted.Bytes)) { decrypted = e2.Decrypt(stream); } // Assert Assert.True(_targetData.Text == decrypted.Text); } [Fact] public void Decrypt_Should_ThrowException_When_ImproperEncryptedDataProvided() { // Arrange var e2 = new ASymmetricEncryption(_privateKey); var encrypted = new EncryptionData(new byte[100]); // Act & Assert Assert.Throws<ArgumentException>(() => { var decrypted = e2.Decrypt(encrypted); }); } [Fact] public void Decrypt_Should_ThrowException_When_NoEncryptedDataProvided() { // Arrange var e2 = new ASymmetricEncryption(_privateKey); var encrypted = new EncryptionData(); // Act & Assert Assert.Throws<ArgumentException>(() => { var decrypted = e2.Decrypt(encrypted); }); } [Fact] public void Decrypt_Should_ThrowException_When_ProvidedWrongPrivateKey() { // Arrange var wrongKey = RsaPrivateKey.LoadFromCertificateFile( $"{_assemblyPath}ASymmetricEncryptionWrong.pfx", "password"); var e1 = new ASymmetricEncryption(_publicKey); var e2 = new ASymmetricEncryption(wrongKey); var encrypted = e1.Encrypt(_targetData); // Act & Assert Assert.Throws<CryptographicException>(() => { var decrypted = e2.Decrypt(encrypted); }); } [Fact] public void Decrypt_Should_ThrowException_When_RSAPublicKeyIsProvided() { // Arrange var e1 = new ASymmetricEncryption(_publicKey); // Act & Assert Assert.Throws<InvalidOperationException>( () => { var encrypted = e1.Decrypt(_targetData); }); } [Fact] public void Decrypt_Should_ThrowException_When_RSAPublicKeyIsProvided_When_UsingStream() { // Arrange var e1 = new ASymmetricEncryption(_publicKey); EncryptionData encrypted; // Act & Assert Assert.Throws<InvalidOperationException>( () => { using (var sr = new StreamReader($"{_assemblyPath}sample.doc")) { encrypted = e1.Decrypt(sr.BaseStream); } }); } [Fact] public void Encrypt_Should_ReturnA32BytePassword() { // Arrange var encrypt = new ASymmetricEncryption(_publicKey); var encryptedPassword = new EncryptionData(new byte[256]); var rsa = new RsaEncryption(); // Act var encryptedBytes = encrypt.Encrypt(_targetData); Buffer.BlockCopy(encryptedBytes.Bytes, 0, encryptedPassword.Bytes, 0, 256); var password = rsa.Decrypt(encryptedPassword, _privateKey); // Assert Assert.True(password.Bytes.Length == 32); } [Fact] public void Encrypt_Should_ReturnEncryptedData() { // Arrange var e1 = new ASymmetricEncryption(_publicKey); // Act var encrypted = e1.Encrypt(_targetData); // Assert Assert.False(encrypted.IsEmpty); } [Fact] public void Encrypt_Should_ReturnEncryptedData_When_UsingStream() { // Arrange var e1 = new ASymmetricEncryption(_publicKey); EncryptionData encrypted; // Act using (var sr = new StreamReader($"{_assemblyPath}sample.doc")) { encrypted = e1.Encrypt(sr.BaseStream); } // Assert Assert.False(encrypted.IsEmpty); } [Fact] public void Encrypt_Should_ReturnSamePassword_When_ExplicitPasswordProvidedAndPasswordLenghtLessThan16() { // Arrange var password = new EncryptionData("password"); var encrypt = new ASymmetricEncryption(_publicKey, password); var encryptedPassword = new EncryptionData(new byte[256]); // Act var encryptedBytes = encrypt.Encrypt(_targetData); Buffer.BlockCopy(encryptedBytes.Bytes, 0, encryptedPassword.Bytes, 0, 256); var decryptedPassword = new RsaEncryption().Decrypt(encryptedPassword, _privateKey); // Assert Assert.True(decryptedPassword.Text == password.Text); } [Fact] public void Encrypt_Should_ReturnSamePassword_When_ExplicitPasswordProvidedAndPasswordLengthGreaterThan16() { // Arrange var password = new EncryptionData("A really long simple password"); var encrypt = new ASymmetricEncryption(_publicKey, password); var encryptedPassword = new EncryptionData(new byte[256]); // Act var encryptedBytes = encrypt.Encrypt(_targetData); Buffer.BlockCopy(encryptedBytes.Bytes, 0, encryptedPassword.Bytes, 0, 256); var decryptedPassword = new RsaEncryption().Decrypt(encryptedPassword, _privateKey); // Assert Assert.True(decryptedPassword.Text == password.Text); } [Fact] public void Encrypt_Should_ReturnSamePassword_When_ExplicitPasswordProvidedAndPasswordWithNonUTF8Password() { // Arrange var password = new EncryptionData("A really long simple password", System.Text.Encoding.ASCII); var encrypt = new ASymmetricEncryption(_publicKey, password); var encryptedPassword = new EncryptionData(new byte[256]); // Act var encryptedBytes = encrypt.Encrypt(_targetData); Buffer.BlockCopy(encryptedBytes.Bytes, 0, encryptedPassword.Bytes, 0, 256); var decryptedPassword = new RsaEncryption().Decrypt(encryptedPassword, _privateKey); // Assert Assert.True(decryptedPassword.Text == password.Text); } [Fact] public void Encrypt_Should_ReturnTheSamePasswordAsEncryptedPassword() { // Arrange var encrypt = new ASymmetricEncryption(_publicKey); var encryptedPassword = new byte[256]; var payloadPassword = new byte[256]; Buffer.BlockCopy(encrypt.EncryptedPassword.Bytes, 0, encryptedPassword, 0, 256); // Act var encryptedBytes = encrypt.Encrypt(_targetData); Buffer.BlockCopy(encryptedBytes.Bytes, 0, payloadPassword, 0, 256); // Assert Assert.True(payloadPassword.SequenceEqual(encryptedPassword)); } [Fact] public void Encrypt_Should_ThrowException_When_NoDataForPayloadProvided() { // Arrange var empty = new EncryptionData(); var e1 = new ASymmetricEncryption(_privateKey); // Act & Assert Assert.Throws<ArgumentException>( () => { var encrypted = e1.Encrypt(empty); }); } [Fact] public void Encrypt_Should_ThrowException_When_RSAPrivateKeyIsProvided() { // Arrange var e1 = new ASymmetricEncryption(_privateKey); // Act & Assert Assert.Throws<InvalidOperationException>( () => { var encrypted = e1.Encrypt(_targetData); }); } [Fact] public void Encrypt_Should_ThrowException_When_RSAPrivateKeyIsProvided_When_UsingStream() { // Arrange var e1 = new ASymmetricEncryption(_privateKey); EncryptionData encrypted; // Act & Assert Assert.Throws<InvalidOperationException>( () => { using (var sr = new StreamReader($"{_assemblyPath}sample.doc")) { encrypted = e1.Encrypt(sr.BaseStream); } }); } [Fact] public void Encrypt_Should_ThrowException_When_StreamIsNotReadable() { // Arrange var fileName = $"{_assemblyPath}{Guid.NewGuid()}"; var e1 = new ASymmetricEncryption(_privateKey); var stream = new FileStream(fileName, FileMode.CreateNew, FileAccess.Write); // Act & Assert Assert.Throws<ArgumentException>( () => { var encrypted = e1.Encrypt(stream); }); stream.Close(); stream.Dispose(); } [Fact] public void EncryptedPassword_Should_ReturnA256ByteEncryptedPassword() { // Arrange var encrypt = new ASymmetricEncryption(_publicKey); // Act var encryptedPassword = encrypt.EncryptedPassword; // Assert Assert.True(encryptedPassword.Bytes.Length == 256); } [Fact] public void Password_Should_ReturnValue_When_ConstructorIsCalled() { // Arrange & Act var encrypt = new ASymmetricEncryption(_publicKey); // Assert Assert.True(encrypt.EncryptedPassword.ToString().Length > 0); } } }
using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Transactions; using log4net; using Rhino.ServiceBus; using Rhino.ServiceBus.Exceptions; using Rhino.ServiceBus.Impl; using Rhino.ServiceBus.Internal; using Rhino.ServiceBus.Msmq.TransportActions; using Rhino.ServiceBus.Transport; using Rhino.ServiceBus.Util; using MessageType = Rhino.ServiceBus.Transport.MessageType; using Rhino.ServiceBus.FileMessaging; using Rhino.ServiceBus.File.TransportActions; namespace Rhino.ServiceBus.File { public class FileTransport : AbstractFileListener, IFileTransport { [ThreadStatic] private static FileCurrentMessageInformation currentMessageInformation; public static FileCurrentMessageInformation FileCurrentMessageInformation { get { return currentMessageInformation; } } public CurrentMessageInformation CurrentMessageInformation { get { return currentMessageInformation; } } private readonly ILog logger = LogManager.GetLogger(typeof(FileTransport)); private readonly IFileTransportAction[] transportActions; private readonly IsolationLevel queueIsolationLevel; private readonly bool consumeInTransaction; public FileTransport(IMessageSerializer serializer, IQueueStrategy queueStrategy, Uri endpoint, int threadCount, IFileTransportAction[] transportActions, IEndpointRouter endpointRouter, IsolationLevel queueIsolationLevel, TransactionalOptions transactional, bool consumeInTransaction, IMessageBuilder<Message> messageBuilder) : base(queueStrategy, endpoint, threadCount, serializer, endpointRouter, transactional, messageBuilder) { this.transportActions = transportActions; this.queueIsolationLevel = queueIsolationLevel; this.consumeInTransaction = consumeInTransaction; } #region ITransport Members protected override void BeforeStart(OpenedQueue queue) { foreach (var messageAction in transportActions) messageAction.Init(this, queue); } public void Reply(params object[] messages) { if (currentMessageInformation == null) throw new TransactionException("There is no message to reply to, sorry."); logger.DebugFormat("Replying to {0}", currentMessageInformation.Source); Send(endpointRouter.GetRoutedEndpoint(currentMessageInformation.Source), messages); } public event Action<CurrentMessageInformation> MessageSent; public event Func<CurrentMessageInformation, bool> AdministrativeMessageArrived; public event Func<CurrentMessageInformation, bool> MessageArrived; public event Action<CurrentMessageInformation, Exception> MessageProcessingFailure; public event Action<CurrentMessageInformation, Exception> MessageProcessingCompleted; public event Action<CurrentMessageInformation> BeforeMessageTransactionRollback; public event Action<CurrentMessageInformation> BeforeMessageTransactionCommit; public event Action<CurrentMessageInformation, Exception> AdministrativeMessageProcessingCompleted; public void Discard(object msg) { var message = GenerateMsmqMessageFromMessageBatch(new[] { msg }); SendMessageToQueue(message.SetSubQueueToSendTo(SubQueue.Discarded), Endpoint); } public bool RaiseAdministrativeMessageArrived(CurrentMessageInformation information) { var copy = AdministrativeMessageArrived; if (copy != null) return copy(information); return false; } public void RaiseAdministrativeMessageProcessingCompleted(CurrentMessageInformation information, Exception ex) { var copy = AdministrativeMessageProcessingCompleted; if (copy != null) copy(information, ex); } public void Send(Endpoint endpoint, DateTime processAgainAt, object[] msgs) { if (!HaveStarted) throw new InvalidOperationException("Cannot send a message before transport is started"); var message = GenerateMsmqMessageFromMessageBatch(msgs); var processAgainBytes = BitConverter.GetBytes(processAgainAt.ToBinary()); if (message.Extension.Length == 16) { var bytes = new List<byte>(message.Extension); bytes.AddRange(processAgainBytes); message.Extension = bytes.ToArray(); } else { var extension = (byte[])message.Extension.Clone(); Buffer.BlockCopy(processAgainBytes, 0, extension, 16, processAgainBytes.Length); message.Extension = extension; } message.AppSpecific = (int)MessageType.TimeoutMessageMarker; SendMessageToQueue(message, endpoint); } public void Send(Endpoint destination, object[] msgs) { if (HaveStarted == false) throw new InvalidOperationException("Cannot send a message before transport is started"); var message = GenerateMsmqMessageFromMessageBatch(msgs); SendMessageToQueue(message, destination); var copy = MessageSent; if (copy == null) return; copy(new CurrentMessageInformation { AllMessages = msgs, Source = Endpoint.Uri, Destination = destination.Uri, MessageId = message.GetMessageId(), }); } public event Action<CurrentMessageInformation, Exception> MessageSerializationException; #endregion public void ReceiveMessageInTransaction(OpenedQueue queue, string messageId, Func<CurrentMessageInformation, bool> messageArrived, Action<CurrentMessageInformation, Exception> messageProcessingCompleted, Action<CurrentMessageInformation> beforeMessageTransactionCommit, Action<CurrentMessageInformation> beforeMessageTransactionRollback) { var transactionOptions = new TransactionOptions { IsolationLevel = queueIsolationLevel, Timeout = TransportUtil.GetTransactionTimeout(), }; using (var tx = new TransactionScope(TransactionScopeOption.Required, transactionOptions)) { var message = queue.TryGetMessageFromQueue(messageId); if (message == null) return; // someone else got our message, better luck next time ProcessMessage(message, queue, tx, messageArrived, beforeMessageTransactionCommit, beforeMessageTransactionRollback, messageProcessingCompleted); } } private void ReceiveMessage(OpenedQueue queue, string messageId, Func<CurrentMessageInformation, bool> messageArrived, Action<CurrentMessageInformation, Exception> messageProcessingCompleted) { var message = queue.TryGetMessageFromQueue(messageId); if (message == null) return; ProcessMessage(message, queue, null, messageArrived, null, null, messageProcessingCompleted); } public void RaiseMessageSerializationException(OpenedQueue queue, Message msg, string errorMessage) { var copy = MessageSerializationException; if (copy == null) return; var messageInformation = new FileCurrentMessageInformation { FileMessage = msg, Queue = queue, Message = null, Source = queue.RootUri, MessageId = Guid.Empty }; copy(messageInformation, new SerializationException(errorMessage)); } public OpenedQueue CreateQueue() { return Endpoint.InitalizeQueue(); } private void ProcessMessage( Message message, OpenedQueue messageQueue, TransactionScope tx, Func<CurrentMessageInformation, bool> messageRecieved, Action<CurrentMessageInformation> beforeMessageTransactionCommit, Action<CurrentMessageInformation> beforeMessageTransactionRollback, Action<CurrentMessageInformation, Exception> messageCompleted) { Exception ex = null; currentMessageInformation = CreateMessageInformation(messageQueue, message, null, null); try { // deserialization errors do not count for module events var messages = DeserializeMessages(messageQueue, message, MessageSerializationException); try { foreach (object msg in messages) { currentMessageInformation = CreateMessageInformation(messageQueue, message, messages, msg); if (TransportUtil.ProcessSingleMessage(currentMessageInformation, messageRecieved) == false) Discard(currentMessageInformation.Message); } } catch (Exception e) { ex = e; logger.Error("Failed to process message", e); } } catch (Exception e) { ex = e; logger.Error("Failed to deserialize message", e); } finally { Action sendMessageBackToQueue = null; if (message != null && (messageQueue.IsTransactional == false || consumeInTransaction == false)) sendMessageBackToQueue = () => messageQueue.Send(message); var messageHandlingCompletion = new MessageHandlingCompletion(tx, sendMessageBackToQueue, ex, messageCompleted, beforeMessageTransactionCommit, beforeMessageTransactionRollback, logger, MessageProcessingFailure, currentMessageInformation); messageHandlingCompletion.HandleMessageCompletion(); currentMessageInformation = null; } } private FileCurrentMessageInformation CreateMessageInformation(OpenedQueue queue, Message message, object[] messages, object msg) { return new FileCurrentMessageInformation { MessageId = message.GetMessageId(), AllMessages = messages, Message = msg, Queue = queue, TransportMessageId = message.Id, Destination = Endpoint.Uri, Source = FileUtil.GetQueueUri(message.ResponseQueue), FileMessage = message, TransactionType = queue.GetTransactionType(), Headers = message.Extension.DeserializeHeaders() }; } private void SendMessageToQueue(Message message, Endpoint endpoint) { if (HaveStarted == false) throw new TransportException("Cannot send message before transport is started"); try { using (var sendQueue = FileUtil.GetQueuePath(endpoint).Open(QueueAccessMode.Send)) { sendQueue.Send(message); logger.DebugFormat("Send message {0} to {1}", message.Label, endpoint); } } catch (Exception e) { throw new TransactionException("Failed to send message to " + endpoint, e); } } protected override void HandlePeekedMessage(OpenedQueue queue, Message message) { foreach (var action in transportActions) { if (!action.CanHandlePeekedMessage(message)) continue; try { if (action.HandlePeekedMessage(this, queue, message)) return; } catch (Exception e) { logger.Error("Error when trying to execute action " + action + " on message " + message.Id + ". Message has been removed without handling!", e); queue.ConsumeMessage(message.Id); } } if (consumeInTransaction) ReceiveMessageInTransaction(queue, message.Id, MessageArrived, MessageProcessingCompleted, BeforeMessageTransactionCommit, BeforeMessageTransactionRollback); else ReceiveMessage(queue, message.Id, MessageArrived, MessageProcessingCompleted); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V8.Services { /// <summary>Settings for <see cref="PaymentsAccountServiceClient"/> instances.</summary> public sealed partial class PaymentsAccountServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="PaymentsAccountServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="PaymentsAccountServiceSettings"/>.</returns> public static PaymentsAccountServiceSettings GetDefault() => new PaymentsAccountServiceSettings(); /// <summary> /// Constructs a new <see cref="PaymentsAccountServiceSettings"/> object with default settings. /// </summary> public PaymentsAccountServiceSettings() { } private PaymentsAccountServiceSettings(PaymentsAccountServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); ListPaymentsAccountsSettings = existing.ListPaymentsAccountsSettings; OnCopy(existing); } partial void OnCopy(PaymentsAccountServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>PaymentsAccountServiceClient.ListPaymentsAccounts</c> and /// <c>PaymentsAccountServiceClient.ListPaymentsAccountsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings ListPaymentsAccountsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="PaymentsAccountServiceSettings"/> object.</returns> public PaymentsAccountServiceSettings Clone() => new PaymentsAccountServiceSettings(this); } /// <summary> /// Builder class for <see cref="PaymentsAccountServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class PaymentsAccountServiceClientBuilder : gaxgrpc::ClientBuilderBase<PaymentsAccountServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public PaymentsAccountServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public PaymentsAccountServiceClientBuilder() { UseJwtAccessWithScopes = PaymentsAccountServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref PaymentsAccountServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<PaymentsAccountServiceClient> task); /// <summary>Builds the resulting client.</summary> public override PaymentsAccountServiceClient Build() { PaymentsAccountServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<PaymentsAccountServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<PaymentsAccountServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private PaymentsAccountServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return PaymentsAccountServiceClient.Create(callInvoker, Settings); } private async stt::Task<PaymentsAccountServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return PaymentsAccountServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => PaymentsAccountServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => PaymentsAccountServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => PaymentsAccountServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>PaymentsAccountService client wrapper, for convenient use.</summary> /// <remarks> /// Service to provide payments accounts that can be used to set up consolidated /// billing. /// </remarks> public abstract partial class PaymentsAccountServiceClient { /// <summary> /// The default endpoint for the PaymentsAccountService service, which is a host of "googleads.googleapis.com" /// and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default PaymentsAccountService scopes.</summary> /// <remarks> /// The default PaymentsAccountService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="PaymentsAccountServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="PaymentsAccountServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="PaymentsAccountServiceClient"/>.</returns> public static stt::Task<PaymentsAccountServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new PaymentsAccountServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="PaymentsAccountServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="PaymentsAccountServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="PaymentsAccountServiceClient"/>.</returns> public static PaymentsAccountServiceClient Create() => new PaymentsAccountServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="PaymentsAccountServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="PaymentsAccountServiceSettings"/>.</param> /// <returns>The created <see cref="PaymentsAccountServiceClient"/>.</returns> internal static PaymentsAccountServiceClient Create(grpccore::CallInvoker callInvoker, PaymentsAccountServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } PaymentsAccountService.PaymentsAccountServiceClient grpcClient = new PaymentsAccountService.PaymentsAccountServiceClient(callInvoker); return new PaymentsAccountServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC PaymentsAccountService client</summary> public virtual PaymentsAccountService.PaymentsAccountServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns all payments accounts associated with all managers /// between the login customer ID and specified serving customer in the /// hierarchy, inclusive. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [PaymentsAccountError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual ListPaymentsAccountsResponse ListPaymentsAccounts(ListPaymentsAccountsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns all payments accounts associated with all managers /// between the login customer ID and specified serving customer in the /// hierarchy, inclusive. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [PaymentsAccountError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ListPaymentsAccountsResponse> ListPaymentsAccountsAsync(ListPaymentsAccountsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns all payments accounts associated with all managers /// between the login customer ID and specified serving customer in the /// hierarchy, inclusive. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [PaymentsAccountError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ListPaymentsAccountsResponse> ListPaymentsAccountsAsync(ListPaymentsAccountsRequest request, st::CancellationToken cancellationToken) => ListPaymentsAccountsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns all payments accounts associated with all managers /// between the login customer ID and specified serving customer in the /// hierarchy, inclusive. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [PaymentsAccountError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer to apply the PaymentsAccount list operation to. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual ListPaymentsAccountsResponse ListPaymentsAccounts(string customerId, gaxgrpc::CallSettings callSettings = null) => ListPaymentsAccounts(new ListPaymentsAccountsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), }, callSettings); /// <summary> /// Returns all payments accounts associated with all managers /// between the login customer ID and specified serving customer in the /// hierarchy, inclusive. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [PaymentsAccountError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer to apply the PaymentsAccount list operation to. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ListPaymentsAccountsResponse> ListPaymentsAccountsAsync(string customerId, gaxgrpc::CallSettings callSettings = null) => ListPaymentsAccountsAsync(new ListPaymentsAccountsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), }, callSettings); /// <summary> /// Returns all payments accounts associated with all managers /// between the login customer ID and specified serving customer in the /// hierarchy, inclusive. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [PaymentsAccountError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer to apply the PaymentsAccount list operation to. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ListPaymentsAccountsResponse> ListPaymentsAccountsAsync(string customerId, st::CancellationToken cancellationToken) => ListPaymentsAccountsAsync(customerId, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>PaymentsAccountService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to provide payments accounts that can be used to set up consolidated /// billing. /// </remarks> public sealed partial class PaymentsAccountServiceClientImpl : PaymentsAccountServiceClient { private readonly gaxgrpc::ApiCall<ListPaymentsAccountsRequest, ListPaymentsAccountsResponse> _callListPaymentsAccounts; /// <summary> /// Constructs a client wrapper for the PaymentsAccountService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="PaymentsAccountServiceSettings"/> used within this client. /// </param> public PaymentsAccountServiceClientImpl(PaymentsAccountService.PaymentsAccountServiceClient grpcClient, PaymentsAccountServiceSettings settings) { GrpcClient = grpcClient; PaymentsAccountServiceSettings effectiveSettings = settings ?? PaymentsAccountServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callListPaymentsAccounts = clientHelper.BuildApiCall<ListPaymentsAccountsRequest, ListPaymentsAccountsResponse>(grpcClient.ListPaymentsAccountsAsync, grpcClient.ListPaymentsAccounts, effectiveSettings.ListPaymentsAccountsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callListPaymentsAccounts); Modify_ListPaymentsAccountsApiCall(ref _callListPaymentsAccounts); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_ListPaymentsAccountsApiCall(ref gaxgrpc::ApiCall<ListPaymentsAccountsRequest, ListPaymentsAccountsResponse> call); partial void OnConstruction(PaymentsAccountService.PaymentsAccountServiceClient grpcClient, PaymentsAccountServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC PaymentsAccountService client</summary> public override PaymentsAccountService.PaymentsAccountServiceClient GrpcClient { get; } partial void Modify_ListPaymentsAccountsRequest(ref ListPaymentsAccountsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns all payments accounts associated with all managers /// between the login customer ID and specified serving customer in the /// hierarchy, inclusive. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [PaymentsAccountError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override ListPaymentsAccountsResponse ListPaymentsAccounts(ListPaymentsAccountsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListPaymentsAccountsRequest(ref request, ref callSettings); return _callListPaymentsAccounts.Sync(request, callSettings); } /// <summary> /// Returns all payments accounts associated with all managers /// between the login customer ID and specified serving customer in the /// hierarchy, inclusive. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [PaymentsAccountError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<ListPaymentsAccountsResponse> ListPaymentsAccountsAsync(ListPaymentsAccountsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListPaymentsAccountsRequest(ref request, ref callSettings); return _callListPaymentsAccounts.Async(request, callSettings); } } }
// Copyright (c) 2015, Outercurve Foundation. // 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 the Outercurve Foundation 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Data; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Net.Mail; using System.Text.RegularExpressions; using System.Xml.Linq; namespace WebsitePanel.EnterpriseServer { /// <summary> /// Summary description for UserController. /// </summary> public class UserController { public static bool UserExists(string username) { // try to get user from database UserInfo user = GetUserInternally(username); return (user != null); } public static int AuthenticateUser(string username, string password, string ip) { // start task TaskManager.StartTask("USER", "AUTHENTICATE", username); TaskManager.WriteParameter("IP", ip); try { int result = 0; // try to get user from database UserInfoInternal user = GetUserInternally(username); // check if the user exists if (user == null) { TaskManager.WriteWarning("Wrong username"); return BusinessErrorCodes.ERROR_USER_WRONG_USERNAME; } // check if the user is disabled if (user.LoginStatus == UserLoginStatus.Disabled) { TaskManager.WriteWarning("User disabled"); return BusinessErrorCodes.ERROR_USER_ACCOUNT_DISABLED; } // check if the user is locked out if (user.LoginStatus == UserLoginStatus.LockedOut) { TaskManager.WriteWarning("User locked out"); return BusinessErrorCodes.ERROR_USER_ACCOUNT_LOCKEDOUT; } //Get the password policy UserSettings userSettings = UserController.GetUserSettings(user.UserId, UserSettings.WEBSITEPANEL_POLICY); int lockOut = -1; if (!string.IsNullOrEmpty(userSettings["PasswordPolicy"])) { string passwordPolicy = userSettings["PasswordPolicy"]; try { // parse settings string[] parts = passwordPolicy.Split(';'); lockOut = Convert.ToInt32(parts[7]); } catch { /* skip */ } } // compare user passwords if ((CryptoUtils.SHA1(user.Password) == password) || (user.Password == password)) { switch (user.OneTimePasswordState) { case OneTimePasswordStates.Active: result = BusinessSuccessCodes.SUCCESS_USER_ONETIMEPASSWORD; OneTimePasswordHelper.FireSuccessAuth(user); break; case OneTimePasswordStates.Expired: if (lockOut >= 0) DataProvider.UpdateUserFailedLoginAttempt(user.UserId, lockOut, false); TaskManager.WriteWarning("Expired one time password"); return BusinessErrorCodes.ERROR_USER_EXPIRED_ONETIMEPASSWORD; break; } } else { if (lockOut >= 0) DataProvider.UpdateUserFailedLoginAttempt(user.UserId, lockOut, false); TaskManager.WriteWarning("Wrong password"); return BusinessErrorCodes.ERROR_USER_WRONG_PASSWORD; } DataProvider.UpdateUserFailedLoginAttempt(user.UserId, lockOut, true); // check status if (user.Status == UserStatus.Cancelled) { TaskManager.WriteWarning("Account cancelled"); return BusinessErrorCodes.ERROR_USER_ACCOUNT_CANCELLED; } if (user.Status == UserStatus.Pending) { TaskManager.WriteWarning("Account pending"); return BusinessErrorCodes.ERROR_USER_ACCOUNT_PENDING; } return result; } catch (Exception ex) { throw TaskManager.WriteError(ex); } finally { TaskManager.CompleteTask(); } } public static UserInfo GetUserByUsernamePassword(string username, string password, string ip) { // place log record TaskManager.StartTask("USER", "GET_BY_USERNAME_PASSWORD", username); TaskManager.WriteParameter("IP", ip); try { // try to get user from database UserInfoInternal user = GetUserInternally(username); // check if the user exists if (user == null) { TaskManager.WriteWarning("Account not found"); return null; } // compare user passwords if ((CryptoUtils.SHA1(user.Password) == password) || (user.Password == password)) return new UserInfo(user); return null; } catch (Exception ex) { throw TaskManager.WriteError(ex); } finally { TaskManager.CompleteTask(); } } public static int ChangeUserPassword(string username, string oldPassword, string newPassword, string ip) { // place log record TaskManager.StartTask("USER", "CHANGE_PASSWORD_BY_USERNAME_PASSWORD", username); TaskManager.WriteParameter("IP", ip); try { UserInfo user = GetUserByUsernamePassword(username, oldPassword, ip); if (user == null) { TaskManager.WriteWarning("Account not found"); return BusinessErrorCodes.ERROR_USER_NOT_FOUND; } // change password DataProvider.ChangeUserPassword(-1, user.UserId, CryptoUtils.Encrypt(newPassword)); return 0; } catch (Exception ex) { throw TaskManager.WriteError(ex); } finally { TaskManager.CompleteTask(); } } public static int SendPasswordReminder(string username, string ip) { // place log record TaskManager.StartTask("USER", "SEND_REMINDER", username); TaskManager.WriteParameter("IP", ip); try { // try to get user from database UserInfoInternal user = GetUserInternally(username); if (user == null) { TaskManager.WriteWarning("Account not found"); // Fix for item #273 (NGS-9) //return BusinessErrorCodes.ERROR_USER_NOT_FOUND; return 0; } UserSettings settings = UserController.GetUserSettings(user.UserId, UserSettings.PASSWORD_REMINDER_LETTER); string from = settings["From"]; string cc = settings["CC"]; string subject = settings["Subject"]; string body = user.HtmlMail ? settings["HtmlBody"] : settings["TextBody"]; bool isHtml = user.HtmlMail; MailPriority priority = MailPriority.Normal; if (!String.IsNullOrEmpty(settings["Priority"])) priority = (MailPriority)Enum.Parse(typeof(MailPriority), settings["Priority"], true); if (body == null || body == "") return BusinessErrorCodes.ERROR_SETTINGS_PASSWORD_LETTER_EMPTY_BODY; // One Time Password feature user.Password = OneTimePasswordHelper.SetOneTimePassword(user.UserId); // set template context items Hashtable items = new Hashtable(); items["user"] = user; items["Email"] = true; // get reseller details UserInfoInternal reseller = UserController.GetUser(user.OwnerId); if (reseller != null) { items["reseller"] = new UserInfo(reseller); } subject = PackageController.EvaluateTemplate(subject, items); body = PackageController.EvaluateTemplate(body, items); // send message MailHelper.SendMessage(from, user.Email, cc, subject, body, priority, isHtml); return 0; } catch (Exception ex) { throw TaskManager.WriteError(ex); } finally { TaskManager.CompleteTask(); } } internal static UserInfoInternal GetUserInternally(int userId) { return GetUser(DataProvider.GetUserByIdInternally(userId)); } internal static UserInfoInternal GetUserInternally(string username) { return GetUser(DataProvider.GetUserByUsernameInternally(username)); } public static UserInfoInternal GetUser(int userId) { return GetUser(DataProvider.GetUserById(SecurityContext.User.UserId, userId)); } public static UserInfoInternal GetUser(string username) { return GetUser(DataProvider.GetUserByUsername(SecurityContext.User.UserId, username)); } private static UserInfoInternal GetUser(IDataReader reader) { // try to get user from database UserInfoInternal user = ObjectUtils.FillObjectFromDataReader<UserInfoInternal>(reader); if (user != null) { user.Password = CryptoUtils.Decrypt(user.Password); } return user; } public static List<UserInfo> GetUserParents(int userId) { // get users from database DataSet dsUsers = DataProvider.GetUserParents(SecurityContext.User.UserId, userId); // convert to arraylist List<UserInfo> users = new List<UserInfo>(); ObjectUtils.FillCollectionFromDataSet<UserInfo>(users, dsUsers); return users; } public static List<UserInfo> GetUsers(int userId, bool recursive) { // get users from database DataSet dsUsers = DataProvider.GetUsers(SecurityContext.User.UserId, userId, recursive); // convert to arraylist List<UserInfo> users = new List<UserInfo>(); ObjectUtils.FillCollectionFromDataSet<UserInfo>(users, dsUsers); return users; } public static DataSet GetUsersPaged(int userId, string filterColumn, string filterValue, int statusId, int roleId, string sortColumn, int startRow, int maximumRows) { // get users from database return DataProvider.GetUsersPaged(SecurityContext.User.UserId, userId, filterColumn, filterValue, statusId, roleId, sortColumn, startRow, maximumRows, false); } public static DataSet GetUsersPagedRecursive(int userId, string filterColumn, string filterValue, int statusId, int roleId, string sortColumn, int startRow, int maximumRows) { // get users from database return DataProvider.GetUsersPaged(SecurityContext.User.UserId, userId, filterColumn, filterValue, statusId, roleId, sortColumn, startRow, maximumRows, true); } public static DataSet GetUsersSummary(int userId) { return DataProvider.GetUsersSummary(SecurityContext.User.UserId, userId); } public static DataSet GetUserDomainsPaged(int userId, string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows) { // get users from database return DataProvider.GetUserDomainsPaged(SecurityContext.User.UserId, userId, filterColumn, filterValue, sortColumn, startRow, maximumRows); } public static List<UserInfo> GetUserPeers(int userId) { // get user peers from database return ObjectUtils.CreateListFromDataSet<UserInfo>(GetRawUserPeers(userId)); } public static DataSet GetRawUserPeers(int userId) { // get user peers from database return DataProvider.GetUserPeers(SecurityContext.User.UserId, userId); } public static DataSet GetRawUsers(int ownerId, bool recursive) { // get users from database return DataProvider.GetUsers(SecurityContext.User.UserId, ownerId, recursive); } public static int AddUser(UserInfo user, bool sendLetter, string password) { // check account int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo); if (accountCheck < 0) return accountCheck; string pattern = @"[\\/:*?<>|""]+"; if (String.IsNullOrEmpty(user.Username)) return BusinessErrorCodes.ERROR_INVALID_USER_NAME; if (Regex.IsMatch(user.Username, pattern)) return BusinessErrorCodes.ERROR_INVALID_USER_NAME; if (UserExists(user.Username)) return BusinessErrorCodes.ERROR_USER_ALREADY_EXISTS; // only administrators can set admin role if (!SecurityContext.User.IsInRole(SecurityContext.ROLE_ADMINISTRATOR) && user.Role == UserRole.Administrator) user.Role = UserRole.User; // check integrity when creating a user account if (user.Role == UserRole.User) user.EcommerceEnabled = false; // place log record TaskManager.StartTask("USER", "ADD", user.Username); try { // add user to database int userId = DataProvider.AddUser( SecurityContext.User.UserId, user.OwnerId, user.RoleId, user.StatusId, user.SubscriberNumber, user.LoginStatusId, user.IsDemo, user.IsPeer, user.Comments, user.Username.Trim(), CryptoUtils.Encrypt(password), user.FirstName, user.LastName, user.Email, user.SecondaryEmail, user.Address, user.City, user.Country, user.State, user.Zip, user.PrimaryPhone, user.SecondaryPhone, user.Fax, user.InstantMessenger, user.HtmlMail, user.CompanyName, user.EcommerceEnabled); if (userId == -1) { TaskManager.WriteWarning("Account with such username already exists"); return BusinessErrorCodes.ERROR_USER_ALREADY_EXISTS; } BackgroundTask topTask = TaskManager.TopTask; topTask.ItemId = userId; topTask.UpdateParamValue("SendLetter", sendLetter); TaskController.UpdateTaskWithParams(topTask); return userId; } catch (Exception ex) { throw TaskManager.WriteError(ex); } finally { TaskManager.CompleteTask(); } } const string userAdditionalParamsTemplate = @"<Params><VLans/></Params>"; public static void AddUserVLan(int userId, UserVlan vLan) { UserInfo user = GetUser(userId); // if (user == null) throw new ApplicationException(String.Format("User with UserID={0} not found", userId)); XDocument doc = XDocument.Parse(user.AdditionalParams ?? userAdditionalParamsTemplate); XElement vlans = doc.Root.Element("VLans"); vlans.Add(new XElement("VLan", new XAttribute("VLanID", vLan.VLanID), new XAttribute("Comment", vLan.Comment))); user.AdditionalParams = doc.ToString(); UpdateUser(user); } public static void DeleteUserVLan(int userId, ushort vLanId) { UserInfo user = GetUser(userId); // if (user == null) throw new ApplicationException(String.Format("User with UserID={0} not found", userId)); XDocument doc = XDocument.Parse(user.AdditionalParams ?? userAdditionalParamsTemplate); XElement vlans = doc.Root.Element("VLans"); if (vlans != null) foreach (XElement element in vlans.Elements("VLan")) if (ushort.Parse(element.Attribute("VLanID").Value) == vLanId) element.Remove(); user.AdditionalParams = doc.ToString(); UpdateUser(user); } public static int UpdateUser(UserInfo user) { return UpdateUser(null, user); } public static int UpdateUserAsync(string taskId, UserInfo user) { UserAsyncWorker usersWorker = new UserAsyncWorker(); usersWorker.ThreadUserId = SecurityContext.User.UserId; usersWorker.TaskId = taskId; usersWorker.User = user; usersWorker.UpdateUserAsync(); return 0; } public static int UpdateUser(string taskId, UserInfo user) { try { // start task TaskManager.StartTask(taskId, "USER", "UPDATE", user.Username, user.UserId); // check account int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo); if (accountCheck < 0) return accountCheck; UserInfo currentUser = GetUser(user.UserId); //prevent downgrade reseller with child accounts to user role if (currentUser.RoleId.Equals(2)) { if (user.RoleId.Equals(3)) { // check if user has child accounts (It happens when Reseller has child accounts and admin changes his role to User) if (GetUsers(currentUser.UserId, false).Count > 0) return BusinessErrorCodes.ERROR_USER_HAS_USERS; } } // only administrators can set admin role if (!SecurityContext.User.IsInRole(SecurityContext.ROLE_ADMINISTRATOR) && user.Role == UserRole.Administrator) user.Role = UserRole.User; // check integrity when creating a user account if (user.Role == UserRole.User) user.EcommerceEnabled = false; //// task progress //int maxSteps = 100; //TaskManager.IndicatorMaximum = maxSteps; //for (int i = 0; i < maxSteps; i++) //{ // TaskManager.Write(String.Format("Step {0} of {1}", i, maxSteps)); // TaskManager.IndicatorCurrent = i; // System.Threading.Thread.Sleep(1000); //} DataProvider.UpdateUser( SecurityContext.User.UserId, user.UserId, user.RoleId, user.StatusId, user.SubscriberNumber, user.LoginStatusId, user.IsDemo, user.IsPeer, user.Comments, user.FirstName, user.LastName, user.Email, user.SecondaryEmail, user.Address, user.City, user.Country, user.State, user.Zip, user.PrimaryPhone, user.SecondaryPhone, user.Fax, user.InstantMessenger, user.HtmlMail, user.CompanyName, user.EcommerceEnabled, user.AdditionalParams); return 0; } catch (System.Threading.ThreadAbortException ex) { TaskManager.WriteError(ex, "The process has been terminated by the user."); return 0; } catch (Exception ex) { throw TaskManager.WriteError(ex); } finally { TaskManager.CompleteTask(); } } public static int DeleteUser(int userId) { return DeleteUser(null, userId); } public static int DeleteUser(string taskId, int userId) { // check account int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo); if (accountCheck < 0) return accountCheck; // check if user has child accounts if (GetUsers(userId, false).Count > 0) return BusinessErrorCodes.ERROR_USER_HAS_USERS; UserAsyncWorker userWorker = new UserAsyncWorker(); userWorker.ThreadUserId = SecurityContext.User.UserId; userWorker.UserId = userId; userWorker.TaskId = taskId; userWorker.DeleteUserAsync(); return 0; } public static int ChangeUserPassword(int userId, string password) { // check account int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo); if (accountCheck < 0) return accountCheck; // get user details UserInfo user = GetUserInternally(userId); // place log record TaskManager.StartTask("USER", "CHANGE_PASSWORD", user.Username, user.UserId); try { DataProvider.ChangeUserPassword(SecurityContext.User.UserId, userId, CryptoUtils.Encrypt(password)); return 0; } catch (Exception ex) { throw TaskManager.WriteError(ex); } finally { TaskManager.CompleteTask(); } } public static int ChangeUserStatus(int userId, UserStatus status) { return ChangeUserStatus(null, userId, status); } public static int ChangeUserStatus(string taskId, int userId, UserStatus status) { // check account int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo); if (accountCheck < 0) return accountCheck; int result = 0; // get user details UserInfo user = GetUserInternally(userId); // place log record TaskManager.StartTask(taskId, "USER", "CHANGE_STATUS", user.Username, user.UserId); // update user packages List<PackageInfo> packages = new List<PackageInfo>(); // Add the users package(s) packages.AddRange(PackageController.GetPackages(userId)); try { // change this account result = ChangeUserStatusInternal(userId, status); if (result < 0) return result; // change peer accounts List<UserInfo> peers = GetUserPeers(userId); foreach (UserInfo peer in peers) { result = ChangeUserStatusInternal(peer.UserId, status); if (result < 0) return result; } // change child accounts List<UserInfo> children = GetUsers(userId, true); foreach (UserInfo child in children) { // Add the child users packages packages.AddRange(PackageController.GetPackages(child.UserId)); // change child user peers List<UserInfo> childPeers = GetUserPeers(child.UserId); foreach (UserInfo peer in childPeers) { result = ChangeUserStatusInternal(peer.UserId, status); if (result < 0) return result; } // change child account result = ChangeUserStatusInternal(child.UserId, status); if (result < 0) return result; } PackageStatus packageStatus = PackageStatus.Active; switch (status) { case UserStatus.Active: packageStatus = PackageStatus.Active; break; case UserStatus.Cancelled: packageStatus = PackageStatus.Cancelled; break; case UserStatus.Pending: packageStatus = PackageStatus.New; break; case UserStatus.Suspended: packageStatus = PackageStatus.Suspended; break; } // change packages state result = PackageController.ChangePackagesStatus(packages, packageStatus, true); if (result < 0) return result; return 0; } catch (Exception ex) { throw TaskManager.WriteError(ex); } finally { TaskManager.CompleteTask(); } } private static int ChangeUserStatusInternal(int userId, UserStatus status) { // get user details UserInfo user = GetUser(userId); if (user != null && user.Status != status) { // change status user.Status = status; // save user UpdateUser(user); } return 0; } #region User Settings public static UserSettings GetUserSettings(int userId, string settingsName) { IDataReader reader = DataProvider.GetUserSettings( SecurityContext.User.UserId, userId, settingsName); UserSettings settings = new UserSettings(); settings.UserId = userId; settings.SettingsName = settingsName; while (reader.Read()) { settings.UserId = (int)reader["UserID"]; settings[(string)reader["PropertyName"]] = (string)reader["PropertyValue"]; } reader.Close(); return settings; } public static int UpdateUserSettings(UserSettings settings) { // check account int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo); if (accountCheck < 0) return accountCheck; // get user details UserInfo user = GetUserInternally(settings.UserId); // place log record TaskManager.StartTask("USER", "UPDATE_SETTINGS", user.Username, user.UserId); try { // build xml XmlDocument doc = new XmlDocument(); XmlElement nodeProps = doc.CreateElement("properties"); if (settings.SettingsArray != null) { foreach (string[] pair in settings.SettingsArray) { XmlElement nodeProp = doc.CreateElement("property"); nodeProp.SetAttribute("name", pair[0]); nodeProp.SetAttribute("value", pair[1]); nodeProps.AppendChild(nodeProp); } } string xml = nodeProps.OuterXml; // update settings DataProvider.UpdateUserSettings(SecurityContext.User.UserId, settings.UserId, settings.SettingsName, xml); return 0; } catch (Exception ex) { throw TaskManager.WriteError(ex); } finally { TaskManager.CompleteTask(); } } #endregion } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using NUnit.Framework; using QuantConnect.Data; using QuantConnect.Util; using QuantConnect.Algorithm; using System.Collections.Generic; using QuantConnect.Lean.Engine.DataFeeds; using QuantConnect.Data.UniverseSelection; using QuantConnect.Tests.Engine.DataFeeds; using QuantConnect.Data.Custom.AlphaStreams; using QuantConnect.Lean.Engine.HistoricalData; using QuantConnect.Algorithm.Framework.Alphas; using QuantConnect.Algorithm.Framework.Portfolio; using QuantConnect.Tests.Common.Data.UniverseSelection; namespace QuantConnect.Tests.Algorithm.Framework.Portfolio { [TestFixture] public class EqualWeightingAlphaStreamsPortfolioConstructionModelTests { private ZipDataCacheProvider _cacheProvider; private QCAlgorithm _algorithm; [SetUp] public virtual void SetUp() { _algorithm = new QCAlgorithm(); var historyProvider = new SubscriptionDataReaderHistoryProvider(); _cacheProvider = new ZipDataCacheProvider(TestGlobals.DataProvider); historyProvider.Initialize(new HistoryProviderInitializeParameters(null, null, TestGlobals.DataProvider, _cacheProvider, TestGlobals.MapFileProvider, TestGlobals.FactorFileProvider, null, true, new DataPermissionManager())); _algorithm.SetHistoryProvider(historyProvider); _algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(_algorithm)); _algorithm.Settings.FreePortfolioValue = 0; _algorithm.SetFinishedWarmingUp(); } [TearDown] public virtual void TearDown() { _cacheProvider.DisposeSafely(); } [TestCase(Language.CSharp)] public void NoTargets(Language language) { SetPortfolioConstruction(language); var targets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, Array.Empty<Insight>()).ToList(); Assert.AreEqual(0, targets.Count); } [TestCase(Language.CSharp)] public void IgnoresInsights(Language language) { SetPortfolioConstruction(language); var insight = Insight.Price(Symbols.AAPL, Resolution.Minute, 1, InsightDirection.Down, 1, 1, "AlphaId", 0.5); insight.GeneratedTimeUtc = _algorithm.UtcTime; insight.CloseTimeUtc = _algorithm.UtcTime.Add(insight.Period); var targets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, new[] { insight }).ToList(); Assert.AreEqual(0, targets.Count); } [TestCase(Language.CSharp)] public void SingleAlphaSinglePosition(Language language) { SetPortfolioConstruction(language); var alpha = _algorithm.AddData<AlphaStreamsPortfolioState>("9fc8ef73792331b11dbd5429a").Symbol; var data = _algorithm.History<AlphaStreamsPortfolioState>(alpha, TimeSpan.FromDays(2)).Last(); AddSecurities(_algorithm, data); _algorithm.SetCurrentSlice(new Slice(_algorithm.UtcTime, new List<BaseData> { data })); var targets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, Array.Empty<Insight>()).ToList(); Assert.AreEqual(1, targets.Count); var position = data.PositionGroups.Single().Positions.Single(); Assert.AreEqual(position.Symbol, targets.Single().Symbol); Assert.AreEqual(position.Quantity, targets.Single().Quantity); } [TestCase(Language.CSharp)] public void SingleAlphaMultiplePositions(Language language) { SetPortfolioConstruction(language); var alpha = _algorithm.AddData<AlphaStreamsPortfolioState>("9fc8ef73792331b11dbd5429a").Symbol; var data = _algorithm.History<AlphaStreamsPortfolioState>(alpha, TimeSpan.FromDays(1)).ToList()[0]; AddSecurities(_algorithm, data); _algorithm.SetCurrentSlice(new Slice(_algorithm.UtcTime, new List<BaseData> { data })); var targets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, Array.Empty<Insight>()).ToList(); Assert.AreEqual(2, targets.Count); Assert.AreEqual(600, targets.Single(target => target.Symbol == Symbols.GOOG).Quantity); var option = Symbol.CreateOption(Symbols.GOOG, Market.USA, OptionStyle.American, OptionRight.Call, 750, new DateTime(2016, 6, 17)); Assert.AreEqual(-5, targets.Single(target => target.Symbol == option).Quantity); } [TestCase(Language.CSharp)] public void SingleAlphaPositionRemoval(Language language) { SetPortfolioConstruction(language); var alpha = _algorithm.AddData<AlphaStreamsPortfolioState>("9fc8ef73792331b11dbd5429a").Symbol; var data = _algorithm.History<AlphaStreamsPortfolioState>(alpha, TimeSpan.FromDays(2)).Last(); AddSecurities(_algorithm, data); var position = data.PositionGroups.Single().Positions.Single(); _algorithm.SetCurrentSlice(new Slice(_algorithm.UtcTime, new List<BaseData> { data })); var targets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, Array.Empty<Insight>()).ToList(); Assert.AreEqual(1, targets.Count); Assert.AreEqual(position.Symbol, targets.Single().Symbol); Assert.AreEqual(position.Quantity, targets.Single().Quantity); _algorithm.SetCurrentSlice(new Slice(_algorithm.UtcTime, new List<BaseData> { new AlphaStreamsPortfolioState { Symbol = alpha } })); targets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, Array.Empty<Insight>()).ToList(); Assert.AreEqual(1, targets.Count); Assert.AreEqual(position.Symbol, targets.Single().Symbol); Assert.AreEqual(0, targets.Single().Quantity); // no new targets targets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, Array.Empty<Insight>()).ToList(); Assert.AreEqual(0, targets.Count); } [TestCase(Language.CSharp, 1000000, 10000, 0)] [TestCase(Language.CSharp, 10000, 1000000, 0)] [TestCase(Language.CSharp, 10000, 10000, 0)] [TestCase(Language.CSharp, 100000, 100000, 0)] [TestCase(Language.CSharp, 1000000, 1000000, 0)] [TestCase(Language.CSharp, 1000000, 10000, 5000)] [TestCase(Language.CSharp, 10000, 1000000, 5000)] [TestCase(Language.CSharp, 10000, 10000, 5000)] [TestCase(Language.CSharp, 100000, 100000, 5000)] [TestCase(Language.CSharp, 1000000, 1000000, 5000)] public void MultipleAlphaPositionAggregation(Language language, decimal totalPortfolioValueAlpha1, decimal totalPortfolioValueAlpha2, decimal freePortfolioValue) { SetPortfolioConstruction(language); _algorithm.Settings.FreePortfolioValue = freePortfolioValue; var alpha1 = _algorithm.AddData<AlphaStreamsPortfolioState>("9fc8ef73792331b11dbd5429a"); var alpha2 = _algorithm.AddData<AlphaStreamsPortfolioState>("623b06b231eb1cc1aa3643a46"); _algorithm.OnFrameworkSecuritiesChanged(SecurityChangesTests.AddedNonInternal(alpha1, alpha2)); var symbol = alpha1.Symbol; var symbol2 = alpha2.Symbol; var data = _algorithm.History<AlphaStreamsPortfolioState>(symbol, TimeSpan.FromDays(1)).Last(); AddSecurities(_algorithm, data); data.TotalPortfolioValue = totalPortfolioValueAlpha1; var position = data.PositionGroups.Single().Positions.Single(); var data2 = (AlphaStreamsPortfolioState)data.Clone(); data2.Symbol = symbol2; data2.TotalPortfolioValue = totalPortfolioValueAlpha2; data2.PositionGroups = new List<PositionGroupState> { new PositionGroupState { Positions = new List<PositionState> { new PositionState { Quantity = position.Quantity * -10, Symbol = position.Symbol, UnitQuantity = 1 } }} }; _algorithm.SetCurrentSlice(new Slice(_algorithm.UtcTime, new List<BaseData> { data, data2 })); var targets = _algorithm.PortfolioConstruction.CreateTargets(_algorithm, Array.Empty<Insight>()).ToList(); Assert.AreEqual(1, targets.Count); Assert.AreEqual(position.Symbol, targets.Single().Symbol); var tvpPerAlpha = (_algorithm.Portfolio.TotalPortfolioValue - freePortfolioValue) * 0.5m; var alpha1Weight = tvpPerAlpha / data.TotalPortfolioValue; var alpha2Weight = tvpPerAlpha / data2.TotalPortfolioValue; Assert.AreEqual((position.Quantity * alpha1Weight).DiscretelyRoundBy(1, MidpointRounding.ToZero) + (position.Quantity * -10m * alpha2Weight).DiscretelyRoundBy(1, MidpointRounding.ToZero), targets.Single().Quantity); } private void AddSecurities(QCAlgorithm algorithm, AlphaStreamsPortfolioState portfolioState) { foreach (var symbol in portfolioState.PositionGroups?.SelectMany(positionGroup => positionGroup.Positions) .Select(state => state.Symbol) ?? Enumerable.Empty<Symbol>()) { _algorithm.AddSecurity(symbol); } } private void SetUtcTime(DateTime dateTime) => _algorithm.SetDateTime(dateTime.ConvertToUtc(_algorithm.TimeZone)); private void SetPortfolioConstruction(Language language) { _algorithm.SetCurrentSlice(null); IPortfolioConstructionModel model; if (language == Language.CSharp) { model = new EqualWeightingAlphaStreamsPortfolioConstructionModel(); } else { throw new NotImplementedException($"{language} not implemented"); } _algorithm.SetPortfolioConstruction(model); foreach (var kvp in _algorithm.Portfolio) { kvp.Value.SetHoldings(kvp.Value.Price, 0); } _algorithm.Portfolio.SetCash(100000); SetUtcTime(new DateTime(2018, 4, 5)); var changes = SecurityChangesTests.AddedNonInternal(_algorithm.Securities.Values.ToArray()); _algorithm.PortfolioConstruction.OnSecuritiesChanged(_algorithm, changes); } } }
/* ==================================================================== 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 TestCases.SS.Formula.Functions { using NPOI.SS.Formula.Eval; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using System; using NUnit.Framework; /** * Tests for the INDIRECT() function.</p> * * @author Josh Micich */ [TestFixture] public class TestIndirect { // convenient access to namespace //private static ErrorEval EE = null; private static void CreateDataRow(ISheet sheet, int rowIndex, params double[] vals) { IRow row = sheet.CreateRow(rowIndex); for (int i = 0; i < vals.Length; i++) { row.CreateCell(i).SetCellValue(vals[i]); } } private static HSSFWorkbook CreateWBA() { HSSFWorkbook wb = new HSSFWorkbook(); ISheet sheet1 = wb.CreateSheet("Sheet1"); ISheet sheet2 = wb.CreateSheet("Sheet2"); ISheet sheet3 = wb.CreateSheet("John's sales"); CreateDataRow(sheet1, 0, 11, 12, 13, 14); CreateDataRow(sheet1, 1, 21, 22, 23, 24); CreateDataRow(sheet1, 2, 31, 32, 33, 34); CreateDataRow(sheet2, 0, 50, 55, 60, 65); CreateDataRow(sheet2, 1, 51, 56, 61, 66); CreateDataRow(sheet2, 2, 52, 57, 62, 67); CreateDataRow(sheet3, 0, 30, 31, 32); CreateDataRow(sheet3, 1, 33, 34, 35); IName name1 = wb.CreateName(); name1.NameName = ("sales1"); name1.RefersToFormula = ("Sheet1!A1:D1"); IName name2 = wb.CreateName(); name2.NameName = ("sales2"); name2.RefersToFormula = ("Sheet2!B1:C3"); IRow row = sheet1.CreateRow(3); row.CreateCell(0).SetCellValue("sales1"); //A4 row.CreateCell(1).SetCellValue("sales2"); //B4 return wb; } private static HSSFWorkbook CreateWBB() { HSSFWorkbook wb = new HSSFWorkbook(); ISheet sheet1 = wb.CreateSheet("Sheet1"); ISheet sheet2 = wb.CreateSheet("Sheet2"); ISheet sheet3 = wb.CreateSheet("## Look here!"); CreateDataRow(sheet1, 0, 400, 440, 480, 520); CreateDataRow(sheet1, 1, 420, 460, 500, 540); CreateDataRow(sheet2, 0, 50, 55, 60, 65); CreateDataRow(sheet2, 1, 51, 56, 61, 66); CreateDataRow(sheet3, 0, 42); return wb; } [Test] public void TestBasic() { HSSFWorkbook wbA = CreateWBA(); ICell c = wbA.GetSheetAt(0).CreateRow(5).CreateCell(2); HSSFFormulaEvaluator feA = new HSSFFormulaEvaluator(wbA); // non-error cases Confirm(feA, c, "INDIRECT(\"C2\")", 23); Confirm(feA, c, "INDIRECT(\"$C2\")", 23); Confirm(feA, c, "INDIRECT(\"C$2\")", 23); Confirm(feA, c, "SUM(INDIRECT(\"Sheet2!B1:C3\"))", 351); // area ref Confirm(feA, c, "SUM(INDIRECT(\"Sheet2! B1 : C3 \"))", 351); // spaces in area ref Confirm(feA, c, "SUM(INDIRECT(\"'John''s sales'!A1:C1\"))", 93); // special chars in sheet name Confirm(feA, c, "INDIRECT(\"'Sheet1'!B3\")", 32); // redundant sheet name quotes Confirm(feA, c, "INDIRECT(\"sHeet1!B3\")", 32); // case-insensitive sheet name Confirm(feA, c, "INDIRECT(\" D3 \")", 34); // spaces around cell ref Confirm(feA, c, "INDIRECT(\"Sheet1! D3 \")", 34); // spaces around cell ref Confirm(feA, c, "INDIRECT(\"A1\", TRUE)", 11); // explicit arg1. only TRUE supported so far Confirm(feA, c, "INDIRECT(\"A1:G1\")", 13); // de-reference area ref (note formula is in C4) Confirm(feA, c, "SUM(INDIRECT(A4))", 50); // indirect defined name Confirm(feA, c, "SUM(INDIRECT(B4))", 351); // indirect defined name pointinh to other sheet // simple error propagation: // arg0 is Evaluated to text first Confirm(feA, c, "INDIRECT(#DIV/0!)", ErrorEval.DIV_ZERO); Confirm(feA, c, "INDIRECT(#DIV/0!)", ErrorEval.DIV_ZERO); Confirm(feA, c, "INDIRECT(#NAME?, \"x\")", ErrorEval.NAME_INVALID); Confirm(feA, c, "INDIRECT(#NUM!, #N/A)", ErrorEval.NUM_ERROR); // arg1 is Evaluated to bool before arg0 is decoded Confirm(feA, c, "INDIRECT(\"garbage\", #N/A)", ErrorEval.NA); Confirm(feA, c, "INDIRECT(\"garbage\", \"\")", ErrorEval.VALUE_INVALID); // empty string is not valid bool Confirm(feA, c, "INDIRECT(\"garbage\", \"flase\")", ErrorEval.VALUE_INVALID); // must be "TRUE" or "FALSE" // spaces around sheet name (with or without quotes Makes no difference) Confirm(feA, c, "INDIRECT(\"'Sheet1 '!D3\")", ErrorEval.REF_INVALID); Confirm(feA, c, "INDIRECT(\" Sheet1!D3\")", ErrorEval.REF_INVALID); Confirm(feA, c, "INDIRECT(\"'Sheet1' !D3\")", ErrorEval.REF_INVALID); Confirm(feA, c, "SUM(INDIRECT(\"'John's sales'!A1:C1\"))", ErrorEval.REF_INVALID); // bad quote escaping Confirm(feA, c, "INDIRECT(\"[Book1]Sheet1!A1\")", ErrorEval.REF_INVALID); // unknown external workbook Confirm(feA, c, "INDIRECT(\"Sheet3!A1\")", ErrorEval.REF_INVALID); // unknown sheet #if !HIDE_UNREACHABLE_CODE if (false) { // TODO - support Evaluation of defined names Confirm(feA, c, "INDIRECT(\"Sheet1!IW1\")", ErrorEval.REF_INVALID); // bad column Confirm(feA, c, "INDIRECT(\"Sheet1!A65537\")", ErrorEval.REF_INVALID); // bad row } #endif Confirm(feA, c, "INDIRECT(\"Sheet1!A 1\")", ErrorEval.REF_INVALID); // space in cell ref } [Test] public void TestMultipleWorkbooks() { HSSFWorkbook wbA = CreateWBA(); ICell cellA = wbA.GetSheetAt(0).CreateRow(10).CreateCell(0); HSSFFormulaEvaluator feA = new HSSFFormulaEvaluator(wbA); HSSFWorkbook wbB = CreateWBB(); ICell cellB = wbB.GetSheetAt(0).CreateRow(10).CreateCell(0); HSSFFormulaEvaluator feB = new HSSFFormulaEvaluator(wbB); String[] workbookNames = { "MyBook", "Figures for January", }; HSSFFormulaEvaluator[] Evaluators = { feA, feB, }; HSSFFormulaEvaluator.SetupEnvironment(workbookNames, Evaluators); Confirm(feB, cellB, "INDIRECT(\"'[Figures for January]## Look here!'!A1\")", 42); // same wb Confirm(feA, cellA, "INDIRECT(\"'[Figures for January]## Look here!'!A1\")", 42); // across workbooks // 2 level recursion Confirm(feB, cellB, "INDIRECT(\"[MyBook]Sheet2!A1\")", 50); // Set up (and Check) first level Confirm(feA, cellA, "INDIRECT(\"'[Figures for January]Sheet1'!A11\")", 50); // points to cellB } private static void Confirm(IFormulaEvaluator fe, ICell cell, String formula, double expectedResult) { fe.ClearAllCachedResultValues(); cell.CellFormula = (formula); CellValue cv = fe.Evaluate(cell); if (cv.CellType != CellType.Numeric) { throw new AssertionException("expected numeric cell type but got " + cv.FormatAsString()); } Assert.AreEqual(expectedResult, cv.NumberValue, 0.0); } private static void Confirm(IFormulaEvaluator fe, ICell cell, String formula, ErrorEval expectedResult) { fe.ClearAllCachedResultValues(); cell.CellFormula=(formula); CellValue cv = fe.Evaluate(cell); if (cv.CellType != CellType.Error) { throw new AssertionException("expected error cell type but got " + cv.FormatAsString()); } int expCode = expectedResult.ErrorCode; if (cv.ErrorValue != expCode) { throw new AssertionException("Expected error '" + ErrorEval.GetText(expCode) + "' but got '" + cv.FormatAsString() + "'."); } } } }
// 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.Security.Cryptography { using System.IO; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] public abstract class HashAlgorithm : IDisposable, ICryptoTransform { protected int HashSizeValue; protected internal byte[] HashValue; protected int State = 0; private bool m_bDisposed = false; protected HashAlgorithm() {} // // public properties // public virtual int HashSize { get { return HashSizeValue; } } public virtual byte[] Hash { get { if (m_bDisposed) throw new ObjectDisposedException(null); if (State != 0) throw new CryptographicUnexpectedOperationException(Environment.GetResourceString("Cryptography_HashNotYetFinalized")); return (byte[]) HashValue.Clone(); } } // // public methods // static public HashAlgorithm Create() { return Create("System.Security.Cryptography.HashAlgorithm"); } static public HashAlgorithm Create(String hashName) { return (HashAlgorithm) CryptoConfig.CreateFromName(hashName); } public byte[] ComputeHash(Stream inputStream) { if (m_bDisposed) throw new ObjectDisposedException(null); // Default the buffer size to 4K. byte[] buffer = new byte[4096]; int bytesRead; do { bytesRead = inputStream.Read(buffer, 0, 4096); if (bytesRead > 0) { HashCore(buffer, 0, bytesRead); } } while (bytesRead > 0); HashValue = HashFinal(); byte[] Tmp = (byte[]) HashValue.Clone(); Initialize(); return(Tmp); } public byte[] ComputeHash(byte[] buffer) { if (m_bDisposed) throw new ObjectDisposedException(null); // Do some validation if (buffer == null) throw new ArgumentNullException("buffer"); HashCore(buffer, 0, buffer.Length); HashValue = HashFinal(); byte[] Tmp = (byte[]) HashValue.Clone(); Initialize(); return(Tmp); } public byte[] ComputeHash(byte[] buffer, int offset, int count) { // Do some validation if (buffer == null) throw new ArgumentNullException("buffer"); if (offset < 0) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0 || (count > buffer.Length)) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue")); if ((buffer.Length - count) < offset) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); if (m_bDisposed) throw new ObjectDisposedException(null); HashCore(buffer, offset, count); HashValue = HashFinal(); byte[] Tmp = (byte[]) HashValue.Clone(); Initialize(); return(Tmp); } // ICryptoTransform methods // we assume any HashAlgorithm can take input a byte at a time public virtual int InputBlockSize { get { return(1); } } public virtual int OutputBlockSize { get { return(1); } } public virtual bool CanTransformMultipleBlocks { get { return(true); } } public virtual bool CanReuseTransform { get { return(true); } } // We implement TransformBlock and TransformFinalBlock here public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { // Do some validation, we let BlockCopy do the destination array validation if (inputBuffer == null) throw new ArgumentNullException("inputBuffer"); if (inputOffset < 0) throw new ArgumentOutOfRangeException("inputOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (inputCount < 0 || (inputCount > inputBuffer.Length)) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue")); if ((inputBuffer.Length - inputCount) < inputOffset) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); if (m_bDisposed) throw new ObjectDisposedException(null); // Change the State value State = 1; HashCore(inputBuffer, inputOffset, inputCount); if ((outputBuffer != null) && ((inputBuffer != outputBuffer) || (inputOffset != outputOffset))) Buffer.BlockCopy(inputBuffer, inputOffset, outputBuffer, outputOffset, inputCount); return inputCount; } public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { // Do some validation if (inputBuffer == null) throw new ArgumentNullException("inputBuffer"); if (inputOffset < 0) throw new ArgumentOutOfRangeException("inputOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (inputCount < 0 || (inputCount > inputBuffer.Length)) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue")); if ((inputBuffer.Length - inputCount) < inputOffset) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); if (m_bDisposed) throw new ObjectDisposedException(null); HashCore(inputBuffer, inputOffset, inputCount); HashValue = HashFinal(); byte[] outputBytes; if (inputCount != 0) { outputBytes = new byte[inputCount]; Buffer.InternalBlockCopy(inputBuffer, inputOffset, outputBytes, 0, inputCount); } else { outputBytes = EmptyArray<Byte>.Value; } // reset the State value State = 0; return outputBytes; } // IDisposable methods // To keep mscorlib compatibility with Orcas, CoreCLR's HashAlgorithm has an explicit IDisposable // implementation. Post-Orcas the desktop has an implicit IDispoable implementation. #if FEATURE_CORECLR void IDisposable.Dispose() { Dispose(); } #endif // FEATURE_CORECLR public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public void Clear() { (this as IDisposable).Dispose(); } protected virtual void Dispose(bool disposing) { if (disposing) { if (HashValue != null) Array.Clear(HashValue, 0, HashValue.Length); HashValue = null; m_bDisposed = true; } } // // abstract public methods // public abstract void Initialize(); protected abstract void HashCore(byte[] array, int ibStart, int cbSize); protected abstract byte[] HashFinal(); } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.Collections.Generic; using System.Reflection; using log4net; using Nini.Config; using OpenSim.Framework; using OpenMetaverse; namespace OpenSim.Region.Physics.Manager { public delegate void physicsCrash(); public delegate void RaycastCallback(bool hitYN, Vector3 collisionPoint, uint localid, float distance, Vector3 normal); public delegate void RayCallback(List<ContactResult> list); public delegate void JointMoved(PhysicsJoint joint); public delegate void JointDeactivated(PhysicsJoint joint); public delegate void JointErrorMessage(PhysicsJoint joint, string message); // this refers to an "error message due to a problem", not "amount of joint constraint violation" public enum RayFilterFlags : ushort { // the flags water = 0x01, land = 0x02, agent = 0x04, nonphysical = 0x08, physical = 0x10, phantom = 0x20, volumedtc = 0x40, // ray cast colision control (may only work for meshs) ContactsUnImportant = 0x2000, BackFaceCull = 0x4000, ClosestHit = 0x8000, // some combinations LSLPhantom = phantom | volumedtc, PrimsNonPhantom = nonphysical | physical, PrimsNonPhantomAgents = nonphysical | physical | agent, AllPrims = nonphysical | phantom | volumedtc | physical, AllButLand = agent | nonphysical | physical | phantom | volumedtc, ClosestAndBackCull = ClosestHit | BackFaceCull, All = 0x3f } public delegate void RequestAssetDelegate(UUID assetID, AssetReceivedDelegate callback); public delegate void AssetReceivedDelegate(AssetBase asset); /// <summary> /// Contact result from a raycast. /// </summary> public struct ContactResult { public Vector3 Pos; public float Depth; public uint ConsumerID; public Vector3 Normal; } public abstract class PhysicsScene { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// A unique identifying string for this instance of the physics engine. /// Useful in debug messages to distinguish one OdeScene instance from another. /// Usually set to include the region name that the physics engine is acting for. /// </summary> public string Name { get; protected set; } /// <summary> /// A string identifying the family of this physics engine. Most common values returned /// are "OpenDynamicsEngine" and "BulletSim" but others are possible. /// </summary> public string EngineType { get; protected set; } // The only thing that should register for this event is the SceneGraph // Anything else could cause problems. public event physicsCrash OnPhysicsCrash; public static PhysicsScene Null { get { return new NullPhysicsScene(); } } public RequestAssetDelegate RequestAssetMethod { get; set; } public virtual void TriggerPhysicsBasedRestart() { physicsCrash handler = OnPhysicsCrash; if (handler != null) { OnPhysicsCrash(); } } public abstract void Initialise(IMesher meshmerizer, IConfigSource config); /// <summary> /// Add an avatar /// </summary> /// <param name="avName"></param> /// <param name="position"></param> /// <param name="size"></param> /// <param name="isFlying"></param> /// <returns></returns> public abstract PhysicsActor AddAvatar(string avName, Vector3 position, Vector3 size, bool isFlying); /// <summary> /// Add an avatar /// </summary> /// <param name="localID"></param> /// <param name="avName"></param> /// <param name="position"></param> /// <param name="size"></param> /// <param name="isFlying"></param> /// <returns></returns> public virtual PhysicsActor AddAvatar(uint localID, string avName, Vector3 position, Vector3 size, bool isFlying) { PhysicsActor ret = AddAvatar(avName, position, size, isFlying); if (ret != null) ret.LocalID = localID; return ret; } /// <summary> /// Remove an avatar. /// </summary> /// <param name="actor"></param> public abstract void RemoveAvatar(PhysicsActor actor); /// <summary> /// Remove a prim. /// </summary> /// <param name="prim"></param> public abstract void RemovePrim(PhysicsActor prim); public abstract PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position, Vector3 size, Quaternion rotation, bool isPhysical, uint localid); public virtual PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position, Vector3 size, Quaternion rotation, bool isPhysical, bool isPhantom, byte shapetype, uint localid) { return AddPrimShape(primName, pbs, position, size, rotation, isPhysical, localid); } public virtual float TimeDilation { get { return 1.0f; } } public virtual bool SupportsNINJAJoints { get { return false; } } public virtual PhysicsJoint RequestJointCreation(string objectNameInScene, PhysicsJointType jointType, Vector3 position, Quaternion rotation, string parms, List<string> bodyNames, string trackedBodyName, Quaternion localRotation) { return null; } public virtual void RequestJointDeletion(string objectNameInScene) { return; } public virtual void RemoveAllJointsConnectedToActorThreadLocked(PhysicsActor actor) { return; } public virtual void DumpJointInfo() { return; } public event JointMoved OnJointMoved; protected virtual void DoJointMoved(PhysicsJoint joint) { // We need this to allow subclasses (but not other classes) to invoke the event; C# does // not allow subclasses to invoke the parent class event. if (OnJointMoved != null) { OnJointMoved(joint); } } public event JointDeactivated OnJointDeactivated; protected virtual void DoJointDeactivated(PhysicsJoint joint) { // We need this to allow subclasses (but not other classes) to invoke the event; C# does // not allow subclasses to invoke the parent class event. if (OnJointDeactivated != null) { OnJointDeactivated(joint); } } public event JointErrorMessage OnJointErrorMessage; protected virtual void DoJointErrorMessage(PhysicsJoint joint, string message) { // We need this to allow subclasses (but not other classes) to invoke the event; C# does // not allow subclasses to invoke the parent class event. if (OnJointErrorMessage != null) { OnJointErrorMessage(joint, message); } } public virtual Vector3 GetJointAnchor(PhysicsJoint joint) { return Vector3.Zero; } public virtual Vector3 GetJointAxis(PhysicsJoint joint) { return Vector3.Zero; } public abstract void AddPhysicsActorTaint(PhysicsActor prim); /// <summary> /// Perform a simulation of the current physics scene over the given timestep. /// </summary> /// <param name="timeStep"></param> /// <returns>The number of frames simulated over that period.</returns> public abstract float Simulate(float timeStep); /// <summary> /// Get statistics about this scene. /// </summary> /// <remarks>This facility is currently experimental and subject to change.</remarks> /// <returns> /// A dictionary where the key is the statistic name. If no statistics are supplied then returns null. /// </returns> public virtual Dictionary<string, float> GetStats() { return null; } public abstract void GetResults(); public abstract void SetTerrain(float[] heightMap); public abstract void SetWaterLevel(float baseheight); public abstract void DeleteTerrain(); public abstract void Dispose(); public abstract Dictionary<uint, float> GetTopColliders(); public abstract bool IsThreaded { get; } /// <summary> /// True if the physics plugin supports raycasting against the physics scene /// </summary> public virtual bool SupportsRayCast() { return false; } public virtual bool SupportsCombining() { return false; } public virtual void Combine(PhysicsScene pScene, Vector3 offset, Vector3 extents) {} public virtual void UnCombine(PhysicsScene pScene) {} /// <summary> /// Queue a raycast against the physics scene. /// The provided callback method will be called when the raycast is complete /// /// Many physics engines don't support collision testing at the same time as /// manipulating the physics scene, so we queue the request up and callback /// a custom method when the raycast is complete. /// This allows physics engines that give an immediate result to callback immediately /// and ones that don't, to callback when it gets a result back. /// /// ODE for example will not allow you to change the scene while collision testing or /// it asserts, 'opteration not valid for locked space'. This includes adding a ray to the scene. /// /// This is named RayCastWorld to not conflict with modrex's Raycast method. /// </summary> /// <param name="position">Origin of the ray</param> /// <param name="direction">Direction of the ray</param> /// <param name="length">Length of ray in meters</param> /// <param name="retMethod">Method to call when the raycast is complete</param> public virtual void RaycastWorld(Vector3 position, Vector3 direction, float length, RaycastCallback retMethod) { if (retMethod != null) retMethod(false, Vector3.Zero, 0, 999999999999f, Vector3.Zero); } public virtual void RaycastWorld(Vector3 position, Vector3 direction, float length, int Count, RayCallback retMethod) { if (retMethod != null) retMethod(new List<ContactResult>()); } public virtual List<ContactResult> RaycastWorld(Vector3 position, Vector3 direction, float length, int Count) { return new List<ContactResult>(); } public virtual object RaycastWorld(Vector3 position, Vector3 direction, float length, int Count, RayFilterFlags filter) { return null; } public virtual bool SupportsRaycastWorldFiltered() { return false; } } }
using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Linq; using System.Text; using Kemel.Orm.Data; using Kemel.Orm.Providers; using Kemel.Orm.Entity; using Kemel.Orm.Schema; using Kemel.Orm.NQuery.Storage.Constraint; using Kemel.Orm.NQuery.Storage.Column; namespace Kemel.Orm.NQuery.Storage { public class Executer { private Query objParent = null; public Query Parent { get { return this.objParent; } } private OrmTransaction objTransaction = null; public OrmTransaction Transaction { get { return this.objTransaction; } set { this.objTransaction = value; } } internal Executer(Query parent) { this.objParent = parent; this.objParent.Compile(); } public Executer(Query parent, OrmTransaction transaction) : this(parent) { this.Transaction = transaction; } //Private Function CreateCommand() As OrmCommand // Return Me.Parent.Provider.ReQueryBuilder.GetCommand(Me.Parent, Me.Transaction) //End Function public OrmCommand CreateCommand() { return this.Parent.CreateCommand(this.Transaction); } public List<TEtt> List<TEtt>() where TEtt : EntityBase, new() { OrmCommand command = this.Parent.CreateCommand(this.Transaction); return command.ExecuteList<TEtt>(); } public List<TEtt> List<TEtt>(bool useExtendProperties) where TEtt : EntityBase, new() { OrmCommand command = this.Parent.CreateCommand(this.Transaction); return command.ExecuteList<TEtt>(useExtendProperties); } public System.Data.DataTable DataTable() { OrmCommand command = this.Parent.CreateCommand(this.Transaction); return command.ExecuteDataTable(); } public int NonQuery() { OrmCommand command = this.Parent.CreateCommand(this.Transaction); return command.ExecuteNonQuery(); } //, bool blockPK) public int NonQuery<TEtt>(List<TEtt> lstEntities) where TEtt : EntityBase { bool finalizeTransaction = false; if (this.Transaction == null) { this.Transaction = this.Parent.Provider.GetConnection().CreateTransaction(); finalizeTransaction = true; } OrmConnection connection = this.Transaction.Connection; OrmCommand command = this.Parent.CreateCommand(this.Transaction); bool ignoreIdentity = this.Parent.Type == Query.QueryType.Insert; int ret = 0; if (finalizeTransaction) { this.Transaction.Begin(); } try { ret = command.ExecuteNonQuery(); for (int i = 1; i <= lstEntities.Count - 1; i++) { //this.SetNewParameters<TEtt>(command, lstEntities[i]);//, blockPK); SetParameters<TEtt>(command, this.Parent, lstEntities[i], ignoreIdentity); ret += command.ExecuteNonQuery(); } if (finalizeTransaction) { this.Transaction.Commit(); } } catch (Exception ex) { if (finalizeTransaction) { this.Transaction.Rollback(); } throw new OrmException(ex.Message, ex); } finally { if (finalizeTransaction) { connection.Close(); } } return ret; } //private void SetNewParameters<TEtt>(OrmCommand command, TEtt ettEntity)//, bool blockPK) //{ // TableSchema schema = this.Parent.IntoTable.TableSchema; // string prefixParam = Provider.Instance.QueryBuilder.DataBasePrefixParameter; // foreach (ColumnSchema column in schema.Columns) // { // if (column.IgnoreColumn) // continue; // if (column.IsIdentity) // continue; // Constraint columnConstraint = this.Parent.Constraints.FindByColumn(column); // //(command.Parameters[string.Concat(prefixParam, column.Name)] as System.Data.IDbDataParameter).Value = column.GetValue(ettEntity); // (command.Parameters[columnConstraint.Column.ParameterName] as System.Data.IDbDataParameter).Value = column.GetValue(ettEntity); // } //} public object Scalar() { OrmCommand command = this.Parent.CreateCommand(this.Transaction); return command.ExecuteScalar(); } public T Scalar<T>() { OrmCommand command = this.Parent.CreateCommand(this.Transaction); return command.ExecuteScalar<T>(); } //Public Shared Sub Save(Of TEtt As {EntityBase, New})(lstEntity As List(Of TEtt), ormTransaction As OrmTransaction) // Dim qryInsert As SQuery = Nothing // Dim qrySelectIdentity As SQuery = Nothing // Dim qryUpdate As SQuery = Nothing // Dim qryDelete As SQuery = Nothing // Dim cmdInsert As OrmCommand = Nothing // Dim cmdSelectIdentity As OrmCommand = Nothing // Dim cmdUpdate As OrmCommand = Nothing // Dim cmdDelete As OrmCommand = Nothing // Dim createTransaction As Boolean = False // Dim provider__1 As Provider = Provider.GetProvider(Of TEtt)() // If ormTransaction Is Nothing Then // createTransaction = True // ormTransaction = provider__1.GetConnection().CreateTransaction() // ormTransaction.Begin() // End If // qrySelectIdentity = provider__1.EntityCrudBuilder.GetSelectIdentity(Of TEtt)() // cmdSelectIdentity = ormTransaction.Connection.CreateCommand(ormTransaction) // qrySelectIdentity.WriteQuery(cmdSelectIdentity) // Dim schema As TableSchema = qrySelectIdentity.Tables(0).TableSchema // Try // For Each ett As TEtt In lstEntity // Select Case ett.EntityState // #Region "case EntityItemState.Added" // Case EntityItemState.Added // If cmdInsert Is Nothing Then // qryInsert = provider__1.EntityCrudBuilder.GetInsert(Of TEtt)(ett) // cmdInsert = ormTransaction.Connection.CreateCommand(ormTransaction) // qryInsert.WriteQuery(cmdInsert) // Else // SetParameters(Of TEtt)(cmdInsert, qryInsert, ett, True) // End If // cmdInsert.ExecuteNonQuery() // SetIdentityValues(Of TEtt)(ett, cmdSelectIdentity.ExecuteList(Of TEtt)().First(), schema) // Exit Select // #End Region // #Region "case EntityItemState.Deleted" // Case EntityItemState.Deleted // If cmdDelete Is Nothing Then // qryDelete = provider__1.EntityCrudBuilder.GetDeleteById(Of TEtt)(ett) // cmdDelete = ormTransaction.Connection.CreateCommand(ormTransaction) // qryDelete.WriteQuery(cmdDelete) // Else // SetParameters(Of TEtt)(cmdDelete, qryDelete, ett, False) // End If // cmdDelete.ExecuteNonQuery() // Exit Select // #End Region // #Region "case EntityItemState.Modified" // Case EntityItemState.Modified // If cmdUpdate Is Nothing Then // qryUpdate = provider__1.EntityCrudBuilder.GetUpdate(Of TEtt)(ett) // cmdUpdate = ormTransaction.Connection.CreateCommand(ormTransaction) // qryUpdate.WriteQuery(cmdUpdate) // Else // SetParameters(Of TEtt)(cmdUpdate, qryUpdate, ett, False) // End If // cmdUpdate.ExecuteNonQuery() // Exit Select // #End Region // End Select // Next // If createTransaction Then // ormTransaction.Commit() // End If // Catch ex As Exception // If createTransaction Then // ormTransaction.Rollback() // End If // Throw ex // End Try //End Sub public static void SetIdentityValues<TEtt>(TEtt ett, object value) where TEtt : EntityBase { TableSchema schema = TableSchema.FromEntity<TEtt>(); foreach (ColumnSchema column in schema.IdentityColumns) { column.SetValue(ett, value); } } public static void SetIdentityValues<TEtt>(TEtt ett, TEtt pIdentityValues, TableSchema schema) where TEtt : EntityBase { foreach (ColumnSchema column in schema.IdentityColumns) { column.SetValue(ett, column.GetValue(pIdentityValues)); } } public static void SetParameters<TEtt>(OrmCommand command, Query query, TEtt ett, bool ignoreIdentity) where TEtt : EntityBase { Provider provider__1 = Provider.GetProvider<TEtt>(); string prefixParam = provider__1.QueryBuilder.DataBasePrefixParameter; foreach (StoredConstraint constraint in query.Constraints) { StoredColumn column = constraint.Column; if (column != null && column.Type == StoredColumn.StoredTypes.Schema) { ColumnSchema colSchema = (ColumnSchema)column.ColumnDefinition; if (colSchema.IgnoreColumn || (ignoreIdentity && colSchema.IsIdentity)) { continue; } object value = colSchema.GetValue(ett); if (value == null) { value = DBNull.Value; } (command.Parameters[prefixParam + column.ParameterName] as System.Data.IDbDataParameter).Value = value; } } } //Public Function GetCommand() As OrmCommand // 'Dim command As OrmCommand = Me.CreateCommand() // 'Me.Parent.WriteQuery(command) // 'Return command // Return Me.CreateCommand() //End Function } }
// Copyright (c) Umbraco. // See LICENSE for more details. using System; using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; using Moq; using NUnit.Framework; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Cache; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Models.Membership; using Umbraco.Cms.Core.Security; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Tests.Common.Builders; using Umbraco.Cms.Web.BackOffice.Authorization; using Umbraco.Extensions; using Constants = Umbraco.Cms.Core.Constants; namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Web.BackOffice.Authorization { public class ContentPermissionsQueryStringHandlerTests { private const string QueryStringName = "id"; private const int NodeId = 1000; private static readonly Guid s_nodeGuid = Guid.NewGuid(); private static readonly Udi s_nodeUdi = UdiParser.Parse($"umb://document/{s_nodeGuid.ToString().ToLowerInvariant().Replace("-", string.Empty)}"); [Test] public async Task Node_Id_From_Requirement_With_Permission_Is_Authorized() { AuthorizationHandlerContext authHandlerContext = CreateAuthorizationHandlerContext(NodeId); Mock<IHttpContextAccessor> mockHttpContextAccessor = CreateMockHttpContextAccessor(); ContentPermissionsQueryStringHandler sut = CreateHandler(mockHttpContextAccessor.Object, NodeId, new string[] { "A" }); await sut.HandleAsync(authHandlerContext); Assert.IsTrue(authHandlerContext.HasSucceeded); } [Test] public async Task Node_Id_From_Requirement_Without_Permission_Is_Not_Authorized() { AuthorizationHandlerContext authHandlerContext = CreateAuthorizationHandlerContext(NodeId); Mock<IHttpContextAccessor> mockHttpContextAccessor = CreateMockHttpContextAccessor(); ContentPermissionsQueryStringHandler sut = CreateHandler(mockHttpContextAccessor.Object, NodeId, new string[] { "B" }); await sut.HandleAsync(authHandlerContext); Assert.IsFalse(authHandlerContext.HasSucceeded); AssertContentCached(mockHttpContextAccessor); } [Test] public async Task Node_Id_Missing_From_Requirement_And_QueryString_Is_Authorized() { AuthorizationHandlerContext authHandlerContext = CreateAuthorizationHandlerContext(); Mock<IHttpContextAccessor> mockHttpContextAccessor = CreateMockHttpContextAccessor(queryStringName: "xxx"); ContentPermissionsQueryStringHandler sut = CreateHandler(mockHttpContextAccessor.Object, NodeId, new string[] { "A" }); await sut.HandleAsync(authHandlerContext); Assert.IsTrue(authHandlerContext.HasSucceeded); } [Test] public async Task Node_Integer_Id_From_QueryString_With_Permission_Is_Authorized() { AuthorizationHandlerContext authHandlerContext = CreateAuthorizationHandlerContext(); Mock<IHttpContextAccessor> mockHttpContextAccessor = CreateMockHttpContextAccessor(queryStringValue: NodeId.ToString()); ContentPermissionsQueryStringHandler sut = CreateHandler(mockHttpContextAccessor.Object, NodeId, new string[] { "A" }); await sut.HandleAsync(authHandlerContext); Assert.IsTrue(authHandlerContext.HasSucceeded); AssertContentCached(mockHttpContextAccessor); } [Test] public async Task Node_Integer_Id_From_QueryString_Without_Permission_Is_Not_Authorized() { AuthorizationHandlerContext authHandlerContext = CreateAuthorizationHandlerContext(); Mock<IHttpContextAccessor> mockHttpContextAccessor = CreateMockHttpContextAccessor(queryStringValue: NodeId.ToString()); ContentPermissionsQueryStringHandler sut = CreateHandler(mockHttpContextAccessor.Object, NodeId, new string[] { "B" }); await sut.HandleAsync(authHandlerContext); Assert.IsFalse(authHandlerContext.HasSucceeded); AssertContentCached(mockHttpContextAccessor); } [Test] public async Task Node_Udi_Id_From_QueryString_With_Permission_Is_Authorized() { AuthorizationHandlerContext authHandlerContext = CreateAuthorizationHandlerContext(); Mock<IHttpContextAccessor> mockHttpContextAccessor = CreateMockHttpContextAccessor(queryStringValue: s_nodeUdi.ToString()); ContentPermissionsQueryStringHandler sut = CreateHandler(mockHttpContextAccessor.Object, NodeId, new string[] { "A" }); await sut.HandleAsync(authHandlerContext); Assert.IsTrue(authHandlerContext.HasSucceeded); AssertContentCached(mockHttpContextAccessor); } [Test] public async Task Node_Udi_Id_From_QueryString_Without_Permission_Is_Not_Authorized() { AuthorizationHandlerContext authHandlerContext = CreateAuthorizationHandlerContext(); Mock<IHttpContextAccessor> mockHttpContextAccessor = CreateMockHttpContextAccessor(queryStringValue: s_nodeUdi.ToString()); ContentPermissionsQueryStringHandler sut = CreateHandler(mockHttpContextAccessor.Object, NodeId, new string[] { "B" }); await sut.HandleAsync(authHandlerContext); Assert.IsFalse(authHandlerContext.HasSucceeded); AssertContentCached(mockHttpContextAccessor); } [Test] public async Task Node_Guid_Id_From_QueryString_With_Permission_Is_Authorized() { AuthorizationHandlerContext authHandlerContext = CreateAuthorizationHandlerContext(); Mock<IHttpContextAccessor> mockHttpContextAccessor = CreateMockHttpContextAccessor(queryStringValue: s_nodeGuid.ToString()); ContentPermissionsQueryStringHandler sut = CreateHandler(mockHttpContextAccessor.Object, NodeId, new string[] { "A" }); await sut.HandleAsync(authHandlerContext); Assert.IsTrue(authHandlerContext.HasSucceeded); AssertContentCached(mockHttpContextAccessor); } [Test] public async Task Node_Guid_Id_From_QueryString_Without_Permission_Is_Not_Authorized() { AuthorizationHandlerContext authHandlerContext = CreateAuthorizationHandlerContext(); Mock<IHttpContextAccessor> mockHttpContextAccessor = CreateMockHttpContextAccessor(queryStringValue: s_nodeGuid.ToString()); ContentPermissionsQueryStringHandler sut = CreateHandler(mockHttpContextAccessor.Object, NodeId, new string[] { "B" }); await sut.HandleAsync(authHandlerContext); Assert.IsFalse(authHandlerContext.HasSucceeded); AssertContentCached(mockHttpContextAccessor); } [Test] public async Task Node_Invalid_Id_From_QueryString_Is_Authorized() { AuthorizationHandlerContext authHandlerContext = CreateAuthorizationHandlerContext(); Mock<IHttpContextAccessor> mockHttpContextAccessor = CreateMockHttpContextAccessor(queryStringValue: "invalid"); ContentPermissionsQueryStringHandler sut = CreateHandler(mockHttpContextAccessor.Object, NodeId, new string[] { "A" }); await sut.HandleAsync(authHandlerContext); Assert.IsTrue(authHandlerContext.HasSucceeded); } private static AuthorizationHandlerContext CreateAuthorizationHandlerContext(int? nodeId = null) { const char Permission = 'A'; ContentPermissionsQueryStringRequirement requirement = nodeId.HasValue ? new ContentPermissionsQueryStringRequirement(nodeId.Value, Permission) : new ContentPermissionsQueryStringRequirement(Permission, QueryStringName); var user = new ClaimsPrincipal(new ClaimsIdentity(new List<Claim>())); object resource = new object(); return new AuthorizationHandlerContext(new List<IAuthorizationRequirement> { requirement }, user, resource); } private static Mock<IHttpContextAccessor> CreateMockHttpContextAccessor(string queryStringName = QueryStringName, string queryStringValue = "") { var mockHttpContextAccessor = new Mock<IHttpContextAccessor>(); var mockHttpContext = new Mock<HttpContext>(); var mockHttpRequest = new Mock<HttpRequest>(); var queryParams = new Dictionary<string, StringValues> { { queryStringName, queryStringValue }, }; mockHttpRequest.SetupGet(x => x.Query).Returns(new QueryCollection(queryParams)); mockHttpContext.SetupGet(x => x.Request).Returns(mockHttpRequest.Object); mockHttpContext.SetupGet(x => x.Items).Returns(new Dictionary<object, object>()); mockHttpContextAccessor.SetupGet(x => x.HttpContext).Returns(mockHttpContext.Object); return mockHttpContextAccessor; } private ContentPermissionsQueryStringHandler CreateHandler(IHttpContextAccessor httpContextAccessor, int nodeId, string[] permissionsForPath) { Mock<IBackOfficeSecurityAccessor> mockBackOfficeSecurityAccessor = CreateMockBackOfficeSecurityAccessor(); Mock<IEntityService> mockEntityService = CreateMockEntityService(); ContentPermissions contentPermissions = CreateContentPermissions(mockEntityService.Object, nodeId, permissionsForPath); return new ContentPermissionsQueryStringHandler(mockBackOfficeSecurityAccessor.Object, httpContextAccessor, mockEntityService.Object, contentPermissions); } private static Mock<IEntityService> CreateMockEntityService() { var mockEntityService = new Mock<IEntityService>(); mockEntityService .Setup(x => x.GetId(It.Is<Udi>(y => y == s_nodeUdi))) .Returns(Attempt<int>.Succeed(NodeId)); mockEntityService .Setup(x => x.GetId(It.Is<Guid>(y => y == s_nodeGuid), It.Is<UmbracoObjectTypes>(y => y == UmbracoObjectTypes.Document))) .Returns(Attempt<int>.Succeed(NodeId)); return mockEntityService; } private static Mock<IBackOfficeSecurityAccessor> CreateMockBackOfficeSecurityAccessor() { User user = CreateUser(); var mockBackOfficeSecurity = new Mock<IBackOfficeSecurity>(); mockBackOfficeSecurity.SetupGet(x => x.CurrentUser).Returns(user); var mockBackOfficeSecurityAccessor = new Mock<IBackOfficeSecurityAccessor>(); mockBackOfficeSecurityAccessor.Setup(x => x.BackOfficeSecurity).Returns(mockBackOfficeSecurity.Object); return mockBackOfficeSecurityAccessor; } private static User CreateUser() => new UserBuilder() .Build(); private static ContentPermissions CreateContentPermissions(IEntityService entityService, int nodeId, string[] permissionsForPath) { var mockUserService = new Mock<IUserService>(); mockUserService .Setup(x => x.GetPermissionsForPath(It.IsAny<IUser>(), It.Is<string>(y => y == $"{Constants.System.RootString},{nodeId.ToInvariantString()}"))) .Returns(new EntityPermissionSet(nodeId, new EntityPermissionCollection(new List<EntityPermission> { new EntityPermission(1, nodeId, permissionsForPath) }))); var mockContentService = new Mock<IContentService>(); mockContentService .Setup(x => x.GetById(It.Is<int>(y => y == nodeId))) .Returns(CreateContent(nodeId)); return new ContentPermissions(mockUserService.Object, mockContentService.Object, entityService, AppCaches.Disabled); } private static IContent CreateContent(int nodeId) { ContentType contentType = ContentTypeBuilder.CreateBasicContentType(); return ContentBuilder.CreateBasicContent(contentType, nodeId); } private static void AssertContentCached(Mock<IHttpContextAccessor> mockHttpContextAccessor) => Assert.AreEqual(NodeId, ((IContent)mockHttpContextAccessor.Object.HttpContext.Items[typeof(IContent).ToString()]).Id); } }
#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.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Reflection; using Newtonsoft.Json.Utilities; using System.Collections; using Newtonsoft.Json.Utilities.LinqBridge; namespace Newtonsoft.Json.Serialization { /// <summary> /// Contract details for a <see cref="Type"/> used by the <see cref="JsonSerializer"/>. /// </summary> public class JsonArrayContract : JsonContainerContract { /// <summary> /// Gets the <see cref="Type"/> of the collection items. /// </summary> /// <value>The <see cref="Type"/> of the collection items.</value> public Type CollectionItemType { get; private set; } /// <summary> /// Gets a value indicating whether the collection type is a multidimensional array. /// </summary> /// <value><c>true</c> if the collection type is a multidimensional array; otherwise, <c>false</c>.</value> public bool IsMultidimensionalArray { get; private set; } private readonly Type _genericCollectionDefinitionType; private Type _genericWrapperType; private ObjectConstructor<object> _genericWrapperCreator; private Func<object> _genericTemporaryCollectionCreator; internal bool IsArray { get; private set; } internal bool ShouldCreateWrapper { get; private set; } internal bool CanDeserialize { get; private set; } private readonly ConstructorInfo _parametrizedConstructor; private ObjectConstructor<object> _parametrizedCreator; internal ObjectConstructor<object> ParametrizedCreator { get { if (_parametrizedCreator == null) _parametrizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParametrizedConstructor(_parametrizedConstructor); return _parametrizedCreator; } } internal bool HasParametrizedCreator { get { return _parametrizedCreator != null || _parametrizedConstructor != null; } } /// <summary> /// Initializes a new instance of the <see cref="JsonArrayContract"/> class. /// </summary> /// <param name="underlyingType">The underlying type for the contract.</param> public JsonArrayContract(Type underlyingType) : base(underlyingType) { ContractType = JsonContractType.Array; IsArray = CreatedType.IsArray; bool canDeserialize; Type tempCollectionType; if (IsArray) { CollectionItemType = ReflectionUtils.GetCollectionItemType(UnderlyingType); IsReadOnlyOrFixedSize = true; _genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType); canDeserialize = true; IsMultidimensionalArray = (IsArray && UnderlyingType.GetArrayRank() > 1); } else if (typeof(IList).IsAssignableFrom(underlyingType)) { if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType)) CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0]; else CollectionItemType = ReflectionUtils.GetCollectionItemType(underlyingType); if (underlyingType == typeof(IList)) CreatedType = typeof(List<object>); if (CollectionItemType != null) _parametrizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType); IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyCollection<>)); canDeserialize = true; } else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType)) { CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0]; if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ICollection<>)) || ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IList<>))) CreatedType = typeof(List<>).MakeGenericType(CollectionItemType); _parametrizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType); canDeserialize = true; ShouldCreateWrapper = true; } else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IEnumerable<>), out tempCollectionType)) { CollectionItemType = tempCollectionType.GetGenericArguments()[0]; if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IEnumerable<>))) CreatedType = typeof(List<>).MakeGenericType(CollectionItemType); _parametrizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType); if (underlyingType.IsGenericType() && underlyingType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) { _genericCollectionDefinitionType = tempCollectionType; IsReadOnlyOrFixedSize = false; ShouldCreateWrapper = false; canDeserialize = true; } else { _genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType); IsReadOnlyOrFixedSize = true; ShouldCreateWrapper = true; canDeserialize = HasParametrizedCreator; } } else { // types that implement IEnumerable and nothing else canDeserialize = false; ShouldCreateWrapper = true; } CanDeserialize = canDeserialize; if (CollectionItemType != null && ReflectionUtils.IsNullableType(CollectionItemType)) { // bug in .NET 2.0 & 3.5 that List<Nullable<T>> throws an error when adding null via IList.Add(object) // wrapper will handle calling Add(T) instead if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(List<>), out tempCollectionType) || (IsArray && !IsMultidimensionalArray)) { ShouldCreateWrapper = true; } } } internal IWrappedCollection CreateWrapper(object list) { if (_genericWrapperCreator == null) { _genericWrapperType = typeof(CollectionWrapper<>).MakeGenericType(CollectionItemType); Type constructorArgument; if (ReflectionUtils.InheritsGenericDefinition(_genericCollectionDefinitionType, typeof(List<>)) || _genericCollectionDefinitionType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) constructorArgument = typeof(ICollection<>).MakeGenericType(CollectionItemType); else constructorArgument = _genericCollectionDefinitionType; ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { constructorArgument }); _genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParametrizedConstructor(genericWrapperConstructor); } return (IWrappedCollection)_genericWrapperCreator(list); } internal IList CreateTemporaryCollection() { if (_genericTemporaryCollectionCreator == null) { // multidimensional array will also have array instances in it Type collectionItemType = (IsMultidimensionalArray) ? typeof(object) : CollectionItemType; Type temporaryListType = typeof(List<>).MakeGenericType(collectionItemType); _genericTemporaryCollectionCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor<object>(temporaryListType); } return (IList)_genericTemporaryCollectionCreator(); } } }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="Networking.IPsecIkePeerBinding", Namespace="urn:iControl")] public partial class NetworkingIPsecIkePeer : iControlInterface { public NetworkingIPsecIkePeer() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // add_ike_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void add_ike_version( string [] peers, NetworkingIPsecIkeVersion [] [] versions ) { this.Invoke("add_ike_version", new object [] { peers, versions}); } public System.IAsyncResult Beginadd_ike_version(string [] peers,NetworkingIPsecIkeVersion [] [] versions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("add_ike_version", new object[] { peers, versions}, callback, asyncState); } public void Endadd_ike_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // add_traffic_selector //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void add_traffic_selector( string [] peers, string [] [] traffic_selectors ) { this.Invoke("add_traffic_selector", new object [] { peers, traffic_selectors}); } public System.IAsyncResult Beginadd_traffic_selector(string [] peers,string [] [] traffic_selectors, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("add_traffic_selector", new object[] { peers, traffic_selectors}, callback, asyncState); } public void Endadd_traffic_selector(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // create //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void create( string [] peers, string [] files, string [] keys, string [] addresses ) { this.Invoke("create", new object [] { peers, files, keys, addresses}); } public System.IAsyncResult Begincreate(string [] peers,string [] files,string [] keys,string [] addresses, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("create", new object[] { peers, files, keys, addresses}, callback, asyncState); } public void Endcreate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_all_ike_peers //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void delete_all_ike_peers( ) { this.Invoke("delete_all_ike_peers", new object [0]); } public System.IAsyncResult Begindelete_all_ike_peers(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_all_ike_peers", new object[0], callback, asyncState); } public void Enddelete_all_ike_peers(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_ike_peer //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void delete_ike_peer( string [] peers ) { this.Invoke("delete_ike_peer", new object [] { peers}); } public System.IAsyncResult Begindelete_ike_peer(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_ike_peer", new object[] { peers}, callback, asyncState); } public void Enddelete_ike_peer(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // get_ca_certificate_file //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_ca_certificate_file( string [] peers ) { object [] results = this.Invoke("get_ca_certificate_file", new object [] { peers}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_ca_certificate_file(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_ca_certificate_file", new object[] { peers}, callback, asyncState); } public string [] Endget_ca_certificate_file(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_certificate_type //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public NetworkingIPsecIkePeerCertType [] get_certificate_type( string [] peers ) { object [] results = this.Invoke("get_certificate_type", new object [] { peers}); return ((NetworkingIPsecIkePeerCertType [])(results[0])); } public System.IAsyncResult Beginget_certificate_type(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_certificate_type", new object[] { peers}, callback, asyncState); } public NetworkingIPsecIkePeerCertType [] Endget_certificate_type(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((NetworkingIPsecIkePeerCertType [])(results[0])); } //----------------------------------------------------------------------- // get_crl_file //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_crl_file( string [] peers ) { object [] results = this.Invoke("get_crl_file", new object [] { peers}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_crl_file(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_crl_file", new object[] { peers}, callback, asyncState); } public string [] Endget_crl_file(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_description( string [] peers ) { object [] results = this.Invoke("get_description", new object [] { peers}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_description(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_description", new object[] { peers}, callback, asyncState); } public string [] Endget_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_dpd_delay //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long [] get_dpd_delay( string [] peers ) { object [] results = this.Invoke("get_dpd_delay", new object [] { peers}); return ((long [])(results[0])); } public System.IAsyncResult Beginget_dpd_delay(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_dpd_delay", new object[] { peers}, callback, asyncState); } public long [] Endget_dpd_delay(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long [])(results[0])); } //----------------------------------------------------------------------- // get_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonEnabledState [] get_enabled_state( string [] peers ) { object [] results = this.Invoke("get_enabled_state", new object [] { peers}); return ((CommonEnabledState [])(results[0])); } public System.IAsyncResult Beginget_enabled_state(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_enabled_state", new object[] { peers}, callback, asyncState); } public CommonEnabledState [] Endget_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_generate_policy //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public NetworkingIPsecIkePeerGeneratePolicy [] get_generate_policy( string [] peers ) { object [] results = this.Invoke("get_generate_policy", new object [] { peers}); return ((NetworkingIPsecIkePeerGeneratePolicy [])(results[0])); } public System.IAsyncResult Beginget_generate_policy(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_generate_policy", new object[] { peers}, callback, asyncState); } public NetworkingIPsecIkePeerGeneratePolicy [] Endget_generate_policy(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((NetworkingIPsecIkePeerGeneratePolicy [])(results[0])); } //----------------------------------------------------------------------- // get_ike_proposal_name //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_ike_proposal_name( string [] peers ) { object [] results = this.Invoke("get_ike_proposal_name", new object [] { peers}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_ike_proposal_name(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_ike_proposal_name", new object[] { peers}, callback, asyncState); } public string [] Endget_ike_proposal_name(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_ike_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public NetworkingIPsecIkeVersion [] [] get_ike_version( string [] peers ) { object [] results = this.Invoke("get_ike_version", new object [] { peers}); return ((NetworkingIPsecIkeVersion [] [])(results[0])); } public System.IAsyncResult Beginget_ike_version(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_ike_version", new object[] { peers}, callback, asyncState); } public NetworkingIPsecIkeVersion [] [] Endget_ike_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((NetworkingIPsecIkeVersion [] [])(results[0])); } //----------------------------------------------------------------------- // get_lifetime //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long [] get_lifetime( string [] peers ) { object [] results = this.Invoke("get_lifetime", new object [] { peers}); return ((long [])(results[0])); } public System.IAsyncResult Beginget_lifetime(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_lifetime", new object[] { peers}, callback, asyncState); } public long [] Endget_lifetime(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long [])(results[0])); } //----------------------------------------------------------------------- // get_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_list( ) { object [] results = this.Invoke("get_list", new object [0]); return ((string [])(results[0])); } public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_list", new object[0], callback, asyncState); } public string [] Endget_list(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_mode //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public NetworkingIPsecIkePeerMode [] get_mode( string [] peers ) { object [] results = this.Invoke("get_mode", new object [] { peers}); return ((NetworkingIPsecIkePeerMode [])(results[0])); } public System.IAsyncResult Beginget_mode(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_mode", new object[] { peers}, callback, asyncState); } public NetworkingIPsecIkePeerMode [] Endget_mode(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((NetworkingIPsecIkePeerMode [])(results[0])); } //----------------------------------------------------------------------- // get_my_certificate_file //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_my_certificate_file( string [] peers ) { object [] results = this.Invoke("get_my_certificate_file", new object [] { peers}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_my_certificate_file(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_my_certificate_file", new object[] { peers}, callback, asyncState); } public string [] Endget_my_certificate_file(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_my_certificate_key_file //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_my_certificate_key_file( string [] peers ) { object [] results = this.Invoke("get_my_certificate_key_file", new object [] { peers}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_my_certificate_key_file(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_my_certificate_key_file", new object[] { peers}, callback, asyncState); } public string [] Endget_my_certificate_key_file(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_my_certificate_key_passphrase //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_my_certificate_key_passphrase( string [] peers ) { object [] results = this.Invoke("get_my_certificate_key_passphrase", new object [] { peers}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_my_certificate_key_passphrase(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_my_certificate_key_passphrase", new object[] { peers}, callback, asyncState); } public string [] Endget_my_certificate_key_passphrase(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_my_id_type //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public NetworkingIPsecIkePeerIDType [] get_my_id_type( string [] peers ) { object [] results = this.Invoke("get_my_id_type", new object [] { peers}); return ((NetworkingIPsecIkePeerIDType [])(results[0])); } public System.IAsyncResult Beginget_my_id_type(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_my_id_type", new object[] { peers}, callback, asyncState); } public NetworkingIPsecIkePeerIDType [] Endget_my_id_type(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((NetworkingIPsecIkePeerIDType [])(results[0])); } //----------------------------------------------------------------------- // get_my_id_value //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_my_id_value( string [] peers ) { object [] results = this.Invoke("get_my_id_value", new object [] { peers}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_my_id_value(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_my_id_value", new object[] { peers}, callback, asyncState); } public string [] Endget_my_id_value(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_nat_traversal //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public NetworkingIPsecIkePeerNatTraversal [] get_nat_traversal( string [] peers ) { object [] results = this.Invoke("get_nat_traversal", new object [] { peers}); return ((NetworkingIPsecIkePeerNatTraversal [])(results[0])); } public System.IAsyncResult Beginget_nat_traversal(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_nat_traversal", new object[] { peers}, callback, asyncState); } public NetworkingIPsecIkePeerNatTraversal [] Endget_nat_traversal(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((NetworkingIPsecIkePeerNatTraversal [])(results[0])); } //----------------------------------------------------------------------- // get_passive_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonEnabledState [] get_passive_state( string [] peers ) { object [] results = this.Invoke("get_passive_state", new object [] { peers}); return ((CommonEnabledState [])(results[0])); } public System.IAsyncResult Beginget_passive_state(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_passive_state", new object[] { peers}, callback, asyncState); } public CommonEnabledState [] Endget_passive_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_peer_certificate_file //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_peer_certificate_file( string [] peers ) { object [] results = this.Invoke("get_peer_certificate_file", new object [] { peers}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_peer_certificate_file(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_peer_certificate_file", new object[] { peers}, callback, asyncState); } public string [] Endget_peer_certificate_file(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_peer_id_type //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public NetworkingIPsecIkePeerIDType [] get_peer_id_type( string [] peers ) { object [] results = this.Invoke("get_peer_id_type", new object [] { peers}); return ((NetworkingIPsecIkePeerIDType [])(results[0])); } public System.IAsyncResult Beginget_peer_id_type(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_peer_id_type", new object[] { peers}, callback, asyncState); } public NetworkingIPsecIkePeerIDType [] Endget_peer_id_type(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((NetworkingIPsecIkePeerIDType [])(results[0])); } //----------------------------------------------------------------------- // get_peer_id_value //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_peer_id_value( string [] peers ) { object [] results = this.Invoke("get_peer_id_value", new object [] { peers}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_peer_id_value(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_peer_id_value", new object[] { peers}, callback, asyncState); } public string [] Endget_peer_id_value(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_phase1_auth_method //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public NetworkingIPsecSaMethod [] get_phase1_auth_method( string [] peers ) { object [] results = this.Invoke("get_phase1_auth_method", new object [] { peers}); return ((NetworkingIPsecSaMethod [])(results[0])); } public System.IAsyncResult Beginget_phase1_auth_method(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_phase1_auth_method", new object[] { peers}, callback, asyncState); } public NetworkingIPsecSaMethod [] Endget_phase1_auth_method(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((NetworkingIPsecSaMethod [])(results[0])); } //----------------------------------------------------------------------- // get_phase1_encryption_algorithm //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public NetworkingIPsecIkeEncrAlgorithm [] get_phase1_encryption_algorithm( string [] peers ) { object [] results = this.Invoke("get_phase1_encryption_algorithm", new object [] { peers}); return ((NetworkingIPsecIkeEncrAlgorithm [])(results[0])); } public System.IAsyncResult Beginget_phase1_encryption_algorithm(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_phase1_encryption_algorithm", new object[] { peers}, callback, asyncState); } public NetworkingIPsecIkeEncrAlgorithm [] Endget_phase1_encryption_algorithm(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((NetworkingIPsecIkeEncrAlgorithm [])(results[0])); } //----------------------------------------------------------------------- // get_phase1_hash_algorithm //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public NetworkingIPsecIkeHashAlgorithm [] get_phase1_hash_algorithm( string [] peers ) { object [] results = this.Invoke("get_phase1_hash_algorithm", new object [] { peers}); return ((NetworkingIPsecIkeHashAlgorithm [])(results[0])); } public System.IAsyncResult Beginget_phase1_hash_algorithm(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_phase1_hash_algorithm", new object[] { peers}, callback, asyncState); } public NetworkingIPsecIkeHashAlgorithm [] Endget_phase1_hash_algorithm(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((NetworkingIPsecIkeHashAlgorithm [])(results[0])); } //----------------------------------------------------------------------- // get_phase1_perfect_forward_secrecy //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public NetworkingIPsecDiffieHellmanGroup [] get_phase1_perfect_forward_secrecy( string [] peers ) { object [] results = this.Invoke("get_phase1_perfect_forward_secrecy", new object [] { peers}); return ((NetworkingIPsecDiffieHellmanGroup [])(results[0])); } public System.IAsyncResult Beginget_phase1_perfect_forward_secrecy(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_phase1_perfect_forward_secrecy", new object[] { peers}, callback, asyncState); } public NetworkingIPsecDiffieHellmanGroup [] Endget_phase1_perfect_forward_secrecy(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((NetworkingIPsecDiffieHellmanGroup [])(results[0])); } //----------------------------------------------------------------------- // get_phase1_pseudo_random_function //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public NetworkingIPsecIkeHashAlgorithm [] get_phase1_pseudo_random_function( string [] peers ) { object [] results = this.Invoke("get_phase1_pseudo_random_function", new object [] { peers}); return ((NetworkingIPsecIkeHashAlgorithm [])(results[0])); } public System.IAsyncResult Beginget_phase1_pseudo_random_function(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_phase1_pseudo_random_function", new object[] { peers}, callback, asyncState); } public NetworkingIPsecIkeHashAlgorithm [] Endget_phase1_pseudo_random_function(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((NetworkingIPsecIkeHashAlgorithm [])(results[0])); } //----------------------------------------------------------------------- // get_preshared_key //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_preshared_key( string [] peers ) { object [] results = this.Invoke("get_preshared_key", new object [] { peers}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_preshared_key(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_preshared_key", new object[] { peers}, callback, asyncState); } public string [] Endget_preshared_key(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_preshared_key_encrypted //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_preshared_key_encrypted( string [] peers ) { object [] results = this.Invoke("get_preshared_key_encrypted", new object [] { peers}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_preshared_key_encrypted(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_preshared_key_encrypted", new object[] { peers}, callback, asyncState); } public string [] Endget_preshared_key_encrypted(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_proxy_support_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonEnabledState [] get_proxy_support_state( string [] peers ) { object [] results = this.Invoke("get_proxy_support_state", new object [] { peers}); return ((CommonEnabledState [])(results[0])); } public System.IAsyncResult Beginget_proxy_support_state(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_proxy_support_state", new object[] { peers}, callback, asyncState); } public CommonEnabledState [] Endget_proxy_support_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_remote_address //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_remote_address( string [] peers ) { object [] results = this.Invoke("get_remote_address", new object [] { peers}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_remote_address(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_remote_address", new object[] { peers}, callback, asyncState); } public string [] Endget_remote_address(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_replay_window_size //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long [] get_replay_window_size( string [] peers ) { object [] results = this.Invoke("get_replay_window_size", new object [] { peers}); return ((long [])(results[0])); } public System.IAsyncResult Beginget_replay_window_size(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_replay_window_size", new object[] { peers}, callback, asyncState); } public long [] Endget_replay_window_size(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long [])(results[0])); } //----------------------------------------------------------------------- // get_traffic_selector //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] [] get_traffic_selector( string [] peers ) { object [] results = this.Invoke("get_traffic_selector", new object [] { peers}); return ((string [] [])(results[0])); } public System.IAsyncResult Beginget_traffic_selector(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_traffic_selector", new object[] { peers}, callback, asyncState); } public string [] [] Endget_traffic_selector(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [] [])(results[0])); } //----------------------------------------------------------------------- // get_verify_certificate_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonEnabledState [] get_verify_certificate_state( string [] peers ) { object [] results = this.Invoke("get_verify_certificate_state", new object [] { peers}); return ((CommonEnabledState [])(results[0])); } public System.IAsyncResult Beginget_verify_certificate_state(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_verify_certificate_state", new object[] { peers}, callback, asyncState); } public CommonEnabledState [] Endget_verify_certificate_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // remove_all_ike_versions //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void remove_all_ike_versions( string [] peers ) { this.Invoke("remove_all_ike_versions", new object [] { peers}); } public System.IAsyncResult Beginremove_all_ike_versions(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_all_ike_versions", new object[] { peers}, callback, asyncState); } public void Endremove_all_ike_versions(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // remove_all_traffic_selectors //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void remove_all_traffic_selectors( string [] peers ) { this.Invoke("remove_all_traffic_selectors", new object [] { peers}); } public System.IAsyncResult Beginremove_all_traffic_selectors(string [] peers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_all_traffic_selectors", new object[] { peers}, callback, asyncState); } public void Endremove_all_traffic_selectors(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // remove_ike_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void remove_ike_version( string [] peers, NetworkingIPsecIkeVersion [] [] versions ) { this.Invoke("remove_ike_version", new object [] { peers, versions}); } public System.IAsyncResult Beginremove_ike_version(string [] peers,NetworkingIPsecIkeVersion [] [] versions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_ike_version", new object[] { peers, versions}, callback, asyncState); } public void Endremove_ike_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // remove_traffic_selector //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void remove_traffic_selector( string [] peers, string [] [] traffic_selectors ) { this.Invoke("remove_traffic_selector", new object [] { peers, traffic_selectors}); } public System.IAsyncResult Beginremove_traffic_selector(string [] peers,string [] [] traffic_selectors, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_traffic_selector", new object[] { peers, traffic_selectors}, callback, asyncState); } public void Endremove_traffic_selector(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_ca_certificate_file //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_ca_certificate_file( string [] peers, string [] files ) { this.Invoke("set_ca_certificate_file", new object [] { peers, files}); } public System.IAsyncResult Beginset_ca_certificate_file(string [] peers,string [] files, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_ca_certificate_file", new object[] { peers, files}, callback, asyncState); } public void Endset_ca_certificate_file(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_certificate_type //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_certificate_type( string [] peers, NetworkingIPsecIkePeerCertType [] types ) { this.Invoke("set_certificate_type", new object [] { peers, types}); } public System.IAsyncResult Beginset_certificate_type(string [] peers,NetworkingIPsecIkePeerCertType [] types, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_certificate_type", new object[] { peers, types}, callback, asyncState); } public void Endset_certificate_type(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_crl_file //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_crl_file( string [] peers, string [] files ) { this.Invoke("set_crl_file", new object [] { peers, files}); } public System.IAsyncResult Beginset_crl_file(string [] peers,string [] files, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_crl_file", new object[] { peers, files}, callback, asyncState); } public void Endset_crl_file(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_description( string [] peers, string [] descriptions ) { this.Invoke("set_description", new object [] { peers, descriptions}); } public System.IAsyncResult Beginset_description(string [] peers,string [] descriptions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_description", new object[] { peers, descriptions}, callback, asyncState); } public void Endset_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_dpd_delay //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_dpd_delay( string [] peers, long [] delays ) { this.Invoke("set_dpd_delay", new object [] { peers, delays}); } public System.IAsyncResult Beginset_dpd_delay(string [] peers,long [] delays, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_dpd_delay", new object[] { peers, delays}, callback, asyncState); } public void Endset_dpd_delay(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_enabled_state( string [] peers, CommonEnabledState [] states ) { this.Invoke("set_enabled_state", new object [] { peers, states}); } public System.IAsyncResult Beginset_enabled_state(string [] peers,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_enabled_state", new object[] { peers, states}, callback, asyncState); } public void Endset_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_generate_policy //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_generate_policy( string [] peers, NetworkingIPsecIkePeerGeneratePolicy [] policies ) { this.Invoke("set_generate_policy", new object [] { peers, policies}); } public System.IAsyncResult Beginset_generate_policy(string [] peers,NetworkingIPsecIkePeerGeneratePolicy [] policies, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_generate_policy", new object[] { peers, policies}, callback, asyncState); } public void Endset_generate_policy(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_ike_proposal_name //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_ike_proposal_name( string [] peers, string [] names ) { this.Invoke("set_ike_proposal_name", new object [] { peers, names}); } public System.IAsyncResult Beginset_ike_proposal_name(string [] peers,string [] names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_ike_proposal_name", new object[] { peers, names}, callback, asyncState); } public void Endset_ike_proposal_name(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_lifetime //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_lifetime( string [] peers, long [] lifetimes ) { this.Invoke("set_lifetime", new object [] { peers, lifetimes}); } public System.IAsyncResult Beginset_lifetime(string [] peers,long [] lifetimes, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_lifetime", new object[] { peers, lifetimes}, callback, asyncState); } public void Endset_lifetime(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_mode //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_mode( string [] peers, NetworkingIPsecIkePeerMode [] modes ) { this.Invoke("set_mode", new object [] { peers, modes}); } public System.IAsyncResult Beginset_mode(string [] peers,NetworkingIPsecIkePeerMode [] modes, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_mode", new object[] { peers, modes}, callback, asyncState); } public void Endset_mode(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_my_certificate_authentication //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_my_certificate_authentication( string [] peers, NetworkingIPsecSaMethod [] methods, string [] certs, string [] keys, string [] passphrases ) { this.Invoke("set_my_certificate_authentication", new object [] { peers, methods, certs, keys, passphrases}); } public System.IAsyncResult Beginset_my_certificate_authentication(string [] peers,NetworkingIPsecSaMethod [] methods,string [] certs,string [] keys,string [] passphrases, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_my_certificate_authentication", new object[] { peers, methods, certs, keys, passphrases}, callback, asyncState); } public void Endset_my_certificate_authentication(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_my_certificate_file //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_my_certificate_file( string [] peers, string [] files ) { this.Invoke("set_my_certificate_file", new object [] { peers, files}); } public System.IAsyncResult Beginset_my_certificate_file(string [] peers,string [] files, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_my_certificate_file", new object[] { peers, files}, callback, asyncState); } public void Endset_my_certificate_file(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_my_certificate_key_file //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_my_certificate_key_file( string [] peers, string [] files ) { this.Invoke("set_my_certificate_key_file", new object [] { peers, files}); } public System.IAsyncResult Beginset_my_certificate_key_file(string [] peers,string [] files, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_my_certificate_key_file", new object[] { peers, files}, callback, asyncState); } public void Endset_my_certificate_key_file(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_my_certificate_key_passphrase //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_my_certificate_key_passphrase( string [] peers, string [] passphrases ) { this.Invoke("set_my_certificate_key_passphrase", new object [] { peers, passphrases}); } public System.IAsyncResult Beginset_my_certificate_key_passphrase(string [] peers,string [] passphrases, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_my_certificate_key_passphrase", new object[] { peers, passphrases}, callback, asyncState); } public void Endset_my_certificate_key_passphrase(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_my_id_type //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_my_id_type( string [] peers, NetworkingIPsecIkePeerIDType [] types ) { this.Invoke("set_my_id_type", new object [] { peers, types}); } public System.IAsyncResult Beginset_my_id_type(string [] peers,NetworkingIPsecIkePeerIDType [] types, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_my_id_type", new object[] { peers, types}, callback, asyncState); } public void Endset_my_id_type(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_my_id_value //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_my_id_value( string [] peers, string [] values ) { this.Invoke("set_my_id_value", new object [] { peers, values}); } public System.IAsyncResult Beginset_my_id_value(string [] peers,string [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_my_id_value", new object[] { peers, values}, callback, asyncState); } public void Endset_my_id_value(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_nat_traversal //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_nat_traversal( string [] peers, NetworkingIPsecIkePeerNatTraversal [] nat_traversals ) { this.Invoke("set_nat_traversal", new object [] { peers, nat_traversals}); } public System.IAsyncResult Beginset_nat_traversal(string [] peers,NetworkingIPsecIkePeerNatTraversal [] nat_traversals, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_nat_traversal", new object[] { peers, nat_traversals}, callback, asyncState); } public void Endset_nat_traversal(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_passive_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_passive_state( string [] peers, CommonEnabledState [] states ) { this.Invoke("set_passive_state", new object [] { peers, states}); } public System.IAsyncResult Beginset_passive_state(string [] peers,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_passive_state", new object[] { peers, states}, callback, asyncState); } public void Endset_passive_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_peer_certificate_file //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_peer_certificate_file( string [] peers, string [] files ) { this.Invoke("set_peer_certificate_file", new object [] { peers, files}); } public System.IAsyncResult Beginset_peer_certificate_file(string [] peers,string [] files, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_peer_certificate_file", new object[] { peers, files}, callback, asyncState); } public void Endset_peer_certificate_file(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_peer_id_type //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_peer_id_type( string [] peers, NetworkingIPsecIkePeerIDType [] types ) { this.Invoke("set_peer_id_type", new object [] { peers, types}); } public System.IAsyncResult Beginset_peer_id_type(string [] peers,NetworkingIPsecIkePeerIDType [] types, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_peer_id_type", new object[] { peers, types}, callback, asyncState); } public void Endset_peer_id_type(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_peer_id_value //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_peer_id_value( string [] peers, string [] values ) { this.Invoke("set_peer_id_value", new object [] { peers, values}); } public System.IAsyncResult Beginset_peer_id_value(string [] peers,string [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_peer_id_value", new object[] { peers, values}, callback, asyncState); } public void Endset_peer_id_value(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_phase1_auth_method //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_phase1_auth_method( string [] peers, NetworkingIPsecSaMethod [] methods ) { this.Invoke("set_phase1_auth_method", new object [] { peers, methods}); } public System.IAsyncResult Beginset_phase1_auth_method(string [] peers,NetworkingIPsecSaMethod [] methods, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_phase1_auth_method", new object[] { peers, methods}, callback, asyncState); } public void Endset_phase1_auth_method(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_phase1_encryption_algorithm //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_phase1_encryption_algorithm( string [] peers, NetworkingIPsecIkeEncrAlgorithm [] algorithms ) { this.Invoke("set_phase1_encryption_algorithm", new object [] { peers, algorithms}); } public System.IAsyncResult Beginset_phase1_encryption_algorithm(string [] peers,NetworkingIPsecIkeEncrAlgorithm [] algorithms, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_phase1_encryption_algorithm", new object[] { peers, algorithms}, callback, asyncState); } public void Endset_phase1_encryption_algorithm(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_phase1_hash_algorithm //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_phase1_hash_algorithm( string [] peers, NetworkingIPsecIkeHashAlgorithm [] algorithms ) { this.Invoke("set_phase1_hash_algorithm", new object [] { peers, algorithms}); } public System.IAsyncResult Beginset_phase1_hash_algorithm(string [] peers,NetworkingIPsecIkeHashAlgorithm [] algorithms, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_phase1_hash_algorithm", new object[] { peers, algorithms}, callback, asyncState); } public void Endset_phase1_hash_algorithm(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_phase1_perfect_forward_secrecy //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_phase1_perfect_forward_secrecy( string [] peers, NetworkingIPsecDiffieHellmanGroup [] secrecies ) { this.Invoke("set_phase1_perfect_forward_secrecy", new object [] { peers, secrecies}); } public System.IAsyncResult Beginset_phase1_perfect_forward_secrecy(string [] peers,NetworkingIPsecDiffieHellmanGroup [] secrecies, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_phase1_perfect_forward_secrecy", new object[] { peers, secrecies}, callback, asyncState); } public void Endset_phase1_perfect_forward_secrecy(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_phase1_pseudo_random_function //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_phase1_pseudo_random_function( string [] peers, NetworkingIPsecIkeHashAlgorithm [] functions ) { this.Invoke("set_phase1_pseudo_random_function", new object [] { peers, functions}); } public System.IAsyncResult Beginset_phase1_pseudo_random_function(string [] peers,NetworkingIPsecIkeHashAlgorithm [] functions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_phase1_pseudo_random_function", new object[] { peers, functions}, callback, asyncState); } public void Endset_phase1_pseudo_random_function(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_preshared_key //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_preshared_key( string [] peers, string [] keys ) { this.Invoke("set_preshared_key", new object [] { peers, keys}); } public System.IAsyncResult Beginset_preshared_key(string [] peers,string [] keys, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_preshared_key", new object[] { peers, keys}, callback, asyncState); } public void Endset_preshared_key(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_preshared_key_encrypted //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_preshared_key_encrypted( string [] peers, string [] keys ) { this.Invoke("set_preshared_key_encrypted", new object [] { peers, keys}); } public System.IAsyncResult Beginset_preshared_key_encrypted(string [] peers,string [] keys, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_preshared_key_encrypted", new object[] { peers, keys}, callback, asyncState); } public void Endset_preshared_key_encrypted(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_proxy_support_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_proxy_support_state( string [] peers, CommonEnabledState [] states ) { this.Invoke("set_proxy_support_state", new object [] { peers, states}); } public System.IAsyncResult Beginset_proxy_support_state(string [] peers,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_proxy_support_state", new object[] { peers, states}, callback, asyncState); } public void Endset_proxy_support_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_remote_address //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_remote_address( string [] peers, string [] addresses ) { this.Invoke("set_remote_address", new object [] { peers, addresses}); } public System.IAsyncResult Beginset_remote_address(string [] peers,string [] addresses, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_remote_address", new object[] { peers, addresses}, callback, asyncState); } public void Endset_remote_address(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_replay_window_size //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_replay_window_size( string [] peers, long [] sizes ) { this.Invoke("set_replay_window_size", new object [] { peers, sizes}); } public System.IAsyncResult Beginset_replay_window_size(string [] peers,long [] sizes, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_replay_window_size", new object[] { peers, sizes}, callback, asyncState); } public void Endset_replay_window_size(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_verify_certificate_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecIkePeer", RequestNamespace="urn:iControl:Networking/IPsecIkePeer", ResponseNamespace="urn:iControl:Networking/IPsecIkePeer")] public void set_verify_certificate_state( string [] peers, CommonEnabledState [] states ) { this.Invoke("set_verify_certificate_state", new object [] { peers, states}); } public System.IAsyncResult Beginset_verify_certificate_state(string [] peers,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_verify_certificate_state", new object[] { peers, states}, callback, asyncState); } public void Endset_verify_certificate_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= //======================================================================= // Structs //======================================================================= }
namespace AdMaiora.Bugghy { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using AdMaiora.AppKit.UI; using AdMaiora.Bugghy.Model; #pragma warning disable CS4014 public class GimmickFragment : AdMaiora.AppKit.UI.App.Fragment { #region Inner Classes #endregion #region Constants and Fields private Gimmick _gimmick; // This flag check if we are already calling the login REST service private bool _isRefreshingStats; // This cancellation token is used to cancel the rest send message request private CancellationTokenSource _cts0; #endregion #region Widgets [Widget] private RoundedImageView ThumbImage; [Widget] private TextView NameLabel; [Widget] private TextView OwnerLabel; [Widget] private ImageButton AddButton; [Widget] private RelativeLayout OpenedLayout; [Widget] private TextView OpenedNumberLabel; [Widget] private Button ViewOpenedButton; [Widget] private RelativeLayout WorkingLayout; [Widget] private TextView WorkingNumberLabel; [Widget] private Button ViewWorkingButton; [Widget] private RelativeLayout ClosedLayout; [Widget] private TextView ClosedNumberLabel; [Widget] private Button ViewClosedButton; #endregion #region Constructors public GimmickFragment() { } #endregion #region Properties #endregion #region Fragment Methods public override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); _gimmick = this.Arguments.GetObject<Gimmick>("Gimmick"); } public override void OnCreateView(LayoutInflater inflater, ViewGroup container) { base.OnCreateView(inflater, container); #region Desinger Stuff SetContentView(Resource.Layout.FragmentGimmick, inflater, container); this.HasOptionsMenu = true; #endregion this.Title = "Stats"; this.AddButton.Click += AddButton_Click; this.ViewOpenedButton.Click += ViewIssuesButton_Click; this.ViewWorkingButton.Click += ViewIssuesButton_Click; this.ViewClosedButton.Click += ViewIssuesButton_Click; RefreshThumb(); RefreshStats(); } public override void OnCreateOptionsMenu(IMenu menu, MenuInflater inflater) { base.OnCreateOptionsMenu(menu, inflater); menu.Clear(); menu.Add(0, 1, 0, "Refresh").SetShowAsAction(ShowAsAction.Always); } public override bool OnOptionsItemSelected(IMenuItem item) { switch (item.ItemId) { case 1: RefreshStats(); return true; default: return base.OnOptionsItemSelected(item); } } public override void OnDestroyView() { base.OnDestroyView(); if (_cts0 != null) _cts0.Cancel(); this.AddButton.Click -= AddButton_Click; this.ViewOpenedButton.Click -= ViewIssuesButton_Click; this.ViewWorkingButton.Click -= ViewIssuesButton_Click; this.ViewClosedButton.Click -= ViewIssuesButton_Click; } #endregion #region Public Methods #endregion #region Methods private void RefreshThumb() { if (_gimmick.ImageUrl != null) { // This will load async the image and cache it locally var uri = new Uri(_gimmick.ImageUrl); AppController.Images.SetImageForView( uri, "image_empty_thumb", this.ThumbImage); } } private void RefreshStats() { if (_gimmick == null) return; if (_isRefreshingStats) return; this.NameLabel.Text = _gimmick.Name; this.OwnerLabel.Text = _gimmick.Owner; _isRefreshingStats = true; ((MainActivity)this.Activity).BlockUI(); this.ViewOpenedButton.Enabled = false; this.ViewWorkingButton.Enabled = false; this.ViewClosedButton.Enabled = false; Dictionary<string, int> stats = null; _cts0 = new CancellationTokenSource(); AppController.RefreshStats(_cts0, _gimmick.GimmickId, (newStats) => { stats = newStats; }, (error) => { Toast.MakeText(this.Activity.ApplicationContext, error, ToastLength.Long).Show(); }, () => { if(stats != null) { LoadStatistics(stats); _isRefreshingStats = false; ((MainActivity)this.Activity).UnblockUI(); } else { AppController.Utility.ExecuteOnAsyncTask(_cts0.Token, () => { stats = AppController.GetStats(_gimmick.GimmickId); }, () => { LoadStatistics(stats); _isRefreshingStats = false; ((MainActivity)this.Activity).UnblockUI(); }); } }); } private void LoadStatistics(Dictionary<string, int> stats) { int opened = stats["Opened"]; this.OpenedNumberLabel.Text = opened.ToString(); this.OpenedNumberLabel.SetTextColor(ViewBuilder.ColorFromARGB(opened > 0 ? AppController.Colors.AndroidGreen : AppController.Colors.DarkLiver)); this.ViewOpenedButton.Enabled = opened > 0; this.ViewOpenedButton.SetTextUnderline(opened > 0); int working = stats["Working"]; this.WorkingNumberLabel.Text = working.ToString(); this.WorkingNumberLabel.SetTextColor(ViewBuilder.ColorFromARGB(working > 0 ? AppController.Colors.AndroidGreen : AppController.Colors.DarkLiver)); this.ViewWorkingButton.Enabled = working > 0; this.ViewWorkingButton.SetTextUnderline(working > 0); int closed = stats["Closed"]; this.ClosedNumberLabel.Text = closed.ToString(); this.ClosedNumberLabel.SetTextColor(ViewBuilder.ColorFromARGB(closed > 0 ? AppController.Colors.AndroidGreen : AppController.Colors.DarkLiver)); this.ViewClosedButton.Enabled = closed > 0; this.ViewClosedButton.SetTextUnderline(closed > 0); } private void GoToIssues(int filter, bool addNew = false) { var f = new IssuesFragment(); f.Arguments = new Bundle(); f.Arguments.PutInt("GimmickId", _gimmick.GimmickId); f.Arguments.PutInt("Filter", addNew ? 0 : filter); f.Arguments.PutBoolean("AddNew", addNew); this.FragmentManager.BeginTransaction() .AddToBackStack("BeforeIssuesFragment") .Replace(Resource.Id.ContentLayout, f, "IssuesFragment") .Commit(); } #endregion #region Event Handlers private void AddButton_Click(object sender, EventArgs e) { GoToIssues(0, true); } private void ViewIssuesButton_Click(object sender, EventArgs e) { var buttons = new[] { this.ViewOpenedButton, this.ViewWorkingButton, this.ViewClosedButton }; int index = Array.IndexOf(buttons, sender); GoToIssues(index); } #endregion } }
#region Licence... /* The MIT License (MIT) Copyright (c) 2015 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 using Microsoft.Win32; using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Text.RegularExpressions; namespace WixSharp { internal static class RegFileImporter { public static bool SkipUnknownTypes = false; static public RegValue[] ImportFrom(string regFile) { var result = new List<RegValue>(); string content = System.IO.File.ReadAllText(regFile); var parser = new RegParser(); char[] delimiter = new[] { '\\' }; foreach (KeyValuePair<string, Dictionary<string, string>> entry in parser.Parse(content)) foreach (KeyValuePair<string, string> item in entry.Value) { string path = entry.Key; var regval = new RegValue(); regval.Root = GetHive(path); regval.Key = path.Split(delimiter, 2).Last(); regval.Name = item.Key; regval.Value = Deserialize(item.Value, parser.Encoding); if (regval.Value != null) result.Add(regval); } return result.ToArray(); } /* hex: REG_BINARY hex(0): REG_NONE hex(1): REG_SZ (WiX string) hex(2): REG_EXPAND_SZ (Wix expandable) hex(3): REG_BINARY (WiX binary) hex(4): REG_DWORD (WiX integer) hex(5): REG_DWORD_BIG_ENDIAN ; invalid type ? hex(6): REG_LINK hex(7): REG_MULTI_SZ (WiX multiString) hex(8): REG_RESOURCE_LIST hex(9): REG_FULL_RESOURCE_DESCRIPTOR hex(a): REG_RESOURCE_REQUIREMENTS_LIST hex(b): REG_QWORD */ public static object Deserialize(string text, Encoding encoding) { //Note all string are encoded as Encoding.Unicode (UTF16LE) //http://en.wikipedia.org/wiki/Windows_Registry string rawValue = ""; Func<string, bool> isPreffix = preffix => { if (text.StartsWith(preffix, StringComparison.OrdinalIgnoreCase)) { rawValue = text.Substring(preffix.Length); return true; } else return false; }; //WiX 'integer' if (isPreffix("hex(4):") || isPreffix("dword:")) return Convert.ToInt32(rawValue, 16); //WiX 'multiString' if (isPreffix("hex(7):")) { byte[] data = rawValue.Unescape().DecodeFromRegHex(); return encoding.GetString(data).TrimEnd('\0').Replace("\0", "\r\n"); } //WiX 'expandable' if (isPreffix("hex(2):")) { byte[] data = rawValue.Unescape().DecodeFromRegHex(); return encoding.GetString(data).TrimEnd('\0'); } //WiX 'binary' if (isPreffix("hex:")) { byte[] data = rawValue.Unescape().DecodeFromRegHex(); return data; } //WiX 'string' if (isPreffix("hex(1):")) return rawValue.Unescape(); if (isPreffix("\"")) { var strValue = rawValue.Substring(0, rawValue.Length-1); //trim a single " char return Regex.Unescape(strValue); } if (SkipUnknownTypes) return null; else throw new Exception("Cannot deserialize RegFile value: '" + text + "'"); } public static byte[] DecodeFromRegHex(this string obj) { var data = new List<byte>(); for (int i = 0; !string.IsNullOrEmpty(obj) && i < obj.Length; ) { if (obj[i] == ',') { i++; continue; } data.Add(byte.Parse(obj.Substring(i, 2), System.Globalization.NumberStyles.HexNumber)); i += 2; } return data.ToArray(); } static string Unescape(this string text) { //Strip 'continue' char and merge string return Regex.Replace(text, "\\\\\r\n[ ]*", string.Empty); } static RegistryHive GetHive(this string skey) { string tmpLine = skey.Trim(); if (tmpLine.StartsWith("HKEY_LOCAL_MACHINE\\")) return RegistryHive.LocalMachine; if (tmpLine.StartsWith("HKEY_CLASSES_ROOT\\")) return RegistryHive.ClassesRoot; if (tmpLine.StartsWith("HKEY_USERS\\")) return RegistryHive.Users; if (tmpLine.StartsWith("HKEY_CURRENT_CONFIG\\")) return RegistryHive.CurrentConfig; if (tmpLine.StartsWith("HKEY_CURRENT_USER\\")) return RegistryHive.CurrentUser; throw new Exception("Cannot extract hive from key path: " + skey); } } /// <summary> /// Based on Henryk Filipowicz work http://www.codeproject.com/Articles/125573/Registry-Export-File-reg-Parser /// Licensed under The Code Project Open License (CPOL) /// </summary> internal class RegParser { public Encoding Encoding; public Dictionary<string, Dictionary<string, string>> Entries; /// <summary> /// Parses the reg file for reg keys and reg values /// </summary> /// <returns>A Dictionary with reg keys as Dictionary keys and a Dictionary of (valuename, valuedata)</returns> public Dictionary<string, Dictionary<string, string>> Parse(string content) { Encoding = Encoding.GetEncoding(this.GetEncoding(content)); var retValue = new Dictionary<string, Dictionary<string, string>>(); //Get registry keys and values content string Dictionary<string, string> dictKeys = NormalizeDictionary("^[\t ]*\\[.+\\][\r\n]+", content, true); //Get registry values for a given key foreach (KeyValuePair<string, string> item in dictKeys) { Dictionary<string, string> dictValues = NormalizeDictionary("^[\t ]*(\".+\"|@)=", item.Value, false); retValue.Add(item.Key, dictValues); } return Entries = retValue; } /// <summary> /// Creates a flat Dictionary using given search pattern /// </summary> /// <param name="searchPattern">The search pattern</param> /// <param name="content">The content string to be parsed</param> /// <param name="stripeBraces">Flag for striping braces (true for reg keys, false for reg values)</param> /// <returns>A Dictionary with retrieved keys and remaining content</returns> Dictionary<string, string> NormalizeDictionary(string searchPattern, string content, bool stripeBraces) { MatchCollection matches = Regex.Matches(content, searchPattern, RegexOptions.Multiline); Int32 startIndex = 0; Int32 lengthIndex = 0; var dictKeys = new Dictionary<string, string>(); foreach (Match match in matches) { try { //Retrieve key string sKey = match.Value; while (sKey.EndsWith("\r\n")) sKey = sKey.Substring(0, sKey.Length - 2); if (sKey.EndsWith("=")) sKey = sKey.Substring(0, sKey.Length - 1); if (stripeBraces) sKey = StripeBraces(sKey); if (sKey == "@") sKey = ""; else sKey = StripeLeadingChars(sKey, "\""); //Retrieve value startIndex = match.Index + match.Length; Match nextMatch = match.NextMatch(); lengthIndex = ((nextMatch.Success) ? nextMatch.Index : content.Length) - startIndex; string sValue = content.Substring(startIndex, lengthIndex); //Removing the ending CR while (sValue.EndsWith("\r\n")) sValue = sValue.Substring(0, sValue.Length - 2); dictKeys.Add(sKey, sValue); } catch (Exception ex) { throw new Exception(string.Format("Exception thrown on processing string {0}", match.Value), ex); } } return dictKeys; } /// <summary> /// Removes the leading and ending characters from the given string /// </summary> /// <param name="sLine">given string</param> /// <param name="leadChar">The lead character.</param> /// <returns> /// edited string /// </returns> string StripeLeadingChars(string sLine, string leadChar) { string tmpvalue = sLine.Trim(); if (tmpvalue.StartsWith(leadChar) & tmpvalue.EndsWith(leadChar)) { return tmpvalue.Substring(1, tmpvalue.Length - 2); } return tmpvalue; } /// <summary> /// Removes the leading and ending parenthesis from the given string /// </summary> /// <param name="sLine">given string</param> /// <returns>edited string</returns> /// <remarks></remarks> string StripeBraces(string sLine) { string tmpvalue = sLine.Trim(); if (tmpvalue.StartsWith("[") & tmpvalue.EndsWith("]")) { return tmpvalue.Substring(1, tmpvalue.Length - 2); } return tmpvalue; } /// <summary> /// Retrieves the encoding of the reg file, checking the word "REGEDIT4" /// </summary> /// <returns></returns> string GetEncoding(string content) { if (Regex.IsMatch(content, "([ ]*(\r\n)*)REGEDIT4", RegexOptions.IgnoreCase | RegexOptions.Singleline)) return "ANSI"; else return "Unicode"; //The original code had a mistake. It is not UTF8 but UTF16LE (Encoding.Unicode) } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using Microsoft.Win32; using NuGet.Configuration; using Cosmos.Build.Installer; namespace Cosmos.Build.Builder { /// <summary> /// Cosmos task. /// </summary> /// <seealso cref="Cosmos.Build.Installer.Task" /> internal class CosmosTask : Tasks.Task { private string mCosmosPath; // Root Cosmos dir private string mVsipPath; // Build/VSIP private string mAppDataPath; // User Kit in AppData private string mSourcePath; // Cosmos source rood private string mInnoPath; private string mInnoFile; private string mIL2CPUPath; private string mXSPath; private BuildState mBuildState; private int mReleaseNo; private List<string> mExceptionList = new List<string>(); public CosmosTask(ILogger logger, string aCosmosDir, int aReleaseNo) : base(logger) { mCosmosPath = aCosmosDir; mVsipPath = Path.Combine(mCosmosPath, @"Build\VSIP"); mSourcePath = Path.Combine(mCosmosPath, "source"); mAppDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Cosmos User Kit"); mReleaseNo = aReleaseNo; mInnoFile = Path.Combine(mCosmosPath, @"Setup\Cosmos.iss"); mXSPath = Path.GetFullPath(Path.Combine(mCosmosPath, @"..\XSharp")); mIL2CPUPath = Path.GetFullPath(Path.Combine(mCosmosPath, @"..\IL2CPU")); } /// <summary> /// Get name of the setup file based on release number and the current setting. /// </summary> /// <param name="releaseNumber">Release number for the current setup.</param> /// <returns>Name of the setup file.</returns> public static string GetSetupName(int releaseNumber) { return $"CosmosUserKit-{releaseNumber}-vs2017"; } private void CleanDirectory(string aName, string aPath) { if (Directory.Exists(aPath)) { Logger.LogMessage("Cleaning up existing " + aName + " directory."); Directory.Delete(aPath, true); } Logger.LogMessage("Creating " + aName + " as " + aPath); Directory.CreateDirectory(aPath); } protected override List<string> DoRun() { if (PrereqsOK()) { Section("Init Directories"); CleanDirectory("VSIP", mVsipPath); if (!App.BuilderConfiguration.UserKit) { CleanDirectory("User Kit", mAppDataPath); } CompileCosmos(); CreateSetup(); if (!App.BuilderConfiguration.UserKit) { RunSetup(); WriteDevKit(); if (!App.BuilderConfiguration.NoVsLaunch) { LaunchVS(); } } Done(); } return mExceptionList; } protected void MSBuild(string aSlnFile, string aBuildCfg) { string xMSBuild = Path.Combine(Paths.VSPath, "MSBuild", "15.0", "Bin", "msbuild.exe"); string xParams = $"{Quoted(aSlnFile)} " + "/nologo " + "/maxcpucount " + "/nodeReuse:False " + "/p:DeployExtension=False " + $"/p:Configuration={Quoted(aBuildCfg)} " + $"/p:Platform={Quoted("Any CPU")} " + $"/p:OutputPath={Quoted(mVsipPath)}"; if (!App.BuilderConfiguration.NoClean) { StartConsole(xMSBuild, $"/t:Clean {xParams}"); } StartConsole(xMSBuild, $"/t:Build {xParams}"); } protected int NumProcessesContainingName(string name) { return (from x in Process.GetProcesses() where x.ProcessName.Contains(name) select x).Count(); } protected void CheckIfBuilderRunning() { //Check for builder process Logger.LogMessage("Check if Builder is running."); // Check > 1 so we exclude ourself. if (NumProcessesContainingName("Cosmos.Build.Builder") > 1) { throw new Exception("Another instance of builder is running."); } } protected void CheckIfUserKitRunning() { Logger.LogMessage("Check if User Kit Installer is already running."); if (NumProcessesContainingName("CosmosUserKit") > 0) { throw new Exception("Another instance of the user kit installer is running."); } } protected void CheckIfVSandCoRunning() { bool xRunningFound = false; if (IsRunning("devenv")) { xRunningFound = true; Logger.LogMessage("--Visual Studio is running."); } if (IsRunning("VSIXInstaller")) { xRunningFound = true; Logger.LogMessage("--VSIXInstaller is running."); } if (IsRunning("ServiceHub.IdentityHost")) { xRunningFound = true; Logger.LogMessage("--ServiceHub.IdentityHost is running."); } if (IsRunning("ServiceHub.VSDetouredHost")) { xRunningFound = true; Logger.LogMessage("--ServiceHub.VSDetouredHost is running."); } if (IsRunning("ServiceHub.Host.Node.x86")) { xRunningFound = true; Logger.LogMessage("--ServiceHub.Host.Node.x86 is running."); } if (IsRunning("ServiceHub.SettingsHost")) { xRunningFound = true; Logger.LogMessage("--ServiceHub.SettingsHost is running."); } if (IsRunning("ServiceHub.Host.CLR.x86")) { xRunningFound = true; Logger.LogMessage("--ServiceHub.Host.CLR.x86 is running."); } if (xRunningFound) { Logger.LogMessage("--Running blockers found. Setup will warning you and wait for it."); } } protected void NotFound(string aName) { mExceptionList.Add("Prerequisite '" + aName + "' not found."); mBuildState = BuildState.PrerequisiteMissing; } protected bool PrereqsOK() { Section("Check Prerequisites"); CheckIfUserKitRunning(); CheckIfVSandCoRunning(); CheckIfBuilderRunning(); CheckForNetCore(); CheckForVisualStudioExtensionTools(); CheckForInno(); CheckForRepos(); return mBuildState != BuildState.PrerequisiteMissing; } private void CheckForRepos() { Logger.LogMessage("Checking for existing IL2CPU and XSharp repositories..."); if (!Directory.Exists(mIL2CPUPath)) { if (!File.Exists(Path.Combine(mIL2CPUPath, @"IL2CPU.sln"))) { mExceptionList.Add("Missing IL2CPU Repository! Make sure to clone IL2CPU in the parent directory of Cosmos! Download IL2CPU and extract to " + mIL2CPUPath + "."); mBuildState = BuildState.PrerequisiteMissing; return; } } else if (!Directory.Exists(mXSPath)) { if (!File.Exists(Path.Combine(mXSPath, @"XSharp.sln"))) { mExceptionList.Add("Missing XSharp Repository! Make sure to clone XSharp in the parent directory of Cosmos! Download XSharp and extract to " + mXSPath + "."); mBuildState = BuildState.PrerequisiteMissing; return; } } } private void CheckForInno() { Logger.LogMessage("Check for Inno Setup"); using (var xLocalMachineKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32)) { using (var xKey = xLocalMachineKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Inno Setup 5_is1", false)) { if (xKey == null) { mExceptionList.Add("Cannot find Inno Setup."); mBuildState = BuildState.PrerequisiteMissing; return; } mInnoPath = (string)xKey.GetValue("InstallLocation"); if (String.IsNullOrWhiteSpace(mInnoPath)) { mExceptionList.Add("Cannot find Inno Setup."); mBuildState = BuildState.PrerequisiteMissing; return; } } } Logger.LogMessage("Check for Inno Preprocessor"); if (!File.Exists(Path.Combine(mInnoPath, "ISPP.dll"))) { mExceptionList.Add("Inno Preprocessor not detected."); mBuildState = BuildState.PrerequisiteMissing; return; } } private void CheckForNetCore() { Logger.LogMessage("Check for .NET Core"); if (!Paths.VSInstancePackages.Contains("Microsoft.VisualStudio.Workload.NetCoreTools")) { mExceptionList.Add(".NET Core not detected."); mBuildState = BuildState.PrerequisiteMissing; } } private void CheckForVisualStudioExtensionTools() { Logger.LogMessage("Check for Visual Studio Extension Tools"); if (!Paths.VSInstancePackages.Contains("Microsoft.VisualStudio.Workload.VisualStudioExtension")) { mExceptionList.Add("Visual Studio Extension tools not detected."); mBuildState = BuildState.PrerequisiteMissing; } } private void WriteDevKit() { Section("Write Dev Kit to Registry"); // Inno deletes this from registry, so we must add this after. // We let Inno delete it, so if user runs it by itself they get // only UserKit, and no DevKit settings. // HKCU instead of HKLM because builder does not run as admin. // // HKCU is not redirected. using (var xKey = Registry.CurrentUser.CreateSubKey(@"Software\Cosmos")) { xKey.SetValue("DevKit", mCosmosPath); } } private void Clean(string project) { string xNuget = Path.Combine(mCosmosPath, "Build", "Tools", "nuget.exe"); string xListParams = $"sources List"; StartConsole(xNuget, xListParams); var xStart = new ProcessStartInfo(); xStart.FileName = xNuget; xStart.WorkingDirectory = Directory.GetCurrentDirectory(); xStart.Arguments = xListParams; xStart.UseShellExecute = false; xStart.CreateNoWindow = true; xStart.RedirectStandardOutput = true; xStart.RedirectStandardError = true; using (var xProcess = Process.Start(xStart)) { using (var xReader = xProcess.StandardOutput) { string xLine; while (true) { xLine = xReader.ReadLine(); if (xLine == null) { break; } if (xLine.Contains("Cosmos Local Package Feed")) { string xUninstallParams = $"sources Remove -Name \"Cosmos Local Package Feed\""; StartConsole(xNuget, xUninstallParams); } } } } // Clean Cosmos packages from NuGet cache var xGlobalFolder = SettingsUtility.GetGlobalPackagesFolder(Settings.LoadDefaultSettings(Environment.SystemDirectory)); // Later we should specify the packages, currently we're moving to gen3 so package names are a bit unstable foreach (var xFolder in Directory.EnumerateDirectories(xGlobalFolder)) { if (new DirectoryInfo(xFolder).Name.StartsWith("Cosmos", StringComparison.InvariantCultureIgnoreCase)) { CleanPackage(xFolder); } } void CleanPackage(string aPackage) { var xPath = Path.Combine(xGlobalFolder, aPackage); if (Directory.Exists(xPath)) { Directory.Delete(xPath, true); } } } private void Restore(string project) { string xNuget = Path.Combine(mCosmosPath, "Build", "Tools", "nuget.exe"); string xRestoreParams = $"restore {Quoted(project)}"; StartConsole(xNuget, xRestoreParams); } private void Update() { string xNuget = Path.Combine(mCosmosPath, "Build", "Tools", "nuget.exe"); string xUpdateParams = $"update -self"; StartConsole(xNuget, xUpdateParams); } private void Pack(string project, string destDir) { string xMSBuild = Path.Combine(Paths.VSPath, "MSBuild", "15.0", "Bin", "msbuild.exe"); string xParams = $"{Quoted(project)} /nodeReuse:False /t:Restore;Pack /maxcpucount /p:PackageOutputPath={Quoted(destDir)}"; StartConsole(xMSBuild, xParams); } private void Publish(string project, string destDir) { string xMSBuild = Path.Combine(Paths.VSPath, "MSBuild", "15.0", "Bin", "msbuild.exe"); string xParams = $"{Quoted(project)} /nodeReuse:False /t:Publish /maxcpucount /p:RuntimeIdentifier=win7-x86 /p:PublishDir={Quoted(destDir)}"; StartConsole(xMSBuild, xParams); } private void CompileCosmos() { string xVsipDir = Path.Combine(mCosmosPath, "Build", "VSIP"); string xNugetPkgDir = Path.Combine(xVsipDir, "Packages"); Section("Clean NuGet Local Feed"); Clean(Path.Combine(mCosmosPath, @"Build.sln")); Section("Restore NuGet Packages"); Restore(Path.Combine(mCosmosPath, @"Build.sln")); Restore(Path.Combine(mCosmosPath, @"../IL2CPU/IL2CPU.sln")); Restore(Path.Combine(mCosmosPath, @"../XSharp/XSharp.sln")); Section("Update NuGet"); Update(); Section("Build Cosmos"); // Build.sln is the old master but because of how VS manages refs, we have to hack // this short term with the new slns. MSBuild(Path.Combine(mCosmosPath, @"Build.sln"), "Debug"); Section("Publish Tools"); Publish(Path.Combine(mSourcePath, "../../IL2CPU/source/IL2CPU"), Path.Combine(xVsipDir, "IL2CPU")); Section("Create Packages"); // Pack(Path.Combine(mSourcePath, "Cosmos.Build.Tasks"), xNugetPkgDir); // Pack(Path.Combine(mSourcePath, "Cosmos.Common"), xNugetPkgDir); // Pack(Path.Combine(mSourcePath, "Cosmos.Core"), xNugetPkgDir); Pack(Path.Combine(mSourcePath, "Cosmos.Core_Plugs"), xNugetPkgDir); Pack(Path.Combine(mSourcePath, "Cosmos.Core_Asm"), xNugetPkgDir); // Pack(Path.Combine(mSourcePath, "Cosmos.HAL2"), xNugetPkgDir); // Pack(Path.Combine(mSourcePath, "Cosmos.System2"), xNugetPkgDir); Pack(Path.Combine(mSourcePath, "Cosmos.System2_Plugs"), xNugetPkgDir); // Pack(Path.Combine(mSourcePath, "Cosmos.Debug.Kernel"), xNugetPkgDir); Pack(Path.Combine(mSourcePath, "Cosmos.Debug.Kernel.Plugs.Asm"), xNugetPkgDir); // Pack(Path.Combine(mSourcePath, "../../IL2CPU/source/IL2CPU.API"), xNugetPkgDir); } private void CopyTemplates() { Section("Copy Templates"); using (var x = new FileMgr(Logger, Path.Combine(mSourcePath, @"Cosmos.VS.Package\obj\Debug"), mVsipPath)) { x.Copy("CosmosProject (C#).zip"); x.Copy("CosmosKernel (C#).zip"); x.Copy("CosmosProject (F#).zip"); x.Copy("Cosmos.zip"); x.Copy("CosmosProject (VB).zip"); x.Copy("CosmosKernel (VB).zip"); x.Copy(mSourcePath + @"XSharp.VS\Template\XSharpFileItem.zip"); } } private void CreateSetup() { Section("Creating Setup"); string xISCC = Path.Combine(mInnoPath, "ISCC.exe"); if (!File.Exists(xISCC)) { mExceptionList.Add("Cannot find Inno setup."); return; } string xCfg = App.BuilderConfiguration.UserKit ? "UserKit" : "DevKit"; string vsVersionConfiguration = "vs2017"; Logger.LogMessage($" {xISCC} /Q {Quoted(mInnoFile)} /dBuildConfiguration={xCfg} /dVSVersion={vsVersionConfiguration} /dChangeSetVersion={Quoted(mReleaseNo.ToString())}"); StartConsole(xISCC, $"/Q {Quoted(mInnoFile)} /dBuildConfiguration={xCfg} /dVSVersion={vsVersionConfiguration} /dChangeSetVersion={Quoted(mReleaseNo.ToString())}"); } private void LaunchVS() { Section("Launching Visual Studio"); string xVisualStudio = Path.Combine(Paths.VSPath, "Common7", "IDE", "devenv.exe"); if (!File.Exists(xVisualStudio)) { mExceptionList.Add("Cannot find Visual Studio."); return; } Logger.LogMessage("Launching Visual Studio"); Start(xVisualStudio, Quoted(Path.Combine(mCosmosPath, "Kernel.sln")), false, true); } private void RunSetup() { Section("Running Setup"); // These cache in RAM which cause problems, so we kill them if present. KillProcesses("dotnet"); KillProcesses("msbuild"); string setupName = GetSetupName(mReleaseNo); Start(Path.Combine(mCosmosPath, "Setup", "Output", setupName + ".exe"), @"/SILENT"); } private void Done() { Section("Build Complete!"); } } }
using System; using System.Diagnostics; namespace CocosSharp { public class CCMenuItemImage : CCMenuItem { CCSprite disabledImage; CCSprite normalImage; CCSprite selectedImage; CCSprite visibleMenuItemSprite; CCPoint originalScale; #region Properties public CCSprite NormalImage { get { return normalImage; } set { if (value != null && normalImage != value) { normalImage = value; UpdateVisibleMenuItemSprite(); } } } public CCSpriteFrame NormalImageSpriteFrame { set { NormalImage = (value == null) ? new CCSprite() : new CCSprite(value.ContentSize, value); } } public CCSprite SelectedImage { get { return selectedImage; } set { if (value != null && selectedImage != value) { selectedImage = value; UpdateVisibleMenuItemSprite(); } } } public CCSpriteFrame SelectedImageSpriteFrame { set { SelectedImage = (value == null) ? new CCSprite() : new CCSprite(value.ContentSize, value); } } public CCSprite DisabledImage { get { return disabledImage; } set { if (value != null && disabledImage != value) { disabledImage = value; UpdateVisibleMenuItemSprite(); } } } public CCSpriteFrame DisabledImageSpriteFrame { set { DisabledImage = (value == null) ? new CCSprite() : new CCSprite(value.ContentSize, value); } } public override bool Enabled { get { return base.Enabled; } set { base.Enabled = value; UpdateVisibleMenuItemSprite(); } } /// <summary> /// Set this to true if you want to zoom-in/out on the button image like the CCMenuItemLabel works. /// </summary> public bool ZoomBehaviorOnTouch { get; set; } public override bool Selected { set { base.Selected = value; UpdateVisibleMenuItemSprite(); if (Selected && (ZoomActionState == null || ZoomActionState.IsDone)) { originalScale.X = ScaleX; originalScale.Y = ScaleY; } if (ZoomBehaviorOnTouch) { CCPoint zoomScale = (Selected) ? originalScale * 1.2f : originalScale; CCAction zoomAction = new CCScaleTo(0.1f, zoomScale.X, zoomScale.Y); if(ZoomActionState !=null) { ZoomActionState.Stop(); } ZoomActionState = RunAction(zoomAction); } } } #endregion Properties #region Constructors public CCMenuItemImage() : this(new CCSprite()) { } public CCMenuItemImage(CCSprite normalSprite, CCSprite selectedSprite, CCSprite disabledSprite, Action<object> target = null) : base(target) { Debug.Assert(normalSprite != null, "NormalImage cannot be null"); visibleMenuItemSprite = new CCSprite(); NormalImage = normalSprite; SelectedImage = selectedSprite; DisabledImage = disabledSprite; originalScale.X = ScaleX; originalScale.Y = ScaleY; IsColorCascaded = true; IsOpacityCascaded = true; ZoomBehaviorOnTouch = true; AddChild (visibleMenuItemSprite); } public CCMenuItemImage(CCSprite normalSprite, CCSprite selectedSprite, Action<object> target = null) : this(normalSprite, selectedSprite, new CCSprite(), target) { } public CCMenuItemImage(CCSprite normalSprite, Action<object> selector = null) : this(normalSprite, new CCSprite()) { } public CCMenuItemImage(CCSpriteFrame normalSpFrame, CCSpriteFrame selectedSpFrame, CCSpriteFrame disabledSpFrame, Action<object> target = null) : this(new CCSprite(normalSpFrame), new CCSprite(selectedSpFrame), new CCSprite(disabledSpFrame), target) { } public CCMenuItemImage(string normalSprite, string selectedSprite, string disabledSprite, Action<object> target = null) : this(new CCSprite(normalSprite), new CCSprite(selectedSprite), new CCSprite(disabledSprite), target) { } public CCMenuItemImage(string normalSprite, string selectedSprite, Action<object> target = null) : this(new CCSprite(normalSprite), new CCSprite(selectedSprite), target) { } #endregion Constructors protected override void UpdateTransform () { base.UpdateTransform (); } public override void Activate() { if (Enabled) { if (ZoomBehaviorOnTouch) { if(ZoomActionState !=null) { ZoomActionState.Stop(); ZoomActionState = null; } ScaleX = originalScale.X; ScaleY = originalScale.Y; } base.Activate(); } } void UpdateVisibleMenuItemSprite() { if (normalImage == null) return; CCSprite menuItemSprite = null; if(Selected) { menuItemSprite = selectedImage; } if(Enabled == false && menuItemSprite == null) { menuItemSprite = disabledImage; } if (menuItemSprite == null) { menuItemSprite = normalImage; } visibleMenuItemSprite.ContentSize = menuItemSprite.ContentSize; visibleMenuItemSprite.Texture = menuItemSprite.Texture; visibleMenuItemSprite.TextureRectInPixels = menuItemSprite.TextureRectInPixels; visibleMenuItemSprite.IsTextureRectRotated = menuItemSprite.IsTextureRectRotated; ContentSize = visibleMenuItemSprite.ContentSize; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Azure; using Management; using Rest; using 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> /// VirtualNetworksOperations operations. /// </summary> internal partial class VirtualNetworksOperations : IServiceOperations<NetworkManagementClient>, IVirtualNetworksOperations { /// <summary> /// Initializes a new instance of the VirtualNetworksOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal VirtualNetworksOperations(NetworkManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// Deletes the specified virtual network. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified virtual network by resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<VirtualNetwork>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-03-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<VirtualNetwork>(); _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<VirtualNetwork>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a virtual network in the specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update virtual network operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<VirtualNetwork>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<VirtualNetwork> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, parameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all virtual networks in a subscription. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<VirtualNetwork>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-03-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAll", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/virtualNetworks").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<VirtualNetwork>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<VirtualNetwork>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all virtual networks in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<VirtualNetwork>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-03-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<VirtualNetwork>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<VirtualNetwork>>(_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> /// Checks whether a private IP address is available for use. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='ipAddress'> /// The private IP address to be verified. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPAddressAvailabilityResult>> CheckIPAddressAvailabilityWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string ipAddress = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-03-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("ipAddress", ipAddress); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CheckIPAddressAvailability", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/CheckIPAddressAvailability").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (ipAddress != null) { _queryParameters.Add(string.Format("ipAddress={0}", System.Uri.EscapeDataString(ipAddress))); } if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPAddressAvailabilityResult>(); _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<IPAddressAvailabilityResult>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified virtual network. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-03-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 202 && (int)_statusCode != 204 && (int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a virtual network in the specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update virtual network operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<VirtualNetwork>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, VirtualNetwork parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-03-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<VirtualNetwork>(); _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<VirtualNetwork>(_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 == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<VirtualNetwork>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all virtual networks in a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<VirtualNetwork>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAllNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<VirtualNetwork>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<VirtualNetwork>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all virtual networks in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<VirtualNetwork>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<VirtualNetwork>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<VirtualNetwork>>(_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; } } }
using System; using System.Collections; using System.ComponentModel; using SharpGL.SceneGraph.Core; using SharpGL.SceneGraph.Helpers; using System.Xml.Serialization; namespace SharpGL.SceneGraph.Lighting { /// <summary> /// A Light is defined purely mathematically, but works well with OpenGL. /// A light is a scene element, it can be interacted with using the mouse /// and it is bindable. /// </summary> [Serializable()] public class Light : SceneElement, IBindable, IVolumeBound { /// <summary> /// Initializes a new instance of the <see cref="Light"/> class. /// </summary> public Light() { Name = "Light"; Position = new Vertex(0, 3, 0); } /// <summary> /// This function sets all of the lights parameters into OpenGL. /// </summary> /// <param name="gl">The OpenGL instance.</param> public virtual void Bind(OpenGL gl) { if(on) { // Enable this light. gl.Enable(OpenGL.GL_LIGHTING); gl.Enable(glCode); // The light is on, so set it's properties. gl.Light(glCode, OpenGL.GL_AMBIENT, ambient); gl.Light(glCode, OpenGL.GL_DIFFUSE, diffuse); gl.Light(glCode, OpenGL.GL_SPECULAR, specular); gl.Light(glCode, OpenGL.GL_POSITION, new float[] { position.X, position.Y, position.Z, 1.0f }); // 180 degree cutoff gives an omnidirectional light. gl.Light(GLCode, OpenGL.GL_SPOT_CUTOFF, 180.0f); } else gl.Disable(glCode); } /// <summary> /// This is the OpenGL code for the light. /// </summary> private uint glCode = 0; /// <summary> /// The ambient colour of the light. /// </summary> private GLColor ambient = new GLColor(0, 0, 0, 1); /// <summary> /// The diffuse color of the light. /// </summary> private GLColor diffuse = new GLColor(1, 1, 1, 1); /// <summary> /// The specular colour of the light. /// </summary> private GLColor specular = new GLColor(1, 1, 1, 1); /// <summary> /// The colour of the shadow created by this light. /// </summary> private GLColor shadowColor = new GLColor(0, 0, 0, 0.4f); /// <summary> /// True when the light is on. /// </summary> private bool on = false; /// <summary> /// The position of the light. /// </summary> private Vertex position = new Vertex(0, 0, 0); /// <summary> /// Should the light cast a shadow? /// </summary> private bool castShadow = true; /// <summary> /// Used to aid in the implementation of IVolumeBound. /// </summary> private BoundingVolumeHelper boundingVolumeHelper = new BoundingVolumeHelper(); /// <summary> /// Gets the bounding volume. /// </summary> [Browsable(false)] [XmlIgnore] public BoundingVolume BoundingVolume { get { return boundingVolumeHelper.BoundingVolume; } } /// <summary> /// Gets or sets the GL code. /// </summary> /// <value> /// The GL code. /// </value> [Browsable(false)] public uint GLCode { get {return glCode;} set {glCode = value; } } /// <summary> /// Gets or sets the position. /// </summary> /// <value> /// The position. /// </value> [Category("Light"), Description("The position.")] public Vertex Position { get { return position; } set { position = value; BoundingVolume.FromSphericalVolume(position, 0.3f); } } /// <summary> /// Gets or sets the ambient. /// </summary> /// <value> /// The ambient. /// </value> [Category("Light"), Description("The ambient value.")] public System.Drawing.Color Ambient { get {return ambient.ColorNET;} set {ambient.ColorNET = value; } } /// <summary> /// Gets or sets the diffuse. /// </summary> /// <value> /// The diffuse. /// </value> [Category("Light"), Description("The diffuse value.")] public System.Drawing.Color Diffuse { get {return diffuse.ColorNET;} set {diffuse.ColorNET = value; } } /// <summary> /// Gets or sets the specular. /// </summary> /// <value> /// The specular. /// </value> [Category("Light"), Description("The specular value.")] public System.Drawing.Color Specular { get {return specular.ColorNET;} set {specular.ColorNET = value; } } /// <summary> /// Gets or sets the color of the shadow. /// </summary> /// <value> /// The color of the shadow. /// </value> [Category("Light"), Description("The shadow color.")] public GLColor ShadowColor { get {return shadowColor;} set {shadowColor = value; } } /// <summary> /// Gets or sets a value indicating whether this <see cref="Light"/> is on. /// </summary> /// <value> /// <c>true</c> if on; otherwise, <c>false</c>. /// </value> [Description("Is the light turned on?"), Category("Light")] public bool On { get {return on;} set {on = value;} } /// <summary> /// Gets or sets a value indicating whether [cast shadow]. /// </summary> /// <value> /// <c>true</c> if [cast shadow]; otherwise, <c>false</c>. /// </value> [Category("Light"), Description("If true, a shadow is cast.")] public bool CastShadow { get {return castShadow;} set {castShadow = value; } } } }
// // DefaultPreferenceWidgets.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 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 Mono.Unix; using Gtk; using Hyena; using Hyena.Widgets; using Banshee.Base; using Banshee.Sources; using Banshee.Library; using Banshee.Preferences; using Banshee.Collection; using Banshee.ServiceStack; using Banshee.Widgets; using Banshee.Gui.Widgets; namespace Banshee.Preferences.Gui { public static class DefaultPreferenceWidgets { public static void Load (PreferenceService service) { foreach (var library in ServiceManager.SourceManager.FindSources<LibrarySource> ()) { new LibraryLocationButton (library); if (library.PathPattern != null) { var library_page = library.PreferencesPage; var pattern = library.PathPattern; var folder_pattern = library_page["file-system"][pattern.FolderSchema.Key]; folder_pattern.DisplayWidget = new PatternComboBox (library, folder_pattern, pattern.SuggestedFolders); var file_pattern = library_page["file-system"][pattern.FileSchema.Key]; file_pattern.DisplayWidget = new PatternComboBox (library, file_pattern, pattern.SuggestedFiles); var pattern_display = library_page["file-system"].FindOrAdd (new VoidPreference ("file_folder_pattern")); pattern_display.DisplayWidget = new PatternDisplay (library, folder_pattern.DisplayWidget, file_pattern.DisplayWidget); } } service["extensions"].DisplayWidget = new Banshee.Addins.Gui.AddinView (); } private class LibraryLocationButton : HBox { private LibrarySource source; private SchemaPreference<string> preference; private FileChooserButton chooser; private Button reset; private string created_directory; public LibraryLocationButton (LibrarySource source) { this.source = source; preference = source.PreferencesPage["library-location"]["library-location"] as SchemaPreference<string>; preference.ShowLabel = false; preference.DisplayWidget = this; string dir = preference.Value ?? source.DefaultBaseDirectory; Spacing = 5; // FileChooserButton wigs out if the directory does not exist, // so create it if it doesn't and store the fact that we did // in case it ends up not being used, we can remove it try { if (!Banshee.IO.Directory.Exists (dir)) { Banshee.IO.Directory.Create (dir); created_directory = dir; Log.DebugFormat ("Created library directory: {0}", created_directory); } } catch { } chooser = new FileChooserButton (Catalog.GetString ("Select library location"), FileChooserAction.SelectFolder); // Only set the LocalOnly property if false; setting it when true // causes the "Other..." entry to be hidden in older Gtk+ if (!Banshee.IO.Provider.LocalOnly) { chooser.LocalOnly = Banshee.IO.Provider.LocalOnly; } chooser.SetCurrentFolder (dir); chooser.SelectionChanged += OnChooserChanged; HBox box = new HBox (); box.Spacing = 2; box.PackStart (new Image (Stock.Undo, IconSize.Button), false, false, 0); box.PackStart (new Label (Catalog.GetString ("Reset")), false, false, 0); reset = new Button () { Sensitive = dir != source.DefaultBaseDirectory, TooltipText = String.Format (Catalog.GetString ("Reset location to default ({0})"), source.DefaultBaseDirectory) }; reset.Clicked += OnReset; reset.Add (box); //Button open = new Button (); //open.PackStart (new Image (Stock.Open, IconSize.Button), false, false, 0); //open.Clicked += OnOpen; PackStart (chooser, true, true, 0); PackStart (reset, false, false, 0); //PackStart (open, false, false, 0); chooser.Show (); reset.ShowAll (); } private void OnReset (object o, EventArgs args) { chooser.SetFilename (source.DefaultBaseDirectory); } //private void OnOpen (object o, EventArgs args) //{ //open chooser.Filename //} private void OnChooserChanged (object o, EventArgs args) { preference.Value = chooser.Filename; reset.Sensitive = chooser.Filename != source.DefaultBaseDirectory; } protected override void OnUnrealized () { // If the directory we had to create to appease FileSystemChooser exists // and ended up not being the one selected by the user we clean it up if (created_directory != null && chooser.Filename != created_directory) { try { Banshee.IO.Directory.Delete (created_directory); if (!Banshee.IO.Directory.Exists (created_directory)) { Log.DebugFormat ("Deleted unused and empty previous library directory: {0}", created_directory); created_directory = null; } } catch { } } base.OnUnrealized (); } } private class PatternComboBox : DictionaryComboBox<string> { private Preference<string> preference; public PatternComboBox (PrimarySource source, PreferenceBase pref, string [] patterns) { preference = (Preference<string>)pref; bool already_added = false; string conf_pattern = preference.Value; foreach (string pattern in patterns) { if (!already_added && pattern.Equals (conf_pattern)) { already_added = true; } Add (source.PathPattern.CreatePatternDescription (pattern), pattern); } if (!already_added) { Add (source.PathPattern.CreatePatternDescription (conf_pattern), conf_pattern); } ActiveValue = conf_pattern; } protected override void OnChanged () { preference.Value = ActiveValue; base.OnChanged (); } } private class PatternDisplay : WrapLabel { private PatternComboBox folder; private PatternComboBox file; private PrimarySource source; public PatternDisplay (PrimarySource source, object a, object b) { this.source = source; folder= (PatternComboBox)a; file = (PatternComboBox)b; folder.Changed += OnChanged; file.Changed += OnChanged; OnChanged (null, null); } private void OnChanged (object o, EventArgs args) { var pattern = source.PathPattern.CreateFolderFilePattern (folder.ActiveValue, file.ActiveValue); var sb = new System.Text.StringBuilder (); foreach (var track in source.PathPattern.SampleTracks) { string display = source.PathPattern.CreateFromTrackInfo (pattern, track); if (!String.IsNullOrEmpty (display)) { sb.AppendFormat ("<small>{0}.ogg</small>", GLib.Markup.EscapeText (display)); } } Markup = sb.ToString (); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Web.UI; using System.Web.UI.WebControls; using Nucleo.EventArguments; using Nucleo.Web.Registration; using Nucleo.Web.DataFields; using Nucleo.Registration; using Nucleo.Registration.Configuration; using Nucleo.Reflection; namespace Nucleo.Web.Registration { public class CustomRegistrationDetailsView : CompositeDataBoundControl { private CustomRegistrationDetailsViewItemCollection _items = null; #region " Enumerations " public enum ViewMode { /// <summary> /// Readonly mode for the item. /// </summary> View, /// <summary> /// Insertion mode for a new item. /// </summary> Insert, /// <summary> /// Editing mode, which means editing existing information. /// </summary> Edit, /// <summary> /// Determines whether the key value is null; if null, render in insert mode. Otherwise, render in edit mode. /// </summary> EditOrInsert } #endregion #region " Events " public event Nucleo.EventArguments.PropertyChangedEventHandler KeyValueChanged; public event EventHandler KeyValueNullStatusChanged; /// <summary> /// Fired whenever the mode changes within the control. /// </summary> public event EventHandler ModeChanged; /// <summary> /// Fired whenever the mode is starting to change. /// </summary> public event CustomRegistrationDetailsViewModeEventHandler ModeChanging; public event Nucleo.EventArguments.PropertyChangedEventHandler PropertyValueChanged; public event CancelEventHandler PropertyValueChanging; #endregion #region " Properties " /// <summary> /// The name of the configuration to use within the custom registration API. /// </summary> public string ConfigurationName { get { object o = ViewState["ConfigurationName"]; return (o == null) ? string.Empty : (string)o; } set { ViewState["ConfigurationName"] = value; } } /// <summary> /// The current mode being displayed in. /// </summary> public ViewMode CurrentMode { get { object o = ViewState["CurrentMode"]; return (o == null) ? ViewMode.View : (ViewMode)o; } } new private object DataSource { get { throw new InvalidOperationException(); } } new private string DataSourceID { get { throw new InvalidOperationException(); } } /// <summary> /// The collection of items. /// </summary> public CustomRegistrationDetailsViewItemCollection Items { get { if (_items == null) _items = new CustomRegistrationDetailsViewItemCollection(); return _items; } } /// <summary> /// The key value to use when retrieving code. /// </summary> public object KeyFieldValue { get { return ViewState["KeyFieldValue"]; } set { ViewState["KeyFieldValue"] = value; } } #endregion #region " Methods " /// <summary> /// Changes the mode to an alternative mode. /// </summary> /// <param name="mode">The mode to change to.</param> public void ChangeMode(ViewMode mode) { bool changing = false; ViewMode oldMode = this.CurrentMode; if (ViewState["CurrentMode"] == null) { changing = true; } if (!changing && !ViewState["CurrentMode"].Equals(mode)) { changing = true; oldMode = (ViewMode)ViewState["CurrentMode"]; } if (changing) { CustomRegistrationDetailsViewModeEventArgs args = new CustomRegistrationDetailsViewModeEventArgs(oldMode, mode); this.OnModeChanging(args); if (!args.Cancel) ViewState["CurrentMode"] = mode; } if (mode == ViewMode.View) { if (this.KeyFieldValue == null) throw new Exception("The key needs to be provided when changing modes to view mode"); } } /// <summary> /// Creates the table structure within the system. /// </summary> /// <exception cref="ArgumentNullException">Thrown if the <see cref="ConfigurationName">ConfigurationName property</see> is null or if the configuration doesn't exist.</exception> protected override void CreateChildControls() { //if (string.IsNullOrEmpty(this.ConfigurationName)) // throw new ArgumentNullException("ConfigurationName"); //CustomRegistrationSetupElement setupElement = CustomRegistrationSetupSection.Instance.Setups[this.ConfigurationName]; //if (setupElement == null) // throw new ArgumentNullException("The configuration could not be found in the configuration file"); //this.Controls.Clear(); //Table table = new Table(); //this.Controls.Add(table); ////Add an empty header row, so the header is rendered //table.Rows.Add(new TableHeaderRow()); //CustomRegistration registration = this.GetRegistration(); ////Create the label and the UI control for each property //foreach (CustomRegistrationPropertyElement prop in setupElement.PropertyFields) //{ // CustomRegistrationDetailsViewItem item = this.CreateItem(table, prop); // this.Items.Add(item); //} } protected override int CreateChildControls(System.Collections.IEnumerable dataSource, bool dataBinding) { throw new Exception("The method or operation is not implemented."); } /// <summary> /// Creates the control that will edit or insert the value. /// </summary> /// <param name="parentCell">The parent cell for the control adding the values to.</param> /// <param name="property">The property to edit or insert.</param> protected virtual void CreateEditingControl(TableCell parentCell, CustomRegistrationPropertyElement property, object propertyValue) { bool skipMinimumLengthCheck = false; //if (TypeUtility.IsNumericType(property.Type)) // this.CreateNumericEditor(parentCell, property); //else if (TypeUtility.IsEnumeratedType(property.Type)) // this.CreateEnumeratedEditor(parentCell, property); //else // this.CreateStandardEditor(parentCell, property); if (property.IsRequired) { RequiredFieldValidator validator = new RequiredFieldValidator(); parentCell.Controls.Add(validator); validator.ControlToValidate = parentCell.Controls[0].ID; validator.ErrorMessage = string.Format("The '{0}' field is required.", property.Name); } if (!skipMinimumLengthCheck && property.MinimumLength > 0) { RegularExpressionValidator revMinimumLength = new RegularExpressionValidator(); parentCell.Controls.Add(revMinimumLength); revMinimumLength.ControlToValidate = parentCell.Controls[0].ID; revMinimumLength.ErrorMessage = string.Format("The value must be between {0} and {1} characters long.", property.MinimumLength, property.MaximumLength); revMinimumLength.ValidationExpression = string.Format(".{{{0}, {1}}}", property.MinimumLength, property.MaximumLength); } if (TypeUtility.IsNumericType(property.Type)) { RegularExpressionValidator revNumericType = new RegularExpressionValidator(); parentCell.Controls.Add(revNumericType); revNumericType.ControlToValidate = parentCell.Controls[0].ID; revNumericType.ErrorMessage = "The value provided must be numeric"; revNumericType.ValidationExpression = @"\d+"; } } /// <summary> /// Creates an editor that works with enumerated values. /// </summary> /// <param name="parentCell">The cell that contains the editor.</param> /// <param name="property">The property definition for the enumerated type.</param> protected virtual void CreateEnumeratedEditor(TableCell parentCell, CustomRegistrationPropertyElement property, object propertyValue) { DropDownList editControl = new DropDownList(); parentCell.Controls.Add(editControl); Array enumValues = Enum.GetValues(Type.GetType(property.Type)); foreach (object enumValue in enumValues) editControl.Items.Add(enumValue.ToString()); editControl.SelectedValue = this.GetPropertyValueAsString(property, propertyValue); } /// <summary> /// Create a new item based on the properties defined. /// </summary> /// <param name="table">The parent table that contains the control structure.</param> /// <returns>A new instance of the row.</returns> /// <remarks>The row is added to the table after instantiation.</remarks> protected virtual CustomRegistrationDetailsViewItem CreateItem(Table table, CustomRegistrationPropertyElement property, object propertyValue) { CustomRegistrationDetailsViewItem item = new CustomRegistrationDetailsViewItem(property); table.Rows.Add(item); item.Cells.Add(new TableCell()); item.Cells.Add(new TableCell()); Label header = new Label(); item.Cells[0].Controls.Add(header); header.Text = property.Name; if (this.CurrentMode == ViewMode.View) { Label value = new Label(); item.Cells[1].Controls.Add(value); header.AssociatedControlID = value.ID; value.Text = this.GetPropertyValueAsString(property, propertyValue); } else { this.CreateEditingControl(item.Cells[1], property, propertyValue); header.AssociatedControlID = item.Cells[1].Controls[0].ID; } return item; } /// <summary> /// Creates an editor that works with numeric values. /// </summary> /// <param name="parentCell">The cell that contains the editor.</param> /// <param name="property">The property definition for the enumerated type.</param> protected virtual void CreateNumericEditor(TableCell parentCell, CustomRegistrationPropertyElement property, object propertyValue) { TextBox editControl = new TextBox(); parentCell.Controls.Add(editControl); if (property.MaximumLength > 0) editControl.MaxLength = property.MaximumLength; editControl.Text = this.GetPropertyValueAsString(property, propertyValue); } /// <summary> /// Creates an editor that works with any value. /// </summary> /// <param name="parentCell">The cell that contains the editor.</param> /// <param name="property">The property definition for the enumerated type.</param> protected virtual void CreateStandardEditor(TableCell parentCell, CustomRegistrationPropertyElement property, object propertyValue) { TextBox editControl = new TextBox(); parentCell.Controls.Add(editControl); if (property.MaximumLength > 0) editControl.MaxLength = property.MaximumLength; editControl.Text = this.GetPropertyValueAsString(property, propertyValue); } private string GetPropertyValueAsString(CustomRegistrationPropertyElement property, object propertyValue) { if (propertyValue == null) return string.Empty; else if (TypeUtility.IsValueType(property.Type)) return propertyValue.ToString(); else return string.Empty; } private CustomRegistration GetRegistration() { if (this.KeyFieldValue != null) return CustomRegistrationManager.GetRegistration(this.KeyFieldValue); else return CustomRegistrationManager.CreateNewRegistration(); } private void HandleCommand(CommandEventArgs e) { if (string.Compare(e.CommandName, "edit", true) == 0) this.HandleEdit(e); else if (string.Compare(e.CommandName, "insert", true) == 0) this.HandleInsert(e); else if (string.Compare(e.CommandName, "delete", true) == 0) this.HandleDelete(e); } private void HandleDelete(CommandEventArgs e) { } private void HandleEdit(CommandEventArgs e) { } private void HandleInsert(CommandEventArgs e) { } protected override void OnInit(EventArgs e) { if (string.IsNullOrEmpty(this.ConfigurationName)) throw new ArgumentNullException("ConfigurationName"); CustomRegistrationManager.ChangeConfiguration(this.ConfigurationName); base.OnInit(e); } protected virtual void OnKeyValueChanged(Nucleo.EventArguments.PropertyChangedEventArgs e) { if (KeyValueChanged != null) KeyValueChanged(this, e); } protected virtual void OnKeyValueNullStatusChanged(EventArgs e) { if (KeyValueNullStatusChanged != null) KeyValueNullStatusChanged(this, e); } /// <summary> /// Loads the data based on the information provided (such as current mode, and whether a key value exists). /// </summary> /// <param name="e">Empty.</param> protected override void OnLoad(EventArgs e) { //TODO:Determine how to load the data base.OnLoad(e); } /// <summary> /// Raises the mode changed event. /// </summary> /// <param name="e">Empty.</param> protected virtual void OnModeChanged(EventArgs e) { if (ModeChanged != null) ModeChanged(this, e); } /// <summary> /// Raises the mode changing event. /// </summary> /// <param name="e">The details about the change.</param> protected virtual void OnModeChanging(CustomRegistrationDetailsViewModeEventArgs e) { if (ModeChanging != null) ModeChanging(this, e); } protected virtual void OnPropertyValueChanged(Nucleo.EventArguments.PropertyChangedEventArgs e) { if (PropertyValueChanged != null) PropertyValueChanged(this, e); } protected virtual void OnPropertyValueChanging(CancelEventArgs e) { if (PropertyValueChanging != null) PropertyValueChanging(this, e); } protected override void PerformDataBinding(System.Collections.IEnumerable data) { base.PerformDataBinding(data); } #endregion } }
// Copyright 2007-2012 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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. namespace Topshelf.Rehab { using System; using System.Security; using System.Security.Permissions; using System.Threading; using HostConfigurators; using Logging; using Runtime; public class RehabServiceHandle<T> : ServiceHandle, HostControl where T : class { readonly LogWriter _log = HostLogger.Get<RehabServiceHandle<T>>(); readonly ServiceBuilderFactory _serviceBuilderFactory; readonly HostSettings _settings; AppDomain _appDomain; HostControl _hostControl; ServiceHandle _service; public RehabServiceHandle(HostSettings settings, ServiceBuilderFactory serviceBuilderFactory) { _settings = settings; _serviceBuilderFactory = serviceBuilderFactory; _service = CreateServiceInAppDomain(); } void HostControl.RequestAdditionalTime(TimeSpan timeRemaining) { if (_hostControl == null) throw new InvalidOperationException("The HostControl reference has not been set, this is invalid"); _hostControl.RequestAdditionalTime(timeRemaining); } void HostControl.Stop() { if (_hostControl == null) throw new InvalidOperationException("The HostControl reference has not been set, this is invalid"); _hostControl.Stop(); } void HostControl.Restart() { ThreadPool.QueueUserWorkItem(RestartService); } void IDisposable.Dispose() { UnloadServiceAppDomain(); } bool ServiceHandle.Start(HostControl hostControl) { _hostControl = hostControl; var control = new AppDomainHostControl(this); return _service.Start(control); } bool ServiceHandle.Pause(HostControl hostControl) { var control = new AppDomainHostControl(this); return _service.Pause(control); } bool ServiceHandle.Continue(HostControl hostControl) { var control = new AppDomainHostControl(this); return _service.Continue(control); } bool ServiceHandle.Stop(HostControl hostControl) { var control = new AppDomainHostControl(this); return _service.Stop(control); } public void Shutdown(HostControl hostControl) { var control = new AppDomainHostControl(this); _service.Shutdown(control); } public void SessionChanged(HostControl hostControl, SessionChangedArguments arguments) { var control = new AppDomainHostControl(this); _service.SessionChanged(control, arguments); } public void CustomCommand(HostControl hostControl, int command) { var control = new AppDomainHostControl(this); _service.CustomCommand(control, command); } void RestartService(object state) { try { _log.InfoFormat("Restarting service: {0}", _settings.ServiceName); var control = new AppDomainHostControl(this); _service.Stop(control); UnloadServiceAppDomain(); _log.DebugFormat("Service AppDomain unloaded: {0}", _settings.ServiceName); _service = CreateServiceInAppDomain(); _log.DebugFormat("Service created in new AppDomain: {0}", _settings.ServiceName); _service.Start(control); _log.InfoFormat("The service has been restarted: {0}", _settings.ServiceName); } catch (Exception ex) { _log.Error("Failed to restart service", ex); _hostControl.Stop(); } } void UnloadServiceAppDomain() { try { _service.Dispose(); } finally { try { AppDomain.Unload(_appDomain); } catch (Exception ex) { _log.Error("Failed to unload AppDomain", ex); } } } ServiceHandle CreateServiceInAppDomain() { var appDomainSetup = new AppDomainSetup { ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase, ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile, ApplicationName = AppDomain.CurrentDomain.SetupInformation.ApplicationName, LoaderOptimization = LoaderOptimization.MultiDomainHost, }; var permissionSet = new PermissionSet(PermissionState.Unrestricted); permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); AppDomain appDomain = null; try { appDomain = AppDomain.CreateDomain( "Topshelf." + _settings.Name, null, appDomainSetup, permissionSet, null); return CreateServiceHandle(appDomain); } catch (Exception) { if (appDomain != null) { AppDomain.Unload(appDomain); appDomain = null; } throw; } finally { if (appDomain != null) _appDomain = appDomain; } } ServiceHandle CreateServiceHandle(AppDomain appDomain) { Type type = typeof(AppDomainServiceHandle); string assemblyName = type.Assembly.FullName; string typeName = type.FullName ?? typeof(AppDomainServiceHandle).Name; var serviceHandle = (AppDomainServiceHandle)appDomain.CreateInstanceAndUnwrap(assemblyName, typeName); serviceHandle.Create(_serviceBuilderFactory, _settings, HostLogger.CurrentHostLoggerConfigurator); return serviceHandle; } } }
using IntuiLab.Kinect.Events; using System; namespace IntuiLab.Kinect { public class PosturesOrdersFacade : IDisposable { #region Properties #region PostureHomeEnabled public bool PostureHomeEnabled { get { return PropertiesPluginKinect.Instance.EnablePostureHome; } set { if (PropertiesPluginKinect.Instance.EnablePostureHome != value) { PropertiesPluginKinect.Instance.EnablePostureHome = value; } } } #endregion #region TimePostureHome public int TimePostureHome { get { return PropertiesPluginKinect.Instance.HomeLowerBoundForSuccess / 30; } set { if (PropertiesPluginKinect.Instance.HomeLowerBoundForSuccess/30 != value) { PropertiesPluginKinect.Instance.HomeLowerBoundForSuccess = value * 30; } } } #endregion #region PostureStayEnabled public bool PostureStayEnabled { get { return PropertiesPluginKinect.Instance.EnablePostureStay; } set { if (PropertiesPluginKinect.Instance.EnablePostureStay != value) { PropertiesPluginKinect.Instance.EnablePostureStay = value; } } } #endregion #region TimePostureStay public int TimePostureStay { get { return PropertiesPluginKinect.Instance.StayLowerBoundForSuccess / 30; } set { if (PropertiesPluginKinect.Instance.StayLowerBoundForSuccess/30 != value) { PropertiesPluginKinect.Instance.StayLowerBoundForSuccess = value * 30; } } } #endregion #region PostureWaitEnabled public bool PostureWaitEnabled { get { return PropertiesPluginKinect.Instance.EnablePostureWait; } set { if (PropertiesPluginKinect.Instance.EnablePostureWait != value) { PropertiesPluginKinect.Instance.EnablePostureWait = value; } } } #endregion #region TimePostureWait public int TimePostureWait { get { return PropertiesPluginKinect.Instance.WaitLowerBoundForSuccess / 30; } set { if (PropertiesPluginKinect.Instance.WaitLowerBoundForSuccess/30 != value) { PropertiesPluginKinect.Instance.WaitLowerBoundForSuccess = value * 30; } } } #endregion #endregion #region Events #region PostureHomeDetected public event GestureHomeDetectedEventHandler PostureHomeDetected; protected void RaisePostureHomeDetected() { if (PostureHomeDetected != null) { PostureHomeDetected(this, new GestureHomeDetectedEventArgs()); } } private void OnHome(object sender, GestureHomeDetectedEventArgs e) { RaisePostureHomeDetected(); } #endregion #region PostureHomeProgress public event GestureHomeProgressEventHandler PostureHomeProgress; protected void RaisePostureHomeProgress(float percent) { if (PostureHomeProgress != null) { PostureHomeProgress(this, new GestureHomeProgressEventArgs(percent)); } } private void OnHomeProgress(object sender, GestureHomeProgressEventArgs e) { RaisePostureHomeProgress(e.Percent); } #endregion #region PostureHomeLost public event GestureHomeLostEventHandler PostureHomeLost; protected void RaisePostureHomeLost() { if (PostureHomeLost != null) { PostureHomeLost(this, new GestureHomeLostEventArgs()); } } private void OnHomeLost(object sender, GestureHomeLostEventArgs e) { RaisePostureHomeLost(); } #endregion #region PostureStayDetected public event GestureStayDetectedEventHandler PostureStayDetected; protected void RaisePostureStayDetected() { if (PostureStayDetected != null) { PostureStayDetected(this, new GestureStayDetectedEventArgs()); } } private void OnStay(object sender, GestureStayDetectedEventArgs e) { RaisePostureStayDetected(); } #endregion #region PostureStayProgress public event GestureStayProgressEventHandler PostureStayProgress; protected void RaisePostureStayProgress(float percent) { if (PostureStayProgress != null) { PostureStayProgress(this, new GestureStayProgressEventArgs(percent)); } } private void OnStayProgress(object sender, GestureStayProgressEventArgs e) { RaisePostureStayProgress(e.Percent); } #endregion #region PostureStayLost public event GestureStayLostEventHandler PostureStayLost; protected void RaisePostureStayLost() { if (PostureStayLost != null) { PostureStayLost(this, new GestureStayLostEventArgs()); } } private void OnStayLost(object sender, GestureStayLostEventArgs e) { RaisePostureStayLost(); } #endregion #region PostureWaitDetected public event GestureWaitDetectedEventHandler PostureWaitDetected; protected void RaisePostureWaitDetected() { if (PostureWaitDetected != null) { PostureWaitDetected(this, new GestureWaitDetectedEventArgs()); } } private void OnWait(object sender, GestureWaitDetectedEventArgs e) { RaisePostureWaitDetected(); } #endregion #region PostureWaitProgress public event GestureWaitProgressEventHandler PostureWaitProgress; protected void RaisePostureWaitProgress(float percent) { if (PostureWaitProgress != null) { PostureWaitProgress(this, new GestureWaitProgressEventArgs(percent)); } } private void OnWaitProgress(object sender, GestureWaitProgressEventArgs e) { RaisePostureWaitProgress(e.Percent); } #endregion #region PostureWaitLost public event GestureWaitLostEventHandler PostureWaitLost; protected void RaisePostureWaitLost() { if (PostureWaitLost != null) { PostureWaitLost(this, new GestureWaitLostEventArgs()); } } private void OnWaitLost(object sender, GestureWaitLostEventArgs e) { RaisePostureWaitLost(); } #endregion #endregion #region Constructor public PosturesOrdersFacade() { if (PluginKinect.InstancePluginKinect == null) { PluginKinect plugin = new PluginKinect(); } PostureHomeEnabled = true; PostureStayEnabled = true; PostureWaitEnabled = true; TimePostureHome = 1; TimePostureStay = 1; TimePostureWait = 1; ConnectHandler(); Main.RegisterFacade(this); } #endregion #region Public Methods public void ConnectHandler() { if (PluginKinect.InstancePluginKinect != null) { PluginKinect.InstancePluginKinect.Kinect.GestureHomeDetected += OnHome; PluginKinect.InstancePluginKinect.Kinect.GestureHomeProgress += OnHomeProgress; PluginKinect.InstancePluginKinect.Kinect.GestureHomeLost += OnHomeLost; PluginKinect.InstancePluginKinect.Kinect.GestureStayDetected += OnStay; PluginKinect.InstancePluginKinect.Kinect.GestureStayProgress += OnStayProgress; PluginKinect.InstancePluginKinect.Kinect.GestureStayLost += OnStayLost; PluginKinect.InstancePluginKinect.Kinect.GestureWaitDetected += OnWait; PluginKinect.InstancePluginKinect.Kinect.GestureWaitProgress += OnWaitProgress; PluginKinect.InstancePluginKinect.Kinect.GestureWaitLost += OnWaitLost; } } public void ResetHandler() { if (PluginKinect.InstancePluginKinect != null) { PluginKinect.InstancePluginKinect.Kinect.GestureHomeDetected -= OnHome; PluginKinect.InstancePluginKinect.Kinect.GestureHomeProgress -= OnHomeProgress; PluginKinect.InstancePluginKinect.Kinect.GestureHomeLost -= OnHomeLost; PluginKinect.InstancePluginKinect.Kinect.GestureStayDetected -= OnStay; PluginKinect.InstancePluginKinect.Kinect.GestureStayProgress -= OnStayProgress; PluginKinect.InstancePluginKinect.Kinect.GestureStayLost -= OnStayLost; PluginKinect.InstancePluginKinect.Kinect.GestureWaitDetected -= OnWait; PluginKinect.InstancePluginKinect.Kinect.GestureWaitProgress -= OnWaitProgress; PluginKinect.InstancePluginKinect.Kinect.GestureWaitLost -= OnWaitLost; } } #endregion #region IDisposable's members /// <summary> /// Dispose this instance. /// </summary> public void Dispose() { lock (this) { ResetHandler(); } } #endregion } }