context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection; using System.Reflection.Emit; using System.Collections; using System.Collections.Generic; using Xunit; namespace System.Reflection.Emit.Tests { public class ModuleBuilderDefineEnum { private static Type[] s_builtInIntegerTypes = new Type[] { typeof(byte), typeof(SByte), typeof(Int16), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong) }; [Fact] public void TestWithValueType() { List<object> myArray = new List<object>(); myArray = GetVisibilityAttr(true); foreach (TypeAttributes current in myArray) { foreach (Type integerType in s_builtInIntegerTypes) { VerificationHelper(current, integerType); } } } [Fact] public void TestForNonVisibilityAttributes() { List<object> myArray = new List<object>(); myArray = GetVisibilityAttr(false); foreach (TypeAttributes current in myArray) { string name = "MyEnum"; VerificationHelperNegative(name, current, typeof(int), true); } } [Fact] public void TestForAlreadyExistingEnumWithSameName() { List<object> myArray = new List<object>(); myArray = GetVisibilityAttr(true); foreach (TypeAttributes current in myArray) { string name = "MyEnum"; VerificationHelperNegative(name, current, typeof(object), false); } } [Fact] public void TestWithNullName() { List<object> myArray = new List<object>(); myArray = GetVisibilityAttr(true); foreach (TypeAttributes current in myArray) { string name = null; VerificationHelperNegative(name, current, typeof(object), typeof(ArgumentNullException)); } } [Fact] public void TestWithEmptyName() { List<object> myArray = new List<object>(); myArray = GetVisibilityAttr(true); foreach (TypeAttributes current in myArray) { string name = string.Empty; VerificationHelperNegative(name, current, typeof(object), typeof(ArgumentException)); } } [Fact] public void TestWithIncorrectVisibilityAttributes() { List<object> myArray = new List<object>(); myArray = GetNestVisibilityAttr(true); foreach (TypeAttributes current in myArray) { string name = "MyEnum"; VerificationHelperNegative(name, current, typeof(object), true); } } [Fact] public void TestWithReferenceType() { List<object> myArray = new List<object>(); myArray = GetVisibilityAttr(true); foreach (TypeAttributes current in myArray) { VerificationHelperNegative("MyEnum", current, typeof(string), typeof(TypeLoadException)); } } private ModuleBuilder GetModuleBuilder() { ModuleBuilder myModuleBuilder; AssemblyBuilder myAssemblyBuilder; // Get the current application domain for the current thread. AssemblyName myAssemblyName = new AssemblyName(); myAssemblyName.Name = "TempAssembly"; // Define a dynamic assembly in the current domain. myAssemblyBuilder = AssemblyBuilder.DefineDynamicAssembly (myAssemblyName, AssemblyBuilderAccess.Run); // Define a dynamic module in "TempAssembly" assembly. myModuleBuilder = TestLibrary.Utilities.GetModuleBuilder(myAssemblyBuilder, "Module1"); return myModuleBuilder; } private List<object> GetNestVisibilityAttr(bool flag) { List<object> myArray = new List<object>(); if (JudgeVisibilityMaskAttributes(TypeAttributes.NestedAssembly, flag)) myArray.Add(TypeAttributes.NestedAssembly); if (JudgeVisibilityMaskAttributes(TypeAttributes.NestedFamANDAssem, flag)) myArray.Add(TypeAttributes.NestedFamANDAssem); if (JudgeVisibilityMaskAttributes(TypeAttributes.NestedFamily, flag)) myArray.Add(TypeAttributes.NestedFamily); if (JudgeVisibilityMaskAttributes(TypeAttributes.NestedFamANDAssem, flag)) myArray.Add(TypeAttributes.NestedFamANDAssem); if (JudgeVisibilityMaskAttributes(TypeAttributes.NestedFamORAssem, flag)) myArray.Add(TypeAttributes.NestedFamORAssem); if (JudgeVisibilityMaskAttributes(TypeAttributes.NestedPrivate, flag)) myArray.Add(TypeAttributes.NestedPrivate); if (JudgeVisibilityMaskAttributes(TypeAttributes.NestedPublic, flag)) myArray.Add(TypeAttributes.NestedPublic); return myArray; } private List<object> GetVisibilityAttr(bool flag) { List<object> myArray = new List<object>(); if (JudgeVisibilityMaskAttributes(TypeAttributes.Abstract, flag)) myArray.Add(TypeAttributes.Abstract); if (JudgeVisibilityMaskAttributes(TypeAttributes.AnsiClass, flag)) myArray.Add(TypeAttributes.AnsiClass); if (JudgeVisibilityMaskAttributes(TypeAttributes.AutoClass, flag)) myArray.Add(TypeAttributes.AutoClass); if (JudgeVisibilityMaskAttributes(TypeAttributes.AutoLayout, flag)) myArray.Add(TypeAttributes.AutoLayout); if (JudgeVisibilityMaskAttributes(TypeAttributes.BeforeFieldInit, flag)) myArray.Add(TypeAttributes.BeforeFieldInit); if (JudgeVisibilityMaskAttributes(TypeAttributes.Class, flag)) myArray.Add(TypeAttributes.Class); if (JudgeVisibilityMaskAttributes(TypeAttributes.ClassSemanticsMask, flag)) myArray.Add(TypeAttributes.ClassSemanticsMask); if (JudgeVisibilityMaskAttributes(TypeAttributes.CustomFormatClass, flag)) myArray.Add(TypeAttributes.CustomFormatClass); if (JudgeVisibilityMaskAttributes(TypeAttributes.CustomFormatMask, flag)) myArray.Add(TypeAttributes.CustomFormatMask); if (JudgeVisibilityMaskAttributes(TypeAttributes.ExplicitLayout, flag)) myArray.Add(TypeAttributes.ExplicitLayout); if (JudgeVisibilityMaskAttributes(TypeAttributes.HasSecurity, flag)) myArray.Add(TypeAttributes.HasSecurity); if (JudgeVisibilityMaskAttributes(TypeAttributes.Import, flag)) myArray.Add(TypeAttributes.Import); if (JudgeVisibilityMaskAttributes(TypeAttributes.Interface, flag)) myArray.Add(TypeAttributes.Interface); if (JudgeVisibilityMaskAttributes(TypeAttributes.LayoutMask, flag)) myArray.Add(TypeAttributes.LayoutMask); if (JudgeVisibilityMaskAttributes(TypeAttributes.NotPublic, flag)) myArray.Add(TypeAttributes.NotPublic); if (JudgeVisibilityMaskAttributes(TypeAttributes.Public, flag)) myArray.Add(TypeAttributes.Public); if (JudgeVisibilityMaskAttributes(TypeAttributes.RTSpecialName, flag)) myArray.Add(TypeAttributes.RTSpecialName); if (JudgeVisibilityMaskAttributes(TypeAttributes.Sealed, flag)) myArray.Add(TypeAttributes.Sealed); if (JudgeVisibilityMaskAttributes(TypeAttributes.SequentialLayout, flag)) myArray.Add(TypeAttributes.SequentialLayout); if (JudgeVisibilityMaskAttributes(TypeAttributes.Serializable, flag)) myArray.Add(TypeAttributes.Serializable); if (JudgeVisibilityMaskAttributes(TypeAttributes.SpecialName, flag)) myArray.Add(TypeAttributes.SpecialName); if (JudgeVisibilityMaskAttributes(TypeAttributes.StringFormatMask, flag)) myArray.Add(TypeAttributes.StringFormatMask); if (JudgeVisibilityMaskAttributes(TypeAttributes.UnicodeClass, flag)) myArray.Add(TypeAttributes.UnicodeClass); return myArray; } private bool JudgeVisibilityMaskAttributes(TypeAttributes visibility, bool flag) { if (flag) { if ((visibility & ~TypeAttributes.VisibilityMask) == 0) return true; else return false; } else { if ((visibility & ~TypeAttributes.VisibilityMask) != 0) return true; else return false; } } private void VerificationHelper(TypeAttributes myTypeAttribute, Type mytype) { ModuleBuilder myModuleBuilder = GetModuleBuilder(); // Define a enumeration type with name 'MyEnum' in the 'TempModule'. EnumBuilder myEnumBuilder = myModuleBuilder.DefineEnum("MyEnum", myTypeAttribute, mytype); Assert.True(myEnumBuilder.IsEnum); Assert.Equal(myEnumBuilder.FullName, "MyEnum"); myEnumBuilder.CreateTypeInfo().AsType(); } private void VerificationHelperNegative(string name, TypeAttributes myTypeAttribute, Type mytype, bool flag) { ModuleBuilder myModuleBuilder = GetModuleBuilder(); // Define a enumeration type with name 'MyEnum' in the 'TempModule'. Assert.Throws<ArgumentException>(() => { EnumBuilder myEnumBuilder = myModuleBuilder.DefineEnum(name, myTypeAttribute, mytype); if (!flag) { myEnumBuilder = myModuleBuilder.DefineEnum(name, myTypeAttribute, typeof(int)); } }); } private void VerificationHelperNegative(string name, TypeAttributes myTypeAttribute, Type mytype, Type expectedException) { ModuleBuilder myModuleBuilder = GetModuleBuilder(); // Define a enumeration type with name 'MyEnum' in the 'TempModule'. Action test = () => { EnumBuilder myEnumBuilder = myModuleBuilder.DefineEnum(name, myTypeAttribute, mytype); myEnumBuilder.CreateTypeInfo().AsType(); }; Assert.Throws(expectedException, test); } } public class Container1 { public class Nested { private Container1 _parent; public Nested() { } public Nested(Container1 parent) { _parent = parent; } } } }
// // SocialMediaPost.cs // s.im.pl serialization // // Generated by MetaMetadataDotNetTranslator. // Copyright 2017 Interface Ecology Lab. // using Ecologylab.BigSemantics.Generated.Library.CreativeWorkNS; using Ecologylab.BigSemantics.Generated.Library.CreativeWorkNS.BlogPostNS; using Ecologylab.BigSemantics.Generated.Library.PersonNS.AuthorNS; using Ecologylab.BigSemantics.MetaMetadataNS; using Ecologylab.BigSemantics.MetadataNS; using Ecologylab.BigSemantics.MetadataNS.Builtins; using Ecologylab.BigSemantics.MetadataNS.Builtins.PersonNS; using Ecologylab.BigSemantics.MetadataNS.Scalar; using Ecologylab.Collections; using Simpl.Fundamental.Generic; using Simpl.Serialization; using Simpl.Serialization.Attributes; using System; using System.Collections; using System.Collections.Generic; namespace Ecologylab.BigSemantics.Generated.Library.CreativeWorkNS.BlogPostNS { /// <summary> /// social media post /// </summary> [SimplInherit] public class SocialMediaPost : Post { [SimplScalar] private MetadataString titleContent; [SimplComposite] [MmName("shared")] private SocialMediaUser shared; [SimplScalar] private MetadataString shares; [SimplScalar] private MetadataString feeling; /// <summary> /// location created /// </summary> [SimplScalar] private MetadataString creationLocation; /// <summary> /// date created /// </summary> [SimplScalar] private MetadataString date; /// <summary> /// Timestamp of when created AM/PM /// </summary> [SimplScalar] private MetadataString time; [SimplCollection("up_vote")] [MmName("up_votes")] private List<Ecologylab.BigSemantics.MetadataNS.Scalar.MetadataString> upVotes; [SimplScalar] private MetadataString downVotes; [SimplCollection("url")] [MmName("urls")] private List<Ecologylab.BigSemantics.MetadataNS.Scalar.MetadataString> urls; [SimplComposite] [MmName("video")] private SocialVideo video; [SimplCollection("description_content")] [MmName("description_content")] private List<Ecologylab.BigSemantics.MetadataNS.Scalar.MetadataString> descriptionContent; [SimplComposite] [MmName("sticker")] private Image sticker; /// <summary> /// Photos posted in post. /// </summary> [SimplCollection("image")] [MmName("photos")] private List<Image> photos; [SimplScalar] private MetadataString numComments; [SimplCollection("person")] [MmName("with_users")] private List<Person> withUsers; /// <summary> /// comments,replys,subtweets /// </summary> [SimplCollection("social_media_post")] [MmName("comments")] private List<SocialMediaPost> comments; public SocialMediaPost() { } public SocialMediaPost(MetaMetadataCompositeField mmd) : base(mmd) { } public MetadataString TitleContent { get{return titleContent;} set { if (this.titleContent != value) { this.titleContent = value; // TODO we need to implement our property change notification mechanism. } } } public SocialMediaUser Shared { get{return shared;} set { if (this.shared != value) { this.shared = value; // TODO we need to implement our property change notification mechanism. } } } public MetadataString Shares { get{return shares;} set { if (this.shares != value) { this.shares = value; // TODO we need to implement our property change notification mechanism. } } } public MetadataString Feeling { get{return feeling;} set { if (this.feeling != value) { this.feeling = value; // TODO we need to implement our property change notification mechanism. } } } public MetadataString CreationLocation { get{return creationLocation;} set { if (this.creationLocation != value) { this.creationLocation = value; // TODO we need to implement our property change notification mechanism. } } } public MetadataString Date { get{return date;} set { if (this.date != value) { this.date = value; // TODO we need to implement our property change notification mechanism. } } } public MetadataString Time { get{return time;} set { if (this.time != value) { this.time = value; // TODO we need to implement our property change notification mechanism. } } } public List<Ecologylab.BigSemantics.MetadataNS.Scalar.MetadataString> UpVotes { get{return upVotes;} set { if (this.upVotes != value) { this.upVotes = value; // TODO we need to implement our property change notification mechanism. } } } public MetadataString DownVotes { get{return downVotes;} set { if (this.downVotes != value) { this.downVotes = value; // TODO we need to implement our property change notification mechanism. } } } public List<Ecologylab.BigSemantics.MetadataNS.Scalar.MetadataString> Urls { get{return urls;} set { if (this.urls != value) { this.urls = value; // TODO we need to implement our property change notification mechanism. } } } public SocialVideo Video { get{return video;} set { if (this.video != value) { this.video = value; // TODO we need to implement our property change notification mechanism. } } } public List<Ecologylab.BigSemantics.MetadataNS.Scalar.MetadataString> DescriptionContent { get{return descriptionContent;} set { if (this.descriptionContent != value) { this.descriptionContent = value; // TODO we need to implement our property change notification mechanism. } } } public Image Sticker { get{return sticker;} set { if (this.sticker != value) { this.sticker = value; // TODO we need to implement our property change notification mechanism. } } } public List<Image> Photos { get{return photos;} set { if (this.photos != value) { this.photos = value; // TODO we need to implement our property change notification mechanism. } } } public MetadataString NumComments { get{return numComments;} set { if (this.numComments != value) { this.numComments = value; // TODO we need to implement our property change notification mechanism. } } } public List<Person> WithUsers { get{return withUsers;} set { if (this.withUsers != value) { this.withUsers = value; // TODO we need to implement our property change notification mechanism. } } } public List<SocialMediaPost> Comments { get{return comments;} set { if (this.comments != value) { this.comments = value; // TODO we need to implement our property change notification mechanism. } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace LaunchAtlanta.FaceSwap.Web.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.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 Recipies.Api.Areas.HelpPage.Models; namespace Recipies.Api.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); } } } }
using System; using System.Collections.Generic; using System.Linq; using MbUnit.Framework; using Subtext.Framework.Text; namespace UnitTests.Subtext.Framework.Text { /// <summary> /// Summary description for StringHelperTests. /// </summary> [TestFixture] public class StringHelperTests { [Test] public void Remove_PassingInTextWithRepeatingSequenceAndOccurrenceCountOfOne_RemovesFirstOccurrence() { //act string result = "foo/bar/foo".Remove("Foo", 1, StringComparison.OrdinalIgnoreCase); //assert Assert.AreEqual("/bar/foo", result); } [Test] public void Remove_PassingInTextWithRepeatingSequenceAndOccurrenceCountOfTwo_RemovesAllOccurrences() { //act string result = "foo/bar/foo".Remove("Foo", 2, StringComparison.OrdinalIgnoreCase); //assert Assert.AreEqual("/bar/", result); } [Test] public void Remove_PassingInTextWithRepeatingSequenceAndOccurrenceCountOfFour_RemovesAllOccurrences() { //act string result = "foo/bar/foo".Remove("Foo", 4, StringComparison.OrdinalIgnoreCase); //assert Assert.AreEqual("/bar/", result); } [RowTest] [Row("Blah..Blah", '.', "Blah.Blah")] [Row("Blah...Blah", '.', "Blah.Blah")] [Row("Blah....Blah", '.', "Blah.Blah")] [Row("Blah- -Blah", '-', "Blah- -Blah")] [Row("Blah--Blah", '.', "Blah--Blah")] public void CanRemoveDoubleCharacter(string text, char character, string expected) { Assert.AreEqual(expected, text.RemoveDoubleCharacter(character)); } [Test] public void RemoveDoubleCharacter_WithNullCharacter_ThrowsArgumentNullException() { UnitTestHelper.AssertThrowsArgumentNullException( () => "6 bdy.RemoveDoubleCharacter(e)".RemoveDoubleCharacter(Char.MinValue) ); } /// <summary> /// Tests that we can properly pascal case text. /// </summary> /// <remarks> /// Does not remove punctuation. /// </remarks> /// <param name="original"></param> /// <param name="expected"></param> [RowTest] [Row("", "")] [Row("a", "A")] [Row("A", "A")] [Row("A B", "AB")] [Row("a bee keeper's dream.", "ABeeKeeper'sDream.")] public void PascalCaseTests(string original, string expected) { Assert.AreEqual(expected, original.ToPascalCase()); } [Test] public void PascalCaseThrowsArgumentNullException() { UnitTestHelper.AssertThrowsArgumentNullException(() => StringHelper.ToPascalCase(null) ); } [RowTest] [Row("BLAH Tast", "a", 6, StringComparison.Ordinal)] [Row("BLAH Tast", "a", 2, StringComparison.OrdinalIgnoreCase)] public void IndexOfHandlesCaseSensitivity(string source, string search, int expectedIndex, StringComparison comparison) { Assert.AreEqual(expectedIndex, source.IndexOf(search, comparison), "Did not find the string '{0}' at the index {1}", search, expectedIndex); } [RowTest] [Row("Blah/Default.aspx", "Default.aspx", "Blah/", StringComparison.Ordinal)] [Row("Blah/Default.aspx", "default.aspx", "Blah/", StringComparison.OrdinalIgnoreCase)] [Row("Blah/Default.aspx", "default.aspx", "Blah/Default.aspx", StringComparison.Ordinal)] public void LeftBeforeOfHandlesCaseSensitivity(string source, string search, string expected, StringComparison comparison) { Assert.AreEqual(expected, source.LeftBefore(search, comparison), "Truncating did not return the correct result."); } [Test] public void SplitIntoWords_WithStringContainingSpaces_SplitsIntoWords() { //arrange, act IEnumerable<string> words = "this is a test".SplitIntoWords().ToList(); //assert Assert.AreEqual(4, words.Count()); Assert.AreEqual("this", words.First()); Assert.AreEqual("is", words.ElementAt(1)); Assert.AreEqual("a", words.ElementAt(2)); Assert.AreEqual("test", words.ElementAt(3)); } [Test] public void SplitIntoWords_WithStringContainingTabsAndDoubleSpaces_SplitsIntoWords() { //arrange, act IEnumerable<string> words = " this \t is\ta test \t".SplitIntoWords().ToList(); //assert Assert.AreEqual(4, words.Count()); Assert.AreEqual("this", words.First()); Assert.AreEqual("is", words.ElementAt(1)); Assert.AreEqual("a", words.ElementAt(2)); Assert.AreEqual("test", words.ElementAt(3)); } /* "string\r\n".chop #=> "string" "string\n\r".chop #=> "string\n" "string\n".chop #=> "string" "string".chop #=> "strin" "x".chop.chop #=> "" */ [Test] public void Chop_WithStringEndingWithWindowsNewLine_ReturnsStringWithoutNewline() { Assert.AreEqual("string", "string\r\n".Chop()); } [Test] public void Chop_WithStringEndingWithSlashR_OnlyChopsSlashR() { Assert.AreEqual("string\n", "string\n\r".Chop()); } [Test] public void Chop_WithStringEndingWithNewline_ChopsNewline() { Assert.AreEqual("string", "string\n".Chop()); } [Test] public void Chop_WithStringEndingWithLetter_ReturnsStringWithoutLastLetter() { Assert.AreEqual("strin", "string".Chop()); } [Test] public void Chop_WithOneLetter_ReturnsEmptyString() { Assert.AreEqual(string.Empty, "x".Chop()); } /* "hello".chomp #=> "hello" "hello\n".chomp #=> "hello" "hello\r\n".chomp #=> "hello" "hello\n\r".chomp #=> "hello\n" "hello\r".chomp #=> "hello" "hello \n there".chomp #=> "hello \n there" "hello".chomp("llo") #=> "he" */ [Test] public void Chomp_WithStringNotEndingWithDefaultSeparator_ReturnsString() { Assert.AreEqual("hello", "hello".Chomp()); } [Test] public void Chomp_WithStringEndingWithNewline_ChopsNewline() { Assert.AreEqual("hello", "hello\n".Chop()); } [Test] public void Chomp_WithStringEndingWithWindowsNewLine_ReturnsStringWithoutNewline() { Assert.AreEqual("hello", "hello\r\n".Chomp()); } [Test] public void Chomp_WithStringEndingWithSlashNSlashR_OnlyChopsSlashR() { Assert.AreEqual("hello\n", "hello\n\r".Chop()); } [Test] public void Chomp_WithStringEndingWithSlashR_OnlyChopsSlashR() { Assert.AreEqual("hello", "hello\r".Chop()); } [Test] public void Chomp_WithSeparator_ChopsSeparator() { Assert.AreEqual("he", "hello".Chomp("llo", StringComparison.Ordinal)); } [Test] public void Chomp_WithSeparatorButStringNotEndingWithSeparator_LeavesStringAlone() { Assert.AreEqual("hello world", "hello world".Chomp("llo", StringComparison.Ordinal)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; public interface IRetArg<T> { T ReturnArg(T t); } public interface IRetThis { IRetThis ReturnThis(); Type GetMyType(); } public interface IUnimplemented { void UnimplementedMethod(); } public interface IExtra { int InnocentMethod(); } public class CastableException : Exception {}; public class RetArgImpl: IRetArg<string> { public string ReturnArg(string t) { Console.WriteLine("ReturnArg has been called."); return t; } } public class GenRetArgImpl<T>: IRetArg<T> { public T ReturnArg(T t) { Console.WriteLine("Generic ReturnArg has been called. My type is {0}", GetType()); return t; } } public class RetThisImpl: IRetThis { public IRetThis ReturnThis() { Console.WriteLine("RetThis has been called."); return this; } public Type GetMyType() { Console.WriteLine("GetMyType has been called. My type is {0}", GetType()); return GetType(); } } public class Castable : ICastable, IExtra { private Dictionary<Type, Type> _interface2impl; public Castable(Dictionary<Type, Type> interface2impl) { _interface2impl = interface2impl; } public bool IsInstanceOfInterface(RuntimeTypeHandle interfaceType, out Exception castError) { Console.WriteLine("IsInstanceOfInterface has been called for type {0}", Type.GetTypeFromHandle(interfaceType)); if (_interface2impl == null) { castError = new CastableException(); return false; } castError = null; return _interface2impl.ContainsKey(Type.GetTypeFromHandle(interfaceType)); } public RuntimeTypeHandle GetImplType(RuntimeTypeHandle interfaceType) { Console.WriteLine("GetImplType has been called for type {0}", Type.GetTypeFromHandle(interfaceType)); return _interface2impl[Type.GetTypeFromHandle(interfaceType)].TypeHandle; } public int InnocentMethod() { Console.WriteLine("InnocentMethod has been called. My type is {0}", GetType()); return 3; } } public class BadCastable : ICastable { public bool IsInstanceOfInterface(RuntimeTypeHandle interfaceType, out Exception castError) { castError = null; return true; } public RuntimeTypeHandle GetImplType(RuntimeTypeHandle interfaceType) { return default(RuntimeTypeHandle); } } public class Program { private static bool passed = true; public static void Assert(bool value, string message) { if (!value) { Console.WriteLine("FAIL! " + message); passed = false; } } public static int Main() { //Console.WriteLine("Execution started. Attach debugger and press enter."); //Console.ReadLine(); try { object implProxy = new Castable( new Dictionary<Type, Type>() { { typeof(IRetArg<string>), typeof(RetArgImpl) }, { typeof(IRetArg<int>), typeof(GenRetArgImpl<int>) }, { typeof(IRetThis), typeof(RetThisImpl) }, { typeof(IExtra), null }, //we should never use it } ); // testing simple cases Assert(implProxy is IRetThis, "implProxy should be castable to IRetThis via is"); Assert(!(implProxy is IUnimplemented), "implProxy should not be castable to IUnimplemented via is"); Assert((implProxy as IRetThis) != null, "implProxy should be castable to IRetThis is as"); Assert((implProxy as IUnimplemented) == null, "implProxy should not be castable to IUnimplemented is as"); var retThis = (IRetThis)implProxy; Assert(object.ReferenceEquals(retThis.ReturnThis(), implProxy), "RetThis should return implProxy"); Assert(retThis.GetMyType() == typeof(Castable), "GetMyType should return typeof(Castable)"); Assert(!(implProxy is IUnimplemented), "implProxy should not be castable to IUnimplemented via is"); Assert((implProxy as IUnimplemented) == null, "implProxy should not be castable to IUnimplemented via as"); // testing generics IRetArg<string> retArgStr = (IRetArg<string>)implProxy; Assert(retArgStr.ReturnArg("hohoho") == "hohoho", "retArgStr.ReturnArg() should return arg"); IRetArg<int> retArgInt = (IRetArg<int>)implProxy; Assert(retArgInt.ReturnArg(42) == 42, "retArgInt.ReturnArg() should return arg"); // testing Castable implemeting other interfaces var extra = (IExtra)implProxy; Assert(extra.InnocentMethod() == 3, "InnocentMethod() should be called on Castable and return 3"); // testing error handling try { var _ = (IUnimplemented)implProxy; Assert(false, "pProxy should not be castable to I1"); } catch (InvalidCastException) {} object nullCastable = new Castable(null); try { var _ = (IRetThis)nullCastable; Assert(false, "Exceptions should be thrown from IsInstanceOfInterface"); } catch (CastableException) {} Assert(!(nullCastable is IRetThis), "null castable shouldn't be allowed to be casted to anything"); var shouldBeNull = nullCastable as IRetThis; Assert(shouldBeNull == null, "shouldBeNull should be assigned null"); object badCastable = new BadCastable(); try { var r = (IRetThis)badCastable; r.ReturnThis(); Assert(false, "Exceptions should be thrown from ReturnThis()"); } catch (EntryPointNotFoundException) {} //delegate testing Func<int> fInt = new Func<int>(extra.InnocentMethod); Assert(fInt() == 3, "Delegate call to InnocentMethod() should return 3"); Func<IRetThis> func = new Func<IRetThis>(retThis.ReturnThis); Assert(object.ReferenceEquals(func(), implProxy), "Delegate call to ReturnThis() should return this"); } catch (Exception e) { Assert(false, e.ToString()); } if (passed) { Console.WriteLine("Test PASSED!"); return 100; } else { Console.WriteLine("Test FAILED!"); return -1; } } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ArcGIS.Desktop.Framework; using ArcGIS.Desktop.Framework.Contracts; using System.Collections.ObjectModel; using System.Windows.Input; using ArcGIS.Desktop.Layouts; using ArcGIS.Core.CIM; using ArcGIS.Core.Geometry; using ArcGIS.Desktop.Mapping; using ArcGIS.Desktop.Core; using ArcGIS.Desktop.Framework.Threading.Tasks; using LayoutMapSeries.LayoutSettings; using System.Windows.Media; using ArcGIS.Core.Data; using System.Windows.Data; using LayoutMapSeries.Helpers; using System.Windows; using System.Windows.Threading; using ArcGIS.Desktop.Catalog; namespace LayoutMapSeries { internal class GenerateMapSeriesViewModel : DockPane { private const string _dockPaneID = "LayoutMapSeries_GenerateMapSeries"; private SetPages _setPages = null; private Layout _layout = null; private MapSeriesDefinition _mapSeriesDefinition = new MapSeriesDefinition(); private static object _lock = new object(); private MapSeriesHelper _msHelper = new Helpers.MapSeriesHelper(); private ObservableCollection<SetPage> _mapPageLayouts = new ObservableCollection<SetPage>(); private ObservableCollection<MapSeriesItem> _mapSeriesItems = new ObservableCollection<MapSeriesItem>(); protected GenerateMapSeriesViewModel() { _setPages = new SetPages(); BindingOperations.EnableCollectionSynchronization(_mapSeriesItems, _lock); } /// <summary> /// Show the DockPane. /// </summary> internal static void Show() { DockPane pane = FrameworkApplication.DockPaneManager.Find(_dockPaneID); if (pane == null) return; pane.Activate(); } public IReadOnlyCollection<SetPage> PageLayouts { get { if (_mapPageLayouts.Count == 0) { foreach (var setPg in _setPages.SetPageList) { _mapPageLayouts.Add(setPg); } } return _mapPageLayouts; } } private SetPage _myPageLyt = null; public SetPage SelectedPageLayout { get { return _myPageLyt; } set { SetProperty(ref _myPageLyt, value, () => SelectedPageLayout); } } public IReadOnlyCollection<MapSeriesItem> MapSeriesItems { get { return _mapSeriesItems; } } private MapSeriesItem _myMapSeriesItem = null; public MapSeriesItem SelectedMapSeriesItem { get { return _myMapSeriesItem; } set { SetProperty(ref _myMapSeriesItem, value, () => SelectedMapSeriesItem); try { if (_myMapSeriesItem != null) { _msHelper.SetCurrentPageAsync(_layout, _myMapSeriesItem.Oid, _myMapSeriesItem.Id); } } catch (Exception ex) { MessageBox.Show($@"Error in SelectedMapSeriesItem: {ex}"); } } } public ICommand ExportMapSeriesItem { get { return new RelayCommand(async () => { try { // Reference a layoutitem in a project by name LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals(SelectedMapSeriesItem?.LayoutName)); if (layoutItem != null) { // Create the log file and write the current Folder-Connection's to it SaveItemDialog saveDialog = new SaveItemDialog(); saveDialog.Title = "Export the current selected map series item"; saveDialog.OverwritePrompt = true; saveDialog.DefaultExt = "pdf"; // If the save dialog was not dismissed, create the file if (saveDialog.ShowDialog() == true) { await QueuedTask.Run(() => { Layout layout = layoutItem.GetLayout(); if (layout == null) return; // Create PDF format with appropriate settings PDFFormat PDF = new PDFFormat() { Resolution = 300, OutputFileName = saveDialog.FilePath }; if (PDF.ValidateOutputFilePath()) { layout.Export(PDF); } }); } } } catch (Exception ex) { MessageBox.Show($@"Error in create layout: {ex}"); } }, () => SelectedMapSeriesItem != null); } } public ICommand GenerateMapSeries { get { return new RelayCommand(async () => { try { _layout = await QueuedTask.Run<Layout>(() => { //Set up a page CIMPage newPage = new CIMPage { //required Width = SelectedPageLayout.Width, Height = SelectedPageLayout.Height, Units = SelectedPageLayout.LinearUnit }; Layout layout = LayoutFactory.Instance.CreateLayout(newPage); layout.SetName(SelectedPageLayout.LayoutName); //Add Map Frame Coordinate2D llMap = new Coordinate2D(SelectedPageLayout.MarginLayout, SelectedPageLayout.MarginLayout); Coordinate2D urMAP = new Coordinate2D(SelectedPageLayout.WidthMap, SelectedPageLayout.Height - SelectedPageLayout.MarginLayout); Envelope envMap = EnvelopeBuilder.CreateEnvelope(llMap, urMAP); //Reference map, create Map Frame and add to layout MapProjectItem mapPrjItem = Project.Current.GetItems<MapProjectItem>().FirstOrDefault(item => item.Name.Equals("Map")); Map theMap = mapPrjItem.GetMap(); MapFrame mfElm = LayoutElementFactory.Instance.CreateMapFrame(layout, envMap, theMap); mfElm.SetName(SelectedPageLayout.MapFrameName); //Scale bar Coordinate2D llScalebar = new Coordinate2D(2 * SelectedPageLayout.MarginLayout, 2 * SelectedPageLayout.MarginLayout); LayoutElementFactory.Instance.CreateScaleBar(layout, llScalebar, mfElm); //NorthArrow Coordinate2D llNorthArrow = new Coordinate2D(SelectedPageLayout.WidthMap - 2 * SelectedPageLayout.MarginLayout, 2 * SelectedPageLayout.MarginLayout); var northArrow = LayoutElementFactory.Instance.CreateNorthArrow(layout, llNorthArrow, mfElm); northArrow.SetAnchor(Anchor.CenterPoint); northArrow.SetLockedAspectRatio(true); northArrow.SetWidth(2 * SelectedPageLayout.MarginLayout); // Title: dynamic text: <dyn type="page" property="name"/> var title = @"<dyn type = ""page"" property = ""name"" />"; Coordinate2D llTitle = new Coordinate2D(SelectedPageLayout.XOffsetMapMarginalia, SelectedPageLayout.Height - 2 * SelectedPageLayout.MarginLayout); var titleGraphics = LayoutElementFactory.Instance.CreatePointTextGraphicElement(layout, llTitle, null) as TextElement; titleGraphics.SetTextProperties(new TextProperties(title, "Arial", 16, "Bold")); // Table 1 AddTableToLayout(layout, theMap, mfElm, "Inspection Locations", SelectedPageLayout, 3 * SelectedPageLayout.HeightPartsMarginalia); // Table 2 AddTableToLayout(layout, theMap, mfElm, "Service Locations", SelectedPageLayout, 2 * SelectedPageLayout.HeightPartsMarginalia); // legend Coordinate2D llLegend = new Coordinate2D(SelectedPageLayout.XOffsetMapMarginalia, SelectedPageLayout.MarginLayout); Coordinate2D urLegend = new Coordinate2D(SelectedPageLayout.XOffsetMapMarginalia + SelectedPageLayout.XWidthMapMarginalia, SelectedPageLayout.HeightPartsMarginalia); System.Diagnostics.Debug.WriteLine(mfElm); LayoutElementFactory.Instance.CreateLegend(layout, EnvelopeBuilder.CreateEnvelope(llLegend, urLegend), mfElm); // Defince the CIM MapSeries var CimSpatialMapSeries = new CIMSpatialMapSeries() { Enabled = true, MapFrameName = SelectedPageLayout.MapFrameName, StartingPageNumber = 1, CurrentPageID = 1, IndexLayerURI = "CIMPATH=map/railroadmaps.xml", NameField = "ServiceAreaName", SortField = "SeqId", RotationField = "Angle", SortAscending = true, ScaleRounding = 1000, ExtentOptions = ExtentFitType.BestFit, MarginType = ArcGIS.Core.CIM.UnitType.Percent, Margin = 2 }; CIMLayout layCIM = layout.GetDefinition(); layCIM.MapSeries = CimSpatialMapSeries; layout.SetDefinition(layCIM); return layout; }); //CREATE, OPEN LAYOUT VIEW (must be in the GUI thread) ILayoutPane layoutPane = await LayoutFrameworkExtender.CreateLayoutPaneAsync(ProApp.Panes,_layout); var cimLayout = await QueuedTask.Run<CIMLayout>(() => { return _layout.GetDefinition(); }); // refresh the UI with the map series records _msHelper = null; { MapProjectItem mapPrjItem = Project.Current.GetItems<MapProjectItem>().FirstOrDefault(item => item.Name.Equals("Map")); MapSeriesDefinition ms = await QueuedTask.Run<MapSeriesDefinition>(() => { var theMap = mapPrjItem.GetMap(); var fc = GetFeatureClassByName(theMap, "RailroadMaps"); var newMs = new MapSeriesDefinition { FeatureClassName = fc.GetName() }; newMs.LoadFromFeatureClass(layoutPane.LayoutView.Layout.Name, fc, "ID,ServiceAreaName"); _msHelper = new Helpers.MapSeriesHelper(); _msHelper.Initialize(_layout, GetFeatureLayerFromMap (theMap, "RailroadMaps")); return newMs; }); lock (_lock) { _mapSeriesItems.Clear(); } var setSelection = true; foreach (var msItem in ms.MapSeriesItems) { var newMsItem = new MapSeriesItem { Id = msItem.Id, Name = msItem.Name, Oid = msItem.Oid, LayoutName = msItem.LayoutName }; lock (_lock) _mapSeriesItems.Add(newMsItem); if (setSelection) { setSelection = false; await Application.Current.Dispatcher.BeginInvoke( DispatcherPriority.Background, new Action(() => { SelectedMapSeriesItem = newMsItem; })); } } } } catch (Exception ex) { MessageBox.Show($@"Error in create layout: {ex}"); } }, () => SelectedPageLayout != null); } } private CIMPointSymbol GetPointSymbolFromLayer(Layer layer) { if (!(layer is FeatureLayer)) return null; var fLyr = layer as FeatureLayer; var renderer = fLyr.GetRenderer() as CIMSimpleRenderer; if (renderer == null || renderer.Symbol == null) return null; return renderer.Symbol.Symbol as CIMPointSymbol; } private FeatureClass GetFeatureClassByName(Map theMap, string fcName) { var layers = theMap.FindLayers(fcName, true); if (layers.Count > 0) { Layer lyr = layers[0]; if (lyr is FeatureLayer) return (lyr as FeatureLayer).GetFeatureClass(); } return null; } private FeatureLayer GetFeatureLayerFromMap(Map theMap, string featureLayerName) { var lyrs = theMap.FindLayers(featureLayerName, true); if (lyrs.Count > 0) { return lyrs[0] as FeatureLayer; } return null; } private void AddTableToLayout(Layout layout, Map theMap, MapFrame mfElm, string layerName, SetPage setPage, double yOffset) { var lyrs = theMap.FindLayers(layerName, true); if (lyrs.Count > 0) { Layer lyr = lyrs[0]; var ptSymbol = GetPointSymbolFromLayer(lyr); if (ptSymbol != null) { Coordinate2D llSym = new Coordinate2D(setPage.XOffsetMapMarginalia, setPage.YOffsetSymbol + yOffset); var sym = LayoutElementFactory.Instance.CreatePointGraphicElement(layout, llSym, ptSymbol); Coordinate2D llText = new Coordinate2D(setPage.XOffsetMapMarginalia + sym.GetWidth(), setPage.YOffsetSymbol + yOffset - sym.GetHeight()/2); var text = LayoutElementFactory.Instance.CreatePointTextGraphicElement(layout, llText, lyr.Name); text.SetAnchor(Anchor.CenterPoint); text.SetHeight(text.GetHeight()); if (text.GetHeight() > sym.GetHeight()) { sym.SetLockedAspectRatio(true); sym.SetHeight(text.GetHeight()); } else { text.SetLockedAspectRatio(true); text.SetHeight(sym.GetHeight()); } } Coordinate2D llTab1 = new Coordinate2D(setPage.XOffsetMapMarginalia, yOffset - setPage.HeightPartsMarginalia); Coordinate2D urTab1 = new Coordinate2D(setPage.XOffsetMapMarginalia + setPage.XWidthMapMarginalia, yOffset); var table1 = LayoutElementFactory.Instance.CreateTableFrame(layout, EnvelopeBuilder.CreateEnvelope(llTab1, urTab1), mfElm, lyr, new string[] { "No", "Type", "Description" }); } } } /// <summary> /// Button implementation to show the DockPane. /// </summary> internal class GenerateMapSeries_ShowButton : Button { protected override void OnClick() { GenerateMapSeriesViewModel.Show(); } } }
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Xml.Serialization; using System.Reflection; using System.Threading; using Analysis; using Analysis.EDM; using Data; using Data.EDM; using SirCachealot.Database; using SirCachealot.Parallel; namespace SirCachealot { public class Controller : MarshalByRefObject { // UI internal MainWindow mainWindow; System.Threading.Timer statusMonitorTimer; // Database private MySqlDBlockStore blockStore; // TOF Demodulation // private TOFChannelSetGroupAccumulator tcsga; private object accumulatorLock = new object(); // Threading private ThreadManager threadManager = new ThreadManager(); #region Setup and UI // This method is called before the main form is created. // Don't do any UI stuff here! internal void Initialise() { //set up sql database blockStore = new MySqlDBlockStore(); blockStore.Start(); threadManager.InitialiseThreading(this); } // This method is called by the GUI thread once the form has // loaded and the UI is ready. internal void UIInitialise() { // put the version number in the title bar to avoid confusion! Version version = Assembly.GetEntryAssembly().GetName().Version; mainWindow.Text += " " + version.ToString(); // This will load the shared code assembly so that we can get its // version number and display that as well. TOF t = new TOF(); Version sharedCodeVersion = Assembly.GetAssembly(t.GetType()).GetName().Version; mainWindow.Text += " (" + sharedCodeVersion.ToString() + ")"; // start the status monitor statusMonitorTimer = new System.Threading.Timer(new TimerCallback(UpdateStatusMonitor), null, 500, 500); } // this method gets called by the main window menu exit item, and when // the form's close button is pressed. internal void Exit() { blockStore.Stop(); // not sure whether this is needed, or even helpful. statusMonitorTimer.Dispose(); } internal void UpdateStatusMonitor(object unused) { StringBuilder b = new StringBuilder(); b.AppendLine(threadManager.GetThreadStats()); b.AppendLine(""); b.AppendLine(GetDatabaseStats()); mainWindow.SetStatsText(b.ToString()); } internal void log(string txt) { mainWindow.AppendToLog(txt); } internal void errorLog(string txt) { mainWindow.AppendToErrorLog(txt); } // without this method, any remote connections to this object will time out after // five minutes of inactivity. // It just overrides the lifetime lease system completely. public override Object InitializeLifetimeService() { return null; } #endregion #region Threading methods public void ClearAnalysisRunStats() { threadManager.ClearAnalysisRunStats(); } #endregion #region Database methods /* This is the interface that SirCachealot provides to the d-block store. The actual d-block * store class is an instance of the DBlock store interface. That object is available as a * private member, for internal use. External users need to get the block store through this * getter, which only exposes the block store's generic functions. */ public DBlockStore DBlockStore { get { return blockStore; } } /* This is a convenient way to add a block, if you're using standard demodulation * configurations. This method is thread-safe. */ public void AddBlock(Block b, string[] demodulationConfigs) { log("Adding block " + b.Config.Settings["cluster"] + " - " + b.Config.Settings["clusterIndex"]); BlockDemodulator blockDemodulator = new BlockDemodulator(); foreach (string dcName in demodulationConfigs) { DemodulationConfig dc = DemodulationConfig.GetStandardDemodulationConfig(dcName, b); DemodulatedBlock dBlock = blockDemodulator.DemodulateBlockNL(b, dc); blockStore.AddDBlock(dBlock); } } // This method is thread-safe. public void AddBlock(string path, string[] demodulationConfigs) { string[] splitPath = path.Split('\\'); log("Loading block " + splitPath[splitPath.Length - 1]); BlockSerializer bs = new BlockSerializer(); Block b = bs.DeserializeBlockFromZippedXML(path, "block.xml"); AddBlock(b, demodulationConfigs); } // Use this to add blocks to SirCachealot's analysis queue. public void AddBlockToQueue(string path, string[] demodulationConfigs) { blockAddParams bap = new blockAddParams(); bap.path = path; bap.demodulationConfigs = demodulationConfigs; threadManager.AddToQueue(AddBlockThreadWrapper, bap); } // Use this to add blocks to SirCachealot's analysis queue. public void AddBlocksToQueue(string[] paths, string[] demodulationConfigs) { foreach (string path in paths) { blockAddParams bap = new blockAddParams(); bap.path = path; bap.demodulationConfigs = demodulationConfigs; threadManager.AddToQueue(AddBlockThreadWrapper, bap); } } // this method and the following struct are wrappers so that we can add a block // with a single parameter, as required by the threadpool. private void AddBlockThreadWrapper(object parametersIn) { threadManager.QueueItemWrapper(delegate(object parms) { blockAddParams parameters = (blockAddParams)parms; AddBlock(parameters.path, parameters.demodulationConfigs); }, parametersIn ); } private struct blockAddParams { public string path; public string[] demodulationConfigs; // this struct has a ToString method defined for error reporting porpoises. public override string ToString() { return path; } } internal void CreateDB() { CreateDBDialog dialog = new CreateDBDialog(); if (dialog.ShowDialog() == DialogResult.OK) { blockStore.CreateDatabase(dialog.GetName()); log("Created db: " + dialog.GetName()); } } internal void SelectDB() { List<string> databases = blockStore.GetDatabaseList(); ListSelectionDialog dialog = new ListSelectionDialog(); dialog.Populate(databases); if (dialog.ShowDialog() == DialogResult.OK) { string db = dialog.SelectedItem(); if (db != "") { SelectDB(db); } } } public void SelectDB(string db) { blockStore.Connect(db); log("Selected db: " + db); } private string GetDatabaseStats() { StringBuilder b = new StringBuilder(); b.AppendLine("Database queries: " + blockStore.QueryCount); b.AppendLine("DBlocks served: " + blockStore.DBlockCount); return b.ToString(); } #endregion #region TOFDemodulation //public void TOFDemodulateBlocks(string[] blockFiles, string savePath) //{ // // first of all test that the save location exists to avoid later disappointment. // if (!Directory.Exists(Path.GetDirectoryName(savePath))) // { // log("Save path does not exist!!"); // return; // } // // initialise the accumulator // tcsga = new TOFChannelSetGroupAccumulator(); // // queue the blocks - the last block analysed will take care of saving the results. // foreach (string blockFile in blockFiles) // { // tofDemodulateParams tdp = new tofDemodulateParams(); // tdp.blockPath = blockFile; // tdp.savePath = savePath; // threadManager.AddToQueue(TOFDemodulateThreadWrapper, tdp); // } //} //private void TOFDemodulateBlock(string blockPath, string savePath) //{ // BlockSerializer bs = new BlockSerializer(); // string[] splitPath = blockPath.Split('\\'); // log("Loading block " + splitPath[splitPath.Length - 1]); // Block b = bs.DeserializeBlockFromZippedXML(blockPath, "block.xml"); // log("Demodulating block " + b.Config.Settings["cluster"] + " - " + b.Config.Settings["clusterIndex"]); // BlockTOFDemodulator btd = new BlockTOFDemodulator(); // TOFChannelSet tcs = btd.TOFDemodulateBlock(b, 0, true); // log("Accumulating block " + b.Config.Settings["cluster"] + " - " + b.Config.Settings["clusterIndex"]); // lock (accumulatorLock) tcsga.Add(tcs); // // are we the last block to be added? If so, it's our job to save the results // if (threadManager.RemainingJobs == 1) // { // // this lock should not be needed // lock(accumulatorLock) // { // TOFChannelSetGroup tcsg = tcsga.GetResult(); // Stream fileStream = new FileStream(savePath, FileMode.Create); // (new BinaryFormatter()).Serialize(fileStream, tcsg); // fileStream.Close(); // } // } //} //private void TOFDemodulateThreadWrapper(object parametersIn) //{ // threadManager.QueueItemWrapper(delegate(object parms) // { // tofDemodulateParams parameters = (tofDemodulateParams)parms; // TOFDemodulateBlock(parameters.blockPath, parameters.savePath); // }, // parametersIn // ); //} //private struct tofDemodulateParams //{ // public string blockPath; // public string savePath; // // this struct has a ToString method defined for error reporting porpoises. // public override string ToString() // { // return blockPath; // } //} #endregion #region Testing // Somewhere for SirCachealot to store test results that's accessible by Mathematica. // Makes debugging easier and is needed as a workaround for the constant Mathematica // NET/Link errors. // public TOFChannelSetGroup ChanSetGroup; // workarounds for NET/Link bugs //public TOFChannelSet GetAveragedChannelSet(bool eSign, bool bSign, bool rfSign) //{ // return ChanSetGroup.AverageChannelSetSignedByMachineState(eSign, bSign, rfSign); //} //public void LoadChannelSetGroup(string path) //{ // BinaryFormatter bf = new BinaryFormatter(); // FileStream fs = new FileStream(path, FileMode.Open); // ChanSetGroup = (TOFChannelSetGroup)bf.Deserialize(fs); // fs.Close(); //} public void Test1() { BlockSerializer bs = new BlockSerializer(); Block b = bs.DeserializeBlockFromZippedXML( "C:\\Users\\jony\\Files\\Data\\SEDM\\v3\\2009\\October2009\\01Oct0900_0.zip", "block.xml"); BlockDemodulator bd = new BlockDemodulator(); DemodulatedBlock db = bd.DemodulateBlockNL(b, DemodulationConfig.GetStandardDemodulationConfig("cgate11Fixed", b)); //JsonSerializer serializer = new JsonSerializer(); //using (StreamWriter sw = new StreamWriter("c:\\Users\\jony\\Desktop\\test.json")) //using (JsonWriter writer = new JsonTextWriter(sw)) //{ // serializer.Serialize(writer, b.Config); //} //bs.SerializeBlockAsJSON("c:\\Users\\jony\\Desktop\\test.json", b); } #endregion } }
#region PDFsharp - A .NET library for processing PDF // // Authors: // Stefan Lange // // Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany) // // http://www.pdfsharp.com // http://sourceforge.net/projects/pdfsharp // // 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.Diagnostics; using System.Collections.Generic; using System.Text; #if CORE || GDI using System.Drawing; using GdiFontFamily = System.Drawing.FontFamily; using GdiFont = System.Drawing.Font; #endif #if WPF using System.Windows; using System.Windows.Media; using System.Windows.Resources; using WpfFontFamily = System.Windows.Media.FontFamily; using WpfGlyphTypeface = System.Windows.Media.GlyphTypeface; using WpfTypeface = System.Windows.Media.Typeface; #endif using PdfSharp.Drawing; using PdfSharp.Fonts.OpenType; using PdfSharp.Internal; #pragma warning disable 1591 // ReSharper disable RedundantNameQualifier namespace PdfSharp.Fonts { /// <summary> /// Provides functionality to map a fontface request to a physical font. /// </summary> internal static class FontFactory { //// Suffix for internal face names to indicate that the font data comes from the platform //// and not from the users font resolver. //public const string PlatformTag = "platform:"; /// <summary> /// Converts specified information about a required typeface into a specific font. /// </summary> /// <param name="familyName">Name of the font family.</param> /// <param name="fontResolvingOptions">The font resolving options.</param> /// <param name="typefaceKey">Typeface key if already known by caller, null otherwise.</param> /// <returns> /// Information about the typeface, or null if no typeface can be found. /// </returns> public static FontResolverInfo ResolveTypeface(string familyName, FontResolvingOptions fontResolvingOptions, string typefaceKey) { if (string.IsNullOrEmpty(typefaceKey)) typefaceKey = XGlyphTypeface.ComputeKey(familyName, fontResolvingOptions); try { Lock.EnterFontFactory(); // Was this typeface requested before? FontResolverInfo fontResolverInfo; if (FontResolverInfosByName.TryGetValue(typefaceKey, out fontResolverInfo)) return fontResolverInfo; // Case: This typeface was not resolved before. // Is there a custom font resolver available? IFontResolver customFontResolver = GlobalFontSettings.FontResolver; if (customFontResolver != null) { // Case: Use custom font resolver. fontResolverInfo = customFontResolver.ResolveTypeface(familyName, fontResolvingOptions.IsBold, fontResolvingOptions.IsItalic); // If resolved by custom font resolver register info and font source. if (fontResolverInfo != null && !(fontResolverInfo is PlatformFontResolverInfo)) { string resolverInfoKey = fontResolverInfo.Key; FontResolverInfo existingFontResolverInfo; if (FontResolverInfosByName.TryGetValue(resolverInfoKey, out existingFontResolverInfo)) { // Case: A new typeface was resolved with the same info as a previous one. // Discard new object an reuse previous one. fontResolverInfo = existingFontResolverInfo; // Associate with typeface key. FontResolverInfosByName.Add(typefaceKey, fontResolverInfo); #if DEBUG // The font source should exist. Debug.Assert(FontSourcesByName.ContainsKey(fontResolverInfo.FaceName)); #endif } else { // Case: No such font resolver info exists. // Add to both dictionaries. FontResolverInfosByName.Add(typefaceKey, fontResolverInfo); Debug.Assert(resolverInfoKey == fontResolverInfo.Key); FontResolverInfosByName.Add(resolverInfoKey, fontResolverInfo); // Create font source if not yet exists. XFontSource previousFontSource; if (FontSourcesByName.TryGetValue(fontResolverInfo.FaceName, out previousFontSource)) { // Case: The font source exists, because a previous font resolver info comes // with the same face name, but was different in style simulation flags. // Nothing to do. } else { // Case: Get font from custom font resolver and create font source. byte[] bytes = customFontResolver.GetFont(fontResolverInfo.FaceName); XFontSource fontSource = XFontSource.GetOrCreateFrom(bytes); // Add font source's font resolver name if it is different to the face name. if (string.Compare(fontResolverInfo.FaceName, fontSource.FontName, StringComparison.OrdinalIgnoreCase) != 0) FontSourcesByName.Add(fontResolverInfo.FaceName, fontSource); } } } } else { // Case: There was no custom font resolver set. // Use platform font resolver. // If it was successful resolver info and font source are cached // automatically by PlatformFontResolver.ResolveTypeface. fontResolverInfo = PlatformFontResolver.ResolveTypeface(familyName, fontResolvingOptions, typefaceKey); } // Return value is null if the typeface could not be resolved. // In this case PDFsharp stops. return fontResolverInfo; } finally { Lock.ExitFontFactory(); } } #if GDI /// <summary> /// Registers the font face. /// </summary> public static XFontSource RegisterFontFace(byte[] fontBytes) { try { Lock.EnterFontFactory(); ulong key = FontHelper.CalcChecksum(fontBytes); XFontSource fontSource; if (FontSourcesByKey.TryGetValue(key, out fontSource)) { throw new InvalidOperationException("Font face already registered."); } fontSource = XFontSource.GetOrCreateFrom(fontBytes); Debug.Assert(FontSourcesByKey.ContainsKey(key)); Debug.Assert(fontSource.Fontface != null); //fontSource.Fontface = new OpenTypeFontface(fontSource); //FontSourcesByKey.Add(checksum, fontSource); //FontSourcesByFontName.Add(fontSource.FontName, fontSource); XGlyphTypeface glyphTypeface = new XGlyphTypeface(fontSource); FontSourcesByName.Add(glyphTypeface.Key, fontSource); GlyphTypefaceCache.AddGlyphTypeface(glyphTypeface); return fontSource; } finally { Lock.ExitFontFactory(); } } #endif /// <summary> /// Gets the bytes of a physical font with specified face name. /// </summary> public static XFontSource GetFontSourceByFontName(string fontName) { XFontSource fontSource; if (FontSourcesByName.TryGetValue(fontName, out fontSource)) return fontSource; Debug.Assert(false, string.Format("An XFontSource with the name '{0}' does not exists.", fontName)); return null; } /// <summary> /// Gets the bytes of a physical font with specified face name. /// </summary> public static XFontSource GetFontSourceByTypefaceKey(string typefaceKey) { XFontSource fontSource; if (FontSourcesByName.TryGetValue(typefaceKey, out fontSource)) return fontSource; Debug.Assert(false, string.Format("An XFontSource with the typeface key '{0}' does not exists.", typefaceKey)); return null; } public static bool TryGetFontSourceByKey(ulong key, out XFontSource fontSource) { return FontSourcesByKey.TryGetValue(key, out fontSource); } /// <summary> /// Gets a value indicating whether at least one font source was created. /// </summary> public static bool HasFontSources { get { return FontSourcesByName.Count > 0; } } public static bool TryGetFontResolverInfoByTypefaceKey(string typeFaceKey, out FontResolverInfo info) { return FontResolverInfosByName.TryGetValue(typeFaceKey, out info); } public static bool TryGetFontSourceByTypefaceKey(string typefaceKey, out XFontSource source) { return FontSourcesByName.TryGetValue(typefaceKey, out source); } //public static bool TryGetFontSourceByFaceName(string faceName, out XFontSource source) //{ // return FontSourcesByName.TryGetValue(faceName, out source); //} internal static void CacheFontResolverInfo(string typefaceKey, FontResolverInfo fontResolverInfo) { FontResolverInfo existingfFontResolverInfo; // Check whether identical font is already registered. if (FontResolverInfosByName.TryGetValue(typefaceKey, out existingfFontResolverInfo)) { // Should never come here. throw new InvalidOperationException(string.Format("A font file with different content already exists with the specified face name '{0}'.", typefaceKey)); } if (FontResolverInfosByName.TryGetValue(fontResolverInfo.Key, out existingfFontResolverInfo)) { // Should never come here. throw new InvalidOperationException(string.Format("A font resolver already exists with the specified key '{0}'.", fontResolverInfo.Key)); } // Add to both dictionaries. FontResolverInfosByName.Add(typefaceKey, fontResolverInfo); FontResolverInfosByName.Add(fontResolverInfo.Key, fontResolverInfo); } /// <summary> /// Caches a font source under its face name and its key. /// </summary> public static XFontSource CacheFontSource(XFontSource fontSource) { try { Lock.EnterFontFactory(); // Check whether an identical font source with a different face name already exists. XFontSource existingFontSource; if (FontSourcesByKey.TryGetValue(fontSource.Key, out existingFontSource)) { #if DEBUG // Fonts have same length and check sum. Now check byte by byte identity. int length = fontSource.Bytes.Length; for (int idx = 0; idx < length; idx++) { if (existingFontSource.Bytes[idx] != fontSource.Bytes[idx]) { //Debug.Assert(false,"Two fonts with identical checksum found."); break; //goto FontsAreNotIdentical; } } Debug.Assert(existingFontSource.Fontface != null); #endif return existingFontSource; //FontsAreNotIdentical: //// Incredible rare case: Two different fonts have the same size and check sum. //// Give the new one a new key until it do not clash with an existing one. //while (FontSourcesByKey.ContainsKey(fontSource.Key)) // fontSource.IncrementKey(); } OpenTypeFontface fontface = fontSource.Fontface; if (fontface == null) { // Create OpenType fontface for this font source. fontSource.Fontface = new OpenTypeFontface(fontSource); } FontSourcesByKey.Add(fontSource.Key, fontSource); FontSourcesByName.Add(fontSource.FontName, fontSource); return fontSource; } finally { Lock.ExitFontFactory(); } } /// <summary> /// Caches a font source under its face name and its key. /// </summary> public static XFontSource CacheNewFontSource(string typefaceKey, XFontSource fontSource) { // Debug.Assert(!FontSourcesByFaceName.ContainsKey(fontSource.FaceName)); // Check whether an identical font source with a different face name already exists. XFontSource existingFontSource; if (FontSourcesByKey.TryGetValue(fontSource.Key, out existingFontSource)) { //// Fonts have same length and check sum. Now check byte by byte identity. //int length = fontSource.Bytes.Length; //for (int idx = 0; idx < length; idx++) //{ // if (existingFontSource.Bytes[idx] != fontSource.Bytes[idx]) // { // goto FontsAreNotIdentical; // } //} return existingFontSource; ////// The bytes are really identical. Register font source again with the new face name ////// but return the existing one to save memory. ////FontSourcesByFaceName.Add(fontSource.FaceName, existingFontSource); ////return existingFontSource; //FontsAreNotIdentical: //// Incredible rare case: Two different fonts have the same size and check sum. //// Give the new one a new key until it do not clash with an existing one. //while (FontSourcesByKey.ContainsKey(fontSource.Key)) // fontSource.IncrementKey(); } OpenTypeFontface fontface = fontSource.Fontface; if (fontface == null) { fontface = new OpenTypeFontface(fontSource); fontSource.Fontface = fontface; // Also sets the font name in fontSource } FontSourcesByName.Add(typefaceKey, fontSource); FontSourcesByName.Add(fontSource.FontName, fontSource); FontSourcesByKey.Add(fontSource.Key, fontSource); return fontSource; } public static void CacheExistingFontSourceWithNewTypefaceKey(string typefaceKey, XFontSource fontSource) { try { Lock.EnterFontFactory(); FontSourcesByName.Add(typefaceKey, fontSource); } finally { Lock.ExitFontFactory(); } } internal static string GetFontCachesState() { StringBuilder state = new StringBuilder(); string[] keys; int count; // FontResolverInfo by name. state.Append("====================\n"); state.Append("Font resolver info by name\n"); Dictionary<string, FontResolverInfo>.KeyCollection keyCollection = FontResolverInfosByName.Keys; count = keyCollection.Count; keys = new string[count]; keyCollection.CopyTo(keys, 0); Array.Sort(keys, StringComparer.OrdinalIgnoreCase); foreach (string key in keys) state.AppendFormat(" {0}: {1}\n", key, FontResolverInfosByName[key].DebuggerDisplay); state.Append("\n"); // FontSource by key. state.Append("Font source by key and name\n"); Dictionary<ulong, XFontSource>.KeyCollection fontSourceKeys = FontSourcesByKey.Keys; count = fontSourceKeys.Count; ulong[] ulKeys = new ulong[count]; fontSourceKeys.CopyTo(ulKeys, 0); Array.Sort(ulKeys, delegate (ulong x, ulong y) { return x == y ? 0 : (x > y ? 1 : -1); }); foreach (ulong ul in ulKeys) state.AppendFormat(" {0}: {1}\n", ul, FontSourcesByKey[ul].DebuggerDisplay); Dictionary<string, XFontSource>.KeyCollection fontSourceNames = FontSourcesByName.Keys; count = fontSourceNames.Count; keys = new string[count]; fontSourceNames.CopyTo(keys, 0); Array.Sort(keys, StringComparer.OrdinalIgnoreCase); foreach (string key in keys) state.AppendFormat(" {0}: {1}\n", key, FontSourcesByName[key].DebuggerDisplay); state.Append("--------------------\n\n"); // FontFamilyInternal by name. state.Append(FontFamilyCache.GetCacheState()); // XGlyphTypeface by name. state.Append(GlyphTypefaceCache.GetCacheState()); // OpenTypeFontface by name. state.Append(OpenTypeFontfaceCache.GetCacheState()); return state.ToString(); } // TODO: Move to ctor /// <summary> /// Maps font typeface key to font resolver info. /// </summary> //static readonly Dictionary<string, FontResolverInfo> FontResolverInfosByTypefaceKey = new Dictionary<string, FontResolverInfo>(StringComparer.OrdinalIgnoreCase); static readonly Dictionary<string, FontResolverInfo> FontResolverInfosByName = new Dictionary<string, FontResolverInfo>(StringComparer.OrdinalIgnoreCase); ///// <summary> ///// Maps font resolver info key to font resolver info. ///// </summary> //static readonly Dictionary<string, FontResolverInfo> FontResolverInfosByKey = new Dictionary<string, FontResolverInfo>(); /// <summary> /// Maps typeface key or font name to font source. /// </summary> //static readonly Dictionary<string, XFontSource> FontSourcesByTypefaceKey = new Dictionary<string, XFontSource>(StringComparer.OrdinalIgnoreCase); static readonly Dictionary<string, XFontSource> FontSourcesByName = new Dictionary<string, XFontSource>(StringComparer.OrdinalIgnoreCase); ///// <summary> ///// Maps font name to font source. ///// </summary> //static readonly Dictionary<string, XFontSource> FontSourcesByFontName = new Dictionary<string, XFontSource>(); /// <summary> /// Maps font source key to font source. /// </summary> static readonly Dictionary<ulong, XFontSource> FontSourcesByKey = new Dictionary<ulong, XFontSource>(); } }
#nullable enable using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Mail; using System.Threading.Tasks; using BTCPayServer.Abstractions.Constants; using BTCPayServer.Abstractions.Extensions; using BTCPayServer.Abstractions.Models; using BTCPayServer.Configuration; using BTCPayServer.Data; using BTCPayServer.HostedServices; using BTCPayServer.Hosting; using BTCPayServer.Logging; using BTCPayServer.Models; using BTCPayServer.Models.ServerViewModels; using BTCPayServer.Services; using BTCPayServer.Services.Apps; using BTCPayServer.Services.Mails; using BTCPayServer.Services.Stores; using BTCPayServer.Storage.Models; using BTCPayServer.Storage.Services; using BTCPayServer.Storage.Services.Providers; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using MimeKit; using NBitcoin; using NBitcoin.DataEncoders; using Renci.SshNet; using AuthenticationSchemes = BTCPayServer.Abstractions.Constants.AuthenticationSchemes; namespace BTCPayServer.Controllers { [Authorize(Policy = BTCPayServer.Client.Policies.CanModifyServerSettings, AuthenticationSchemes = AuthenticationSchemes.Cookie)] public partial class UIServerController : Controller { private readonly UserManager<ApplicationUser> _UserManager; private readonly UserService _userService; readonly SettingsRepository _SettingsRepository; private readonly NBXplorerDashboard _dashBoard; private readonly StoreRepository _StoreRepository; readonly LightningConfigurationProvider _LnConfigProvider; private readonly TorServices _torServices; private readonly BTCPayServerOptions _Options; private readonly AppService _AppService; private readonly CheckConfigurationHostedService _sshState; private readonly EventAggregator _eventAggregator; private readonly IOptions<ExternalServicesOptions> _externalServiceOptions; private readonly Logs Logs; private readonly StoredFileRepository _StoredFileRepository; private readonly FileService _FileService; private readonly IEnumerable<IStorageProviderService> _StorageProviderServices; public UIServerController( UserManager<ApplicationUser> userManager, UserService userService, StoredFileRepository storedFileRepository, FileService fileService, IEnumerable<IStorageProviderService> storageProviderServices, BTCPayServerOptions options, SettingsRepository settingsRepository, NBXplorerDashboard dashBoard, IHttpClientFactory httpClientFactory, LightningConfigurationProvider lnConfigProvider, TorServices torServices, StoreRepository storeRepository, AppService appService, CheckConfigurationHostedService sshState, EventAggregator eventAggregator, IOptions<ExternalServicesOptions> externalServiceOptions, Logs logs) { _Options = options; _StoredFileRepository = storedFileRepository; _FileService = fileService; _StorageProviderServices = storageProviderServices; _UserManager = userManager; _userService = userService; _SettingsRepository = settingsRepository; _dashBoard = dashBoard; HttpClientFactory = httpClientFactory; _StoreRepository = storeRepository; _LnConfigProvider = lnConfigProvider; _torServices = torServices; _AppService = appService; _sshState = sshState; _eventAggregator = eventAggregator; _externalServiceOptions = externalServiceOptions; Logs = logs; } [Route("server/maintenance")] public IActionResult Maintenance() { MaintenanceViewModel vm = new MaintenanceViewModel(); vm.CanUseSSH = _sshState.CanUseSSH; if (!vm.CanUseSSH) TempData[WellKnownTempData.ErrorMessage] = "Maintenance feature requires access to SSH properly configured in BTCPay Server configuration."; vm.DNSDomain = this.Request.Host.Host; if (IPAddress.TryParse(vm.DNSDomain, out var unused)) vm.DNSDomain = null; return View(vm); } [Route("server/maintenance")] [HttpPost] public async Task<IActionResult> Maintenance(MaintenanceViewModel vm, string command) { vm.CanUseSSH = _sshState.CanUseSSH; if (!vm.CanUseSSH) { TempData[WellKnownTempData.ErrorMessage] = "Maintenance feature requires access to SSH properly configured in BTCPay Server configuration."; return View(vm); } if (!ModelState.IsValid) return View(vm); if (command == "changedomain") { if (string.IsNullOrWhiteSpace(vm.DNSDomain)) { ModelState.AddModelError(nameof(vm.DNSDomain), $"Required field"); return View(vm); } vm.DNSDomain = vm.DNSDomain.Trim().ToLowerInvariant(); if (vm.DNSDomain.Equals(this.Request.Host.Host, StringComparison.OrdinalIgnoreCase)) return View(vm); if (IPAddress.TryParse(vm.DNSDomain, out var unused)) { ModelState.AddModelError(nameof(vm.DNSDomain), $"This should be a domain name"); return View(vm); } if (vm.DNSDomain.Equals(this.Request.Host.Host, StringComparison.InvariantCultureIgnoreCase)) { ModelState.AddModelError(nameof(vm.DNSDomain), $"The server is already set to use this domain"); return View(vm); } var builder = new UriBuilder(); using (var client = new HttpClient(new HttpClientHandler() { ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator })) { try { builder.Scheme = this.Request.Scheme; builder.Host = vm.DNSDomain; var addresses1 = GetAddressAsync(this.Request.Host.Host); var addresses2 = GetAddressAsync(vm.DNSDomain); await Task.WhenAll(addresses1, addresses2); var addressesSet = addresses1.GetAwaiter().GetResult().Select(c => c.ToString()).ToHashSet(); var hasCommonAddress = addresses2.GetAwaiter().GetResult().Select(c => c.ToString()).Any(s => addressesSet.Contains(s)); if (!hasCommonAddress) { ModelState.AddModelError(nameof(vm.DNSDomain), $"Invalid host ({vm.DNSDomain} is not pointing to this BTCPay instance)"); return View(vm); } } catch (Exception ex) { var messages = new List<object>(); messages.Add(ex.Message); if (ex.InnerException != null) messages.Add(ex.InnerException.Message); ModelState.AddModelError(nameof(vm.DNSDomain), $"Invalid domain ({string.Join(", ", messages.ToArray())})"); return View(vm); } } var error = await RunSSH(vm, $"changedomain.sh {vm.DNSDomain}"); if (error != null) return error; builder.Path = null; builder.Query = null; TempData[WellKnownTempData.SuccessMessage] = $"Domain name changing... the server will restart, please use \"{builder.Uri.AbsoluteUri}\" (this page won't reload automatically)"; } else if (command == "update") { var error = await RunSSH(vm, $"btcpay-update.sh"); if (error != null) return error; TempData[WellKnownTempData.SuccessMessage] = $"The server might restart soon if an update is available... (this page won't reload automatically)"; } else if (command == "clean") { var error = await RunSSH(vm, $"btcpay-clean.sh"); if (error != null) return error; TempData[WellKnownTempData.SuccessMessage] = $"The old docker images will be cleaned soon..."; } else if (command == "restart") { var error = await RunSSH(vm, $"btcpay-restart.sh"); if (error != null) return error; TempData[WellKnownTempData.SuccessMessage] = $"BTCPay will restart momentarily."; } else { return NotFound(); } return RedirectToAction(nameof(Maintenance)); } private Task<IPAddress[]> GetAddressAsync(string domainOrIP) { if (IPAddress.TryParse(domainOrIP, out var ip)) return Task.FromResult(new[] { ip }); return Dns.GetHostAddressesAsync(domainOrIP); } public static string RunId = Encoders.Hex.EncodeData(NBitcoin.RandomUtils.GetBytes(32)); [HttpGet] [Route("runid")] [AllowAnonymous] public IActionResult SeeRunId(string? expected = null) { if (expected == RunId) return Ok(); return BadRequest(); } private async Task<IActionResult?> RunSSH(MaintenanceViewModel vm, string command) { SshClient? sshClient = null; try { sshClient = await _Options.SSHSettings.ConnectAsync(); } catch (Exception ex) { var message = ex.Message; if (ex is AggregateException aggrEx && aggrEx.InnerException?.Message != null) { message = aggrEx.InnerException.Message; } ModelState.AddModelError(string.Empty, $"Connection problem ({message})"); return View(vm); } _ = RunSSHCore(sshClient, $". /etc/profile.d/btcpay-env.sh && nohup {command} > /dev/null 2>&1 & disown"); return null; } private async Task RunSSHCore(SshClient sshClient, string ssh) { try { Logs.PayServer.LogInformation("Running SSH command: " + ssh); var result = await sshClient.RunBash(ssh, TimeSpan.FromMinutes(1.0)); Logs.PayServer.LogInformation($"SSH command executed with exit status {result.ExitStatus}. Output: {result.Output}"); } catch (Exception ex) { Logs.PayServer.LogWarning("Error while executing SSH command: " + ex.Message); } finally { sshClient.Dispose(); } } public IHttpClientFactory HttpClientFactory { get; } [Route("server/policies")] public async Task<IActionResult> Policies() { var data = (await _SettingsRepository.GetSettingAsync<PoliciesSettings>()) ?? new PoliciesSettings(); ViewBag.AppsList = await GetAppSelectList(); ViewBag.UpdateUrlPresent = _Options.UpdateUrl != null; return View(data); } [Route("server/policies")] [HttpPost] public async Task<IActionResult> Policies([FromServices] BTCPayNetworkProvider btcPayNetworkProvider, PoliciesSettings settings, string command = "") { ViewBag.UpdateUrlPresent = _Options.UpdateUrl != null; ViewBag.AppsList = await GetAppSelectList(); if (command == "add-domain") { ModelState.Clear(); settings.DomainToAppMapping.Add(new PoliciesSettings.DomainToAppMappingItem()); return View(settings); } if (command.StartsWith("remove-domain", StringComparison.InvariantCultureIgnoreCase)) { ModelState.Clear(); var index = int.Parse(command.Substring(command.IndexOf(":", StringComparison.InvariantCultureIgnoreCase) + 1), CultureInfo.InvariantCulture); settings.DomainToAppMapping.RemoveAt(index); return View(settings); } settings.BlockExplorerLinks = settings.BlockExplorerLinks.Where(tuple => btcPayNetworkProvider.GetNetwork(tuple.CryptoCode).BlockExplorerLinkDefault != tuple.Link).ToList(); if (!ModelState.IsValid) { return View(settings); } var appIdsToFetch = settings.DomainToAppMapping.Select(item => item.AppId).ToList(); if (!string.IsNullOrEmpty(settings.RootAppId)) { appIdsToFetch.Add(settings.RootAppId); } else { settings.RootAppType = null; } if (appIdsToFetch.Any()) { var apps = (await _AppService.GetApps(appIdsToFetch.ToArray())) .ToDictionary(data => data.Id, data => Enum.Parse<AppType>(data.AppType)); ; if (!string.IsNullOrEmpty(settings.RootAppId)) { settings.RootAppType = apps[settings.RootAppId]; } foreach (var domainToAppMappingItem in settings.DomainToAppMapping) { domainToAppMappingItem.AppType = apps[domainToAppMappingItem.AppId]; } } await _SettingsRepository.UpdateSetting(settings); BlockExplorerLinkStartupTask.SetLinkOnNetworks(settings.BlockExplorerLinks, btcPayNetworkProvider); TempData[WellKnownTempData.SuccessMessage] = "Policies updated successfully"; return RedirectToAction(nameof(Policies)); } [Route("server/services")] public async Task<IActionResult> Services() { var result = new ServicesViewModel(); result.ExternalServices = _externalServiceOptions.Value.ExternalServices.ToList(); // other services foreach (var externalService in _externalServiceOptions.Value.OtherExternalServices) { result.OtherExternalServices.Add(new ServicesViewModel.OtherExternalService() { Name = externalService.Key, Link = this.Request.GetAbsoluteUriNoPathBase(externalService.Value).AbsoluteUri }); } if (await CanShowSSHService()) { result.OtherExternalServices.Add(new ServicesViewModel.OtherExternalService() { Name = "SSH", Link = this.Url.Action(nameof(SSHService)) }); } result.OtherExternalServices.Add(new ServicesViewModel.OtherExternalService() { Name = "Dynamic DNS", Link = this.Url.Action(nameof(DynamicDnsServices)) }); foreach (var torService in _torServices.Services) { if (torService.VirtualPort == 80) { result.TorHttpServices.Add(new ServicesViewModel.OtherExternalService() { Name = torService.Name, Link = $"http://{torService.OnionHost}" }); } else if (TryParseAsExternalService(torService, out var externalService)) { result.ExternalServices.Add(externalService); } else { result.TorOtherServices.Add(new ServicesViewModel.OtherExternalService() { Name = torService.Name, Link = $"{torService.OnionHost}:{torService.VirtualPort}" }); } } // external storage services var storageSettings = await _SettingsRepository.GetSettingAsync<StorageSettings>(); result.ExternalStorageServices.Add(new ServicesViewModel.OtherExternalService() { Name = storageSettings == null ? "Not set" : storageSettings.Provider.ToString(), Link = Url.Action("Storage") }); return View(result); } private async Task<List<SelectListItem>> GetAppSelectList() { var apps = (await _AppService.GetAllApps(null, true)) .Select(a => new SelectListItem($"{typeof(AppType).DisplayName(a.AppType)} - {a.AppName} - {a.StoreName}", a.Id)).ToList(); apps.Insert(0, new SelectListItem("(None)", null)); return apps; } private static bool TryParseAsExternalService(TorService torService, [MaybeNullWhen(false)] out ExternalService externalService) { externalService = null; if (torService.ServiceType == TorServiceType.P2P) { externalService = new ExternalService() { CryptoCode = torService.Network.CryptoCode, DisplayName = "Full node P2P", Type = ExternalServiceTypes.P2P, ConnectionString = new ExternalConnectionString(new Uri($"bitcoin-p2p://{torService.OnionHost}:{torService.VirtualPort}", UriKind.Absolute)), ServiceName = torService.Name, }; } if (torService.ServiceType == TorServiceType.RPC) { externalService = new ExternalService() { CryptoCode = torService.Network.CryptoCode, DisplayName = "Full node RPC", Type = ExternalServiceTypes.RPC, ConnectionString = new ExternalConnectionString(new Uri($"btcrpc://btcrpc:btcpayserver4ever@{torService.OnionHost}:{torService.VirtualPort}?label=BTCPayNode", UriKind.Absolute)), ServiceName = torService.Name }; } return externalService != null; } private ExternalService? GetService(string serviceName, string cryptoCode) { var result = _externalServiceOptions.Value.ExternalServices.GetService(serviceName, cryptoCode); if (result != null) return result; foreach (var torService in _torServices.Services) { if (TryParseAsExternalService(torService, out var torExternalService) && torExternalService.ServiceName == serviceName) return torExternalService; } return null; } [Route("server/services/{serviceName}/{cryptoCode?}")] public async Task<IActionResult> Service(string serviceName, string cryptoCode, bool showQR = false, ulong? nonce = null) { var service = GetService(serviceName, cryptoCode); if (service == null) return NotFound(); if (!string.IsNullOrEmpty(cryptoCode) && !_dashBoard.IsFullySynched(cryptoCode, out _) && service.Type != ExternalServiceTypes.RPC) { TempData[WellKnownTempData.ErrorMessage] = $"{cryptoCode} is not fully synched"; return RedirectToAction(nameof(Services)); } try { if (service.Type == ExternalServiceTypes.P2P) { return View("P2PService", new LightningWalletServices() { ShowQR = showQR, WalletName = service.ServiceName, ServiceLink = service.ConnectionString.Server.AbsoluteUri.WithoutEndingSlash() }); } if (service.Type == ExternalServiceTypes.LNDSeedBackup) { var model = LndSeedBackupViewModel.Parse(service.ConnectionString.CookieFilePath); if (!model.IsWalletUnlockPresent) { TempData.SetStatusMessageModel(new StatusMessageModel() { Severity = StatusMessageModel.StatusSeverity.Warning, Html = "Your LND does not seem to allow seed backup.<br />" + "It's recommended, but not required, that you migrate as instructed by <a href=\"https://blog.btcpayserver.org/btcpay-lnd-migration\">our migration blog post</a>.<br />" + "You will need to close all of your channels, and migrate your funds as <a href=\"https://blog.btcpayserver.org/btcpay-lnd-migration\">we documented</a>." }); } return View("LndSeedBackup", model); } if (service.Type == ExternalServiceTypes.RPC) { return View("RPCService", new LightningWalletServices() { ShowQR = showQR, WalletName = service.ServiceName, ServiceLink = service.ConnectionString.Server.AbsoluteUri.WithoutEndingSlash() }); } var connectionString = await service.ConnectionString.Expand(this.Request.GetAbsoluteUriNoPathBase(), service.Type, _Options.NetworkType); switch (service.Type) { case ExternalServiceTypes.Charge: return LightningChargeServices(service, connectionString, showQR); case ExternalServiceTypes.RTL: case ExternalServiceTypes.ThunderHub: case ExternalServiceTypes.Spark: if (connectionString.AccessKey == null) { TempData[WellKnownTempData.ErrorMessage] = $"The access key of the service is not set"; return RedirectToAction(nameof(Services)); } LightningWalletServices vm = new LightningWalletServices(); vm.ShowQR = showQR; vm.WalletName = service.DisplayName; string tokenParam = "access-key"; if (service.Type == ExternalServiceTypes.ThunderHub) tokenParam = "token"; vm.ServiceLink = $"{connectionString.Server}?{tokenParam}={connectionString.AccessKey}"; return View("LightningWalletServices", vm); case ExternalServiceTypes.CLightningRest: return LndServices(service, connectionString, nonce, "CLightningRestServices"); case ExternalServiceTypes.LNDGRPC: case ExternalServiceTypes.LNDRest: return LndServices(service, connectionString, nonce); case ExternalServiceTypes.Configurator: return View("ConfiguratorService", new LightningWalletServices() { ShowQR = showQR, WalletName = service.ServiceName, ServiceLink = $"{connectionString.Server}?password={connectionString.AccessKey}" }); default: throw new NotSupportedException(service.Type.ToString()); } } catch (Exception ex) { TempData[WellKnownTempData.ErrorMessage] = ex.Message; return RedirectToAction(nameof(Services)); } } [HttpGet("server/services/{serviceName}/{cryptoCode}/removelndseed")] public IActionResult RemoveLndSeed(string serviceName, string cryptoCode) { return View("Confirm", new ConfirmModel("Delete LND seed", "This action will permanently delete your LND seed and password. You will not be able to recover them if you don't have a backup. Are you sure?", "Delete")); } [HttpPost("server/services/{serviceName}/{cryptoCode}/removelndseed")] public async Task<IActionResult> RemoveLndSeedPost(string serviceName, string cryptoCode) { var service = GetService(serviceName, cryptoCode); if (service == null) return NotFound(); var model = LndSeedBackupViewModel.Parse(service.ConnectionString.CookieFilePath); if (!model.IsWalletUnlockPresent) { TempData[WellKnownTempData.ErrorMessage] = $"File with wallet password and seed info not present"; return RedirectToAction(nameof(Services)); } if (string.IsNullOrEmpty(model.Seed)) { TempData[WellKnownTempData.ErrorMessage] = $"Seed information was already removed"; return RedirectToAction(nameof(Services)); } if (await model.RemoveSeedAndWrite(service.ConnectionString.CookieFilePath)) { TempData[WellKnownTempData.SuccessMessage] = $"Seed successfully removed"; return RedirectToAction(nameof(Service), new { serviceName, cryptoCode }); } else { TempData[WellKnownTempData.ErrorMessage] = $"Seed removal failed"; return RedirectToAction(nameof(Services)); } } private IActionResult LightningChargeServices(ExternalService service, ExternalConnectionString connectionString, bool showQR = false) { ChargeServiceViewModel vm = new ChargeServiceViewModel(); vm.Uri = connectionString.Server.AbsoluteUri; vm.APIToken = connectionString.APIToken; var builder = new UriBuilder(connectionString.Server); builder.UserName = "api-token"; builder.Password = vm.APIToken; vm.AuthenticatedUri = builder.ToString(); return View(nameof(LightningChargeServices), vm); } private IActionResult LndServices(ExternalService service, ExternalConnectionString connectionString, ulong? nonce, string view = nameof(LndServices)) { var model = new LndServicesViewModel(); if (service.Type == ExternalServiceTypes.LNDGRPC) { model.Host = $"{connectionString.Server.DnsSafeHost}:{connectionString.Server.Port}"; model.SSL = connectionString.Server.Scheme == "https"; model.ConnectionType = "GRPC"; model.GRPCSSLCipherSuites = "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256"; } else if (service.Type == ExternalServiceTypes.LNDRest || service.Type == ExternalServiceTypes.CLightningRest) { model.Uri = connectionString.Server.AbsoluteUri; model.ConnectionType = "REST"; } if (connectionString.CertificateThumbprint != null) { model.CertificateThumbprint = connectionString.CertificateThumbprint; } if (connectionString.Macaroon != null) { model.Macaroon = Encoders.Hex.EncodeData(connectionString.Macaroon); } model.AdminMacaroon = connectionString.Macaroons?.AdminMacaroon?.Hex; model.InvoiceMacaroon = connectionString.Macaroons?.InvoiceMacaroon?.Hex; model.ReadonlyMacaroon = connectionString.Macaroons?.ReadonlyMacaroon?.Hex; if (nonce != null) { var configKey = GetConfigKey("lnd", service.ServiceName, service.CryptoCode, nonce.Value); var lnConfig = _LnConfigProvider.GetConfig(configKey); if (lnConfig != null) { model.QRCodeLink = Request.GetAbsoluteUri(Url.Action(nameof(GetLNDConfig), new { configKey = configKey })); model.QRCode = $"config={model.QRCodeLink}"; } } return View(view, model); } private static ulong GetConfigKey(string type, string serviceName, string cryptoCode, ulong nonce) { return ((ulong)(uint)HashCode.Combine(type, serviceName, cryptoCode, nonce) | (nonce & 0xffffffff00000000UL)); } [Route("lnd-config/{configKey}/lnd.config")] [AllowAnonymous] public IActionResult GetLNDConfig(ulong configKey) { var conf = _LnConfigProvider.GetConfig(configKey); if (conf == null) return NotFound(); return Json(conf); } [Route("server/services/{serviceName}/{cryptoCode}")] [HttpPost] public async Task<IActionResult> ServicePost(string serviceName, string cryptoCode) { if (!_dashBoard.IsFullySynched(cryptoCode, out var unusud)) { TempData[WellKnownTempData.ErrorMessage] = $"{cryptoCode} is not fully synched"; return RedirectToAction(nameof(Services)); } var service = GetService(serviceName, cryptoCode); if (service == null) return NotFound(); ExternalConnectionString? connectionString = null; try { connectionString = await service.ConnectionString.Expand(this.Request.GetAbsoluteUriNoPathBase(), service.Type, _Options.NetworkType); } catch (Exception ex) { TempData[WellKnownTempData.ErrorMessage] = ex.Message; return RedirectToAction(nameof(Services)); } LightningConfigurations confs = new LightningConfigurations(); if (service.Type == ExternalServiceTypes.LNDGRPC) { LightningConfiguration grpcConf = new LightningConfiguration(); grpcConf.Type = "grpc"; grpcConf.Host = connectionString.Server.DnsSafeHost; grpcConf.Port = connectionString.Server.Port; grpcConf.SSL = connectionString.Server.Scheme == "https"; confs.Configurations.Add(grpcConf); } else if (service.Type == ExternalServiceTypes.LNDRest || service.Type == ExternalServiceTypes.CLightningRest) { var restconf = new LNDRestConfiguration(); restconf.Type = service.Type == ExternalServiceTypes.LNDRest ? "lnd-rest" : "clightning-rest"; restconf.Uri = connectionString.Server.AbsoluteUri; confs.Configurations.Add(restconf); } else throw new NotSupportedException(service.Type.ToString()); var commonConf = (LNDConfiguration)confs.Configurations[confs.Configurations.Count - 1]; commonConf.ChainType = _Options.NetworkType.ToString(); commonConf.CryptoCode = cryptoCode; commonConf.Macaroon = connectionString.Macaroon == null ? null : Encoders.Hex.EncodeData(connectionString.Macaroon); commonConf.CertificateThumbprint = connectionString.CertificateThumbprint == null ? null : connectionString.CertificateThumbprint; commonConf.AdminMacaroon = connectionString.Macaroons?.AdminMacaroon?.Hex; commonConf.ReadonlyMacaroon = connectionString.Macaroons?.ReadonlyMacaroon?.Hex; commonConf.InvoiceMacaroon = connectionString.Macaroons?.InvoiceMacaroon?.Hex; var nonce = RandomUtils.GetUInt64(); var configKey = GetConfigKey("lnd", serviceName, cryptoCode, nonce); _LnConfigProvider.KeepConfig(configKey, confs); return RedirectToAction(nameof(Service), new { cryptoCode = cryptoCode, serviceName = serviceName, nonce = nonce }); } [Route("server/services/dynamic-dns")] public async Task<IActionResult> DynamicDnsServices() { var settings = (await _SettingsRepository.GetSettingAsync<DynamicDnsSettings>()) ?? new DynamicDnsSettings(); return View(settings.Services.Select(s => new DynamicDnsViewModel() { Settings = s }).ToArray()); } [Route("server/services/dynamic-dns/{hostname}")] public async Task<IActionResult> DynamicDnsServices(string hostname) { var settings = (await _SettingsRepository.GetSettingAsync<DynamicDnsSettings>()) ?? new DynamicDnsSettings(); var service = settings.Services.FirstOrDefault(s => s.Hostname.Equals(hostname, StringComparison.OrdinalIgnoreCase)); if (service == null) return NotFound(); var vm = new DynamicDnsViewModel(); vm.Modify = true; vm.Settings = service; return View(nameof(DynamicDnsService), vm); } [Route("server/services/dynamic-dns")] [HttpPost] public async Task<IActionResult> DynamicDnsService(DynamicDnsViewModel viewModel, string? command = null) { if (!ModelState.IsValid) { return View(viewModel); } if (command == "Save") { var settings = (await _SettingsRepository.GetSettingAsync<DynamicDnsSettings>()) ?? new DynamicDnsSettings(); var i = settings.Services.FindIndex(d => d.Hostname.Equals(viewModel.Settings.Hostname, StringComparison.OrdinalIgnoreCase)); if (i != -1) { ModelState.AddModelError(nameof(viewModel.Settings.Hostname), "This hostname already exists"); return View(viewModel); } if (viewModel.Settings.Hostname != null) viewModel.Settings.Hostname = viewModel.Settings.Hostname.Trim().ToLowerInvariant(); string errorMessage = await viewModel.Settings.SendUpdateRequest(HttpClientFactory.CreateClient()); if (errorMessage == null) { TempData[WellKnownTempData.SuccessMessage] = $"The Dynamic DNS has been successfully queried, your configuration is saved"; viewModel.Settings.LastUpdated = DateTimeOffset.UtcNow; settings.Services.Add(viewModel.Settings); await _SettingsRepository.UpdateSetting(settings); return RedirectToAction(nameof(DynamicDnsServices)); } else { ModelState.AddModelError(string.Empty, errorMessage); return View(viewModel); } } else { return View(new DynamicDnsViewModel() { Settings = new DynamicDnsService() }); } } [Route("server/services/dynamic-dns/{hostname}")] [HttpPost] public async Task<IActionResult> DynamicDnsService(DynamicDnsViewModel viewModel, string hostname, string? command = null) { if (!ModelState.IsValid) { return View(viewModel); } var settings = (await _SettingsRepository.GetSettingAsync<DynamicDnsSettings>()) ?? new DynamicDnsSettings(); var i = settings.Services.FindIndex(d => d.Hostname.Equals(hostname, StringComparison.OrdinalIgnoreCase)); if (i == -1) return NotFound(); if (viewModel.Settings.Password == null) viewModel.Settings.Password = settings.Services[i].Password; if (viewModel.Settings.Hostname != null) viewModel.Settings.Hostname = viewModel.Settings.Hostname.Trim().ToLowerInvariant(); if (!viewModel.Settings.Enabled) { TempData[WellKnownTempData.SuccessMessage] = $"The Dynamic DNS service has been disabled"; viewModel.Settings.LastUpdated = null; } else { string errorMessage = await viewModel.Settings.SendUpdateRequest(HttpClientFactory.CreateClient()); if (errorMessage == null) { TempData[WellKnownTempData.SuccessMessage] = $"The Dynamic DNS has been successfully queried, your configuration is saved"; viewModel.Settings.LastUpdated = DateTimeOffset.UtcNow; } else { ModelState.AddModelError(string.Empty, errorMessage); return View(viewModel); } } settings.Services[i] = viewModel.Settings; await _SettingsRepository.UpdateSetting(settings); this.RouteData.Values.Remove(nameof(hostname)); return RedirectToAction(nameof(DynamicDnsServices)); } [HttpGet("server/services/dynamic-dns/{hostname}/delete")] public async Task<IActionResult> DeleteDynamicDnsService(string hostname) { var settings = await _SettingsRepository.GetSettingAsync<DynamicDnsSettings>() ?? new DynamicDnsSettings(); var i = settings.Services.FindIndex(d => d.Hostname.Equals(hostname, StringComparison.OrdinalIgnoreCase)); if (i == -1) return NotFound(); return View("Confirm", new ConfirmModel("Delete dynamic DNS service", $"Deleting the dynamic DNS service for <strong>{hostname}</strong> means your BTCPay Server will stop updating the associated DNS record periodically.", "Delete")); } [HttpPost("server/services/dynamic-dns/{hostname}/delete")] public async Task<IActionResult> DeleteDynamicDnsServicePost(string hostname) { var settings = (await _SettingsRepository.GetSettingAsync<DynamicDnsSettings>()) ?? new DynamicDnsSettings(); var i = settings.Services.FindIndex(d => d.Hostname.Equals(hostname, StringComparison.OrdinalIgnoreCase)); if (i == -1) return NotFound(); settings.Services.RemoveAt(i); await _SettingsRepository.UpdateSetting(settings); TempData[WellKnownTempData.SuccessMessage] = "Dynamic DNS service successfully removed"; RouteData.Values.Remove(nameof(hostname)); return RedirectToAction(nameof(DynamicDnsServices)); } [HttpGet("server/services/ssh")] public async Task<IActionResult> SSHService() { if (!await CanShowSSHService()) return NotFound(); var settings = _Options.SSHSettings; var server = Extensions.IsLocalNetwork(settings.Server) ? this.Request.Host.Host : settings.Server; SSHServiceViewModel vm = new SSHServiceViewModel(); string port = settings.Port == 22 ? "" : $" -p {settings.Port}"; vm.CommandLine = $"ssh {settings.Username}@{server}{port}"; vm.Password = settings.Password; vm.KeyFilePassword = settings.KeyFilePassword; vm.HasKeyFile = !string.IsNullOrEmpty(settings.KeyFile); // Let's try to just read the authorized key file if (CanAccessAuthorizedKeyFile()) { try { vm.SSHKeyFileContent = await System.IO.File.ReadAllTextAsync(settings.AuthorizedKeysFile); } catch { } } // If that fail, just fallback to ssh if (vm.SSHKeyFileContent == null && _sshState.CanUseSSH) { try { using var sshClient = await _Options.SSHSettings.ConnectAsync(); var result = await sshClient.RunBash("cat ~/.ssh/authorized_keys", TimeSpan.FromSeconds(10)); vm.SSHKeyFileContent = result.Output; } catch { } } return View(vm); } async Task<bool> CanShowSSHService() { var policies = await _SettingsRepository.GetSettingAsync<PoliciesSettings>(); return !(policies?.DisableSSHService is true) && _Options.SSHSettings != null && (_sshState.CanUseSSH || CanAccessAuthorizedKeyFile()); } private bool CanAccessAuthorizedKeyFile() { return _Options.SSHSettings?.AuthorizedKeysFile != null && System.IO.File.Exists(_Options.SSHSettings.AuthorizedKeysFile); } [HttpPost("server/services/ssh")] public async Task<IActionResult> SSHService(SSHServiceViewModel viewModel, string? command = null) { if (!await CanShowSSHService()) return NotFound(); if (command is "Save") { string newContent = viewModel?.SSHKeyFileContent ?? string.Empty; newContent = newContent.Replace("\r\n", "\n", StringComparison.OrdinalIgnoreCase); bool updated = false; Exception? exception = null; // Let's try to just write the file if (CanAccessAuthorizedKeyFile()) { try { await System.IO.File.WriteAllTextAsync(_Options.SSHSettings.AuthorizedKeysFile, newContent); TempData[WellKnownTempData.SuccessMessage] = "authorized_keys has been updated"; updated = true; } catch (Exception ex) { exception = ex; } } // If that fail, fallback to ssh if (!updated && _sshState.CanUseSSH) { try { using (var sshClient = await _Options.SSHSettings.ConnectAsync()) { await sshClient.RunBash($"mkdir -p ~/.ssh && echo '{newContent.EscapeSingleQuotes()}' > ~/.ssh/authorized_keys", TimeSpan.FromSeconds(10)); } updated = true; exception = null; } catch (Exception ex) { exception = ex; } } if (exception is null) { TempData[WellKnownTempData.SuccessMessage] = "authorized_keys has been updated"; } else { TempData[WellKnownTempData.ErrorMessage] = exception.Message; } return RedirectToAction(nameof(SSHService)); } if (command is "disable") { return RedirectToAction(nameof(SSHServiceDisable)); } return NotFound(); } [HttpGet("server/services/ssh/disable")] public IActionResult SSHServiceDisable() { return View("Confirm", new ConfirmModel("Disable modification of SSH settings", "This action is permanent and will remove the ability to change the SSH settings via the BTCPay Server user interface.", "Disable")); } [HttpPost("server/services/ssh/disable")] public async Task<IActionResult> SSHServiceDisablePost() { var policies = await _SettingsRepository.GetSettingAsync<PoliciesSettings>() ?? new PoliciesSettings(); policies.DisableSSHService = true; await _SettingsRepository.UpdateSetting(policies); TempData[WellKnownTempData.SuccessMessage] = "Changes to the SSH settings are now permanently disabled in the BTCPay Server user interface"; return RedirectToAction(nameof(Services)); } [Route("server/theme")] public async Task<IActionResult> Theme() { var data = await _SettingsRepository.GetSettingAsync<ThemeSettings>() ?? new ThemeSettings(); return View(data); } [Route("server/theme")] [HttpPost] public async Task<IActionResult> Theme(ThemeSettings settings) { if (settings.CustomTheme && !Uri.IsWellFormedUriString(settings.CssUri, UriKind.RelativeOrAbsolute)) { TempData[WellKnownTempData.ErrorMessage] = "Please provide a non-empty theme URI"; } else { await _SettingsRepository.UpdateSetting(settings); TempData[WellKnownTempData.SuccessMessage] = "Theme settings updated successfully"; } return View(settings); } [Route("server/emails")] public async Task<IActionResult> Emails() { var data = (await _SettingsRepository.GetSettingAsync<EmailSettings>()) ?? new EmailSettings(); return View(new EmailsViewModel(data)); } [Route("server/emails")] [HttpPost] public async Task<IActionResult> Emails(EmailsViewModel model, string command) { if (command == "Test") { try { if (model.PasswordSet) { var settings = await _SettingsRepository.GetSettingAsync<EmailSettings>() ?? new EmailSettings(); model.Settings.Password = settings.Password; } if (!model.Settings.IsComplete()) { TempData[WellKnownTempData.ErrorMessage] = "Required fields missing"; return View(model); } using (var client = await model.Settings.CreateSmtpClient()) using (var message = model.Settings.CreateMailMessage(new MailboxAddress(model.TestEmail, model.TestEmail), "BTCPay test", "BTCPay test", false)) { await client.SendAsync(message); await client.DisconnectAsync(true); } TempData[WellKnownTempData.SuccessMessage] = "Email sent to " + model.TestEmail + ", please, verify you received it"; } catch (Exception ex) { TempData[WellKnownTempData.ErrorMessage] = ex.Message; } return View(model); } else if (command == "ResetPassword") { var settings = await _SettingsRepository.GetSettingAsync<EmailSettings>() ?? new EmailSettings(); settings.Password = null; await _SettingsRepository.UpdateSetting(model.Settings); TempData[WellKnownTempData.SuccessMessage] = "Email server password reset"; return RedirectToAction(nameof(Emails)); } else // if(command == "Save") { var oldSettings = await _SettingsRepository.GetSettingAsync<EmailSettings>() ?? new EmailSettings(); if (new EmailsViewModel(oldSettings).PasswordSet) { model.Settings.Password = oldSettings.Password; } await _SettingsRepository.UpdateSetting(model.Settings); TempData[WellKnownTempData.SuccessMessage] = "Email settings saved"; return RedirectToAction(nameof(Emails)); } } [Route("server/logs/{file?}")] public async Task<IActionResult> LogsView(string? file = null, int offset = 0) { if (offset < 0) { offset = 0; } var vm = new LogsViewModel(); if (string.IsNullOrEmpty(_Options.LogFile)) { TempData[WellKnownTempData.ErrorMessage] = "File Logging Option not specified. " + "You need to set debuglog and optionally " + "debugloglevel in the configuration or through runtime arguments"; } else { var di = Directory.GetParent(_Options.LogFile); if (di is null) { TempData[WellKnownTempData.ErrorMessage] = "Could not load log files"; return View("Logs", vm); } var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(_Options.LogFile); var fileExtension = Path.GetExtension(_Options.LogFile) ?? string.Empty; // We are checking if "di" is null above yet accessing GetFiles on it, this could lead to an exception? var logFiles = di.GetFiles($"{fileNameWithoutExtension}*{fileExtension}"); vm.LogFileCount = logFiles.Length; vm.LogFiles = logFiles .OrderBy(info => info.LastWriteTime) .Skip(offset) .Take(5) .ToList(); vm.LogFileOffset = offset; if (string.IsNullOrEmpty(file) || !file.EndsWith(fileExtension, StringComparison.Ordinal)) return View("Logs", vm); vm.Log = ""; var fi = vm.LogFiles.FirstOrDefault(o => o.Name == file); if (fi == null) return NotFound(); try { using var fileStream = new FileStream( fi.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); using var reader = new StreamReader(fileStream); vm.Log = await reader.ReadToEndAsync(); } catch { return NotFound(); } } return View("Logs", vm); } } }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Newtonsoft.Json; using Sensus.UI.UiProperties; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading; using Syncfusion.SfChart.XForms; using System.Threading.Tasks; using Sensus.Context; namespace Sensus.Probes { /// <summary> /// An abstract probe. /// </summary> public abstract class Probe { #region static members public static List<Probe> GetAll() { List<Probe> probes = null; // the reflection stuff we do below (at least on android) needs to be run on the main thread. SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(() => { probes = Assembly.GetExecutingAssembly().GetTypes().Where(t => !t.IsAbstract && t.IsSubclassOf(typeof(Probe))).Select(t => Activator.CreateInstance(t) as Probe).OrderBy(p => p.DisplayName).ToList(); }); return probes; } #endregion /// <summary> /// Fired when the most recently sensed datum is changed, regardless of whether the datum was stored. /// </summary> public event EventHandler<Tuple<Datum, Datum>> MostRecentDatumChanged; private bool _enabled; private bool _running; private Datum _mostRecentDatum; private Protocol _protocol; private bool _storeData; private DateTimeOffset? _mostRecentStoreTimestamp; private bool _originallyEnabled; private List<Tuple<bool, DateTime>> _startStopTimes; private List<DateTime> _successfulHealthTestTimes; private List<ChartDataPoint> _chartData; private int _maxChartDataCount; private bool _runLocalCommitOnStore; private readonly object _locker = new object(); [JsonIgnore] public abstract string DisplayName { get; } [JsonIgnore] public abstract string CollectionDescription { get; } [OnOffUiProperty("Enabled:", true, 2)] public bool Enabled { get { return _enabled; } set { if (value != _enabled) { _enabled = value; // _protocol can be null when deserializing the probe -- if Enabled is set before Protocol if (_protocol != null && _protocol.Running) { if (_enabled) StartAsync(); else StopAsync(); } } } } /// <summary> /// Gets or sets whether or not this probe was originally enabled within the protocol. Some probes can become disabled when /// attempting to start them. For example, the temperature probe might not be supported on all hardware and will thus become /// disabled after its failed initialization. Thus, we need a separate variable (other than Enabled) to tell us whether the /// probe was originally enabled. We use this value to calculate participation levels and also to restore the probe before /// sharing it with others (e.g., since other people might have temperature hardware in their devices). /// </summary> /// <value>Whether or not this probe was enabled the first time the protocol was started.</value> public bool OriginallyEnabled { get { return _originallyEnabled; } set { _originallyEnabled = value; } } [JsonIgnore] public bool Running { get { return _running; } } /// <summary> /// Gets or sets the datum that was most recently sensed, regardless of whether the datum was stored. /// </summary> /// <value>The most recent datum.</value> [JsonIgnore] public Datum MostRecentDatum { get { return _mostRecentDatum; } set { if (value != _mostRecentDatum) { Datum previousDatum = _mostRecentDatum; _mostRecentDatum = value; if (MostRecentDatumChanged != null) MostRecentDatumChanged(this, new Tuple<Datum, Datum>(previousDatum, _mostRecentDatum)); } } } [JsonIgnore] public DateTimeOffset? MostRecentStoreTimestamp { get { return _mostRecentStoreTimestamp; } } public Protocol Protocol { get { return _protocol; } set { _protocol = value; } } [OnOffUiProperty("Store Data:", true, 3)] public bool StoreData { get { return _storeData; } set { _storeData = value; } } [JsonIgnore] public abstract Type DatumType { get; } [JsonIgnore] protected abstract float RawParticipation { get; } /// <summary> /// Gets a list of times at which the probe was started (tuple bool = True) and stopped (tuple bool = False). Only includes /// those that have occurred within the protocol's participation horizon. /// </summary> /// <value>The start stop times.</value> public List<Tuple<bool, DateTime>> StartStopTimes { get { return _startStopTimes; } } /// <summary> /// Gets the successful health test times. Only includes those that have occurred within the /// protocol's participation horizon. /// </summary> /// <value>The successful health test times.</value> public List<DateTime> SuccessfulHealthTestTimes { get { return _successfulHealthTestTimes; } } [EntryIntegerUiProperty("Max Chart Data Count:", true, 50)] public int MaxChartDataCount { get { return _maxChartDataCount; } set { if (value > 0) _maxChartDataCount = value; // trim chart data collection lock (_chartData) { while (_chartData.Count > 0 && _chartData.Count > _maxChartDataCount) _chartData.RemoveAt(0); } } } [OnOffUiProperty("Run Local Commit On Store:", true, 14)] public bool RunLocalCommitOnStore { get { return _runLocalCommitOnStore; } set { _runLocalCommitOnStore = value; } } protected Probe() { _enabled = _running = false; _storeData = true; _startStopTimes = new List<Tuple<bool, DateTime>>(); _successfulHealthTestTimes = new List<DateTime>(); _maxChartDataCount = 10; _chartData = new List<ChartDataPoint>(_maxChartDataCount + 1); } /// <summary> /// Initializes this probe. Throws an exception if initialization fails. After successful completion the probe is considered to be /// running and a candidate for stopping at some future point. /// </summary> protected virtual void Initialize() { lock (_chartData) { _chartData.Clear(); } _mostRecentDatum = null; _mostRecentStoreTimestamp = DateTimeOffset.UtcNow; // mark storage delay from initialization of probe } /// <summary> /// Gets the participation level for the current probe. If this probe was originally enabled within the protocol, then /// this will be a value between 0 and 1, with 1 indicating perfect participation and 0 indicating no participation. If /// this probe was not originally enabled within the protocol, then the returned value will be null, indicating that this /// probe should not be included in calculations of overall protocol participation. Probes can become disabled if they /// are not supported on the current device or if the user refuses to initialize them. /// Although they become disabled, they were originally enabled within the protocol and participation should reflect this. /// Lastly, this will return null if the probe is not storing its data, as might be the case if a probe is enabled in order /// to trigger scripts but not told to store its data. /// </summary> /// <returns>The participation level (null, or somewhere 0-1).</returns> public float? GetParticipation() { if (_originallyEnabled && _storeData) return Math.Min(RawParticipation, 1); // raw participations can be > 1, e.g. in the case of polling probes that the user can cause to poll repeatedly. cut off at 1 to maintain the interpretation of 1 as perfect participation. else return null; } protected void StartAsync() { Task.Run(() => { try { Start(); } catch (Exception) { } }); } /// <summary> /// Start this instance, throwing an exception if anything goes wrong. If an exception is thrown, the caller can assume that any relevant /// information will have already been logged and displayed. Thus, the caller doesn't need to do anything with the exception information. /// </summary> public void Start() { try { InternalStart(); } catch (Exception startException) { // stop probe to clean up any inconsistent state information. try { Stop(); } catch (Exception stopException) { SensusServiceHelper.Get().Logger.Log("Failed to stop probe after failing to start it: " + stopException.Message, LoggingLevel.Normal, GetType()); } string message = "Failed to start probe \"" + GetType().Name + "\": " + startException.Message; SensusServiceHelper.Get().Logger.Log(message, LoggingLevel.Normal, GetType()); SensusServiceHelper.Get().FlashNotificationAsync(message, false, TimeSpan.FromSeconds(4)); // don't save failure messages for later, since they might be confusing at that future time. // disable probe if it is not supported on the device (or if the user has elected not to enable it -- e.g., by refusing to log into facebook) if (startException is NotSupportedException) { Enabled = false; } throw startException; } } /// <summary> /// Throws an exception if start fails. Should be called first within child-class overrides. This should only be called within Start. This setup /// allows for child-class overrides, but since InternalStart is protected, it cannot be called from the outside. Outsiders only have access to /// Start (perhaps via Enabled), which takes care of any exceptions arising from the entire chain of InternalStart overrides. /// </summary> protected virtual void InternalStart() { lock (_locker) { if (_running) SensusServiceHelper.Get().Logger.Log("Attempted to start probe, but it was already running.", LoggingLevel.Normal, GetType()); else { SensusServiceHelper.Get().Logger.Log("Starting.", LoggingLevel.Normal, GetType()); Initialize(); // the probe has successfully initialized and can now be considered started/running. _running = true; lock (_startStopTimes) { _startStopTimes.Add(new Tuple<bool, DateTime>(true, DateTime.Now)); _startStopTimes.RemoveAll(t => t.Item2 < Protocol.ParticipationHorizon); } } } } public virtual Task StoreDatumAsync(Datum datum, CancellationToken cancellationToken) { // track the most recent datum and call timestamp regardless of whether the datum is null or whether we're storing data MostRecentDatum = datum; _mostRecentStoreTimestamp = DateTimeOffset.UtcNow; // datum is allowed to be null, indicating the the probe attempted to obtain data but it didn't find any (in the case of polling probes). if (datum != null) { datum.ProtocolId = Protocol.Id; if (_storeData) { ChartDataPoint chartDataPoint = GetChartDataPointFromDatum(datum); if (chartDataPoint != null) { lock (_chartData) { _chartData.Add(chartDataPoint); while (_chartData.Count > 0 && _chartData.Count > _maxChartDataCount) _chartData.RemoveAt(0); } } return _protocol.LocalDataStore.AddAsync(datum, cancellationToken, _runLocalCommitOnStore); } } return Task.FromResult(false); } protected void StopAsync() { Task.Run(() => { try { Stop(); } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Failed to stop: " + ex.Message, LoggingLevel.Normal, GetType()); } }); } /// <summary> /// Should be called first within child-class overrides. /// </summary> public virtual void Stop() { lock (_locker) { if (_running) { SensusServiceHelper.Get().Logger.Log("Stopping.", LoggingLevel.Normal, GetType()); _running = false; lock (_startStopTimes) { _startStopTimes.Add(new Tuple<bool, DateTime>(false, DateTime.Now)); _startStopTimes.RemoveAll(t => t.Item2 < Protocol.ParticipationHorizon); } } else SensusServiceHelper.Get().Logger.Log("Attempted to stop probe, but it wasn't running.", LoggingLevel.Normal, GetType()); } } public void Restart() { lock (_locker) { Stop(); Start(); } } public virtual bool TestHealth(ref string error, ref string warning, ref string misc) { bool restart = false; if (!_running) { restart = true; error += "Probe \"" + GetType().FullName + "\" is not running." + Environment.NewLine; } return restart; } public virtual void Reset() { if (_running) throw new Exception("Cannot reset probe while it is running."); lock (_chartData) { _chartData.Clear(); } lock (_startStopTimes) { _startStopTimes.Clear(); } lock (_successfulHealthTestTimes) { _successfulHealthTestTimes.Clear(); } _mostRecentDatum = null; _mostRecentStoreTimestamp = null; } public SfChart GetChart() { ChartSeries series = GetChartSeries(); if (series == null) return null; // provide the series with a copy of the chart data. if we provide the actual list, then the // chart wants to auto-update the display on subsequent additions to the list. if this happens, // then we'll need to update the list on the UI thread so that the chart is redrawn correctly. // and if this is the case then we're in trouble because xamarin forms is not always initialized // when the list is updated with probed data (if the activity is killed). lock (_chartData) { series.ItemsSource = _chartData.ToList(); } SfChart chart = new SfChart { PrimaryAxis = GetChartPrimaryAxis(), SecondaryAxis = GetChartSecondaryAxis(), }; chart.Series.Add(series); chart.ChartBehaviors.Add(new ChartZoomPanBehavior { EnablePanning = true, EnableZooming = true, EnableDoubleTap = true }); return chart; } protected abstract ChartSeries GetChartSeries(); protected abstract ChartAxis GetChartPrimaryAxis(); protected abstract RangeAxisBase GetChartSecondaryAxis(); protected abstract ChartDataPoint GetChartDataPointFromDatum(Datum datum); } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using org.swyn.foundation.utils; namespace tdbadmin { /// <summary> /// Summary description for Country. /// </summary> public class FGraphics : System.Windows.Forms.Form { private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.GroupBox TDB_abgrp; private System.Windows.Forms.Button TDB_ab_clr; private System.Windows.Forms.Button TDB_ab_sel; private System.Windows.Forms.Button TDB_ab_exit; private System.Windows.Forms.Button TDB_ab_del; private System.Windows.Forms.Button TDB_ab_upd; private System.Windows.Forms.Button TDB_ab_ins; private System.Windows.Forms.Label tdb_e_id; private System.Windows.Forms.TextBox tdb_e_bez; private System.Windows.Forms.TextBox tdb_e_text; private System.Windows.Forms.Label tdb_l_text; private System.Windows.Forms.Label tdb_l_bez; private System.Windows.Forms.Label tdb_l_id; private tdbgui.GUIpricet PT; private Button Gra_b_draw; private ComboBox Gra_e_dlt; private Label Gra_l_dlt; private Button Gra_b_regions; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public FGraphics() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // PT = new tdbgui.GUIpricet(); } /// <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.groupBox1 = new System.Windows.Forms.GroupBox(); this.Gra_b_regions = new System.Windows.Forms.Button(); this.Gra_b_draw = new System.Windows.Forms.Button(); this.Gra_e_dlt = new System.Windows.Forms.ComboBox(); this.Gra_l_dlt = new System.Windows.Forms.Label(); this.tdb_e_id = new System.Windows.Forms.Label(); this.tdb_e_bez = new System.Windows.Forms.TextBox(); this.tdb_e_text = new System.Windows.Forms.TextBox(); this.tdb_l_text = new System.Windows.Forms.Label(); this.tdb_l_bez = new System.Windows.Forms.Label(); this.tdb_l_id = new System.Windows.Forms.Label(); this.TDB_abgrp = new System.Windows.Forms.GroupBox(); this.TDB_ab_clr = new System.Windows.Forms.Button(); this.TDB_ab_sel = new System.Windows.Forms.Button(); this.TDB_ab_exit = new System.Windows.Forms.Button(); this.TDB_ab_del = new System.Windows.Forms.Button(); this.TDB_ab_upd = new System.Windows.Forms.Button(); this.TDB_ab_ins = new System.Windows.Forms.Button(); this.groupBox1.SuspendLayout(); this.TDB_abgrp.SuspendLayout(); this.SuspendLayout(); // // groupBox1 // this.groupBox1.Controls.Add(this.Gra_b_regions); this.groupBox1.Controls.Add(this.Gra_b_draw); this.groupBox1.Controls.Add(this.Gra_e_dlt); this.groupBox1.Controls.Add(this.Gra_l_dlt); this.groupBox1.Controls.Add(this.tdb_e_id); this.groupBox1.Controls.Add(this.tdb_e_bez); this.groupBox1.Controls.Add(this.tdb_e_text); this.groupBox1.Controls.Add(this.tdb_l_text); this.groupBox1.Controls.Add(this.tdb_l_bez); this.groupBox1.Controls.Add(this.tdb_l_id); this.groupBox1.Dock = System.Windows.Forms.DockStyle.Fill; this.groupBox1.Location = new System.Drawing.Point(0, 0); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(608, 249); this.groupBox1.TabIndex = 13; this.groupBox1.TabStop = false; this.groupBox1.Text = "Description"; // // Gra_b_regions // this.Gra_b_regions.Location = new System.Drawing.Point(499, 158); this.Gra_b_regions.Name = "Gra_b_regions"; this.Gra_b_regions.Size = new System.Drawing.Size(93, 23); this.Gra_b_regions.TabIndex = 13; this.Gra_b_regions.Text = "Regions"; this.Gra_b_regions.UseVisualStyleBackColor = true; // // Gra_b_draw // this.Gra_b_draw.Location = new System.Drawing.Point(395, 158); this.Gra_b_draw.Name = "Gra_b_draw"; this.Gra_b_draw.Size = new System.Drawing.Size(98, 23); this.Gra_b_draw.TabIndex = 12; this.Gra_b_draw.Text = "Edit graphics"; this.Gra_b_draw.UseVisualStyleBackColor = true; // // Gra_e_dlt // this.Gra_e_dlt.FormattingEnabled = true; this.Gra_e_dlt.Location = new System.Drawing.Point(136, 160); this.Gra_e_dlt.Name = "Gra_e_dlt"; this.Gra_e_dlt.Size = new System.Drawing.Size(253, 21); this.Gra_e_dlt.TabIndex = 11; // // Gra_l_dlt // this.Gra_l_dlt.AutoSize = true; this.Gra_l_dlt.Location = new System.Drawing.Point(8, 163); this.Gra_l_dlt.Name = "Gra_l_dlt"; this.Gra_l_dlt.Size = new System.Drawing.Size(45, 13); this.Gra_l_dlt.TabIndex = 10; this.Gra_l_dlt.Text = "Supplier"; // // tdb_e_id // this.tdb_e_id.Location = new System.Drawing.Point(136, 24); this.tdb_e_id.Name = "tdb_e_id"; this.tdb_e_id.Size = new System.Drawing.Size(64, 16); this.tdb_e_id.TabIndex = 9; // // tdb_e_bez // this.tdb_e_bez.Location = new System.Drawing.Point(136, 40); this.tdb_e_bez.Name = "tdb_e_bez"; this.tdb_e_bez.Size = new System.Drawing.Size(456, 20); this.tdb_e_bez.TabIndex = 0; // // tdb_e_text // this.tdb_e_text.Location = new System.Drawing.Point(136, 66); this.tdb_e_text.Multiline = true; this.tdb_e_text.Name = "tdb_e_text"; this.tdb_e_text.Size = new System.Drawing.Size(456, 88); this.tdb_e_text.TabIndex = 2; // // tdb_l_text // this.tdb_l_text.Location = new System.Drawing.Point(8, 99); this.tdb_l_text.Name = "tdb_l_text"; this.tdb_l_text.RightToLeft = System.Windows.Forms.RightToLeft.No; this.tdb_l_text.Size = new System.Drawing.Size(100, 23); this.tdb_l_text.TabIndex = 4; this.tdb_l_text.Text = "Description"; // // tdb_l_bez // this.tdb_l_bez.Location = new System.Drawing.Point(8, 39); this.tdb_l_bez.Name = "tdb_l_bez"; this.tdb_l_bez.Size = new System.Drawing.Size(100, 23); this.tdb_l_bez.TabIndex = 2; this.tdb_l_bez.Text = "Title"; // // tdb_l_id // this.tdb_l_id.Location = new System.Drawing.Point(8, 21); this.tdb_l_id.Name = "tdb_l_id"; this.tdb_l_id.Size = new System.Drawing.Size(100, 23); this.tdb_l_id.TabIndex = 1; this.tdb_l_id.Text = "ID"; // // TDB_abgrp // this.TDB_abgrp.Controls.Add(this.TDB_ab_clr); this.TDB_abgrp.Controls.Add(this.TDB_ab_sel); this.TDB_abgrp.Controls.Add(this.TDB_ab_exit); this.TDB_abgrp.Controls.Add(this.TDB_ab_del); this.TDB_abgrp.Controls.Add(this.TDB_ab_upd); this.TDB_abgrp.Controls.Add(this.TDB_ab_ins); this.TDB_abgrp.Dock = System.Windows.Forms.DockStyle.Bottom; this.TDB_abgrp.Location = new System.Drawing.Point(0, 196); this.TDB_abgrp.Name = "TDB_abgrp"; this.TDB_abgrp.Size = new System.Drawing.Size(608, 53); this.TDB_abgrp.TabIndex = 15; this.TDB_abgrp.TabStop = false; this.TDB_abgrp.Text = "Actions"; // // TDB_ab_clr // this.TDB_ab_clr.Dock = System.Windows.Forms.DockStyle.Right; this.TDB_ab_clr.Location = new System.Drawing.Point(455, 16); this.TDB_ab_clr.Name = "TDB_ab_clr"; this.TDB_ab_clr.Size = new System.Drawing.Size(75, 34); this.TDB_ab_clr.TabIndex = 10; this.TDB_ab_clr.Text = "Clear"; this.TDB_ab_clr.Click += new System.EventHandler(this.TDB_ab_clr_Click); // // TDB_ab_sel // this.TDB_ab_sel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(255))))); this.TDB_ab_sel.Dock = System.Windows.Forms.DockStyle.Left; this.TDB_ab_sel.Location = new System.Drawing.Point(228, 16); this.TDB_ab_sel.Name = "TDB_ab_sel"; this.TDB_ab_sel.Size = new System.Drawing.Size(80, 34); this.TDB_ab_sel.TabIndex = 8; this.TDB_ab_sel.Text = "Select"; this.TDB_ab_sel.UseVisualStyleBackColor = false; this.TDB_ab_sel.Click += new System.EventHandler(this.TDB_ab_sel_Click); // // TDB_ab_exit // this.TDB_ab_exit.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(192))))); this.TDB_ab_exit.Dock = System.Windows.Forms.DockStyle.Right; this.TDB_ab_exit.Location = new System.Drawing.Point(530, 16); this.TDB_ab_exit.Name = "TDB_ab_exit"; this.TDB_ab_exit.Size = new System.Drawing.Size(75, 34); this.TDB_ab_exit.TabIndex = 9; this.TDB_ab_exit.Text = "Exit"; this.TDB_ab_exit.UseVisualStyleBackColor = false; this.TDB_ab_exit.Click += new System.EventHandler(this.TDB_ab_exit_Click); // // TDB_ab_del // this.TDB_ab_del.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192))))); this.TDB_ab_del.Dock = System.Windows.Forms.DockStyle.Left; this.TDB_ab_del.Location = new System.Drawing.Point(153, 16); this.TDB_ab_del.Name = "TDB_ab_del"; this.TDB_ab_del.Size = new System.Drawing.Size(75, 34); this.TDB_ab_del.TabIndex = 7; this.TDB_ab_del.Text = "Delete"; this.TDB_ab_del.UseVisualStyleBackColor = false; this.TDB_ab_del.Click += new System.EventHandler(this.TDB_ab_del_Click); // // TDB_ab_upd // this.TDB_ab_upd.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192))))); this.TDB_ab_upd.Dock = System.Windows.Forms.DockStyle.Left; this.TDB_ab_upd.Location = new System.Drawing.Point(78, 16); this.TDB_ab_upd.Name = "TDB_ab_upd"; this.TDB_ab_upd.Size = new System.Drawing.Size(75, 34); this.TDB_ab_upd.TabIndex = 6; this.TDB_ab_upd.Text = "Update"; this.TDB_ab_upd.UseVisualStyleBackColor = false; this.TDB_ab_upd.Click += new System.EventHandler(this.TDB_ab_upd_Click); // // TDB_ab_ins // this.TDB_ab_ins.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192))))); this.TDB_ab_ins.Dock = System.Windows.Forms.DockStyle.Left; this.TDB_ab_ins.Location = new System.Drawing.Point(3, 16); this.TDB_ab_ins.Name = "TDB_ab_ins"; this.TDB_ab_ins.Size = new System.Drawing.Size(75, 34); this.TDB_ab_ins.TabIndex = 5; this.TDB_ab_ins.Text = "Insert"; this.TDB_ab_ins.UseVisualStyleBackColor = false; this.TDB_ab_ins.Click += new System.EventHandler(this.TDB_ab_ins_Click); // // FGraphics // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(608, 249); this.Controls.Add(this.TDB_abgrp); this.Controls.Add(this.groupBox1); this.Name = "FGraphics"; this.Text = "Graphics"; this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.TDB_abgrp.ResumeLayout(false); this.ResumeLayout(false); } #endregion #region Form callbacks private void TDB_ab_sel_Click(object sender, System.EventArgs e) { SelForm Fsel = new SelForm(); PT.Sel(Fsel.GetLV); Fsel.Accept += new EventHandler(TDB_ab_sel_Click_Return); Fsel.ShowDialog(this); } void TDB_ab_sel_Click_Return(object sender, EventArgs e) { int id = -1, rows = 0; SelForm Fsel = (SelForm)sender; id = Fsel.GetID; PT.Get(id, ref rows); tdb_e_id.Text = PT.ObjId.ToString(); tdb_e_bez.Text = PT.ObjBez; tdb_e_text.Text = PT.ObjText; } private void TDB_ab_exit_Click(object sender, System.EventArgs e) { Close(); } private void TDB_ab_ins_Click(object sender, System.EventArgs e) { PT.InsUpd(true, tdb_e_bez.Text, tdb_e_text.Text); tdb_e_id.Text = PT.ObjId.ToString(); } private void TDB_ab_upd_Click(object sender, System.EventArgs e) { PT.InsUpd(false, tdb_e_bez.Text, tdb_e_text.Text); } private void TDB_ab_del_Click(object sender, System.EventArgs e) { int rows = 0; PT.Get(Convert.ToInt32(tdb_e_id.Text), ref rows); PT.Delete(); } private void TDB_ab_clr_Click(object sender, System.EventArgs e) { tdb_e_id.Text = ""; tdb_e_bez.Text = ""; tdb_e_text.Text = ""; } #endregion } }
// *********************************************************************** // Copyright (c) 2007 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Xml; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal.Filters; namespace NUnit.Framework.Internal { /// <summary> /// Interface to be implemented by filters applied to tests. /// The filter applies when running the test, after it has been /// loaded, since this is the only time an ITest exists. /// </summary> public abstract class TestFilter : ITestFilter { /// <summary> /// Unique Empty filter. /// </summary> public readonly static TestFilter Empty = new EmptyFilter(); /// <summary> /// Indicates whether this is the EmptyFilter /// </summary> public bool IsEmpty { get { return this is TestFilter.EmptyFilter; } } /// <summary> /// Indicates whether this is a top-level filter, /// not contained in any other filter. /// </summary> public bool TopLevel { get; set; } /// <summary> /// Determine if a particular test passes the filter criteria. The default /// implementation checks the test itself, its parents and any descendants. /// /// Derived classes may override this method or any of the Match methods /// to change the behavior of the filter. /// </summary> /// <param name="test">The test to which the filter is applied</param> /// <returns>True if the test passes the filter, otherwise false</returns> public virtual bool Pass(ITest test) { return Match(test) || MatchParent(test) || MatchDescendant(test); } /// <summary> /// Determine if a test matches the filter explicitly. That is, it must /// be a direct match of the test itself or one of it's children. /// </summary> /// <param name="test">The test to which the filter is applied</param> /// <returns>True if the test matches the filter explicitly, otherwise false</returns> public virtual bool IsExplicitMatch(ITest test) { return Match(test) || MatchDescendant(test); } /// <summary> /// Determine whether the test itself matches the filter criteria, without /// examining either parents or descendants. This is overridden by each /// different type of filter to perform the necessary tests. /// </summary> /// <param name="test">The test to which the filter is applied</param> /// <returns>True if the filter matches the any parent of the test</returns> public abstract bool Match(ITest test); /// <summary> /// Determine whether any ancestor of the test matches the filter criteria /// </summary> /// <param name="test">The test to which the filter is applied</param> /// <returns>True if the filter matches the an ancestor of the test</returns> public bool MatchParent(ITest test) { return test.Parent != null && (Match(test.Parent) || MatchParent(test.Parent)); } /// <summary> /// Determine whether any descendant of the test matches the filter criteria. /// </summary> /// <param name="test">The test to be matched</param> /// <returns>True if at least one descendant matches the filter criteria</returns> protected virtual bool MatchDescendant(ITest test) { if (test.Tests == null) return false; foreach (ITest child in test.Tests) { if (Match(child) || MatchDescendant(child)) return true; } return false; } /// <summary> /// Create a TestFilter instance from an xml representation. /// </summary> public static TestFilter FromXml(string xmlText) { if (string.IsNullOrEmpty(xmlText)) xmlText = "<filter />"; TNode topNode = TNode.FromXml(xmlText); if (topNode.Name != "filter") throw new Exception("Expected filter element at top level"); int count = topNode.ChildNodes.Count; TestFilter filter = count == 0 ? TestFilter.Empty : count == 1 ? FromXml(topNode.FirstChild) : FromXml(topNode); filter.TopLevel = true; return filter; } /// <summary> /// Create a TestFilter from it's TNode representation /// </summary> public static TestFilter FromXml(TNode node) { bool isRegex = node.Attributes["re"] == "1"; switch (node.Name) { case "filter": case "and": var andFilter = new AndFilter(); foreach (var childNode in node.ChildNodes) andFilter.Add(FromXml(childNode)); return andFilter; case "or": var orFilter = new OrFilter(); foreach (var childNode in node.ChildNodes) orFilter.Add(FromXml(childNode)); return orFilter; case "not": return new NotFilter(FromXml(node.FirstChild)); case "id": return new IdFilter(node.Value); case "test": return new FullNameFilter(node.Value) { IsRegex = isRegex }; case "name": return new TestNameFilter(node.Value) { IsRegex = isRegex }; case "method": return new MethodNameFilter(node.Value) { IsRegex = isRegex }; case "class": return new ClassNameFilter(node.Value) { IsRegex = isRegex }; case "namespace": return new NamespaceFilter(node.Value) { IsRegex = isRegex }; case "cat": return new CategoryFilter(node.Value) { IsRegex = isRegex }; case "prop": string name = node.Attributes["name"]; if (name != null) return new PropertyFilter(name, node.Value) { IsRegex = isRegex }; break; } throw new ArgumentException("Invalid filter element: " + node.Name, "xmlNode"); } /// <summary> /// Nested class provides an empty filter - one that always /// returns true when called. It never matches explicitly. /// </summary> #if !NETSTANDARD1_6 [Serializable] #endif private class EmptyFilter : TestFilter { public override bool Match( ITest test ) { return true; } public override bool Pass( ITest test ) { return true; } public override bool IsExplicitMatch( ITest test ) { return false; } public override TNode AddToXml(TNode parentNode, bool recursive) { return parentNode.AddElement("filter"); } } #region IXmlNodeBuilder Implementation /// <summary> /// Adds an XML node /// </summary> /// <param name="recursive">True if recursive</param> /// <returns>The added XML node</returns> public TNode ToXml(bool recursive) { return AddToXml(new TNode("dummy"), recursive); } /// <summary> /// Adds an XML node /// </summary> /// <param name="parentNode">Parent node</param> /// <param name="recursive">True if recursive</param> /// <returns>The added XML node</returns> public abstract TNode AddToXml(TNode parentNode, bool recursive); #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace Core.Versioning { [DebuggerDisplay("Rev {value} {original} IsDirty {IsDirty} WasComitted {WasComitted} , new {IsNew}")] public class SyncObject { // private object value; private object original; //48 byte public Guid Version { get; private set; } public Guid PreviousVersion { get; private set; } public Guid MergedVersion { get; private set; } //constructs a new sync object public SyncObject() { this.original = null; this.value = null; } /// <summary> /// returns true iff this is new and unchanged /// </summary> public bool IsNew { get { return Version.IsEmpty() && PreviousVersion.IsEmpty(); } } /// <summary> /// returns true if clean meaning it is either unchanged or comitted /// </summary> public bool IsClean { get { if (IsNew && value != null)return false; if (PreviousVersion.IsEmpty() && !Version.IsEmpty())return true; return Version == PreviousVersion; } } /// <summary> /// alias for !IsClean /// </summary> public bool IsDirty { get { return !IsClean; } } /// <summary> /// only possible if object has not been comitted yet /// </summary> public void Revert() { CommitCheck(); if (IsClean) return; value = original.DeepClone(); Version = PreviousVersion; } private void CommitCheck() { if (WasComitted) throw new InvalidOperationException("cannot change value after it was already committed. try using the SyncObject returned by Commit"); } /// <summary> /// returns a deep clone of the clean value /// the clean value is the original value (the value obtained when Revert is called) if the object is not yet committed /// otherwise the clean value is the original value /// /// </summary> public object CleanValue { get { if (WasComitted) return value.DeepClone(); return original.DeepClone(); } } /// <summary> /// returns either the comitted version or if the object was not committed yet /// </summary> public Guid CleanVersion { get { if (WasComitted) return Version; return PreviousVersion; } } public Guid CleanMergedVersion { get { if (WasComitted) return Guid.Empty; return MergedVersion; } } /// <summary> /// returns the value /// if the value is a reference type and the object was already committed a deep copy is returned /// /// </summary> public object Value { get { // return a copy of the value if syncobject was already comitted if (WasComitted) return value.DeepClone(); return value; } set { CommitCheck(); this.value = value; NotifyValueChanged(); } } /// <summary> /// call if object has reference has changed causing the syncobjects Dirty logic to kick in /// </summary> public void NotifyValueChanged() { if (IsDirty) return; Version = Guid.Empty; } /// <summary> /// returns true if commit was called successfully /// </summary> public bool WasComitted { get { return !Version.IsEmpty() && Version != PreviousVersion; } } /// <summary> /// commit the changes. closing off this syncobject to further modification /// </summary> /// <returns></returns> public SyncObject Commit() { if (!IsDirty) throw new InvalidOperationException("No Changes were made. Cannot commit"); Version = Guid.NewGuid(); // deepclone value in case it is still referenced outside of this object value = value.DeepClone(); return Branch(); } /// <summary> /// depending on wether previous version is committed or not /// not committed: create a branch from previousVersion's previousVersion but keep changes made (resulting in a new dirty version) /// comitted: create a branch based on previous versions value. the object will be clean /// </summary> /// <param name="previousVersion"></param> internal SyncObject(SyncObject previousVersion) { if (!previousVersion.WasComitted) { // just branch the previous version of the previous version Value = previousVersion.Value.DeepClone(); original = previousVersion.CleanValue; PreviousVersion = previousVersion.CleanVersion; MergedVersion = previousVersion.MergedVersion; Version = Guid.Empty; } else { PreviousVersion = previousVersion.Version; MergedVersion = Guid.Empty; value = previousVersion.value.DeepClone(); original = previousVersion.value.DeepClone(); Version = PreviousVersion; } } internal SyncObject(SyncObject previous, SyncObject mergedBranch, object mergedValue) { if (!previous.WasComitted) throw new InvalidOperationException("cannot create a merged sync object if previous version was not comitted"); if (!previous.WasComitted) throw new InvalidOperationException("cannot create a merged sync object if branch to be mergedwas not comitted"); this.Value = mergedValue.DeepClone(); this.original = mergedValue.DeepClone(); MergedVersion = mergedBranch.Version; PreviousVersion = previous.Version; Version = Guid.Empty; } internal SyncObject(object value, Guid originalVersion, Guid mergedVersion) { PreviousVersion = originalVersion; MergedVersion = mergedVersion; this.value = value.DeepClone(); } /// <summary> /// creates a branch of this syncobject /// </summary> /// <returns></returns> public SyncObject Branch() { return new SyncObject(this); } /// <summary> /// tries to merge this the specified branch into this object /// </summary> /// <param name="branch"></param> /// <returns></returns> public MergeResult Merge(SyncObject branch) { MergeResult result = new MergeResult(this, branch); return result; } /// <summary> /// returns true if object can commit (isdirty && wascomitted) /// </summary> public bool CanCommit { get { return IsDirty && !WasComitted; } } } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace JavaScriptInjectionWeb { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace SouthwindRepository { /// <summary> /// Strongly-typed collection for the Employee class. /// </summary> [Serializable] public partial class EmployeeCollection : RepositoryList<Employee, EmployeeCollection> { public EmployeeCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>EmployeeCollection</returns> public EmployeeCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { Employee o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the employees table. /// </summary> [Serializable] public partial class Employee : RepositoryRecord<Employee>, IRecordBase { #region .ctors and Default Settings public Employee() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public Employee(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("employees", TableType.Table, DataService.GetInstance("SouthwindRepository")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @""; //columns TableSchema.TableColumn colvarEmployeeID = new TableSchema.TableColumn(schema); colvarEmployeeID.ColumnName = "EmployeeID"; colvarEmployeeID.DataType = DbType.Int32; colvarEmployeeID.MaxLength = 10; colvarEmployeeID.AutoIncrement = true; colvarEmployeeID.IsNullable = false; colvarEmployeeID.IsPrimaryKey = true; colvarEmployeeID.IsForeignKey = false; colvarEmployeeID.IsReadOnly = false; colvarEmployeeID.DefaultSetting = @""; colvarEmployeeID.ForeignKeyTableName = ""; schema.Columns.Add(colvarEmployeeID); TableSchema.TableColumn colvarLastName = new TableSchema.TableColumn(schema); colvarLastName.ColumnName = "LastName"; colvarLastName.DataType = DbType.String; colvarLastName.MaxLength = 20; colvarLastName.AutoIncrement = false; colvarLastName.IsNullable = false; colvarLastName.IsPrimaryKey = false; colvarLastName.IsForeignKey = true; colvarLastName.IsReadOnly = false; colvarLastName.DefaultSetting = @""; colvarLastName.ForeignKeyTableName = ""; schema.Columns.Add(colvarLastName); TableSchema.TableColumn colvarFirstName = new TableSchema.TableColumn(schema); colvarFirstName.ColumnName = "FirstName"; colvarFirstName.DataType = DbType.String; colvarFirstName.MaxLength = 10; colvarFirstName.AutoIncrement = false; colvarFirstName.IsNullable = false; colvarFirstName.IsPrimaryKey = false; colvarFirstName.IsForeignKey = false; colvarFirstName.IsReadOnly = false; colvarFirstName.DefaultSetting = @""; colvarFirstName.ForeignKeyTableName = ""; schema.Columns.Add(colvarFirstName); TableSchema.TableColumn colvarTitle = new TableSchema.TableColumn(schema); colvarTitle.ColumnName = "Title"; colvarTitle.DataType = DbType.String; colvarTitle.MaxLength = 30; colvarTitle.AutoIncrement = false; colvarTitle.IsNullable = true; colvarTitle.IsPrimaryKey = false; colvarTitle.IsForeignKey = false; colvarTitle.IsReadOnly = false; colvarTitle.DefaultSetting = @""; colvarTitle.ForeignKeyTableName = ""; schema.Columns.Add(colvarTitle); TableSchema.TableColumn colvarTitleOfCourtesy = new TableSchema.TableColumn(schema); colvarTitleOfCourtesy.ColumnName = "TitleOfCourtesy"; colvarTitleOfCourtesy.DataType = DbType.String; colvarTitleOfCourtesy.MaxLength = 25; colvarTitleOfCourtesy.AutoIncrement = false; colvarTitleOfCourtesy.IsNullable = true; colvarTitleOfCourtesy.IsPrimaryKey = false; colvarTitleOfCourtesy.IsForeignKey = false; colvarTitleOfCourtesy.IsReadOnly = false; colvarTitleOfCourtesy.DefaultSetting = @""; colvarTitleOfCourtesy.ForeignKeyTableName = ""; schema.Columns.Add(colvarTitleOfCourtesy); TableSchema.TableColumn colvarBirthDate = new TableSchema.TableColumn(schema); colvarBirthDate.ColumnName = "BirthDate"; colvarBirthDate.DataType = DbType.DateTime; colvarBirthDate.MaxLength = 0; colvarBirthDate.AutoIncrement = false; colvarBirthDate.IsNullable = true; colvarBirthDate.IsPrimaryKey = false; colvarBirthDate.IsForeignKey = false; colvarBirthDate.IsReadOnly = false; colvarBirthDate.DefaultSetting = @""; colvarBirthDate.ForeignKeyTableName = ""; schema.Columns.Add(colvarBirthDate); TableSchema.TableColumn colvarHireDate = new TableSchema.TableColumn(schema); colvarHireDate.ColumnName = "HireDate"; colvarHireDate.DataType = DbType.DateTime; colvarHireDate.MaxLength = 0; colvarHireDate.AutoIncrement = false; colvarHireDate.IsNullable = true; colvarHireDate.IsPrimaryKey = false; colvarHireDate.IsForeignKey = false; colvarHireDate.IsReadOnly = false; colvarHireDate.DefaultSetting = @""; colvarHireDate.ForeignKeyTableName = ""; schema.Columns.Add(colvarHireDate); TableSchema.TableColumn colvarAddress = new TableSchema.TableColumn(schema); colvarAddress.ColumnName = "Address"; colvarAddress.DataType = DbType.String; colvarAddress.MaxLength = 60; colvarAddress.AutoIncrement = false; colvarAddress.IsNullable = true; colvarAddress.IsPrimaryKey = false; colvarAddress.IsForeignKey = false; colvarAddress.IsReadOnly = false; colvarAddress.DefaultSetting = @""; colvarAddress.ForeignKeyTableName = ""; schema.Columns.Add(colvarAddress); TableSchema.TableColumn colvarCity = new TableSchema.TableColumn(schema); colvarCity.ColumnName = "City"; colvarCity.DataType = DbType.String; colvarCity.MaxLength = 15; colvarCity.AutoIncrement = false; colvarCity.IsNullable = true; colvarCity.IsPrimaryKey = false; colvarCity.IsForeignKey = false; colvarCity.IsReadOnly = false; colvarCity.DefaultSetting = @""; colvarCity.ForeignKeyTableName = ""; schema.Columns.Add(colvarCity); TableSchema.TableColumn colvarRegion = new TableSchema.TableColumn(schema); colvarRegion.ColumnName = "Region"; colvarRegion.DataType = DbType.String; colvarRegion.MaxLength = 15; colvarRegion.AutoIncrement = false; colvarRegion.IsNullable = true; colvarRegion.IsPrimaryKey = false; colvarRegion.IsForeignKey = false; colvarRegion.IsReadOnly = false; colvarRegion.DefaultSetting = @""; colvarRegion.ForeignKeyTableName = ""; schema.Columns.Add(colvarRegion); TableSchema.TableColumn colvarPostalCode = new TableSchema.TableColumn(schema); colvarPostalCode.ColumnName = "PostalCode"; colvarPostalCode.DataType = DbType.String; colvarPostalCode.MaxLength = 10; colvarPostalCode.AutoIncrement = false; colvarPostalCode.IsNullable = true; colvarPostalCode.IsPrimaryKey = false; colvarPostalCode.IsForeignKey = true; colvarPostalCode.IsReadOnly = false; colvarPostalCode.DefaultSetting = @""; colvarPostalCode.ForeignKeyTableName = ""; schema.Columns.Add(colvarPostalCode); TableSchema.TableColumn colvarCountry = new TableSchema.TableColumn(schema); colvarCountry.ColumnName = "Country"; colvarCountry.DataType = DbType.String; colvarCountry.MaxLength = 15; colvarCountry.AutoIncrement = false; colvarCountry.IsNullable = true; colvarCountry.IsPrimaryKey = false; colvarCountry.IsForeignKey = false; colvarCountry.IsReadOnly = false; colvarCountry.DefaultSetting = @""; colvarCountry.ForeignKeyTableName = ""; schema.Columns.Add(colvarCountry); TableSchema.TableColumn colvarHomePhone = new TableSchema.TableColumn(schema); colvarHomePhone.ColumnName = "HomePhone"; colvarHomePhone.DataType = DbType.String; colvarHomePhone.MaxLength = 24; colvarHomePhone.AutoIncrement = false; colvarHomePhone.IsNullable = true; colvarHomePhone.IsPrimaryKey = false; colvarHomePhone.IsForeignKey = false; colvarHomePhone.IsReadOnly = false; colvarHomePhone.DefaultSetting = @""; colvarHomePhone.ForeignKeyTableName = ""; schema.Columns.Add(colvarHomePhone); TableSchema.TableColumn colvarExtension = new TableSchema.TableColumn(schema); colvarExtension.ColumnName = "Extension"; colvarExtension.DataType = DbType.String; colvarExtension.MaxLength = 4; colvarExtension.AutoIncrement = false; colvarExtension.IsNullable = true; colvarExtension.IsPrimaryKey = false; colvarExtension.IsForeignKey = false; colvarExtension.IsReadOnly = false; colvarExtension.DefaultSetting = @""; colvarExtension.ForeignKeyTableName = ""; schema.Columns.Add(colvarExtension); TableSchema.TableColumn colvarPhoto = new TableSchema.TableColumn(schema); colvarPhoto.ColumnName = "Photo"; colvarPhoto.DataType = DbType.Binary; colvarPhoto.MaxLength = 0; colvarPhoto.AutoIncrement = false; colvarPhoto.IsNullable = true; colvarPhoto.IsPrimaryKey = false; colvarPhoto.IsForeignKey = false; colvarPhoto.IsReadOnly = false; colvarPhoto.DefaultSetting = @""; colvarPhoto.ForeignKeyTableName = ""; schema.Columns.Add(colvarPhoto); TableSchema.TableColumn colvarNotes = new TableSchema.TableColumn(schema); colvarNotes.ColumnName = "Notes"; colvarNotes.DataType = DbType.String; colvarNotes.MaxLength = 0; colvarNotes.AutoIncrement = false; colvarNotes.IsNullable = true; colvarNotes.IsPrimaryKey = false; colvarNotes.IsForeignKey = false; colvarNotes.IsReadOnly = false; colvarNotes.DefaultSetting = @""; colvarNotes.ForeignKeyTableName = ""; schema.Columns.Add(colvarNotes); TableSchema.TableColumn colvarReportsTo = new TableSchema.TableColumn(schema); colvarReportsTo.ColumnName = "ReportsTo"; colvarReportsTo.DataType = DbType.Int32; colvarReportsTo.MaxLength = 10; colvarReportsTo.AutoIncrement = false; colvarReportsTo.IsNullable = true; colvarReportsTo.IsPrimaryKey = false; colvarReportsTo.IsForeignKey = true; colvarReportsTo.IsReadOnly = false; colvarReportsTo.DefaultSetting = @""; colvarReportsTo.ForeignKeyTableName = ""; schema.Columns.Add(colvarReportsTo); TableSchema.TableColumn colvarPhotoPath = new TableSchema.TableColumn(schema); colvarPhotoPath.ColumnName = "PhotoPath"; colvarPhotoPath.DataType = DbType.String; colvarPhotoPath.MaxLength = 255; colvarPhotoPath.AutoIncrement = false; colvarPhotoPath.IsNullable = true; colvarPhotoPath.IsPrimaryKey = false; colvarPhotoPath.IsForeignKey = false; colvarPhotoPath.IsReadOnly = false; colvarPhotoPath.DefaultSetting = @""; colvarPhotoPath.ForeignKeyTableName = ""; schema.Columns.Add(colvarPhotoPath); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["SouthwindRepository"].AddSchema("employees",schema); } } #endregion #region Props [XmlAttribute("EmployeeID")] [Bindable(true)] public int EmployeeID { get { return GetColumnValue<int>(Columns.EmployeeID); } set { SetColumnValue(Columns.EmployeeID, value); } } [XmlAttribute("LastName")] [Bindable(true)] public string LastName { get { return GetColumnValue<string>(Columns.LastName); } set { SetColumnValue(Columns.LastName, value); } } [XmlAttribute("FirstName")] [Bindable(true)] public string FirstName { get { return GetColumnValue<string>(Columns.FirstName); } set { SetColumnValue(Columns.FirstName, value); } } [XmlAttribute("Title")] [Bindable(true)] public string Title { get { return GetColumnValue<string>(Columns.Title); } set { SetColumnValue(Columns.Title, value); } } [XmlAttribute("TitleOfCourtesy")] [Bindable(true)] public string TitleOfCourtesy { get { return GetColumnValue<string>(Columns.TitleOfCourtesy); } set { SetColumnValue(Columns.TitleOfCourtesy, value); } } [XmlAttribute("BirthDate")] [Bindable(true)] public DateTime? BirthDate { get { return GetColumnValue<DateTime?>(Columns.BirthDate); } set { SetColumnValue(Columns.BirthDate, value); } } [XmlAttribute("HireDate")] [Bindable(true)] public DateTime? HireDate { get { return GetColumnValue<DateTime?>(Columns.HireDate); } set { SetColumnValue(Columns.HireDate, value); } } [XmlAttribute("Address")] [Bindable(true)] public string Address { get { return GetColumnValue<string>(Columns.Address); } set { SetColumnValue(Columns.Address, value); } } [XmlAttribute("City")] [Bindable(true)] public string City { get { return GetColumnValue<string>(Columns.City); } set { SetColumnValue(Columns.City, value); } } [XmlAttribute("Region")] [Bindable(true)] public string Region { get { return GetColumnValue<string>(Columns.Region); } set { SetColumnValue(Columns.Region, value); } } [XmlAttribute("PostalCode")] [Bindable(true)] public string PostalCode { get { return GetColumnValue<string>(Columns.PostalCode); } set { SetColumnValue(Columns.PostalCode, value); } } [XmlAttribute("Country")] [Bindable(true)] public string Country { get { return GetColumnValue<string>(Columns.Country); } set { SetColumnValue(Columns.Country, value); } } [XmlAttribute("HomePhone")] [Bindable(true)] public string HomePhone { get { return GetColumnValue<string>(Columns.HomePhone); } set { SetColumnValue(Columns.HomePhone, value); } } [XmlAttribute("Extension")] [Bindable(true)] public string Extension { get { return GetColumnValue<string>(Columns.Extension); } set { SetColumnValue(Columns.Extension, value); } } [XmlAttribute("Photo")] [Bindable(true)] public byte[] Photo { get { return GetColumnValue<byte[]>(Columns.Photo); } set { SetColumnValue(Columns.Photo, value); } } [XmlAttribute("Notes")] [Bindable(true)] public string Notes { get { return GetColumnValue<string>(Columns.Notes); } set { SetColumnValue(Columns.Notes, value); } } [XmlAttribute("ReportsTo")] [Bindable(true)] public int? ReportsTo { get { return GetColumnValue<int?>(Columns.ReportsTo); } set { SetColumnValue(Columns.ReportsTo, value); } } [XmlAttribute("PhotoPath")] [Bindable(true)] public string PhotoPath { get { return GetColumnValue<string>(Columns.PhotoPath); } set { SetColumnValue(Columns.PhotoPath, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region Typed Columns public static TableSchema.TableColumn EmployeeIDColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn LastNameColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn FirstNameColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn TitleColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn TitleOfCourtesyColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn BirthDateColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn HireDateColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn AddressColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn CityColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn RegionColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn PostalCodeColumn { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn CountryColumn { get { return Schema.Columns[11]; } } public static TableSchema.TableColumn HomePhoneColumn { get { return Schema.Columns[12]; } } public static TableSchema.TableColumn ExtensionColumn { get { return Schema.Columns[13]; } } public static TableSchema.TableColumn PhotoColumn { get { return Schema.Columns[14]; } } public static TableSchema.TableColumn NotesColumn { get { return Schema.Columns[15]; } } public static TableSchema.TableColumn ReportsToColumn { get { return Schema.Columns[16]; } } public static TableSchema.TableColumn PhotoPathColumn { get { return Schema.Columns[17]; } } #endregion #region Columns Struct public struct Columns { public static string EmployeeID = @"EmployeeID"; public static string LastName = @"LastName"; public static string FirstName = @"FirstName"; public static string Title = @"Title"; public static string TitleOfCourtesy = @"TitleOfCourtesy"; public static string BirthDate = @"BirthDate"; public static string HireDate = @"HireDate"; public static string Address = @"Address"; public static string City = @"City"; public static string Region = @"Region"; public static string PostalCode = @"PostalCode"; public static string Country = @"Country"; public static string HomePhone = @"HomePhone"; public static string Extension = @"Extension"; public static string Photo = @"Photo"; public static string Notes = @"Notes"; public static string ReportsTo = @"ReportsTo"; public static string PhotoPath = @"PhotoPath"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using Xunit; public partial class ConsoleEncoding : RemoteExecutorTestBase { public static IEnumerable<object[]> InputData() { yield return new object[] { "This is Ascii string" }; yield return new object[] { "This is string have surrogates \uD800\uDC00" }; yield return new object[] { "This string has non ascii characters \u03b1\u00df\u0393\u03c0\u03a3\u03c3\u00b5" }; yield return new object[] { "This string has invalid surrogates \uD800\uD800\uD800\uD800\uD800\uD800" }; yield return new object[] { "\uD800" }; } [Theory] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Issue https://github.com/dotnet/corefx/issues/18220")] [MemberData(nameof(InputData))] public void TestEncoding(string inputString) { TextWriter outConsoleStream = Console.Out; TextReader inConsoleStream = Console.In; try { byte [] inputBytes; byte [] inputBytesNoBom = Console.OutputEncoding.GetBytes(inputString); byte [] bom = Console.OutputEncoding.GetPreamble(); if (bom.Length > 0) { inputBytes = new byte[inputBytesNoBom.Length + bom.Length]; Array.Copy(bom, inputBytes, bom.Length); Array.Copy(inputBytesNoBom, 0, inputBytes, bom.Length, inputBytesNoBom.Length); } else { inputBytes = inputBytesNoBom; } byte[] outBytes = new byte[inputBytes.Length]; using (MemoryStream ms = new MemoryStream(outBytes, true)) { using (StreamWriter sw = new StreamWriter(ms, Console.OutputEncoding)) { Console.SetOut(sw); Console.Write(inputString); } } Assert.Equal(inputBytes, outBytes); string inString = new String(Console.InputEncoding.GetChars(inputBytesNoBom)); string outString; using (MemoryStream ms = new MemoryStream(inputBytesNoBom, false)) { using (StreamReader sr = new StreamReader(ms, Console.InputEncoding)) { Console.SetIn(sr); outString = Console.In.ReadToEnd(); } } Assert.True(inString.Equals(outString), $"Encoding: {Console.InputEncoding}, Codepage: {Console.InputEncoding.CodePage}, Expected: {inString}, Actual: {outString} "); } finally { Console.SetOut(outConsoleStream); Console.SetIn(inConsoleStream); } } [Fact] public void TestValidEncodings() { Action<Encoding> check = encoding => { Console.OutputEncoding = encoding; Assert.Equal(encoding, Console.OutputEncoding); Console.InputEncoding = encoding; Assert.Equal(encoding, Console.InputEncoding); }; // These seem to always be available check(Encoding.UTF8); check(Encoding.Unicode); // On full Windows, ASCII is available also if (!PlatformDetection.IsWindowsNanoServer) { check(Encoding.ASCII); } } public class NonexistentCodePageEncoding : Encoding { public override int CodePage => int.MinValue; public override int GetByteCount(char[] chars, int index, int count) => 0; public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) => 0; public override int GetCharCount(byte[] bytes, int index, int count) => 0; public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) => 0; public override int GetMaxByteCount(int charCount) => 0; public override int GetMaxCharCount(int byteCount) => 0; } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Issue https://github.com/dotnet/corefx/issues/18220")] public void InputEncoding_SetWithInInitialized_ResetsIn() { RemoteInvoke(() => { // Initialize Console.In TextReader inReader = Console.In; Assert.NotNull(inReader); Assert.Same(inReader, Console.In); // Change the InputEncoding Console.InputEncoding = Encoding.Unicode; // Not ASCII: not supported by Windows Nano Assert.Equal(Encoding.Unicode, Console.InputEncoding); if (PlatformDetection.IsWindows) { // Console.set_InputEncoding is effectively a nop on Unix, // so although the reader accessed by Console.In will be reset, // it'll be re-initialized on re-access to the same singleton, // (assuming input isn't redirected). Assert.NotSame(inReader, Console.In); } return SuccessExitCode; }).Dispose(); } [Fact] public void InputEncoding_SetNull_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("value", () => Console.InputEncoding = null); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void InputEncoding_SetEncodingWithInvalidCodePage_ThrowsIOException() { NonexistentCodePageEncoding invalidEncoding = new NonexistentCodePageEncoding(); Assert.Throws<IOException>(() => Console.InputEncoding = invalidEncoding); Assert.NotSame(invalidEncoding, Console.InputEncoding); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Issue https://github.com/dotnet/corefx/issues/18220")] public void OutputEncoding_SetWithErrorAndOutputInitialized_ResetsErrorAndOutput() { RemoteInvoke(() => { // Initialize Console.Error TextWriter errorWriter = Console.Error; Assert.NotNull(errorWriter); Assert.Same(errorWriter, Console.Error); // Initialize Console.Out TextWriter outWriter = Console.Out; Assert.NotNull(outWriter); Assert.Same(outWriter, Console.Out); // Change the OutputEncoding Console.OutputEncoding = Encoding.Unicode; // Not ASCII: not supported by Windows Nano Assert.Equal(Encoding.Unicode, Console.OutputEncoding); Assert.NotSame(errorWriter, Console.Error); Assert.NotSame(outWriter, Console.Out); return SuccessExitCode; }).Dispose(); } [Fact] public void OutputEncoding_SetNull_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("value", () => Console.OutputEncoding = null); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Issue https://github.com/dotnet/corefx/issues/18220")] [PlatformSpecific(TestPlatforms.Windows)] public void OutputEncoding_SetEncodingWithInvalidCodePage_ThrowsIOException() { NonexistentCodePageEncoding invalidEncoding = new NonexistentCodePageEncoding(); Assert.Throws<IOException>(() => Console.OutputEncoding = invalidEncoding); Assert.NotSame(invalidEncoding, Console.OutputEncoding); } }
/*************************************************************************** * SourceManager.cs * * Copyright (C) 2005-2006 Novell, Inc. * Written by Aaron Bockover <[email protected]> ****************************************************************************/ /* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ using System; using System.Collections; using System.Collections.Generic; using Banshee.Base; #if win32 using Banshee.Winforms; #else using Mono.Unix; #endif namespace Banshee.Sources { public delegate void SourceEventHandler(SourceEventArgs args); public delegate void SourceAddedHandler(SourceAddedArgs args); public class SourceEventArgs : EventArgs { public Source Source; } public class SourceAddedArgs : SourceEventArgs { public int Position; } public static class SourceManager { private static List<Source> sources = new List<Source>(); private static Source active_source; private static Source default_source; public static event SourceEventHandler SourceUpdated; public static event SourceEventHandler SourceViewChanged; public static event SourceAddedHandler SourceAdded; public static event SourceEventHandler SourceRemoved; public static event SourceEventHandler ActiveSourceChanged; public static event TrackEventHandler SourceTrackAdded; public static event TrackEventHandler SourceTrackRemoved; public static void AddSource(Source source, bool isDefault) { if(source == null || ContainsSource (source)) { return; } int position = FindSourceInsertPosition(source); sources.Insert(position, source); if(isDefault) { default_source = source; } source.Updated += OnSourceUpdated; source.ViewChanged += OnSourceViewChanged; source.TrackAdded += OnSourceTrackAdded; source.TrackRemoved += OnSourceTrackRemoved; source.ChildSourceAdded += OnChildSourceAdded; source.ChildSourceRemoved += OnChildSourceRemoved; ThreadAssist.ProxyToMain(delegate { SourceAddedHandler handler = SourceAdded; if(handler != null) { SourceAddedArgs args = new SourceAddedArgs(); args.Position = position; args.Source = source; handler(args); } }); foreach(Source child_source in source.Children) { AddSource(child_source, false); } } public static void AddSource(Source source) { AddSource(source, false); } public static void RemoveSource(Source source) { if(source == default_source) { default_source = null; } sources.Remove(source); source.Updated -= OnSourceUpdated; source.ViewChanged -= OnSourceViewChanged; source.TrackAdded -= OnSourceTrackAdded; source.TrackRemoved -= OnSourceTrackRemoved; ThreadAssist.ProxyToMain(delegate { if(source == active_source) { SetActiveSource(default_source); } SourceEventHandler handler = SourceRemoved; if(handler != null) { SourceEventArgs args = new SourceEventArgs(); args.Source = source; handler(args); } }); } public static void RemoveSource(Type type) { Queue<Source> remove_queue = new Queue<Source>(); foreach(Source source in Sources) { if(source.GetType() == type) { remove_queue.Enqueue(source); } } while(remove_queue.Count > 0) { RemoveSource(remove_queue.Dequeue()); } } public static bool ContainsSource(Source source) { return sources.Contains(source); } private static void OnSourceUpdated(object o, EventArgs args) { SourceEventHandler handler = SourceUpdated; if(handler != null) { SourceEventArgs evargs = new SourceEventArgs(); evargs.Source = o as Source; handler(evargs); } } private static void OnSourceViewChanged(object o, EventArgs args) { SourceEventHandler handler = SourceViewChanged; if(handler != null) { SourceEventArgs evargs = new SourceEventArgs(); evargs.Source = o as Source; handler(evargs); } } private static void OnSourceTrackAdded(object o, TrackEventArgs args) { TrackEventHandler handler = SourceTrackAdded; if(handler != null) { handler(o, args); } } private static void OnSourceTrackRemoved(object o, TrackEventArgs args) { TrackEventHandler handler = SourceTrackRemoved; if(handler != null) { handler(o, args); } } private static void OnChildSourceAdded(SourceEventArgs args) { args.Source.Updated += OnSourceUpdated; } private static void OnChildSourceRemoved(SourceEventArgs args) { args.Source.Updated -= OnSourceUpdated; } private static int FindSourceInsertPosition(Source source) { for(int i = sources.Count - 1; i >= 0; i--) { if((sources[i] as Source).Order == source.Order) { return i; } } for(int i = 0; i < sources.Count; i++) { if((sources[i] as Source).Order >= source.Order) { return i; } } return sources.Count; } public static Source DefaultSource { get { return default_source; } set { default_source = value; } } public static Source ActiveSource { get { return active_source; } } public static void SetActiveSource(Source source) { SetActiveSource(source, true); } public static void SetActiveSource(Source source, bool notify) { if(active_source != null) { active_source.Deactivate(); } active_source = source; source.Activate(); if(!notify) { return; } ThreadAssist.ProxyToMain(delegate { SourceEventHandler handler = ActiveSourceChanged; if(handler != null) { SourceEventArgs args = new SourceEventArgs(); args.Source = active_source; handler(args); } }); } #if !win32 public static void SensitizeActions(Source source) { Globals.ActionManager["WriteCDAction"].Visible = source.CanWriteToCD; Globals.ActionManager["WriteCDAction"].Sensitive = source is Banshee.Burner.BurnerSource; Globals.ActionManager.AudioCdActions.Visible = source is AudioCdSource; Globals.ActionManager["RenameSourceAction"].Visible = source.CanRename; Globals.ActionManager["UnmapSourceAction"].Visible = source.CanUnmap; Globals.ActionManager.DapActions.Visible = source is DapSource; Globals.ActionManager["SelectedSourcePropertiesAction"].Visible = source.HasProperties; if(source is IImportSource) { Globals.ActionManager["ImportSourceAction"].Visible = source is IImportSource; Globals.ActionManager["ImportSourceAction"].Label = Catalog.GetString("Import") + " '" + source.Name + "'"; } else { Globals.ActionManager["ImportSourceAction"].Visible = false; } if(source is DapSource) { DapSource dapSource = source as DapSource; if (dapSource.Device.CanSynchronize) { Globals.ActionManager["SyncDapAction"].Sensitive = !dapSource.Device.IsReadOnly; Globals.ActionManager.SetActionLabel("SyncDapAction", String.Format("{0} {1}", Catalog.GetString("Synchronize"), dapSource.Device.GenericName)); } else { Globals.ActionManager["SyncDapAction"].Visible = false; } } Globals.ActionManager["RenameSourceAction"].Label = String.Format ( Catalog.GetString("Rename {0}"), source.GenericName ); Globals.ActionManager["UnmapSourceAction"].Label = source.UnmapLabel; Globals.ActionManager["UnmapSourceAction"].StockId = source.UnmapIcon; Globals.ActionManager["SelectedSourcePropertiesAction"].Label = source.SourcePropertiesLabel; Globals.ActionManager["SelectedSourcePropertiesAction"].StockId = source.SourcePropertiesIcon; } #endif public static ICollection<Source> Sources { get { return sources; } } } }
using Mono.Unix; using System; using System.Runtime.InteropServices; using Gphoto2; namespace LibGPhoto2 { internal enum CameraFileType { Preview, Normal, Raw, Audio, Exif, MetaData } internal enum CameraFileAccessType { Memory, Fd } internal static class MimeTypes { [MarshalAs(UnmanagedType.LPTStr)] public const string WAV = "audio/wav"; [MarshalAs(UnmanagedType.LPTStr)] public const string RAW = "image/x-raw"; [MarshalAs(UnmanagedType.LPTStr)] public const string PNG = "image/png"; [MarshalAs(UnmanagedType.LPTStr)] public const string PGM = "image/x-portable-graymap"; [MarshalAs(UnmanagedType.LPTStr)] public const string PPM = "image/x-portable-pixmap"; [MarshalAs(UnmanagedType.LPTStr)] public const string PNM = "image/x-portable-anymap"; [MarshalAs(UnmanagedType.LPTStr)] public const string JPEG = "image/jpeg"; [MarshalAs(UnmanagedType.LPTStr)] public const string TIFF = "image/tiff"; [MarshalAs(UnmanagedType.LPTStr)] public const string BMP = "image/bmp"; [MarshalAs(UnmanagedType.LPTStr)] public const string QUICKTIME = "video/quicktime"; [MarshalAs(UnmanagedType.LPTStr)] public const string AVI = "video/x-msvideo"; [MarshalAs(UnmanagedType.LPTStr)] public const string CRW = "image/x-canon-raw"; [MarshalAs(UnmanagedType.LPTStr)] public const string UNKNOWN = "application/octet-stream"; [MarshalAs(UnmanagedType.LPTStr)] public const string EXIF = "application/x-exif"; [MarshalAs(UnmanagedType.LPTStr)] public const string MP3 = "audio/mpeg"; [MarshalAs(UnmanagedType.LPTStr)] public const string OGG = "application/ogg"; [MarshalAs(UnmanagedType.LPTStr)] public const string WMA = "audio/x-wma"; [MarshalAs(UnmanagedType.LPTStr)] public const string ASF = "audio/x-asf"; [MarshalAs(UnmanagedType.LPTStr)] public const string MPEG = "video/mpeg"; } internal class CameraFile : Object { public CameraFile() { IntPtr native; Error.CheckError (gp_file_new (out native)); this.handle = new HandleRef (this, native); } public CameraFile (UnixStream file) { IntPtr native; Error.CheckError (gp_file_new_from_fd (out native, file.Handle)); this.handle = new HandleRef (this, native); } public CameraFile (int fd) { IntPtr native; Error.CheckError (gp_file_new_from_fd (out native, fd)); this.handle = new HandleRef (this, native); } protected override void Dispose (bool disposing) { if(!Disposed) { // Don't check the error as we don't want to throw an exception if it fails gp_file_unref (this.Handle); base.Dispose(disposing); } } public void Append (byte[] data) { Error.CheckError (gp_file_append (this.Handle, data, new IntPtr(data.Length))); } public void Open (string filename) { Error.CheckError (gp_file_open (this.Handle, filename)); } public void Save (string filename) { Error.CheckError (gp_file_save (this.Handle, filename)); } public void Clean (string filename) { Error.CheckError (gp_file_clean (this.Handle)); } public string GetName () { string name; Error.CheckError (gp_file_get_name (this.Handle, out name)); return name; } public void SetName (string name) { Error.CheckError (gp_file_set_name (this.Handle, name)); } public CameraFileType GetFileType () { CameraFileType type; Error.CheckError (gp_file_get_type (this.Handle, out type)); return type; } public void SetFileType (CameraFileType type) { Error.CheckError (gp_file_set_type (this.Handle, type)); } public string GetMimeType () { string mime; Error.CheckError (gp_file_get_mime_type (this.Handle, out mime)); return mime; } public void SetMimeType (string mime_type) { Error.CheckError (gp_file_set_mime_type (this.Handle, mime_type)); } public void AdjustNameForMimeType () { Error.CheckError (gp_file_adjust_name_for_mime_type (this.Handle)); } public void Convert (string mime_type) { Error.CheckError (CameraFile.gp_file_convert (this.Handle, mime_type)); } public void Copy (CameraFile source) { Error.CheckError (gp_file_copy (this.Handle, source.Handle)); } public void SetHeader (byte[] header) { Error.CheckError (gp_file_set_header(this.Handle, header)); } public void SetWidthHeight (int width, int height) { Error.CheckError (gp_file_set_width_and_height(this.Handle, width, height)); } public void SetDataAndSize (byte[] data) { // The lifetime of the data is controlled by C. It requires that i need to pass it // a malloc'ed array. IntPtr unmanagedData = Marshal.AllocHGlobal(data.Length); Marshal.Copy(data, 0, unmanagedData, data.Length); try { Error.CheckError (gp_file_set_data_and_size (this.Handle, unmanagedData, new IntPtr(data.Length))); } catch { // If there's a problem uploading the file, then // we need to be responsible for freeing the pointer Marshal.FreeHGlobal(unmanagedData); throw; } } public byte[] GetDataAndSize () { IntPtr size; byte[] data; IntPtr data_addr; Error.CheckError (gp_file_get_data_and_size (this.Handle, out data_addr, out size)); if(data_addr == IntPtr.Zero || size.ToInt32() == 0) return new byte[0]; data = new byte[size.ToInt32()]; Marshal.Copy(data_addr, data, 0, (int)size.ToInt32()); return data; } [DllImport ("libgphoto2.so")] private static extern ErrorCode gp_file_new (out IntPtr file); [DllImport ("libgphoto2.so")] private static extern ErrorCode gp_file_new_from_fd (out IntPtr file, int fd); [DllImport ("libgphoto2.so")] private static extern ErrorCode gp_file_unref (HandleRef file); [DllImport ("libgphoto2.so")] private static extern ErrorCode gp_file_append (HandleRef file, byte[] data, IntPtr size); [DllImport ("libgphoto2.so")] private static extern ErrorCode gp_file_open (HandleRef file, string filename); [DllImport ("libgphoto2.so")] private static extern ErrorCode gp_file_save (HandleRef file, string filename); [DllImport ("libgphoto2.so")] private static extern ErrorCode gp_file_clean (HandleRef file); [DllImport ("libgphoto2.so")] private static extern ErrorCode gp_file_get_name (HandleRef file, out string name); [DllImport ("libgphoto2.so")] private static extern ErrorCode gp_file_set_name (HandleRef file, string name); [DllImport ("libgphoto2.so")] private static extern ErrorCode gp_file_get_type (HandleRef file, out CameraFileType type); [DllImport ("libgphoto2.so")] private static extern ErrorCode gp_file_set_type (HandleRef file, CameraFileType type); [DllImport ("libgphoto2.so")] private static extern ErrorCode gp_file_get_mime_type (HandleRef file, out string mime_type); [DllImport ("libgphoto2.so")] private static extern ErrorCode gp_file_set_mime_type (HandleRef file, string mime_type); [DllImport ("libgphoto2.so")] private static extern ErrorCode gp_file_adjust_name_for_mime_type (HandleRef file); [DllImport ("libgphoto2.so")] private static extern ErrorCode gp_file_convert (HandleRef file, [MarshalAs(UnmanagedType.LPTStr)] string mime_type); [DllImport ("libgphoto2.so")] private static extern ErrorCode gp_file_copy (HandleRef destination, HandleRef source); /* TODO: Implement a wrapper for this [DllImport ("libgphoto2.so")] private static extern ErrorCode gp_file_set_color_table (HandleRef file, byte *red_table, int red_size, byte *green_table, int green_size, byte *blue_table, int blue_size); */ [DllImport ("libgphoto2.so")] private static extern ErrorCode gp_file_set_header (HandleRef file, [MarshalAs(UnmanagedType.LPTStr)] byte[] header); [DllImport ("libgphoto2.so")] private static extern ErrorCode gp_file_set_width_and_height (HandleRef file, int width, int height); [DllImport ("libgphoto2.so")] private static extern ErrorCode gp_file_set_data_and_size (HandleRef file, IntPtr data, IntPtr size); [DllImport ("libgphoto2.so")] private static extern ErrorCode gp_file_get_data_and_size (HandleRef file, out IntPtr data, out IntPtr size); } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IFluentQueryDialectCommand.cs" company=""> // // </copyright> // <summary> // The FluentQueryDialectCommand interface. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace FluentQuery.Core.Dialects.Base { using System.Collections.Generic; using Commands.Interfaces; using Commands.Model; using Infrastructure.Enums; /// <summary> /// The FluentQueryDialectCommand interface. /// </summary> public interface IFluentQueryDialectCommand { /// <summary> /// The create equal to. /// </summary> /// <param name="whereItem"> /// The where item. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> string CreateEqualTo(IFluentQueryWhereItemModel whereItem); /// <summary> /// The create not equal to. /// </summary> /// <param name="whereItem"> /// The where item. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> string CreateNotEqualTo(IFluentQueryWhereItemModel whereItem); /// <summary> /// The create greater than. /// </summary> /// <param name="whereItem"> /// The where item. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> string CreateGreaterThan(IFluentQueryWhereItemModel whereItem); /// <summary> /// The create greater or equal. /// </summary> /// <param name="whereItem"> /// The where item. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> string CreateGreaterOrEqual(IFluentQueryWhereItemModel whereItem); /// <summary> /// The create less than. /// </summary> /// <param name="whereItem"> /// The where item. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> string CreateLessThan(IFluentQueryWhereItemModel whereItem); /// <summary> /// The create less or equal. /// </summary> /// <param name="whereItem"> /// The where item. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> string CreateLessOrEqual(IFluentQueryWhereItemModel whereItem); /// <summary> /// The create null. /// </summary> /// <param name="whereItem"> /// The where item. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> string CreateNull(IFluentQueryWhereItemModel whereItem); /// <summary> /// The create not null. /// </summary> /// <param name="whereItem"> /// The where item. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> string CreateNotNull(IFluentQueryWhereItemModel whereItem); /// <summary> /// The create empty. /// </summary> /// <param name="whereItem"> /// The where item. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> string CreateEmpty(IFluentQueryWhereItemModel whereItem); /// <summary> /// The create not empty. /// </summary> /// <param name="whereItem"> /// The where item. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> string CreateNotEmpty(IFluentQueryWhereItemModel whereItem); /// <summary> /// The create between. /// </summary> /// <param name="whereItem"> /// The where item. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> string CreateBetween(IFluentQueryWhereItemModel whereItem); /// <summary> /// The create in. /// </summary> /// <param name="whereItem"> /// The where item. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> string CreateIn(IFluentQueryWhereItemModel whereItem); /// <summary> /// The create or. /// </summary> /// <param name="whereItem"> /// The where item. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> string CreateOr(IFluentQueryWhereItemModel whereItem); /// <summary> /// The create and. /// </summary> /// <param name="whereItem"> /// The where item. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> string CreateAnd(IFluentQueryWhereItemModel whereItem); /// <summary> /// The create raw. /// </summary> /// <param name="whereItem"> /// The where item. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> string CreateRaw(IFluentQueryWhereItemModel whereItem); /// <summary> /// The create like. /// </summary> /// <param name="whereItem"> /// The where item. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> string CreateLike(IFluentQueryWhereItemModel whereItem); /// <summary> /// The build column item in select. /// </summary> /// <param name="item"> /// The item. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> string BuildColumnItemInSelect(IFluentQuerySelectItem item); /// <summary> /// The build column item. /// </summary> /// <param name="item"> /// The item. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> string BuildColumnItem(IFluentQuerySelectItem item); /// <summary> /// The build from item. /// </summary> /// <param name="item"> /// The item. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> string BuildFromItem(IFluentQueryFromItemModel item); /// <summary> /// The build from join item. /// </summary> /// <param name="item"> /// The item. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> string BuildFromJoinItem(IFluentQueryFromItemModel item); /// <summary> /// The build column item in update. /// </summary> /// <param name="item"> /// The item. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> string BuildColumnItemInUpdate(IFluentQueryUpdateItemModel item); /// <summary> /// The create parameter. /// </summary> /// <param name="name"> /// The name. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> string CreateParameter(string name); /// <summary> /// The build insert column. /// </summary> /// <param name="item"> /// The item. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> string BuildInsertColumn(IFluentQuerySelectItem item); /// <summary> /// The build return id inserted row. /// </summary> /// <param name="item"> /// The item. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> string BuildReturnIdInsertedRow(IFluentQuerySelectItem item); /// <summary> /// The build order item. /// </summary> /// <param name="orderItem"> /// The order item. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> string BuildOrderItem(KeyValuePair<IFluentQuerySelectItem, FluentQuerySortDirection> orderItem); /// <summary> /// The build sort order. /// </summary> /// <param name="order"> /// The order. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> string BuildSortOrder(FluentQuerySortDirection order); /// <summary> /// The build paginate. /// </summary> /// <param name="limit"> /// The limit. /// </param> /// <param name="offset"> /// The offset. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> string BuildPaginate(long limit, long offset); /// <summary> /// The create paginate select field. /// </summary> /// <param name="idField"> /// The id field. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> string CreatePaginateSelectField(IFluentQuerySelectItem idField); /// <summary> /// The generate select query. /// </summary> /// <param name="queryModel"> /// The query model. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> string GenerateSelectQuery(FluentQuerySelectModel queryModel); } }
using System; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace VLispProfiler.Tests { [TestClass] public class ScannerTests { [DataTestMethod] [DataRow("")] [DataRow(" ")] [DataRow("\t\t")] [DataRow("\n\n\t \t\n")] public void TestEndOfFile(string input) { // Arrange var scanner = MakeScanner(input); // Act var tok = scanner.Scan(); // Assert Assert.AreEqual(Token.EndOfFile, tok); } [TestMethod] public void TestOperators() { // Arrange var scanner = MakeScanner("'.()"); // Act var tok1 = scanner.Scan(); var tok2 = scanner.Scan(); var tok3 = scanner.Scan(); var tok4 = scanner.Scan(); var tok5 = scanner.Scan(); // Assert Assert.AreEqual(Token.Quote, tok1); Assert.AreEqual(Token.Dot, tok2); Assert.AreEqual(Token.ParenLeft, tok3); Assert.AreEqual(Token.ParenRight, tok4); Assert.AreEqual(Token.EndOfFile, tok5); } [DataTestMethod] [DataRow(Token.Quote, " '")] [DataRow(Token.Quote, " '")] [DataRow(Token.Quote, " \n \n '")] [DataRow(Token.EndOfFile, " ")] public void TestWhitespace(Token token, string input) { // Arrange var scanner = MakeScanner(input); // Act var tok = scanner.Scan(); // Assert Assert.AreEqual(token, tok); } [DataTestMethod] [DataRow(";; Hello")] [DataRow(";| Hello |;")] [DataRow(";| Hello\n\n")] public void TestComments(string input) { // Arrange var scanner = MakeScanner(input); scanner.RescanComments = false; // Act scanner.Scan(); // Assert Assert.AreEqual(Token.Comment, scanner.CurrentToken); Assert.AreEqual(input, scanner.CurrentLiteral); } [DataTestMethod] [DataRow("\"Hello World\"", Token.String)] // "Hello World" [DataRow("\"\\\\\"", Token.String)] // "\\" [DataRow("\"Hello", Token.Illegal)] // "Hello [DataRow("\"", Token.Illegal)] // "\ [DataRow("3", Token.Int)] [DataRow("3.", Token.Real)] [DataRow("3..4", Token.Identifier)] [DataRow("1+", Token.Identifier)] [DataRow("-3", Token.Int)] [DataRow("+3.14", Token.Real)] [DataRow("++3", Token.Identifier)] public void TestLiterals(string input, Token token) { // Arrange var scanner = MakeScanner(input); // Act scanner.Scan(); // Assert Assert.AreEqual(token, scanner.CurrentToken); Assert.AreEqual(input, scanner.CurrentLiteral); } [DataTestMethod] [DataRow("+2147483647" /* int32_max */, Token.Int, DisplayName = "(type +2147483647) returns INT")] [DataRow("+2147483648" /* int32_max + 1 */, Token.Real, DisplayName = "(type +2147483648) returns REAL")] [DataRow("-2147483648" /* int32_min */, Token.Real, DisplayName = "(type -2147483648) returns REAL")] // i don't know why, does vlisp use one's complement? public void TestTokenIntLimits(string input, Token expected) { // Arrange var scanner = MakeScanner(input); // Act var tok = scanner.Scan(); // Assert Assert.AreEqual(expected, tok); } [TestMethod] public void TestProgram() { // Arrange var scanner = MakeScanner("(list 3 3.14 \"3.14\" 3..14)"); // Act + Assert scanner.Scan(); Assert.AreEqual(Token.ParenLeft, scanner.CurrentToken); scanner.Scan(); Assert.AreEqual(Token.Identifier, scanner.CurrentToken); Assert.AreEqual("list", scanner.CurrentLiteral); scanner.Scan(); Assert.AreEqual(Token.Int, scanner.CurrentToken); Assert.AreEqual("3", scanner.CurrentLiteral); scanner.Scan(); Assert.AreEqual(Token.Real, scanner.CurrentToken); Assert.AreEqual("3.14", scanner.CurrentLiteral); scanner.Scan(); Assert.AreEqual(Token.String, scanner.CurrentToken); Assert.AreEqual("\"3.14\"", scanner.CurrentLiteral); scanner.Scan(); Assert.AreEqual(Token.Identifier, scanner.CurrentToken); Assert.AreEqual("3..14", scanner.CurrentLiteral); scanner.Scan(); Assert.AreEqual(Token.ParenRight, scanner.CurrentToken); } [TestMethod] public void TestCurrentTokenStartPos() { // Arrange var scanner = MakeScanner("a b c d"); // Act + Assert scanner.Scan(); Assert.AreEqual(0, scanner.CurrentTokenStartPos); scanner.Scan(); Assert.AreEqual(4, scanner.CurrentTokenStartPos); scanner.Scan(); Assert.AreEqual(8, scanner.CurrentTokenStartPos); scanner.Scan(); Assert.AreEqual(10, scanner.CurrentTokenStartPos); } [DataTestMethod] [DataRow("a", 1, 1)] [DataRow("\na", 2, 1)] [DataRow("\n \n hello", 3, 4)] [DataRow("a\n\nb", 1, 1)] public void TestLineOffsets(string input, int expectedLine, int expectedColumn) { // Arrange var scanner = MakeScanner(input); // Act var tok = scanner.Scan(); var linePos = scanner.GetLinePosition(scanner.CurrentTokenStartPos); // Assert Assert.AreEqual(expectedLine, linePos.Line); Assert.AreEqual(expectedColumn, linePos.Column); } [TestMethod] public void TestLineOffsets2() { // Arrange var input = @"(setq i 3) (while (>= (setq i (1- i)) 0) (setq p1 (list 0 (* i 30)) p2 (list 200 (* i 30)) ) (command ""pline"" p1 p2 "") ) "; var scanner = MakeScanner(input); // Act var tok = scanner.Scan(); var linePos = scanner.GetLinePosition(scanner.CurrentTokenStartPos); // Assert Assert.AreEqual(1, linePos.Line); Assert.AreEqual(1, linePos.Column); } [DataTestMethod] [DataRow("10e0", Token.Real)] [DataRow("5e-1", Token.Real)] [DataRow("5.5e2", Token.Real)] [DataRow("-7e-2", Token.Real)] [DataRow("10.e2", Token.Real)] [DataRow("10e5.5", Token.Identifier)] public void TestEpsilon(string input, Token token) { // Arrange var scanner = MakeScanner(input); // Act var tok = scanner.Scan(); // Assert Assert.AreEqual(input, scanner.CurrentLiteral); Assert.AreEqual(token, tok); } [DataTestMethod] [DataRow("INPUT", 0, 2, "IN")] [DataRow("INPUT", 2, 5, "PUT")] public void TestGetSourceText(string input, int pos, int end, string test) { // Arrange var scanner = MakeScanner(input); // Act var sourceText = scanner.GetSourceText(pos, end); // Assert Assert.AreEqual(test, sourceText); } #region "Helpers" private Scanner MakeScanner(string sourceText) { return new Scanner(sourceText); } #endregion } }
/*************************************************************************************************************************************** * Copyright (C) 2001-2012 LearnLift USA * * Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, [email protected] * * * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License * * as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************************************************************************/ using System; using System.Collections.Generic; using System.Data; using System.Data.SqlServerCe; using System.IO; using System.Text; using MLifter.DAL.Interfaces; using MLifter.DAL.Interfaces.DB; using MLifter.DAL.Tools; namespace MLifter.DAL.DB.MsSqlCe { /// <summary> /// The MS SQL CE connector for the IDbMediaConnector interface. /// </summary> /// <remarks>Documented by Dev03, 2009-01-12</remarks> class MsSqlCeMediaConnector : IDbMediaConnector { private static Dictionary<ConnectionStringStruct, MsSqlCeMediaConnector> instances = new Dictionary<ConnectionStringStruct, MsSqlCeMediaConnector>(); /// <summary> /// Gets the instance. /// </summary> /// <param name="parentClass">The parent class.</param> /// <returns></returns> /// <remarks>Documented by Dev03, 2009-01-09</remarks> public static MsSqlCeMediaConnector GetInstance(ParentClass parentClass) { lock (instances) { ConnectionStringStruct connection = parentClass.CurrentUser.ConnectionString; if (!instances.ContainsKey(connection)) instances.Add(connection, new MsSqlCeMediaConnector(parentClass)); return instances[connection]; } } private ParentClass Parent; private MsSqlCeMediaConnector(ParentClass parentClass) { Parent = parentClass; Parent.DictionaryClosed += new EventHandler(Parent_DictionaryClosed); } void Parent_DictionaryClosed(object sender, EventArgs e) { IParent parent = sender as IParent; instances.Remove(parent.Parent.CurrentUser.ConnectionString); } /// <summary> /// Gets the byte array from stream. /// </summary> /// <param name="media">The media.</param> /// <param name="rpu">The rpu.</param> /// <param name="caller">The caller.</param> /// <returns></returns> /// <remarks>Documented by Dev05, 2009-01-16</remarks> private static byte[] GetByteArrayFromStream(System.IO.Stream media, MLifter.DAL.Tools.StatusMessageReportProgress rpu, object caller) { int buffer_length = 10240; byte[] data = new byte[media.Length]; StatusMessageEventArgs args = new StatusMessageEventArgs(StatusMessageType.CreateMediaProgress, (int)media.Length); media.Seek(0, SeekOrigin.Begin); int read = 0; int pos = 0; do { read = media.Read(data, pos, Math.Min(buffer_length, data.Length - pos)); pos += read; args.Progress = pos; if (rpu != null) rpu.Invoke(args, caller); } while (read == buffer_length); return data; } #region IDbMediaConnector Members /// <summary> /// Gets the media resources. /// </summary> /// <param name="id">The id.</param> /// <returns></returns> /// <remarks>Documented by Dev05, 2009-03-30</remarks> public List<int> GetMediaResources(int id) { List<int> ids = new List<int>(); SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser); cmd.CommandText = "SELECT id FROM MediaContent"; SqlCeDataReader reader = MSSQLCEConn.ExecuteReader(cmd); while (reader.Read()) ids.Add(Convert.ToInt32(reader["id"])); return ids; } /// <summary> /// Gets the empty media resources. /// </summary> /// <param name="id">The id.</param> /// <returns></returns> /// <remarks>Documented by Dev05, 2009-03-31</remarks> public List<int> GetEmptyMediaResources(int id) { List<int> ids = new List<int>(); SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser); cmd.CommandText = "SELECT id FROM MediaContent WHERE data IS NULL"; SqlCeDataReader reader = MSSQLCEConn.ExecuteReader(cmd); while (reader.Read()) ids.Add(Convert.ToInt32(reader["id"])); return ids; } /// <summary> /// Creates a new media object. /// </summary> /// <param name="media">The memory stream containing the media.</param> /// <param name="type">The media type.</param> /// <param name="rpu">A delegate of type <see cref="StatusMessageReportProgress"/> used to send messages back to the calling object.</param> /// <param name="caller">The calling object.</param> /// <returns>The id for the new media object.</returns> /// <remarks>Documented by Dev03, 2008-08-05</remarks> /// <remarks>Documented by Dev03, 2009-01-13</remarks> public int CreateMedia(System.IO.Stream media, MLifter.DAL.Interfaces.EMedia type, MLifter.DAL.Tools.StatusMessageReportProgress rpu, object caller) { int newId; SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser); cmd.CommandText = "INSERT INTO MediaContent (data, media_type) VALUES (@data, @type); SELECT @@IDENTITY;"; cmd.Parameters.Add("@data", SqlDbType.Image); cmd.Parameters.Add("@type", SqlDbType.NVarChar, 100); cmd.Parameters["@data"].Value = GetByteArrayFromStream(media, rpu, caller); cmd.Parameters["@type"].Value = type.ToString(); newId = Convert.ToInt32(MSSQLCEConn.ExecuteScalar(cmd)); return newId; } /// <summary> /// Gets the type of the media. /// </summary> /// <param name="id">The id.</param> /// <returns></returns> /// <remarks>Documented by Dev02, 2009-06-25</remarks> /// <remarks>Documented by Dev02, 2009-06-25</remarks> public EMedia GetMediaType(int id) { try { SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser); cmd.CommandText = "SELECT media_type FROM MediaContent WHERE id=@id"; cmd.Parameters.Add("@id", SqlDbType.Int, 4); cmd.Parameters["@id"].Value = id; return (EMedia)Enum.Parse(typeof(EMedia), Convert.ToString(MSSQLCEConn.ExecuteScalar(cmd))); } catch(ArgumentException) { return EMedia.Unknown; } } /// <summary> /// Updates the media. /// </summary> /// <param name="id">The id.</param> /// <param name="media">The media.</param> /// <remarks>Documented by Dev02, 2008-08-06</remarks> /// <remarks>Documented by Dev03, 2009-01-13</remarks> public void UpdateMedia(int id, System.IO.Stream media) { SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser); cmd.CommandText = "UPDATE MediaContent SET data=@data WHERE id=@id"; cmd.Parameters.Add("@data", SqlDbType.Image); cmd.Parameters.Add("@id", SqlDbType.Int, 4); cmd.Parameters["@data"].Value = GetByteArrayFromStream(media, null, null); cmd.Parameters["@id"].Value = id; MSSQLCEConn.ExecuteNonQuery(cmd); } /// <summary> /// Determines whether this media is available. /// </summary> /// <param name="id">The id.</param> /// <returns> /// <c>true</c> if media is available; otherwise, <c>false</c>. /// </returns> /// <remarks>Documented by Dev05, 2009-03-30</remarks> public bool IsMediaAvailable(int id) { SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser); cmd.CommandText = "SELECT count(*) FROM MediaContent WHERE id=@id AND data IS NOT NULL"; cmd.Parameters.Add("@id", id); return MSSQLCEConn.ExecuteScalar<int>(cmd).Value > 0; } /// <summary> /// Gets the media. /// </summary> /// <param name="id">The id.</param> /// <returns></returns> /// <remarks>Documented by Dev03, 2008-08-05</remarks> /// <remarks>Documented by Dev05, 2009-03-30</remarks> public Stream GetMediaStream(int id) { return GetMediaStream(id, null); } /// <summary> /// Gets the media. /// </summary> /// <param name="id">The id.</param> /// <param name="cacheConnector">The cache connector.</param> /// <returns>A memory stream for the media object.</returns> /// <remarks>Documented by Dev03, 2008-08-05</remarks> /// <remarks>Documented by Dev03, 2009-01-13</remarks> public System.IO.Stream GetMediaStream(int id, IDbMediaConnector cacheConnector) { MemoryStream stream = null; SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser); cmd.CommandText = "SELECT data FROM \"MediaContent\" WHERE id=@id;"; cmd.Parameters.Add("@id", id); byte[] media = (byte[])MSSQLCEConn.ExecuteScalar(cmd); if (media != null) { stream = new MemoryStream(media); stream.Seek(0, SeekOrigin.Begin); } return stream; } /// <summary> /// Deletes the media object. /// </summary> /// <param name="id">The id.</param> /// <remarks>Documented by Dev03, 2008-08-05</remarks> /// <remarks>Documented by Dev03, 2009-01-13</remarks> public void DeleteMedia(int id) { SqlCeCommand deletecmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser); deletecmd.CommandText = "DELETE FROM MediaProperties WHERE media_id=@id; DELETE FROM MediaContent WHERE id=@id;"; deletecmd.Parameters.Add("@id", id); MSSQLCEConn.ExecuteNonQuery(deletecmd); } /// <summary> /// Gets the properties for a media object. /// </summary> /// <param name="id">The id of the media object.</param> /// <returns>A list of properties.</returns> /// <remarks>Documented by Dev03, 2008-08-05</remarks> /// <remarks>Documented by Dev03, 2009-01-13</remarks> public Dictionary<MLifter.DAL.Interfaces.MediaProperty, string> GetProperties(int id) { Dictionary<MediaProperty, string> props = new Dictionary<MediaProperty, string>(); SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser); cmd.CommandText = "SELECT media_id, property, value FROM MediaProperties WHERE media_id=@id;"; cmd.Parameters.Add("@id", id); SqlCeDataReader reader = MSSQLCEConn.ExecuteReader(cmd); while (reader.Read()) try { props.Add((MediaProperty)Enum.Parse(typeof(MediaProperty), Convert.ToString(reader["property"]), true), Convert.ToString(reader["value"])); } catch (ArgumentException) //ignore argument exception (thrown in case the enum cannot be parsed). { } reader.Close(); return props; } /// <summary> /// Sets the properties for a media object. /// </summary> /// <param name="id">The id of the media object.</param> /// <param name="properties">The properties for the media object.</param> /// <remarks>Documented by Dev03, 2008-08-05</remarks> /// <remarks>Documented by Dev03, 2009-01-13</remarks> public void SetProperties(int id, Dictionary<MLifter.DAL.Interfaces.MediaProperty, string> properties) { SqlCeCommand cmd1 = MSSQLCEConn.CreateCommand(Parent.CurrentUser); SqlCeTransaction tran = cmd1.Connection.BeginTransaction(); cmd1.CommandText = "DELETE FROM MediaProperties WHERE media_id=@id;"; cmd1.Parameters.Add("@id", id); MSSQLCEConn.ExecuteNonQuery(cmd1); SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser); cmd.CommandText = "INSERT INTO MediaProperties (media_id, property, value) VALUES (@media_id, @property, @value);"; cmd.Parameters.Add("@media_id", SqlDbType.Int, 4); cmd.Parameters.Add("@property", SqlDbType.NVarChar, 100); cmd.Parameters.Add("@value", SqlDbType.NVarChar, 100); foreach (KeyValuePair<MediaProperty, string> item in properties) { cmd.Parameters["@media_id"].Value = id; cmd.Parameters["@property"].Value = item.Key.ToString(); cmd.Parameters["@value"].Value = item.Value; MSSQLCEConn.ExecuteNonQuery(cmd); } tran.Commit(); } /// <summary> /// Gets a single property value for a media object. /// </summary> /// <param name="id">The id.</param> /// <param name="property">The property.</param> /// <returns></returns> /// <remarks>Documented by Dev02, 2008-08-07</remarks> /// <remarks>Documented by Dev03, 2009-01-13</remarks> public string GetPropertyValue(int id, MLifter.DAL.Interfaces.MediaProperty property) { Dictionary<MediaProperty, string> properties = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.MediaProperties, id)] as Dictionary<MediaProperty, string>; if (properties != null && properties.ContainsKey(property)) return properties[property]; SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser); cmd.CommandText = "SELECT property, value FROM MediaProperties WHERE media_id=@id"; cmd.Parameters.Add("@id", id); SqlCeDataReader reader = MSSQLCEConn.ExecuteReader(cmd); properties = new Dictionary<MediaProperty, string>(); while (reader.Read()) properties[(MediaProperty)Enum.Parse(typeof(MediaProperty), reader["property"].ToString())] = reader["value"].ToString(); reader.Close(); Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.MediaProperties, id, new TimeSpan(1, 0, 0))] = properties; if (properties.ContainsKey(property)) return properties[property]; else return null; } /// <summary> /// Sets a single property value for a media object. /// </summary> /// <param name="id">The id.</param> /// <param name="property">The property.</param> /// <param name="value">The value.</param> /// <remarks>Documented by Dev02, 2008-08-07</remarks> /// <remarks>Documented by Dev03, 2009-01-13</remarks> public void SetPropertyValue(int id, MLifter.DAL.Interfaces.MediaProperty property, string value) { SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser); SqlCeTransaction tran = cmd.Connection.BeginTransaction(); if (GetPropertyValue(id, property) == null) cmd.CommandText = "INSERT INTO MediaProperties (media_id, property, value) VALUES (@media_id, @property, @value);"; else cmd.CommandText = "UPDATE MediaProperties SET value=@value WHERE media_id=@media_id AND property=@property;"; Dictionary<MediaProperty, string> properties = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.MediaProperties, id)] as Dictionary<MediaProperty, string>; if (properties == null) properties = new Dictionary<MediaProperty, string>(); properties[property] = value; Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.MediaProperties, id, new TimeSpan(1, 0, 0))] = properties; cmd.Parameters.Add("@media_id", id); cmd.Parameters.Add("@property", property.ToString()); cmd.Parameters.Add("@value", value); MSSQLCEConn.ExecuteNonQuery(cmd); tran.Commit(); } /// <summary> /// Checks if the media object exists. /// </summary> /// <param name="id">The id.</param> /// <remarks>Documented by Dev02, 2008-08-05</remarks> /// <remarks>Documented by Dev03, 2009-01-13</remarks> public void CheckMediaId(int id) { SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser); cmd.CommandText = "SELECT count(*) FROM MediaContent WHERE id=@id;"; cmd.Parameters.Add("@id", id); if (Convert.ToInt32(MSSQLCEConn.ExecuteScalar(cmd)) < 1) throw new IdAccessException(id); } #endregion } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// A tourist attraction. /// </summary> public class TouristAttraction_Core : TypeCore, IPlace { public TouristAttraction_Core() { this._TypeId = 268; this._Id = "TouristAttraction"; this._Schema_Org_Url = "http://schema.org/TouristAttraction"; string label = ""; GetLabel(out label, "TouristAttraction", typeof(TouristAttraction_Core)); this._Label = label; this._Ancestors = new int[]{266,206}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{206}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
#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 #if !(NET20 || NET35) using System.Collections.Generic; using System.Linq; using System.Text; using System; using System.Linq.Expressions; using System.Reflection; using Newtonsoft.Json.Serialization; namespace Newtonsoft.Json.Utilities { internal class ExpressionReflectionDelegateFactory : ReflectionDelegateFactory { private static readonly ExpressionReflectionDelegateFactory _instance = new ExpressionReflectionDelegateFactory(); internal static ReflectionDelegateFactory Instance => _instance; public override ObjectConstructor<object> CreateParameterizedConstructor(MethodBase method) { ValidationUtils.ArgumentNotNull(method, nameof(method)); Type type = typeof(object); ParameterExpression argsParameterExpression = Expression.Parameter(typeof(object[]), "args"); Expression callExpression = BuildMethodCall(method, type, null, argsParameterExpression); LambdaExpression lambdaExpression = Expression.Lambda(typeof(ObjectConstructor<object>), callExpression, argsParameterExpression); ObjectConstructor<object> compiled = (ObjectConstructor<object>)lambdaExpression.Compile(); return compiled; } public override MethodCall<T, object> CreateMethodCall<T>(MethodBase method) { ValidationUtils.ArgumentNotNull(method, nameof(method)); Type type = typeof(object); ParameterExpression targetParameterExpression = Expression.Parameter(type, "target"); ParameterExpression argsParameterExpression = Expression.Parameter(typeof(object[]), "args"); Expression callExpression = BuildMethodCall(method, type, targetParameterExpression, argsParameterExpression); LambdaExpression lambdaExpression = Expression.Lambda(typeof(MethodCall<T, object>), callExpression, targetParameterExpression, argsParameterExpression); MethodCall<T, object> compiled = (MethodCall<T, object>)lambdaExpression.Compile(); return compiled; } private class ByRefParameter { public Expression Value; public ParameterExpression Variable; public bool IsOut; } private Expression BuildMethodCall(MethodBase method, Type type, ParameterExpression targetParameterExpression, ParameterExpression argsParameterExpression) { ParameterInfo[] parametersInfo = method.GetParameters(); Expression[] argsExpression; IList<ByRefParameter> refParameterMap; if (parametersInfo.Length == 0) { argsExpression = CollectionUtils.ArrayEmpty<Expression>(); refParameterMap = CollectionUtils.ArrayEmpty<ByRefParameter>(); } else { argsExpression = new Expression[parametersInfo.Length]; refParameterMap = new List<ByRefParameter>(); for (int i = 0; i < parametersInfo.Length; i++) { ParameterInfo parameter = parametersInfo[i]; Type parameterType = parameter.ParameterType; bool isByRef = false; if (parameterType.IsByRef) { parameterType = parameterType.GetElementType(); isByRef = true; } Expression indexExpression = Expression.Constant(i); Expression paramAccessorExpression = Expression.ArrayIndex(argsParameterExpression, indexExpression); Expression argExpression = EnsureCastExpression(paramAccessorExpression, parameterType, !isByRef); if (isByRef) { ParameterExpression variable = Expression.Variable(parameterType); refParameterMap.Add(new ByRefParameter {Value = argExpression, Variable = variable, IsOut = parameter.IsOut}); argExpression = variable; } argsExpression[i] = argExpression; } } Expression callExpression; if (method.IsConstructor) { callExpression = Expression.New((ConstructorInfo)method, argsExpression); } else if (method.IsStatic) { callExpression = Expression.Call((MethodInfo)method, argsExpression); } else { Expression readParameter = EnsureCastExpression(targetParameterExpression, method.DeclaringType); callExpression = Expression.Call(readParameter, (MethodInfo)method, argsExpression); } MethodInfo m = method as MethodInfo; if (m != null) { if (m.ReturnType != typeof(void)) { callExpression = EnsureCastExpression(callExpression, type); } else { callExpression = Expression.Block(callExpression, Expression.Constant(null)); } } else { callExpression = EnsureCastExpression(callExpression, type); } if (refParameterMap.Count > 0) { IList<ParameterExpression> variableExpressions = new List<ParameterExpression>(); IList<Expression> bodyExpressions = new List<Expression>(); foreach (ByRefParameter p in refParameterMap) { if (!p.IsOut) { bodyExpressions.Add(Expression.Assign(p.Variable, p.Value)); } variableExpressions.Add(p.Variable); } bodyExpressions.Add(callExpression); callExpression = Expression.Block(variableExpressions, bodyExpressions); } return callExpression; } public override Func<T> CreateDefaultConstructor<T>(Type type) { ValidationUtils.ArgumentNotNull(type, "type"); // avoid error from expressions compiler because of abstract class if (type.IsAbstract()) { return () => (T)Activator.CreateInstance(type); } try { Type resultType = typeof(T); Expression expression = Expression.New(type); expression = EnsureCastExpression(expression, resultType); LambdaExpression lambdaExpression = Expression.Lambda(typeof(Func<T>), expression); Func<T> compiled = (Func<T>)lambdaExpression.Compile(); return compiled; } catch { // an error can be thrown if constructor is not valid on Win8 // will have INVOCATION_FLAGS_NON_W8P_FX_API invocation flag return () => (T)Activator.CreateInstance(type); } } public override Func<T, object> CreateGet<T>(PropertyInfo propertyInfo) { ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); Type instanceType = typeof(T); Type resultType = typeof(object); ParameterExpression parameterExpression = Expression.Parameter(instanceType, "instance"); Expression resultExpression; MethodInfo getMethod = propertyInfo.GetGetMethod(true); if (getMethod.IsStatic) { resultExpression = Expression.MakeMemberAccess(null, propertyInfo); } else { Expression readParameter = EnsureCastExpression(parameterExpression, propertyInfo.DeclaringType); resultExpression = Expression.MakeMemberAccess(readParameter, propertyInfo); } resultExpression = EnsureCastExpression(resultExpression, resultType); LambdaExpression lambdaExpression = Expression.Lambda(typeof(Func<T, object>), resultExpression, parameterExpression); Func<T, object> compiled = (Func<T, object>)lambdaExpression.Compile(); return compiled; } public override Func<T, object> CreateGet<T>(FieldInfo fieldInfo) { ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo)); ParameterExpression sourceParameter = Expression.Parameter(typeof(T), "source"); Expression fieldExpression; if (fieldInfo.IsStatic) { fieldExpression = Expression.Field(null, fieldInfo); } else { Expression sourceExpression = EnsureCastExpression(sourceParameter, fieldInfo.DeclaringType); fieldExpression = Expression.Field(sourceExpression, fieldInfo); } fieldExpression = EnsureCastExpression(fieldExpression, typeof(object)); Func<T, object> compiled = Expression.Lambda<Func<T, object>>(fieldExpression, sourceParameter).Compile(); return compiled; } public override Action<T, object> CreateSet<T>(FieldInfo fieldInfo) { ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo)); // use reflection for structs // expression doesn't correctly set value if (fieldInfo.DeclaringType.IsValueType() || fieldInfo.IsInitOnly) { return LateBoundReflectionDelegateFactory.Instance.CreateSet<T>(fieldInfo); } ParameterExpression sourceParameterExpression = Expression.Parameter(typeof(T), "source"); ParameterExpression valueParameterExpression = Expression.Parameter(typeof(object), "value"); Expression fieldExpression; if (fieldInfo.IsStatic) { fieldExpression = Expression.Field(null, fieldInfo); } else { Expression sourceExpression = EnsureCastExpression(sourceParameterExpression, fieldInfo.DeclaringType); fieldExpression = Expression.Field(sourceExpression, fieldInfo); } Expression valueExpression = EnsureCastExpression(valueParameterExpression, fieldExpression.Type); BinaryExpression assignExpression = Expression.Assign(fieldExpression, valueExpression); LambdaExpression lambdaExpression = Expression.Lambda(typeof(Action<T, object>), assignExpression, sourceParameterExpression, valueParameterExpression); Action<T, object> compiled = (Action<T, object>)lambdaExpression.Compile(); return compiled; } public override Action<T, object> CreateSet<T>(PropertyInfo propertyInfo) { ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); // use reflection for structs // expression doesn't correctly set value if (propertyInfo.DeclaringType.IsValueType()) { return LateBoundReflectionDelegateFactory.Instance.CreateSet<T>(propertyInfo); } Type instanceType = typeof(T); Type valueType = typeof(object); ParameterExpression instanceParameter = Expression.Parameter(instanceType, "instance"); ParameterExpression valueParameter = Expression.Parameter(valueType, "value"); Expression readValueParameter = EnsureCastExpression(valueParameter, propertyInfo.PropertyType); MethodInfo setMethod = propertyInfo.GetSetMethod(true); Expression setExpression; if (setMethod.IsStatic) { setExpression = Expression.Call(setMethod, readValueParameter); } else { Expression readInstanceParameter = EnsureCastExpression(instanceParameter, propertyInfo.DeclaringType); setExpression = Expression.Call(readInstanceParameter, setMethod, readValueParameter); } LambdaExpression lambdaExpression = Expression.Lambda(typeof(Action<T, object>), setExpression, instanceParameter, valueParameter); Action<T, object> compiled = (Action<T, object>)lambdaExpression.Compile(); return compiled; } private Expression EnsureCastExpression(Expression expression, Type targetType, bool allowWidening = false) { Type expressionType = expression.Type; // check if a cast or conversion is required if (expressionType == targetType || (!expressionType.IsValueType() && targetType.IsAssignableFrom(expressionType))) { return expression; } if (targetType.IsValueType()) { Expression convert = Expression.Unbox(expression, targetType); if (allowWidening && targetType.IsPrimitive()) { MethodInfo toTargetTypeMethod = typeof(Convert) .GetMethod("To" + targetType.Name, new[] { typeof(object) }); if (toTargetTypeMethod != null) { convert = Expression.Condition( Expression.TypeIs(expression, targetType), convert, Expression.Call(toTargetTypeMethod, expression)); } } return Expression.Condition( Expression.Equal(expression, Expression.Constant(null, typeof(object))), Expression.Default(targetType), convert); } return Expression.Convert(expression, targetType); } } } #endif
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Web; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.IO; using System.Collections.Generic; namespace Epi.Windows.Globalization.Translators { /// <summary> /// Translate text items using the BableFish web service /// </summary> public class WebServiceTranslator : NormalizedStringTranslator { //Dictionary<string, string> translationTable = new Dictionary<string, string>(ds.CulturalResources.Rows.Count); Dictionary<string, string> translationTable = new Dictionary<string, string>(3000); /// <summary> /// Translate string from source culture to target culture /// </summary> /// <param name="sourceCultureName"></param> /// <param name="targetCultureName"></param> /// <param name="sourceText"></param> /// <returns></returns> public override string Translate(string sourceCultureName, string targetCultureName, string sourceText) { string normalizedText = base.Translate(sourceCultureName, targetCultureName, sourceText); string translatedText; // cache translated strings, weak implementation if (translationTable.ContainsKey(normalizedText)) { translatedText = translationTable[normalizedText]; } else { translatedText = TranslateResourceText(sourceCultureName, targetCultureName, sourceText, normalizedText); translationTable.Add(normalizedText, translatedText); } return translatedText; } string TranslateResourceText(string sourceCultureName, string targetCultureName, string resourceValue, string resourceText) { string translatedString = BabelFish(sourceCultureName, targetCultureName, resourceText); return translatedString; } static readonly string[] VALIDTRANSLATIONMODES = new string[] { "zh_en", "zt_en", "en_zh", "en_zt", "en_nl", "en_fr", "en_de", "en_el", "en_it", "en_ja", "en_ko", "en_pt", "en_ru", "en_es", "nl_en", "nl_fr", "fr_nl", "fr_en", "fr_de", "fr_el", "fr_it", "fr_pt", "fr_es", "de_en", "de_fr", "el_en", "el_fr", "it_en", "it_fr", "ja_en", "ko_en", "pt_en", "pt_fr", "ru_en", "es_en", "es_fr" }; const string BABELFISHURL = "http://babelfish.altavista.com/babelfish/tr"; const string BABELFISHREFERER = "http://babelfish.altavista.com/"; const string ERRORSTRINGSTART = "<font color=red>"; const string ERRORSTRINGEND = "</font>"; /// <summary> /// GetSupportedTargetLanguages() method /// </summary> /// <param name="sourceCultureName"></param> /// <returns></returns> public static List<string> GetSupportedTargetLanguages(string sourceCultureName) { List<string> result = new List<string>(); string sourceLanguage; int seperatorPosition = sourceCultureName.IndexOf('-'); if (seperatorPosition > -1) sourceLanguage = sourceCultureName.Substring(0, seperatorPosition); else sourceLanguage = sourceCultureName; foreach (string language in VALIDTRANSLATIONMODES) { if (language.StartsWith(sourceLanguage)) { result.Add(language.Substring(3, 2)); } } return result; } /// <summary> /// Translate using AltaVista's BabelFish Translation service /// </summary> /// <param name="sourceCultureName"></param> /// <param name="targetCultureName"></param> /// <param name="sourcedata"></param> /// <returns></returns> public static string BabelFish(string sourceCultureName, string targetCultureName, string sourcedata) { string translation; try { // validate and remove trailing spaces if (string.IsNullOrEmpty(sourceCultureName)) throw new ArgumentNullException("sourceCultureName"); if (string.IsNullOrEmpty(targetCultureName)) throw new ArgumentNullException("targetCultureName"); if (string.IsNullOrEmpty(sourcedata)) throw new ArgumentNullException("sourcedata"); int hyphenPosition; hyphenPosition = targetCultureName.IndexOf('-'); if (hyphenPosition > -1) { targetCultureName = targetCultureName.Substring(0, hyphenPosition); } hyphenPosition = sourceCultureName.IndexOf('-'); if (hyphenPosition > -1) { sourceCultureName = sourceCultureName.Substring(0, hyphenPosition); } string translationmode = sourceCultureName + "_" + targetCultureName; Uri uri = new Uri(BABELFISHURL); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.Referer = BABELFISHREFERER; // Encode all the sourcedata string postsourcedata; postsourcedata = "lp=" + translationmode + "&tt=urltext&intl=1&doit=done&urltext=" + System.Web.HttpUtility.UrlEncode(sourcedata); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = postsourcedata.Length; request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"; // new code request.KeepAlive = false; request.ProtocolVersion = HttpVersion.Version10; //request.Proxy = System.Net.WebProxy.GetDefaultProxy(); request.AllowAutoRedirect = true; request.MaximumAutomaticRedirections = 10; request.Timeout = (int)new TimeSpan(0, 0, 300).TotalMilliseconds; request.ServicePoint.ConnectionLimit = 25; using (Stream writeStream = request.GetRequestStream()) { UTF8Encoding encoding = new UTF8Encoding(); byte[] bytes = encoding.GetBytes(postsourcedata); writeStream.Write(bytes, 0, bytes.Length); writeStream.Close(); } StringBuilder pageBuilder = new StringBuilder(); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8); bool record = false; while (true) { string nextline = readStream.ReadLine(); if (nextline == null) break; if (nextline.Contains("form ") && nextline.Contains("http://www.altavista.com/web/results")) record = true; if (record) pageBuilder.AppendLine(nextline); if (nextline.Contains("</html>")) break; } } } Regex reg = new Regex(@"<div style=padding:10px;>((?:.|\n)*?)</div>", RegexOptions.IgnoreCase); MatchCollection matches = reg.Matches(pageBuilder.ToString()); if (matches.Count != 1 || matches[0].Groups.Count != 2) { translation = sourcedata.ToUpperInvariant(); } else { translation = matches[0].Groups[1].Value; } translation.Replace("\n", ""); translation.Replace("\r", ""); } catch (WebException wex) { System.Diagnostics.Debug.WriteLine(wex.Message); translation = sourcedata; } return translation; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Web; using System.Reflection; using Umbraco.Core; using Umbraco.Core.Logging; using umbraco.BasePages; using umbraco.BusinessLogic.Utils; using umbraco.cms; using umbraco.cms.businesslogic.web; using umbraco.cms.businesslogic.workflow; using umbraco.interfaces; using System.Text.RegularExpressions; using System.Linq; using Umbraco.Core.IO; using TypeFinder = Umbraco.Core.TypeFinder; namespace umbraco.BusinessLogic.Actions { /// <summary> /// Actions and Actionhandlers are a key concept to umbraco and a developer whom wish to apply /// businessrules whenever data is changed within umbraco, by implementing the IActionHandler /// interface it's possible to invoke methods (foreign to umbraco) - this can be used whenever /// there is a specific rule which needs to be applied to content. /// /// The Action class itself has responsibility for registering actions and actionhandlers, /// and contains methods which will be invoked whenever a change is made to ex. a document, media or member /// /// An action/actionhandler will automatically be registered, using reflection /// which is enabling thirdparty developers to extend the core functionality of /// umbraco without changing the codebase. /// </summary> [Obsolete("Actions and ActionHandlers are obsolete and should no longer be used")] public class Action { private static readonly Dictionary<string, string> ActionJs = new Dictionary<string, string>(); private static readonly object Lock = new object(); static Action() { ReRegisterActionsAndHandlers(); } /// <summary> /// This is used when an IAction or IActionHandler is installed into the system /// and needs to be loaded into memory. /// </summary> /// <remarks> /// TODO: this shouldn't be needed... we should restart the app pool when a package is installed! /// </remarks> public static void ReRegisterActionsAndHandlers() { lock (Lock) { // NOTE use the DirtyBackdoor to change the resolution configuration EXCLUSIVELY // ie do NOT do ANYTHING else while holding the backdoor, because while it is open // the whole resolution system is locked => nothing can work properly => deadlocks var newResolver = new ActionsResolver( new ActivatorServiceProvider(), LoggerResolver.Current.Logger, () => TypeFinder.FindClassesOfType<IAction>(PluginManager.Current.AssembliesToScan)); using (Umbraco.Core.ObjectResolution.Resolution.DirtyBackdoorToConfiguration) { ActionsResolver.Reset(false); // and do NOT reset the whole resolution! ActionsResolver.Current = newResolver; } } } /// <summary> /// Jacascript for the contextmenu /// Suggestion: this method should be moved to the presentation layer. /// </summary> /// <param name="language"></param> /// <returns>String representation</returns> public string ReturnJavascript(string language) { return findActions(language); } /// <summary> /// Returns a list of JavaScript file paths. /// </summary> /// <returns></returns> public static List<string> GetJavaScriptFileReferences() { return ActionsResolver.Current.Actions .Where(x => !string.IsNullOrWhiteSpace(x.JsSource)) .Select(x => x.JsSource).ToList(); //return ActionJsReference; } /// <summary> /// Javascript menuitems - tree contextmenu /// Umbraco console /// /// Suggestion: this method should be moved to the presentation layer. /// </summary> /// <param name="language"></param> /// <returns></returns> private static string findActions(string language) { if (!ActionJs.ContainsKey(language)) { string _actionJsList = ""; foreach (IAction action in ActionsResolver.Current.Actions) { // Adding try/catch so this rutine doesn't fail if one of the actions fail // Add to language JsList try { // NH: Add support for css sprites string icon = action.Icon; if (!string.IsNullOrEmpty(icon) && icon.StartsWith(".")) icon = icon.Substring(1, icon.Length - 1); else icon = "images/" + icon; _actionJsList += string.Format(",\n\tmenuItem(\"{0}\", \"{1}\", \"{2}\", \"{3}\")", action.Letter, icon, ui.GetText("actions", action.Alias, language), action.JsFunctionName); } catch (Exception ee) { LogHelper.Error<Action>("Error registrering action to javascript", ee); } } if (_actionJsList.Length > 0) _actionJsList = _actionJsList.Substring(2, _actionJsList.Length - 2); _actionJsList = "\nvar menuMethods = new Array(\n" + _actionJsList + "\n)\n"; ActionJs.Add(language, _actionJsList); } return ActionJs[language]; } /// <summary> /// /// </summary> /// <returns>An arraylist containing all javascript variables for the contextmenu in the tree</returns> [Obsolete("Use ActionsResolver.Current.Actions instead")] public static ArrayList GetAll() { return new ArrayList(ActionsResolver.Current.Actions.ToList()); } /// <summary> /// This method will return a list of IAction's based on a string list. Each character in the list may represent /// an IAction. This will associate any found IActions based on the Letter property of the IAction with the character being referenced. /// </summary> /// <param name="actions"></param> /// <returns>returns a list of actions that have an associated letter found in the action string list</returns> public static List<IAction> FromString(string actions) { List<IAction> list = new List<IAction>(); foreach (char c in actions.ToCharArray()) { IAction action = ActionsResolver.Current.Actions.ToList().Find( delegate(IAction a) { return a.Letter == c; } ); if (action != null) list.Add(action); } return list; } /// <summary> /// Returns the string representation of the actions that make up the actions collection /// </summary> /// <returns></returns> public static string ToString(List<IAction> actions) { string[] strMenu = Array.ConvertAll<IAction, string>(actions.ToArray(), delegate(IAction a) { return (a.Letter.ToString()); }); return string.Join("", strMenu); } /// <summary> /// Returns a list of IActions that are permission assignable /// </summary> /// <returns></returns> public static List<IAction> GetPermissionAssignable() { return ActionsResolver.Current.Actions.ToList().FindAll( delegate(IAction a) { return (a.CanBePermissionAssigned); } ); } /// <summary> /// Check if the current IAction is using legacy javascript methods /// </summary> /// <param name="action"></param> /// <returns>false if the Iaction is incompatible with 4.5</returns> public static bool ValidateActionJs(IAction action) { return !action.JsFunctionName.Contains("+"); } /// <summary> /// Method to convert the old modal calls to the new ones /// </summary> /// <param name="javascript"></param> /// <returns></returns> public static string ConvertLegacyJs(string javascript) { MatchCollection tags = Regex.Matches(javascript, "openModal[^;]*;", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); foreach (Match tag in tags) { string[] function = tag.Value.Split(','); if (function.Length > 0) { string newFunction = "UmbClientMgr.openModalWindow" + function[0].Substring(9).Replace("parent.nodeID", "UmbClientMgr.mainTree().getActionNode().nodeId").Replace("nodeID", "UmbClientMgr.mainTree().getActionNode().nodeId").Replace("parent.returnRandom()", "'" + Guid.NewGuid().ToString() + "'"); newFunction += ", " + function[1]; newFunction += ", true"; newFunction += ", " + function[2]; newFunction += ", " + function[3]; javascript = javascript.Replace(tag.Value, newFunction); } } return javascript; } } /// <summary> /// This class is used to manipulate IActions that are implemented in a wrong way /// For instance incompatible trees with 4.0 vs 4.5 /// </summary> public class PlaceboAction : IAction { public char Letter { get; set; } public bool ShowInNotifier { get; set; } public bool CanBePermissionAssigned { get; set; } public string Icon { get; set; } public string Alias { get; set; } public string JsFunctionName { get; set; } public string JsSource { get; set; } public PlaceboAction() { } public PlaceboAction(IAction legacyAction) { Letter = legacyAction.Letter; ShowInNotifier = legacyAction.ShowInNotifier; CanBePermissionAssigned = legacyAction.CanBePermissionAssigned; Icon = legacyAction.Icon; Alias = legacyAction.Alias; JsFunctionName = legacyAction.JsFunctionName; JsSource = legacyAction.JsSource; } } }
// 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.2.2.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DataLake.Analytics { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.DataLake; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// PipelineOperations operations. /// </summary> internal partial class PipelineOperations : IServiceOperations<DataLakeAnalyticsJobManagementClient>, IPipelineOperations { /// <summary> /// Initializes a new instance of the PipelineOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal PipelineOperations(DataLakeAnalyticsJobManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the DataLakeAnalyticsJobManagementClient /// </summary> public DataLakeAnalyticsJobManagementClient Client { get; private set; } /// <summary> /// Lists all pipelines. /// </summary> /// <param name='accountName'> /// The Azure Data Lake Analytics account to execute job operations on. /// </param> /// <param name='startDateTime'> /// The start date for when to get the list of pipelines. The startDateTime and /// endDateTime can be no more than 30 days apart. /// </param> /// <param name='endDateTime'> /// The end date for when to get the list of pipelines. The startDateTime and /// endDateTime can be no more than 30 days apart. /// </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<JobPipelineInformation>>> ListWithHttpMessagesAsync(string accountName, System.DateTimeOffset? startDateTime = default(System.DateTimeOffset?), System.DateTimeOffset? endDateTime = default(System.DateTimeOffset?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (Client.AdlaJobDnsSuffix == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.AdlaJobDnsSuffix"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("accountName", accountName); tracingParameters.Add("startDateTime", startDateTime); tracingParameters.Add("endDateTime", endDateTime); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri; var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "pipelines"; _url = _url.Replace("{accountName}", accountName); _url = _url.Replace("{adlaJobDnsSuffix}", Client.AdlaJobDnsSuffix); List<string> _queryParameters = new List<string>(); if (startDateTime != null) { _queryParameters.Add(string.Format("startDateTime={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(startDateTime, Client.SerializationSettings).Trim('"')))); } if (endDateTime != null) { _queryParameters.Add(string.Format("endDateTime={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(endDateTime, Client.SerializationSettings).Trim('"')))); } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new 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<JobPipelineInformation>>(); _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<JobPipelineInformation>>(_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 the Pipeline information for the specified pipeline ID. /// </summary> /// <param name='accountName'> /// The Azure Data Lake Analytics account to execute job operations on. /// </param> /// <param name='pipelineIdentity'> /// Pipeline ID. /// </param> /// <param name='startDateTime'> /// The start date for when to get the pipeline and aggregate its data. The /// startDateTime and endDateTime can be no more than 30 days apart. /// </param> /// <param name='endDateTime'> /// The end date for when to get the pipeline and aggregate its data. The /// startDateTime and endDateTime can be no more than 30 days apart. /// </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<JobPipelineInformation>> GetWithHttpMessagesAsync(string accountName, System.Guid pipelineIdentity, System.DateTimeOffset? startDateTime = default(System.DateTimeOffset?), System.DateTimeOffset? endDateTime = default(System.DateTimeOffset?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (Client.AdlaJobDnsSuffix == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.AdlaJobDnsSuffix"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("accountName", accountName); tracingParameters.Add("pipelineIdentity", pipelineIdentity); tracingParameters.Add("startDateTime", startDateTime); tracingParameters.Add("endDateTime", endDateTime); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri; var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "pipelines/{pipelineIdentity}"; _url = _url.Replace("{accountName}", accountName); _url = _url.Replace("{adlaJobDnsSuffix}", Client.AdlaJobDnsSuffix); _url = _url.Replace("{pipelineIdentity}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(pipelineIdentity, Client.SerializationSettings).Trim('"'))); List<string> _queryParameters = new List<string>(); if (startDateTime != null) { _queryParameters.Add(string.Format("startDateTime={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(startDateTime, Client.SerializationSettings).Trim('"')))); } if (endDateTime != null) { _queryParameters.Add(string.Format("endDateTime={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(endDateTime, Client.SerializationSettings).Trim('"')))); } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new 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<JobPipelineInformation>(); _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<JobPipelineInformation>(_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> /// Lists all pipelines. /// </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<JobPipelineInformation>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = 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<JobPipelineInformation>>(); _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<JobPipelineInformation>>(_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.Generic; using System.Collections.ObjectModel; 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 AllHttpMethods.Areas.HelpPage.ModelDescriptions; using AllHttpMethods.Areas.HelpPage.Models; namespace AllHttpMethods.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; } if (complexTypeDescription != null) { 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 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); } } } }
using UnityEngine; using System.Collections; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Xml; using System.IO; using ProtoBuf; using update_protocol_v3; namespace AssemblyCSharp { public class MasterStream : MonoBehaviour { private class OtherMarker { public Vector3 pos; } private class LiveObjectStorage { public Vector3 pos; public Quaternion rot; public int button_bits; public List<Vector2> axis_buttons; // TODO: Handle extra data } private const int BLACK_BOX_CLIENT_PORT = 1611; private Vector3 DEFAULT_POS_VEC; private Quaternion DEFAULT_ROT_QUAT; private int nBytesReceived; private bool stopReceive; private IPEndPoint ipEndPoint; private System.Threading.Thread thread = null; private Socket socket; private byte[] b1; private byte[] b2; private byte[] b3; private MemoryStream b1ms; private MemoryStream b2ms; private float accum; private int nPackets; private int nFrames; private UnityEngine.Object lock_object; private long lastLoadedFrame; private byte[] lastLoadedBuffer; private MemoryStream lastLoadedBufferMS; private Dictionary<string, LiveObjectStorage> labelToLiveObject; public void Start() { lock_object = new UnityEngine.Object(); Application.runInBackground = true; Application.targetFrameRate = -1; DEFAULT_POS_VEC = new Vector3 (0, 0, 0); DEFAULT_ROT_QUAT = new Quaternion (0, 0, 0, 0); labelToLiveObject = new Dictionary<string, LiveObjectStorage>(); accum = 0; nPackets = 0; nFrames = 0; // ~65KB buffer sizes b1 = new byte[65507]; b2 = new byte[65507]; b1ms = new MemoryStream(b1); b2ms = new MemoryStream(b2); thread = new System.Threading.Thread(ThreadRun); thread.Start(); } // Handle new thread data / invoke Unity routines outside of the socket thread. public void Update() { accum += Time.deltaTime; float round_accum = (float)Math.Floor(accum); if (round_accum > 0) { accum -= round_accum; // print ("FPS: " + ((float)nFrames / round_accum).ToString()); print ("packets per second: " + ((float)nPackets / round_accum).ToString()); nPackets = 0; nFrames = 0; } nFrames++; } public Vector3 getLiveObjectPosition(string name) { LiveObjectStorage o; lock (lock_object) { if (!labelToLiveObject.TryGetValue (name, out o)) { //print ("Body not found: " + name); return DEFAULT_POS_VEC; } } return o.pos; } public Quaternion getLiveObjectRotation(string name) { LiveObjectStorage o; lock (lock_object) { if (!labelToLiveObject.TryGetValue (name, out o)) { //print ("Body not found: " + name); return DEFAULT_ROT_QUAT; } } return o.rot; } public int getLiveObjectButtonBits(string name) { LiveObjectStorage o; lock (lock_object) { if (!labelToLiveObject.TryGetValue (name, out o)) { //print ("Body not found: " + name); return 0; } } return o.button_bits; } public Vector2 getLiveObjectAxisButton(string name, int index) { LiveObjectStorage o; lock (lock_object) { if (!labelToLiveObject.TryGetValue (name, out o)) { //print ("Body not found: " + name); return Vector2.zero; } } return o.axis_buttons[index]; } // This thread handles incoming NatNet packets. private void ThreadRun () { stopReceive = false; Socket socket =new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); ipEndPoint = new IPEndPoint (IPAddress.Any, BLACK_BOX_CLIENT_PORT); //Debug.Log("prebind"); socket.Bind (ipEndPoint); //Debug.Log("bind"); MulticastOption mo = new MulticastOption (IPAddress.Parse ("224.1.1.1")); socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.AddMembership, mo); nBytesReceived = 0; lastLoadedBuffer = b1; lastLoadedBufferMS = b1ms; lastLoadedFrame = 0; byte[] newPacketBuffer = b2; MemoryStream newPacketBufferMS = b2ms; long newPacketFrame = 0; byte[] tempBuffer; MemoryStream tempBufferMS; while (true) { //Debug.Log("preRECV"); nBytesReceived = socket.Receive(newPacketBuffer); //Debug.Log("RECV"); nPackets++; newPacketBufferMS.Position = 0; //Debug.Log ("Deserializing data..."); update_protocol_v3.Update update = Serializer.Deserialize<update_protocol_v3.Update>(new MemoryStream(newPacketBuffer, 0, nBytesReceived)); //Debug.Log ("Data deserialized. Received update of type " + update.label); newPacketFrame = update.mod_version; if(newPacketFrame > lastLoadedFrame) { // Swap the buffers and reset the positions. lastLoadedBufferMS.Position = 0; newPacketBufferMS.Position = 0; tempBuffer = lastLoadedBuffer; tempBufferMS = lastLoadedBufferMS; lastLoadedBuffer = newPacketBuffer; lastLoadedBufferMS = newPacketBufferMS; newPacketBuffer = tempBuffer; newPacketBufferMS = tempBufferMS; lastLoadedFrame = newPacketFrame; for (int j = 0; j < update.live_objects.Count; j++) { LiveObject or = update.live_objects[j]; string label = or.label; if (label == "marker") { Debug.Log ("marker at " + or.x + ", " + or.y + ", " + or.z); } LiveObjectStorage ow; lock (lock_object) { if (!labelToLiveObject.TryGetValue(label, out ow)) { ow = new LiveObjectStorage(); labelToLiveObject[label] = ow; } else { ow = labelToLiveObject[label]; } if (update.lhs_frame) { ow.pos = new Vector3(-(float)or.x, (float)or.y, (float)or.z); ow.rot = new Quaternion(-(float)or.qx, (float)or.qy, (float)or.qz, -(float)or.qw); } else { ow.pos = new Vector3((float)or.x, (float)or.y, (float)or.z); ow.rot = new Quaternion((float)or.qx, (float)or.qy, (float)or.qz, (float)or.qw); } ow.button_bits = or.button_bits; } } } if (stopReceive) { break; } } } private void OnDestroy () { stopReceive = true; } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Web; using AppLimit.CloudComputing.SharpBox; using AppLimit.CloudComputing.SharpBox.Exceptions; using AppLimit.CloudComputing.SharpBox.StorageProvider; using ASC.Common.Web; using ASC.Core; using ASC.Files.Core; using ASC.Web.Files.Classes; namespace ASC.Files.Thirdparty.Sharpbox { public class SharpBoxProviderInfo : IProviderInfo, IDisposable { public int ID { get; set; } public Guid Owner { get; private set; } private readonly nSupportedCloudConfigurations _providerKey; private readonly AuthData _authData; private readonly FolderType _rootFolderType; private readonly DateTime _createOn; public SharpBoxProviderInfo(int id, string providerKey, string customerTitle, AuthData authData, Guid owner, FolderType rootFolderType, DateTime createOn) { if (string.IsNullOrEmpty(providerKey)) throw new ArgumentNullException("providerKey"); if (string.IsNullOrEmpty(authData.Token) && string.IsNullOrEmpty(authData.Password)) throw new ArgumentNullException("token", "Both token and password can't be null"); if (!string.IsNullOrEmpty(authData.Login) && string.IsNullOrEmpty(authData.Password) && string.IsNullOrEmpty(authData.Token)) throw new ArgumentNullException("password", "Password can't be null"); ID = id; CustomerTitle = customerTitle; Owner = owner == Guid.Empty ? SecurityContext.CurrentAccount.ID : owner; _providerKey = (nSupportedCloudConfigurations)Enum.Parse(typeof(nSupportedCloudConfigurations), providerKey, true); _authData = authData; _rootFolderType = rootFolderType; _createOn = createOn; } public void Dispose() { if (StorageOpened) { Storage.Close(); } } private CloudStorage CreateStorage() { var prms = new object[] { }; if (!string.IsNullOrEmpty(_authData.Url)) { var uri = _authData.Url; if (Uri.IsWellFormedUriString(uri, UriKind.Relative)) { uri = Uri.UriSchemeHttp + Uri.SchemeDelimiter + uri; } prms = new object[] { new Uri(uri) }; } var storage = new CloudStorage(); var config = CloudStorage.GetCloudConfigurationEasy(_providerKey, prms); if (!string.IsNullOrEmpty(_authData.Token)) { if (_providerKey != nSupportedCloudConfigurations.BoxNet) { var token = storage.DeserializeSecurityTokenFromBase64(_authData.Token); storage.Open(config, token); } } else { storage.Open(config, new GenericNetworkCredentials { Password = _authData.Password, UserName = _authData.Login }); } return storage; } internal CloudStorage Storage { get { if (HttpContext.Current != null) { var key = "__CLOUD_STORAGE" + ID; var wrapper = (StorageDisposableWrapper)DisposableHttpContext.Current[key]; if (wrapper == null || !wrapper.Storage.IsOpened) { wrapper = new StorageDisposableWrapper(CreateStorage()); DisposableHttpContext.Current[key] = wrapper; } return wrapper.Storage; } return CreateStorage(); } } internal bool StorageOpened { get { if (HttpContext.Current != null) { var key = "__CLOUD_STORAGE" + ID; var wrapper = (StorageDisposableWrapper)DisposableHttpContext.Current[key]; return wrapper != null && wrapper.Storage.IsOpened; } return false; } } internal void UpdateTitle(string newtitle) { CustomerTitle = newtitle; } public string CustomerTitle { get; private set; } public DateTime CreateOn { get { return _createOn; } } public object RootFolderId { get { return "sbox-" + ID; } } public bool CheckAccess() { try { return Storage.GetRoot() != null; } catch (UnauthorizedAccessException) { return false; } catch (SharpBoxException ex) { Global.Logger.Error("Sharpbox CheckAccess error", ex); return false; } } public void InvalidateStorage() { if (HttpContext.Current != null) { var key = "__CLOUD_STORAGE" + ID; var storage = (StorageDisposableWrapper)DisposableHttpContext.Current[key]; if (storage != null) { storage.Dispose(); } } } public string ProviderKey { get { return _providerKey.ToString(); } } public FolderType RootFolderType { get { return _rootFolderType; } } class StorageDisposableWrapper : IDisposable { public CloudStorage Storage { get; private set; } public StorageDisposableWrapper(CloudStorage storage) { Storage = storage; } public void Dispose() { if (Storage.IsOpened) Storage.Close(); } } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Interpreter; namespace Microsoft.PythonTools.Analysis { public struct ModulePath { public static readonly ModulePath Empty = new ModulePath(null, null, null); /// <summary> /// Returns true if the provided version of Python can only import /// packages containing an <c>__init__.py</c> file. /// </summary> public static bool PythonVersionRequiresInitPyFiles(Version languageVersion) { return languageVersion < new Version(3, 3); } /// <summary> /// The name by which the module can be imported in Python code. /// </summary> public string FullName { get; set; } /// <summary> /// The file containing the source for the module. /// </summary> public string SourceFile { get; set; } /// <summary> /// The path to the library containing the module. /// </summary> public string LibraryPath { get; set; } /// <summary> /// The last portion of <see cref="FullName"/>. /// </summary> public string Name { get { return FullName.Substring(FullName.LastIndexOf('.') + 1); } } /// <summary> /// True if the module is named '__main__' or '__init__'. /// </summary> public bool IsSpecialName { get { var name = Name; return name.Equals("__main__", StringComparison.OrdinalIgnoreCase) || name.Equals("__init__", StringComparison.OrdinalIgnoreCase); } } /// <summary> /// The same as FullName unless the last part of the name is '__init__', /// in which case this is FullName without the last part. /// </summary> public string ModuleName { get { if (Name.Equals("__init__", StringComparison.OrdinalIgnoreCase)) { int lastDot = FullName.LastIndexOf('.'); if (lastDot < 0) { return string.Empty; } else { return FullName.Substring(0, lastDot); } } else { return FullName; } } } /// <summary> /// True if the module is a binary file. /// </summary> /// <remarks>Changed in 2.2 to include .pyc and .pyo files.</remarks> public bool IsCompiled { get { return PythonCompiledRegex.IsMatch(Path.GetFileName(SourceFile)); } } /// <summary> /// True if the module is a native extension module. /// </summary> /// <remarks>New in 2.2</remarks> public bool IsNativeExtension { get { return PythonBinaryRegex.IsMatch(Path.GetFileName(SourceFile)); } } /// <summary> /// Creates a new ModulePath item. /// </summary> /// <param name="fullname">The full name of the module.</param> /// <param name="sourceFile">The full path to the source file /// implementing the module.</param> /// <param name="libraryPath"> /// The path to the library containing the module. This is typically a /// higher-level directory of <paramref name="sourceFile"/>. /// </param> public ModulePath(string fullname, string sourceFile, string libraryPath) : this() { FullName = fullname; SourceFile = sourceFile; LibraryPath = libraryPath; } private static readonly Regex PythonPackageRegex = new Regex(@"^(?!\d)(?<name>(\w|_)+)$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); private static readonly Regex PythonFileRegex = new Regex(@"^(?!\d)(?<name>(\w|_)+)\.pyw?$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); private static readonly Regex PythonBinaryRegex = new Regex(@"^(?!\d)(?<name>(\w|_)+)\.((\w|_|-)+?\.)?pyd$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); private static readonly Regex PythonCompiledRegex = new Regex(@"^(?!\d)(?<name>(\w|_)+)\.(((\w|_|-)+?\.)?pyd|py[co])$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); private static IEnumerable<ModulePath> GetModuleNamesFromPathHelper( string libPath, string path, string baseModule, bool skipFiles, bool recurse, bool requireInitPy ) { Debug.Assert(baseModule == "" || baseModule.EndsWith(".")); if (!Directory.Exists(path)) { yield break; } if (!skipFiles) { foreach (var file in PathUtils.EnumerateFiles(path, recurse: false)) { var filename = PathUtils.GetFileOrDirectoryName(file); var match = PythonFileRegex.Match(filename); if (!match.Success) { match = PythonBinaryRegex.Match(filename); } if (match.Success) { var name = match.Groups["name"].Value; if (name.EndsWith("_d") && file.EndsWith(".pyd", StringComparison.OrdinalIgnoreCase)) { name = name.Remove(name.Length - 2); } yield return new ModulePath(baseModule + name, file, libPath ?? path); } } } if (recurse) { foreach (var dir in PathUtils.EnumerateDirectories(path, recurse: false)) { var dirname = PathUtils.GetFileOrDirectoryName(dir); var match = PythonPackageRegex.Match(dirname); if (match.Success && (!requireInitPy || File.Exists(Path.Combine(dir, "__init__.py")))) { foreach (var entry in GetModuleNamesFromPathHelper( skipFiles ? dir : libPath, dir, baseModule + match.Groups["name"].Value + ".", false, true, requireInitPy )) { yield return entry; } } } } } /// <summary> /// Returns a sequence of ModulePath items for all modules importable /// from the provided path, optionally excluding top level files. /// </summary> public static IEnumerable<ModulePath> GetModulesInPath( string path, bool includeTopLevelFiles = true, bool recurse = true, string basePackage = null, bool requireInitPy = true ) { return GetModuleNamesFromPathHelper( path, path, basePackage ?? string.Empty, !includeTopLevelFiles, recurse, requireInitPy ).Where(mp => !string.IsNullOrEmpty(mp.ModuleName)); } /// <summary> /// Returns a sequence of ModulePath items for all modules importable /// from the provided path, optionally excluding top level files. /// </summary> public static IEnumerable<ModulePath> GetModulesInPath( IEnumerable<string> paths, bool includeTopLevelFiles = true, bool recurse = true, string baseModule = null, bool requireInitPy = true ) { return paths.SelectMany(p => GetModuleNamesFromPathHelper( p, p, baseModule ?? string.Empty, !includeTopLevelFiles, recurse, requireInitPy )).Where(mp => !string.IsNullOrEmpty(mp.ModuleName)); } /// <summary> /// Expands a sequence of directory paths to include any paths that are /// referenced in .pth files. /// /// The original directories are not included in the result. /// </summary> public static IEnumerable<string> ExpandPathFiles(IEnumerable<string> paths) { foreach (var path in paths) { if (Directory.Exists(path)) { foreach (var file in PathUtils.EnumerateFiles(path, "*.pth", recurse: false)) { using (var reader = new StreamReader(file)) { string line; while ((line = reader.ReadLine()) != null) { line = line.Trim(); if (line.StartsWith("import ", StringComparison.Ordinal) || !PathUtils.IsValidPath(line)) { continue; } line = line.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); if (!Path.IsPathRooted(line)) { line = PathUtils.GetAbsoluteDirectoryPath(path, line); } if (Directory.Exists(line)) { yield return line; } } } } } } } /// <summary> /// Expands a sequence of directory paths to include any paths that are /// referenced in .pth files. /// /// The original directories are not included in the result. /// </summary> public static IEnumerable<string> ExpandPathFiles(params string[] paths) { return ExpandPathFiles(paths.AsEnumerable()); } /// <summary> /// Returns a sequence of ModulePaths for all modules importable from /// the specified library. /// </summary> public static IEnumerable<ModulePath> GetModulesInLib( string interpreterPath, string libraryPath, string sitePath = null, bool requireInitPyFiles = true ) { if (File.Exists(interpreterPath)) { interpreterPath = Path.GetDirectoryName(interpreterPath); } if (!Directory.Exists(libraryPath)) { return Enumerable.Empty<ModulePath>(); } if (string.IsNullOrEmpty(sitePath)) { sitePath = Path.Combine(libraryPath, "site-packages"); } var pthDirs = ExpandPathFiles(sitePath); var excludedPthDirs = new HashSet<string>() { sitePath, libraryPath }; // Get modules in stdlib var modulesInStdLib = GetModulesInPath(libraryPath, true, true, requireInitPy: requireInitPyFiles); // Get files in site-packages var modulesInSitePackages = GetModulesInPath(sitePath, true, false, requireInitPy: requireInitPyFiles); // Get directories in site-packages // This is separate from getting files to ensure that each package // gets its own library path. var packagesInSitePackages = GetModulesInPath(sitePath, false, true, requireInitPy: requireInitPyFiles); // Get modules in DLLs directory IEnumerable<ModulePath> modulesInDllsPath; // Get modules in interpreter directory IEnumerable<ModulePath> modulesInExePath; if (Directory.Exists(interpreterPath)) { modulesInDllsPath = GetModulesInPath(Path.Combine(interpreterPath, "DLLs"), true, false); modulesInExePath = GetModulesInPath(interpreterPath, true, false); excludedPthDirs.Add(interpreterPath); excludedPthDirs.Add(Path.Combine(interpreterPath, "DLLs")); } else { modulesInDllsPath = Enumerable.Empty<ModulePath>(); modulesInExePath = Enumerable.Empty<ModulePath>(); } // Get directories referenced by pth files var modulesInPath = GetModulesInPath( pthDirs.Where(p1 => excludedPthDirs.All(p2 => !PathUtils.IsSameDirectory(p1, p2))), true, true, requireInitPy: requireInitPyFiles ); return modulesInPath .Concat(modulesInDllsPath) .Concat(modulesInStdLib) .Concat(modulesInExePath) .Concat(modulesInSitePackages) .Concat(packagesInSitePackages); } /// <summary> /// Returns a sequence of ModulePaths for all modules importable by the /// provided factory. /// </summary> public static IEnumerable<ModulePath> GetModulesInLib(IPythonInterpreterFactory factory) { return GetModulesInLib( factory.Configuration.InterpreterPath, factory.Configuration.LibraryPath, null, // default site-packages path PythonVersionRequiresInitPyFiles(factory.Configuration.Version) ); } /// <summary> /// Returns true if the provided path references an importable Python /// module. This function does not access the filesystem. /// Retuns false if an invalid string is provided. This function does /// not raise exceptions. /// </summary> public static bool IsPythonFile(string path) { return IsPythonFile(path, true, true); } /// <summary> /// Returns true if the provided path references an editable Python /// source module. This function does not access the filesystem. /// Retuns false if an invalid string is provided. This function does /// not raise exceptions. /// </summary> /// <remarks> /// This function may return true even if the file is not an importable /// module. Use <see cref="IsPythonFile"/> and specify "strict" to /// ensure the module can be imported. /// </remarks> public static bool IsPythonSourceFile(string path) { return IsPythonFile(path, false, false); } /// <summary> /// Returns true if the provided path references an importable Python /// module. This function does not access the filesystem. /// Retuns false if an invalid string is provided. This function does /// not raise exceptions. /// </summary> /// <param name="path">Path to check.</param> /// <param name="strict"> /// True if the filename must be importable; false to allow unimportable /// names. /// </param> /// <param name="allowCompiled"> /// True if pyd, pyc and pyo files should be allowed. /// </param> public static bool IsPythonFile(string path, bool strict, bool allowCompiled) { if (string.IsNullOrEmpty(path)) { return false; } string name; try { name = PathUtils.GetFileOrDirectoryName(path); } catch (ArgumentException) { return false; } if (strict) { try { var nameMatch = PythonFileRegex.Match(name); if (allowCompiled && (nameMatch == null || !nameMatch.Success)) { nameMatch = PythonCompiledRegex.Match(name); } return nameMatch != null && nameMatch.Success; } catch (RegexMatchTimeoutException) { return false; } } else { var ext = name.Substring(name.LastIndexOf('.') + 1); return "py".Equals(ext, StringComparison.OrdinalIgnoreCase) || "pyw".Equals(ext, StringComparison.OrdinalIgnoreCase) || (allowCompiled && ( "pyd".Equals(ext, StringComparison.OrdinalIgnoreCase) || "pyc".Equals(ext, StringComparison.OrdinalIgnoreCase) || "pyo".Equals(ext, StringComparison.OrdinalIgnoreCase) )); } } /// <summary> /// Returns true if the provided path is to an '__init__.py' file. /// Returns false if an invalid string is provided. This function does /// not raise exceptions. /// </summary> public static bool IsInitPyFile(string path) { if (string.IsNullOrEmpty(path)) { return false; } try { var name = Path.GetFileName(path); return name.Equals("__init__.py", StringComparison.OrdinalIgnoreCase) || name.Equals("__init__.pyw", StringComparison.OrdinalIgnoreCase); } catch (ArgumentException) { return false; } } /// <summary> /// Returns a new ModulePath value determined from the provided full /// path to a Python file. This function will access the filesystem to /// determine the package name. /// </summary> /// <param name="path"> /// The path referring to a Python file. /// </param> /// <exception cref="ArgumentException"> /// path is not a valid Python module. /// </exception> public static ModulePath FromFullPath(string path) { return FromFullPath(path, null, null); } /// <summary> /// Returns a new ModulePath value determined from the provided full /// path to a Python file. This function will access the filesystem to /// determine the package name. /// </summary> /// <param name="path"> /// The path referring to a Python file. /// </param> /// <param name="topLevelPath"> /// The directory to stop searching for packages at. The module name /// will never include the last segment of this path. /// </param> /// <exception cref="ArgumentException"> /// path is not a valid Python module. /// </exception> /// <remarks>This overload </remarks> public static ModulePath FromFullPath(string path, string topLevelPath) { return FromFullPath(path, topLevelPath, null); } /// <summary> /// Returns a new ModulePath value determined from the provided full /// path to a Python file. This function may access the filesystem to /// determine the package name unless <paramref name="isPackage"/> is /// provided. /// </summary> /// <param name="path"> /// The path referring to a Python file. /// </param> /// <param name="topLevelPath"> /// The directory to stop searching for packages at. The module name /// will never include the last segment of this path. /// </param> /// <param name="isPackage"> /// A predicate that determines whether the specified substring of /// <paramref name="path"/> represents a package. If omitted, the /// default behavior is to check for a file named "__init__.py" in the /// directory passed to the predicate. /// </param> /// <exception cref="ArgumentException"> /// path is not a valid Python module. /// </exception> public static ModulePath FromFullPath( string path, string topLevelPath = null, Func<string, bool> isPackage = null ) { var name = PathUtils.GetFileOrDirectoryName(path); var nameMatch = PythonFileRegex.Match(name); if (nameMatch == null || !nameMatch.Success) { nameMatch = PythonBinaryRegex.Match(name); } if (nameMatch == null || !nameMatch.Success) { throw new ArgumentException("Not a valid Python module: " + path); } var fullName = nameMatch.Groups["name"].Value; var remainder = PathUtils.GetParent(path); if (isPackage == null) { // We know that f will be the result of GetParent() and always // ends with a directory separator, so just concatenate to avoid // potential path length problems. isPackage = f => File.Exists(f + "__init__.py"); } while ( PathUtils.IsValidPath(remainder) && isPackage(remainder) && (string.IsNullOrEmpty(topLevelPath) || (PathUtils.IsSubpathOf(topLevelPath, remainder) && !PathUtils.IsSameDirectory(topLevelPath, remainder))) ) { fullName = PathUtils.GetFileOrDirectoryName(remainder) + "." + fullName; remainder = PathUtils.GetParent(remainder); } return new ModulePath(fullName, path, remainder); } internal static IEnumerable<string> GetParents(string name, bool includeFullName = true) { if (string.IsNullOrEmpty(name)) { yield break; } var sb = new StringBuilder(); var parts = name.Split('.'); if (!includeFullName && parts.Length > 0) { parts[parts.Length - 1] = null; } foreach (var bit in parts.TakeWhile(s => !string.IsNullOrEmpty(s))) { sb.Append(bit); yield return sb.ToString(); sb.Append('.'); } } } }
using System.Configuration; using System.IO; using System.Linq; using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Logging; using Umbraco.Core.ObjectResolution; using Umbraco.Core.Profiling; using Umbraco.Core.Sync; using Umbraco.Tests.TestHelpers; namespace Umbraco.Tests { [TestFixture] public class ApplicationUrlHelperTests { private ILogger _logger; // note: in tests, read appContext._umbracoApplicationUrl and not the property, // because reading the property does run some code, as long as the field is null. [TestFixtureSetUp] public void InitializeFixture() { _logger = new Logger(new FileInfo(TestHelper.MapPathForTest("~/unit-test-log4net.config"))); } private static void Initialize(IUmbracoSettingsSection settings) { ServerRegistrarResolver.Current = new ServerRegistrarResolver(new ConfigServerRegistrar(settings.DistributedCall)); Resolution.Freeze(); } [TearDown] public void Reset() { ServerRegistrarResolver.Reset(); } [Test] public void NoApplicationUrlByDefault() { var appCtx = new ApplicationContext(CacheHelper.CreateDisabledCacheHelper(), new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>())); Assert.IsNull(appCtx._umbracoApplicationUrl); } [Test] public void SetApplicationUrlViaProvider() { // no applicable settings, but a provider var settings = Mock.Of<IUmbracoSettingsSection>(section => section.DistributedCall == Mock.Of<IDistributedCallSection>(callSection => callSection.Servers == Enumerable.Empty<IServer>()) && section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string)null) && section.ScheduledTasks == Mock.Of<IScheduledTasksSection>()); ApplicationUrlHelper.ApplicationUrlProvider = request => "http://server1.com/umbraco"; Initialize(settings); var appCtx = new ApplicationContext(CacheHelper.CreateDisabledCacheHelper(), new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>())); ConfigurationManager.AppSettings.Set("umbracoUseSSL", "true"); // does not make a diff here ApplicationUrlHelper.EnsureApplicationUrl(appCtx, settings: settings); Assert.AreEqual("http://server1.com/umbraco", appCtx._umbracoApplicationUrl); } [Test] public void SetApplicationUrlWhenNoSettings() { // no applicable settings, cannot set url var settings = Mock.Of<IUmbracoSettingsSection>(section => section.DistributedCall == Mock.Of<IDistributedCallSection>(callSection => callSection.Servers == Enumerable.Empty<IServer>()) && section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string) null) && section.ScheduledTasks == Mock.Of<IScheduledTasksSection>()); Initialize(settings); var appCtx = new ApplicationContext(CacheHelper.CreateDisabledCacheHelper(), new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>())); ConfigurationManager.AppSettings.Set("umbracoUseSSL", "true"); // does not make a diff here ApplicationUrlHelper.TrySetApplicationUrl(appCtx, settings); // still NOT set Assert.IsNull(appCtx._umbracoApplicationUrl); } [Test] public void SetApplicationUrlFromDcSettingsSsl1() { // set from distributed call settings // first server is master server var settings = Mock.Of<IUmbracoSettingsSection>(section => section.DistributedCall == Mock.Of<IDistributedCallSection>(callSection => callSection.Enabled == true && callSection.Servers == new IServer[] { Mock.Of<IServer>(server => server.ServerName == NetworkHelper.MachineName && server.ServerAddress == "server1.com"), Mock.Of<IServer>(server => server.ServerName == "ANOTHERNAME" && server.ServerAddress == "server2.com"), }) && section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string)null) && section.ScheduledTasks == Mock.Of<IScheduledTasksSection>(tasksSection => tasksSection.BaseUrl == (string)null)); Initialize(settings); var appCtx = new ApplicationContext(CacheHelper.CreateDisabledCacheHelper(), new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>())); ConfigurationManager.AppSettings.Set("umbracoUseSSL", "true"); ApplicationUrlHelper.TrySetApplicationUrl(appCtx, settings); Assert.AreEqual("http://server1.com:80/umbraco", appCtx._umbracoApplicationUrl); var registrar = ServerRegistrarResolver.Current.Registrar as IServerRegistrar2; var role = registrar.GetCurrentServerRole(); Assert.AreEqual(ServerRole.Master, role); } [Test] public void SetApplicationUrlFromDcSettingsSsl2() { // set from distributed call settings // other servers are slave servers var settings = Mock.Of<IUmbracoSettingsSection>(section => section.DistributedCall == Mock.Of<IDistributedCallSection>(callSection => callSection.Enabled == true && callSection.Servers == new IServer[] { Mock.Of<IServer>(server => server.ServerName == "ANOTHERNAME" && server.ServerAddress == "server2.com"), Mock.Of<IServer>(server => server.ServerName == NetworkHelper.MachineName && server.ServerAddress == "server1.com"), }) && section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string)null) && section.ScheduledTasks == Mock.Of<IScheduledTasksSection>(tasksSection => tasksSection.BaseUrl == (string)null)); Initialize(settings); var appCtx = new ApplicationContext(CacheHelper.CreateDisabledCacheHelper(), new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>())); ConfigurationManager.AppSettings.Set("umbracoUseSSL", "true"); ApplicationUrlHelper.TrySetApplicationUrl(appCtx, settings); Assert.AreEqual("http://server1.com:80/umbraco", appCtx._umbracoApplicationUrl); var registrar = ServerRegistrarResolver.Current.Registrar as IServerRegistrar2; var role = registrar.GetCurrentServerRole(); Assert.AreEqual(ServerRole.Slave, role); } [Test] public void SetApplicationUrlFromDcSettingsSsl3() { // set from distributed call settings // cannot set if not enabled var settings = Mock.Of<IUmbracoSettingsSection>(section => section.DistributedCall == Mock.Of<IDistributedCallSection>(callSection => callSection.Enabled == false && callSection.Servers == new IServer[] { Mock.Of<IServer>(server => server.ServerName == "ANOTHERNAME" && server.ServerAddress == "server2.com"), Mock.Of<IServer>(server => server.ServerName == NetworkHelper.MachineName && server.ServerAddress == "server1.com"), }) && section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string)null) && section.ScheduledTasks == Mock.Of<IScheduledTasksSection>(tasksSection => tasksSection.BaseUrl == (string)null)); Initialize(settings); var appCtx = new ApplicationContext(CacheHelper.CreateDisabledCacheHelper(), new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>())); ConfigurationManager.AppSettings.Set("umbracoUseSSL", "true"); ApplicationUrlHelper.TrySetApplicationUrl(appCtx, settings); Assert.IsNull(appCtx._umbracoApplicationUrl); var registrar = ServerRegistrarResolver.Current.Registrar as IServerRegistrar2; var role = registrar.GetCurrentServerRole(); Assert.AreEqual(ServerRole.Single, role); } [Test] public void ServerRoleSingle() { // distributed call settings disabled, single server var settings = Mock.Of<IUmbracoSettingsSection>(section => section.DistributedCall == Mock.Of<IDistributedCallSection>(callSection => callSection.Enabled == false && callSection.Servers == Enumerable.Empty<IServer>()) && section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string)null) && section.ScheduledTasks == Mock.Of<IScheduledTasksSection>(tasksSection => tasksSection.BaseUrl == (string)null)); Initialize(settings); var registrar = ServerRegistrarResolver.Current.Registrar as IServerRegistrar2; var role = registrar.GetCurrentServerRole(); Assert.AreEqual(ServerRole.Single, role); } [Test] public void ServerRoleUnknown1() { // distributed call enabled but missing servers, unknown server var settings = Mock.Of<IUmbracoSettingsSection>(section => section.DistributedCall == Mock.Of<IDistributedCallSection>(callSection => callSection.Enabled == true && callSection.Servers == Enumerable.Empty<IServer>()) && section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string)null) && section.ScheduledTasks == Mock.Of<IScheduledTasksSection>(tasksSection => tasksSection.BaseUrl == (string)null)); Initialize(settings); var registrar = ServerRegistrarResolver.Current.Registrar as IServerRegistrar2; var role = registrar.GetCurrentServerRole(); Assert.AreEqual(ServerRole.Unknown, role); } [Test] public void ServerRoleUnknown2() { // distributed call enabled, cannot find server, assume it's an undeclared slave var settings = Mock.Of<IUmbracoSettingsSection>(section => section.DistributedCall == Mock.Of<IDistributedCallSection>(callSection => callSection.Enabled == true && callSection.Servers == new IServer[] { Mock.Of<IServer>(server => server.ServerName == "ANOTHERNAME" && server.ServerAddress == "server2.com"), }) && section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string)null) && section.ScheduledTasks == Mock.Of<IScheduledTasksSection>(tasksSection => tasksSection.BaseUrl == (string)null)); Initialize(settings); var registrar = ServerRegistrarResolver.Current.Registrar as IServerRegistrar2; var role = registrar.GetCurrentServerRole(); Assert.AreEqual(ServerRole.Slave, role); } [Test] public void SetApplicationUrlFromStSettingsNoSsl() { var settings = Mock.Of<IUmbracoSettingsSection>(section => section.DistributedCall == Mock.Of<IDistributedCallSection>(callSection => callSection.Servers == Enumerable.Empty<IServer>()) && section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string) null) && section.ScheduledTasks == Mock.Of<IScheduledTasksSection>(tasksSection => tasksSection.BaseUrl == "mycoolhost.com/umbraco")); Initialize(settings); var appCtx = new ApplicationContext(CacheHelper.CreateDisabledCacheHelper(), new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>())); ConfigurationManager.AppSettings.Set("umbracoUseSSL", "false"); ApplicationUrlHelper.TrySetApplicationUrl(appCtx, settings); Assert.AreEqual("http://mycoolhost.com/umbraco", appCtx._umbracoApplicationUrl); } [Test] public void SetApplicationUrlFromStSettingsSsl() { var settings = Mock.Of<IUmbracoSettingsSection>(section => section.DistributedCall == Mock.Of<IDistributedCallSection>(callSection => callSection.Servers == Enumerable.Empty<IServer>()) && section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == (string) null) && section.ScheduledTasks == Mock.Of<IScheduledTasksSection>(tasksSection => tasksSection.BaseUrl == "mycoolhost.com/umbraco/")); Initialize(settings); var appCtx = new ApplicationContext(CacheHelper.CreateDisabledCacheHelper(), new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>())); ConfigurationManager.AppSettings.Set("umbracoUseSSL", "true"); ApplicationUrlHelper.TrySetApplicationUrl(appCtx, settings); Assert.AreEqual("https://mycoolhost.com/umbraco", appCtx._umbracoApplicationUrl); } [Test] public void SetApplicationUrlFromWrSettingsSsl() { var settings = Mock.Of<IUmbracoSettingsSection>(section => section.DistributedCall == Mock.Of<IDistributedCallSection>(callSection => callSection.Servers == Enumerable.Empty<IServer>()) && section.WebRouting == Mock.Of<IWebRoutingSection>(wrSection => wrSection.UmbracoApplicationUrl == "httpx://whatever.com/umbraco/") && section.ScheduledTasks == Mock.Of<IScheduledTasksSection>(tasksSection => tasksSection.BaseUrl == "mycoolhost.com/umbraco")); Initialize(settings); var appCtx = new ApplicationContext(CacheHelper.CreateDisabledCacheHelper(), new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>())); ConfigurationManager.AppSettings.Set("umbracoUseSSL", "true"); // does not make a diff here ApplicationUrlHelper.TrySetApplicationUrl(appCtx, settings); Assert.AreEqual("httpx://whatever.com/umbraco", appCtx._umbracoApplicationUrl); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime; namespace System.Collections.ObjectModel { [DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class ReadOnlyCollection<T> : IList<T>, IList, IReadOnlyList<T> { private IList<T> list; // Do not rename (binary serialization) [NonSerialized] private Object _syncRoot; public ReadOnlyCollection(IList<T> list) { if (list == null) { throw new ArgumentNullException(nameof(list)); } this.list = list; } public int Count { get { return list.Count; } } public T this[int index] { get { return list[index]; } } public bool Contains(T value) { return list.Contains(value); } public void CopyTo(T[] array, int index) { list.CopyTo(array, index); } public IEnumerator<T> GetEnumerator() { return list.GetEnumerator(); } public int IndexOf(T value) { return list.IndexOf(value); } protected IList<T> Items { get { return list; } } bool ICollection<T>.IsReadOnly { get { return true; } } T IList<T>.this[int index] { get { return list[index]; } set { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } } void ICollection<T>.Add(T value) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } void ICollection<T>.Clear() { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } void IList<T>.Insert(int index, T value) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } bool ICollection<T>.Remove(T value) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } void IList<T>.RemoveAt(int index) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)list).GetEnumerator(); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (_syncRoot == null) { ICollection c = list as ICollection; if (c != null) { _syncRoot = c.SyncRoot; } else { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } } return _syncRoot; } } void ICollection.CopyTo(Array array, int index) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { throw new ArgumentException(SR.Arg_NonZeroLowerBound); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < Count) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } T[] items = array as T[]; if (items != null) { list.CopyTo(items, index); } else { /* ProjectN port note: IsAssignable no longer available on Type surface area. This is a non-reliable check so we should be able to do without. // // Catch the obvious case assignment will fail. // We can found all possible problems by doing the check though. // For example, if the element type of the Array is derived from T, // we can't figure out if we can successfully copy the element beforehand. // IResolvedRuntimeType targetType = array.GetType().GetElementType().ResolvedType; IResolvedRuntimeType sourceType = typeof(T).ResolvedType; if(!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType))) { throw new ArgumentException(SR.Argument_InvalidArrayType); } */ // // We can't cast array of value type to object[], so we don't support // widening of primitive types here. // object[] objects = array as object[]; if (objects == null) { throw new ArgumentException(SR.Argument_InvalidArrayType); } int count = list.Count; try { for (int i = 0; i < count; i++) { objects[index++] = list[i]; } } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType); } } } bool IList.IsFixedSize { get { return true; } } bool IList.IsReadOnly { get { return true; } } object IList.this[int index] { get { return list[index]; } set { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } } int IList.Add(object value) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } void IList.Clear() { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } private static bool IsCompatibleObject(object value) { // Non-null values are fine. Only accept nulls if T is a class or Nullable<U>. // Note that default(T) is not equal to null for value types except when T is Nullable<U>. return ((value is T) || (value == null && default(T) == null)); } bool IList.Contains(object value) { if (IsCompatibleObject(value)) { return Contains((T)value); } return false; } int IList.IndexOf(object value) { if (IsCompatibleObject(value)) { return IndexOf((T)value); } return -1; } void IList.Insert(int index, object value) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } void IList.Remove(object value) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } void IList.RemoveAt(int index) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System.ComponentModel; using System.Reflection; using System.Text; using NLog.Layouts; using NLog.Targets; #if !SILVERLIGHT namespace NLog.UnitTests { using System; using System.Collections.Generic; using System.IO; using Xunit; using System.Linq; using System.Text.RegularExpressions; using System.Xml.Linq; /// <summary> /// Source code tests. /// </summary> public class SourceCodeTests { private static Regex classNameRegex = new Regex(@"^ (public |abstract |sealed |static |partial |internal )*(class|interface|struct|enum) (?<className>\w+)\b", RegexOptions.Compiled); private static Regex delegateTypeRegex = new Regex(@"^ (public |internal )delegate .*\b(?<delegateType>\w+)\(", RegexOptions.Compiled); private static string[] directoriesToVerify = new[] { "src/NLog", "tests/NLog.UnitTests" }; private static IList<string> fileNamesToIgnore = new List<string>() { "AssemblyInfo.cs", "AssemblyBuildInfo.cs", "GlobalSuppressions.cs", "CompilerAttributes.cs", "Logger1.cs" }; private string sourceCodeDirectory; private string licenseFile; private string[] licenseLines; public SourceCodeTests() { this.sourceCodeDirectory = Directory.GetCurrentDirectory(); while (this.sourceCodeDirectory != null) { this.licenseFile = Path.Combine(sourceCodeDirectory, "LICENSE.txt"); if (File.Exists(licenseFile)) { break; } this.sourceCodeDirectory = Path.GetDirectoryName(this.sourceCodeDirectory); } if (this.sourceCodeDirectory != null) { this.licenseLines = File.ReadAllLines(this.licenseFile); } } [Fact] public void VerifyFileHeaders() { if (this.sourceCodeDirectory == null) { return; } int failedFiles = 0; foreach (string dir in directoriesToVerify) { foreach (string file in Directory.GetFiles(Path.Combine(this.sourceCodeDirectory, dir), "*.cs", SearchOption.AllDirectories)) { if (IgnoreFile(file)) { continue; } if (!VerifySingleFile(file)) { failedFiles++; Console.WriteLine("Missing header: {0}", file); } } } Assert.Equal(0, failedFiles); } private static XNamespace MSBuildNamespace = "http://schemas.microsoft.com/developer/msbuild/2003"; [Fact] public void VerifyProjectsInSync() { if (this.sourceCodeDirectory == null) { return; } int failures = 0; var filesToCompile = new List<string>(); GetAllFilesToCompileInDirectory(filesToCompile, Path.Combine(this.sourceCodeDirectory, "src/NLog/"), "*.cs", ""); failures += CompareDirectoryWithProjects(filesToCompile, "src/NLog/NLog.netfx35.csproj"); failures += CompareDirectoryWithProjects(filesToCompile, "src/NLog/NLog.netfx40.csproj"); failures += CompareDirectoryWithProjects(filesToCompile, "src/NLog/NLog.netfx45.csproj"); failures += CompareDirectoryWithProjects(filesToCompile, "src/NLog/NLog.sl4.csproj"); failures += CompareDirectoryWithProjects(filesToCompile, "src/NLog/NLog.wp7.csproj"); failures += CompareDirectoryWithProjects(filesToCompile, "src/NLog/NLog.mono.csproj"); filesToCompile.Clear(); GetAllFilesToCompileInDirectory(filesToCompile, Path.Combine(this.sourceCodeDirectory, "src/NLog.Extended/"), "*.cs", ""); failures += CompareDirectoryWithProjects(filesToCompile, "src/NLog.Extended/NLog.Extended.netfx35.csproj"); failures += CompareDirectoryWithProjects(filesToCompile, "src/NLog.Extended/NLog.Extended.netfx40.csproj"); failures += CompareDirectoryWithProjects(filesToCompile, "src/NLog.Extended/NLog.Extended.netfx45.csproj"); failures += CompareDirectoryWithProjects(filesToCompile, "src/NLog.Extended/NLog.Extended.mono.csproj"); filesToCompile.Clear(); GetAllFilesToCompileInDirectory(filesToCompile, Path.Combine(this.sourceCodeDirectory, "tests/NLog.UnitTests/"), "*.cs", ""); failures += CompareDirectoryWithProjects(filesToCompile, "tests/NLog.UnitTests/NLog.UnitTests.netfx35.csproj"); failures += CompareDirectoryWithProjects(filesToCompile, "tests/NLog.UnitTests/NLog.UnitTests.netfx40.csproj"); failures += CompareDirectoryWithProjects(filesToCompile, "tests/NLog.UnitTests/NLog.UnitTests.netfx45.csproj"); failures += CompareDirectoryWithProjects(filesToCompile, "tests/NLog.UnitTests/NLog.UnitTests.sl4.csproj"); failures += CompareDirectoryWithProjects(filesToCompile, "tests/NLog.UnitTests/NLog.UnitTests.mono.csproj"); filesToCompile.Clear(); GetAllFilesToCompileInDirectory(filesToCompile, Path.Combine(this.sourceCodeDirectory, "src/NLogAutoLoadExtension/"), "*.cs", ""); failures += CompareDirectoryWithProjects(filesToCompile, "src/NLogAutoLoadExtension/NLogAutoLoadExtension.netfx35.csproj"); failures += CompareDirectoryWithProjects(filesToCompile, "src/NLogAutoLoadExtension/NLogAutoLoadExtension.netfx40.csproj"); failures += CompareDirectoryWithProjects(filesToCompile, "src/NLogAutoLoadExtension/NLogAutoLoadExtension.netfx45.csproj"); failures += CompareDirectoryWithProjects(filesToCompile, "src/NLogAutoLoadExtension/NLogAutoLoadExtension.mono.csproj"); Assert.Equal(0, failures); } private int CompareDirectoryWithProjects(List<string> filesToCompile, params string[] projectFiles) { var filesInProject = new List<string>(); this.GetCompileItemsFromProjects(filesInProject, projectFiles); var missingFiles = filesToCompile.Except(filesInProject).ToList(); if (missingFiles.Count > 0) { Console.WriteLine("The following files must be added to {0}", string.Join(";", projectFiles)); foreach (var f in missingFiles) { Console.WriteLine(" {0}", f); } } return missingFiles.Count; } private void GetCompileItemsFromProjects(List<string> filesInProject, params string[] projectFiles) { foreach (string proj in projectFiles) { string csproj = Path.Combine(this.sourceCodeDirectory, proj); GetCompileItemsFromProject(filesInProject, csproj); } } private static void GetCompileItemsFromProject(List<string> filesInProject, string csproj) { XElement contents = XElement.Load(csproj); filesInProject.AddRange(contents.Descendants(MSBuildNamespace + "Compile").Select(c => (string)c.Attribute("Include"))); } private static void GetAllFilesToCompileInDirectory(List<string> output, string path, string pattern, string prefix) { foreach (string file in Directory.GetFiles(path, pattern)) { if (file.EndsWith(".xaml.cs")) { continue; } if (file.Contains(".g.")) { continue; } output.Add(prefix + Path.GetFileName(file)); } foreach (string dir in Directory.GetDirectories(path)) { GetAllFilesToCompileInDirectory(output, dir, pattern, prefix + Path.GetFileName(dir) + "\\"); } } [Fact] public void VerifyNamespacesAndClassNames() { if (this.sourceCodeDirectory == null) { return; } int failedFiles = 0; foreach (string dir in directoriesToVerify) { failedFiles += VerifyClassNames(Path.Combine(this.sourceCodeDirectory, dir), Path.GetFileName(dir)); } Assert.Equal(0, failedFiles); } bool IgnoreFile(string file) { string baseName = Path.GetFileName(file); if (fileNamesToIgnore.Contains(baseName)) { return true; } if (baseName.IndexOf(".xaml", StringComparison.OrdinalIgnoreCase) >= 0) { return true; } if (baseName.IndexOf(".g.", StringComparison.OrdinalIgnoreCase) >= 0) { return true; } if (baseName == "ExtensionAttribute.cs") { return true; } if (baseName == "NUnitAdapter.cs") { return true; } if (baseName == "LocalizableAttribute.cs") { return true; } if (baseName == "Annotations.cs") { return true; } return false; } private bool VerifySingleFile(string file) { using (StreamReader reader = File.OpenText(file)) { for (int i = 0; i < this.licenseLines.Length; ++i) { string line = reader.ReadLine(); string expected = "// " + this.licenseLines[i]; if (line != expected) { return false; } } return true; } } private int VerifyClassNames(string path, string expectedNamespace) { int failureCount = 0; foreach (string file in Directory.GetFiles(path, "*.cs")) { if (IgnoreFile(file)) { continue; } string expectedClassName = Path.GetFileNameWithoutExtension(file); int p = expectedClassName.IndexOf('-'); if (p >= 0) { expectedClassName = expectedClassName.Substring(0, p); } if (!this.VerifySingleFile(file, expectedNamespace, expectedClassName)) { failureCount++; } } foreach (string dir in Directory.GetDirectories(path)) { failureCount += VerifyClassNames(dir, expectedNamespace + "." + Path.GetFileName(dir)); } return failureCount; } private bool VerifySingleFile(string file, string expectedNamespace, string expectedClassName) { bool success = true; List<string> classNames = new List<string>(); using (StreamReader sr = File.OpenText(file)) { string line; while ((line = sr.ReadLine()) != null) { if (line.StartsWith("namespace ", StringComparison.Ordinal)) { string ns = line.Substring(10); if (expectedNamespace != ns) { Console.WriteLine("Invalid namespace: '{0}' Expected: '{1}'", ns, expectedNamespace); success = false; } } Match match = classNameRegex.Match(line); if (match.Success) { classNames.Add(match.Groups["className"].Value); } match = delegateTypeRegex.Match(line); if (match.Success) { classNames.Add(match.Groups["delegateType"].Value); } } } if (classNames.Count == 0) { Console.WriteLine("No classes found in {0}", file); success = false; } if (classNames.Count > 1) { Console.WriteLine("More than 1 class name found in {0}", file); success = false; } if (classNames.Count == 1 && classNames[0] != expectedClassName) { Console.WriteLine("Invalid class name. Expected '{0}', actual: '{1}'", expectedClassName, classNames[0]); success = false; } return success; } /// <summary> /// Vertify that all properties with the <see cref="DefaultValueAttribute"/> are set with the default ctor. /// </summary> [Fact] public void VerifyDefaultValues() { var ass = typeof(LoggerImpl).Assembly; //var types = AppDomain.CurrentDomain.GetAssemblies() // .SelectMany(s => s.GetTypes()); var types = ass.GetTypes(); // VerifyDefaultValuesType(typeof(MailTarget)); List<string> reportErrors = new List<string>(); foreach (var type in types) { VerifyDefaultValuesType(type, reportErrors); } //one message for all failing properties var fullMessage = string.Format("{0} errors: \n -------- \n- {1}", reportErrors.Count, string.Join("\n- ", reportErrors)); Assert.False(reportErrors.Any(), fullMessage); } ///<summary>Verify all properties with the <see cref="DefaultValueAttribute"/></summary> ///<remarks>Note: Xunit dont like overloads</remarks> private static void VerifyDefaultValuesType(Type type, List<string> reportErrors) { var props = type.GetProperties(); var defaultValuesDict = new Dictionary<string, object>(); //find first [DefaultValue] values of all props foreach (var propertyInfo in props) { var defaultValues = propertyInfo.GetCustomAttributes(typeof(DefaultValueAttribute), true); if (defaultValues.Any()) { var firstDefaultValueAttr = (DefaultValueAttribute)defaultValues.First(); defaultValuesDict.Add(propertyInfo.Name, firstDefaultValueAttr.Value); } } if (defaultValuesDict.Any()) { //find first ctor without parameters var ctor = type.GetConstructors().FirstOrDefault(c => !c.GetParameters().Any()); if (ctor != null) { var newObject = ctor.Invoke(null); //check al needed props foreach (var propertyInfo in props.Where(p => defaultValuesDict.ContainsKey(p.Name))) { var neededVal = defaultValuesDict[propertyInfo.Name]; var currentVal = propertyInfo.GetValue(newObject, null); var eq = AreDefaultValuesEqual(neededVal, currentVal, propertyInfo); if (!eq) { //report string message = string.Format("{0}.{1} has a wrong value for [DefaultValueAttribute] compared to the default ctor. DefaultValueAttribute says = {2} and ctor tells = {3}", type.FullName, propertyInfo.Name, PrintValForMessage(neededVal), PrintValForMessage(currentVal)); reportErrors.Add(message); } } } } } /// <summary> /// Are the values equal? /// </summary> /// <param name="neededVal">the val from the <see cref="DefaultValueAttribute"/></param> /// <param name="currentVal">the val from the empty ctor</param> /// <param name="propertyInfo">the prop where the value came from</param> /// <returns>equals</returns> private static bool AreDefaultValuesEqual(object neededVal, object currentVal, PropertyInfo propertyInfo) { if (neededVal == null) { if (currentVal != null) { return false; } //both null, OK, next return true; } if (currentVal == null) { //needed was null, so wrong return false; } //try as strings first var propType = propertyInfo.PropertyType; var neededString = neededVal.ToString(); var currentString = currentVal.ToString(); //handle quotes with Layouts if (propType == typeof(Layout)) { neededString = "'" + neededString + "'"; } var eqstring = neededString.Equals(currentString); if (eqstring) { //ok, so next return true; } //handle UTF-8 properly if (propType == typeof(Encoding)) { if (currentVal is UTF8Encoding && (neededString.Equals("utf-8", StringComparison.InvariantCultureIgnoreCase) || neededString.Equals("utf8", StringComparison.InvariantCultureIgnoreCase))) return true; } //nulls or not string equals, fallback //Assert.Equal(neededVal, currentVal); return neededVal.Equals(currentVal); } /// <summary> /// print value quoted or as NULL /// </summary> /// <param name="o"></param> /// <returns></returns> private static string PrintValForMessage(object o) { if (o == null) return "NULL"; return "'" + o + "'"; } } } #endif
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * 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. * * 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.ComponentModel; using System.Drawing; using XenAdmin.Controls; using XenAdmin.Core; using XenAPI; using XenAdmin.Actions; namespace XenAdmin.Dialogs { public partial class AttachDiskDialog : XenDialogBase { private readonly VM TheVM; private DiskListVdiItem oldSelected = null; private bool oldROState = false; private Pool poolofone; private readonly CollectionChangeEventHandler SR_CollectionChangedWithInvoke; public AttachDiskDialog(VM vm) : base(vm.Connection) { TheVM = vm; InitializeComponent(); DiskListTreeView.ShowCheckboxes = false; DiskListTreeView.ShowDescription = true; DiskListTreeView.ShowImages = true; DiskListTreeView.SelectedIndexChanged += DiskListTreeView_SelectedIndexChanged; SR_CollectionChangedWithInvoke = Program.ProgramInvokeHandler(SR_CollectionChanged); connection.Cache.RegisterCollectionChanged<SR>(SR_CollectionChangedWithInvoke); poolofone = Helpers.GetPoolOfOne(connection); if (poolofone != null) poolofone.PropertyChanged += Server_Changed; readonlyCheckboxToolTipContainer.SuppressTooltip = false; DeactivateControlsForHvmVm(); BuildList(); DiskListTreeView_SelectedIndexChanged(null, null); } void SR_CollectionChanged(object sender, CollectionChangeEventArgs e) { Program.Invoke(this, BuildList); } private bool skipSelectedIndexChanged; void DiskListTreeView_SelectedIndexChanged(object sender, EventArgs e) { if(skipSelectedIndexChanged) return; if (DiskListTreeView.SelectedItem is DiskListSrItem || DiskListTreeView.SelectedItem == null) { //As we're changing the index below - stall the SelectedIndexChanged event until we're done skipSelectedIndexChanged = true; try { DiskListTreeView.SelectedItem = oldSelected; OkBtn.Enabled = DiskListTreeView.SelectedItem != null; DeactivateAttachButtonIfHvm(); } finally { //Ensure the lock is released skipSelectedIndexChanged = false; } return; } DiskListVdiItem item = DiskListTreeView.SelectedItem as DiskListVdiItem; ReadOnlyCheckBox.Enabled = !item.ForceReadOnly; ReadOnlyCheckBox.Checked = item.ForceReadOnly ? true : oldROState; OkBtn.Enabled = true; oldSelected = item; DeactivateControlsForHvmVm(); } private void DeactivateControlsForHvmVm() { DeactivateReadOnlyCheckBoxForHvmVm(); DeactivateAttachButtonIfHvm(); } private void DeactivateAttachButtonIfHvm() { if (!TheVM.IsHVM()) return; DiskListVdiItem vdiItem = DiskListTreeView.SelectedItem as DiskListVdiItem; if (vdiItem != null && vdiItem.ForceReadOnly) OkBtn.Enabled = false; } private void DeactivateReadOnlyCheckBoxForHvmVm() { if (!TheVM.IsHVM()) return; readonlyCheckboxToolTipContainer.SetToolTip(Messages.ATTACH_DISK_DIALOG_READONLY_DISABLED_FOR_HVM); ReadOnlyCheckBox.Enabled = false; } private void BuildList() { Program.AssertOnEventThread(); DiskListVdiItem lastSelected = DiskListTreeView.SelectedItem as DiskListVdiItem; String oldRef = ""; if (lastSelected != null) oldRef = lastSelected.TheVDI.opaque_ref; DiskListTreeView.BeginUpdate(); try { DiskListTreeView.ClearAllNodes(); foreach (SR sr in connection.Cache.SRs) { DiskListSrItem item = new DiskListSrItem(sr, TheVM); if (item.Show) { DiskListTreeView.AddNode(item); foreach (VDI TheVDI in sr.Connection.ResolveAllShownXenModelObjects(sr.VDIs, Properties.Settings.Default.ShowHiddenVMs)) { DiskListVdiItem VDIitem = new DiskListVdiItem(TheVDI); if (VDIitem.Show) DiskListTreeView.AddChildNode(item, VDIitem); TheVDI.PropertyChanged -= new PropertyChangedEventHandler(Server_Changed); TheVDI.PropertyChanged += new PropertyChangedEventHandler(Server_Changed); } } sr.PropertyChanged -= new PropertyChangedEventHandler(Server_Changed); sr.PropertyChanged += new PropertyChangedEventHandler(Server_Changed); } } finally { DiskListTreeView.EndUpdate(); DiskListTreeView.SelectedItem = SelectByRef(oldRef); } } private object SelectByRef(string oldRef) { for (int i = 0; i < DiskListTreeView.Items.Count; i++) { DiskListVdiItem item = DiskListTreeView.Items[i] as DiskListVdiItem; if (item == null) continue; else if (item.TheVDI.opaque_ref == oldRef) return item; } return null; } private void Server_Changed(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "name_label" || e.PropertyName == "VDIs" || e.PropertyName == "VBDs" || e.PropertyName == "default_SR") { Program.Invoke(this, BuildList); } } private void ReadOnlyCheckBox_CheckedChanged(object sender, EventArgs e) { if (ReadOnlyCheckBox.Enabled) oldROState = ReadOnlyCheckBox.Checked; } private void OkBtn_Click(object sender, EventArgs e) { DiskListVdiItem item = DiskListTreeView.SelectedItem as DiskListVdiItem; if (item == null) return; VDI TheVDI = item.TheVDI; // Run this stuff off the event thread, since it involves a server call System.Threading.ThreadPool.QueueUserWorkItem((System.Threading.WaitCallback)delegate(object o) { // Get a spare userdevice string[] uds = VM.get_allowed_VBD_devices(connection.DuplicateSession(), TheVM.opaque_ref); if (uds.Length == 0) { Program.Invoke(Program.MainWindow, delegate() { using (var dlg = new ThreeButtonDialog( new ThreeButtonDialog.Details( SystemIcons.Error, FriendlyErrorNames.VBDS_MAX_ALLOWED, Messages.DISK_ATTACH))) { dlg.ShowDialog(Program.MainWindow); } }); // Give up return; } string ud = uds[0]; VBD vbd = new VBD(); vbd.VDI = new XenRef<VDI>(TheVDI); vbd.VM = new XenRef<VM>(TheVM); vbd.bootable = ud == "0"; vbd.device = ""; vbd.SetIsOwner(TheVDI.VBDs.Count == 0); vbd.empty = false; vbd.userdevice = ud; vbd.type = vbd_type.Disk; vbd.mode = ReadOnlyCheckBox.Checked ? vbd_mode.RO : vbd_mode.RW; vbd.unpluggable = true; // Try to hot plug the VBD. new VbdSaveAndPlugAction(TheVM, vbd, TheVDI.Name(), null, false,NewDiskDialog.ShowMustRebootBoxCD,NewDiskDialog.ShowVBDWarningBox).RunAsync(); }); Close(); } private void CancelBtn_Click(object sender, EventArgs e) { Close(); } private void AttachDiskDialog_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e) { // unsubscribe to events foreach (SR sr in connection.Cache.SRs) { sr.PropertyChanged -= new PropertyChangedEventHandler(Server_Changed); foreach (VDI TheVDI in sr.Connection.ResolveAllShownXenModelObjects(sr.VDIs, Properties.Settings.Default.ShowHiddenVMs)) { TheVDI.PropertyChanged -= new PropertyChangedEventHandler(Server_Changed); } } DiskListTreeView.SelectedIndexChanged -= DiskListTreeView_SelectedIndexChanged; if (poolofone != null) poolofone.PropertyChanged -= Server_Changed; connection.Cache.DeregisterCollectionChanged<SR>(SR_CollectionChangedWithInvoke); } } public class DiskListSrItem : CustomTreeNode { public enum DisabledReason { None, Broken, NotSeen }; public SR TheSR; public VM TheVM; public bool Show = false; public DisabledReason Reason; public DiskListSrItem(SR sr, VM vm) : base(false) { TheSR = sr; TheVM = vm; Update(); } private void Update() { Text = TheSR.NameWithoutHost(); Image = Images.GetImage16For(Images.GetIconFor(TheSR)); Host affinity = TheVM.Connection.Resolve<Host>(TheVM.affinity); Host activeHost = TheVM.Connection.Resolve<Host>(TheVM.resident_on); if (!TheSR.Show(Properties.Settings.Default.ShowHiddenVMs)) { Show = false; } else if (TheSR.content_type != SR.Content_Type_ISO && !((affinity != null && !TheSR.CanBeSeenFrom(affinity)) || (activeHost != null && TheVM.power_state == vm_power_state.Running && !TheSR.CanBeSeenFrom(activeHost)) || TheSR.IsBroken(false) || TheSR.PBDs.Count < 1)) { Description = ""; Enabled = true; Show = true; Reason = DisabledReason.None; } else if (((affinity != null && !TheSR.CanBeSeenFrom(affinity)) || (activeHost != null && TheVM.power_state == vm_power_state.Running && !TheSR.CanBeSeenFrom(activeHost))) && !TheSR.IsBroken(false) && TheSR.PBDs.Count < 1) { Description = string.Format(Messages.SR_CANNOT_BE_SEEN, Helpers.GetName(affinity)); Enabled = false; Show = true; Reason = DisabledReason.NotSeen; } else if (TheSR.IsBroken(false) && TheSR.PBDs.Count >= 1) { Description = Messages.SR_IS_BROKEN; Enabled = false; Show = true; Reason = DisabledReason.Broken; } else { Show = false; } } protected override int SameLevelSortOrder(CustomTreeNode other) { DiskListSrItem otherItem = other as DiskListSrItem; if (otherItem == null) //shouldnt ever happen!!! return -1; int rank = this.SrRank() - otherItem.SrRank(); if (rank == 0) return base.SameLevelSortOrder(other); else return rank; } public int SrRank() { if (Enabled && TheSR.VDIs.Count > 0) return 0; else return 1 + (int)Reason; } } public class DiskListVdiItem : CustomTreeNode, IEquatable<DiskListVdiItem> { public VDI TheVDI; public bool Show = false; public bool ForceReadOnly = false; public DiskListVdiItem(VDI vdi) { TheVDI = vdi; Update(); } private void Update() { if (TheVDI.type == vdi_type.crashdump || TheVDI.type == vdi_type.ephemeral || TheVDI.type == vdi_type.suspend) Show = false; else if ((TheVDI.VBDs.Count > 0 && !TheVDI.sharable)) { bool allRO = true; foreach (VBD vbd in TheVDI.Connection.ResolveAll<VBD>(TheVDI.VBDs)) { if (!vbd.IsReadOnly() && vbd.currently_attached) { allRO = false; break; } } Show = allRO; if (Show) { ForceReadOnly = true; Text = String.IsNullOrEmpty(TheVDI.Name()) ? Messages.NO_NAME : TheVDI.Name(); if (!string.IsNullOrEmpty(TheVDI.Description())) Description = string.Format(Messages.ATTACHDISK_SIZE_DESCRIPTION, TheVDI.Description(), Util.DiskSizeString(TheVDI.virtual_size)); else Description = Util.DiskSizeString(TheVDI.virtual_size); Image = Images.GetImage16For(Icons.VDI); } } else { Show = true; ForceReadOnly = TheVDI.read_only; Text = String.IsNullOrEmpty(TheVDI.Name()) ? Messages.NO_NAME : TheVDI.Name(); if (!string.IsNullOrEmpty(TheVDI.Description())) Description = string.Format(Messages.ATTACHDISK_SIZE_DESCRIPTION, TheVDI.Description(), Util.DiskSizeString(TheVDI.virtual_size)); else Description = Util.DiskSizeString(TheVDI.virtual_size); Image = Images.GetImage16For(Icons.VDI); } } public bool Equals(DiskListVdiItem other) { return this.TheVDI.opaque_ref == other.TheVDI.opaque_ref; } } }
using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Infrastructure; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Migrations; using AllReady.Models; namespace AllReady.Migrations { [DbContext(typeof(AllReadyContext))] [Migration("20151118232733_InitialRC1Schema")] partial class InitialRC1Schema { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "7.0.0-rc1-16341") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("AllReady.Models.Activity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("CampaignId"); b.Property<string>("Description"); b.Property<DateTime>("EndDateTimeUtc"); b.Property<string>("ImageUrl"); b.Property<int?>("LocationId"); b.Property<string>("Name") .IsRequired(); b.Property<int>("NumberOfVolunteersRequired"); b.Property<string>("OrganizerId"); b.Property<DateTime>("StartDateTimeUtc"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.ActivitySignup", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("ActivityId"); b.Property<string>("AdditionalInfo"); b.Property<DateTime?>("CheckinDateTime"); b.Property<string>("PreferredEmail"); b.Property<string>("PreferredPhoneNumber"); b.Property<DateTime>("SignupDateTime"); b.Property<string>("UserId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.ActivitySkill", b => { b.Property<int>("ActivityId"); b.Property<int>("SkillId"); b.HasKey("ActivityId", "SkillId"); }); modelBuilder.Entity("AllReady.Models.AllReadyTask", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("ActivityId"); b.Property<string>("Description"); b.Property<DateTimeOffset?>("EndDateTimeUtc"); b.Property<string>("Name") .IsRequired(); b.Property<int>("NumberOfVolunteersRequired"); b.Property<DateTimeOffset?>("StartDateTimeUtc"); b.Property<int?>("TenantId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.ApplicationUser", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasAnnotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("Name"); b.Property<string>("NormalizedEmail") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .HasAnnotation("MaxLength", 256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<int?>("TenantId"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasAnnotation("Relational:Name", "EmailIndex"); b.HasIndex("NormalizedUserName") .HasAnnotation("Relational:Name", "UserNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetUsers"); }); modelBuilder.Entity("AllReady.Models.Campaign", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("CampaignImpactId"); b.Property<string>("Description"); b.Property<DateTime>("EndDateTimeUtc"); b.Property<string>("FullDescription"); b.Property<string>("ImageUrl"); b.Property<int?>("LocationId"); b.Property<int>("ManagingTenantId"); b.Property<string>("Name") .IsRequired(); b.Property<string>("OrganizerId"); b.Property<DateTime>("StartDateTimeUtc"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.CampaignContact", b => { b.Property<int>("CampaignId"); b.Property<int>("ContactId"); b.Property<int>("ContactType"); b.HasKey("CampaignId", "ContactId", "ContactType"); }); modelBuilder.Entity("AllReady.Models.CampaignImpact", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("CurrentImpactLevel"); b.Property<bool>("Display"); b.Property<int>("ImpactType"); b.Property<int>("NumericImpactGoal"); b.Property<int>("PercentComplete"); b.Property<string>("TextualImpactGoal"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.CampaignSponsors", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("CampaignId"); b.Property<int?>("TenantId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.Contact", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Email"); b.Property<string>("FirstName"); b.Property<string>("LastName"); b.Property<string>("PhoneNumber"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.Location", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Address1"); b.Property<string>("Address2"); b.Property<string>("City"); b.Property<string>("Country"); b.Property<string>("Name"); b.Property<string>("PhoneNumber"); b.Property<string>("PostalCodePostalCode"); b.Property<string>("State"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.PostalCodeGeo", b => { b.Property<string>("PostalCode"); b.Property<string>("City"); b.Property<string>("State"); b.HasKey("PostalCode"); }); modelBuilder.Entity("AllReady.Models.Resource", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("CategoryTag"); b.Property<string>("Description"); b.Property<string>("MediaUrl"); b.Property<string>("Name"); b.Property<DateTime>("PublishDateBegin"); b.Property<DateTime>("PublishDateEnd"); b.Property<string>("ResourceUrl"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.Skill", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Description"); b.Property<string>("Name") .IsRequired(); b.Property<int?>("ParentSkillId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.TaskSignup", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Status"); b.Property<DateTime>("StatusDateTimeUtc"); b.Property<string>("StatusDescription"); b.Property<int?>("TaskId"); b.Property<string>("UserId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.TaskSkill", b => { b.Property<int>("TaskId"); b.Property<int>("SkillId"); b.HasKey("TaskId", "SkillId"); }); modelBuilder.Entity("AllReady.Models.Tenant", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("LocationId"); b.Property<string>("LogoUrl"); b.Property<string>("Name") .IsRequired(); b.Property<string>("WebUrl"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.TenantContact", b => { b.Property<int>("TenantId"); b.Property<int>("ContactId"); b.Property<int>("ContactType"); b.HasKey("TenantId", "ContactId", "ContactType"); }); modelBuilder.Entity("AllReady.Models.UserSkill", b => { b.Property<string>("UserId"); b.Property<int>("SkillId"); b.HasKey("UserId", "SkillId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasAnnotation("Relational:Name", "RoleNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasAnnotation("Relational:TableName", "AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasAnnotation("Relational:TableName", "AspNetUserRoles"); }); modelBuilder.Entity("AllReady.Models.Activity", b => { b.HasOne("AllReady.Models.Campaign") .WithMany() .HasForeignKey("CampaignId"); b.HasOne("AllReady.Models.Location") .WithMany() .HasForeignKey("LocationId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("OrganizerId"); }); modelBuilder.Entity("AllReady.Models.ActivitySignup", b => { b.HasOne("AllReady.Models.Activity") .WithMany() .HasForeignKey("ActivityId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("AllReady.Models.ActivitySkill", b => { b.HasOne("AllReady.Models.Activity") .WithMany() .HasForeignKey("ActivityId"); b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("SkillId"); }); modelBuilder.Entity("AllReady.Models.AllReadyTask", b => { b.HasOne("AllReady.Models.Activity") .WithMany() .HasForeignKey("ActivityId"); b.HasOne("AllReady.Models.Tenant") .WithMany() .HasForeignKey("TenantId"); }); modelBuilder.Entity("AllReady.Models.ApplicationUser", b => { b.HasOne("AllReady.Models.Tenant") .WithMany() .HasForeignKey("TenantId"); }); modelBuilder.Entity("AllReady.Models.Campaign", b => { b.HasOne("AllReady.Models.CampaignImpact") .WithMany() .HasForeignKey("CampaignImpactId"); b.HasOne("AllReady.Models.Location") .WithMany() .HasForeignKey("LocationId"); b.HasOne("AllReady.Models.Tenant") .WithMany() .HasForeignKey("ManagingTenantId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("OrganizerId"); }); modelBuilder.Entity("AllReady.Models.CampaignContact", b => { b.HasOne("AllReady.Models.Campaign") .WithMany() .HasForeignKey("CampaignId"); b.HasOne("AllReady.Models.Contact") .WithMany() .HasForeignKey("ContactId"); }); modelBuilder.Entity("AllReady.Models.CampaignSponsors", b => { b.HasOne("AllReady.Models.Campaign") .WithMany() .HasForeignKey("CampaignId"); b.HasOne("AllReady.Models.Tenant") .WithMany() .HasForeignKey("TenantId"); }); modelBuilder.Entity("AllReady.Models.Location", b => { b.HasOne("AllReady.Models.PostalCodeGeo") .WithMany() .HasForeignKey("PostalCodePostalCode"); }); modelBuilder.Entity("AllReady.Models.Skill", b => { b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("ParentSkillId"); }); modelBuilder.Entity("AllReady.Models.TaskSignup", b => { b.HasOne("AllReady.Models.AllReadyTask") .WithMany() .HasForeignKey("TaskId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("AllReady.Models.TaskSkill", b => { b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("SkillId"); b.HasOne("AllReady.Models.AllReadyTask") .WithMany() .HasForeignKey("TaskId"); }); modelBuilder.Entity("AllReady.Models.Tenant", b => { b.HasOne("AllReady.Models.Location") .WithMany() .HasForeignKey("LocationId"); }); modelBuilder.Entity("AllReady.Models.TenantContact", b => { b.HasOne("AllReady.Models.Contact") .WithMany() .HasForeignKey("ContactId"); b.HasOne("AllReady.Models.Tenant") .WithMany() .HasForeignKey("TenantId"); }); modelBuilder.Entity("AllReady.Models.UserSkill", b => { b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("SkillId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Hyak.Common; using Microsoft.WindowsAzure.Management.StorSimple; using Microsoft.WindowsAzure.Management.StorSimple.Models; namespace Microsoft.WindowsAzure.Management.StorSimple { /// <summary> /// All Operations related to Backup policies /// </summary> internal partial class BackupPolicyOperations : IServiceOperations<StorSimpleManagementClient>, IBackupPolicyOperations { /// <summary> /// Initializes a new instance of the BackupPolicyOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal BackupPolicyOperations(StorSimpleManagementClient client) { this._client = client; } private StorSimpleManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.StorSimple.StorSimpleManagementClient. /// </summary> public StorSimpleManagementClient Client { get { return this._client; } } /// <summary> /// The BeginCreatingBackupPolicy operation creates a new backup policy /// for this given volume with the given schedules. /// </summary> /// <param name='deviceId'> /// Required. The device id for which the call will be made. /// </param> /// <param name='backupPolicy'> /// Required. Parameters supplied to the Create Backup Policy operation. /// </param> /// <param name='customRequestHeaders'> /// Required. The Custom Request Headers which client must use. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// This is the Task Response for all Async Calls /// </returns> public async Task<TaskResponse> BeginCreatingBackupPolicyAsync(string deviceId, NewBackupPolicyConfig backupPolicy, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (deviceId == null) { throw new ArgumentNullException("deviceId"); } if (backupPolicy == null) { throw new ArgumentNullException("backupPolicy"); } if (backupPolicy.BackupSchedules == null) { throw new ArgumentNullException("backupPolicy.BackupSchedules"); } if (backupPolicy.BackupSchedules != null) { foreach (BackupScheduleBase backupSchedulesParameterItem in backupPolicy.BackupSchedules) { if (backupSchedulesParameterItem.Recurrence == null) { throw new ArgumentNullException("backupPolicy.BackupSchedules.Recurrence"); } if (backupSchedulesParameterItem.StartTime == null) { throw new ArgumentNullException("backupPolicy.BackupSchedules.StartTime"); } } } if (backupPolicy.Name == null) { throw new ArgumentNullException("backupPolicy.Name"); } if (backupPolicy.VolumeIds == null) { throw new ArgumentNullException("backupPolicy.VolumeIds"); } if (customRequestHeaders == null) { throw new ArgumentNullException("customRequestHeaders"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("deviceId", deviceId); tracingParameters.Add("backupPolicy", backupPolicy); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "BeginCreatingBackupPolicyAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/"; url = url + Uri.EscapeDataString(this.Client.CloudServiceName); url = url + "/resources/"; url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/~/"; url = url + "CisVault"; url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceName); url = url + "/api/devices/"; url = url + Uri.EscapeDataString(deviceId); url = url + "/policies"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-01-01.1.0"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/xml"); httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Language); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2014-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement addBackupPolicyRequestElement = new XElement(XName.Get("AddBackupPolicyRequest", "http://windowscloudbackup.com/CiS/V2013_03")); requestDoc.Add(addBackupPolicyRequestElement); XElement nameElement = new XElement(XName.Get("Name", "http://windowscloudbackup.com/CiS/V2013_03")); nameElement.Value = backupPolicy.Name; addBackupPolicyRequestElement.Add(nameElement); XElement schedulesSequenceElement = new XElement(XName.Get("Schedules", "http://windowscloudbackup.com/CiS/V2013_03")); foreach (BackupScheduleBase schedulesItem in backupPolicy.BackupSchedules) { XElement backupScheduleBaseElement = new XElement(XName.Get("BackupScheduleBase", "http://windowscloudbackup.com/CiS/V2013_03")); schedulesSequenceElement.Add(backupScheduleBaseElement); XElement backupTypeElement = new XElement(XName.Get("BackupType", "http://windowscloudbackup.com/CiS/V2013_03")); backupTypeElement.Value = schedulesItem.BackupType.ToString(); backupScheduleBaseElement.Add(backupTypeElement); XElement recurrenceElement = new XElement(XName.Get("Recurrence", "http://windowscloudbackup.com/CiS/V2013_03")); backupScheduleBaseElement.Add(recurrenceElement); XElement recurrenceTypeElement = new XElement(XName.Get("RecurrenceType", "http://windowscloudbackup.com/CiS/V2013_03")); recurrenceTypeElement.Value = schedulesItem.Recurrence.RecurrenceType.ToString(); recurrenceElement.Add(recurrenceTypeElement); XElement recurrenceValueElement = new XElement(XName.Get("RecurrenceValue", "http://windowscloudbackup.com/CiS/V2013_03")); recurrenceValueElement.Value = schedulesItem.Recurrence.RecurrenceValue.ToString(); recurrenceElement.Add(recurrenceValueElement); XElement retentionCountElement = new XElement(XName.Get("RetentionCount", "http://windowscloudbackup.com/CiS/V2013_03")); retentionCountElement.Value = schedulesItem.RetentionCount.ToString(); backupScheduleBaseElement.Add(retentionCountElement); XElement startTimeElement = new XElement(XName.Get("StartTime", "http://windowscloudbackup.com/CiS/V2013_03")); startTimeElement.Value = schedulesItem.StartTime; backupScheduleBaseElement.Add(startTimeElement); XElement statusElement = new XElement(XName.Get("Status", "http://windowscloudbackup.com/CiS/V2013_03")); statusElement.Value = schedulesItem.Status.ToString(); backupScheduleBaseElement.Add(statusElement); } addBackupPolicyRequestElement.Add(schedulesSequenceElement); XElement virtualDiskIdsSequenceElement = new XElement(XName.Get("VirtualDiskIds", "http://windowscloudbackup.com/CiS/V2013_03")); foreach (string virtualDiskIdsItem in backupPolicy.VolumeIds) { XElement virtualDiskIdsItemElement = new XElement(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/Arrays")); virtualDiskIdsItemElement.Value = virtualDiskIdsItem; virtualDiskIdsSequenceElement.Add(virtualDiskIdsItemElement); } addBackupPolicyRequestElement.Add(virtualDiskIdsSequenceElement); requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result TaskResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new TaskResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement stringElement = responseDoc.Element(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/")); if (stringElement != null) { string stringInstance = stringElement.Value; result.TaskId = stringInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Begin deleting a backup policy represented by the policyId provided. /// </summary> /// <param name='deviceId'> /// Required. The device id for which the call will be made. /// </param> /// <param name='policyId'> /// Required. The backup policy ID to delete. /// </param> /// <param name='customRequestHeaders'> /// Required. The Custom Request Headers which client must use. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// This is the Task Response for all Async Calls /// </returns> public async Task<TaskResponse> BeginDeletingAsync(string deviceId, string policyId, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (deviceId == null) { throw new ArgumentNullException("deviceId"); } if (policyId == null) { throw new ArgumentNullException("policyId"); } if (customRequestHeaders == null) { throw new ArgumentNullException("customRequestHeaders"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("deviceId", deviceId); tracingParameters.Add("policyId", policyId); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "BeginDeletingAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/"; url = url + Uri.EscapeDataString(this.Client.CloudServiceName); url = url + "/resources/"; url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/~/"; url = url + "CisVault"; url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceName); url = url + "/api/devices/"; url = url + Uri.EscapeDataString(deviceId); url = url + "/policies/"; url = url + Uri.EscapeDataString(policyId); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-01-01.1.0"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/xml"); httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Language); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2014-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result TaskResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new TaskResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement stringElement = responseDoc.Element(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/")); if (stringElement != null) { string stringInstance = stringElement.Value; result.TaskId = stringInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The BeginUpdatingBackupPolicy operation updates a backup policy /// represented by policyId for this given volume with the given /// schedules. /// </summary> /// <param name='deviceId'> /// Required. The device id for which the call will be made. /// </param> /// <param name='policyId'> /// Required. The backup policy ID to update. /// </param> /// <param name='policyInfo'> /// Required. Parameters supplied to the Update Backup Policy operation. /// </param> /// <param name='customRequestHeaders'> /// Required. The Custom Request Headers which client must use. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// This is the Task Response for all Async Calls /// </returns> public async Task<TaskResponse> BeginUpdatingBackupPolicyAsync(string deviceId, string policyId, UpdateBackupPolicyConfig policyInfo, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (deviceId == null) { throw new ArgumentNullException("deviceId"); } if (policyId == null) { throw new ArgumentNullException("policyId"); } if (policyInfo == null) { throw new ArgumentNullException("policyInfo"); } if (policyInfo.BackupSchedulesToBeAdded != null) { foreach (BackupScheduleBase backupSchedulesToBeAddedParameterItem in policyInfo.BackupSchedulesToBeAdded) { if (backupSchedulesToBeAddedParameterItem.Recurrence == null) { throw new ArgumentNullException("policyInfo.BackupSchedulesToBeAdded.Recurrence"); } if (backupSchedulesToBeAddedParameterItem.StartTime == null) { throw new ArgumentNullException("policyInfo.BackupSchedulesToBeAdded.StartTime"); } } } if (policyInfo.BackupSchedulesToBeUpdated != null) { foreach (BackupScheduleUpdateRequest backupSchedulesToBeUpdatedParameterItem in policyInfo.BackupSchedulesToBeUpdated) { if (backupSchedulesToBeUpdatedParameterItem.Id == null) { throw new ArgumentNullException("policyInfo.BackupSchedulesToBeUpdated.Id"); } if (backupSchedulesToBeUpdatedParameterItem.Recurrence == null) { throw new ArgumentNullException("policyInfo.BackupSchedulesToBeUpdated.Recurrence"); } if (backupSchedulesToBeUpdatedParameterItem.StartTime == null) { throw new ArgumentNullException("policyInfo.BackupSchedulesToBeUpdated.StartTime"); } } } if (policyInfo.Name == null) { throw new ArgumentNullException("policyInfo.Name"); } if (customRequestHeaders == null) { throw new ArgumentNullException("customRequestHeaders"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("deviceId", deviceId); tracingParameters.Add("policyId", policyId); tracingParameters.Add("policyInfo", policyInfo); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "BeginUpdatingBackupPolicyAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/"; url = url + Uri.EscapeDataString(this.Client.CloudServiceName); url = url + "/resources/"; url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/~/"; url = url + "CisVault"; url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceName); url = url + "/api/devices/"; url = url + Uri.EscapeDataString(deviceId); url = url + "/policies/"; url = url + Uri.EscapeDataString(policyId); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-01-01.1.0"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/xml"); httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Language); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2014-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement updateBackupPolicyRequestElement = new XElement(XName.Get("UpdateBackupPolicyRequest", "http://windowscloudbackup.com/CiS/V2013_03")); requestDoc.Add(updateBackupPolicyRequestElement); if (policyInfo.InstanceId != null) { XElement instanceIdElement = new XElement(XName.Get("InstanceId", "http://windowscloudbackup.com/CiS/V2013_03")); instanceIdElement.Value = policyInfo.InstanceId; updateBackupPolicyRequestElement.Add(instanceIdElement); } XElement nameElement = new XElement(XName.Get("Name", "http://windowscloudbackup.com/CiS/V2013_03")); nameElement.Value = policyInfo.Name; updateBackupPolicyRequestElement.Add(nameElement); XElement operationInProgressElement = new XElement(XName.Get("OperationInProgress", "http://windowscloudbackup.com/CiS/V2013_03")); operationInProgressElement.Value = policyInfo.OperationInProgress.ToString(); updateBackupPolicyRequestElement.Add(operationInProgressElement); if (policyInfo.BackupSchedulesToBeAdded != null) { XElement backupSchedulesToBeAddedSequenceElement = new XElement(XName.Get("BackupSchedulesToBeAdded", "http://windowscloudbackup.com/CiS/V2013_03")); foreach (BackupScheduleBase backupSchedulesToBeAddedItem in policyInfo.BackupSchedulesToBeAdded) { XElement backupScheduleBaseElement = new XElement(XName.Get("BackupScheduleBase", "http://windowscloudbackup.com/CiS/V2013_03")); backupSchedulesToBeAddedSequenceElement.Add(backupScheduleBaseElement); XElement backupTypeElement = new XElement(XName.Get("BackupType", "http://windowscloudbackup.com/CiS/V2013_03")); backupTypeElement.Value = backupSchedulesToBeAddedItem.BackupType.ToString(); backupScheduleBaseElement.Add(backupTypeElement); XElement recurrenceElement = new XElement(XName.Get("Recurrence", "http://windowscloudbackup.com/CiS/V2013_03")); backupScheduleBaseElement.Add(recurrenceElement); XElement recurrenceTypeElement = new XElement(XName.Get("RecurrenceType", "http://windowscloudbackup.com/CiS/V2013_03")); recurrenceTypeElement.Value = backupSchedulesToBeAddedItem.Recurrence.RecurrenceType.ToString(); recurrenceElement.Add(recurrenceTypeElement); XElement recurrenceValueElement = new XElement(XName.Get("RecurrenceValue", "http://windowscloudbackup.com/CiS/V2013_03")); recurrenceValueElement.Value = backupSchedulesToBeAddedItem.Recurrence.RecurrenceValue.ToString(); recurrenceElement.Add(recurrenceValueElement); XElement retentionCountElement = new XElement(XName.Get("RetentionCount", "http://windowscloudbackup.com/CiS/V2013_03")); retentionCountElement.Value = backupSchedulesToBeAddedItem.RetentionCount.ToString(); backupScheduleBaseElement.Add(retentionCountElement); XElement startTimeElement = new XElement(XName.Get("StartTime", "http://windowscloudbackup.com/CiS/V2013_03")); startTimeElement.Value = backupSchedulesToBeAddedItem.StartTime; backupScheduleBaseElement.Add(startTimeElement); XElement statusElement = new XElement(XName.Get("Status", "http://windowscloudbackup.com/CiS/V2013_03")); statusElement.Value = backupSchedulesToBeAddedItem.Status.ToString(); backupScheduleBaseElement.Add(statusElement); } updateBackupPolicyRequestElement.Add(backupSchedulesToBeAddedSequenceElement); } else { XElement emptyElement = new XElement(XName.Get("BackupSchedulesToBeAdded", "http://windowscloudbackup.com/CiS/V2013_03")); XAttribute nilAttribute = new XAttribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance"), ""); nilAttribute.Value = "true"; emptyElement.Add(nilAttribute); updateBackupPolicyRequestElement.Add(emptyElement); } if (policyInfo.BackupSchedulesToBeDeleted != null) { XElement backupSchedulesToBeDeletedSequenceElement = new XElement(XName.Get("BackupSchedulesToBeDeleted", "http://windowscloudbackup.com/CiS/V2013_03")); foreach (string backupSchedulesToBeDeletedItem in policyInfo.BackupSchedulesToBeDeleted) { XElement backupSchedulesToBeDeletedItemElement = new XElement(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/Arrays")); backupSchedulesToBeDeletedItemElement.Value = backupSchedulesToBeDeletedItem; backupSchedulesToBeDeletedSequenceElement.Add(backupSchedulesToBeDeletedItemElement); } updateBackupPolicyRequestElement.Add(backupSchedulesToBeDeletedSequenceElement); } else { XElement emptyElement2 = new XElement(XName.Get("BackupSchedulesToBeDeleted", "http://windowscloudbackup.com/CiS/V2013_03")); XAttribute nilAttribute2 = new XAttribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance"), ""); nilAttribute2.Value = "true"; emptyElement2.Add(nilAttribute2); updateBackupPolicyRequestElement.Add(emptyElement2); } if (policyInfo.BackupSchedulesToBeUpdated != null) { XElement backupSchedulesToBeUpdatedSequenceElement = new XElement(XName.Get("BackupSchedulesToBeUpdated", "http://windowscloudbackup.com/CiS/V2013_03")); foreach (BackupScheduleUpdateRequest backupSchedulesToBeUpdatedItem in policyInfo.BackupSchedulesToBeUpdated) { XElement backupScheduleUpdateRequestElement = new XElement(XName.Get("BackupScheduleUpdateRequest", "http://windowscloudbackup.com/CiS/V2013_03")); backupSchedulesToBeUpdatedSequenceElement.Add(backupScheduleUpdateRequestElement); XElement backupTypeElement2 = new XElement(XName.Get("BackupType", "http://windowscloudbackup.com/CiS/V2013_03")); backupTypeElement2.Value = backupSchedulesToBeUpdatedItem.BackupType.ToString(); backupScheduleUpdateRequestElement.Add(backupTypeElement2); XElement recurrenceElement2 = new XElement(XName.Get("Recurrence", "http://windowscloudbackup.com/CiS/V2013_03")); backupScheduleUpdateRequestElement.Add(recurrenceElement2); XElement recurrenceTypeElement2 = new XElement(XName.Get("RecurrenceType", "http://windowscloudbackup.com/CiS/V2013_03")); recurrenceTypeElement2.Value = backupSchedulesToBeUpdatedItem.Recurrence.RecurrenceType.ToString(); recurrenceElement2.Add(recurrenceTypeElement2); XElement recurrenceValueElement2 = new XElement(XName.Get("RecurrenceValue", "http://windowscloudbackup.com/CiS/V2013_03")); recurrenceValueElement2.Value = backupSchedulesToBeUpdatedItem.Recurrence.RecurrenceValue.ToString(); recurrenceElement2.Add(recurrenceValueElement2); XElement retentionCountElement2 = new XElement(XName.Get("RetentionCount", "http://windowscloudbackup.com/CiS/V2013_03")); retentionCountElement2.Value = backupSchedulesToBeUpdatedItem.RetentionCount.ToString(); backupScheduleUpdateRequestElement.Add(retentionCountElement2); XElement startTimeElement2 = new XElement(XName.Get("StartTime", "http://windowscloudbackup.com/CiS/V2013_03")); startTimeElement2.Value = backupSchedulesToBeUpdatedItem.StartTime; backupScheduleUpdateRequestElement.Add(startTimeElement2); XElement statusElement2 = new XElement(XName.Get("Status", "http://windowscloudbackup.com/CiS/V2013_03")); statusElement2.Value = backupSchedulesToBeUpdatedItem.Status.ToString(); backupScheduleUpdateRequestElement.Add(statusElement2); XElement idElement = new XElement(XName.Get("Id", "http://windowscloudbackup.com/CiS/V2013_03")); idElement.Value = backupSchedulesToBeUpdatedItem.Id; backupScheduleUpdateRequestElement.Add(idElement); } updateBackupPolicyRequestElement.Add(backupSchedulesToBeUpdatedSequenceElement); } else { XElement emptyElement3 = new XElement(XName.Get("BackupSchedulesToBeUpdated", "http://windowscloudbackup.com/CiS/V2013_03")); XAttribute nilAttribute3 = new XAttribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance"), ""); nilAttribute3.Value = "true"; emptyElement3.Add(nilAttribute3); updateBackupPolicyRequestElement.Add(emptyElement3); } XElement isPolicyRenamedElement = new XElement(XName.Get("IsPolicyRenamed", "http://windowscloudbackup.com/CiS/V2013_03")); isPolicyRenamedElement.Value = policyInfo.IsPolicyRenamed.ToString().ToLower(); updateBackupPolicyRequestElement.Add(isPolicyRenamedElement); if (policyInfo.VolumeIds != null) { XElement virtualDiskIdsSequenceElement = new XElement(XName.Get("VirtualDiskIds", "http://windowscloudbackup.com/CiS/V2013_03")); foreach (string virtualDiskIdsItem in policyInfo.VolumeIds) { XElement virtualDiskIdsItemElement = new XElement(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/Arrays")); virtualDiskIdsItemElement.Value = virtualDiskIdsItem; virtualDiskIdsSequenceElement.Add(virtualDiskIdsItemElement); } updateBackupPolicyRequestElement.Add(virtualDiskIdsSequenceElement); } else { XElement emptyElement4 = new XElement(XName.Get("VirtualDiskIds", "http://windowscloudbackup.com/CiS/V2013_03")); XAttribute nilAttribute4 = new XAttribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance"), ""); nilAttribute4.Value = "true"; emptyElement4.Add(nilAttribute4); updateBackupPolicyRequestElement.Add(emptyElement4); } requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result TaskResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new TaskResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement stringElement = responseDoc.Element(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/")); if (stringElement != null) { string stringInstance = stringElement.Value; result.TaskId = stringInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <param name='deviceId'> /// Required. The device id for which the call will be made. /// </param> /// <param name='backupPolicy'> /// Required. Parameters supplied to the Create Backup Policy operation. /// </param> /// <param name='customRequestHeaders'> /// Required. The Custom Request Headers which client must use. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Info about the async task /// </returns> public async Task<TaskStatusInfo> CreateAsync(string deviceId, NewBackupPolicyConfig backupPolicy, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { StorSimpleManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("deviceId", deviceId); tracingParameters.Add("backupPolicy", backupPolicy); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); TaskResponse response = await client.BackupPolicy.BeginCreatingBackupPolicyAsync(deviceId, backupPolicy, customRequestHeaders, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); TaskStatusInfo result = await client.GetOperationStatusAsync(response.TaskId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 5; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.AsyncTaskAggregatedResult != AsyncTaskAggregatedResult.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.TaskId, cancellationToken).ConfigureAwait(false); delayInSeconds = 5; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } if (result.AsyncTaskAggregatedResult != AsyncTaskAggregatedResult.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.Error = new CloudError(); ex.Error.Code = result.Error.Code; ex.Error.Message = result.Error.Message; if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } } return result; } /// <param name='deviceId'> /// Required. The device id for which the call will be made. /// </param> /// <param name='policyId'> /// Required. The backup policy ID to delete. /// </param> /// <param name='customRequestHeaders'> /// Required. The Custom Request Headers which client must use. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Info about the async task /// </returns> public async Task<TaskStatusInfo> DeleteAsync(string deviceId, string policyId, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { StorSimpleManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("deviceId", deviceId); tracingParameters.Add("policyId", policyId); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); TaskResponse response = await client.BackupPolicy.BeginDeletingAsync(deviceId, policyId, customRequestHeaders, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); TaskStatusInfo result = await client.GetOperationStatusAsync(response.TaskId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 5; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.AsyncTaskAggregatedResult != AsyncTaskAggregatedResult.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.TaskId, cancellationToken).ConfigureAwait(false); delayInSeconds = 5; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } if (result.AsyncTaskAggregatedResult != AsyncTaskAggregatedResult.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.Error = new CloudError(); ex.Error.Code = result.Error.Code; ex.Error.Message = result.Error.Message; if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } } return result; } /// <param name='deviceId'> /// Required. The device id for which the call will be made. /// </param> /// <param name='policyName'> /// Required. The name of the policy to fetch backup policy details by. /// </param> /// <param name='customRequestHeaders'> /// Required. The Custom Request Headers which client must use. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list of backup policies. /// </returns> public async Task<GetBackupPolicyDetailsResponse> GetBackupPolicyDetailsByNameAsync(string deviceId, string policyName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (deviceId == null) { throw new ArgumentNullException("deviceId"); } if (policyName == null) { throw new ArgumentNullException("policyName"); } if (customRequestHeaders == null) { throw new ArgumentNullException("customRequestHeaders"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("deviceId", deviceId); tracingParameters.Add("policyName", policyName); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "GetBackupPolicyDetailsByNameAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/"; url = url + Uri.EscapeDataString(this.Client.CloudServiceName); url = url + "/resources/"; url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/~/"; url = url + "CisVault"; url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceName); url = url + "/api/devices/"; url = url + Uri.EscapeDataString(deviceId); url = url + "/policies"; List<string> queryParameters = new List<string>(); queryParameters.Add("policyName=" + Uri.EscapeDataString(policyName)); queryParameters.Add("api-version=2014-01-01.1.0"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/xml"); httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Language); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2014-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result GetBackupPolicyDetailsResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new GetBackupPolicyDetailsResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement backupPolicyDetailsElement = responseDoc.Element(XName.Get("BackupPolicyDetails", "http://windowscloudbackup.com/CiS/V2013_03")); if (backupPolicyDetailsElement != null) { BackupPolicyDetails backupPolicyDetailsInstance = new BackupPolicyDetails(); result.BackupPolicyDetails = backupPolicyDetailsInstance; XElement schedulesSequenceElement = backupPolicyDetailsElement.Element(XName.Get("Schedules", "http://windowscloudbackup.com/CiS/V2013_03")); if (schedulesSequenceElement != null) { foreach (XElement schedulesElement in schedulesSequenceElement.Elements(XName.Get("BackupScheduleResponse", "http://windowscloudbackup.com/CiS/V2013_03"))) { BackupScheduleDetails backupScheduleResponseInstance = new BackupScheduleDetails(); backupPolicyDetailsInstance.BackupSchedules.Add(backupScheduleResponseInstance); XElement lastSuccessfulRunElement = schedulesElement.Element(XName.Get("LastSuccessfulRun", "http://windowscloudbackup.com/CiS/V2013_03")); if (lastSuccessfulRunElement != null) { DateTime lastSuccessfulRunInstance = DateTime.Parse(lastSuccessfulRunElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); backupScheduleResponseInstance.LastSuccessfulRun = lastSuccessfulRunInstance; } XElement idElement = schedulesElement.Element(XName.Get("Id", "http://windowscloudbackup.com/CiS/V2013_03")); if (idElement != null) { string idInstance = idElement.Value; backupScheduleResponseInstance.Id = idInstance; } XElement backupTypeElement = schedulesElement.Element(XName.Get("BackupType", "http://windowscloudbackup.com/CiS/V2013_03")); if (backupTypeElement != null) { BackupType backupTypeInstance = ((BackupType)Enum.Parse(typeof(BackupType), backupTypeElement.Value, true)); backupScheduleResponseInstance.BackupType = backupTypeInstance; } XElement recurrenceElement = schedulesElement.Element(XName.Get("Recurrence", "http://windowscloudbackup.com/CiS/V2013_03")); if (recurrenceElement != null) { ScheduleRecurrence recurrenceInstance = new ScheduleRecurrence(); backupScheduleResponseInstance.Recurrence = recurrenceInstance; XElement recurrenceTypeElement = recurrenceElement.Element(XName.Get("RecurrenceType", "http://windowscloudbackup.com/CiS/V2013_03")); if (recurrenceTypeElement != null) { RecurrenceType recurrenceTypeInstance = ((RecurrenceType)Enum.Parse(typeof(RecurrenceType), recurrenceTypeElement.Value, true)); recurrenceInstance.RecurrenceType = recurrenceTypeInstance; } XElement recurrenceValueElement = recurrenceElement.Element(XName.Get("RecurrenceValue", "http://windowscloudbackup.com/CiS/V2013_03")); if (recurrenceValueElement != null) { int recurrenceValueInstance = int.Parse(recurrenceValueElement.Value, CultureInfo.InvariantCulture); recurrenceInstance.RecurrenceValue = recurrenceValueInstance; } } XElement retentionCountElement = schedulesElement.Element(XName.Get("RetentionCount", "http://windowscloudbackup.com/CiS/V2013_03")); if (retentionCountElement != null) { long retentionCountInstance = long.Parse(retentionCountElement.Value, CultureInfo.InvariantCulture); backupScheduleResponseInstance.RetentionCount = retentionCountInstance; } XElement startTimeElement = schedulesElement.Element(XName.Get("StartTime", "http://windowscloudbackup.com/CiS/V2013_03")); if (startTimeElement != null) { string startTimeInstance = startTimeElement.Value; backupScheduleResponseInstance.StartTime = startTimeInstance; } XElement statusElement = schedulesElement.Element(XName.Get("Status", "http://windowscloudbackup.com/CiS/V2013_03")); if (statusElement != null) { ScheduleStatus statusInstance = ((ScheduleStatus)Enum.Parse(typeof(ScheduleStatus), statusElement.Value, true)); backupScheduleResponseInstance.Status = statusInstance; } } } XElement virtualDisksSequenceElement = backupPolicyDetailsElement.Element(XName.Get("VirtualDisks", "http://windowscloudbackup.com/CiS/V2013_03")); if (virtualDisksSequenceElement != null) { foreach (XElement virtualDisksElement in virtualDisksSequenceElement.Elements(XName.Get("VirtualDiskPolicyInfo", "http://windowscloudbackup.com/CiS/V2013_03"))) { VolumePolicyInfo virtualDiskPolicyInfoInstance = new VolumePolicyInfo(); backupPolicyDetailsInstance.Volumes.Add(virtualDiskPolicyInfoInstance); XElement associatedBackupPoliciesSequenceElement = virtualDisksElement.Element(XName.Get("AssociatedBackupPolicies", "http://windowscloudbackup.com/CiS/V2013_03")); if (associatedBackupPoliciesSequenceElement != null) { foreach (XElement associatedBackupPoliciesElement in associatedBackupPoliciesSequenceElement.Elements(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/Arrays"))) { virtualDiskPolicyInfoInstance.AssociatedBackupPolicies.Add(associatedBackupPoliciesElement.Value); } } XElement dataContainerIdElement = virtualDisksElement.Element(XName.Get("DataContainerId", "http://windowscloudbackup.com/CiS/V2013_03")); if (dataContainerIdElement != null) { string dataContainerIdInstance = dataContainerIdElement.Value; virtualDiskPolicyInfoInstance.DataContainerId = dataContainerIdInstance; } XElement dataContainerNameElement = virtualDisksElement.Element(XName.Get("DataContainerName", "http://windowscloudbackup.com/CiS/V2013_03")); if (dataContainerNameElement != null) { string dataContainerNameInstance = dataContainerNameElement.Value; virtualDiskPolicyInfoInstance.DataContainerName = dataContainerNameInstance; } XElement nameElement = virtualDisksElement.Element(XName.Get("Name", "http://windowscloudbackup.com/CiS/V2013_03")); if (nameElement != null) { string nameInstance = nameElement.Value; virtualDiskPolicyInfoInstance.Name = nameInstance; } XElement instanceIdElement = virtualDisksElement.Element(XName.Get("InstanceId", "http://windowscloudbackup.com/CiS/V2013_03")); if (instanceIdElement != null) { string instanceIdInstance = instanceIdElement.Value; virtualDiskPolicyInfoInstance.InstanceId = instanceIdInstance; } XElement operationInProgressElement = virtualDisksElement.Element(XName.Get("OperationInProgress", "http://windowscloudbackup.com/CiS/V2013_03")); if (operationInProgressElement != null) { OperationInProgress operationInProgressInstance = ((OperationInProgress)Enum.Parse(typeof(OperationInProgress), operationInProgressElement.Value, true)); virtualDiskPolicyInfoInstance.OperationInProgress = operationInProgressInstance; } } } XElement volumesCountElement = backupPolicyDetailsElement.Element(XName.Get("VolumesCount", "http://windowscloudbackup.com/CiS/V2013_03")); if (volumesCountElement != null) { long volumesCountInstance = long.Parse(volumesCountElement.Value, CultureInfo.InvariantCulture); backupPolicyDetailsInstance.VolumesCount = volumesCountInstance; } XElement schedulesCountElement = backupPolicyDetailsElement.Element(XName.Get("SchedulesCount", "http://windowscloudbackup.com/CiS/V2013_03")); if (schedulesCountElement != null) { long schedulesCountInstance = long.Parse(schedulesCountElement.Value, CultureInfo.InvariantCulture); backupPolicyDetailsInstance.SchedulesCount = schedulesCountInstance; } XElement nextBackupElement = backupPolicyDetailsElement.Element(XName.Get("NextBackup", "http://windowscloudbackup.com/CiS/V2013_03")); if (nextBackupElement != null) { DateTime nextBackupInstance = DateTime.Parse(nextBackupElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); backupPolicyDetailsInstance.NextBackup = nextBackupInstance; } XElement lastBackupElement = backupPolicyDetailsElement.Element(XName.Get("LastBackup", "http://windowscloudbackup.com/CiS/V2013_03")); if (lastBackupElement != null && !string.IsNullOrEmpty(lastBackupElement.Value)) { DateTime lastBackupInstance = DateTime.Parse(lastBackupElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); backupPolicyDetailsInstance.LastBackup = lastBackupInstance; } XElement backupPolicyCreationTypeElement = backupPolicyDetailsElement.Element(XName.Get("BackupPolicyCreationType", "http://windowscloudbackup.com/CiS/V2013_03")); if (backupPolicyCreationTypeElement != null) { BackupPolicyCreationType backupPolicyCreationTypeInstance = ((BackupPolicyCreationType)Enum.Parse(typeof(BackupPolicyCreationType), backupPolicyCreationTypeElement.Value, true)); backupPolicyDetailsInstance.BackupPolicyCreationType = backupPolicyCreationTypeInstance; } XElement sSMHostNameElement = backupPolicyDetailsElement.Element(XName.Get("SSMHostName", "http://windowscloudbackup.com/CiS/V2013_03")); if (sSMHostNameElement != null) { string sSMHostNameInstance = sSMHostNameElement.Value; backupPolicyDetailsInstance.SSMHostName = sSMHostNameInstance; } XElement nameElement2 = backupPolicyDetailsElement.Element(XName.Get("Name", "http://windowscloudbackup.com/CiS/V2013_03")); if (nameElement2 != null) { string nameInstance2 = nameElement2.Value; backupPolicyDetailsInstance.Name = nameInstance2; } XElement instanceIdElement2 = backupPolicyDetailsElement.Element(XName.Get("InstanceId", "http://windowscloudbackup.com/CiS/V2013_03")); if (instanceIdElement2 != null) { string instanceIdInstance2 = instanceIdElement2.Value; backupPolicyDetailsInstance.InstanceId = instanceIdInstance2; } XElement operationInProgressElement2 = backupPolicyDetailsElement.Element(XName.Get("OperationInProgress", "http://windowscloudbackup.com/CiS/V2013_03")); if (operationInProgressElement2 != null) { OperationInProgress operationInProgressInstance2 = ((OperationInProgress)Enum.Parse(typeof(OperationInProgress), operationInProgressElement2.Value, true)); backupPolicyDetailsInstance.OperationInProgress = operationInProgressInstance2; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <param name='deviceId'> /// Required. The device id for which the call will be made. /// </param> /// <param name='customRequestHeaders'> /// Required. The Custom Request Headers which client must use. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list of backup policies. /// </returns> public async Task<BackupPolicyListResponse> ListAsync(string deviceId, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (deviceId == null) { throw new ArgumentNullException("deviceId"); } if (customRequestHeaders == null) { throw new ArgumentNullException("customRequestHeaders"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("deviceId", deviceId); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/"; url = url + Uri.EscapeDataString(this.Client.CloudServiceName); url = url + "/resources/"; url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/~/"; url = url + "CisVault"; url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceName); url = url + "/api/devices/"; url = url + Uri.EscapeDataString(deviceId); url = url + "/policies"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-01-01.1.0"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/xml"); httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Language); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2014-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result BackupPolicyListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new BackupPolicyListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement arrayOfBackupPolicySequenceElement = responseDoc.Element(XName.Get("ArrayOfBackupPolicy", "http://windowscloudbackup.com/CiS/V2013_03")); if (arrayOfBackupPolicySequenceElement != null) { foreach (XElement arrayOfBackupPolicyElement in arrayOfBackupPolicySequenceElement.Elements(XName.Get("BackupPolicy", "http://windowscloudbackup.com/CiS/V2013_03"))) { BackupPolicy backupPolicyInstance = new BackupPolicy(); result.BackupPolicies.Add(backupPolicyInstance); XElement volumesCountElement = arrayOfBackupPolicyElement.Element(XName.Get("VolumesCount", "http://windowscloudbackup.com/CiS/V2013_03")); if (volumesCountElement != null) { long volumesCountInstance = long.Parse(volumesCountElement.Value, CultureInfo.InvariantCulture); backupPolicyInstance.VolumesCount = volumesCountInstance; } XElement schedulesCountElement = arrayOfBackupPolicyElement.Element(XName.Get("SchedulesCount", "http://windowscloudbackup.com/CiS/V2013_03")); if (schedulesCountElement != null) { long schedulesCountInstance = long.Parse(schedulesCountElement.Value, CultureInfo.InvariantCulture); backupPolicyInstance.SchedulesCount = schedulesCountInstance; } XElement nextBackupElement = arrayOfBackupPolicyElement.Element(XName.Get("NextBackup", "http://windowscloudbackup.com/CiS/V2013_03")); if (nextBackupElement != null) { DateTime nextBackupInstance = DateTime.Parse(nextBackupElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); backupPolicyInstance.NextBackup = nextBackupInstance; } XElement lastBackupElement = arrayOfBackupPolicyElement.Element(XName.Get("LastBackup", "http://windowscloudbackup.com/CiS/V2013_03")); if (lastBackupElement != null && !string.IsNullOrEmpty(lastBackupElement.Value)) { DateTime lastBackupInstance = DateTime.Parse(lastBackupElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); backupPolicyInstance.LastBackup = lastBackupInstance; } XElement backupPolicyCreationTypeElement = arrayOfBackupPolicyElement.Element(XName.Get("BackupPolicyCreationType", "http://windowscloudbackup.com/CiS/V2013_03")); if (backupPolicyCreationTypeElement != null) { BackupPolicyCreationType backupPolicyCreationTypeInstance = ((BackupPolicyCreationType)Enum.Parse(typeof(BackupPolicyCreationType), backupPolicyCreationTypeElement.Value, true)); backupPolicyInstance.BackupPolicyCreationType = backupPolicyCreationTypeInstance; } XElement sSMHostNameElement = arrayOfBackupPolicyElement.Element(XName.Get("SSMHostName", "http://windowscloudbackup.com/CiS/V2013_03")); if (sSMHostNameElement != null) { string sSMHostNameInstance = sSMHostNameElement.Value; backupPolicyInstance.SSMHostName = sSMHostNameInstance; } XElement nameElement = arrayOfBackupPolicyElement.Element(XName.Get("Name", "http://windowscloudbackup.com/CiS/V2013_03")); if (nameElement != null) { string nameInstance = nameElement.Value; backupPolicyInstance.Name = nameInstance; } XElement instanceIdElement = arrayOfBackupPolicyElement.Element(XName.Get("InstanceId", "http://windowscloudbackup.com/CiS/V2013_03")); if (instanceIdElement != null) { string instanceIdInstance = instanceIdElement.Value; backupPolicyInstance.InstanceId = instanceIdInstance; } XElement operationInProgressElement = arrayOfBackupPolicyElement.Element(XName.Get("OperationInProgress", "http://windowscloudbackup.com/CiS/V2013_03")); if (operationInProgressElement != null) { OperationInProgress operationInProgressInstance = ((OperationInProgress)Enum.Parse(typeof(OperationInProgress), operationInProgressElement.Value, true)); backupPolicyInstance.OperationInProgress = operationInProgressInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <param name='deviceId'> /// Required. The device id for which the call will be made. /// </param> /// <param name='policyId'> /// Required. The backup policy ID to update. /// </param> /// <param name='policyInfo'> /// Required. Parameters supplied to the Create Backup Policy operation. /// </param> /// <param name='customRequestHeaders'> /// Required. The Custom Request Headers which client must use. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Info about the async task /// </returns> public async Task<TaskStatusInfo> UpdateAsync(string deviceId, string policyId, UpdateBackupPolicyConfig policyInfo, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { StorSimpleManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("deviceId", deviceId); tracingParameters.Add("policyId", policyId); tracingParameters.Add("policyInfo", policyInfo); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "UpdateAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); TaskResponse response = await client.BackupPolicy.BeginUpdatingBackupPolicyAsync(deviceId, policyId, policyInfo, customRequestHeaders, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); TaskStatusInfo result = await client.GetOperationStatusAsync(response.TaskId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 5; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.AsyncTaskAggregatedResult != AsyncTaskAggregatedResult.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.TaskId, cancellationToken).ConfigureAwait(false); delayInSeconds = 5; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } if (result.AsyncTaskAggregatedResult != AsyncTaskAggregatedResult.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.Error = new CloudError(); ex.Error.Code = result.Error.Code; ex.Error.Message = result.Error.Message; if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } } return result; } } }
/* * 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 log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Threading; namespace OpenSim.Region.CoreModules.Scripting.LSLHttp { /// <summary> /// Data describing an external URL set up by a script. /// </summary> public class UrlData { /// <summary> /// Scene object part hosting the script /// </summary> public UUID hostID; /// <summary> /// The item ID of the script that requested the URL. /// </summary> public UUID itemID; /// <summary> /// The script engine that runs the script. /// </summary> public IScriptModule engine; /// <summary> /// The generated URL. /// </summary> public string url; /// <summary> /// The random UUID component of the generated URL. /// </summary> public UUID urlcode; /// <summary> /// The external requests currently being processed or awaiting retrieval for this URL. /// </summary> public ThreadedClasses.RwLockedDictionary<UUID, RequestData> requests; } public class RequestData { public UUID requestID; public Dictionary<string, string> headers; public string body; public int responseCode; public string responseBody; public string responseType = "text/plain"; //public ManualResetEvent ev; public bool requestDone; public int startTime; public string uri; } /// <summary> /// This module provides external URLs for in-world scripts. /// </summary> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "UrlModule")] public class UrlModule : ISharedRegionModule, IUrlModule { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Indexs the URL request metadata (which script requested it, outstanding requests, etc.) by the request ID /// randomly generated when a request is received for this URL. /// </summary> /// <remarks> /// Manipulation or retrieval from this dictionary must be locked on m_UrlMap to preserve consistency with /// m_UrlMap /// </remarks> private ThreadedClasses.RwLockedDictionary<UUID, UrlData> m_RequestMap = new ThreadedClasses.RwLockedDictionary<UUID, UrlData>(); /// <summary> /// Indexs the URL request metadata (which script requested it, outstanding requests, etc.) by the full URL /// </summary> private ThreadedClasses.RwLockedDictionary<string, UrlData> m_UrlMap = new ThreadedClasses.RwLockedDictionary<string, UrlData>(); private uint m_HttpsPort = 0; private IHttpServer m_HttpServer = null; private IHttpServer m_HttpsServer = null; public string ExternalHostNameForLSL { get; private set; } /// <summary> /// The default maximum number of urls /// </summary> public const int DefaultTotalUrls = 100; /// <summary> /// Maximum number of external urls that can be set up by this module. /// </summary> public int TotalUrls { get; set; } public Type ReplaceableInterface { get { return null; } } public string Name { get { return "UrlModule"; } } public void Initialise(IConfigSource config) { IConfig networkConfig = config.Configs["Network"]; if (networkConfig != null) { ExternalHostNameForLSL = config.Configs["Network"].GetString("ExternalHostNameForLSL", null); bool ssl_enabled = config.Configs["Network"].GetBoolean("https_listener", false); if (ssl_enabled) m_HttpsPort = (uint)config.Configs["Network"].GetInt("https_port", (int)m_HttpsPort); } if (ExternalHostNameForLSL == null) ExternalHostNameForLSL = System.Environment.MachineName; IConfig llFunctionsConfig = config.Configs["LL-Functions"]; if (llFunctionsConfig != null) TotalUrls = llFunctionsConfig.GetInt("max_external_urls_per_simulator", DefaultTotalUrls); else TotalUrls = DefaultTotalUrls; } public void PostInitialise() { } public void AddRegion(Scene scene) { if (m_HttpServer == null) { // There can only be one // m_HttpServer = MainServer.Instance; // // We can use the https if it is enabled if (m_HttpsPort > 0) { m_HttpsServer = MainServer.GetHttpServer(m_HttpsPort); } } scene.RegisterModuleInterface<IUrlModule>(this); scene.EventManager.OnScriptReset += OnScriptReset; } public void RegionLoaded(Scene scene) { IScriptModule[] scriptModules = scene.RequestModuleInterfaces<IScriptModule>(); foreach (IScriptModule scriptModule in scriptModules) { scriptModule.OnScriptRemoved += ScriptRemoved; scriptModule.OnObjectRemoved += ObjectRemoved; } } public void RemoveRegion(Scene scene) { } public void Close() { } public UUID RequestURL(IScriptModule engine, SceneObjectPart host, UUID itemID) { UUID urlcode = UUID.Random(); lock(m_UrlMap) /* this lock here is for preventing concurrency when checking for Url amount */ { if (m_UrlMap.Count >= TotalUrls) { engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", "" }); return urlcode; } string url = "http://" + ExternalHostNameForLSL + ":" + m_HttpServer.Port.ToString() + "/lslhttp/" + urlcode.ToString() + "/"; UrlData urlData = new UrlData(); urlData.hostID = host.UUID; urlData.itemID = itemID; urlData.engine = engine; urlData.url = url; urlData.urlcode = urlcode; urlData.requests = new ThreadedClasses.RwLockedDictionary<UUID, RequestData>(); m_UrlMap[url] = urlData; string uri = "/lslhttp/" + urlcode.ToString() + "/"; PollServiceEventArgs args = new PollServiceEventArgs(HttpRequestHandler, uri, HasEvents, GetEvents, NoEvents, urlcode, 25000); args.Type = PollServiceEventArgs.EventType.LslHttp; m_HttpServer.AddPollServiceHTTPHandler(uri, args); m_log.DebugFormat( "[URL MODULE]: Set up incoming request url {0} for {1} in {2} {3}", uri, itemID, host.Name, host.LocalId); engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_GRANTED", url }); } return urlcode; } public UUID RequestSecureURL(IScriptModule engine, SceneObjectPart host, UUID itemID) { UUID urlcode = UUID.Random(); if (m_HttpsServer == null) { engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", "" }); return urlcode; } lock (m_UrlMap) /* this lock here is for preventing concurrency when checking for Url amount */ { if (m_UrlMap.Count >= TotalUrls) { engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", "" }); return urlcode; } string url = "https://" + ExternalHostNameForLSL + ":" + m_HttpsServer.Port.ToString() + "/lslhttps/" + urlcode.ToString() + "/"; UrlData urlData = new UrlData(); urlData.hostID = host.UUID; urlData.itemID = itemID; urlData.engine = engine; urlData.url = url; urlData.urlcode = urlcode; urlData.requests = new ThreadedClasses.RwLockedDictionary<UUID, RequestData>(); m_UrlMap[url] = urlData; string uri = "/lslhttps/" + urlcode.ToString() + "/"; PollServiceEventArgs args = new PollServiceEventArgs(HttpRequestHandler, uri, HasEvents, GetEvents, NoEvents, urlcode, 25000); args.Type = PollServiceEventArgs.EventType.LslHttp; m_HttpsServer.AddPollServiceHTTPHandler(uri, args); m_log.DebugFormat( "[URL MODULE]: Set up incoming secure request url {0} for {1} in {2} {3}", uri, itemID, host.Name, host.LocalId); engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_GRANTED", url }); } return urlcode; } public void ReleaseURL(string url) { UrlData data; if (!m_UrlMap.Remove(url, out data)) { return; } foreach (UUID req in data.requests.Keys) m_RequestMap.Remove(req); m_log.DebugFormat( "[URL MODULE]: Releasing url {0} for {1} in {2}", url, data.itemID, data.hostID); RemoveUrl(data); m_UrlMap.Remove(url); } public void HttpContentType(UUID request, string type) { UrlData urlData; if (m_RequestMap.TryGetValue(request, out urlData)) { urlData.requests[request].responseType = type; } else { m_log.Info("[HttpRequestHandler] There is no http-in request with id " + request.ToString()); } } public void HttpResponse(UUID request, int status, string body) { UrlData urlData; if (m_RequestMap.TryGetValue(request, out urlData)) { string responseBody = body; if (urlData.requests[request].responseType.Equals("text/plain")) { string value; if (urlData.requests[request].headers.TryGetValue("user-agent", out value)) { if (value != null && value.IndexOf("MSIE") >= 0) { // wrap the html escaped response if the target client is IE // It ignores "text/plain" if the body is html responseBody = "<html>" + System.Web.HttpUtility.HtmlEncode(body) + "</html>"; } } } urlData.requests[request].responseCode = status; urlData.requests[request].responseBody = responseBody; //urlData.requests[request].ev.Set(); urlData.requests[request].requestDone =true; } else { m_log.Info("[HttpRequestHandler] There is no http-in request with id " + request.ToString()); } } public string GetHttpHeader(UUID requestId, string header) { UrlData urlData; if (m_RequestMap.TryGetValue(requestId, out urlData)) { string value; if (urlData.requests[requestId].headers.TryGetValue(header, out value)) return value; } else { m_log.Warn("[HttpRequestHandler] There was no http-in request with id " + requestId); } return String.Empty; } public int GetFreeUrls() { return TotalUrls - m_UrlMap.Count; } public void ScriptRemoved(UUID itemID) { // m_log.DebugFormat("[URL MODULE]: Removing script {0}", itemID); List<string> removeURLs = new List<string>(); m_UrlMap.ForEach(delegate(KeyValuePair<string, UrlData> url) { if (url.Value.itemID == itemID) { RemoveUrl(url.Value); removeURLs.Add(url.Key); foreach (UUID req in url.Value.requests.Keys) m_RequestMap.Remove(req); } }); foreach (string urlname in removeURLs) m_UrlMap.Remove(urlname); } public void ObjectRemoved(UUID objectID) { List<string> removeURLs = new List<string>(); m_UrlMap.ForEach(delegate(KeyValuePair<string, UrlData> url) { if (url.Value.hostID == objectID) { RemoveUrl(url.Value); removeURLs.Add(url.Key); foreach (UUID req in url.Value.requests.Keys) m_RequestMap.Remove(req); } }); foreach (string urlname in removeURLs) m_UrlMap.Remove(urlname); } private void RemoveUrl(UrlData data) { m_HttpServer.RemoveHTTPHandler("", "/lslhttp/" + data.urlcode.ToString() + "/"); } private Hashtable NoEvents(UUID requestID, UUID sessionID) { Hashtable response = new Hashtable(); UrlData urlData; // We need to return a 404 here in case the request URL was removed at exactly the same time that a // request was made. In this case, the request thread can outrace llRemoveURL() and still be polling // for the request ID. if(!m_RequestMap.TryGetValue(requestID, out urlData)) { response["int_response_code"] = 404; response["str_response_string"] = ""; response["keepalive"] = false; response["reusecontext"] = false; return response; } if (System.Environment.TickCount - urlData.requests[requestID].startTime > 25000) { response["int_response_code"] = 500; response["str_response_string"] = "Script timeout"; response["content_type"] = "text/plain"; response["keepalive"] = false; response["reusecontext"] = false; //remove from map urlData.requests.Remove(requestID); m_RequestMap.Remove(requestID); return response; } return response; } private bool HasEvents(UUID requestID, UUID sessionID) { UrlData urlData; RequestData requestData; // We return true here because an external URL request that happened at the same time as an llRemoveURL() // can still make it through to HttpRequestHandler(). That will return without setting up a request // when it detects that the URL has been removed. The poller, however, will continue to ask for // events for that request, so here we will signal that there are events and in GetEvents we will // return a 404. if (!m_RequestMap.TryGetValue(requestID, out urlData)) { return true; } if (!urlData.requests.TryGetValue(requestID, out requestData)) { return true; } // Trigger return of timeout response. if (System.Environment.TickCount - requestData.startTime > 25000) { return true; } return requestData.requestDone; } private Hashtable GetEvents(UUID requestID, UUID sessionID) { Hashtable response; UrlData url = null; RequestData requestData = null; if (!m_RequestMap.TryGetValue(requestID, out url)) { return NoEvents(requestID, sessionID); } if(!url.requests.TryGetValue(requestID, out requestData)) { return NoEvents(requestID, sessionID); } if (!requestData.requestDone) { return NoEvents(requestID, sessionID); } response = new Hashtable(); if (System.Environment.TickCount - requestData.startTime > 25000) { response["int_response_code"] = 500; response["str_response_string"] = "Script timeout"; response["content_type"] = "text/plain"; response["keepalive"] = false; response["reusecontext"] = false; return response; } //put response response["int_response_code"] = requestData.responseCode; response["str_response_string"] = requestData.responseBody; response["content_type"] = requestData.responseType; response["keepalive"] = false; response["reusecontext"] = false; //remove from map url.requests.Remove(requestID); m_RequestMap.Remove(requestID); return response; } public void HttpRequestHandler(UUID requestID, Hashtable request) { string uri = request["uri"].ToString(); bool is_ssl = uri.Contains("lslhttps"); try { Hashtable headers = (Hashtable)request["headers"]; // string uri_full = "http://" + m_ExternalHostNameForLSL + ":" + m_HttpServer.Port.ToString() + uri;// "/lslhttp/" + urlcode.ToString() + "/"; int pos1 = uri.IndexOf("/");// /lslhttp int pos2 = uri.IndexOf("/", pos1 + 1);// /lslhttp/ int pos3 = uri.IndexOf("/", pos2 + 1);// /lslhttp/<UUID>/ string uri_tmp = uri.Substring(0, pos3 + 1); //HTTP server code doesn't provide us with QueryStrings string pathInfo; string queryString; queryString = ""; pathInfo = uri.Substring(pos3); UrlData urlData = null; string url; if (is_ssl) url = "https://" + ExternalHostNameForLSL + ":" + m_HttpsServer.Port.ToString() + uri_tmp; else url = "http://" + ExternalHostNameForLSL + ":" + m_HttpServer.Port.ToString() + uri_tmp; // Avoid a race - the request URL may have been released via llRequestUrl() whilst this // request was being processed. if (!m_UrlMap.TryGetValue(url, out urlData)) return; //for llGetHttpHeader support we need to store original URI here //to make x-path-info / x-query-string / x-script-url / x-remote-ip headers //as per http://wiki.secondlife.com/wiki/LlGetHTTPHeader RequestData requestData = new RequestData(); requestData.requestID = requestID; requestData.requestDone = false; requestData.startTime = System.Environment.TickCount; requestData.uri = uri; if (requestData.headers == null) requestData.headers = new Dictionary<string, string>(); foreach (DictionaryEntry header in headers) { string key = (string)header.Key; string value = (string)header.Value; requestData.headers.Add(key, value); } foreach (DictionaryEntry de in request) { if (de.Key.ToString() == "querystringkeys") { System.String[] keys = (System.String[])de.Value; foreach (String key in keys) { if (request.ContainsKey(key)) { string val = (String)request[key]; queryString = queryString + key + "=" + val + "&"; } } if (queryString.Length > 1) queryString = queryString.Substring(0, queryString.Length - 1); } } //if this machine is behind DNAT/port forwarding, currently this is being //set to address of port forwarding router requestData.headers["x-remote-ip"] = requestData.headers["remote_addr"]; requestData.headers["x-path-info"] = pathInfo; requestData.headers["x-query-string"] = queryString; requestData.headers["x-script-url"] = urlData.url; urlData.requests.Add(requestID, requestData); m_RequestMap.Add(requestID, urlData); urlData.engine.PostScriptEvent( urlData.itemID, "http_request", new Object[] { requestID.ToString(), request["http-method"].ToString(), request["body"].ToString() }); } catch (Exception we) { //Hashtable response = new Hashtable(); m_log.Warn("[HttpRequestHandler]: http-in request failed"); m_log.Warn(we.Message); m_log.Warn(we.StackTrace); } } private void OnScriptReset(uint localID, UUID itemID) { ScriptRemoved(itemID); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.Azure.Management.Compute.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; namespace Microsoft.Azure.Commands.Compute.Automation { [Cmdlet(VerbsCommon.New, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "VmssConfig", SupportsShouldProcess = true, DefaultParameterSetName = "DefaultParameterSet")] [OutputType(typeof(PSVirtualMachineScaleSet))] public partial class NewAzureRmVmssConfigCommand : Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet { [Parameter( Mandatory = false, Position = 0, ValueFromPipelineByPropertyName = true)] public bool? Overprovision { get; set; } [Parameter( Mandatory = false, Position = 1, ValueFromPipelineByPropertyName = true)] [LocationCompleter("Microsoft.Compute/virtualMachineScaleSets")] public string Location { get; set; } [Parameter( Mandatory = false, Position = 2, ValueFromPipelineByPropertyName = true)] public Hashtable Tag { get; set; } [Parameter( Mandatory = false, Position = 3, ValueFromPipelineByPropertyName = true)] [Alias("AccountType")] public string SkuName { get; set; } [Parameter( Mandatory = false, Position = 4, ValueFromPipelineByPropertyName = true)] public string SkuTier { get; set; } [Parameter( Mandatory = false, Position = 5, ValueFromPipelineByPropertyName = true)] public int SkuCapacity { get; set; } [Parameter( Mandatory = false, Position = 6, ValueFromPipelineByPropertyName = true)] public UpgradeMode? UpgradePolicyMode { get; set; } [Parameter( Mandatory = false, Position = 7, ValueFromPipelineByPropertyName = true)] public VirtualMachineScaleSetOSProfile OsProfile { get; set; } [Parameter( Mandatory = false, Position = 8, ValueFromPipelineByPropertyName = true)] public VirtualMachineScaleSetStorageProfile StorageProfile { get; set; } [Parameter( Mandatory = false, Position = 9, ValueFromPipelineByPropertyName = true)] public VirtualMachineScaleSetNetworkConfiguration[] NetworkInterfaceConfiguration { get; set; } [Parameter( Mandatory = false, Position = 10, ValueFromPipelineByPropertyName = true)] public VirtualMachineScaleSetExtension[] Extension { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public bool? SinglePlacementGroup { get; set; } [Parameter( Mandatory = false)] public SwitchParameter ZoneBalance { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public int PlatformFaultDomainCount { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public string[] Zone { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public string PlanName { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public string PlanPublisher { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public string PlanProduct { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public string PlanPromotionCode { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public RollingUpgradePolicy RollingUpgradePolicy { get; set; } [Parameter( Mandatory = false)] public SwitchParameter AutoOSUpgrade { get; set; } [Parameter( Mandatory = false)] public bool DisableAutoRollback { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public string HealthProbeId { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public BootDiagnostics BootDiagnostic { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public string LicenseType { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public string Priority { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] [PSArgumentCompleter("Deallocate", "Delete")] public string EvictionPolicy { get; set; } [Parameter( Mandatory = true, ParameterSetName = "ExplicitIdentityParameterSet", ValueFromPipelineByPropertyName = true)] public ResourceIdentityType? IdentityType { get; set; } [Parameter( Mandatory = false, ParameterSetName = "ExplicitIdentityParameterSet", ValueFromPipelineByPropertyName = true)] public string[] IdentityId { get; set; } protected override void ProcessRecord() { if (ShouldProcess("VirtualMachineScaleSet", "New")) { Run(); } } private void Run() { // Sku Microsoft.Azure.Management.Compute.Models.Sku vSku = null; // Plan Microsoft.Azure.Management.Compute.Models.Plan vPlan = null; // UpgradePolicy Microsoft.Azure.Management.Compute.Models.UpgradePolicy vUpgradePolicy = null; // VirtualMachineProfile Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile vVirtualMachineProfile = null; // Identity Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetIdentity vIdentity = null; if (this.MyInvocation.BoundParameters.ContainsKey("SkuName")) { if (vSku == null) { vSku = new Microsoft.Azure.Management.Compute.Models.Sku(); } vSku.Name = this.SkuName; } if (this.MyInvocation.BoundParameters.ContainsKey("SkuTier")) { if (vSku == null) { vSku = new Microsoft.Azure.Management.Compute.Models.Sku(); } vSku.Tier = this.SkuTier; } if (this.MyInvocation.BoundParameters.ContainsKey("SkuCapacity")) { if (vSku == null) { vSku = new Microsoft.Azure.Management.Compute.Models.Sku(); } vSku.Capacity = this.SkuCapacity; } if (this.MyInvocation.BoundParameters.ContainsKey("PlanName")) { if (vPlan == null) { vPlan = new Microsoft.Azure.Management.Compute.Models.Plan(); } vPlan.Name = this.PlanName; } if (this.MyInvocation.BoundParameters.ContainsKey("PlanPublisher")) { if (vPlan == null) { vPlan = new Microsoft.Azure.Management.Compute.Models.Plan(); } vPlan.Publisher = this.PlanPublisher; } if (this.MyInvocation.BoundParameters.ContainsKey("PlanProduct")) { if (vPlan == null) { vPlan = new Microsoft.Azure.Management.Compute.Models.Plan(); } vPlan.Product = this.PlanProduct; } if (this.MyInvocation.BoundParameters.ContainsKey("PlanPromotionCode")) { if (vPlan == null) { vPlan = new Microsoft.Azure.Management.Compute.Models.Plan(); } vPlan.PromotionCode = this.PlanPromotionCode; } if (this.MyInvocation.BoundParameters.ContainsKey("UpgradePolicyMode")) { if (vUpgradePolicy == null) { vUpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy(); } vUpgradePolicy.Mode = this.UpgradePolicyMode; } if (this.MyInvocation.BoundParameters.ContainsKey("RollingUpgradePolicy")) { if (vUpgradePolicy == null) { vUpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy(); } vUpgradePolicy.RollingUpgradePolicy = this.RollingUpgradePolicy; } if (vUpgradePolicy == null) { vUpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy(); } vUpgradePolicy.AutomaticOSUpgrade = this.AutoOSUpgrade.IsPresent; if (this.MyInvocation.BoundParameters.ContainsKey("DisableAutoRollback")) { if (vUpgradePolicy == null) { vUpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy(); } if (vUpgradePolicy.AutoOSUpgradePolicy == null) { vUpgradePolicy.AutoOSUpgradePolicy = new Microsoft.Azure.Management.Compute.Models.AutoOSUpgradePolicy(); } vUpgradePolicy.AutoOSUpgradePolicy.DisableAutoRollback = this.DisableAutoRollback; } if (this.MyInvocation.BoundParameters.ContainsKey("OsProfile")) { if (vVirtualMachineProfile == null) { vVirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } vVirtualMachineProfile.OsProfile = this.OsProfile; } if (this.MyInvocation.BoundParameters.ContainsKey("StorageProfile")) { if (vVirtualMachineProfile == null) { vVirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } vVirtualMachineProfile.StorageProfile = this.StorageProfile; } if (this.MyInvocation.BoundParameters.ContainsKey("HealthProbeId")) { if (vVirtualMachineProfile == null) { vVirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } if (vVirtualMachineProfile.NetworkProfile == null) { vVirtualMachineProfile.NetworkProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetNetworkProfile(); } if (vVirtualMachineProfile.NetworkProfile.HealthProbe == null) { vVirtualMachineProfile.NetworkProfile.HealthProbe = new Microsoft.Azure.Management.Compute.Models.ApiEntityReference(); } vVirtualMachineProfile.NetworkProfile.HealthProbe.Id = this.HealthProbeId; } if (this.MyInvocation.BoundParameters.ContainsKey("NetworkInterfaceConfiguration")) { if (vVirtualMachineProfile == null) { vVirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } if (vVirtualMachineProfile.NetworkProfile == null) { vVirtualMachineProfile.NetworkProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetNetworkProfile(); } vVirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations = this.NetworkInterfaceConfiguration; } if (this.MyInvocation.BoundParameters.ContainsKey("BootDiagnostic")) { if (vVirtualMachineProfile == null) { vVirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } if (vVirtualMachineProfile.DiagnosticsProfile == null) { vVirtualMachineProfile.DiagnosticsProfile = new Microsoft.Azure.Management.Compute.Models.DiagnosticsProfile(); } vVirtualMachineProfile.DiagnosticsProfile.BootDiagnostics = this.BootDiagnostic; } if (this.MyInvocation.BoundParameters.ContainsKey("Extension")) { if (vVirtualMachineProfile == null) { vVirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } if (vVirtualMachineProfile.ExtensionProfile == null) { vVirtualMachineProfile.ExtensionProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetExtensionProfile(); } vVirtualMachineProfile.ExtensionProfile.Extensions = this.Extension; } if (this.MyInvocation.BoundParameters.ContainsKey("LicenseType")) { if (vVirtualMachineProfile == null) { vVirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } vVirtualMachineProfile.LicenseType = this.LicenseType; } if (this.MyInvocation.BoundParameters.ContainsKey("Priority")) { if (vVirtualMachineProfile == null) { vVirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } vVirtualMachineProfile.Priority = this.Priority; } if (this.MyInvocation.BoundParameters.ContainsKey("EvictionPolicy")) { if (vVirtualMachineProfile == null) { vVirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile(); } vVirtualMachineProfile.EvictionPolicy = this.EvictionPolicy; } if (this.AssignIdentity.IsPresent) { if (vIdentity == null) { vIdentity = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetIdentity(); } vIdentity.Type = ResourceIdentityType.SystemAssigned; } if (this.MyInvocation.BoundParameters.ContainsKey("IdentityType")) { if (vIdentity == null) { vIdentity = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetIdentity(); } vIdentity.Type = this.IdentityType; } if (this.MyInvocation.BoundParameters.ContainsKey("IdentityId")) { if (vIdentity == null) { vIdentity = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetIdentity(); } vIdentity.UserAssignedIdentities = new Dictionary<string, VirtualMachineScaleSetIdentityUserAssignedIdentitiesValue>(); foreach (var id in this.IdentityId) { vIdentity.UserAssignedIdentities.Add(id, new VirtualMachineScaleSetIdentityUserAssignedIdentitiesValue()); } } var vVirtualMachineScaleSet = new PSVirtualMachineScaleSet { Overprovision = this.MyInvocation.BoundParameters.ContainsKey("Overprovision") ? this.Overprovision : (bool?)null, SinglePlacementGroup = this.MyInvocation.BoundParameters.ContainsKey("SinglePlacementGroup") ? this.SinglePlacementGroup : (bool?)null, ZoneBalance = this.ZoneBalance.IsPresent ? true : (bool?)null, PlatformFaultDomainCount = this.MyInvocation.BoundParameters.ContainsKey("PlatformFaultDomainCount") ? this.PlatformFaultDomainCount : (int?)null, Zones = this.MyInvocation.BoundParameters.ContainsKey("Zone") ? this.Zone : null, Location = this.MyInvocation.BoundParameters.ContainsKey("Location") ? this.Location : null, Tags = this.MyInvocation.BoundParameters.ContainsKey("Tag") ? this.Tag.Cast<DictionaryEntry>().ToDictionary(ht => (string)ht.Key, ht => (string)ht.Value) : null, Sku = vSku, Plan = vPlan, UpgradePolicy = vUpgradePolicy, VirtualMachineProfile = vVirtualMachineProfile, Identity = new PSVirtualMachineScaleSetIdentity(vIdentity), }; WriteObject(vVirtualMachineScaleSet); } } }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections; using System.IO; using System.Text; using System.Reflection; using System.Threading; using System.Runtime.Serialization; using System.Runtime.CompilerServices; using DEBUG = System.Diagnostics.Debug; namespace Microsoft.SPOT.Debugger.WireProtocol { public interface IControllerHost { void SpuriousCharacters(byte[] buf, int offset, int count); void ProcessExited(); } public interface IController { DateTime LastActivity { get; } bool IsPortConnected { get; } Packet NewPacket(); bool QueueOutput(MessageRaw raw); void SendRawBuffer(byte[] buf); void ClosePort(); void Start(); void StopProcessing(); void ResumeProcessing(); void Stop(); uint GetUniqueEndpointId(); CLRCapabilities Capabilities { get; set; } } public interface IControllerHostLocal : IControllerHost { Stream OpenConnection(); bool ProcessMessage(IncomingMessage msg, bool fReply); } public interface IControllerLocal : IController { Stream OpenPort(); } public interface IStreamAvailableCharacters { int AvailableCharacters { get; } } public interface IControllerHostRemote : IControllerHost { bool ProcessMessage(byte[] header, byte[] payload, bool fReply); } public interface IControllerRemote : IController { bool RegisterEndpoint(uint epType, uint epId); void DeregisterEndpoint(uint epType, uint epId); } internal class FifoBuffer { byte[] m_buffer; int m_offset; int m_count; ManualResetEvent m_ready; public FifoBuffer() { m_buffer = new byte[1024]; m_offset = 0; m_count = 0; m_ready = new ManualResetEvent(false); } public WaitHandle WaitHandle { get { return m_ready; } } [MethodImplAttribute(MethodImplOptions.Synchronized)] public int Read(byte[] buf, int offset, int count) { int countRequested = count; int len = m_buffer.Length; while(m_count > 0 && count > 0) { int avail = m_count; if(avail + m_offset > len) avail = len - m_offset; if(avail > count) avail = count; Array.Copy(m_buffer, m_offset, buf, offset, avail); m_offset += avail; if(m_offset == len) m_offset = 0; offset += avail; m_count -= avail; count -= avail; } if(m_count == 0) { // // No pending data, resync to the beginning of the buffer. // m_offset = 0; m_ready.Reset(); } return countRequested - count; } [MethodImplAttribute(MethodImplOptions.Synchronized)] public void Write(byte[] buf, int offset, int count) { while(count > 0) { int len = m_buffer.Length; int avail = len - m_count; if(avail == 0) // Buffer full. Expand it. { byte[] buffer = new byte[len * 2]; // // Double the buffer and copy all the data to the left side. // Array.Copy(m_buffer, m_offset, buffer, 0, len - m_offset); Array.Copy(m_buffer, 0, buffer, len - m_offset, m_offset); m_buffer = buffer; m_offset = 0; len *= 2; avail = len; } int offsetWrite = m_offset + m_count; if(offsetWrite >= len) offsetWrite -= len; if(avail + offsetWrite > len) avail = len - offsetWrite; if(avail > count) avail = count; Array.Copy(buf, offset, m_buffer, offsetWrite, avail); offset += avail; m_count += avail; count -= avail; } m_ready.Set(); } public int Available { [MethodImplAttribute( MethodImplOptions.Synchronized )] get { return m_count; } } } public class Controller : IControllerLocal { internal class MessageReassembler { enum ReceiveState { Idle = 0, Initialize = 1, WaitingForHeader = 2, ReadingHeader = 3, CompleteHeader = 4, ReadingPayload = 5, CompletePayload = 6, } Controller m_parent; ReceiveState m_state; MessageRaw m_raw; int m_rawPos; MessageBase m_base; internal MessageReassembler(Controller parent) { m_parent = parent; m_state = ReceiveState.Initialize; } internal IncomingMessage GetCompleteMessage() { return new IncomingMessage(m_parent, m_raw, m_base); } /// <summary> /// Essential Rx method. Drives state machine by reading data and processing it. This works in /// conjunction with NotificationThreadWorker [Tx]. /// </summary> internal void Process() { int count; int bytesRead; try { switch(m_state) { case ReceiveState.Initialize: m_rawPos = 0; m_base = new MessageBase(); m_base.m_header = new Packet(); m_raw = new MessageRaw(); m_raw.m_header = m_parent.CreateConverter().Serialize(m_base.m_header); m_state = ReceiveState.WaitingForHeader; goto case ReceiveState.WaitingForHeader; case ReceiveState.WaitingForHeader: count = m_raw.m_header.Length - m_rawPos; bytesRead = m_parent.Read(m_raw.m_header, m_rawPos, count); m_rawPos += bytesRead; while(m_rawPos > 0) { int flag_Debugger = ValidSignature(m_parent.marker_Debugger); int flag_Packet = ValidSignature(m_parent.marker_Packet); if(flag_Debugger == 1 || flag_Packet == 1) { m_state = ReceiveState.ReadingHeader; goto case ReceiveState.ReadingHeader; } if(flag_Debugger == 0 || flag_Packet == 0) { break; // Partial match. } m_parent.App.SpuriousCharacters(m_raw.m_header, 0, 1); Array.Copy(m_raw.m_header, 1, m_raw.m_header, 0, --m_rawPos); } break; case ReceiveState.ReadingHeader: count = m_raw.m_header.Length - m_rawPos; bytesRead = m_parent.Read(m_raw.m_header, m_rawPos, count); m_rawPos += bytesRead; if(bytesRead != count) break; m_state = ReceiveState.CompleteHeader; goto case ReceiveState.CompleteHeader; case ReceiveState.CompleteHeader: try { m_parent.CreateConverter().Deserialize(m_base.m_header, m_raw.m_header); if(VerifyHeader() == true) { bool fReply = (m_base.m_header.m_flags & Flags.c_Reply) != 0; m_base.DumpHeader("Receiving"); if(m_base.m_header.m_size != 0) { m_raw.m_payload = new byte[m_base.m_header.m_size]; //reuse m_rawPos for position in header to read. m_rawPos = 0; m_state = ReceiveState.ReadingPayload; goto case ReceiveState.ReadingPayload; } else { m_state = ReceiveState.CompletePayload; goto case ReceiveState.CompletePayload; } } } catch(ThreadAbortException) { throw; } catch(Exception e) { Console.WriteLine("Fault at payload deserialization:\n\n{0}", e.ToString()); } m_state = ReceiveState.Initialize; if((m_base.m_header.m_flags & Flags.c_NonCritical) == 0) { IncomingMessage.ReplyBadPacket(m_parent, Flags.c_BadHeader); } break; case ReceiveState.ReadingPayload: count = m_raw.m_payload.Length - m_rawPos; bytesRead = m_parent.Read(m_raw.m_payload, m_rawPos, count); m_rawPos += bytesRead; if(bytesRead != count) break; m_state = ReceiveState.CompletePayload; goto case ReceiveState.CompletePayload; case ReceiveState.CompletePayload: if(VerifyPayload() == true) { try { bool fReply = (m_base.m_header.m_flags & Flags.c_Reply) != 0; if((m_base.m_header.m_flags & Flags.c_NACK) != 0) { m_raw.m_payload = null; } m_parent.App.ProcessMessage(this.GetCompleteMessage(), fReply); m_state = ReceiveState.Initialize; return; } catch(ThreadAbortException) { throw; } catch(Exception e) { Console.WriteLine("Fault at payload deserialization:\n\n{0}", e.ToString()); } } m_state = ReceiveState.Initialize; if((m_base.m_header.m_flags & Flags.c_NonCritical) == 0) { IncomingMessage.ReplyBadPacket(m_parent, Flags.c_BadPayload); } break; } } catch { m_state = ReceiveState.Initialize; throw; } } private int ValidSignature(byte[] sig) { System.Diagnostics.Debug.Assert(sig != null && sig.Length == Packet.SIZE_OF_SIGNATURE); int markerSize = Packet.SIZE_OF_SIGNATURE; int iMax = System.Math.Min(m_rawPos, markerSize); for(int i = 0; i < iMax; i++) { if(m_raw.m_header[i] != sig[i]) return -1; } if(m_rawPos < markerSize) return 0; return 1; } private bool VerifyHeader() { uint crc = m_base.m_header.m_crcHeader; bool fRes; m_base.m_header.m_crcHeader = 0; fRes = CRC.ComputeCRC(m_parent.CreateConverter().Serialize(m_base.m_header), 0) == crc; m_base.m_header.m_crcHeader = crc; return fRes; } private bool VerifyPayload() { if(m_raw.m_payload == null) { return (m_base.m_header.m_size == 0); } else { if(m_base.m_header.m_size != m_raw.m_payload.Length) return false; return CRC.ComputeCRC(m_raw.m_payload, 0) == m_base.m_header.m_crcData; } } } internal byte[] marker_Debugger = Encoding.UTF8.GetBytes(Packet.MARKER_DEBUGGER_V1); internal byte[] marker_Packet = Encoding.UTF8.GetBytes(Packet.MARKER_PACKET_V1); private string m_marker; private IControllerHostLocal m_app; private Stream m_port; private int m_lastOutboundMessage; private DateTime m_lastActivity = DateTime.UtcNow; private int m_nextEndpointId; private FifoBuffer m_inboundData; private Thread m_inboundDataThread; private Thread m_stateMachineThread; private bool m_fProcessExit; private ManualResetEvent m_evtShutdown; private State m_state; private CLRCapabilities m_capabilities; private WaitHandle[] m_waitHandlesRead; public Controller(string marker, IControllerHostLocal app) { m_marker = marker; m_app = app; Random random = new Random(); m_lastOutboundMessage = random.Next(65536); m_nextEndpointId = random.Next(int.MaxValue); m_state = new State(this); //default capabilities m_capabilities = new CLRCapabilities(); } private Converter CreateConverter() { return new Converter(m_capabilities); } private Thread CreateThread(ThreadStart ts) { Thread th = new Thread(ts); th.IsBackground = true; th.Start(); return th; } #region IControllerLocal #region IController DateTime IController.LastActivity { get { return m_lastActivity; } } bool IController.IsPortConnected { [MethodImplAttribute( MethodImplOptions.Synchronized )] get { return (m_port != null); } } Packet IController.NewPacket() { if(!m_state.IsRunning) throw new ArgumentException("Controller not started, cannot create message"); Packet bp = new Packet(); SetSignature(bp, m_marker); bp.m_seq = (ushort)Interlocked.Increment(ref m_lastOutboundMessage); return bp; } bool IController.QueueOutput(MessageRaw raw) { SendRawBuffer(raw.m_header); if(raw.m_payload != null) SendRawBuffer(raw.m_payload); return true; } [MethodImplAttribute(MethodImplOptions.Synchronized)] void IController.ClosePort() { if(m_port != null) { try { m_port.Dispose(); } catch { } m_port = null; } } void IController.Start() { m_state.SetValue(State.Value.Starting, true); m_inboundData = new FifoBuffer(); m_evtShutdown = new ManualResetEvent(false); m_waitHandlesRead = new WaitHandle[] { m_evtShutdown, m_inboundData.WaitHandle }; m_inboundDataThread = CreateThread(new ThreadStart(this.ReceiveInput)); m_stateMachineThread = CreateThread(new ThreadStart(this.Process)); m_state.SetValue(State.Value.Started, false); } void IController.StopProcessing() { m_state.SetValue(State.Value.Stopping, false); m_evtShutdown.Set(); if(m_inboundDataThread != null) { m_inboundDataThread.Join(); m_inboundDataThread = null; } if(m_stateMachineThread != null) { m_stateMachineThread.Join(); m_stateMachineThread = null; } } void IController.ResumeProcessing() { m_evtShutdown.Reset(); m_state.SetValue(State.Value.Resume, false); if(m_inboundDataThread == null) { m_inboundDataThread = CreateThread(new ThreadStart(this.ReceiveInput)); } if(m_stateMachineThread == null) { m_stateMachineThread = CreateThread(new ThreadStart(this.Process)); } } void IController.Stop() { if(m_evtShutdown != null) { m_evtShutdown.Set(); } if(m_state.SetValue(State.Value.Stopping, false)) { ((IController)this).StopProcessing(); ((IController)this).ClosePort(); m_state.SetValue(State.Value.Stopped, false); } } uint IController.GetUniqueEndpointId() { int id = Interlocked.Increment(ref m_nextEndpointId); return (uint)id; } CLRCapabilities IController.Capabilities { get { return m_capabilities; } set { m_capabilities = value; } } #endregion [MethodImplAttribute(MethodImplOptions.Synchronized)] Stream IControllerLocal.OpenPort() { if(m_port == null) { m_port = App.OpenConnection(); } return m_port; } #endregion internal IControllerHostLocal App { get { return m_app; } } internal int Read(byte[] buf, int offset, int count) { //wait on inbound data, or on exit.... int countRequested = count; while(count > 0 && WaitHandle.WaitAny(m_waitHandlesRead) != 0) { System.Diagnostics.Debug.Assert(m_inboundData.Available > 0); int cBytesRead = m_inboundData.Read(buf, offset, count); offset += cBytesRead; count -= cBytesRead; } return countRequested - count; } internal void SetSignature(Packet bp, string sig) { byte[] buf = Encoding.UTF8.GetBytes(sig); Array.Copy(buf, 0, bp.m_signature, 0, buf.Length); } private void ProcessExit() { bool fExit = false; lock(this) { if(!m_fProcessExit) { m_fProcessExit = true; fExit = true; } } if(fExit) { App.ProcessExited(); } } private void Process() { MessageReassembler msg = new MessageReassembler(this); while(m_state.IsRunning) { try { msg.Process(); } catch(ThreadAbortException) { ((IController)this).Stop(); break; } catch { ((IController)this).ClosePort(); Thread.Sleep(100); } } } private void ReceiveInput() { byte[] buf = new byte[128]; int invalidOperationRetry = 5; while(m_state.IsRunning) { try { Stream stream = ((IControllerLocal)this).OpenPort(); IStreamAvailableCharacters streamAvail = stream as IStreamAvailableCharacters; int avail = 0; if(streamAvail != null) { avail = streamAvail.AvailableCharacters; if(avail == 0) { Thread.Sleep(100); continue; } } if(avail == 0) avail = 1; if(avail > buf.Length) buf = new byte[avail]; int read = stream.Read(buf, 0, avail); if(read > 0) { m_lastActivity = DateTime.UtcNow; m_inboundData.Write(buf, 0, read); } else if(read == 0) { Thread.Sleep(100); } } catch(ProcessExitException) { ProcessExit(); ((IController)this).ClosePort(); return; } catch(InvalidOperationException) { if(invalidOperationRetry <= 0) { ProcessExit(); ((IController)this).ClosePort(); return; } else { invalidOperationRetry--; ((IController)this).ClosePort(); Thread.Sleep(200); } } catch(IOException) { ((IController)this).ClosePort(); Thread.Sleep(200); } catch { ((IController)this).ClosePort(); Thread.Sleep(200); } } } public void SendRawBuffer(byte[] buf) { try { Stream stream = ((IControllerLocal)this).OpenPort(); stream.Write(buf, 0, buf.Length); stream.Flush(); } catch(ProcessExitException) { ProcessExit(); return; } catch { ((IController)this).ClosePort(); } } } [Serializable] public class MessageRaw { public byte[] m_header; public byte[] m_payload; } public class MessageBase { public Packet m_header; public object m_payload; [System.Diagnostics.Conditional("TRACE_DBG_HEADERS")] public void DumpHeader(string txt) { Console.WriteLine("{0}: {1:X08} {2:X08} {3} {4}", txt, m_header.m_cmd, m_header.m_flags, m_header.m_seq, m_header.m_seqReply); } } public class IncomingMessage { IController m_parent; MessageRaw m_raw; MessageBase m_base; public IncomingMessage(IController parent, MessageRaw raw, MessageBase messageBase) { m_parent = parent; m_raw = raw; m_base = messageBase; } public MessageRaw Raw { get { return m_raw; } } public MessageBase Base { get { return m_base; } } public IController Parent { get { return m_parent; } } public Packet Header { get { return m_base.m_header; } } public object Payload { get { return m_base.m_payload; } set { object payload = null; if(m_raw.m_payload != null) { if(value != null) { new Converter(m_parent.Capabilities).Deserialize(value, m_raw.m_payload); payload = value; } else { payload = m_raw.m_payload.Clone(); } } m_base.m_payload = payload; } } static public bool IsPositiveAcknowledge(IncomingMessage reply) { return reply != null && ((reply.Header.m_flags & WireProtocol.Flags.c_ACK) != 0); } static public bool ReplyBadPacket(IController ctrl, uint flags) { //What is this for? Nack + Ping? What can the TinyCLR possibly do with this information? OutgoingMessage msg = new OutgoingMessage(ctrl, new WireProtocol.Converter(), Commands.c_Monitor_Ping, Flags.c_NonCritical | Flags.c_NACK | flags, null); return msg.Send(); } public bool Reply(Converter converter, uint flags, object payload) { OutgoingMessage msgReply = new OutgoingMessage(this, converter, flags, payload); return msgReply.Send(); } } public class OutgoingMessage { IController m_parent; MessageRaw m_raw; MessageBase m_base; public OutgoingMessage(IController parent, Converter converter, uint cmd, uint flags, object payload) { InitializeForSend(parent, converter, cmd, flags, payload); UpdateCRC(converter); } internal OutgoingMessage(IncomingMessage req, Converter converter, uint flags, object payload) { InitializeForSend(req.Parent, converter, req.Header.m_cmd, flags, payload); m_base.m_header.m_seqReply = req.Header.m_seq; m_base.m_header.m_flags |= Flags.c_Reply; UpdateCRC(converter); } public bool Send() { try { m_base.DumpHeader("Sending"); return m_parent.QueueOutput(m_raw); } catch { return false; } } public Packet Header { get { return m_base.m_header; } } public object Payload { get { return m_base.m_payload; } } internal void InitializeForSend(IController parent, Converter converter, uint cmd, uint flags, object payload) { Packet header = parent.NewPacket(); header.m_cmd = cmd; header.m_flags = flags; m_parent = parent; m_raw = new MessageRaw(); m_base = new MessageBase(); m_base.m_header = header; m_base.m_payload = payload; if(payload != null) { m_raw.m_payload = converter.Serialize(payload); m_base.m_header.m_size = (uint)m_raw.m_payload.Length; m_base.m_header.m_crcData = CRC.ComputeCRC(m_raw.m_payload, 0); } } private void UpdateCRC(Converter converter) { Packet header = m_base.m_header; // // The CRC for the header is computed setting the CRC field to zero and then running the CRC algorithm. // header.m_crcHeader = 0; header.m_crcHeader = CRC.ComputeCRC(converter.Serialize(header), 0); m_raw.m_header = converter.Serialize(header); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System; using System.Globalization; using Microsoft.Practices.Prism.Events; using Microsoft.Practices.Prism.Logging; using Microsoft.Practices.Prism.Modularity; using Microsoft.Practices.Prism.Regions; using Microsoft.Practices.Prism.UnityExtensions.Properties; using Microsoft.Practices.ServiceLocation; using Microsoft.Practices.Unity; using Microsoft.Practices.Prism.UnityExtensions.Regions; using Microsoft.Practices.Prism.PubSubEvents; namespace Microsoft.Practices.Prism.UnityExtensions { /// <summary> /// Base class that provides a basic bootstrapping sequence that /// registers most of the Prism Library assets /// in a <see cref="IUnityContainer"/>. /// </summary> /// <remarks> /// This class must be overridden to provide application specific configuration. /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")] public abstract class UnityBootstrapper : Bootstrapper { private bool useDefaultConfiguration = true; /// <summary> /// Gets the default <see cref="IUnityContainer"/> for the application. /// </summary> /// <value>The default <see cref="IUnityContainer"/> instance.</value> [CLSCompliant(false)] public IUnityContainer Container { get; protected set; } /// <summary> /// Run the bootstrapper process. /// </summary> /// <param name="runWithDefaultConfiguration">If <see langword="true"/>, registers default Prism Library services in the container. This is the default behavior.</param> public override void Run(bool runWithDefaultConfiguration) { this.useDefaultConfiguration = runWithDefaultConfiguration; this.Logger = this.CreateLogger(); if (this.Logger == null) { throw new InvalidOperationException(Resources.NullLoggerFacadeException); } this.Logger.Log(Resources.LoggerCreatedSuccessfully, Category.Debug, Priority.Low); this.Logger.Log(Resources.CreatingModuleCatalog, Category.Debug, Priority.Low); this.ModuleCatalog = this.CreateModuleCatalog(); if (this.ModuleCatalog == null) { throw new InvalidOperationException(Resources.NullModuleCatalogException); } this.Logger.Log(Resources.ConfiguringModuleCatalog, Category.Debug, Priority.Low); this.ConfigureModuleCatalog(); this.Logger.Log(Resources.CreatingUnityContainer, Category.Debug, Priority.Low); this.Container = this.CreateContainer(); if (this.Container == null) { throw new InvalidOperationException(Resources.NullUnityContainerException); } this.Logger.Log(Resources.ConfiguringUnityContainer, Category.Debug, Priority.Low); this.ConfigureContainer(); this.Logger.Log(Resources.ConfiguringServiceLocatorSingleton, Category.Debug, Priority.Low); this.ConfigureServiceLocator(); this.Logger.Log(Resources.ConfiguringRegionAdapters, Category.Debug, Priority.Low); this.ConfigureRegionAdapterMappings(); this.Logger.Log(Resources.ConfiguringDefaultRegionBehaviors, Category.Debug, Priority.Low); this.ConfigureDefaultRegionBehaviors(); this.Logger.Log(Resources.RegisteringFrameworkExceptionTypes, Category.Debug, Priority.Low); this.RegisterFrameworkExceptionTypes(); this.Logger.Log(Resources.CreatingShell, Category.Debug, Priority.Low); this.Shell = this.CreateShell(); if (this.Shell != null) { this.Logger.Log(Resources.SettingTheRegionManager, Category.Debug, Priority.Low); RegionManager.SetRegionManager(this.Shell, this.Container.Resolve<IRegionManager>()); this.Logger.Log(Resources.UpdatingRegions, Category.Debug, Priority.Low); RegionManager.UpdateRegions(); this.Logger.Log(Resources.InitializingShell, Category.Debug, Priority.Low); this.InitializeShell(); } if (this.Container.IsRegistered<IModuleManager>()) { this.Logger.Log(Resources.InitializingModules, Category.Debug, Priority.Low); this.InitializeModules(); } this.Logger.Log(Resources.BootstrapperSequenceCompleted, Category.Debug, Priority.Low); } /// <summary> /// Configures the LocatorProvider for the <see cref="ServiceLocator" />. /// </summary> protected override void ConfigureServiceLocator() { ServiceLocator.SetLocatorProvider(() => this.Container.Resolve<IServiceLocator>()); } /// <summary> /// Registers in the <see cref="IUnityContainer"/> the <see cref="Type"/> of the Exceptions /// that are not considered root exceptions by the <see cref="ExceptionExtensions"/>. /// </summary> protected override void RegisterFrameworkExceptionTypes() { base.RegisterFrameworkExceptionTypes(); ExceptionExtensions.RegisterFrameworkExceptionType( typeof(Microsoft.Practices.Unity.ResolutionFailedException)); } /// <summary> /// Configures the <see cref="IUnityContainer"/>. May be overwritten in a derived class to add specific /// type mappings required by the application. /// </summary> protected virtual void ConfigureContainer() { this.Logger.Log(Resources.AddingUnityBootstrapperExtensionToContainer, Category.Debug, Priority.Low); this.Container.AddNewExtension<UnityBootstrapperExtension>(); Container.RegisterInstance<ILoggerFacade>(Logger); this.Container.RegisterInstance(this.ModuleCatalog); if (useDefaultConfiguration) { RegisterTypeIfMissing(typeof(IServiceLocator), typeof(UnityServiceLocatorAdapter), true); RegisterTypeIfMissing(typeof(IModuleInitializer), typeof(ModuleInitializer), true); RegisterTypeIfMissing(typeof(IModuleManager), typeof(ModuleManager), true); RegisterTypeIfMissing(typeof(RegionAdapterMappings), typeof(RegionAdapterMappings), true); RegisterTypeIfMissing(typeof(IRegionManager), typeof(RegionManager), true); RegisterTypeIfMissing(typeof(IEventAggregator), typeof(EventAggregator), true); RegisterTypeIfMissing(typeof(IRegionViewRegistry), typeof(RegionViewRegistry), true); RegisterTypeIfMissing(typeof(IRegionBehaviorFactory), typeof(RegionBehaviorFactory), true); RegisterTypeIfMissing(typeof(IRegionNavigationJournalEntry), typeof(RegionNavigationJournalEntry), false); RegisterTypeIfMissing(typeof(IRegionNavigationJournal), typeof(RegionNavigationJournal), false); RegisterTypeIfMissing(typeof(IRegionNavigationService), typeof(RegionNavigationService), false); RegisterTypeIfMissing(typeof(IRegionNavigationContentLoader), typeof(UnityRegionNavigationContentLoader), true); } } /// <summary> /// Initializes the modules. May be overwritten in a derived class to use a custom Modules Catalog /// </summary> protected override void InitializeModules() { IModuleManager manager; try { manager = this.Container.Resolve<IModuleManager>(); } catch (ResolutionFailedException ex) { if (ex.Message.Contains("IModuleCatalog")) { throw new InvalidOperationException(Resources.NullModuleCatalogException); } throw; } manager.Run(); } /// <summary> /// Creates the <see cref="IUnityContainer"/> that will be used as the default container. /// </summary> /// <returns>A new instance of <see cref="IUnityContainer"/>.</returns> [CLSCompliant(false)] protected virtual IUnityContainer CreateContainer() { return new UnityContainer(); } /// <summary> /// Registers a type in the container only if that type was not already registered. /// </summary> /// <param name="fromType">The interface type to register.</param> /// <param name="toType">The type implementing the interface.</param> /// <param name="registerAsSingleton">Registers the type as a singleton.</param> protected void RegisterTypeIfMissing(Type fromType, Type toType, bool registerAsSingleton) { if (fromType == null) { throw new ArgumentNullException("fromType"); } if (toType == null) { throw new ArgumentNullException("toType"); } if (Container.IsTypeRegistered(fromType)) { Logger.Log( String.Format(CultureInfo.CurrentCulture, Resources.TypeMappingAlreadyRegistered, fromType.Name), Category.Debug, Priority.Low); } else { if (registerAsSingleton) { Container.RegisterType(fromType, toType, new ContainerControlledLifetimeManager()); } else { Container.RegisterType(fromType, toType); } } } } }
#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.IO; using System.Globalization; using System.Linq; using System.Numerics; using GodLesZ.Library.Json.Utilities; #if !(NET20 || NET35 || SILVERLIGHT || PORTABLE40 || PORTABLE) #endif #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else #endif namespace GodLesZ.Library.Json { /// <summary> /// Represents a writer that provides a fast, non-cached, forward-only way of generating Json data. /// </summary> public abstract class JsonWriter : IDisposable { internal enum State { Start, Property, ObjectStart, Object, ArrayStart, Array, ConstructorStart, Constructor, Closed, Error } // array that gives a new state based on the current state an the token being written private static readonly State[][] StateArray; internal static readonly State[][] StateArrayTempate = new[] { // Start PropertyName ObjectStart Object ArrayStart Array ConstructorStart Constructor Closed Error // /* None */new[]{ State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error }, /* StartObject */new[]{ State.ObjectStart, State.ObjectStart, State.Error, State.Error, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.Error, State.Error }, /* StartArray */new[]{ State.ArrayStart, State.ArrayStart, State.Error, State.Error, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.Error, State.Error }, /* StartConstructor */new[]{ State.ConstructorStart, State.ConstructorStart, State.Error, State.Error, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.Error, State.Error }, /* Property */new[]{ State.Property, State.Error, State.Property, State.Property, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error }, /* Comment */new[]{ State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error }, /* Raw */new[]{ State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error }, /* Value (this will be copied) */new[]{ State.Start, State.Object, State.Error, State.Error, State.Array, State.Array, State.Constructor, State.Constructor, State.Error, State.Error } }; internal static State[][] BuildStateArray() { var allStates = StateArrayTempate.ToList(); var errorStates = StateArrayTempate[0]; var valueStates = StateArrayTempate[7]; foreach (JsonToken valueToken in EnumUtils.GetValues(typeof(JsonToken))) { if (allStates.Count <= (int)valueToken) { switch (valueToken) { case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Undefined: case JsonToken.Date: case JsonToken.Bytes: allStates.Add(valueStates); break; default: allStates.Add(errorStates); break; } } } return allStates.ToArray(); } static JsonWriter() { StateArray = BuildStateArray(); } private readonly List<JsonPosition> _stack; private JsonPosition _currentPosition; private State _currentState; private Formatting _formatting; /// <summary> /// Gets or sets a value indicating whether the underlying stream or /// <see cref="TextReader"/> should be closed when the writer is closed. /// </summary> /// <value> /// true to close the underlying stream or <see cref="TextReader"/> when /// the writer is closed; otherwise false. The default is true. /// </value> public bool CloseOutput { get; set; } /// <summary> /// Gets the top. /// </summary> /// <value>The top.</value> protected internal int Top { get { int depth = _stack.Count; if (Peek() != JsonContainerType.None) depth++; return depth; } } /// <summary> /// Gets the state of the writer. /// </summary> public WriteState WriteState { get { switch (_currentState) { case State.Error: return WriteState.Error; case State.Closed: return WriteState.Closed; case State.Object: case State.ObjectStart: return WriteState.Object; case State.Array: case State.ArrayStart: return WriteState.Array; case State.Constructor: case State.ConstructorStart: return WriteState.Constructor; case State.Property: return WriteState.Property; case State.Start: return WriteState.Start; default: throw JsonWriterException.Create(this, "Invalid state: " + _currentState, null); } } } internal string ContainerPath { get { if (_currentPosition.Type == JsonContainerType.None) return string.Empty; return JsonPosition.BuildPath(_stack); } } /// <summary> /// Gets the path of the writer. /// </summary> public string Path { get { if (_currentPosition.Type == JsonContainerType.None) return string.Empty; bool insideContainer = (_currentState != State.ArrayStart && _currentState != State.ConstructorStart && _currentState != State.ObjectStart); IEnumerable<JsonPosition> positions = (!insideContainer) ? _stack : _stack.Concat(new[] { _currentPosition }); return JsonPosition.BuildPath(positions); } } private DateFormatHandling _dateFormatHandling; private DateTimeZoneHandling _dateTimeZoneHandling; private StringEscapeHandling _stringEscapeHandling; private FloatFormatHandling _floatFormatHandling; private string _dateFormatString; private CultureInfo _culture; /// <summary> /// Indicates how JSON text output is formatted. /// </summary> public Formatting Formatting { get { return _formatting; } set { _formatting = value; } } /// <summary> /// Get or set how dates are written to JSON text. /// </summary> public DateFormatHandling DateFormatHandling { get { return _dateFormatHandling; } set { _dateFormatHandling = value; } } /// <summary> /// Get or set how <see cref="DateTime"/> time zones are handling when writing JSON text. /// </summary> public DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling; } set { _dateTimeZoneHandling = value; } } /// <summary> /// Get or set how strings are escaped when writing JSON text. /// </summary> public StringEscapeHandling StringEscapeHandling { get { return _stringEscapeHandling; } set { _stringEscapeHandling = value; OnStringEscapeHandlingChanged(); } } internal virtual void OnStringEscapeHandlingChanged() { // hacky but there is a calculated value that relies on StringEscapeHandling } /// <summary> /// Get or set how special floating point numbers, e.g. <see cref="F:System.Double.NaN"/>, /// <see cref="F:System.Double.PositiveInfinity"/> and <see cref="F:System.Double.NegativeInfinity"/>, /// are written to JSON text. /// </summary> public FloatFormatHandling FloatFormatHandling { get { return _floatFormatHandling; } set { _floatFormatHandling = value; } } /// <summary> /// Get or set how <see cref="DateTime"/> and <see cref="DateTimeOffset"/> values are formatting when writing JSON text. /// </summary> public string DateFormatString { get { return _dateFormatString; } set { _dateFormatString = value; } } /// <summary> /// Gets or sets the culture used when writing JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>. /// </summary> public CultureInfo Culture { get { return _culture ?? CultureInfo.InvariantCulture; } set { _culture = value; } } /// <summary> /// Creates an instance of the <c>JsonWriter</c> class. /// </summary> protected JsonWriter() { _stack = new List<JsonPosition>(4); _currentState = State.Start; _formatting = Formatting.None; _dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; CloseOutput = true; } internal void UpdateScopeWithFinishedValue() { if (_currentPosition.HasIndex) _currentPosition.Position++; } private void Push(JsonContainerType value) { if (_currentPosition.Type != JsonContainerType.None) _stack.Add(_currentPosition); _currentPosition = new JsonPosition(value); } private JsonContainerType Pop() { JsonPosition oldPosition = _currentPosition; if (_stack.Count > 0) { _currentPosition = _stack[_stack.Count - 1]; _stack.RemoveAt(_stack.Count - 1); } else { _currentPosition = new JsonPosition(); } return oldPosition.Type; } private JsonContainerType Peek() { return _currentPosition.Type; } /// <summary> /// Flushes whatever is in the buffer to the underlying streams and also flushes the underlying stream. /// </summary> public abstract void Flush(); /// <summary> /// Closes this stream and the underlying stream. /// </summary> public virtual void Close() { AutoCompleteAll(); } /// <summary> /// Writes the beginning of a Json object. /// </summary> public virtual void WriteStartObject() { InternalWriteStart(JsonToken.StartObject, JsonContainerType.Object); } /// <summary> /// Writes the end of a Json object. /// </summary> public virtual void WriteEndObject() { InternalWriteEnd(JsonContainerType.Object); } /// <summary> /// Writes the beginning of a Json array. /// </summary> public virtual void WriteStartArray() { InternalWriteStart(JsonToken.StartArray, JsonContainerType.Array); } /// <summary> /// Writes the end of an array. /// </summary> public virtual void WriteEndArray() { InternalWriteEnd(JsonContainerType.Array); } /// <summary> /// Writes the start of a constructor with the given name. /// </summary> /// <param name="name">The name of the constructor.</param> public virtual void WriteStartConstructor(string name) { InternalWriteStart(JsonToken.StartConstructor, JsonContainerType.Constructor); } /// <summary> /// Writes the end constructor. /// </summary> public virtual void WriteEndConstructor() { InternalWriteEnd(JsonContainerType.Constructor); } /// <summary> /// Writes the property name of a name/value pair on a JSON object. /// </summary> /// <param name="name">The name of the property.</param> public virtual void WritePropertyName(string name) { InternalWritePropertyName(name); } /// <summary> /// Writes the property name of a name/value pair on a JSON object. /// </summary> /// <param name="name">The name of the property.</param> /// <param name="escape">A flag to indicate whether the text should be escaped when it is written as a JSON property name.</param> public virtual void WritePropertyName(string name, bool escape) { WritePropertyName(name); } /// <summary> /// Writes the end of the current Json object or array. /// </summary> public virtual void WriteEnd() { WriteEnd(Peek()); } /// <summary> /// Writes the current <see cref="JsonReader"/> token and its children. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param> public void WriteToken(JsonReader reader) { WriteToken(reader, true, true); } /// <summary> /// Writes the current <see cref="JsonReader"/> token. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param> /// <param name="writeChildren">A flag indicating whether the current token's children should be written.</param> public void WriteToken(JsonReader reader, bool writeChildren) { ValidationUtils.ArgumentNotNull(reader, "reader"); WriteToken(reader, writeChildren, true); } internal void WriteToken(JsonReader reader, bool writeChildren, bool writeDateConstructorAsDate) { int initialDepth; if (reader.TokenType == JsonToken.None) initialDepth = -1; else if (!IsStartToken(reader.TokenType)) initialDepth = reader.Depth + 1; else initialDepth = reader.Depth; WriteToken(reader, initialDepth, writeChildren, writeDateConstructorAsDate); } internal void WriteToken(JsonReader reader, int initialDepth, bool writeChildren, bool writeDateConstructorAsDate) { do { switch (reader.TokenType) { case JsonToken.None: // read to next break; case JsonToken.StartObject: WriteStartObject(); break; case JsonToken.StartArray: WriteStartArray(); break; case JsonToken.StartConstructor: string constructorName = reader.Value.ToString(); // write a JValue date when the constructor is for a date if (writeDateConstructorAsDate && string.Equals(constructorName, "Date", StringComparison.Ordinal)) WriteConstructorDate(reader); else WriteStartConstructor(reader.Value.ToString()); break; case JsonToken.PropertyName: WritePropertyName(reader.Value.ToString()); break; case JsonToken.Comment: WriteComment((reader.Value != null) ? reader.Value.ToString() : null); break; case JsonToken.Integer: #if !(NET20 || NET35 || SILVERLIGHT || PORTABLE || PORTABLE40) if (reader.Value is BigInteger) { WriteValue((BigInteger)reader.Value); } else #endif { WriteValue(Convert.ToInt64(reader.Value, CultureInfo.InvariantCulture)); } break; case JsonToken.Float: object value = reader.Value; if (value is decimal) WriteValue((decimal)value); else if (value is double) WriteValue((double)value); else if (value is float) WriteValue((float)value); else WriteValue(Convert.ToDouble(value, CultureInfo.InvariantCulture)); break; case JsonToken.String: WriteValue(reader.Value.ToString()); break; case JsonToken.Boolean: WriteValue(Convert.ToBoolean(reader.Value, CultureInfo.InvariantCulture)); break; case JsonToken.Null: WriteNull(); break; case JsonToken.Undefined: WriteUndefined(); break; case JsonToken.EndObject: WriteEndObject(); break; case JsonToken.EndArray: WriteEndArray(); break; case JsonToken.EndConstructor: WriteEndConstructor(); break; case JsonToken.Date: #if !NET20 if (reader.Value is DateTimeOffset) WriteValue((DateTimeOffset)reader.Value); else #endif WriteValue(Convert.ToDateTime(reader.Value, CultureInfo.InvariantCulture)); break; case JsonToken.Raw: WriteRawValue((reader.Value != null) ? reader.Value.ToString() : null); break; case JsonToken.Bytes: WriteValue((byte[])reader.Value); break; default: throw MiscellaneousUtils.CreateArgumentOutOfRangeException("TokenType", reader.TokenType, "Unexpected token type."); } } while ( // stop if we have reached the end of the token being read initialDepth - 1 < reader.Depth - (IsEndToken(reader.TokenType) ? 1 : 0) && writeChildren && reader.Read()); } private void WriteConstructorDate(JsonReader reader) { if (!reader.Read()) throw JsonWriterException.Create(this, "Unexpected end when reading date constructor.", null); if (reader.TokenType != JsonToken.Integer) throw JsonWriterException.Create(this, "Unexpected token when reading date constructor. Expected Integer, got " + reader.TokenType, null); long ticks = (long)reader.Value; DateTime date = DateTimeUtils.ConvertJavaScriptTicksToDateTime(ticks); if (!reader.Read()) throw JsonWriterException.Create(this, "Unexpected end when reading date constructor.", null); if (reader.TokenType != JsonToken.EndConstructor) throw JsonWriterException.Create(this, "Unexpected token when reading date constructor. Expected EndConstructor, got " + reader.TokenType, null); WriteValue(date); } internal static bool IsEndToken(JsonToken token) { switch (token) { case JsonToken.EndObject: case JsonToken.EndArray: case JsonToken.EndConstructor: return true; default: return false; } } internal static bool IsStartToken(JsonToken token) { switch (token) { case JsonToken.StartObject: case JsonToken.StartArray: case JsonToken.StartConstructor: return true; default: return false; } } private void WriteEnd(JsonContainerType type) { switch (type) { case JsonContainerType.Object: WriteEndObject(); break; case JsonContainerType.Array: WriteEndArray(); break; case JsonContainerType.Constructor: WriteEndConstructor(); break; default: throw JsonWriterException.Create(this, "Unexpected type when writing end: " + type, null); } } private void AutoCompleteAll() { while (Top > 0) { WriteEnd(); } } private JsonToken GetCloseTokenForType(JsonContainerType type) { switch (type) { case JsonContainerType.Object: return JsonToken.EndObject; case JsonContainerType.Array: return JsonToken.EndArray; case JsonContainerType.Constructor: return JsonToken.EndConstructor; default: throw JsonWriterException.Create(this, "No close token for type: " + type, null); } } private void AutoCompleteClose(JsonContainerType type) { // write closing symbol and calculate new state int levelsToComplete = 0; if (_currentPosition.Type == type) { levelsToComplete = 1; } else { int top = Top - 2; for (int i = top; i >= 0; i--) { int currentLevel = top - i; if (_stack[currentLevel].Type == type) { levelsToComplete = i + 2; break; } } } if (levelsToComplete == 0) throw JsonWriterException.Create(this, "No token to close.", null); for (int i = 0; i < levelsToComplete; i++) { JsonToken token = GetCloseTokenForType(Pop()); if (_currentState == State.Property) WriteNull(); if (_formatting == Formatting.Indented) { if (_currentState != State.ObjectStart && _currentState != State.ArrayStart) WriteIndent(); } WriteEnd(token); JsonContainerType currentLevelType = Peek(); switch (currentLevelType) { case JsonContainerType.Object: _currentState = State.Object; break; case JsonContainerType.Array: _currentState = State.Array; break; case JsonContainerType.Constructor: _currentState = State.Array; break; case JsonContainerType.None: _currentState = State.Start; break; default: throw JsonWriterException.Create(this, "Unknown JsonType: " + currentLevelType, null); } } } /// <summary> /// Writes the specified end token. /// </summary> /// <param name="token">The end token to write.</param> protected virtual void WriteEnd(JsonToken token) { } /// <summary> /// Writes indent characters. /// </summary> protected virtual void WriteIndent() { } /// <summary> /// Writes the JSON value delimiter. /// </summary> protected virtual void WriteValueDelimiter() { } /// <summary> /// Writes an indent space. /// </summary> protected virtual void WriteIndentSpace() { } internal void AutoComplete(JsonToken tokenBeingWritten) { // gets new state based on the current state and what is being written State newState = StateArray[(int)tokenBeingWritten][(int)_currentState]; if (newState == State.Error) throw JsonWriterException.Create(this, "Token {0} in state {1} would result in an invalid JSON object.".FormatWith(CultureInfo.InvariantCulture, tokenBeingWritten.ToString(), _currentState.ToString()), null); if ((_currentState == State.Object || _currentState == State.Array || _currentState == State.Constructor) && tokenBeingWritten != JsonToken.Comment) { WriteValueDelimiter(); } if (_formatting == Formatting.Indented) { if (_currentState == State.Property) WriteIndentSpace(); // don't indent a property when it is the first token to be written (i.e. at the start) if ((_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.Constructor || _currentState == State.ConstructorStart) || (tokenBeingWritten == JsonToken.PropertyName && _currentState != State.Start)) WriteIndent(); } _currentState = newState; } #region WriteValue methods /// <summary> /// Writes a null value. /// </summary> public virtual void WriteNull() { InternalWriteValue(JsonToken.Null); } /// <summary> /// Writes an undefined value. /// </summary> public virtual void WriteUndefined() { InternalWriteValue(JsonToken.Undefined); } /// <summary> /// Writes raw JSON without changing the writer's state. /// </summary> /// <param name="json">The raw JSON to write.</param> public virtual void WriteRaw(string json) { InternalWriteRaw(); } /// <summary> /// Writes raw JSON where a value is expected and updates the writer's state. /// </summary> /// <param name="json">The raw JSON to write.</param> public virtual void WriteRawValue(string json) { // hack. want writer to change state as if a value had been written UpdateScopeWithFinishedValue(); AutoComplete(JsonToken.Undefined); WriteRaw(json); } /// <summary> /// Writes a <see cref="String"/> value. /// </summary> /// <param name="value">The <see cref="String"/> value to write.</param> public virtual void WriteValue(string value) { InternalWriteValue(JsonToken.String); } /// <summary> /// Writes a <see cref="Int32"/> value. /// </summary> /// <param name="value">The <see cref="Int32"/> value to write.</param> public virtual void WriteValue(int value) { InternalWriteValue(JsonToken.Integer); } /// <summary> /// Writes a <see cref="UInt32"/> value. /// </summary> /// <param name="value">The <see cref="UInt32"/> value to write.</param> [CLSCompliant(false)] public virtual void WriteValue(uint value) { InternalWriteValue(JsonToken.Integer); } /// <summary> /// Writes a <see cref="Int64"/> value. /// </summary> /// <param name="value">The <see cref="Int64"/> value to write.</param> public virtual void WriteValue(long value) { InternalWriteValue(JsonToken.Integer); } /// <summary> /// Writes a <see cref="UInt64"/> value. /// </summary> /// <param name="value">The <see cref="UInt64"/> value to write.</param> [CLSCompliant(false)] public virtual void WriteValue(ulong value) { InternalWriteValue(JsonToken.Integer); } /// <summary> /// Writes a <see cref="Single"/> value. /// </summary> /// <param name="value">The <see cref="Single"/> value to write.</param> public virtual void WriteValue(float value) { InternalWriteValue(JsonToken.Float); } /// <summary> /// Writes a <see cref="Double"/> value. /// </summary> /// <param name="value">The <see cref="Double"/> value to write.</param> public virtual void WriteValue(double value) { InternalWriteValue(JsonToken.Float); } /// <summary> /// Writes a <see cref="Boolean"/> value. /// </summary> /// <param name="value">The <see cref="Boolean"/> value to write.</param> public virtual void WriteValue(bool value) { InternalWriteValue(JsonToken.Boolean); } /// <summary> /// Writes a <see cref="Int16"/> value. /// </summary> /// <param name="value">The <see cref="Int16"/> value to write.</param> public virtual void WriteValue(short value) { InternalWriteValue(JsonToken.Integer); } /// <summary> /// Writes a <see cref="UInt16"/> value. /// </summary> /// <param name="value">The <see cref="UInt16"/> value to write.</param> [CLSCompliant(false)] public virtual void WriteValue(ushort value) { InternalWriteValue(JsonToken.Integer); } /// <summary> /// Writes a <see cref="Char"/> value. /// </summary> /// <param name="value">The <see cref="Char"/> value to write.</param> public virtual void WriteValue(char value) { InternalWriteValue(JsonToken.String); } /// <summary> /// Writes a <see cref="Byte"/> value. /// </summary> /// <param name="value">The <see cref="Byte"/> value to write.</param> public virtual void WriteValue(byte value) { InternalWriteValue(JsonToken.Integer); } /// <summary> /// Writes a <see cref="SByte"/> value. /// </summary> /// <param name="value">The <see cref="SByte"/> value to write.</param> [CLSCompliant(false)] public virtual void WriteValue(sbyte value) { InternalWriteValue(JsonToken.Integer); } /// <summary> /// Writes a <see cref="Decimal"/> value. /// </summary> /// <param name="value">The <see cref="Decimal"/> value to write.</param> public virtual void WriteValue(decimal value) { InternalWriteValue(JsonToken.Float); } /// <summary> /// Writes a <see cref="DateTime"/> value. /// </summary> /// <param name="value">The <see cref="DateTime"/> value to write.</param> public virtual void WriteValue(DateTime value) { InternalWriteValue(JsonToken.Date); } #if !NET20 /// <summary> /// Writes a <see cref="DateTimeOffset"/> value. /// </summary> /// <param name="value">The <see cref="DateTimeOffset"/> value to write.</param> public virtual void WriteValue(DateTimeOffset value) { InternalWriteValue(JsonToken.Date); } #endif /// <summary> /// Writes a <see cref="Guid"/> value. /// </summary> /// <param name="value">The <see cref="Guid"/> value to write.</param> public virtual void WriteValue(Guid value) { InternalWriteValue(JsonToken.String); } /// <summary> /// Writes a <see cref="TimeSpan"/> value. /// </summary> /// <param name="value">The <see cref="TimeSpan"/> value to write.</param> public virtual void WriteValue(TimeSpan value) { InternalWriteValue(JsonToken.String); } /// <summary> /// Writes a <see cref="Nullable{Int32}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Int32}"/> value to write.</param> public virtual void WriteValue(int? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{UInt32}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{UInt32}"/> value to write.</param> [CLSCompliant(false)] public virtual void WriteValue(uint? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{Int64}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Int64}"/> value to write.</param> public virtual void WriteValue(long? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{UInt64}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{UInt64}"/> value to write.</param> [CLSCompliant(false)] public virtual void WriteValue(ulong? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{Single}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Single}"/> value to write.</param> public virtual void WriteValue(float? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{Double}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Double}"/> value to write.</param> public virtual void WriteValue(double? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{Boolean}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Boolean}"/> value to write.</param> public virtual void WriteValue(bool? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{Int16}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Int16}"/> value to write.</param> public virtual void WriteValue(short? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{UInt16}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{UInt16}"/> value to write.</param> [CLSCompliant(false)] public virtual void WriteValue(ushort? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{Char}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Char}"/> value to write.</param> public virtual void WriteValue(char? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{Byte}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Byte}"/> value to write.</param> public virtual void WriteValue(byte? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{SByte}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{SByte}"/> value to write.</param> [CLSCompliant(false)] public virtual void WriteValue(sbyte? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{Decimal}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Decimal}"/> value to write.</param> public virtual void WriteValue(decimal? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{DateTime}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{DateTime}"/> value to write.</param> public virtual void WriteValue(DateTime? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } #if !NET20 /// <summary> /// Writes a <see cref="Nullable{DateTimeOffset}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{DateTimeOffset}"/> value to write.</param> public virtual void WriteValue(DateTimeOffset? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } #endif /// <summary> /// Writes a <see cref="Nullable{Guid}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Guid}"/> value to write.</param> public virtual void WriteValue(Guid? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{TimeSpan}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{TimeSpan}"/> value to write.</param> public virtual void WriteValue(TimeSpan? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="T:Byte[]"/> value. /// </summary> /// <param name="value">The <see cref="T:Byte[]"/> value to write.</param> public virtual void WriteValue(byte[] value) { if (value == null) WriteNull(); else InternalWriteValue(JsonToken.Bytes); } /// <summary> /// Writes a <see cref="Uri"/> value. /// </summary> /// <param name="value">The <see cref="Uri"/> value to write.</param> public virtual void WriteValue(Uri value) { if (value == null) WriteNull(); else InternalWriteValue(JsonToken.String); } /// <summary> /// Writes a <see cref="Object"/> value. /// An error will raised if the value cannot be written as a single JSON token. /// </summary> /// <param name="value">The <see cref="Object"/> value to write.</param> public virtual void WriteValue(object value) { if (value == null) { WriteNull(); } else { #if !(NET20 || NET35 || SILVERLIGHT || PORTABLE || PORTABLE40) // this is here because adding a WriteValue(BigInteger) to JsonWriter will // mean the user has to add a reference to System.Numerics.dll if (value is BigInteger) throw CreateUnsupportedTypeException(this, value); #endif WriteValue(this, ConvertUtils.GetTypeCode(value), value); } } #endregion /// <summary> /// Writes out a comment <code>/*...*/</code> containing the specified text. /// </summary> /// <param name="text">Text to place inside the comment.</param> public virtual void WriteComment(string text) { InternalWriteComment(); } /// <summary> /// Writes out the given white space. /// </summary> /// <param name="ws">The string of white space characters.</param> public virtual void WriteWhitespace(string ws) { InternalWriteWhitespace(ws); } void IDisposable.Dispose() { Dispose(true); } private void Dispose(bool disposing) { if (_currentState != State.Closed) Close(); } internal static void WriteValue(JsonWriter writer, PrimitiveTypeCode typeCode, object value) { switch (typeCode) { case PrimitiveTypeCode.Char: writer.WriteValue((char)value); break; case PrimitiveTypeCode.CharNullable: writer.WriteValue((value == null) ? (char?)null : (char)value); break; case PrimitiveTypeCode.Boolean: writer.WriteValue((bool)value); break; case PrimitiveTypeCode.BooleanNullable: writer.WriteValue((value == null) ? (bool?)null : (bool)value); break; case PrimitiveTypeCode.SByte: writer.WriteValue((sbyte)value); break; case PrimitiveTypeCode.SByteNullable: writer.WriteValue((value == null) ? (sbyte?)null : (sbyte)value); break; case PrimitiveTypeCode.Int16: writer.WriteValue((short)value); break; case PrimitiveTypeCode.Int16Nullable: writer.WriteValue((value == null) ? (short?)null : (short)value); break; case PrimitiveTypeCode.UInt16: writer.WriteValue((ushort)value); break; case PrimitiveTypeCode.UInt16Nullable: writer.WriteValue((value == null) ? (ushort?)null : (ushort)value); break; case PrimitiveTypeCode.Int32: writer.WriteValue((int)value); break; case PrimitiveTypeCode.Int32Nullable: writer.WriteValue((value == null) ? (int?)null : (int)value); break; case PrimitiveTypeCode.Byte: writer.WriteValue((byte)value); break; case PrimitiveTypeCode.ByteNullable: writer.WriteValue((value == null) ? (byte?)null : (byte)value); break; case PrimitiveTypeCode.UInt32: writer.WriteValue((uint)value); break; case PrimitiveTypeCode.UInt32Nullable: writer.WriteValue((value == null) ? (uint?)null : (uint)value); break; case PrimitiveTypeCode.Int64: writer.WriteValue((long)value); break; case PrimitiveTypeCode.Int64Nullable: writer.WriteValue((value == null) ? (long?)null : (long)value); break; case PrimitiveTypeCode.UInt64: writer.WriteValue((ulong)value); break; case PrimitiveTypeCode.UInt64Nullable: writer.WriteValue((value == null) ? (ulong?)null : (ulong)value); break; case PrimitiveTypeCode.Single: writer.WriteValue((float)value); break; case PrimitiveTypeCode.SingleNullable: writer.WriteValue((value == null) ? (float?)null : (float)value); break; case PrimitiveTypeCode.Double: writer.WriteValue((double)value); break; case PrimitiveTypeCode.DoubleNullable: writer.WriteValue((value == null) ? (double?)null : (double)value); break; case PrimitiveTypeCode.DateTime: writer.WriteValue((DateTime)value); break; case PrimitiveTypeCode.DateTimeNullable: writer.WriteValue((value == null) ? (DateTime?)null : (DateTime)value); break; #if !NET20 case PrimitiveTypeCode.DateTimeOffset: writer.WriteValue((DateTimeOffset)value); break; case PrimitiveTypeCode.DateTimeOffsetNullable: writer.WriteValue((value == null) ? (DateTimeOffset?)null : (DateTimeOffset)value); break; #endif case PrimitiveTypeCode.Decimal: writer.WriteValue((decimal)value); break; case PrimitiveTypeCode.DecimalNullable: writer.WriteValue((value == null) ? (decimal?)null : (decimal)value); break; case PrimitiveTypeCode.Guid: writer.WriteValue((Guid)value); break; case PrimitiveTypeCode.GuidNullable: writer.WriteValue((value == null) ? (Guid?)null : (Guid)value); break; case PrimitiveTypeCode.TimeSpan: writer.WriteValue((TimeSpan)value); break; case PrimitiveTypeCode.TimeSpanNullable: writer.WriteValue((value == null) ? (TimeSpan?)null : (TimeSpan)value); break; #if !(PORTABLE || PORTABLE40 || NET35 || NET20 || WINDOWS_PHONE || SILVERLIGHT) case PrimitiveTypeCode.BigInteger: // this will call to WriteValue(object) writer.WriteValue((BigInteger)value); break; case PrimitiveTypeCode.BigIntegerNullable: // this will call to WriteValue(object) writer.WriteValue((value == null) ? (BigInteger?)null : (BigInteger)value); break; #endif case PrimitiveTypeCode.Uri: writer.WriteValue((Uri)value); break; case PrimitiveTypeCode.String: writer.WriteValue((string)value); break; case PrimitiveTypeCode.Bytes: writer.WriteValue((byte[])value); break; #if !(PORTABLE || NETFX_CORE) case PrimitiveTypeCode.DBNull: writer.WriteNull(); break; #endif default: #if !(PORTABLE || NETFX_CORE) if (value is IConvertible) { // the value is a non-standard IConvertible // convert to the underlying value and retry IConvertible convertable = (IConvertible)value; TypeInformation typeInformation = ConvertUtils.GetTypeInformation(convertable); object convertedValue = convertable.ToType(typeInformation.Type, CultureInfo.InvariantCulture); WriteValue(writer, typeInformation.TypeCode, convertedValue); } else #endif { throw CreateUnsupportedTypeException(writer, value); } break; } } private static JsonWriterException CreateUnsupportedTypeException(JsonWriter writer, object value) { return JsonWriterException.Create(writer, "Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), null); } /// <summary> /// Sets the state of the JsonWriter, /// </summary> /// <param name="token">The JsonToken being written.</param> /// <param name="value">The value being written.</param> protected void SetWriteState(JsonToken token, object value) { switch (token) { case JsonToken.StartObject: InternalWriteStart(token, JsonContainerType.Object); break; case JsonToken.StartArray: InternalWriteStart(token, JsonContainerType.Array); break; case JsonToken.StartConstructor: InternalWriteStart(token, JsonContainerType.Constructor); break; case JsonToken.PropertyName: if (!(value is string)) throw new ArgumentException("A name is required when setting property name state.", "value"); InternalWritePropertyName((string)value); break; case JsonToken.Comment: InternalWriteComment(); break; case JsonToken.Raw: InternalWriteRaw(); break; case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Date: case JsonToken.Bytes: case JsonToken.Null: case JsonToken.Undefined: InternalWriteValue(token); break; case JsonToken.EndObject: InternalWriteEnd(JsonContainerType.Object); break; case JsonToken.EndArray: InternalWriteEnd(JsonContainerType.Array); break; case JsonToken.EndConstructor: InternalWriteEnd(JsonContainerType.Constructor); break; default: throw new ArgumentOutOfRangeException("token"); } } internal void InternalWriteEnd(JsonContainerType container) { AutoCompleteClose(container); } internal void InternalWritePropertyName(string name) { _currentPosition.PropertyName = name; AutoComplete(JsonToken.PropertyName); } internal void InternalWriteRaw() { } internal void InternalWriteStart(JsonToken token, JsonContainerType container) { UpdateScopeWithFinishedValue(); AutoComplete(token); Push(container); } internal void InternalWriteValue(JsonToken token) { UpdateScopeWithFinishedValue(); AutoComplete(token); } internal void InternalWriteWhitespace(string ws) { if (ws != null) { if (!StringUtils.IsWhiteSpace(ws)) throw JsonWriterException.Create(this, "Only white space characters should be used.", null); } } internal void InternalWriteComment() { AutoComplete(JsonToken.Comment); } } }
using UnityEngine; using UnityEngine.PostProcessing; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace UnityEditor.PostProcessing { //[CanEditMultipleObjects] [CustomEditor(typeof(PostProcessingProfile))] public class PostProcessingInspector : Editor { static GUIContent s_PreviewTitle = new GUIContent("Monitors"); PostProcessingProfile m_ConcreteTarget { get { return target as PostProcessingProfile; } } int m_CurrentMonitorID { get { return m_ConcreteTarget.monitors.currentMonitorID; } set { m_ConcreteTarget.monitors.currentMonitorID = value; } } List<PostProcessingMonitor> m_Monitors; GUIContent[] m_MonitorNames; Dictionary<PostProcessingModelEditor, PostProcessingModel> m_CustomEditors = new Dictionary<PostProcessingModelEditor, PostProcessingModel>(); public bool IsInteractivePreviewOpened { get; private set; } void OnEnable() { if (target == null) return; // Aggregate custom post-fx editors var assembly = Assembly.GetAssembly(typeof(PostProcessingInspector)); var editorTypes = assembly.GetTypes() .Where(x => x.IsDefined(typeof(PostProcessingModelEditorAttribute), false)); var customEditors = new Dictionary<Type, PostProcessingModelEditor>(); foreach (var editor in editorTypes) { var attr = (PostProcessingModelEditorAttribute)editor.GetCustomAttributes(typeof(PostProcessingModelEditorAttribute), false)[0]; var effectType = attr.type; var alwaysEnabled = attr.alwaysEnabled; var editorInst = (PostProcessingModelEditor)Activator.CreateInstance(editor); editorInst.alwaysEnabled = alwaysEnabled; editorInst.profile = target as PostProcessingProfile; editorInst.inspector = this; customEditors.Add(effectType, editorInst); } // ... and corresponding models var baseType = target.GetType(); var property = serializedObject.GetIterator(); while (property.Next(true)) { if (!property.hasChildren) continue; var type = baseType; var srcObject = ReflectionUtils.GetFieldValueFromPath(serializedObject.targetObject, ref type, property.propertyPath); if (srcObject == null) continue; PostProcessingModelEditor editor; if (customEditors.TryGetValue(type, out editor)) { var effect = (PostProcessingModel)srcObject; if (editor.alwaysEnabled) effect.enabled = editor.alwaysEnabled; m_CustomEditors.Add(editor, effect); editor.target = effect; editor.serializedProperty = property.Copy(); editor.OnPreEnable(); } } // Prepare monitors m_Monitors = new List<PostProcessingMonitor>(); var monitors = new List<PostProcessingMonitor> { new HistogramMonitor(), new WaveformMonitor(), new ParadeMonitor(), new VectorscopeMonitor() }; var monitorNames = new List<GUIContent>(); foreach (var monitor in monitors) { if (monitor.IsSupported()) { monitor.Init(m_ConcreteTarget.monitors, this); m_Monitors.Add(monitor); monitorNames.Add(monitor.GetMonitorTitle()); } } m_MonitorNames = monitorNames.ToArray(); if (m_Monitors.Count > 0) m_ConcreteTarget.monitors.onFrameEndEditorOnly = OnFrameEnd; } void OnDisable() { if (m_CustomEditors != null) { foreach (var editor in m_CustomEditors.Keys) editor.OnDisable(); m_CustomEditors.Clear(); } if (m_Monitors != null) { foreach (var monitor in m_Monitors) monitor.Dispose(); m_Monitors.Clear(); } if (m_ConcreteTarget != null) m_ConcreteTarget.monitors.onFrameEndEditorOnly = null; } void OnFrameEnd(RenderTexture source) { if (!IsInteractivePreviewOpened) return; if (m_CurrentMonitorID < m_Monitors.Count) m_Monitors[m_CurrentMonitorID].OnFrameData(source); IsInteractivePreviewOpened = false; } public override void OnInspectorGUI() { serializedObject.Update(); // Handles undo/redo events first (before they get used by the editors' widgets) var e = Event.current; if (e.type == EventType.ValidateCommand && e.commandName == "UndoRedoPerformed") { foreach (var editor in m_CustomEditors) editor.Value.OnValidate(); } if (!m_ConcreteTarget.debugViews.IsModeActive(BuiltinDebugViewsModel.Mode.None)) EditorGUILayout.HelpBox("A debug view is currently enabled. Changes done to an effect might not be visible.", MessageType.Info); foreach (var editor in m_CustomEditors) { EditorGUI.BeginChangeCheck(); editor.Key.OnGUI(); if (EditorGUI.EndChangeCheck()) editor.Value.OnValidate(); } serializedObject.ApplyModifiedProperties(); } public override GUIContent GetPreviewTitle() { return s_PreviewTitle; } public override bool HasPreviewGUI() { return GraphicsUtils.supportsDX11 && m_Monitors.Count > 0; } public override void OnPreviewSettings() { using (new EditorGUILayout.HorizontalScope()) { if (m_CurrentMonitorID < m_Monitors.Count) m_Monitors[m_CurrentMonitorID].OnMonitorSettings(); GUILayout.Space(5); m_CurrentMonitorID = EditorGUILayout.Popup(m_CurrentMonitorID, m_MonitorNames, FxStyles.preDropdown, GUILayout.MaxWidth(100f)); } } public override void OnInteractivePreviewGUI(Rect r, GUIStyle background) { IsInteractivePreviewOpened = true; if (m_CurrentMonitorID < m_Monitors.Count) m_Monitors[m_CurrentMonitorID].OnMonitorGUI(r); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using Vevo; using Vevo.Domain; using Vevo.Domain.Products; using Vevo.Domain.Stores; using Vevo.WebUI; using Vevo.WebUI.International; public partial class Components_ProductImage : BaseLanguageUserControl { private void SetUpJavaScript( string scriptName, string scriptUrl ) { ScriptManager.RegisterClientScriptInclude( this, this.GetType(), scriptName, ResolveClientUrl( scriptUrl ) ); } private void AddCssFile( string cssFilePath ) { HtmlLink cssLink = new HtmlLink(); cssLink.Href = cssFilePath; cssLink.Attributes.Add( "rel", "stylesheet" ); cssLink.Attributes.Add( "type", "text/css" ); Page.Header.Controls.Add( cssLink ); } private void RegisterZoomScript( HyperLink hyLink ) { StringBuilder sb = new StringBuilder(); string zoomID = "easy_zoom"; if ( this.ClientID.ToLower().Contains( "quickview" ) ) { zoomID = "easy_zoom1"; } sb.Append( "jQuery(function($){" ); sb.Append( " $('#" + hyLink.ClientID + ".zoom').easyZoom('','" + zoomID + "','" + this.ClientID + "');" ); sb.Append( "});" ); sb.AppendLine(); ScriptManager.RegisterClientScriptBlock( this, this.GetType(), "ZoomScript2", sb.ToString(), true ); } private void SetUpZoomImage() { SetUpJavaScript( "ZoomScript", "~/ClientScripts/easyzoom/easyzoom.js" ); if (!UrlManager.IsMobileDevice( Request )) { SetUpJavaScript( "ThickBoxScript", "~/ClientScripts/ThickBox/thickbox.js" ); } ScriptManager.RegisterClientScriptBlock( this, this.GetType(), "ThickboxInit", "tb_init('a.zoom, area.zoom, input.zoom');", true ); Product product = DataAccessContext.ProductRepository.GetOne( StoreContext.Culture, ProductID, new StoreRetriever().GetCurrentStoreID() ); IList<ProductImage> imageList = product.ProductImages; if ( product.ProductImages.Count != 0 ) { if ( ImageUrl == null ) { bool checkFirst = true; foreach ( ProductImage image in imageList ) { HyperLink hyLink = new HyperLink(); if ( checkFirst ) { hyLink.Attributes.Add( "class", "zoom" ); HtmlGenericControl div = new HtmlGenericControl( "div" ); div.ID = "len"; div.Attributes.Add( "class", "zoom_len" ); hyLink.Controls.Add( div ); } else { hyLink.Style.Add( "display", "none" ); } hyLink.Attributes.Add( "rel", "gallery" + product.ProductID ); if (!UrlManager.IsMobileDevice( Request )) { hyLink.NavigateUrl = "~/" + image.LargeImage; } if(image.Locales[StoreContext.Culture].TitleTag != null) hyLink.ToolTip = image.Locales[StoreContext.Culture].TitleTag; else hyLink.ToolTip = product.Name; if(image.Locales[StoreContext.Culture].AltTag != null) hyLink.Attributes.Add( "alt", image.Locales[StoreContext.Culture].AltTag); Image HtmlImage = new Image(); HtmlImage = SetUpImage( HtmlImage, image.RegularImage ); HtmlImage.ImageUrl = "~/" + image.RegularImage; hyLink.Controls.Add( HtmlImage ); PlaceHolder1.Controls.Add( hyLink ); if (checkFirst) { RegisterZoomScript( hyLink ); checkFirst = false; } } } else { foreach ( ProductImage image in imageList ) { HyperLink hyLink = new HyperLink(); if (image.Locales[StoreContext.Culture].TitleTag != null) hyLink.ToolTip = image.Locales[StoreContext.Culture].TitleTag; else hyLink.ToolTip = product.Name; if (image.Locales[StoreContext.Culture].AltTag != null) hyLink.Attributes.Add( "alt", image.Locales[StoreContext.Culture].AltTag ); if (!UrlManager.IsMobileDevice( Request )) { hyLink.NavigateUrl = "~/" + image.LargeImage; } hyLink.Attributes.Add( "rel", "gallery" + product.ProductID ); if ( !image.RegularImage.Equals( ImageUrl.Replace( "~/", "" ) ) ) hyLink.Style.Add( "display", "none" ); else { hyLink.Attributes.Add( "class", "zoom" ); HtmlGenericControl div = new HtmlGenericControl( "div" ); div.ID = "len"; div.Attributes.Add( "class", "zoom_len" ); hyLink.Controls.Add( div ); } Image HtmlImage = new Image(); HtmlImage = SetUpImage( HtmlImage, image.RegularImage ); HtmlImage.ImageUrl = "~/" + image.RegularImage; hyLink.Controls.Add( HtmlImage ); PlaceHolder1.Controls.Add( hyLink ); if (image.RegularImage.Equals( ImageUrl.Replace( "~/", "" ) )) RegisterZoomScript( hyLink ); } } } else { ImageUrl = "~/" + DataAccessContext.Configurations.GetValue( "DefaultImageUrl" ); Image HtmlImage = new Image(); HtmlImage.ImageUrl = ImageUrl; PlaceHolder1.Controls.Add( HtmlImage ); } } private Image SetUpImage( Image HtmlImage, string img ) { if ( MaximumWidth != null ) { Unit max = new Unit( MaximumWidth ); if ( max.Type == UnitType.Pixel && System.IO.File.Exists( Server.MapPath( img ) ) ) { using ( System.Drawing.Bitmap mypic = new System.Drawing.Bitmap( Server.MapPath( img ) ) ) { if (mypic.Width > max.Value) HtmlImage.Width = max; } } } return HtmlImage; } protected void Page_Load( object sender, EventArgs e ) { AddCssFile( "~/ClientScripts/easyzoom/default.css" ); AddCssFile( "~/ClientScripts/ThickBox/ThickBox.css" ); } protected void Page_PreRender( object sender, EventArgs e ) { SetUpZoomImage(); } public string ImageUrl { get { return ( string ) ViewState[ "ImageUrl" ]; } set { ViewState[ "ImageUrl" ] = value; } } public string MaximumWidth { get { return ( string ) ViewState[ "MaximumWidth" ]; } set { ViewState[ "MaximumWidth" ] = value; } } public string ProductID { get { if ( ViewState[ "ProductID" ] == null ) ViewState[ "ProductID" ] = "0"; return ViewState[ "ProductID" ].ToString(); } set { ViewState[ "ProductID" ] = value; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Binary { using System; using System.Collections; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Common; /** * <summary>Collection of predefined handlers for various system types.</summary> */ internal static class BinarySystemHandlers { /** Write handlers. */ private static readonly CopyOnWriteConcurrentDictionary<Type, IBinarySystemWriteHandler> WriteHandlers = new CopyOnWriteConcurrentDictionary<Type, IBinarySystemWriteHandler>(); /** Read handlers. */ private static readonly IBinarySystemReader[] ReadHandlers = new IBinarySystemReader[255]; /// <summary> /// Initializes the <see cref="BinarySystemHandlers"/> class. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Readability.")] static BinarySystemHandlers() { // 1. Primitives. ReadHandlers[BinaryTypeId.Bool] = new BinarySystemReader<bool>(s => s.ReadBool()); ReadHandlers[BinaryTypeId.Byte] = new BinarySystemReader<byte>(s => s.ReadByte()); ReadHandlers[BinaryTypeId.Short] = new BinarySystemReader<short>(s => s.ReadShort()); ReadHandlers[BinaryTypeId.Char] = new BinarySystemReader<char>(s => s.ReadChar()); ReadHandlers[BinaryTypeId.Int] = new BinarySystemReader<int>(s => s.ReadInt()); ReadHandlers[BinaryTypeId.Long] = new BinarySystemReader<long>(s => s.ReadLong()); ReadHandlers[BinaryTypeId.Float] = new BinarySystemReader<float>(s => s.ReadFloat()); ReadHandlers[BinaryTypeId.Double] = new BinarySystemReader<double>(s => s.ReadDouble()); ReadHandlers[BinaryTypeId.Decimal] = new BinarySystemReader<decimal?>(BinaryUtils.ReadDecimal); // 2. Date. ReadHandlers[BinaryTypeId.Timestamp] = new BinarySystemReader<DateTime?>(BinaryUtils.ReadTimestamp); // 3. String. ReadHandlers[BinaryTypeId.String] = new BinarySystemReader<string>(BinaryUtils.ReadString); // 4. Guid. ReadHandlers[BinaryTypeId.Guid] = new BinarySystemReader<Guid?>(s => BinaryUtils.ReadGuid(s)); // 5. Primitive arrays. ReadHandlers[BinaryTypeId.ArrayBool] = new BinarySystemReader<bool[]>(BinaryUtils.ReadBooleanArray); ReadHandlers[BinaryTypeId.ArrayByte] = new BinarySystemDualReader<byte[], sbyte[]>(BinaryUtils.ReadByteArray, BinaryUtils.ReadSbyteArray); ReadHandlers[BinaryTypeId.ArrayShort] = new BinarySystemDualReader<short[], ushort[]>(BinaryUtils.ReadShortArray, BinaryUtils.ReadUshortArray); ReadHandlers[BinaryTypeId.ArrayChar] = new BinarySystemReader<char[]>(BinaryUtils.ReadCharArray); ReadHandlers[BinaryTypeId.ArrayInt] = new BinarySystemDualReader<int[], uint[]>(BinaryUtils.ReadIntArray, BinaryUtils.ReadUintArray); ReadHandlers[BinaryTypeId.ArrayLong] = new BinarySystemDualReader<long[], ulong[]>(BinaryUtils.ReadLongArray, BinaryUtils.ReadUlongArray); ReadHandlers[BinaryTypeId.ArrayFloat] = new BinarySystemReader<float[]>(BinaryUtils.ReadFloatArray); ReadHandlers[BinaryTypeId.ArrayDouble] = new BinarySystemReader<double[]>(BinaryUtils.ReadDoubleArray); ReadHandlers[BinaryTypeId.ArrayDecimal] = new BinarySystemReader<decimal?[]>(BinaryUtils.ReadDecimalArray); // 6. Date array. ReadHandlers[BinaryTypeId.ArrayTimestamp] = new BinarySystemReader<DateTime?[]>(BinaryUtils.ReadTimestampArray); // 7. String array. ReadHandlers[BinaryTypeId.ArrayString] = new BinarySystemTypedArrayReader<string>(); // 8. Guid array. ReadHandlers[BinaryTypeId.ArrayGuid] = new BinarySystemTypedArrayReader<Guid?>(); // 9. Array. ReadHandlers[BinaryTypeId.Array] = new BinarySystemReader(ReadArray); // 11. Arbitrary collection. ReadHandlers[BinaryTypeId.Collection] = new BinarySystemReader(ReadCollection); // 13. Arbitrary dictionary. ReadHandlers[BinaryTypeId.Dictionary] = new BinarySystemReader(ReadDictionary); // 14. Enum. Should be read as Array, see WriteEnumArray implementation. ReadHandlers[BinaryTypeId.ArrayEnum] = new BinarySystemReader(ReadArray); // 15. Optimized marshaller objects. ReadHandlers[BinaryTypeId.OptimizedMarshaller] = new BinarySystemReader(ReadOptimizedMarshallerObject); } /// <summary> /// Try getting write handler for type. /// </summary> /// <param name="type"></param> /// <returns></returns> public static IBinarySystemWriteHandler GetWriteHandler(Type type) { return WriteHandlers.GetOrAdd(type, t => { return FindWriteHandler(t); }); } /// <summary> /// Find write handler for type. /// </summary> /// <param name="type">Type.</param> /// <returns> /// Write handler or NULL. /// </returns> private static IBinarySystemWriteHandler FindWriteHandler(Type type) { // 1. Well-known types. if (type == typeof(string)) return new BinarySystemWriteHandler<string>(WriteString, false); if (type == typeof(decimal)) return new BinarySystemWriteHandler<decimal>(WriteDecimal, false); if (type == typeof(Guid)) return new BinarySystemWriteHandler<Guid>(WriteGuid, false); if (type == typeof (BinaryObject)) return new BinarySystemWriteHandler<BinaryObject>(WriteBinary, false); if (type == typeof (BinaryEnum)) return new BinarySystemWriteHandler<BinaryEnum>(WriteBinaryEnum, false); if (type.IsEnum) { var underlyingType = Enum.GetUnderlyingType(type); if (underlyingType == typeof(int)) return new BinarySystemWriteHandler<int>((w, i) => w.WriteEnum(i, type), false); if (underlyingType == typeof(uint)) return new BinarySystemWriteHandler<uint>((w, i) => w.WriteEnum(unchecked((int) i), type), false); if (underlyingType == typeof(byte)) return new BinarySystemWriteHandler<byte>((w, i) => w.WriteEnum(i, type), false); if (underlyingType == typeof(sbyte)) return new BinarySystemWriteHandler<sbyte>((w, i) => w.WriteEnum(i, type), false); if (underlyingType == typeof(short)) return new BinarySystemWriteHandler<short>((w, i) => w.WriteEnum(i, type), false); if (underlyingType == typeof(ushort)) return new BinarySystemWriteHandler<ushort>((w, i) => w.WriteEnum(i, type), false); return null; // Other enums, such as long and ulong, can't be expressed as int. } if (type == typeof(Ignite)) return new BinarySystemWriteHandler<object>(WriteIgnite, false); // All types below can be written as handles. if (type == typeof (ArrayList)) return new BinarySystemWriteHandler<ICollection>(WriteArrayList, true); if (type == typeof (Hashtable)) return new BinarySystemWriteHandler<IDictionary>(WriteHashtable, true); if (type.IsArray) { if (type.GetArrayRank() > 1) { // int[,]-style arrays are wrapped, see comments in holder. return new BinarySystemWriteHandler<Array>( (w, o) => w.WriteObject(new MultidimensionalArrayHolder(o)), true); } // We know how to write any array type. Type elemType = type.GetElementType(); // Primitives. if (elemType == typeof (bool)) return new BinarySystemWriteHandler<bool[]>(WriteBoolArray, true); if (elemType == typeof(byte)) return new BinarySystemWriteHandler<byte[]>(WriteByteArray, true); if (elemType == typeof(short)) return new BinarySystemWriteHandler<short[]>(WriteShortArray, true); if (elemType == typeof(char)) return new BinarySystemWriteHandler<char[]>(WriteCharArray, true); if (elemType == typeof(int)) return new BinarySystemWriteHandler<int[]>(WriteIntArray, true); if (elemType == typeof(long)) return new BinarySystemWriteHandler<long[]>(WriteLongArray, true); if (elemType == typeof(float)) return new BinarySystemWriteHandler<float[]>(WriteFloatArray, true); if (elemType == typeof(double)) return new BinarySystemWriteHandler<double[]>(WriteDoubleArray, true); // Non-CLS primitives. if (elemType == typeof(sbyte)) return new BinarySystemWriteHandler<byte[]>(WriteByteArray, true); if (elemType == typeof(ushort)) return new BinarySystemWriteHandler<short[]>(WriteShortArray, true); if (elemType == typeof(uint)) return new BinarySystemWriteHandler<int[]>(WriteIntArray, true); if (elemType == typeof(ulong)) return new BinarySystemWriteHandler<long[]>(WriteLongArray, true); // Special types. if (elemType == typeof (decimal?)) return new BinarySystemWriteHandler<decimal?[]>(WriteDecimalArray, true); if (elemType == typeof(string)) return new BinarySystemWriteHandler<string[]>(WriteStringArray, true); if (elemType == typeof(Guid?)) return new BinarySystemWriteHandler<Guid?[]>(WriteGuidArray, true); // Enums. if (BinaryUtils.IsIgniteEnum(elemType) || elemType == typeof(BinaryEnum)) return new BinarySystemWriteHandler<object>(WriteEnumArray, true); // Object array. return new BinarySystemWriteHandler<object>(WriteArray, true); } if (type == typeof(OptimizedMarshallerObject)) { return new BinarySystemWriteHandler<OptimizedMarshallerObject>((w, o) => o.Write(w.Stream), false); } return null; } /// <summary> /// Reads an object of predefined type. /// </summary> public static bool TryReadSystemType<T>(byte typeId, BinaryReader ctx, out T res) { var handler = ReadHandlers[typeId]; if (handler == null) { res = default(T); return false; } res = handler.Read<T>(ctx); return true; } /// <summary> /// Write decimal. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteDecimal(BinaryWriter ctx, decimal obj) { ctx.Stream.WriteByte(BinaryTypeId.Decimal); BinaryUtils.WriteDecimal(obj, ctx.Stream); } /// <summary> /// Write string. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Object.</param> private static void WriteString(BinaryWriter ctx, string obj) { ctx.Stream.WriteByte(BinaryTypeId.String); BinaryUtils.WriteString(obj, ctx.Stream); } /// <summary> /// Write Guid. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteGuid(BinaryWriter ctx, Guid obj) { ctx.Stream.WriteByte(BinaryTypeId.Guid); BinaryUtils.WriteGuid(obj, ctx.Stream); } /// <summary> /// Write boolaen array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteBoolArray(BinaryWriter ctx, bool[] obj) { ctx.Stream.WriteByte(BinaryTypeId.ArrayBool); BinaryUtils.WriteBooleanArray(obj, ctx.Stream); } /// <summary> /// Write byte array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteByteArray(BinaryWriter ctx, byte[] obj) { ctx.Stream.WriteByte(BinaryTypeId.ArrayByte); BinaryUtils.WriteByteArray(obj, ctx.Stream); } /// <summary> /// Write short array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteShortArray(BinaryWriter ctx, short[] obj) { ctx.Stream.WriteByte(BinaryTypeId.ArrayShort); BinaryUtils.WriteShortArray(obj, ctx.Stream); } /// <summary> /// Write char array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteCharArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryTypeId.ArrayChar); BinaryUtils.WriteCharArray((char[])obj, ctx.Stream); } /// <summary> /// Write int array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteIntArray(BinaryWriter ctx, int[] obj) { ctx.Stream.WriteByte(BinaryTypeId.ArrayInt); BinaryUtils.WriteIntArray(obj, ctx.Stream); } /// <summary> /// Write long array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteLongArray(BinaryWriter ctx, long[] obj) { ctx.Stream.WriteByte(BinaryTypeId.ArrayLong); BinaryUtils.WriteLongArray(obj, ctx.Stream); } /// <summary> /// Write float array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteFloatArray(BinaryWriter ctx, float[] obj) { ctx.Stream.WriteByte(BinaryTypeId.ArrayFloat); BinaryUtils.WriteFloatArray(obj, ctx.Stream); } /// <summary> /// Write double array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteDoubleArray(BinaryWriter ctx, double[] obj) { ctx.Stream.WriteByte(BinaryTypeId.ArrayDouble); BinaryUtils.WriteDoubleArray(obj, ctx.Stream); } /// <summary> /// Write decimal array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteDecimalArray(BinaryWriter ctx, decimal?[] obj) { ctx.Stream.WriteByte(BinaryTypeId.ArrayDecimal); BinaryUtils.WriteDecimalArray(obj, ctx.Stream); } /// <summary> /// Write string array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteStringArray(BinaryWriter ctx, string[] obj) { ctx.Stream.WriteByte(BinaryTypeId.ArrayString); BinaryUtils.WriteStringArray(obj, ctx.Stream); } /// <summary> /// Write nullable GUID array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteGuidArray(BinaryWriter ctx, Guid?[] obj) { ctx.Stream.WriteByte(BinaryTypeId.ArrayGuid); BinaryUtils.WriteGuidArray(obj, ctx.Stream); } /// <summary> /// Writes the enum array. /// </summary> private static void WriteEnumArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryTypeId.ArrayEnum); BinaryUtils.WriteArray((Array) obj, ctx); } /// <summary> /// Writes the array. /// </summary> private static void WriteArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryTypeId.Array); BinaryUtils.WriteArray((Array) obj, ctx); } /** * <summary>Write ArrayList.</summary> */ private static void WriteArrayList(BinaryWriter ctx, ICollection obj) { ctx.Stream.WriteByte(BinaryTypeId.Collection); BinaryUtils.WriteCollection(obj, ctx, BinaryUtils.CollectionArrayList); } /** * <summary>Write Hashtable.</summary> */ private static void WriteHashtable(BinaryWriter ctx, IDictionary obj) { ctx.Stream.WriteByte(BinaryTypeId.Dictionary); BinaryUtils.WriteDictionary(obj, ctx, BinaryUtils.MapHashMap); } /** * <summary>Write binary object.</summary> */ private static void WriteBinary(BinaryWriter ctx, BinaryObject obj) { ctx.Stream.WriteByte(BinaryTypeId.Binary); BinaryUtils.WriteBinary(ctx.Stream, obj); } /// <summary> /// Write enum. /// </summary> private static void WriteBinaryEnum(BinaryWriter ctx, BinaryEnum obj) { var binEnum = obj; ctx.Stream.WriteByte(BinaryTypeId.BinaryEnum); ctx.WriteInt(binEnum.TypeId); ctx.WriteInt(binEnum.EnumValue); } /// <summary> /// Reads the array. /// </summary> private static object ReadArray(BinaryReader ctx, Type type) { var elemType = type.GetElementType(); if (elemType == null) { if (ctx.Mode == BinaryMode.ForceBinary) { // Forced binary mode: use object because primitives are not represented as IBinaryObject. elemType = typeof(object); } else { // Infer element type from typeId. var typeId = ctx.ReadInt(); elemType = BinaryUtils.GetArrayElementType(typeId, ctx.Marshaller); return BinaryUtils.ReadTypedArray(ctx, false, elemType ?? typeof(object)); } } // Element type is known, no need to check typeId. // In case of incompatible types we'll get exception either way. return BinaryUtils.ReadTypedArray(ctx, true, elemType); } /** * <summary>Read collection.</summary> */ private static object ReadCollection(BinaryReader ctx, Type type) { return BinaryUtils.ReadCollection(ctx, null, null); } /** * <summary>Read dictionary.</summary> */ private static object ReadDictionary(BinaryReader ctx, Type type) { return BinaryUtils.ReadDictionary(ctx, null); } /// <summary> /// Write Ignite. /// </summary> private static void WriteIgnite(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.HdrNull); } /// <summary> /// Reads the optimized marshaller object. /// </summary> private static object ReadOptimizedMarshallerObject(BinaryReader ctx, Type type) { return new OptimizedMarshallerObject(ctx.Stream); } /** * <summary>Read delegate.</summary> * <param name="ctx">Read context.</param> * <param name="type">Type.</param> */ private delegate object BinarySystemReadDelegate(BinaryReader ctx, Type type); /// <summary> /// System type reader. /// </summary> private interface IBinarySystemReader { /// <summary> /// Reads a value of specified type from reader. /// </summary> T Read<T>(BinaryReader ctx); } /// <summary> /// System type generic reader. /// </summary> private interface IBinarySystemReader<out T> { /// <summary> /// Reads a value of specified type from reader. /// </summary> T Read(BinaryReader ctx); } /// <summary> /// Default reader with boxing. /// </summary> private class BinarySystemReader : IBinarySystemReader { /** */ private readonly BinarySystemReadDelegate _readDelegate; /// <summary> /// Initializes a new instance of the <see cref="BinarySystemReader"/> class. /// </summary> /// <param name="readDelegate">The read delegate.</param> public BinarySystemReader(BinarySystemReadDelegate readDelegate) { Debug.Assert(readDelegate != null); _readDelegate = readDelegate; } /** <inheritdoc /> */ public T Read<T>(BinaryReader ctx) { return (T)_readDelegate(ctx, typeof(T)); } } /// <summary> /// Reader without boxing. /// </summary> private class BinarySystemReader<T> : IBinarySystemReader { /** */ private readonly Func<IBinaryStream, T> _readDelegate; /// <summary> /// Initializes a new instance of the <see cref="BinarySystemReader{T}"/> class. /// </summary> /// <param name="readDelegate">The read delegate.</param> public BinarySystemReader(Func<IBinaryStream, T> readDelegate) { Debug.Assert(readDelegate != null); _readDelegate = readDelegate; } /** <inheritdoc /> */ public TResult Read<TResult>(BinaryReader ctx) { return TypeCaster<TResult>.Cast(_readDelegate(ctx.Stream)); } } /// <summary> /// Reader without boxing. /// </summary> private class BinarySystemTypedArrayReader<T> : IBinarySystemReader { public TResult Read<TResult>(BinaryReader ctx) { return TypeCaster<TResult>.Cast(BinaryUtils.ReadArray<T>(ctx, false)); } } /// <summary> /// Reader with selection based on requested type. /// </summary> private class BinarySystemDualReader<T1, T2> : IBinarySystemReader, IBinarySystemReader<T2> { /** */ private readonly Func<IBinaryStream, T1> _readDelegate1; /** */ private readonly Func<IBinaryStream, T2> _readDelegate2; /// <summary> /// Initializes a new instance of the <see cref="BinarySystemDualReader{T1,T2}"/> class. /// </summary> /// <param name="readDelegate1">The read delegate1.</param> /// <param name="readDelegate2">The read delegate2.</param> public BinarySystemDualReader(Func<IBinaryStream, T1> readDelegate1, Func<IBinaryStream, T2> readDelegate2) { Debug.Assert(readDelegate1 != null); Debug.Assert(readDelegate2 != null); _readDelegate1 = readDelegate1; _readDelegate2 = readDelegate2; } /** <inheritdoc /> */ [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")] T2 IBinarySystemReader<T2>.Read(BinaryReader ctx) { return _readDelegate2(ctx.Stream); } /** <inheritdoc /> */ public T Read<T>(BinaryReader ctx) { // Can't use "as" because of variance. // For example, IBinarySystemReader<byte[]> can be cast to IBinarySystemReader<sbyte[]>, which // will cause incorrect behavior. if (typeof (T) == typeof (T2)) return ((IBinarySystemReader<T>) this).Read(ctx); return TypeCaster<T>.Cast(_readDelegate1(ctx.Stream)); } } } /// <summary> /// Write delegate + handles flag. /// </summary> internal interface IBinarySystemWriteHandler { /// <summary> /// Gets a value indicating whether this handler supports handles. /// </summary> bool SupportsHandles { get; } /// <summary> /// Writes object to a specified writer. /// </summary> /// <param name="writer">The writer.</param> /// <param name="obj">The object.</param> void Write<T>(BinaryWriter writer, T obj); } /// <summary> /// Write delegate + handles flag. /// </summary> internal class BinarySystemWriteHandler<T1> : IBinarySystemWriteHandler { /** */ private readonly Action<BinaryWriter, T1> _writeAction; /** */ private readonly bool _supportsHandles; /// <summary> /// Initializes a new instance of the <see cref="BinarySystemWriteHandler{T1}" /> class. /// </summary> /// <param name="writeAction">The write action.</param> /// <param name="supportsHandles">Handles flag.</param> public BinarySystemWriteHandler(Action<BinaryWriter, T1> writeAction, bool supportsHandles) { Debug.Assert(writeAction != null); _writeAction = writeAction; _supportsHandles = supportsHandles; } /** <inheritdoc /> */ public void Write<T>(BinaryWriter writer, T obj) { _writeAction(writer, TypeCaster<T1>.Cast(obj)); } /** <inheritdoc /> */ public bool SupportsHandles { get { return _supportsHandles; } } } }
// 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.Collections.Specialized { /// <devdoc> /// <para> /// This is a simple implementation of IDictionary using a singly linked list. This /// will be smaller and faster than a Hashtable if the number of elements is 10 or less. /// This should not be used if performance is important for large numbers of elements. /// </para> /// </devdoc> [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class ListDictionary : IDictionary { private DictionaryNode head; // Do not rename (binary serialization) private int version; // Do not rename (binary serialization) private int count; // Do not rename (binary serialization) private readonly IComparer comparer; // Do not rename (binary serialization) [NonSerialized] private Object _syncRoot; public ListDictionary() { } public ListDictionary(IComparer comparer) { this.comparer = comparer; } public object this[object key] { get { if (key == null) { throw new ArgumentNullException(nameof(key)); } DictionaryNode node = head; if (comparer == null) { while (node != null) { object oldKey = node.key; if (oldKey.Equals(key)) { return node.value; } node = node.next; } } else { while (node != null) { object oldKey = node.key; if (comparer.Compare(oldKey, key) == 0) { return node.value; } node = node.next; } } return null; } set { if (key == null) { throw new ArgumentNullException(nameof(key)); } version++; DictionaryNode last = null; DictionaryNode node; for (node = head; node != null; node = node.next) { object oldKey = node.key; if ((comparer == null) ? oldKey.Equals(key) : comparer.Compare(oldKey, key) == 0) { break; } last = node; } if (node != null) { // Found it node.value = value; return; } // Not found, so add a new one DictionaryNode newNode = new DictionaryNode(); newNode.key = key; newNode.value = value; if (last != null) { last.next = newNode; } else { head = newNode; } count++; } } public int Count { get { return count; } } public ICollection Keys { get { return new NodeKeyValueCollection(this, true); } } public bool IsReadOnly { get { return false; } } public bool IsFixedSize { get { return false; } } public bool IsSynchronized { get { return false; } } public object SyncRoot { get { if (_syncRoot == null) { System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null); } return _syncRoot; } } public ICollection Values { get { return new NodeKeyValueCollection(this, false); } } public void Add(object key, object value) { if (key == null) { throw new ArgumentNullException(nameof(key)); } version++; DictionaryNode last = null; DictionaryNode node; for (node = head; node != null; node = node.next) { object oldKey = node.key; if ((comparer == null) ? oldKey.Equals(key) : comparer.Compare(oldKey, key) == 0) { throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, key)); } last = node; } // Not found, so add a new one DictionaryNode newNode = new DictionaryNode(); newNode.key = key; newNode.value = value; if (last != null) { last.next = newNode; } else { head = newNode; } count++; } public void Clear() { count = 0; head = null; version++; } public bool Contains(object key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } for (DictionaryNode node = head; node != null; node = node.next) { object oldKey = node.key; if ((comparer == null) ? oldKey.Equals(key) : comparer.Compare(oldKey, key) == 0) { return true; } } return false; } public void CopyTo(Array array, int index) { if (array == null) throw new ArgumentNullException(nameof(array)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - index < count) throw new ArgumentException(SR.Arg_InsufficientSpace); for (DictionaryNode node = head; node != null; node = node.next) { array.SetValue(new DictionaryEntry(node.key, node.value), index); index++; } } public IDictionaryEnumerator GetEnumerator() { return new NodeEnumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return new NodeEnumerator(this); } public void Remove(object key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } version++; DictionaryNode last = null; DictionaryNode node; for (node = head; node != null; node = node.next) { object oldKey = node.key; if ((comparer == null) ? oldKey.Equals(key) : comparer.Compare(oldKey, key) == 0) { break; } last = node; } if (node == null) { return; } if (node == head) { head = node.next; } else { last.next = node.next; } count--; } private class NodeEnumerator : IDictionaryEnumerator { private ListDictionary _list; private DictionaryNode _current; private int _version; private bool _start; public NodeEnumerator(ListDictionary list) { _list = list; _version = list.version; _start = true; _current = null; } public object Current { get { return Entry; } } public DictionaryEntry Entry { get { if (_current == null) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return new DictionaryEntry(_current.key, _current.value); } } public object Key { get { if (_current == null) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return _current.key; } } public object Value { get { if (_current == null) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return _current.value; } } public bool MoveNext() { if (_version != _list.version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } if (_start) { _current = _list.head; _start = false; } else if (_current != null) { _current = _current.next; } return (_current != null); } public void Reset() { if (_version != _list.version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } _start = true; _current = null; } } private class NodeKeyValueCollection : ICollection { private ListDictionary _list; private bool _isKeys; public NodeKeyValueCollection(ListDictionary list, bool isKeys) { _list = list; _isKeys = isKeys; } void ICollection.CopyTo(Array array, int index) { if (array == null) throw new ArgumentNullException(nameof(array)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); for (DictionaryNode node = _list.head; node != null; node = node.next) { array.SetValue(_isKeys ? node.key : node.value, index); index++; } } int ICollection.Count { get { int count = 0; for (DictionaryNode node = _list.head; node != null; node = node.next) { count++; } return count; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return _list.SyncRoot; } } IEnumerator IEnumerable.GetEnumerator() { return new NodeKeyValueEnumerator(_list, _isKeys); } private class NodeKeyValueEnumerator : IEnumerator { private ListDictionary _list; private DictionaryNode _current; private int _version; private bool _isKeys; private bool _start; public NodeKeyValueEnumerator(ListDictionary list, bool isKeys) { _list = list; _isKeys = isKeys; _version = list.version; _start = true; _current = null; } public object Current { get { if (_current == null) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return _isKeys ? _current.key : _current.value; } } public bool MoveNext() { if (_version != _list.version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } if (_start) { _current = _list.head; _start = false; } else if (_current != null) { _current = _current.next; } return (_current != null); } public void Reset() { if (_version != _list.version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } _start = true; _current = null; } } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class DictionaryNode { public object key; // Do not rename (binary serialization) public object value; // Do not rename (binary serialization) public DictionaryNode next; // Do not rename (binary serialization) } } }
// Copyright (c) Govert van Drimmelen. All rights reserved. // Excel-DNA is licensed under the zlib license. See LICENSE.txt for details. using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Xml.Serialization; using ExcelDna.Logging; namespace ExcelDna.Integration { // TODO: Allow Com References (via TlbImp?)/Exported Libraries // DOCUMENT When loading ExternalLibraries, we check first the path given in the Path attribute: // if there is no such file, we try to find a file with the right name in the same // directory as the .xll. // We load files with .dna extension as Dna Libraries [Serializable] [XmlType(AnonymousType = true)] public class ExternalLibrary { private string _Path; [XmlAttribute] public string Path { get { return _Path; } set { _Path = value; } } private string _TypeLibPath; [XmlAttribute] public string TypeLibPath { get { return _TypeLibPath; } set { _TypeLibPath = value; } } private bool _ComServer; [XmlAttribute] public bool ComServer { get { return _ComServer; } set { _ComServer = value; } } private bool _Pack = false; [XmlAttribute] public bool Pack { get { return _Pack; } set { _Pack = value; } } private bool _LoadFromBytes = false; [XmlAttribute] public bool LoadFromBytes { get { return _LoadFromBytes; } set { _LoadFromBytes = value; } } private bool _ExplicitExports = false; [XmlAttribute] public bool ExplicitExports { get { return _ExplicitExports; } set { _ExplicitExports = value; } } private bool _ExplicitRegistration = false; [XmlAttribute] public bool ExplicitRegistration { get { return _ExplicitRegistration; } set { _ExplicitRegistration = value; } } internal List<ExportedAssembly> GetAssemblies(string pathResolveRoot, DnaLibrary dnaLibrary) { List<ExportedAssembly> list = new List<ExportedAssembly>(); try { string realPath = Path; if (Path.StartsWith("packed:")) { // The ExternalLibrary is packed. // We'll have to load it from resources. string resourceName = Path.Substring(7); if (Path.EndsWith(".DNA", StringComparison.OrdinalIgnoreCase)) { byte[] dnaContent = ExcelIntegration.GetDnaFileBytes(resourceName); DnaLibrary lib = DnaLibrary.LoadFrom(dnaContent, pathResolveRoot); if (lib == null) { Logger.Initialization.Error("External library could not be registered - Path: {0}\r\n - Packed DnaLibrary could not be loaded", Path); return list; } return lib.GetAssemblies(pathResolveRoot); } else { // DOCUMENT: TypeLibPath which is a resource in a library is denoted as fileName.dll\4 // For packed assemblies, we set TypeLibPath="packed:2" string typeLibPath = null; if (!string.IsNullOrEmpty(TypeLibPath) && TypeLibPath.StartsWith("packed:")) { typeLibPath = DnaLibrary.XllPath + @"\" + TypeLibPath.Substring(7); } // It would be nice to check here whether the assembly is loaded already. // But because of the name mangling in the packing we can't easily check. // So we make the following assumptions: // 1. Packed assemblies won't also be loadable from files (else they might be loaded twice) // 2. ExternalLibrary loads will happen before reference loads via AssemblyResolve. // Under these assumptions we should not have assemblies loaded more than once, // even if not checking here. byte[] rawAssembly = ExcelIntegration.GetAssemblyBytes(resourceName); Assembly assembly = Assembly.Load(rawAssembly); list.Add(new ExportedAssembly(assembly, ExplicitExports, ExplicitRegistration, ComServer, false, typeLibPath, dnaLibrary)); return list; } } if (Uri.IsWellFormedUriString(Path, UriKind.Absolute)) { // Here is support for loading ExternalLibraries from http. Uri uri = new Uri(Path, UriKind.Absolute); if (uri.IsUnc) { realPath = uri.LocalPath; // Will continue to load later with the regular file load part below... } else { string scheme = uri.Scheme.ToLowerInvariant(); if (scheme != "http" && scheme != "file" && scheme != "https") { Logger.Initialization.Error("The ExternalLibrary path {0} is not a valid Uri scheme.", Path); return list; } else { if (uri.AbsolutePath.EndsWith("dna", StringComparison.InvariantCultureIgnoreCase)) { DnaLibrary lib = DnaLibrary.LoadFrom(uri); if (lib == null) { Logger.Initialization.Error("External library could not be registered - Path: {0} - DnaLibrary could not be loaded" + Path); return list; } // CONSIDER: Should we add a resolve story for .dna files at Uris? return lib.GetAssemblies(null); // No explicit resolve path } else { // Load as a regular assembly - TypeLib not supported. Assembly assembly = Assembly.LoadFrom(Path); list.Add(new ExportedAssembly(assembly, ExplicitExports, ExplicitRegistration, ComServer, false, null, dnaLibrary)); return list; } } } } // Keep trying with the current value of realPath. string resolvedPath = DnaLibrary.ResolvePath(realPath, pathResolveRoot); if (resolvedPath == null) { Logger.Initialization.Error("External library could not be registered - Path: {0} - The library could not be found at this location" + Path); return list; } if (System.IO.Path.GetExtension(resolvedPath).Equals(".DNA", StringComparison.OrdinalIgnoreCase)) { // Load as a DnaLibrary DnaLibrary lib = DnaLibrary.LoadFrom(resolvedPath); if (lib == null) { Logger.Initialization.Error("External library could not be registered - Path: {0} - DnaLibrary could not be loaded" + Path); return list; } string pathResolveRelative = System.IO.Path.GetDirectoryName(resolvedPath); return lib.GetAssemblies(pathResolveRelative); } else { Assembly assembly; // Load as a regular assembly // First check if it is already loaded (e.g. as a reference from another assembly) // DOCUMENT: Some cases might still have assemblies loaded more than once. // E.g. for an assembly that is both ExternalLibrary and references from another assembly, // having the assembly LoadFromBytes and in the file system would load it twice, // because LoadFromBytes here happens before the .NET loaders assembly resolution. string assemblyName = System.IO.Path.GetFileNameWithoutExtension(resolvedPath); assembly = GetAssemblyIfLoaded(assemblyName); if (assembly == null) { // Really have to load it. if (LoadFromBytes) { // We need to be careful here to not re-load the assembly if it had already been loaded, // e.g. as a dependency of an assembly loaded earlier. // In that case we won't be able to have the library 'LoadFromBytes'. byte[] bytes = File.ReadAllBytes(resolvedPath); string pdbPath = System.IO.Path.ChangeExtension(resolvedPath, "pdb"); if (File.Exists(pdbPath)) { byte[] pdbBytes = File.ReadAllBytes(pdbPath); assembly = Assembly.Load(bytes, pdbBytes); } else { assembly = Assembly.Load(bytes); } } else { assembly = Assembly.LoadFrom(resolvedPath); } } string resolvedTypeLibPath = null; if (!string.IsNullOrEmpty(TypeLibPath)) { resolvedTypeLibPath = DnaLibrary.ResolvePath(TypeLibPath, pathResolveRoot); // null is unresolved if (resolvedTypeLibPath == null) { resolvedTypeLibPath = DnaLibrary.ResolvePath(TypeLibPath, System.IO.Path.GetDirectoryName(resolvedPath)); } } else { // Check for .tlb with same name next to resolvedPath string tlbCheck = System.IO.Path.ChangeExtension(resolvedPath, "tlb"); if (System.IO.File.Exists(tlbCheck)) { resolvedTypeLibPath = tlbCheck; } } list.Add(new ExportedAssembly(assembly, ExplicitExports, ExplicitRegistration, ComServer, false, resolvedTypeLibPath, dnaLibrary)); return list; } } catch (Exception e) { // Assembly could not be loaded. Logger.Initialization.Error(e, "External library could not be registered - Path: {0}", Path); return list; } } // A copy of this method lives in ExcelDna.Loader - AssemblyManager.cs private static Assembly GetAssemblyIfLoaded(string assemblyName) { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly loadedAssembly in assemblies) { string loadedAssemblyName = loadedAssembly.FullName.Split(',')[0]; if (string.Equals(assemblyName, loadedAssemblyName, StringComparison.OrdinalIgnoreCase)) return loadedAssembly; } return null; } } }
/* * Copyright (c) Contributors, http://aurora-sim.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 Aurora-Sim 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.Linq; using System.Reflection; using Aurora.Framework; using C5; namespace Aurora.DataManager.Migration { public class MigrationManager { private readonly IDataConnector genericData; private readonly string migratorName; private readonly List<Migrator> migrators = new List<Migrator>(); private readonly bool validateTables; private bool executed; private MigrationOperationDescription operationDescription; private IRestorePoint restorePoint; private bool rollback; public MigrationManager(IDataConnector genericData, string migratorName, bool validateTables) { this.genericData = genericData; this.migratorName = migratorName; this.validateTables = validateTables; List<IMigrator> allMigrators = AuroraModuleLoader.PickupModules<IMigrator>(); #if (!ISWIN) foreach (IMigrator m in allMigrators) { if (m.MigrationName != null) { if (m.MigrationName == migratorName) { migrators.Add((Migrator)m); } } } #else foreach (IMigrator m in allMigrators.Where(m => m.MigrationName != null).Where(m => m.MigrationName == migratorName)) { migrators.Add((Migrator) m); } #endif } public Version LatestVersion { get { return GetLatestVersionMigrator().Version; } } public MigrationOperationDescription GetDescriptionOfCurrentOperation() { return operationDescription; } public void DetermineOperation() { if (migratorName == "") return; executed = false; Version currentVersion = genericData.GetAuroraVersion(migratorName); //if there is no aurora version, this is likely an entirely new installation if (currentVersion == null) { Migrator defaultMigrator = GetHighestVersionMigratorThatCanProvideDefaultSetup(); currentVersion = defaultMigrator.Version; Migrator startMigrator = GetMigratorAfterVersion(defaultMigrator.Version); var latestMigrator = GetLatestVersionMigrator(); Migrator targetMigrator = defaultMigrator == latestMigrator ? null : latestMigrator; operationDescription = new MigrationOperationDescription(MigrationOperationTypes.CreateDefaultAndUpgradeToTarget, currentVersion, startMigrator != null ? startMigrator.Version : null, targetMigrator != null ? targetMigrator.Version : null); } else { Migrator startMigrator = GetMigratorAfterVersion(currentVersion); if (startMigrator != null) { Migrator targetMigrator = GetLatestVersionMigrator(); operationDescription = new MigrationOperationDescription(MigrationOperationTypes.UpgradeToTarget, currentVersion, startMigrator.Version, targetMigrator.Version); } else { operationDescription = new MigrationOperationDescription(MigrationOperationTypes.DoNothing, currentVersion); } } } private Migrator GetMigratorAfterVersion(Version version) { if (version == null) { return null; } #if (!ISWIN) foreach (Migrator migrator in (from m in migrators orderby m.Version ascending select m)) { if (migrator.Version > version) { return migrator; } } return null; #else return (from m in migrators orderby m.Version ascending select m).FirstOrDefault(migrator => migrator.Version > version); #endif } private Migrator GetLatestVersionMigrator() { return (from m in migrators orderby m.Version descending select m).First(); } private Migrator GetHighestVersionMigratorThatCanProvideDefaultSetup() { return (from m in migrators orderby m.Version descending select m).First(); } public void ExecuteOperation() { if (migratorName == "") return; if (operationDescription != null && executed == false && operationDescription.OperationType != MigrationOperationTypes.DoNothing) { Migrator currentMigrator = GetMigratorByVersion(operationDescription.CurrentVersion); //if we are creating default, do it now if (operationDescription.OperationType == MigrationOperationTypes.CreateDefaultAndUpgradeToTarget) { try { currentMigrator.CreateDefaults(genericData); } catch { } executed = true; } //lets first validate where we think we are bool validated = currentMigrator != null && currentMigrator.Validate(genericData); if (!validated && validateTables && currentMigrator != null) { //Try rerunning the migrator and then the validation //prepare restore point if something goes wrong MainConsole.Instance.Fatal(string.Format("Failed to validate migration {0}-{1}, retrying...", currentMigrator.MigrationName, currentMigrator.Version)); currentMigrator.Migrate(genericData); validated = currentMigrator.Validate(genericData); if (!validated) { Rec<string, ColumnDefinition[], IndexDefinition[]> rec; currentMigrator.DebugTestThatAllTablesValidate(genericData, out rec); MainConsole.Instance.Fatal(string.Format( "FAILED TO REVALIDATE MIGRATION {0}-{1}, FIXING TABLE FORCIBLY... NEW TABLE NAME {2}", currentMigrator.MigrationName, currentMigrator.Version, rec.X1 + "_broken" )); genericData.RenameTable(rec.X1, rec.X1 + "_broken"); currentMigrator.Migrate(genericData); validated = currentMigrator.Validate(genericData); if (!validated) { throw new MigrationOperationException(string.Format( "Current version {0}-{1} did not validate. Stopping here so we don't cause any trouble. No changes were made.", currentMigrator.MigrationName, currentMigrator.Version )); } } } //else // MainConsole.Instance.Fatal (string.Format ("Failed to validate migration {0}-{1}, continueing...", currentMigrator.MigrationName, currentMigrator.Version)); bool restoreTaken = false; //Loop through versions from start to end, migrating then validating Migrator executingMigrator = GetMigratorByVersion(operationDescription.StartVersion); //only restore if we are going to do something if (executingMigrator != null) { if (validateTables && currentMigrator != null) { //prepare restore point if something goes wrong restorePoint = currentMigrator.PrepareRestorePoint(genericData); restoreTaken = true; } } while (executingMigrator != null) { try { executingMigrator.Migrate(genericData); } catch (Exception ex) { if (currentMigrator != null) throw new MigrationOperationException(string.Format("Migrating to version {0} failed, {1}.", currentMigrator.Version, ex)); } executed = true; validated = executingMigrator.Validate(genericData); //if it doesn't validate, rollback if (!validated && validateTables) { RollBackOperation(); if (currentMigrator != null) throw new MigrationOperationException( string.Format("Migrating to version {0} did not validate. Restoring to restore point.", currentMigrator.Version)); } else { executingMigrator.FinishedMigration(genericData); } if (executingMigrator.Version == operationDescription.EndVersion) break; executingMigrator = GetMigratorAfterVersion(executingMigrator.Version); } if (restoreTaken) { currentMigrator.ClearRestorePoint(genericData); } } } public void RollBackOperation() { if (operationDescription != null && executed && rollback == false && restorePoint != null) { restorePoint.DoRestore(genericData); rollback = true; } } public bool ValidateVersion(Version version) { return GetMigratorByVersion(version).Validate(genericData); } private Migrator GetMigratorByVersion(Version version) { if (version == null) return null; try { return (from m in migrators where m.Version == version select m).First(); } catch { return null; } } } }
// This file is part of the C5 Generic Collection Library for C# and CLI // See https://github.com/sestoft/C5/blob/master/LICENSE for licensing details. // C5 example: 2006-01-29, 2006-06-26 namespace C5.UserGuideExamples { class MultiDictionary { static void Main() { MultiDictionary_MultiDictionary1.TestIt.Run(); MultiDictionary_MultiDictionary2.TestIt.Run(); } } namespace MultiDictionary_MultiDictionary1 { class TestIt { public static void Run() { var mdict = new MultiHashDictionary<int, string> { { 2, "to" }, { 2, "deux" }, { 2, "two" }, { 20, "tyve" }, { 20, "twenty" } }; Console.WriteLine(mdict); Console.WriteLine("mdict.Count is {0}", mdict.Count); Console.WriteLine("mdict.Count (keys) is {0}", ((IDictionary<int, ICollection<string>>)mdict).Count); Console.WriteLine("mdict[2].Count is {0}", mdict[2].Count); mdict.Remove(20, "tyve"); mdict.Remove(20, "twenty"); Console.WriteLine(mdict); Console.WriteLine("mdict.Count is {0}", mdict.Count); ICollection<string> zwei = new HashSet<string> { "zwei" }; mdict[2] = zwei; mdict[-2] = zwei; Console.WriteLine(mdict); Console.WriteLine("mdict.Count is {0}", mdict.Count); zwei.Add("kaksi"); Console.WriteLine(mdict); Console.WriteLine("mdict.Count is {0}", mdict.Count); ICollection<string> empty = new HashSet<string>(); mdict[0] = empty; Console.WriteLine(mdict); Console.WriteLine("mdict.Count is {0}", mdict.Count); Console.WriteLine("mdict contains key 0: {0}", mdict.Contains(0)); mdict.Remove(-2); Console.WriteLine(mdict); Console.WriteLine("mdict.Count is {0}", mdict.Count); zwei.Remove("kaksi"); Console.WriteLine(mdict); Console.WriteLine("mdict.Count is {0}", mdict.Count); zwei.Clear(); Console.WriteLine(mdict); Console.WriteLine("mdict.Count is {0}", mdict.Count); Console.WriteLine("------------------------------"); } } // Here we implement a multivalued dictionary as a hash dictionary // from keys to value collections. The value collections may have // set or bag semantics. // The value collections are externally modifiable (as in Peter // Golde's PowerCollections library), and therefore: // // * A value collection associated with a key may be null or // non-empty. Hence for correct semantics, the Contains(k) method // must check that the value collection associated with a key is // non-null and non-empty. // // * A value collection may be shared between two or more keys. // public class MultiHashDictionary<K, V> : HashDictionary<K, ICollection<V>> { // Return total count of values associated with keys. This basic // implementation simply sums over all value collections, and so // is a linear-time operation in the total number of values. public new virtual int Count { get { int count = 0; foreach (System.Collections.Generic.KeyValuePair<K, ICollection<V>> entry in this) { if (entry.Value != null) { count += entry.Value.Count; } } return count; } } public override Speed CountSpeed => Speed.Linear; // Add a (key,value) pair public virtual void Add(K k, V v) { if (!base.Find(ref k, out ICollection<V> values) || values == null) { values = new HashSet<V>(); Add(k, values); } values.Add(v); } // Remove a single (key,value) pair, if present; return true if // anything was removed, else false public virtual bool Remove(K k, V v) { if (base.Find(ref k, out ICollection<V> values) && values != null) { if (values.Remove(v)) { if (values.IsEmpty) base.Remove(k); return true; } } return false; } // Determine whether key k is associated with a value public override bool Contains(K k) { return base.Find(ref k, out ICollection<V> values) && values != null && !values.IsEmpty; } // Determine whether each key in ks is associated with a value public override bool ContainsAll<U>(SCG.IEnumerable<U> ks) { foreach (K k in ks) if (!Contains(k)) return false; return true; } // Get or set the value collection associated with key k public override ICollection<V> this[K k] { get { return base.Find(ref k, out ICollection<V> values) && values != null ? values : new HashSet<V>(); } set { base[k] = value; } } // Inherited from base class HashDictionary<K,ICollection<V>>: // Add(K k, ICollection<V> values) // AddAll(IEnumerable<System.Collections.Generic.KeyValuePair<K,ICollection<V>>> kvs) // Clear // Clone // Find(K k, out ICollection<V> values) // Find(ref K k, out ICollection<V> values) // FindOrAdd(K k, ref ICollection<V> values) // Remove(K k) // Remove(K k, out ICollection<V> values) // Update(K k, ICollection<V> values) // Update(K k, ICollection<V> values, out ICollection<V> oldValues) // UpdateOrAdd(K k, ICollection<V> values) // UpdateOrAdd(K k, ICollection<V> values, out ICollection<V> oldValues) } } namespace MultiDictionary_MultiDictionary2 { class TestIt { public static void Run() { { var mdict = new MultiHashDictionary<int, string> { { 2, "to" }, { 2, "deux" }, { 2, "two" }, { 20, "tyve" }, { 20, "twenty" } }; Console.WriteLine(mdict); Console.WriteLine("mdict.Count is {0}", mdict.Count); Console.WriteLine("mdict.Count (keys) is {0}", ((IDictionary<int, ICollection<string>>)mdict).Count); Console.WriteLine("mdict[2].Count is {0}", mdict[2].Count); mdict.Remove(20, "tyve"); mdict.Remove(20, "twenty"); Console.WriteLine(mdict); Console.WriteLine("mdict.Count is {0}", mdict.Count); ICollection<string> zwei = new HashSet<string> { "zwei" }; mdict[2] = zwei; mdict[-2] = zwei; Console.WriteLine(mdict); Console.WriteLine("mdict.Count is {0}", mdict.Count); zwei.Add("kaksi"); Console.WriteLine(mdict); Console.WriteLine("mdict.Count is {0}", mdict.Count); ICollection<string> empty = new HashSet<string>(); mdict[0] = empty; Console.WriteLine(mdict); Console.WriteLine("mdict.Count is {0}", mdict.Count); Console.WriteLine("mdict contains key 0: {0}", mdict.Contains(0)); mdict.Remove(-2); Console.WriteLine(mdict); Console.WriteLine("mdict.Count is {0}", mdict.Count); zwei.Remove("kaksi"); Console.WriteLine(mdict); Console.WriteLine("mdict.Count is {0}", mdict.Count); zwei.Clear(); Console.WriteLine(mdict); Console.WriteLine("mdict.Count is {0}", mdict.Count); Console.WriteLine("------------------------------"); } { MultiHashDictionary<int, string, HashSet<string>> mdict = new MultiHashDictionary<int, string, HashSet<string>> { { 2, "to" }, { 2, "deux" }, { 2, "two" }, { 20, "tyve" }, { 20, "twenty" } }; Console.WriteLine(mdict); Console.WriteLine("mdict.Count is {0}", mdict.Count); Console.WriteLine("mdict.Count (keys) is {0}", ((IDictionary<int, HashSet<string>>)mdict).Count); Console.WriteLine("mdict[2].Count is {0}", mdict[2].Count); mdict.Remove(20, "tyve"); mdict.Remove(20, "twenty"); Console.WriteLine(mdict); Console.WriteLine("mdict.Count is {0}", mdict.Count); HashSet<string> zwei = new HashSet<string> { "zwei" }; mdict[2] = zwei; mdict[-2] = zwei; Console.WriteLine(mdict); Console.WriteLine("mdict.Count is {0}", mdict.Count); zwei.Add("kaksi"); Console.WriteLine(mdict); Console.WriteLine("mdict.Count is {0}", mdict.Count); HashSet<string> empty = new HashSet<string>(); mdict[0] = empty; Console.WriteLine(mdict); Console.WriteLine("mdict.Count is {0}", mdict.Count); Console.WriteLine("mdict contains key 0: {0}", mdict.Contains(0)); mdict.Remove(-2); Console.WriteLine(mdict); Console.WriteLine("mdict.Count is {0}", mdict.Count); zwei.Remove("kaksi"); Console.WriteLine(mdict); Console.WriteLine("mdict.Count is {0}", mdict.Count); zwei.Clear(); Console.WriteLine(mdict); Console.WriteLine("mdict.Count is {0}", mdict.Count); Console.WriteLine("------------------------------"); } } } // This version of the multidictionary uses event listeners to make // the Count operation constant time. // The total value count for the multidictionary is cached, and // event listeners on the value collections keep this cached count // updated. Event listeners on the dictionary make sure that event // listeners are added to and removed from value collections. public class MultiHashDictionary<K, V> : HashDictionary<K, ICollection<V>> { private int count = 0; // Cached value count, updated by events only private void IncrementCount(object sender, ItemCountEventArgs<V> args) { count += args.Count; } private void DecrementCount(object sender, ItemCountEventArgs<V> args) { count -= args.Count; } private void ClearedCount(object sender, ClearedEventArgs args) { count -= args.Count; } public MultiHashDictionary() { ItemsAdded += delegate (object sender, ItemCountEventArgs<System.Collections.Generic.KeyValuePair<K, ICollection<V>>> args) { ICollection<V> values = args.Item.Value; if (values != null) { count += values.Count; values.ItemsAdded += IncrementCount; values.ItemsRemoved += DecrementCount; values.CollectionCleared += ClearedCount; } }; ItemsRemoved += delegate (object sender, ItemCountEventArgs<System.Collections.Generic.KeyValuePair<K, ICollection<V>>> args) { ICollection<V> values = args.Item.Value; if (values != null) { count -= values.Count; values.ItemsAdded -= IncrementCount; values.ItemsRemoved -= DecrementCount; values.CollectionCleared -= ClearedCount; } }; } // Return total count of values associated with keys. public new virtual int Count { get { return count; } } public override Speed CountSpeed { get { return Speed.Constant; } } // Add a (key,value) pair public virtual void Add(K k, V v) { if (!base.Find(ref k, out ICollection<V> values) || values == null) { values = new HashSet<V>(); Add(k, values); } values.Add(v); } // Remove a single (key,value) pair, if present; return true if // anything was removed, else false public virtual bool Remove(K k, V v) { if (base.Find(ref k, out ICollection<V> values) && values != null) { if (values.Remove(v)) { if (values.IsEmpty) base.Remove(k); return true; } } return false; } // Determine whether key k is associated with a value public override bool Contains(K k) { return Find(ref k, out ICollection<V> values) && values != null && !values.IsEmpty; } // Determine whether each key in ks is associated with a value public override bool ContainsAll<U>(SCG.IEnumerable<U> ks) { foreach (K k in ks) if (!Contains(k)) return false; return true; } // Get or set the value collection associated with key k public override ICollection<V> this[K k] { get { return base.Find(ref k, out ICollection<V> values) && values != null ? values : new HashSet<V>(); } set { base[k] = value; } } // Clearing the multidictionary should remove event listeners public override void Clear() { foreach (ICollection<V> values in Values) if (values != null) { count -= values.Count; values.ItemsAdded -= IncrementCount; values.ItemsRemoved -= DecrementCount; values.CollectionCleared -= ClearedCount; } base.Clear(); } } // -------------------------------------------------- // This version of the multidictionary also uses event listeners to // make the Count operation constant time. // The difference relative to the preceding version is that each // value collection must be an instance of some type VS that has an // argumentless constructor and that implements ICollection<V>. // This provides additional flexibility: The creator of a // multidictionary instance can determine the collection class VC // used for value collections, instead of having to put up with the // choice made by the multidictionary implementation. public class MultiHashDictionary<K, V, VC> : HashDictionary<K, VC> where VC : ICollection<V>, new() { private int count = 0; // Cached value count, updated by events only private void IncrementCount(object sender, ItemCountEventArgs<V> args) { count += args.Count; } private void DecrementCount(object sender, ItemCountEventArgs<V> args) { count -= args.Count; } private void ClearedCount(object sender, ClearedEventArgs args) { count -= args.Count; } public MultiHashDictionary() { ItemsAdded += (object sender, ItemCountEventArgs<SCG.KeyValuePair<K, VC>> args) => { VC values = args.Item.Value; if (values != null) { count += values.Count; values.ItemsAdded += IncrementCount; values.ItemsRemoved += DecrementCount; values.CollectionCleared += ClearedCount; } }; ItemsRemoved += (object sender, ItemCountEventArgs<SCG.KeyValuePair<K, VC>> args) => { VC values = args.Item.Value; if (values != null) { count -= values.Count; values.ItemsAdded -= IncrementCount; values.ItemsRemoved -= DecrementCount; values.CollectionCleared -= ClearedCount; } }; } // Return total count of values associated with keys. public new virtual int Count => count; public override Speed CountSpeed => Speed.Constant; // Add a (key,value) pair public virtual void Add(K k, V v) { if (!base.Find(ref k, out VC values) || values == null) { values = new VC(); Add(k, values); } values.Add(v); } // Remove a single (key,value) pair, if present; return true if // anything was removed, else false public virtual bool Remove(K k, V v) { if (base.Find(ref k, out VC values) && values != null) { if (values.Remove(v)) { if (values.IsEmpty) { base.Remove(k); } return true; } } return false; } // Determine whether key k is associated with a value public override bool Contains(K k) { return Find(ref k, out VC values) && values != null && !values.IsEmpty; } // Determine whether each key in ks is associated with a value public override bool ContainsAll<U>(SCG.IEnumerable<U> ks) { foreach (K k in ks) { if (!Contains(k)) { return false; } } return true; } // Get or set the value collection associated with key k public override VC this[K k] { get => base.Find(ref k, out VC values) && values != null ? values : new VC(); set => base[k] = value; } public override void Clear() { foreach (VC values in Values) { if (values != null) { count -= values.Count; values.ItemsAdded -= IncrementCount; values.ItemsRemoved -= DecrementCount; values.CollectionCleared -= ClearedCount; } } base.Clear(); } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; namespace System.Management.Automation { /// <summary> /// The metadata associated with a parameter. /// </summary> internal class CompiledCommandParameter { #region ctor /// <summary> /// Constructs an instance of the CompiledCommandAttribute using the specified /// runtime-defined parameter. /// </summary> /// <param name="runtimeDefinedParameter"> /// A runtime defined parameter that contains the definition of the parameter and its metadata. /// </param> /// <param name="processingDynamicParameters"> /// True if dynamic parameters are being processed, or false otherwise. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="runtimeDefinedParameter"/> is null. /// </exception> /// <exception cref="MetadataException"> /// If the parameter has more than one <see cref="ParameterAttribute">ParameterAttribute</see> /// that defines the same parameter-set name. /// </exception> internal CompiledCommandParameter(RuntimeDefinedParameter runtimeDefinedParameter, bool processingDynamicParameters) { if (runtimeDefinedParameter == null) { throw PSTraceSource.NewArgumentNullException(nameof(runtimeDefinedParameter)); } this.Name = runtimeDefinedParameter.Name; this.Type = runtimeDefinedParameter.ParameterType; this.IsDynamic = processingDynamicParameters; this.CollectionTypeInformation = new ParameterCollectionTypeInformation(runtimeDefinedParameter.ParameterType); this.CompiledAttributes = new Collection<Attribute>(); this.ParameterSetData = new Dictionary<string, ParameterSetSpecificMetadata>(StringComparer.OrdinalIgnoreCase); Collection<ValidateArgumentsAttribute> validationAttributes = null; Collection<ArgumentTransformationAttribute> argTransformationAttributes = null; string[] aliases = null; // First, process attributes that aren't type conversions foreach (Attribute attribute in runtimeDefinedParameter.Attributes) { if (processingDynamicParameters) { // When processing dynamic parameters, the attribute list may contain experimental attributes // and disabled parameter attributes. We should ignore those attributes. // When processing non-dynamic parameters, the experimental attributes and disabled parameter // attributes have already been filtered out when constructing the RuntimeDefinedParameter. if (attribute is ExperimentalAttribute || attribute is ParameterAttribute param && param.ToHide) { continue; } } if (attribute is not ArgumentTypeConverterAttribute) { ProcessAttribute(runtimeDefinedParameter.Name, attribute, ref validationAttributes, ref argTransformationAttributes, ref aliases); } } // If this is a PSCredential type and they haven't added any argument transformation attributes, // add one for credential transformation if ((this.Type == typeof(PSCredential)) && argTransformationAttributes == null) { ProcessAttribute(runtimeDefinedParameter.Name, new CredentialAttribute(), ref validationAttributes, ref argTransformationAttributes, ref aliases); } // Now process type converters foreach (var attribute in runtimeDefinedParameter.Attributes.OfType<ArgumentTypeConverterAttribute>()) { ProcessAttribute(runtimeDefinedParameter.Name, attribute, ref validationAttributes, ref argTransformationAttributes, ref aliases); } this.ValidationAttributes = validationAttributes == null ? Array.Empty<ValidateArgumentsAttribute>() : validationAttributes.ToArray(); this.ArgumentTransformationAttributes = argTransformationAttributes == null ? Array.Empty<ArgumentTransformationAttribute>() : argTransformationAttributes.ToArray(); this.Aliases = aliases == null ? Array.Empty<string>() : aliases.ToArray(); } /// <summary> /// Constructs an instance of the CompiledCommandAttribute using the reflection information retrieved /// from the enclosing bindable object type. /// </summary> /// <param name="member"> /// The member information for the parameter /// </param> /// <param name="processingDynamicParameters"> /// True if dynamic parameters are being processed, or false otherwise. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="member"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// If <paramref name="member"/> is not a field or a property. /// </exception> /// <exception cref="MetadataException"> /// If the member has more than one <see cref="ParameterAttribute">ParameterAttribute</see> /// that defines the same parameter-set name. /// </exception> internal CompiledCommandParameter(MemberInfo member, bool processingDynamicParameters) { if (member == null) { throw PSTraceSource.NewArgumentNullException(nameof(member)); } this.Name = member.Name; this.DeclaringType = member.DeclaringType; this.IsDynamic = processingDynamicParameters; var propertyInfo = member as PropertyInfo; if (propertyInfo != null) { this.Type = propertyInfo.PropertyType; } else { var fieldInfo = member as FieldInfo; if (fieldInfo != null) { this.Type = fieldInfo.FieldType; } else { ArgumentException e = PSTraceSource.NewArgumentException( nameof(member), DiscoveryExceptions.CompiledCommandParameterMemberMustBeFieldOrProperty); throw e; } } this.CollectionTypeInformation = new ParameterCollectionTypeInformation(this.Type); this.CompiledAttributes = new Collection<Attribute>(); this.ParameterSetData = new Dictionary<string, ParameterSetSpecificMetadata>(StringComparer.OrdinalIgnoreCase); // We do not want to get the inherited custom attributes, only the attributes exposed // directly on the member var memberAttributes = member.GetCustomAttributes(false); Collection<ValidateArgumentsAttribute> validationAttributes = null; Collection<ArgumentTransformationAttribute> argTransformationAttributes = null; string[] aliases = null; foreach (Attribute attr in memberAttributes) { switch (attr) { case ExperimentalAttribute _: case ParameterAttribute param when param.ToHide: break; default: ProcessAttribute(member.Name, attr, ref validationAttributes, ref argTransformationAttributes, ref aliases); break; } } this.ValidationAttributes = validationAttributes == null ? Array.Empty<ValidateArgumentsAttribute>() : validationAttributes.ToArray(); this.ArgumentTransformationAttributes = argTransformationAttributes == null ? Array.Empty<ArgumentTransformationAttribute>() : argTransformationAttributes.ToArray(); this.Aliases = aliases ?? Array.Empty<string>(); } #endregion ctor /// <summary> /// Gets the name of the parameter. /// </summary> internal string Name { get; } /// <summary> /// The PSTypeName from a PSTypeNameAttribute. /// </summary> internal string PSTypeName { get; private set; } /// <summary> /// Gets the Type information of the attribute. /// </summary> internal Type Type { get; } /// <summary> /// Gets the Type information of the attribute. /// </summary> internal Type DeclaringType { get; } /// <summary> /// Gets whether the parameter is a dynamic parameter or not. /// </summary> internal bool IsDynamic { get; } /// <summary> /// Gets the parameter collection type information. /// </summary> internal ParameterCollectionTypeInformation CollectionTypeInformation { get; } /// <summary> /// A collection of the attributes found on the member. The attributes have been compiled into /// a format that easier to digest by the metadata processor. /// </summary> internal Collection<Attribute> CompiledAttributes { get; } /// <summary> /// Gets the collection of data generation attributes on this parameter. /// </summary> internal ArgumentTransformationAttribute[] ArgumentTransformationAttributes { get; } /// <summary> /// Gets the collection of data validation attributes on this parameter. /// </summary> internal ValidateArgumentsAttribute[] ValidationAttributes { get; } /// <summary> /// Get and private set the obsolete attribute on this parameter. /// </summary> internal ObsoleteAttribute ObsoleteAttribute { get; private set; } /// <summary> /// If true, null can be bound to the parameter even if the parameter is mandatory. /// </summary> internal bool AllowsNullArgument { get; private set; } /// <summary> /// If true, null cannot be bound to the parameter (ValidateNotNull /// and/or ValidateNotNullOrEmpty has been specified). /// </summary> internal bool CannotBeNull { get; private set; } /// <summary> /// If true, an empty string can be bound to the string parameter /// even if the parameter is mandatory. /// </summary> internal bool AllowsEmptyStringArgument { get; private set; } /// <summary> /// If true, an empty collection can be bound to the collection/array parameter /// even if the parameter is mandatory. /// </summary> internal bool AllowsEmptyCollectionArgument { get; private set; } /// <summary> /// Gets or sets the value that tells whether this parameter /// is for the "all" parameter set. /// </summary> internal bool IsInAllSets { get; set; } /// <summary> /// Returns true if this parameter is ValueFromPipeline or ValueFromPipelineByPropertyName /// in one or more (but not necessarily all) parameter sets. /// </summary> internal bool IsPipelineParameterInSomeParameterSet { get; private set; } /// <summary> /// Returns true if this parameter is Mandatory in one or more (but not necessarily all) parameter sets. /// </summary> internal bool IsMandatoryInSomeParameterSet { get; private set; } /// <summary> /// Gets or sets the parameter set flags that map the parameter sets /// for this parameter to the parameter set names. /// </summary> /// <remarks> /// This is a bit-field that maps the parameter sets in this parameter /// to the parameter sets for the rest of the command. /// </remarks> internal uint ParameterSetFlags { get; set; } /// <summary> /// A delegate that can set the property. /// </summary> internal Action<object, object> Setter { get; set; } /// <summary> /// A dictionary of the parameter sets and the parameter set specific data for this parameter. /// </summary> internal Dictionary<string, ParameterSetSpecificMetadata> ParameterSetData { get; } /// <summary> /// The alias names for this parameter. /// </summary> internal string[] Aliases { get; } /// <summary> /// Determines if this parameter takes pipeline input for any of the specified /// parameter set flags. /// </summary> /// <param name="validParameterSetFlags"> /// The flags for the parameter sets to check to see if the parameter takes /// pipeline input. /// </param> /// <returns> /// True if the parameter takes pipeline input in any of the specified parameter /// sets, or false otherwise. /// </returns> internal bool DoesParameterSetTakePipelineInput(uint validParameterSetFlags) { if (!IsPipelineParameterInSomeParameterSet) { return false; } // Loop through each parameter set the parameter is in to see if that parameter set is // still valid. If so, and the parameter takes pipeline input in that parameter set, // then return true foreach (ParameterSetSpecificMetadata parameterSetData in ParameterSetData.Values) { if ((parameterSetData.IsInAllSets || (parameterSetData.ParameterSetFlag & validParameterSetFlags) != 0) && (parameterSetData.ValueFromPipeline || parameterSetData.ValueFromPipelineByPropertyName)) { return true; } } return false; } /// <summary> /// Gets the parameter set data for this parameter for the specified parameter set. /// </summary> /// <param name="parameterSetFlag"> /// The parameter set to get the parameter set data for. /// </param> /// <returns> /// The parameter set specified data for the specified parameter set. /// </returns> internal ParameterSetSpecificMetadata GetParameterSetData(uint parameterSetFlag) { ParameterSetSpecificMetadata result = null; foreach (ParameterSetSpecificMetadata setData in ParameterSetData.Values) { // If the parameter is in all sets, then remember the data, but // try to find a more specific match if (setData.IsInAllSets) { result = setData; } else { if ((setData.ParameterSetFlag & parameterSetFlag) != 0) { result = setData; break; } } } return result; } /// <summary> /// Gets the parameter set data for this parameter for the specified parameter sets. /// </summary> /// <param name="parameterSetFlags"> /// The parameter sets to get the parameter set data for. /// </param> /// <returns> /// A collection for all parameter set specified data for the parameter sets specified by /// the <paramref name="parameterSetFlags"/>. /// </returns> internal IEnumerable<ParameterSetSpecificMetadata> GetMatchingParameterSetData(uint parameterSetFlags) { foreach (ParameterSetSpecificMetadata setData in ParameterSetData.Values) { // If the parameter is in all sets, then remember the data, but // try to find a more specific match if (setData.IsInAllSets) { yield return setData; } else { if ((setData.ParameterSetFlag & parameterSetFlags) != 0) { yield return setData; } } } } #region helper methods /// <summary> /// Processes the Attribute metadata to generate a CompiledCommandAttribute. /// </summary> /// <exception cref="MetadataException"> /// If the attribute is a parameter attribute and another parameter attribute /// has been processed with the same parameter-set name. /// </exception> private void ProcessAttribute( string memberName, Attribute attribute, ref Collection<ValidateArgumentsAttribute> validationAttributes, ref Collection<ArgumentTransformationAttribute> argTransformationAttributes, ref string[] aliases) { if (attribute == null) return; CompiledAttributes.Add(attribute); // Now process the attribute based on it's type if (attribute is ParameterAttribute paramAttr) { ProcessParameterAttribute(memberName, paramAttr); return; } ValidateArgumentsAttribute validateAttr = attribute as ValidateArgumentsAttribute; if (validateAttr != null) { if (validationAttributes == null) validationAttributes = new Collection<ValidateArgumentsAttribute>(); validationAttributes.Add(validateAttr); if ((attribute is ValidateNotNullAttribute) || (attribute is ValidateNotNullOrEmptyAttribute)) { this.CannotBeNull = true; } return; } AliasAttribute aliasAttr = attribute as AliasAttribute; if (aliasAttr != null) { if (aliases == null) { aliases = aliasAttr.aliasNames; } else { var prevAliasNames = aliases; var newAliasNames = aliasAttr.aliasNames; aliases = new string[prevAliasNames.Length + newAliasNames.Length]; Array.Copy(prevAliasNames, aliases, prevAliasNames.Length); Array.Copy(newAliasNames, 0, aliases, prevAliasNames.Length, newAliasNames.Length); } return; } ArgumentTransformationAttribute argumentAttr = attribute as ArgumentTransformationAttribute; if (argumentAttr != null) { if (argTransformationAttributes == null) argTransformationAttributes = new Collection<ArgumentTransformationAttribute>(); argTransformationAttributes.Add(argumentAttr); return; } AllowNullAttribute allowNullAttribute = attribute as AllowNullAttribute; if (allowNullAttribute != null) { this.AllowsNullArgument = true; return; } AllowEmptyStringAttribute allowEmptyStringAttribute = attribute as AllowEmptyStringAttribute; if (allowEmptyStringAttribute != null) { this.AllowsEmptyStringArgument = true; return; } AllowEmptyCollectionAttribute allowEmptyCollectionAttribute = attribute as AllowEmptyCollectionAttribute; if (allowEmptyCollectionAttribute != null) { this.AllowsEmptyCollectionArgument = true; return; } ObsoleteAttribute obsoleteAttr = attribute as ObsoleteAttribute; if (obsoleteAttr != null) { ObsoleteAttribute = obsoleteAttr; return; } PSTypeNameAttribute psTypeNameAttribute = attribute as PSTypeNameAttribute; if (psTypeNameAttribute != null) { this.PSTypeName = psTypeNameAttribute.PSTypeName; } } /// <summary> /// Extracts the data from the ParameterAttribute and creates the member data as necessary. /// </summary> /// <param name="parameterName"> /// The name of the parameter. /// </param> /// <param name="parameter"> /// The instance of the ParameterAttribute to extract the data from. /// </param> /// <exception cref="MetadataException"> /// If a parameter set name has already been declared on this parameter. /// </exception> private void ProcessParameterAttribute( string parameterName, ParameterAttribute parameter) { // If the parameter set name already exists on this parameter and the set name is the default parameter // set name, it is an error. if (ParameterSetData.ContainsKey(parameter.ParameterSetName)) { MetadataException e = new MetadataException( "ParameterDeclaredInParameterSetMultipleTimes", null, DiscoveryExceptions.ParameterDeclaredInParameterSetMultipleTimes, parameterName, parameter.ParameterSetName); throw e; } if (parameter.ValueFromPipeline || parameter.ValueFromPipelineByPropertyName) { IsPipelineParameterInSomeParameterSet = true; } if (parameter.Mandatory) { IsMandatoryInSomeParameterSet = true; } // Construct an instance of the parameter set specific data ParameterSetSpecificMetadata parameterSetSpecificData = new ParameterSetSpecificMetadata(parameter); ParameterSetData.Add(parameter.ParameterSetName, parameterSetSpecificData); } public override string ToString() { return Name; } #endregion helper methods } /// <summary> /// The types of collections that are supported as parameter types. /// </summary> internal enum ParameterCollectionType { NotCollection, IList, Array, ICollectionGeneric } /// <summary> /// Contains the collection type information for a parameter. /// </summary> internal class ParameterCollectionTypeInformation { /// <summary> /// Constructs a parameter collection type information object /// which exposes the specified Type's collection type in a /// simple way. /// </summary> /// <param name="type"> /// The type to determine the collection information for. /// </param> internal ParameterCollectionTypeInformation(Type type) { ParameterCollectionType = ParameterCollectionType.NotCollection; Diagnostics.Assert(type != null, "Caller to verify type argument"); // NTRAID#Windows OS Bugs-1009284-2004/05/11-JeffJon // What other collection types should be supported? // Look for array types // NTRAID#Windows Out of Band Releases-906820-2005/09/07 // According to MSDN, IsSubclassOf returns false if the types are exactly equal. // Should this include ==? if (type.IsSubclassOf(typeof(Array))) { ParameterCollectionType = ParameterCollectionType.Array; ElementType = type.GetElementType(); return; } if (typeof(IDictionary).IsAssignableFrom(type)) { return; } Type[] interfaces = type.GetInterfaces(); if (interfaces.Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDictionary<,>)) || (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IDictionary<,>))) { return; } bool implementsIList = (type.GetInterface(nameof(IList)) != null); // Look for class Collection<T>. Collection<T> implements IList, and also IList // is more efficient to bind than ICollection<T>. This optimization // retrieves the element type so that we can coerce the elements. // Otherwise they must already be the right type. if (implementsIList && type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Collection<>))) { ParameterCollectionType = ParameterCollectionType.IList; // figure out elementType Type[] elementTypes = type.GetGenericArguments(); Diagnostics.Assert( elementTypes.Length == 1, "Expected 1 generic argument, got " + elementTypes.Length); ElementType = elementTypes[0]; return; } // Look for interface ICollection<T>. Note that Collection<T> // does not implement ICollection<T>, and also, ICollection<T> // does not derive from IList. The only way to add elements // to an ICollection<T> is via reflected calls to Add(T), // but the advantage over plain IList is that we can typecast the elements. Type interfaceICollection = Array.Find(interfaces, static i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICollection<>)); if (interfaceICollection != null) { // We only deal with the first type for which ICollection<T> is implemented ParameterCollectionType = ParameterCollectionType.ICollectionGeneric; // figure out elementType Type[] elementTypes = interfaceICollection.GetGenericArguments(); Diagnostics.Assert( elementTypes.Length == 1, "Expected 1 generic argument, got " + elementTypes.Length); ElementType = elementTypes[0]; return; } // Look for IList if (implementsIList) { ParameterCollectionType = ParameterCollectionType.IList; // elementType remains null return; } } /// <summary> /// The collection type of the parameter. /// </summary> internal ParameterCollectionType ParameterCollectionType { get; } /// <summary> /// The type of the elements in the collection. /// </summary> internal Type ElementType { get; } } }
using System; using System.Collections.Generic; using System.Reflection; #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { /// <summary> /// TraceLogging: Type handler for empty or unsupported types. /// </summary> internal sealed class NullTypeInfo : TraceLoggingTypeInfo { public NullTypeInfo() : base(typeof(EmptyStruct)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { collector.AddGroup(name); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { return; } public override object GetData(object value) { return null; } } /// <summary> /// Type handler for simple scalar types. /// </summary> sealed class ScalarTypeInfo : TraceLoggingTypeInfo { Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc; TraceLoggingDataType nativeFormat; private ScalarTypeInfo( Type type, Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc, TraceLoggingDataType nativeFormat) : base(type) { this.formatFunc = formatFunc; this.nativeFormat = nativeFormat; } public override void WriteMetadata(TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { collector.AddScalar(name, formatFunc(format, nativeFormat)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { collector.AddScalar(value); } public static TraceLoggingTypeInfo Boolean() { return new ScalarTypeInfo(typeof(Boolean), Statics.Format8, TraceLoggingDataType.Boolean8); } public static TraceLoggingTypeInfo Byte() { return new ScalarTypeInfo(typeof(Byte), Statics.Format8, TraceLoggingDataType.UInt8); } public static TraceLoggingTypeInfo SByte() { return new ScalarTypeInfo(typeof(SByte), Statics.Format8, TraceLoggingDataType.Int8); } public static TraceLoggingTypeInfo Char() { return new ScalarTypeInfo(typeof(Char), Statics.Format16, TraceLoggingDataType.Char16); } public static TraceLoggingTypeInfo Int16() { return new ScalarTypeInfo(typeof(Int16), Statics.Format16, TraceLoggingDataType.Int16); } public static TraceLoggingTypeInfo UInt16() { return new ScalarTypeInfo(typeof(UInt16), Statics.Format16, TraceLoggingDataType.UInt16); } public static TraceLoggingTypeInfo Int32() { return new ScalarTypeInfo(typeof(Int32), Statics.Format32, TraceLoggingDataType.Int32); } public static TraceLoggingTypeInfo UInt32() { return new ScalarTypeInfo(typeof(UInt32), Statics.Format32, TraceLoggingDataType.UInt32); } public static TraceLoggingTypeInfo Int64() { return new ScalarTypeInfo(typeof(Int64), Statics.Format64, TraceLoggingDataType.Int64); } public static TraceLoggingTypeInfo UInt64() { return new ScalarTypeInfo(typeof(UInt64), Statics.Format64, TraceLoggingDataType.UInt64); } public static TraceLoggingTypeInfo IntPtr() { return new ScalarTypeInfo(typeof(IntPtr), Statics.FormatPtr, Statics.IntPtrType); } public static TraceLoggingTypeInfo UIntPtr() { return new ScalarTypeInfo(typeof(UIntPtr), Statics.FormatPtr, Statics.UIntPtrType); } public static TraceLoggingTypeInfo Single() { return new ScalarTypeInfo(typeof(Single), Statics.Format32, TraceLoggingDataType.Float); } public static TraceLoggingTypeInfo Double() { return new ScalarTypeInfo(typeof(Double), Statics.Format64, TraceLoggingDataType.Double); } public static TraceLoggingTypeInfo Guid() { return new ScalarTypeInfo(typeof(Guid), (f, t) => Statics.MakeDataType(TraceLoggingDataType.Guid, f), TraceLoggingDataType.Guid); } } /// <summary> /// Type handler for arrays of scalars /// </summary> internal sealed class ScalarArrayTypeInfo : TraceLoggingTypeInfo { Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc; TraceLoggingDataType nativeFormat; int elementSize; private ScalarArrayTypeInfo( Type type, Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc, TraceLoggingDataType nativeFormat, int elementSize) : base(type) { this.formatFunc = formatFunc; this.nativeFormat = nativeFormat; this.elementSize = elementSize; } public override void WriteMetadata(TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { collector.AddArray(name, formatFunc(format, nativeFormat)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { collector.AddArray(value, elementSize); } public static TraceLoggingTypeInfo Boolean() { return new ScalarArrayTypeInfo(typeof(Boolean[]), Statics.Format8, TraceLoggingDataType.Boolean8, sizeof(Boolean)); } public static TraceLoggingTypeInfo Byte() { return new ScalarArrayTypeInfo(typeof(Byte[]), Statics.Format8, TraceLoggingDataType.UInt8, sizeof(Byte)); } public static TraceLoggingTypeInfo SByte() { return new ScalarArrayTypeInfo(typeof(SByte[]), Statics.Format8, TraceLoggingDataType.Int8, sizeof(SByte)); } public static TraceLoggingTypeInfo Char() { return new ScalarArrayTypeInfo(typeof(Char[]), Statics.Format16, TraceLoggingDataType.Char16, sizeof(Char)); } public static TraceLoggingTypeInfo Int16() { return new ScalarArrayTypeInfo(typeof(Int16[]), Statics.Format16, TraceLoggingDataType.Int16, sizeof(Int16)); } public static TraceLoggingTypeInfo UInt16() { return new ScalarArrayTypeInfo(typeof(UInt16[]), Statics.Format16, TraceLoggingDataType.UInt16, sizeof(UInt16)); } public static TraceLoggingTypeInfo Int32() { return new ScalarArrayTypeInfo(typeof(Int32[]), Statics.Format32, TraceLoggingDataType.Int32, sizeof(Int32)); } public static TraceLoggingTypeInfo UInt32() { return new ScalarArrayTypeInfo(typeof(UInt32[]), Statics.Format32, TraceLoggingDataType.UInt32, sizeof(UInt32)); } public static TraceLoggingTypeInfo Int64() { return new ScalarArrayTypeInfo(typeof(Int64[]), Statics.Format64, TraceLoggingDataType.Int64, sizeof(Int64)); } public static TraceLoggingTypeInfo UInt64() { return new ScalarArrayTypeInfo(typeof(UInt64[]), Statics.Format64, TraceLoggingDataType.UInt64, sizeof(UInt64)); } public static TraceLoggingTypeInfo IntPtr() { return new ScalarArrayTypeInfo(typeof(IntPtr[]), Statics.FormatPtr, Statics.IntPtrType, System.IntPtr.Size); } public static TraceLoggingTypeInfo UIntPtr() { return new ScalarArrayTypeInfo(typeof(UIntPtr[]), Statics.FormatPtr, Statics.UIntPtrType, System.IntPtr.Size); } public static TraceLoggingTypeInfo Single() { return new ScalarArrayTypeInfo(typeof(Single[]), Statics.Format32, TraceLoggingDataType.Float, sizeof(Single)); } public static TraceLoggingTypeInfo Double() { return new ScalarArrayTypeInfo(typeof(Double[]), Statics.Format64, TraceLoggingDataType.Double, sizeof(Double)); } public unsafe static TraceLoggingTypeInfo Guid() { return new ScalarArrayTypeInfo(typeof(Guid), (f, t) => Statics.MakeDataType(TraceLoggingDataType.Guid, f), TraceLoggingDataType.Guid, sizeof(Guid)); } } /// <summary> /// TraceLogging: Type handler for String. /// </summary> internal sealed class StringTypeInfo : TraceLoggingTypeInfo { public StringTypeInfo() : base(typeof(string)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { collector.AddBinary(name, Statics.MakeDataType(TraceLoggingDataType.CountedUtf16String, format)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { collector.AddBinary((string)value.ReferenceValue); } } /// <summary> /// TraceLogging: Type handler for DateTime. /// </summary> internal sealed class DateTimeTypeInfo : TraceLoggingTypeInfo { public DateTimeTypeInfo() : base(typeof(DateTime)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { collector.AddScalar(name, Statics.MakeDataType(TraceLoggingDataType.FileTime, format)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { var ticks = value.ScalarValue.AsDateTime.Ticks; collector.AddScalar(ticks < 504911232000000000 ? 0 : ticks - 504911232000000000); } } /// <summary> /// TraceLogging: Type handler for DateTimeOffset. /// </summary> internal sealed class DateTimeOffsetTypeInfo : TraceLoggingTypeInfo { public DateTimeOffsetTypeInfo() : base(typeof(DateTimeOffset)) { } public override void WriteMetadata(TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { var group = collector.AddGroup(name); group.AddScalar("Ticks", Statics.MakeDataType(TraceLoggingDataType.FileTime, format)); group.AddScalar("Offset", TraceLoggingDataType.Int64); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { var dateTimeOffset = value.ScalarValue.AsDateTimeOffset; var ticks = dateTimeOffset.Ticks; collector.AddScalar(ticks < 504911232000000000 ? 0 : ticks - 504911232000000000); collector.AddScalar(dateTimeOffset.Offset.Ticks); } } /// <summary> /// TraceLogging: Type handler for TimeSpan. /// </summary> internal sealed class TimeSpanTypeInfo : TraceLoggingTypeInfo { public TimeSpanTypeInfo() : base(typeof(TimeSpan)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { collector.AddScalar(name, Statics.MakeDataType(TraceLoggingDataType.Int64, format)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { collector.AddScalar(value.ScalarValue.AsTimeSpan.Ticks); } } /// <summary> /// TraceLogging: Type handler for Decimal. (Note: not full-fidelity, exposed as Double.) /// </summary> internal sealed class DecimalTypeInfo : TraceLoggingTypeInfo { public DecimalTypeInfo() : base(typeof(Decimal)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { collector.AddScalar(name, Statics.MakeDataType(TraceLoggingDataType.Double, format)); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { collector.AddScalar((double)value.ScalarValue.AsDecimal); } } /// <summary> /// TraceLogging: Type handler for Nullable. /// </summary> internal sealed class NullableTypeInfo : TraceLoggingTypeInfo { private readonly TraceLoggingTypeInfo valueInfo; private readonly Func<PropertyValue, PropertyValue> hasValueGetter; private readonly Func<PropertyValue, PropertyValue> valueGetter; public NullableTypeInfo(Type type, List<Type> recursionCheck) : base(type) { var typeArgs = type.GenericTypeArguments; Debug.Assert(typeArgs.Length == 1); this.valueInfo = TraceLoggingTypeInfo.GetInstance(typeArgs[0], recursionCheck); this.hasValueGetter = PropertyValue.GetPropertyGetter(type.GetTypeInfo().GetDeclaredProperty("HasValue")); this.valueGetter = PropertyValue.GetPropertyGetter(type.GetTypeInfo().GetDeclaredProperty("Value")); } public override void WriteMetadata( TraceLoggingMetadataCollector collector, string name, EventFieldFormat format) { var group = collector.AddGroup(name); group.AddScalar("HasValue", TraceLoggingDataType.Boolean8); this.valueInfo.WriteMetadata(group, "Value", format); } public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value) { var hasValue = hasValueGetter(value); collector.AddScalar(hasValue); var val = hasValue.ScalarValue.AsBoolean ? valueGetter(value) : valueInfo.PropertyValueFactory(Activator.CreateInstance(valueInfo.DataType)); this.valueInfo.WriteData(collector, val); } } }
// // CanvasItem.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright 2009 Aaron Bockover // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using Hyena.Gui.Theming; namespace Hyena.Gui.Canvas { public class CanvasItem { private CanvasManager manager; private Hyena.Data.IDataBinder binder; private Theme theme; private bool prelight_in; private double prelight_opacity; #region Public API public event EventHandler<EventArgs> SizeChanged; public event EventHandler<EventArgs> LayoutUpdated; public CanvasItem () { Visible = true; Opacity = 1.0; Width = Double.NaN; Height = Double.NaN; Margin = new Thickness (0); Padding = new Thickness (0); Foreground = Brush.Black; Background = Brush.White; MarginStyle = MarginStyle.None; } public void InvalidateArrange () { CanvasItem root = RootAncestor; if (root != null && root.Manager != null) { root.Manager.QueueArrange (this); } } public void InvalidateMeasure () { CanvasItem root = RootAncestor; if (root != null && root.Manager != null) { root.Manager.QueueMeasure (this); } } public void InvalidateRender () { InvalidateRender (InvalidationRect); } public void Invalidate (Rect area) { InvalidateRender (area); } public Hyena.Data.IDataBinder Binder { get { return binder ?? (binder = new MemoryDataBinder ()); } set { binder = value; } } public virtual void Bind (object o) { Binder.Bind (o); } public virtual void Arrange () { } public Action<Cairo.Context, Theme, Rect, double> PrelightRenderer { get; set; } public virtual Size Measure (Size available) { double m_x = Margin.X; double m_y = Margin.Y; double a_w = available.Width - m_x; double a_h = available.Height - m_y; return DesiredSize = new Size ( Math.Max (0, Math.Min (a_w, Double.IsNaN (Width) ? a_w : Width + m_x)), Math.Max (0, Math.Min (a_h, Double.IsNaN (Height) ? a_h : Height + m_y)) ); } public void Render (Hyena.Data.Gui.CellContext context) { var alloc = ContentAllocation; var cr = context.Context; double opacity = Opacity; if (alloc.Width <= 0 || alloc.Height <= 0 || opacity <= 0) { return; } cr.Save (); if (opacity < 1.0) { cr.PushGroup (); } MarginStyle margin_style = MarginStyle; if (margin_style != null && margin_style != MarginStyle.None) { cr.Translate (Math.Round (Allocation.X), Math.Round (Allocation.Y)); cr.Save (); margin_style.Apply (this, cr); cr.Restore (); cr.Translate (Math.Round (Margin.Left), Math.Round (Margin.Top)); } else { cr.Translate (Math.Round (alloc.X), Math.Round (alloc.Y)); } cr.Antialias = Cairo.Antialias.Default; //cr.Rectangle (0, 0, alloc.Width, alloc.Height); //cr.Clip (); ClippedRender (context); if (PrelightRenderer != null && prelight_opacity > 0) { PrelightRenderer (context.Context, context.Theme, new Rect (0, 0, ContentAllocation.Width, ContentAllocation.Height), prelight_opacity); } //cr.ResetClip (); if (opacity < 1.0) { cr.PopGroupToSource (); cr.PaintWithAlpha (Opacity); } cr.Restore (); } public CanvasItem RootAncestor { get { CanvasItem root = this; while (root.Parent != null) { root = root.Parent; } return root; } } public CanvasItem Parent { get; set; } public Theme Theme { get { return theme ?? (Parent != null ? Parent.Theme : null); } set { theme = value; } } public virtual bool GetTooltipMarkupAt (Point pt, out string markup, out Rect area) { markup = TooltipMarkup; area = TopLevelAllocation; return markup != null; } protected string TooltipMarkup { get; set; } public bool Visible { get; set; } public double Opacity { get; set; } public Brush Foreground { get; set; } public Brush Background { get; set; } public Thickness Padding { get; set; } public MarginStyle MarginStyle { get; set; } public Size DesiredSize { get; protected set; } // FIXME need this? public Rect VirtualAllocation { get; set; } private double min_width, max_width; public double MinWidth { get { return min_width; } set { min_width = value; if (value > max_width) { max_width = value; } } } public double MaxWidth { get { return max_width; } set { max_width = value; if (value < min_width) { min_width = value; } } } public double Width { get; set; } public double Height { get; set; } private Thickness margin; public Thickness Margin { get { return margin; } set { margin = value; // Refresh the ContentAllocation etc values Allocation = allocation; } } private Rect allocation; public Rect Allocation { get { return allocation; } set { allocation = value; ContentAllocation = new Rect ( Allocation.X + Margin.Left, Allocation.Y + Margin.Top, Math.Max (0, Allocation.Width - Margin.X), Math.Max (0, Allocation.Height - Margin.Y) ); ContentSize = new Size (ContentAllocation.Width, ContentAllocation.Height); RenderSize = new Size (Math.Round (ContentAllocation.Width), Math.Round (ContentAllocation.Height)); } } public Rect ContentAllocation { get; private set; } public Size ContentSize { get; private set; } protected Size RenderSize { get; private set; } protected virtual Rect InvalidationRect { //get { return Rect.Empty; } get { return Allocation; } } #endregion public void Invalidate () { InvalidateMeasure (); InvalidateArrange (); InvalidateRender (); } protected void InvalidateRender (Rect area) { if (Parent == null) { OnInvalidate (area); } else { var alloc = Parent.ContentAllocation; area.Offset (alloc.X, alloc.Y); Parent.Invalidate (area); } } private void OnInvalidate (Rect area) { CanvasItem root = RootAncestor; if (root != null && root.Manager != null) { root.Manager.QueueRender (this, area); } else { Hyena.Log.WarningFormat ("Asked to invalidate {0} for {1} but no CanvasManager!", area, this); } } protected object BoundObject { get { return Binder.BoundObject; } set { Binder.BoundObject = value; } } private Rect TopLevelAllocation { get { var alloc = ContentAllocation; var top = this; while (top.Parent != null) { alloc.Offset (top.Parent.Allocation); top = top.Parent; } return alloc; } } protected virtual void ClippedRender (Cairo.Context cr) { } protected virtual void ClippedRender (Hyena.Data.Gui.CellContext context) { ClippedRender (context.Context); } protected virtual void OnSizeChanged () { EventHandler<EventArgs> handler = SizeChanged; if (handler != null) { handler (this, EventArgs.Empty); } } protected virtual void OnLayoutUpdated () { EventHandler<EventArgs> handler = LayoutUpdated; if (handler != null) { handler (this, EventArgs.Empty); } } internal CanvasManager Manager { get { return manager ?? (Parent != null ? Parent.Manager : null); } set { manager = value; } } #region Input Events //public event EventHandler<EventArgs> Clicked; private bool pointer_grabbed; public virtual bool IsPointerGrabbed { get { return pointer_grabbed; } } protected void GrabPointer () { pointer_grabbed = true; } protected void ReleasePointer () { pointer_grabbed = false; } public virtual bool ButtonEvent (Point press, bool pressed, uint button) { //GrabPointer (); return false; } /*public virtual void ButtonRelease () { ReleasePointer (); OnClicked (); }*/ public virtual bool CursorMotionEvent (Point cursor) { return false; } public virtual bool CursorEnterEvent () { if (PrelightRenderer != null) { prelight_in = true; prelight_stage.AddOrReset (this); } return false; } public virtual bool CursorLeaveEvent () { if (PrelightRenderer != null) { prelight_in = false; prelight_stage.AddOrReset (this); } return false; } private static Hyena.Gui.Theatrics.Stage<CanvasItem> prelight_stage = new Hyena.Gui.Theatrics.Stage<CanvasItem> (250); static CanvasItem () { prelight_stage.ActorStep += actor => { var alpha = actor.Target.prelight_opacity; alpha += actor.Target.prelight_in ? actor.StepDeltaPercent : -actor.StepDeltaPercent; actor.Target.prelight_opacity = alpha = Math.Max (0.0, Math.Min (1.0, alpha)); actor.Target.InvalidateRender (); return alpha > 0 && alpha < 1; }; } /*protected virtual void OnClicked () { var handler = Clicked; if (handler != null) { handler (this, EventArgs.Empty); } }*/ #endregion private class MemoryDataBinder : Hyena.Data.IDataBinder { public void Bind (object o) { BoundObject = o; } public object BoundObject { get; set; } } } }
// **************************************************************** // 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/?p=license&r=2.4. // **************************************************************** using System; using System.IO; using System.Reflection; namespace NUnit.Framework.Tests { public class TestFile : IDisposable { private bool _disposedValue = false; private string _resourceName; private string _fileName; #region Nested TestFile Utility Class public TestFile(string fileName, string resourceName) { _resourceName = resourceName; _fileName = fileName; Assembly a = Assembly.GetExecutingAssembly(); using (Stream s = a.GetManifestResourceStream(_resourceName)) { if (s == null) throw new Exception("Manifest Resource Stream " + _resourceName + " was not found."); byte[] buffer = new byte[1024]; using (FileStream fs = File.Create(_fileName)) { while(true) { int count = s.Read(buffer, 0, buffer.Length); if(count == 0) break; fs.Write(buffer, 0, count); } } } } protected virtual void Dispose(bool disposing) { if (!this._disposedValue) { if (disposing) { if(File.Exists(_fileName)) { File.Delete(_fileName); } } } this._disposedValue = true; } #region IDisposable Members public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); GC.SuppressFinalize(this); } #endregion } #endregion /// <summary> /// Summary description for FileAssertTests. /// </summary> [TestFixture] public class FileAssertTests : MessageChecker { #region AreEqual #region Success Tests [Test] public void AreEqualPassesWhenBothAreNull() { FileStream expected = null; FileStream actual = null; FileAssert.AreEqual( expected, actual ); } [Test] public void AreEqualPassesWithStreams() { using(TestFile tf1 = new TestFile("Test1.jpg","NUnit.Framework.Tests.TestImage1.jpg")) using(TestFile tf2 = new TestFile("Test2.jpg","NUnit.Framework.Tests.TestImage1.jpg")) { using(FileStream expected = File.OpenRead("Test1.jpg")) { using(FileStream actual = File.OpenRead("Test2.jpg")) { FileAssert.AreEqual( expected, actual ); } } } } [Test] public void AreEqualPassesWithFiles() { using(TestFile tf1 = new TestFile("Test1.jpg","NUnit.Framework.Tests.TestImage1.jpg")) using(TestFile tf2 = new TestFile("Test2.jpg","NUnit.Framework.Tests.TestImage1.jpg")) { FileAssert.AreEqual( "Test1.jpg", "Test2.jpg", "Failed using file names" ); } } [Test] public void AreEqualPassesUsingSameFileTwice() { using(TestFile tf1 = new TestFile("Test1.jpg","NUnit.Framework.Tests.TestImage1.jpg")) { FileAssert.AreEqual( "Test1.jpg", "Test1.jpg" ); } } [Test] public void AreEqualPassesWithFileInfos() { using(TestFile tf1 = new TestFile("Test1.jpg","NUnit.Framework.Tests.TestImage1.jpg")) using(TestFile tf2 = new TestFile("Test2.jpg","NUnit.Framework.Tests.TestImage1.jpg")) { FileInfo expected = new FileInfo( "Test1.jpg" ); FileInfo actual = new FileInfo( "Test2.jpg" ); FileAssert.AreEqual( expected, actual ); FileAssert.AreEqual( expected, actual ); } } [Test] public void AreEqualPassesWithTextFiles() { using(TestFile tf1 = new TestFile("Test1.txt","NUnit.Framework.Tests.TestText1.txt")) { using(TestFile tf2 = new TestFile("Test2.txt","NUnit.Framework.Tests.TestText1.txt")) { FileAssert.AreEqual( "Test1.txt", "Test2.txt" ); } } } #endregion #region Failure Tests [Test,ExpectedException(typeof(AssertionException))] public void AreEqualFailsWhenOneIsNull() { using(TestFile tf1 = new TestFile("Test1.jpg","NUnit.Framework.Tests.TestImage1.jpg")) { using(FileStream expected = File.OpenRead("Test1.jpg")) { expectedMessage = " Expected: <System.IO.FileStream>" + Environment.NewLine + " But was: null" + Environment.NewLine; FileAssert.AreEqual( expected, null ); } } } [Test,ExpectedException(typeof(AssertionException))] public void AreEqualFailsWithStreams() { string expectedFile = "Test1.jpg"; string actualFile = "Test2.jpg"; using(TestFile tf1 = new TestFile(expectedFile,"NUnit.Framework.Tests.TestImage1.jpg")) { using(TestFile tf2 = new TestFile(actualFile,"NUnit.Framework.Tests.TestImage2.jpg")) { using(FileStream expected = File.OpenRead(expectedFile)) { using(FileStream actual = File.OpenRead(actualFile)) { expectedMessage = string.Format(" Expected Stream length {0} but was {1}." + Environment.NewLine, new FileInfo(expectedFile).Length, new FileInfo(actualFile).Length); FileAssert.AreEqual( expected, actual); } } } } } [Test,ExpectedException(typeof(AssertionException))] public void AreEqualFailsWithFileInfos() { using(TestFile tf1 = new TestFile("Test1.jpg","NUnit.Framework.Tests.TestImage1.jpg")) { using(TestFile tf2 = new TestFile("Test2.jpg","NUnit.Framework.Tests.TestImage2.jpg")) { FileInfo expected = new FileInfo( "Test1.jpg" ); FileInfo actual = new FileInfo( "Test2.jpg" ); expectedMessage = string.Format(" Expected Stream length {0} but was {1}." + Environment.NewLine, expected.Length, actual.Length); FileAssert.AreEqual( expected, actual ); } } } [Test,ExpectedException(typeof(AssertionException))] public void AreEqualFailsWithFiles() { string expected = "Test1.jpg"; string actual = "Test2.jpg"; using(TestFile tf1 = new TestFile(expected,"NUnit.Framework.Tests.TestImage1.jpg")) { using(TestFile tf2 = new TestFile(actual,"NUnit.Framework.Tests.TestImage2.jpg")) { expectedMessage = string.Format(" Expected Stream length {0} but was {1}." + Environment.NewLine, new FileInfo(expected).Length, new FileInfo(actual).Length); FileAssert.AreEqual( expected, actual ); } } } [Test,ExpectedException(typeof(AssertionException))] public void AreEqualFailsWithTextFilesAfterReadingBothFiles() { using(TestFile tf1 = new TestFile("Test1.txt","NUnit.Framework.Tests.TestText1.txt")) { using(TestFile tf2 = new TestFile("Test2.txt","NUnit.Framework.Tests.TestText2.txt")) { expectedMessage = " Stream lengths are both 65600. Streams differ at offset 65597." + Environment.NewLine; FileAssert.AreEqual( "Test1.txt", "Test2.txt" ); } } } #endregion #endregion #region AreNotEqual #region Success Tests [Test] public void AreNotEqualPassesIfOneIsNull() { using(TestFile tf1 = new TestFile("Test1.jpg","NUnit.Framework.Tests.TestImage1.jpg")) { using(FileStream expected = File.OpenRead("Test1.jpg")) { FileAssert.AreNotEqual( expected, null ); } } } [Test] public void AreNotEqualPassesWithStreams() { using(TestFile tf1 = new TestFile("Test1.jpg","NUnit.Framework.Tests.TestImage1.jpg")) { using(TestFile tf2 = new TestFile("Test2.jpg","NUnit.Framework.Tests.TestImage2.jpg")) { using(FileStream expected = File.OpenRead("Test1.jpg")) { using(FileStream actual = File.OpenRead("Test2.jpg")) { FileAssert.AreNotEqual( expected, actual); } } } } } [Test] public void AreNotEqualPassesWithFiles() { using(TestFile tf1 = new TestFile("Test1.jpg","NUnit.Framework.Tests.TestImage1.jpg")) { using(TestFile tf2 = new TestFile("Test2.jpg","NUnit.Framework.Tests.TestImage2.jpg")) { FileAssert.AreNotEqual( "Test1.jpg", "Test2.jpg" ); } } } [Test] public void AreNotEqualPassesWithFileInfos() { using(TestFile tf1 = new TestFile("Test1.jpg","NUnit.Framework.Tests.TestImage1.jpg")) { using(TestFile tf2 = new TestFile("Test2.jpg","NUnit.Framework.Tests.TestImage2.jpg")) { FileInfo expected = new FileInfo( "Test1.jpg" ); FileInfo actual = new FileInfo( "Test2.jpg" ); FileAssert.AreNotEqual( expected, actual ); } } } [Test] public void AreNotEqualIteratesOverTheEntireFile() { using(TestFile tf1 = new TestFile("Test1.txt","NUnit.Framework.Tests.TestText1.txt")) { using(TestFile tf2 = new TestFile("Test2.txt","NUnit.Framework.Tests.TestText2.txt")) { FileAssert.AreNotEqual( "Test1.txt", "Test2.txt" ); } } } #endregion #region Failure Tests [Test, ExpectedException(typeof(AssertionException))] public void AreNotEqualFailsWhenBothAreNull() { FileStream expected = null; FileStream actual = null; expectedMessage = " Expected: not null" + Environment.NewLine + " But was: null" + Environment.NewLine; FileAssert.AreNotEqual( expected, actual ); } [Test,ExpectedException(typeof(AssertionException))] public void AreNotEqualFailsWithStreams() { using(TestFile tf1 = new TestFile("Test1.jpg","NUnit.Framework.Tests.TestImage1.jpg")) using(TestFile tf2 = new TestFile("Test2.jpg","NUnit.Framework.Tests.TestImage1.jpg")) using(FileStream expected = File.OpenRead("Test1.jpg")) using(FileStream actual = File.OpenRead("Test2.jpg")) { expectedMessage = " Expected: not <System.IO.FileStream>" + Environment.NewLine + " But was: <System.IO.FileStream>" + Environment.NewLine; FileAssert.AreNotEqual( expected, actual ); } } [Test,ExpectedException(typeof(AssertionException))] public void AreNotEqualFailsWithFileInfos() { using(TestFile tf1 = new TestFile("Test1.jpg","NUnit.Framework.Tests.TestImage1.jpg")) { using(TestFile tf2 = new TestFile("Test2.jpg","NUnit.Framework.Tests.TestImage1.jpg")) { FileInfo expected = new FileInfo( "Test1.jpg" ); FileInfo actual = new FileInfo( "Test2.jpg" ); expectedMessage = " Expected: not <System.IO.FileStream>" + Environment.NewLine + " But was: <System.IO.FileStream>" + Environment.NewLine; FileAssert.AreNotEqual( expected, actual ); } } } [Test,ExpectedException(typeof(AssertionException))] public void AreNotEqualFailsWithFiles() { using(TestFile tf1 = new TestFile("Test1.jpg","NUnit.Framework.Tests.TestImage1.jpg")) { expectedMessage = " Expected: not <System.IO.FileStream>" + Environment.NewLine + " But was: <System.IO.FileStream>" + Environment.NewLine; FileAssert.AreNotEqual( "Test1.jpg", "Test1.jpg" ); } } [Test,ExpectedException(typeof(AssertionException))] public void AreNotEqualIteratesOverTheEntireFileAndFails() { using(TestFile tf1 = new TestFile("Test1.txt","NUnit.Framework.Tests.TestText1.txt")) { using(TestFile tf2 = new TestFile("Test2.txt","NUnit.Framework.Tests.TestText1.txt")) { expectedMessage = " Expected: not <System.IO.FileStream>" + Environment.NewLine + " But was: <System.IO.FileStream>" + Environment.NewLine; FileAssert.AreNotEqual( "Test1.txt", "Test2.txt" ); } } } #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. using System.Diagnostics; using System.Threading.Tasks; using Xunit; namespace System.Threading.Tests { /// <summary> /// Barrier unit tests /// </summary> public class BarrierTests { /// <summary> /// Runs all the unit tests /// </summary> /// <returns>True if all tests succeeded, false if one or more tests failed</returns> [Fact] public static void RunBarrierConstructorTests() { RunBarrierTest1_ctor(10, null); RunBarrierTest1_ctor(0, null); } [Fact] public static void RunBarrierConstructorTests_NegativeTests() { RunBarrierTest1_ctor(-1, typeof(ArgumentOutOfRangeException)); RunBarrierTest1_ctor(int.MaxValue, typeof(ArgumentOutOfRangeException)); } /// <summary> /// Testing Barrier constructor /// </summary> /// <param name="initialCount">The initial barrier count</param> /// <param name="exceptionType">Type of the exception in case of invalid input, null for valid cases</param> /// <returns>True if the test succeeded, false otherwise</returns> private static void RunBarrierTest1_ctor(int initialCount, Type exceptionType) { try { Barrier b = new Barrier(initialCount); Assert.Equal(initialCount, b.ParticipantCount); } catch (Exception ex) { Assert.NotNull(exceptionType); Assert.IsType(exceptionType, ex); } } [Fact] public static void RunBarrierSignalAndWaitTests() { RunBarrierTest2_SignalAndWait(1, new TimeSpan(0, 0, 0, 0, -1), true, null); RunBarrierTest2_SignalAndWait(5, new TimeSpan(0, 0, 0, 0, 100), false, null); RunBarrierTest2_SignalAndWait(5, new TimeSpan(0), false, null); RunBarrierTest3_SignalAndWait(3); } [Fact] public static void RunBarrierSignalAndWaitTests_NegativeTests() { RunBarrierTest2_SignalAndWait(1, new TimeSpan(0, 0, 0, 0, -2), false, typeof(ArgumentOutOfRangeException)); } /// <summary> /// Test SignalAndWait sequential /// </summary> /// <param name="initialCount">The initial barrier participants</param> /// <param name="timeout">SignalAndWait timeout</param> /// <param name="result">Expected return value</param> /// <param name="exceptionType">Type of the exception in case of invalid input, null for valid cases</param> /// <returns>True if the test succeeded, false otherwise</returns> private static void RunBarrierTest2_SignalAndWait(int initialCount, TimeSpan timeout, bool result, Type exceptionType) { Barrier b = new Barrier(initialCount); try { Assert.Equal(result, b.SignalAndWait(timeout)); if (result && b.CurrentPhaseNumber != 1) { Assert.Equal(1, b.CurrentPhaseNumber); Assert.Equal(b.ParticipantCount, b.ParticipantsRemaining); } } catch (Exception ex) { Assert.NotNull(exceptionType); Assert.IsType(exceptionType, ex); } } /// <summary> /// Test SignalANdWait parallel /// </summary> /// <param name="initialCount">Initial barrier count</param> /// <returns>True if the test succeeded, false otherwise</returns> private static void RunBarrierTest3_SignalAndWait(int initialCount) { Barrier b = new Barrier(initialCount); for (int i = 0; i < initialCount - 1; i++) { Task.Run(() => b.SignalAndWait()); } b.SignalAndWait(); Assert.Equal(1, b.CurrentPhaseNumber); Assert.Equal(b.ParticipantCount, b.ParticipantsRemaining); } [Fact] public static void RunBarrierAddParticipantsTest() { RunBarrierTest4_AddParticipants(0, 1, null); RunBarrierTest4_AddParticipants(5, 3, null); } [Fact] public static void RunBarrierAddParticipantsTest_NegativeTests() { RunBarrierTest4_AddParticipants(0, 0, typeof(ArgumentOutOfRangeException)); RunBarrierTest4_AddParticipants(2, -1, typeof(ArgumentOutOfRangeException)); RunBarrierTest4_AddParticipants(0x00007FFF, 1, typeof(ArgumentOutOfRangeException)); RunBarrierTest4_AddParticipants(100, int.MaxValue, typeof(ArgumentOutOfRangeException)); } [Fact] public static void TooManyParticipants() { Barrier b = new Barrier(short.MaxValue); Assert.Throws<InvalidOperationException>(() => b.AddParticipant()); } [Fact] public static void RemovingParticipants() { Barrier b; b = new Barrier(1); b.RemoveParticipant(); Assert.Throws<ArgumentOutOfRangeException>(() => b.RemoveParticipant()); b = new Barrier(1); b.RemoveParticipants(1); Assert.Throws<ArgumentOutOfRangeException>(() => b.RemoveParticipants(1)); b = new Barrier(1); Assert.Throws<ArgumentOutOfRangeException>(() => b.RemoveParticipants(2)); } [Fact] public static async Task RemovingWaitingParticipants() { Barrier b = new Barrier(4); Task t = Task.Run(() => { b.SignalAndWait(); }); while (b.ParticipantsRemaining > 3) { await Task.Delay(100); } b.RemoveParticipants(2); // Legal. Succeeds. Assert.Equal(1, b.ParticipantsRemaining); Assert.Throws<ArgumentOutOfRangeException>(() => b.RemoveParticipants(20)); // Too few total to remove Assert.Equal(1, b.ParticipantsRemaining); Assert.Throws<InvalidOperationException>(() => b.RemoveParticipants(2)); // Too few remaining to remove Assert.Equal(1, b.ParticipantsRemaining); b.RemoveParticipant(); // Barrier survives the incorrect removals, and we can still remove correctly. await t; // t can now complete. } /// <summary> /// Test AddParticipants /// </summary> /// <param name="initialCount">The initial barrier participants count</param> /// <param name="participantsToAdd">The participants that will be added</param> /// <param name="exceptionType">Type of the exception in case of invalid input, null for valid cases</param> /// <returns>True if the test succeeded, false otherwise</returns> private static void RunBarrierTest4_AddParticipants(int initialCount, int participantsToAdd, Type exceptionType) { Barrier b = new Barrier(initialCount); try { Assert.Equal(0, b.AddParticipants(participantsToAdd)); Assert.Equal(initialCount + participantsToAdd, b.ParticipantCount); } catch (Exception ex) { Assert.NotNull(exceptionType); Assert.IsType(exceptionType, ex); } } [Fact] public static void RunBarrierRemoveParticipantsTests() { RunBarrierTest5_RemoveParticipants(1, 1, null); RunBarrierTest5_RemoveParticipants(10, 7, null); } [Fact] public static void RunBarrierRemoveParticipantsTests_NegativeTests() { RunBarrierTest5_RemoveParticipants(10, 0, typeof(ArgumentOutOfRangeException)); RunBarrierTest5_RemoveParticipants(1, -1, typeof(ArgumentOutOfRangeException)); RunBarrierTest5_RemoveParticipants(5, 6, typeof(ArgumentOutOfRangeException)); } /// <summary> /// Test RemoveParticipants /// </summary> /// <param name="initialCount">The initial barrier participants count</param> /// <param name="participantsToRemove">The participants that will be added</param> /// <param name="exceptionType">Type of the exception in case of invalid input, null for valid cases</param> /// <returns>True if the test succeeded, false otherwise</returns> private static void RunBarrierTest5_RemoveParticipants(int initialCount, int participantsToRemove, Type exceptionType) { Barrier b = new Barrier(initialCount); try { b.RemoveParticipants(participantsToRemove); Assert.Equal(initialCount - participantsToRemove, b.ParticipantCount); } catch (Exception ex) { Assert.NotNull(exceptionType); Assert.IsType(exceptionType, ex); } } /// <summary> /// Test Dispose /// </summary> /// <returns>True if the test succeeded, false otherwise</returns> [Fact] public static void RunBarrierTest6_Dispose() { Barrier b = new Barrier(1); b.Dispose(); Assert.Throws<ObjectDisposedException>(() => b.SignalAndWait()); } [Fact] public static void SignalBarrierWithoutParticipants() { using (Barrier b = new Barrier(0)) { Assert.Throws<InvalidOperationException>(() => b.SignalAndWait()); } } [Fact] public static void RunBarrierTest7a() { for (int j = 0; j < 100; j++) { Barrier b = new Barrier(0); Action[] actions = new Action[4]; for (int k = 0; k < 4; k++) { actions[k] = (Action)(() => { for (int i = 0; i < 400; i++) { b.AddParticipant(); b.RemoveParticipant(); } }); } Task[] tasks = new Task[actions.Length]; for (int k = 0; k < tasks.Length; k++) tasks[k] = Task.Factory.StartNew((index) => actions[(int)index](), k, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); Task.WaitAll(tasks); Assert.Equal(0, b.ParticipantCount); } } /// <summary> /// Test the case when the post phase action throws an exception /// </summary> /// <returns>True if the test succeeded, false otherwise</returns> [Fact] public static void RunBarrierTest8_PostPhaseException() { bool shouldThrow = true; int participants = 4; Barrier barrier = new Barrier(participants, (b) => { if (shouldThrow) throw new InvalidOperationException(); }); int succeededCount = 0; // Run threads that will expect BarrierPostPhaseException when they call SignalAndWait, and increment the count in the catch block // The BarrierPostPhaseException inner exception should be the real exception thrown by the post phase action Task[] threads = new Task[participants]; for (int i = 0; i < threads.Length; i++) { threads[i] = Task.Run(() => { try { barrier.SignalAndWait(); } catch (BarrierPostPhaseException ex) { if (ex.InnerException.GetType().Equals(typeof(InvalidOperationException))) Interlocked.Increment(ref succeededCount); } }); } foreach (Task t in threads) t.Wait(); Assert.Equal(participants, succeededCount); Assert.Equal(1, barrier.CurrentPhaseNumber); // turn off the exception shouldThrow = false; // Now run the threads again and they shouldn't got the exception, decrement the count if it got the exception threads = new Task[participants]; for (int i = 0; i < threads.Length; i++) { threads[i] = Task.Run(() => { try { barrier.SignalAndWait(); } catch (BarrierPostPhaseException) { Interlocked.Decrement(ref succeededCount); } }); } foreach (Task t in threads) t.Wait(); Assert.Equal(participants, succeededCount); } /// <summary> /// Test ithe case when the post phase action throws an exception /// </summary> /// <returns>True if the test succeeded, false otherwise</returns> [Fact] public static void RunBarrierTest9_PostPhaseException() { Barrier barrier = new Barrier(1, (b) => b.SignalAndWait()); EnsurePostPhaseThrew(barrier); barrier = new Barrier(1, (b) => b.Dispose()); EnsurePostPhaseThrew(barrier); barrier = new Barrier(1, (b) => b.AddParticipant()); EnsurePostPhaseThrew(barrier); barrier = new Barrier(1, (b) => b.RemoveParticipant()); EnsurePostPhaseThrew(barrier); } [Fact] [OuterLoop] public static void RunBarrierTest10a() { // Regression test for Barrier race condition for (int j = 0; j < 1000; j++) { Barrier b = new Barrier(2); Task[] tasks = new Task[2]; var src = new CancellationTokenSource(); for (int i = 0; i < tasks.Length; i++) { tasks[i] = Task.Run(() => { try { if (b.SignalAndWait(-1, src.Token)) src.Cancel(); } catch (OperationCanceledException) { } }); } Task.WaitAll(tasks); } } [Fact] public static void RunBarrierTest10b() { // Regression test for Barrier race condition for (int j = 0; j < 10; j++) { Barrier b = new Barrier(2); var t1 = Task.Run(() => { b.SignalAndWait(); b.RemoveParticipant(); b.SignalAndWait(); }); var t2 = Task.Run(() => b.SignalAndWait()); Task.WaitAll(t1, t2); if (j > 0 && j % 1000 == 0) Debug.WriteLine(" > Finished {0} iterations", j); } } [Fact] public static void RunBarrierTest10c() { for (int j = 0; j < 10; j++) { Task[] tasks = new Task[2]; Barrier b = new Barrier(3); tasks[0] = Task.Run(() => b.SignalAndWait()); tasks[1] = Task.Run(() => b.SignalAndWait()); b.SignalAndWait(); b.Dispose(); GC.Collect(); Task.WaitAll(tasks); } } [Fact] public static void PostPhaseException() { Exception exc = new Exception("inner"); Assert.NotNull(new BarrierPostPhaseException().Message); Assert.NotNull(new BarrierPostPhaseException((string)null).Message); Assert.Equal("test", new BarrierPostPhaseException("test").Message); Assert.NotNull(new BarrierPostPhaseException(exc).Message); Assert.Same(exc, new BarrierPostPhaseException(exc).InnerException); Assert.Equal("test", new BarrierPostPhaseException("test", exc).Message); Assert.Same(exc, new BarrierPostPhaseException("test", exc).InnerException); } #region Helper Methods /// <summary> /// Ensures the post phase action throws if Dispose,SignalAndWait and Add/Remove participants called from it. /// </summary> private static void EnsurePostPhaseThrew(Barrier barrier) { BarrierPostPhaseException be = Assert.Throws<BarrierPostPhaseException>(() => barrier.SignalAndWait()); Assert.IsType<InvalidOperationException>(be.InnerException); } #endregion } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace OpenLiveWriter.CoreServices.Settings { /// <summary> /// A simple mechanism for serializing/deserializing arbitrary data types to the registry. /// </summary> public class RegistryCodec { # region Singleton private static RegistryCodec singleton = new RegistryCodec(); private RegistryCodec(){} public static RegistryCodec Instance { get { return singleton; } } #endregion /// <summary> /// The available codecs, in order of priority (highest priority first). /// Any <c>Codec</c> that is not part of this list will never get called. /// </summary> private Codec[] codecs = { // common types up top new StringCodec(), new BooleanCodec(), new Int32Codec(), new DoubleCodec(), new Int64Codec(), // now all other primitive types new SByteCodec(), new ByteCodec(), new CharCodec(), new Int16Codec(), new UInt16Codec(), new UInt32Codec(), new UInt64Codec(), new FloatCodec(), new DecimalCodec(), // date-time new DateTimeCodec(), new RectangleCodec(), new PointCodec(), new SizeCodec(), new SizeFCodec(), new MultiStringCodec(), // catch-all case new SerializableCodec() }; /// <summary> /// A cache of previously matchd type/codec pairs. /// Keys are <c>Types</c>, values are <c>Codecs</c>. /// </summary> private Hashtable codecCache = new Hashtable(); /// <summary> /// Take a native value and return a registry-ready representation. /// </summary> public object Encode(object val) { return GetCodec(val.GetType()).Encode(val); } /// <summary> /// Take a registry representation and return a native value. /// </summary> public object Decode(object val, Type desiredType) { return GetCodec(desiredType).Decode(val); } protected Codec GetCodec(Type type) { lock(this) { // if cached, return immediately if (codecCache.ContainsKey(type)) return (Codec)codecCache[type]; // not cached? then iterate over the list foreach (Codec c in codecs) { if (c.CanHandle(type)) { // put it in the cache codecCache[type] = c; return c; } } } // this is bad! Debug.Fail("No codec was found for type " + type.ToString()); return null; } /// <summary> /// Basic interface for encoding/decoding values to/from registry. /// Any concrete impl of this interface must be threadsafe and /// must be added to RegistryCodec.codecs. /// </summary> public abstract class Codec { /// <summary> /// Subclasses that can handle only one exact type should override this /// method. All other subclasses should override <c>CanHandle</c>. No /// subclass should override both. /// </summary> protected virtual Type Type() { return null; } /// <summary> /// Returns true if the codec can be used to encode/decode an object /// of the specified <c>Type</c>. Most subclasses should leave this alone /// and override the <c>Type</c> method. /// </summary> public virtual bool CanHandle(Type type) { return Type().Equals(type); } /// <summary> /// Convert a native object into a symmetrically persistable type (see below). /// /// This method will only be called if the type of the "val" parameter /// caused CanHandle to return true. A properly written subclass will /// never throw ClassCastException on this method. /// /// The type returned by this method must be something that can /// be symmetrically persisted into the registry; i.e., when RegistryKey.GetValue /// is called, the value returned must be equal to the value that was /// previously passed in to RegistryKey.SetValue. Types that are OK /// include strings, ints, longs, and byte arrays. Types that are not OK /// include floating point values (which can be stored, but come back as /// strings). /// </summary> public abstract object Encode(object val); /// <summary> /// Convert a symetrically persistable type back into a native object. /// /// The return value should be of the same type as Encode() expects /// to receive. The val parameter can reasonably expected to be of /// the same type as Encode() returns. However, if someone goes into /// the registry and changes the types of the values, for example, then /// all bets are off. No need to code defensively around that case, though; /// that will be handled at a higher level. It's OK just to throw an exception /// here. /// </summary> public abstract object Decode(object val); } /// <summary> /// Abstract impl of codec for values that can be stored "as-is" in the registry. /// </summary> abstract class PassthoughCodec : Codec { public override object Encode(object val) { return val; } public override object Decode(object val) { return val; } } /// <summary> /// Abstract impl of codec for values that can be stored as their /// natural string representation in the registry. /// </summary> abstract class StringifyCodec : Codec { public override object Encode(object val) { return Convert.ToString(val, CultureInfo.InvariantCulture); } public sealed override object Decode(object val) { return DecodeString((string)val); } protected abstract object DecodeString(string val); } /// <summary> /// Abstract impl of codec for values that can be represented as ints. /// This is basically for the integral value types that are smaller than /// Int32. /// </summary> abstract class IntifyCodec : Codec { public override object Encode(object val) { return ((IConvertible)val).ToInt32(CultureInfo.InvariantCulture); } } class StringCodec : PassthoughCodec { protected override Type Type() { return typeof(string); } } class MultiStringCodec : PassthoughCodec { protected override Type Type() { return typeof(string[]); } } class BooleanCodec : Codec { protected override Type Type() { return typeof(bool); } public override object Encode(object val) { return (bool)val ? 1 : 0; } public override object Decode(object val) { int intValue = (int)val; return (int)val == 1; } } #region Integral datatypes class SByteCodec : IntifyCodec { protected override Type Type() {return typeof(sbyte);} public override object Decode(object val) {return ((IConvertible)val).ToSByte(NumberFormatInfo.CurrentInfo);} } class ByteCodec : IntifyCodec { protected override Type Type() {return typeof(byte);} public override object Decode(object val) {return ((IConvertible)val).ToByte(NumberFormatInfo.CurrentInfo);} } class CharCodec : StringifyCodec { protected override Type Type() {return typeof(char);} protected override object DecodeString(string val) {return val.ToCharArray(0, 1)[0];} } class Int16Codec : IntifyCodec { protected override Type Type() {return typeof(short);} public override object Decode(object val) {return (short)val;} } class UInt16Codec : IntifyCodec { protected override Type Type() {return typeof(ushort);} public override object Decode(object val) {return (ushort)val;} } class Int32Codec : PassthoughCodec { protected override Type Type() {return typeof(int);} } class UInt32Codec : StringifyCodec { protected override Type Type() {return typeof(uint);} protected override object DecodeString(string val) {return uint.Parse(val, CultureInfo.InvariantCulture);} } class Int64Codec : StringifyCodec { protected override Type Type() {return typeof(long);} protected override object DecodeString(string val) {return long.Parse(val, CultureInfo.InvariantCulture);} } class UInt64Codec : StringifyCodec { protected override Type Type() {return typeof(ulong);} protected override object DecodeString(string val) {return ulong.Parse(val, CultureInfo.InvariantCulture);} } #endregion #region Floating-point datatypes class DoubleCodec : StringifyCodec { protected override Type Type() { return typeof(double); } protected override object DecodeString(string val) { return double.Parse(val, CultureInfo.InvariantCulture); } } class FloatCodec : StringifyCodec { protected override Type Type() { return typeof(float); } protected override object DecodeString(string val) { return float.Parse(val, CultureInfo.InvariantCulture); } } #endregion class DecimalCodec : StringifyCodec { protected override Type Type() {return typeof(decimal);} protected override object DecodeString(string val) {return decimal.Parse(val, CultureInfo.InvariantCulture);} } /// <summary> /// Uses a string of ticks (millis) as the registry representation. /// </summary> class DateTimeCodec : Codec { protected override Type Type() { return typeof(DateTime); } public override object Encode(object val) { return ((DateTime)val).Ticks.ToString(CultureInfo.InvariantCulture); } public override object Decode(object val) { return new DateTime(long.Parse((string)val, CultureInfo.InvariantCulture)); } } /// <summary> /// Persists a System.Drawing.Rectangle into "<x>,<y>,<width>,<height>". /// Useful for saving System.Windows.Control.Bounds. /// </summary> class RectangleCodec : Codec { protected override Type Type() { return typeof(Rectangle); } public override object Encode(object val) { Rectangle r = (Rectangle)val; return string.Format(CultureInfo.InvariantCulture, "{0},{1},{2},{3}", r.Left, r.Top, r.Width, r.Height); } public override object Decode(object val) { string[] strings = ((string)val).Split(','); if (strings.Length != 4) return null; try { return new Rectangle( int.Parse(strings[0], CultureInfo.InvariantCulture), int.Parse(strings[1], CultureInfo.InvariantCulture), int.Parse(strings[2], CultureInfo.InvariantCulture), int.Parse(strings[3], CultureInfo.InvariantCulture)); } catch { return null; } } } /// <summary> /// Persists a System.Drawing.Point into "<x>,<y>". /// Useful for saving System.Windows.Control.Bounds.Location. /// </summary> class PointCodec : Codec { protected override Type Type() { return typeof(Point); } public override object Encode(object val) { Point p = (Point)val; return string.Format(CultureInfo.InvariantCulture, "{0},{1}", p.X, p.Y); } public override object Decode(object val) { string[] strings = ((string)val).Split(','); if (strings.Length != 2) return null; try { return new Point( int.Parse(strings[0], CultureInfo.InvariantCulture), int.Parse(strings[1], CultureInfo.InvariantCulture)); } catch { return null; } } } /// <summary> /// Persists a System.Drawing.Size into "<x>,<y>". /// Useful for saving System.Windows.Control.Bounds.Size. /// </summary> class SizeCodec : Codec { protected override Type Type() { return typeof(Size); } public override object Encode(object val) { Size s = (Size)val; return string.Format(CultureInfo.InvariantCulture, "{0},{1}", s.Width, s.Height); } public override object Decode(object val) { string[] strings = ((string)val).Split(','); if (strings.Length != 2) return null; try { return new Size( int.Parse(strings[0], CultureInfo.InvariantCulture), int.Parse(strings[1], CultureInfo.InvariantCulture)); } catch { return null; } } } /// <summary> /// Persists a System.Drawing.Size into "<x>,<y>". /// Useful for saving System.Windows.Control.Bounds.Size. /// </summary> class SizeFCodec : Codec { protected override Type Type() { return typeof(SizeF); } public override object Encode(object val) { SizeF s = (SizeF)val; return string.Format(CultureInfo.InvariantCulture, "{0},{1}", s.Width, s.Height); } public override object Decode(object val) { string[] strings = ((string)val).Split(','); if (strings.Length != 2) return null; try { return new SizeF( float.Parse(strings[0], CultureInfo.InvariantCulture), float.Parse(strings[1], CultureInfo.InvariantCulture)); } catch { return null; } } } /// <summary> /// Handles any ISerializable type by converting to/from byte array. /// </summary> internal class SerializableCodec : Codec { /// <summary> /// Unlike the other codecs, Serializable can handle a variety /// of types--anything that can be serialized. /// </summary> public override bool CanHandle(Type type) { return type.IsSerializable; } public override object Encode(object val) { byte[] data; using (MemoryStream ms = new MemoryStream(1000)) { BinaryFormatter formatter = new BinaryFormatter(); // not threadsafe, so must create locally formatter.Serialize(ms, val); data = ms.ToArray(); } return data; } public override object Decode(object val) { return Deserialize((byte[]) val); } public static object Deserialize(byte[] data) { using (MemoryStream ms = new MemoryStream(data)) { BinaryFormatter formatter = new BinaryFormatter(); // not threadsafe, so must create locally return formatter.Deserialize(ms); } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System; class r8NaNmul { //user-defined class that overloads operator * public class numHolder { double d_num; public numHolder(double d_num) { this.d_num = Convert.ToDouble(d_num); } public static double operator *(numHolder a, double b) { return a.d_num * b; } public static double operator *(numHolder a, numHolder b) { return a.d_num * b.d_num; } } static double d_s_test1_op1 = Double.NegativeInfinity; static double d_s_test1_op2 = Double.NaN; static double d_s_test2_op1 = Double.NaN; static double d_s_test2_op2 = Double.PositiveInfinity; static double d_s_test3_op1 = Double.NaN; static double d_s_test3_op2 = 0; public static double d_test1_f(String s) { if (s == "test1_op1") return Double.NegativeInfinity; else return Double.NaN; } public static double d_test2_f(String s) { if (s == "test2_op1") return Double.NaN; else return Double.PositiveInfinity; } public static double d_test3_f(String s) { if (s == "test3_op1") return Double.NaN; else return 0; } class CL { public double d_cl_test1_op1 = Double.NegativeInfinity; public double d_cl_test1_op2 = Double.NaN; public double d_cl_test2_op1 = Double.NaN; public double d_cl_test2_op2 = Double.PositiveInfinity; public double d_cl_test3_op1 = Double.NaN; public double d_cl_test3_op2 = 0; } struct VT { public double d_vt_test1_op1; public double d_vt_test1_op2; public double d_vt_test2_op1; public double d_vt_test2_op2; public double d_vt_test3_op1; public double d_vt_test3_op2; } public static int Main() { bool passed = true; //initialize class CL cl1 = new CL(); //initialize struct VT vt1; vt1.d_vt_test1_op1 = Double.NegativeInfinity; vt1.d_vt_test1_op2 = Double.NaN; vt1.d_vt_test2_op1 = Double.NaN; vt1.d_vt_test2_op2 = Double.PositiveInfinity; vt1.d_vt_test3_op1 = Double.NaN; vt1.d_vt_test3_op2 = 0; double[] d_arr1d_test1_op1 = { 0, Double.NegativeInfinity }; double[,] d_arr2d_test1_op1 = { { 0, Double.NegativeInfinity }, { 1, 1 } }; double[, ,] d_arr3d_test1_op1 = { { { 0, Double.NegativeInfinity }, { 1, 1 } } }; double[] d_arr1d_test1_op2 = { Double.NaN, 0, 1 }; double[,] d_arr2d_test1_op2 = { { 0, Double.NaN }, { 1, 1 } }; double[, ,] d_arr3d_test1_op2 = { { { 0, Double.NaN }, { 1, 1 } } }; double[] d_arr1d_test2_op1 = { 0, Double.NaN }; double[,] d_arr2d_test2_op1 = { { 0, Double.NaN }, { 1, 1 } }; double[, ,] d_arr3d_test2_op1 = { { { 0, Double.NaN }, { 1, 1 } } }; double[] d_arr1d_test2_op2 = { Double.PositiveInfinity, 0, 1 }; double[,] d_arr2d_test2_op2 = { { 0, Double.PositiveInfinity }, { 1, 1 } }; double[, ,] d_arr3d_test2_op2 = { { { 0, Double.PositiveInfinity }, { 1, 1 } } }; double[] d_arr1d_test3_op1 = { 0, Double.NaN }; double[,] d_arr2d_test3_op1 = { { 0, Double.NaN }, { 1, 1 } }; double[, ,] d_arr3d_test3_op1 = { { { 0, Double.NaN }, { 1, 1 } } }; double[] d_arr1d_test3_op2 = { 0, 0, 1 }; double[,] d_arr2d_test3_op2 = { { 0, 0 }, { 1, 1 } }; double[, ,] d_arr3d_test3_op2 = { { { 0, 0 }, { 1, 1 } } }; int[,] index = { { 0, 0 }, { 1, 1 } }; { double d_l_test1_op1 = Double.NegativeInfinity; double d_l_test1_op2 = Double.NaN; if (!Double.IsNaN(d_l_test1_op1 * d_l_test1_op2)) { Console.WriteLine("Test1_testcase 1 failed"); passed = false; } if (!Double.IsNaN(d_l_test1_op1 * d_s_test1_op2)) { Console.WriteLine("Test1_testcase 2 failed"); passed = false; } if (!Double.IsNaN(d_l_test1_op1 * d_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 3 failed"); passed = false; } if (!Double.IsNaN(d_l_test1_op1 * cl1.d_cl_test1_op2)) { Console.WriteLine("Test1_testcase 4 failed"); passed = false; } if (!Double.IsNaN(d_l_test1_op1 * vt1.d_vt_test1_op2)) { Console.WriteLine("Test1_testcase 5 failed"); passed = false; } if (!Double.IsNaN(d_l_test1_op1 * d_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 6 failed"); passed = false; } if (!Double.IsNaN(d_l_test1_op1 * d_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 7 failed"); passed = false; } if (!Double.IsNaN(d_l_test1_op1 * d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 8 failed"); passed = false; } if (!Double.IsNaN(d_s_test1_op1 * d_l_test1_op2)) { Console.WriteLine("Test1_testcase 9 failed"); passed = false; } if (!Double.IsNaN(d_s_test1_op1 * d_s_test1_op2)) { Console.WriteLine("Test1_testcase 10 failed"); passed = false; } if (!Double.IsNaN(d_s_test1_op1 * d_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 11 failed"); passed = false; } if (!Double.IsNaN(d_s_test1_op1 * cl1.d_cl_test1_op2)) { Console.WriteLine("Test1_testcase 12 failed"); passed = false; } if (!Double.IsNaN(d_s_test1_op1 * vt1.d_vt_test1_op2)) { Console.WriteLine("Test1_testcase 13 failed"); passed = false; } if (!Double.IsNaN(d_s_test1_op1 * d_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 14 failed"); passed = false; } if (!Double.IsNaN(d_s_test1_op1 * d_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 15 failed"); passed = false; } if (!Double.IsNaN(d_s_test1_op1 * d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 16 failed"); passed = false; } if (!Double.IsNaN(d_test1_f("test1_op1") * d_l_test1_op2)) { Console.WriteLine("Test1_testcase 17 failed"); passed = false; } if (!Double.IsNaN(d_test1_f("test1_op1") * d_s_test1_op2)) { Console.WriteLine("Test1_testcase 18 failed"); passed = false; } if (!Double.IsNaN(d_test1_f("test1_op1") * d_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 19 failed"); passed = false; } if (!Double.IsNaN(d_test1_f("test1_op1") * cl1.d_cl_test1_op2)) { Console.WriteLine("Test1_testcase 20 failed"); passed = false; } if (!Double.IsNaN(d_test1_f("test1_op1") * vt1.d_vt_test1_op2)) { Console.WriteLine("Test1_testcase 21 failed"); passed = false; } if (!Double.IsNaN(d_test1_f("test1_op1") * d_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 22 failed"); passed = false; } if (!Double.IsNaN(d_test1_f("test1_op1") * d_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 23 failed"); passed = false; } if (!Double.IsNaN(d_test1_f("test1_op1") * d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 24 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test1_op1 * d_l_test1_op2)) { Console.WriteLine("Test1_testcase 25 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test1_op1 * d_s_test1_op2)) { Console.WriteLine("Test1_testcase 26 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test1_op1 * d_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 27 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test1_op1 * cl1.d_cl_test1_op2)) { Console.WriteLine("Test1_testcase 28 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test1_op1 * vt1.d_vt_test1_op2)) { Console.WriteLine("Test1_testcase 29 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test1_op1 * d_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 30 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test1_op1 * d_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 31 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test1_op1 * d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 32 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test1_op1 * d_l_test1_op2)) { Console.WriteLine("Test1_testcase 33 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test1_op1 * d_s_test1_op2)) { Console.WriteLine("Test1_testcase 34 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test1_op1 * d_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 35 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test1_op1 * cl1.d_cl_test1_op2)) { Console.WriteLine("Test1_testcase 36 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test1_op1 * vt1.d_vt_test1_op2)) { Console.WriteLine("Test1_testcase 37 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test1_op1 * d_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 38 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test1_op1 * d_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 39 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test1_op1 * d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 40 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test1_op1[1] * d_l_test1_op2)) { Console.WriteLine("Test1_testcase 41 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test1_op1[1] * d_s_test1_op2)) { Console.WriteLine("Test1_testcase 42 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test1_op1[1] * d_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 43 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test1_op1[1] * cl1.d_cl_test1_op2)) { Console.WriteLine("Test1_testcase 44 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test1_op1[1] * vt1.d_vt_test1_op2)) { Console.WriteLine("Test1_testcase 45 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test1_op1[1] * d_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 46 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test1_op1[1] * d_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 47 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test1_op1[1] * d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 48 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] * d_l_test1_op2)) { Console.WriteLine("Test1_testcase 49 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] * d_s_test1_op2)) { Console.WriteLine("Test1_testcase 50 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] * d_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 51 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] * cl1.d_cl_test1_op2)) { Console.WriteLine("Test1_testcase 52 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] * vt1.d_vt_test1_op2)) { Console.WriteLine("Test1_testcase 53 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] * d_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 54 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] * d_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 55 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] * d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 56 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] * d_l_test1_op2)) { Console.WriteLine("Test1_testcase 57 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] * d_s_test1_op2)) { Console.WriteLine("Test1_testcase 58 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] * d_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 59 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] * cl1.d_cl_test1_op2)) { Console.WriteLine("Test1_testcase 60 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] * vt1.d_vt_test1_op2)) { Console.WriteLine("Test1_testcase 61 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] * d_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 62 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] * d_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 63 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] * d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 64 failed"); passed = false; } } { double d_l_test2_op1 = Double.NaN; double d_l_test2_op2 = Double.PositiveInfinity; if (!Double.IsNaN(d_l_test2_op1 * d_l_test2_op2)) { Console.WriteLine("Test2_testcase 1 failed"); passed = false; } if (!Double.IsNaN(d_l_test2_op1 * d_s_test2_op2)) { Console.WriteLine("Test2_testcase 2 failed"); passed = false; } if (!Double.IsNaN(d_l_test2_op1 * d_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 3 failed"); passed = false; } if (!Double.IsNaN(d_l_test2_op1 * cl1.d_cl_test2_op2)) { Console.WriteLine("Test2_testcase 4 failed"); passed = false; } if (!Double.IsNaN(d_l_test2_op1 * vt1.d_vt_test2_op2)) { Console.WriteLine("Test2_testcase 5 failed"); passed = false; } if (!Double.IsNaN(d_l_test2_op1 * d_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 6 failed"); passed = false; } if (!Double.IsNaN(d_l_test2_op1 * d_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 7 failed"); passed = false; } if (!Double.IsNaN(d_l_test2_op1 * d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 8 failed"); passed = false; } if (!Double.IsNaN(d_s_test2_op1 * d_l_test2_op2)) { Console.WriteLine("Test2_testcase 9 failed"); passed = false; } if (!Double.IsNaN(d_s_test2_op1 * d_s_test2_op2)) { Console.WriteLine("Test2_testcase 10 failed"); passed = false; } if (!Double.IsNaN(d_s_test2_op1 * d_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 11 failed"); passed = false; } if (!Double.IsNaN(d_s_test2_op1 * cl1.d_cl_test2_op2)) { Console.WriteLine("Test2_testcase 12 failed"); passed = false; } if (!Double.IsNaN(d_s_test2_op1 * vt1.d_vt_test2_op2)) { Console.WriteLine("Test2_testcase 13 failed"); passed = false; } if (!Double.IsNaN(d_s_test2_op1 * d_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 14 failed"); passed = false; } if (!Double.IsNaN(d_s_test2_op1 * d_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 15 failed"); passed = false; } if (!Double.IsNaN(d_s_test2_op1 * d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 16 failed"); passed = false; } if (!Double.IsNaN(d_test2_f("test2_op1") * d_l_test2_op2)) { Console.WriteLine("Test2_testcase 17 failed"); passed = false; } if (!Double.IsNaN(d_test2_f("test2_op1") * d_s_test2_op2)) { Console.WriteLine("Test2_testcase 18 failed"); passed = false; } if (!Double.IsNaN(d_test2_f("test2_op1") * d_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 19 failed"); passed = false; } if (!Double.IsNaN(d_test2_f("test2_op1") * cl1.d_cl_test2_op2)) { Console.WriteLine("Test2_testcase 20 failed"); passed = false; } if (!Double.IsNaN(d_test2_f("test2_op1") * vt1.d_vt_test2_op2)) { Console.WriteLine("Test2_testcase 21 failed"); passed = false; } if (!Double.IsNaN(d_test2_f("test2_op1") * d_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 22 failed"); passed = false; } if (!Double.IsNaN(d_test2_f("test2_op1") * d_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 23 failed"); passed = false; } if (!Double.IsNaN(d_test2_f("test2_op1") * d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 24 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test2_op1 * d_l_test2_op2)) { Console.WriteLine("Test2_testcase 25 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test2_op1 * d_s_test2_op2)) { Console.WriteLine("Test2_testcase 26 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test2_op1 * d_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 27 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test2_op1 * cl1.d_cl_test2_op2)) { Console.WriteLine("Test2_testcase 28 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test2_op1 * vt1.d_vt_test2_op2)) { Console.WriteLine("Test2_testcase 29 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test2_op1 * d_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 30 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test2_op1 * d_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 31 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test2_op1 * d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 32 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test2_op1 * d_l_test2_op2)) { Console.WriteLine("Test2_testcase 33 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test2_op1 * d_s_test2_op2)) { Console.WriteLine("Test2_testcase 34 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test2_op1 * d_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 35 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test2_op1 * cl1.d_cl_test2_op2)) { Console.WriteLine("Test2_testcase 36 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test2_op1 * vt1.d_vt_test2_op2)) { Console.WriteLine("Test2_testcase 37 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test2_op1 * d_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 38 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test2_op1 * d_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 39 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test2_op1 * d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 40 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test2_op1[1] * d_l_test2_op2)) { Console.WriteLine("Test2_testcase 41 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test2_op1[1] * d_s_test2_op2)) { Console.WriteLine("Test2_testcase 42 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test2_op1[1] * d_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 43 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test2_op1[1] * cl1.d_cl_test2_op2)) { Console.WriteLine("Test2_testcase 44 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test2_op1[1] * vt1.d_vt_test2_op2)) { Console.WriteLine("Test2_testcase 45 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test2_op1[1] * d_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 46 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test2_op1[1] * d_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 47 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test2_op1[1] * d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 48 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] * d_l_test2_op2)) { Console.WriteLine("Test2_testcase 49 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] * d_s_test2_op2)) { Console.WriteLine("Test2_testcase 50 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] * d_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 51 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] * cl1.d_cl_test2_op2)) { Console.WriteLine("Test2_testcase 52 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] * vt1.d_vt_test2_op2)) { Console.WriteLine("Test2_testcase 53 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] * d_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 54 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] * d_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 55 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] * d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 56 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] * d_l_test2_op2)) { Console.WriteLine("Test2_testcase 57 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] * d_s_test2_op2)) { Console.WriteLine("Test2_testcase 58 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] * d_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 59 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] * cl1.d_cl_test2_op2)) { Console.WriteLine("Test2_testcase 60 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] * vt1.d_vt_test2_op2)) { Console.WriteLine("Test2_testcase 61 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] * d_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 62 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] * d_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 63 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] * d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 64 failed"); passed = false; } } { double d_l_test3_op1 = Double.NaN; double d_l_test3_op2 = 0; if (!Double.IsNaN(d_l_test3_op1 * d_l_test3_op2)) { Console.WriteLine("Test3_testcase 1 failed"); passed = false; } if (!Double.IsNaN(d_l_test3_op1 * d_s_test3_op2)) { Console.WriteLine("Test3_testcase 2 failed"); passed = false; } if (!Double.IsNaN(d_l_test3_op1 * d_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 3 failed"); passed = false; } if (!Double.IsNaN(d_l_test3_op1 * cl1.d_cl_test3_op2)) { Console.WriteLine("Test3_testcase 4 failed"); passed = false; } if (!Double.IsNaN(d_l_test3_op1 * vt1.d_vt_test3_op2)) { Console.WriteLine("Test3_testcase 5 failed"); passed = false; } if (!Double.IsNaN(d_l_test3_op1 * d_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 6 failed"); passed = false; } if (!Double.IsNaN(d_l_test3_op1 * d_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 7 failed"); passed = false; } if (!Double.IsNaN(d_l_test3_op1 * d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 8 failed"); passed = false; } if (!Double.IsNaN(d_s_test3_op1 * d_l_test3_op2)) { Console.WriteLine("Test3_testcase 9 failed"); passed = false; } if (!Double.IsNaN(d_s_test3_op1 * d_s_test3_op2)) { Console.WriteLine("Test3_testcase 10 failed"); passed = false; } if (!Double.IsNaN(d_s_test3_op1 * d_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 11 failed"); passed = false; } if (!Double.IsNaN(d_s_test3_op1 * cl1.d_cl_test3_op2)) { Console.WriteLine("Test3_testcase 12 failed"); passed = false; } if (!Double.IsNaN(d_s_test3_op1 * vt1.d_vt_test3_op2)) { Console.WriteLine("Test3_testcase 13 failed"); passed = false; } if (!Double.IsNaN(d_s_test3_op1 * d_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 14 failed"); passed = false; } if (!Double.IsNaN(d_s_test3_op1 * d_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 15 failed"); passed = false; } if (!Double.IsNaN(d_s_test3_op1 * d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 16 failed"); passed = false; } if (!Double.IsNaN(d_test3_f("test3_op1") * d_l_test3_op2)) { Console.WriteLine("Test3_testcase 17 failed"); passed = false; } if (!Double.IsNaN(d_test3_f("test3_op1") * d_s_test3_op2)) { Console.WriteLine("Test3_testcase 18 failed"); passed = false; } if (!Double.IsNaN(d_test3_f("test3_op1") * d_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 19 failed"); passed = false; } if (!Double.IsNaN(d_test3_f("test3_op1") * cl1.d_cl_test3_op2)) { Console.WriteLine("Test3_testcase 20 failed"); passed = false; } if (!Double.IsNaN(d_test3_f("test3_op1") * vt1.d_vt_test3_op2)) { Console.WriteLine("Test3_testcase 21 failed"); passed = false; } if (!Double.IsNaN(d_test3_f("test3_op1") * d_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 22 failed"); passed = false; } if (!Double.IsNaN(d_test3_f("test3_op1") * d_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 23 failed"); passed = false; } if (!Double.IsNaN(d_test3_f("test3_op1") * d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 24 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test3_op1 * d_l_test3_op2)) { Console.WriteLine("Test3_testcase 25 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test3_op1 * d_s_test3_op2)) { Console.WriteLine("Test3_testcase 26 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test3_op1 * d_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 27 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test3_op1 * cl1.d_cl_test3_op2)) { Console.WriteLine("Test3_testcase 28 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test3_op1 * vt1.d_vt_test3_op2)) { Console.WriteLine("Test3_testcase 29 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test3_op1 * d_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 30 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test3_op1 * d_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 31 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test3_op1 * d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 32 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test3_op1 * d_l_test3_op2)) { Console.WriteLine("Test3_testcase 33 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test3_op1 * d_s_test3_op2)) { Console.WriteLine("Test3_testcase 34 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test3_op1 * d_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 35 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test3_op1 * cl1.d_cl_test3_op2)) { Console.WriteLine("Test3_testcase 36 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test3_op1 * vt1.d_vt_test3_op2)) { Console.WriteLine("Test3_testcase 37 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test3_op1 * d_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 38 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test3_op1 * d_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 39 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test3_op1 * d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 40 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test3_op1[1] * d_l_test3_op2)) { Console.WriteLine("Test3_testcase 41 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test3_op1[1] * d_s_test3_op2)) { Console.WriteLine("Test3_testcase 42 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test3_op1[1] * d_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 43 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test3_op1[1] * cl1.d_cl_test3_op2)) { Console.WriteLine("Test3_testcase 44 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test3_op1[1] * vt1.d_vt_test3_op2)) { Console.WriteLine("Test3_testcase 45 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test3_op1[1] * d_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 46 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test3_op1[1] * d_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 47 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test3_op1[1] * d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 48 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] * d_l_test3_op2)) { Console.WriteLine("Test3_testcase 49 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] * d_s_test3_op2)) { Console.WriteLine("Test3_testcase 50 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] * d_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 51 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] * cl1.d_cl_test3_op2)) { Console.WriteLine("Test3_testcase 52 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] * vt1.d_vt_test3_op2)) { Console.WriteLine("Test3_testcase 53 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] * d_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 54 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] * d_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 55 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] * d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 56 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] * d_l_test3_op2)) { Console.WriteLine("Test3_testcase 57 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] * d_s_test3_op2)) { Console.WriteLine("Test3_testcase 58 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] * d_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 59 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] * cl1.d_cl_test3_op2)) { Console.WriteLine("Test3_testcase 60 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] * vt1.d_vt_test3_op2)) { Console.WriteLine("Test3_testcase 61 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] * d_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 62 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] * d_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 63 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] * d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 64 failed"); passed = false; } } if (!passed) { Console.WriteLine("FAILED"); return 1; } else { Console.WriteLine("PASSED"); return 100; } } }
using System; using System.Text; using System.Collections.Generic; using csfmt.Parsers; using csfmt.Lexers; using csfmt.Exceptions; namespace csfmt.Statements { public class ParserUtils { public static StringBuilder RefOutIn(Parser psr) { var status = psr.SaveStatus(); try { var sb = new StringBuilder(); switch (psr.GetNextTextOrEmpty()) { case @"ref": case @"out": case @"in": sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); break; } return sb; } catch (ResetException) { } psr.LoadStatus(status); throw new ResetException(); } public static StringBuilder AccessModifiers(Parser psr) { var status = psr.SaveStatus(); try { var sb = new StringBuilder(); switch (psr.GetNextTextOrEmpty()) { case @"protected": sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); if (psr.GetNextTextOrEmpty() == @"internal") { sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); } break; case @"public": case @"private": case @"internal": sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); break; } return sb; } catch (ResetException) { } psr.LoadStatus(status); throw new ResetException(); } public static StringBuilder ConditionalOprator(Parser psr) { var status = psr.SaveStatus(); var sb = new StringBuilder(); try { if (psr.GetNextTextOrEmpty() == @"?") { sb.Append(psr.SpaceToken()); sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); sb.Append(Expr(psr)); if (psr.GetNextTextOrEmpty() == @":") { sb.Append(psr.SpaceToken()); sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); sb.Append(Expr(psr)); return sb; } } } catch (ResetException) { } psr.LoadStatus(status); throw new ResetException(); } public static StringBuilder AsIs(Parser psr) { var status = psr.SaveStatus(); var sb = new StringBuilder(); try { switch (psr.GetNextTextOrEmpty()) { case @"as": case @"is": sb.Append(psr.SpaceToken()); sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); sb.Append(Type(psr)); return sb; } } catch (ResetException) { } psr.LoadStatus(status); throw new ResetException(); } public static StringBuilder _Expr(Parser psr) { var status = psr.SaveStatus(); try { var sb = new StringBuilder(); sb.Append(psr.SpaceToken()); switch (psr.GetNextTextOrEmpty()) { case @"!": switch (psr.GetNextTextOrEmpty(1)) { case @"=": sb.Append(psr.Consume()); sb.Append(psr.Consume()); break; } break; case @"=": switch (psr.GetNextTextOrEmpty(1)) { case @"=": case @">": sb.Append(psr.Consume()); sb.Append(psr.Consume()); break; } break; case @"-": sb.Append(psr.Consume()); if (psr.GetNextTextOrEmpty() == @">") { sb.Append(psr.Consume()); } break; case @"+": case @"*": case @"/": case @"%": sb.Append(psr.Consume()); break; case @"|": sb.Append(psr.Consume()); if (psr.GetNextTextOrEmpty() == @"|") { sb.Append(psr.Consume()); } break; case @"&": sb.Append(psr.Consume()); if (psr.GetNextTextOrEmpty() == @"&") { sb.Append(psr.Consume()); } break; case @"<": sb.Append(psr.Consume()); switch (psr.GetNextTextOrEmpty()) { case @"<": case @"=": sb.Append(psr.Consume()); break; } break; case @">": sb.Append(psr.Consume()); switch (psr.GetNextTextOrEmpty()) { case @">": case @"=": sb.Append(psr.Consume()); break; } break; case @"?": switch (psr.GetNextTextOrEmpty(1)) { case @"?": case @".": sb.Append(psr.Consume()); sb.Append(psr.Consume()); break; } break; default: throw new ResetException(); } sb.Append(psr.SpaceToken()); sb.Append(Term(psr)); return sb; } catch (ResetException) { } psr.LoadStatus(status); throw new ResetException(); } public static StringBuilder Expr(Parser psr) { var status = psr.SaveStatus(); try { var sb = new StringBuilder(); sb.Append(Term(psr)); while (true) { try { sb.Append(_Expr(psr)); } catch (ResetException) { break; } } try { sb.Append(ConditionalOprator(psr)); } catch (ResetException) { } try { sb.Append(AsIs(psr)); } catch (ResetException) { } return sb; } catch (ResetException) { } psr.LoadStatus(status); throw new ResetException(); } public static StringBuilder Type(Parser psr) { var status = psr.SaveStatus(); try { var sb = new StringBuilder(); if (psr.GetNextTypeOrUnknown() == TokenType.Identifier) { sb.Append(psr.Consume()); while (true) { if (psr.GetNextTextOrEmpty() == @".") { sb.Append(psr.Consume()); } else { break; } if (psr.GetNextTypeOrUnknown() == TokenType.Identifier) { sb.Append(psr.Consume()); } else { throw new ResetException(); } } } else { throw new ResetException(); } if (psr.GetNextTextOrEmpty() == @"<") { sb.Append(psr.Consume()); if (psr.GetNextTextOrEmpty() != @">") { sb.Append(Type(psr)); while (psr.GetNextTextOrEmpty() == @",") { var status2 = psr.SaveStatus(); try { var sb2 = new StringBuilder(); sb2.Append(psr.Consume()); sb2.Append(psr.SpaceToken()); sb2.Append(Type(psr)); sb.Append(sb2); } catch (ResetException) { psr.LoadStatus(status2); break; } } } if (psr.GetNextTextOrEmpty() == @">") { sb.Append(psr.Consume()); } else { throw new ResetException(); } } if (psr.GetNextTextOrEmpty() == @"[" && psr.GetNextTextOrEmpty(1) == @"]") { sb.Append(psr.Consume()); sb.Append(psr.Consume()); } if (psr.GetNextTextOrEmpty() == @"?") { sb.Append(psr.Consume()); } return sb; } catch (ResetException) { } psr.LoadStatus(status); throw new ResetException(); } private static StringBuilder New(Parser psr) { var status = psr.SaveStatus(); try { var sb = new StringBuilder(); if (psr.GetNextTextOrEmpty() == @"new") { sb.Append(psr.Consume()); if (psr.GetNextTextOrEmpty() == @"[") { sb.Append(SquareBrackets(psr)); sb.Append(CurlyBrackets_Exprs(psr)); } else { try { var t = Type(psr); sb.Append(psr.SpaceToken()); sb.Append(t); } catch (ResetException) { } if (psr.GetNextTypeOrUnknown() == TokenType.ParenthesesOpen) { sb.Append(FuncArgs(psr)); } if (psr.GetNextTypeOrUnknown() == TokenType.CurlyBracketOpen) { sb.Append(CurlyBrackets_Exprs(psr)); } } return sb; } } catch (ResetException) { } psr.LoadStatus(status); throw new ResetException(); } private static StringBuilder ExprWithParenthese(Parser psr) { var status = psr.SaveStatus(); try { var sb = new StringBuilder(); if (psr.GetNextTypeOrUnknown() == TokenType.ParenthesesOpen) { sb.Append(psr.Consume()); sb.Append(Expr(psr)); if (psr.GetNextTypeOrUnknown() == TokenType.ParenthesesClose) { sb.Append(psr.Consume()); return sb; } } } catch (ResetException) { } psr.LoadStatus(status); throw new ResetException(); } private static StringBuilder SquareBrackets(Parser psr) { var status = psr.SaveStatus(); try { var sb = new StringBuilder(); while (psr.GetNextTextOrEmpty() == @"[") { sb.Append(psr.Consume()); if (psr.GetNextTextOrEmpty() != @"]") { sb.Append(ParserUtils.Expr(psr)); } if (psr.GetNextTextOrEmpty() == @"]") { sb.Append(psr.Consume()); return sb; } } } catch (ResetException) { } psr.LoadStatus(status); throw new ResetException(); } private static StringBuilder CurlyBrackets_Exprs(Parser psr) { var status = psr.SaveStatus(); try { var sb = new StringBuilder(); while (psr.GetNextTypeOrUnknown() == TokenType.CurlyBracketOpen) { sb.Append(psr.Consume()); if (psr.GetNextTypeOrUnknown() == TokenType.CurlyBracketClose) { sb.Append(psr.Consume()); return sb; } else { sb.Append(psr.LineBreakToken()); psr.IndentDown(); while (psr.GetNextTypeOrUnknown() != TokenType.CurlyBracketClose) { sb.Append(psr.IndentToken(@"ParserUtils.CurlyBrackets_Exprs")); sb.Append(Expr(psr)); if (psr.GetNextTextOrEmpty() == @"=") { sb.Append(psr.SpaceToken()); sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); sb.Append(Expr(psr)); } if (psr.GetNextTextOrEmpty() == @",") { sb.Append(psr.Consume()); } sb.Append(psr.LineBreakToken()); } if (psr.GetNextTypeOrUnknown() == TokenType.CurlyBracketClose) { psr.IndentUp(); sb.Append(psr.IndentToken(@"ParserUtils.CurlyBrackets_Exprs")); sb.Append(psr.Consume()); return sb; } } } } catch (ResetException) { } psr.LoadStatus(status); throw new ResetException(); } private static StringBuilder CurlyBracket_Statements(Parser psr) { var status = psr.SaveStatus(); try { var sb = new StringBuilder(); if (psr.GetNextTypeOrUnknown() == TokenType.CurlyBracketOpen) { sb.Append(psr.Consume()); sb.Append(psr.LineBreakToken()); psr.IndentDown(); sb.Append(psr.DefaultManyStatement()); if (psr.GetNextTypeOrUnknown() == TokenType.CurlyBracketClose) { psr.IndentUp(); sb.Append(psr.IndentToken(@"ParserUtils.CurlyBracket_Statements")); sb.Append(psr.Consume()); return sb; } } } catch (ResetException) { } psr.LoadStatus(status); throw new ResetException(); } private static StringBuilder Parentheses_Tuple(Parser psr) { var status = psr.SaveStatus(); try { var sb = new StringBuilder(); if (psr.GetNextTypeOrUnknown() == TokenType.ParenthesesOpen) { sb.Append(psr.Consume()); if (psr.GetNextTypeOrUnknown() != TokenType.ParenthesesClose) { if (psr.GetNextTextOrEmpty(1) != @"," && psr.GetNextTypeOrUnknown(1) != TokenType.ParenthesesClose) { sb.Append(Type(psr)); sb.Append(psr.SpaceToken()); } if (psr.GetNextTypeOrUnknown() == TokenType.Identifier) { sb.Append(psr.Consume()); while (psr.GetNextTextOrEmpty() == @",") { sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); if (psr.GetNextTextOrEmpty(1) != @"," && psr.GetNextTypeOrUnknown(1) != TokenType.ParenthesesClose) { sb.Append(Type(psr)); sb.Append(psr.SpaceToken()); } if (psr.GetNextTypeOrUnknown() == TokenType.Identifier) { sb.Append(psr.Consume()); } } } } if (psr.GetNextTypeOrUnknown() == TokenType.ParenthesesClose) { sb.Append(psr.Consume()); return sb; } } } catch (ResetException) { } psr.LoadStatus(status); throw new ResetException(); } private static StringBuilder Query(Parser psr) { var status = psr.SaveStatus(); try { var sb = new StringBuilder(); var doExit = false; var n = 0; while (!doExit) { switch (psr.GetNextTextOrEmpty()) { case @"let": if (0 < n) { sb.Append(psr.SpaceToken()); } sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); if (psr.GetNextTypeOrUnknown() == TokenType.Identifier && psr.GetNextTextOrEmpty(1) == @"=") { sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); sb.Append(Expr(psr)); } break; case @"where": if (0 < n) { sb.Append(psr.SpaceToken()); } sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); sb.Append(Expr(psr)); break; case @"orderby": if (0 < n) { sb.Append(psr.SpaceToken()); } sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); while (true) { sb.Append(Expr(psr)); switch (psr.GetNextTextOrEmpty()) { case @"desceding": case @"ascending": sb.Append(psr.SpaceToken()); sb.Append(psr.Consume()); break; } if (psr.GetNextTextOrEmpty() == @",") { sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); } else { break; } } break; case @"select": if (0 < n) { sb.Append(psr.SpaceToken()); } sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); sb.Append(Expr(psr)); if (psr.GetNextTextOrEmpty() == @"into") { sb.Append(psr.SpaceToken()); sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); sb.Append(Expr(psr)); } break; case @"join": if (0 < n) { sb.Append(psr.SpaceToken()); } sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); sb.Append(Expr(psr)); if (psr.GetNextTextOrEmpty() == @"in") { sb.Append(psr.SpaceToken()); sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); sb.Append(Expr(psr)); if (psr.GetNextTextOrEmpty() == @"on") { sb.Append(psr.SpaceToken()); sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); sb.Append(Expr(psr)); if (psr.GetNextTextOrEmpty() == @"equals") { sb.Append(psr.SpaceToken()); sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); sb.Append(Expr(psr)); if (psr.GetNextTextOrEmpty() == @"into") { sb.Append(psr.SpaceToken()); sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); sb.Append(Expr(psr)); } } } } break; case @"group": if (0 < n) { sb.Append(psr.SpaceToken()); } sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); sb.Append(Expr(psr)); if (psr.GetNextTextOrEmpty() == @"by") { sb.Append(psr.SpaceToken()); sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); sb.Append(Expr(psr)); if (psr.GetNextTextOrEmpty() == @"into") { sb.Append(psr.SpaceToken()); sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); sb.Append(Expr(psr)); } } break; case @"from": if (0 < n) { sb.Append(psr.SpaceToken()); } sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); sb.Append(Expr(psr)); if (psr.GetNextTextOrEmpty() == @"in") { sb.Append(psr.SpaceToken()); sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); sb.Append(Expr(psr)); } break; default: doExit = true; break; } n++; } return sb; } catch (ResetException) { } psr.LoadStatus(status); throw new ResetException(); } private static StringBuilder Atom(Parser psr) { var status = psr.SaveStatus(); try { var sb = new StringBuilder(); switch (psr.GetNextTypeOrUnknown()) { case TokenType.Identifier: switch (psr.GetNextTextOrEmpty()) { case @"delegate": sb.Append(psr.Consume()); if (psr.GetNextTypeOrUnknown() == TokenType.ParenthesesOpen) { sb.Append(Parentheses_Tuple(psr)); } sb.Append(CurlyBracket_Statements(psr)); break; case @"new": sb.Append(New(psr)); break; case @"select": case @"from": case @"where": case @"join": case @"orderby": case @"group": sb.Append(Query(psr)); break; default: sb.Append(psr.Consume()); break; } break; case TokenType.Number: case TokenType.Boolean: case TokenType.String: case TokenType.Char: sb.Append(psr.Consume()); break; case TokenType.ParenthesesOpen: try { sb.Append(Parentheses_Tuple(psr)); } catch (ResetException) { sb.Append(ExprWithParenthese(psr)); } break; case TokenType.CurlyBracketOpen: sb.Append(CurlyBracket_Statements(psr)); break; default: throw new ResetException(); } while (true) { try { if (psr.GetNextTypeOrUnknown() == TokenType.ParenthesesOpen) { sb.Append(FuncArgs(psr)); } else if (psr.GetNextTextOrEmpty() == @"[") { sb.Append(SquareBrackets(psr)); } else { break; } } catch (ResetException) { break; } } return sb; } catch (ResetException) { } psr.LoadStatus(status); throw new ResetException(); } private static StringBuilder Cast(Parser psr) { var status = psr.SaveStatus(); try { var sb = new StringBuilder(); if (psr.GetNextTypeOrUnknown() == TokenType.ParenthesesOpen) { sb.Append(psr.Consume()); sb.Append(Type(psr)); if (psr.GetNextTypeOrUnknown() == TokenType.ParenthesesClose) { sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); return sb; } } } catch (ResetException) { } psr.LoadStatus(status); throw new ResetException(); } private static StringBuilder Term(Parser psr) { var status = psr.SaveStatus(); try { var sb = new StringBuilder(); try { sb.Append(Cast(psr)); } catch (ResetException) { } switch (psr.GetNextTextOrEmpty()) { case @"+": case @"-": case @"*": case @"&": case @"!": case @"~": sb.Append(psr.Consume()); break; } sb.Append(Atom(psr)); while (psr.GetNextTextOrEmpty() == @".") { var status2 = psr.SaveStatus(); try { var sb2 = new StringBuilder(); sb2.Append(psr.Consume()); sb2.Append(Atom(psr)); sb.Append(sb2); } catch (ResetException) { psr.LoadStatus(status2); break; } } try { sb.Append(PostOperator(psr)); } catch (ResetException) { } return sb; } catch (ResetException) { } psr.LoadStatus(status); throw new ResetException(); } private static StringBuilder PostOperator(Parser psr) { var status = psr.SaveStatus(); try { var sb = new StringBuilder(); if (psr.GetNextTextOrEmpty() == @"+" && psr.GetNextTextOrEmpty(1) == @"+") { sb.Append(psr.Consume()); sb.Append(psr.Consume()); return sb; } else if (psr.GetNextTextOrEmpty() == @"-" && psr.GetNextTextOrEmpty(1) == @"-") { sb.Append(psr.Consume()); sb.Append(psr.Consume()); return sb; } } catch (ResetException) { } psr.LoadStatus(status); throw new ResetException(); } private static StringBuilder FuncArgs(Parser psr) { var status = psr.SaveStatus(); try { var sb = new StringBuilder(); while (psr.GetNextTypeOrUnknown() == TokenType.ParenthesesOpen) { sb.Append(psr.Consume()); while (psr.GetNextTypeOrUnknown() != TokenType.ParenthesesClose) { sb.Append(RefOutIn(psr)); sb.Append(Expr(psr)); if (psr.GetNextTextOrEmpty() == @"=") { sb.Append(psr.SpaceToken()); sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); sb.Append(ParserUtils.Expr(psr)); } if (psr.GetNextTextOrEmpty() == @",") { sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); } } if (psr.GetNextTypeOrUnknown() == TokenType.ParenthesesClose) { sb.Append(psr.Consume()); return sb; } } } catch (ResetException) { } psr.LoadStatus(status); throw new ResetException(); } public static StringBuilder Attribute(Parser psr) { var sb = new StringBuilder(); var status = psr.SaveStatus(); try { if (psr.GetNextTextOrEmpty() == @"[") { sb.Append(psr.Consume()); if (psr.GetNextTextOrEmpty(1) == @":") { switch (psr.GetNextTextOrEmpty()) { case @"assembly": case @"module": case @"type": case @"field": case @"method": case @"event": case @"property": case @"param": case @"return": sb.Append(psr.Consume()); sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); break; } } while (psr.GetNextTextOrEmpty() != @"]") { sb.Append(Expr(psr)); if (psr.GetNextTextOrEmpty() == @",") { sb.Append(psr.Consume()); sb.Append(psr.SpaceToken()); } else if (psr.GetNextTextOrEmpty() != @"]") { throw new ResetException(); } } if (psr.GetNextTextOrEmpty() == @"]") { sb.Append(psr.Consume()); return sb; } } } catch (ResetException) { } psr.LoadStatus(status); throw new ResetException(); } } }
// 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Preview; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Differencing; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Preview { public class PreviewWorkspaceTests { [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewCreationDefault() { using (var previewWorkspace = new PreviewWorkspace()) { Assert.NotNull(previewWorkspace.CurrentSolution); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewCreationWithExplicitHostServices() { var assembly = typeof(ISolutionCrawlerRegistrationService).Assembly; using (var previewWorkspace = new PreviewWorkspace(MefHostServices.Create(MefHostServices.DefaultAssemblies.Concat(assembly)))) { Assert.NotNull(previewWorkspace.CurrentSolution); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewCreationWithSolution() { using (var custom = new AdhocWorkspace()) using (var previewWorkspace = new PreviewWorkspace(custom.CurrentSolution)) { Assert.NotNull(previewWorkspace.CurrentSolution); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewAddRemoveProject() { using (var previewWorkspace = new PreviewWorkspace()) { var solution = previewWorkspace.CurrentSolution; var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp); Assert.True(previewWorkspace.TryApplyChanges(project.Solution)); var newSolution = previewWorkspace.CurrentSolution.RemoveProject(project.Id); Assert.True(previewWorkspace.TryApplyChanges(newSolution)); Assert.Equal(0, previewWorkspace.CurrentSolution.ProjectIds.Count); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewProjectChanges() { using (var previewWorkspace = new PreviewWorkspace()) { var solution = previewWorkspace.CurrentSolution; var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp); Assert.True(previewWorkspace.TryApplyChanges(project.Solution)); var addedSolution = previewWorkspace.CurrentSolution.Projects.First() .AddMetadataReference(TestReferences.NetFx.v4_0_30319.mscorlib) .AddDocument("document", "").Project.Solution; Assert.True(previewWorkspace.TryApplyChanges(addedSolution)); Assert.Equal(1, previewWorkspace.CurrentSolution.Projects.First().MetadataReferences.Count); Assert.Equal(1, previewWorkspace.CurrentSolution.Projects.First().DocumentIds.Count); var text = "class C {}"; var changedSolution = previewWorkspace.CurrentSolution.Projects.First().Documents.First().WithText(SourceText.From(text)).Project.Solution; Assert.True(previewWorkspace.TryApplyChanges(changedSolution)); Assert.Equal(previewWorkspace.CurrentSolution.Projects.First().Documents.First().GetTextAsync().Result.ToString(), text); var removedSolution = previewWorkspace.CurrentSolution.Projects.First() .RemoveMetadataReference(previewWorkspace.CurrentSolution.Projects.First().MetadataReferences[0]) .RemoveDocument(previewWorkspace.CurrentSolution.Projects.First().DocumentIds[0]).Solution; Assert.True(previewWorkspace.TryApplyChanges(removedSolution)); Assert.Equal(0, previewWorkspace.CurrentSolution.Projects.First().MetadataReferences.Count); Assert.Equal(0, previewWorkspace.CurrentSolution.Projects.First().DocumentIds.Count); } } [WorkItem(923121)] [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewOpenCloseFile() { using (var previewWorkspace = new PreviewWorkspace()) { var solution = previewWorkspace.CurrentSolution; var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp); var document = project.AddDocument("document", ""); Assert.True(previewWorkspace.TryApplyChanges(document.Project.Solution)); previewWorkspace.OpenDocument(document.Id); Assert.Equal(1, previewWorkspace.GetOpenDocumentIds().Count()); Assert.True(previewWorkspace.IsDocumentOpen(document.Id)); previewWorkspace.CloseDocument(document.Id); Assert.Equal(0, previewWorkspace.GetOpenDocumentIds().Count()); Assert.False(previewWorkspace.IsDocumentOpen(document.Id)); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewServices() { using (var previewWorkspace = new PreviewWorkspace(MefV1HostServices.Create(TestExportProvider.ExportProviderWithCSharpAndVisualBasic.AsExportProvider()))) { var service = previewWorkspace.Services.GetService<ISolutionCrawlerRegistrationService>(); Assert.True(service is PreviewSolutionCrawlerRegistrationService); var persistentService = previewWorkspace.Services.GetService<IPersistentStorageService>(); Assert.NotNull(persistentService); var storage = persistentService.GetStorage(previewWorkspace.CurrentSolution); Assert.True(storage is NoOpPersistentStorage); } } [WorkItem(923196)] [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewDiagnostic() { var diagnosticService = TestExportProvider.ExportProviderWithCSharpAndVisualBasic.GetExportedValue<IDiagnosticAnalyzerService>() as IDiagnosticUpdateSource; var taskSource = new TaskCompletionSource<DiagnosticsUpdatedArgs>(); diagnosticService.DiagnosticsUpdated += (s, a) => taskSource.TrySetResult(a); using (var previewWorkspace = new PreviewWorkspace(MefV1HostServices.Create(TestExportProvider.ExportProviderWithCSharpAndVisualBasic.AsExportProvider()))) { var solution = previewWorkspace.CurrentSolution .AddProject("project", "project.dll", LanguageNames.CSharp) .AddDocument("document", "class { }") .Project .Solution; Assert.True(previewWorkspace.TryApplyChanges(solution)); previewWorkspace.OpenDocument(previewWorkspace.CurrentSolution.Projects.First().DocumentIds[0]); previewWorkspace.EnableDiagnostic(); // wait 20 seconds taskSource.Task.Wait(20000); if (!taskSource.Task.IsCompleted) { // something is wrong FatalError.Report(new System.Exception("not finished after 20 seconds")); } var args = taskSource.Task.Result; Assert.True(args.Diagnostics.Length > 0); } } [Fact] public void TestPreviewDiagnosticTagger() { using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines("class { }")) using (var previewWorkspace = new PreviewWorkspace(workspace.CurrentSolution)) { // set up to listen diagnostic changes so that we can wait until it happens var diagnosticService = workspace.ExportProvider.GetExportedValue<IDiagnosticService>() as DiagnosticService; var taskSource = new TaskCompletionSource<DiagnosticsUpdatedArgs>(); diagnosticService.DiagnosticsUpdated += (s, a) => taskSource.TrySetResult(a); // preview workspace and owner of the solution now share solution and its underlying text buffer var hostDocument = workspace.Projects.First().Documents.First(); var buffer = hostDocument.GetTextBuffer(); // enable preview diagnostics previewWorkspace.OpenDocument(hostDocument.Id); previewWorkspace.EnableDiagnostic(); var foregroundService = new TestForegroundNotificationService(); var optionsService = workspace.Services.GetService<IOptionService>(); var squiggleWaiter = new ErrorSquiggleWaiter(); // create a tagger for preview workspace var taggerSource = new DiagnosticsSquiggleTaggerProvider.TagSource(buffer, foregroundService, diagnosticService, optionsService, squiggleWaiter); // wait up to 20 seconds for diagnostic service taskSource.Task.Wait(20000); if (!taskSource.Task.IsCompleted) { // something is wrong FatalError.Report(new System.Exception("not finished after 20 seconds")); } // wait for tagger squiggleWaiter.CreateWaitTask().PumpingWait(); var snapshot = buffer.CurrentSnapshot; var intervalTree = taggerSource.GetTagIntervalTreeForBuffer(buffer); var spans = intervalTree.GetIntersectingSpans(new SnapshotSpan(snapshot, 0, snapshot.Length)); taggerSource.TestOnly_Dispose(); Assert.Equal(1, spans.Count); } } [Fact] public void TestPreviewDiagnosticTaggerInPreviewPane() { using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines("class { }")) { // set up listener to wait until diagnostic finish running var diagnosticService = workspace.ExportProvider.GetExportedValue<IDiagnosticService>() as DiagnosticService; // no easy way to setup waiter. kind of hacky way to setup waiter var source = new CancellationTokenSource(); var taskSource = new TaskCompletionSource<DiagnosticsUpdatedArgs>(); diagnosticService.DiagnosticsUpdated += (s, a) => { source.Cancel(); source = new CancellationTokenSource(); var cancellationToken = source.Token; Task.Delay(2000, cancellationToken).ContinueWith(t => taskSource.TrySetResult(a), CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Current); }; var hostDocument = workspace.Projects.First().Documents.First(); // make a change to remove squiggle var oldDocument = workspace.CurrentSolution.GetDocument(hostDocument.Id); var oldText = oldDocument.GetTextAsync().Result; var newDocument = oldDocument.WithText(oldText.WithChanges(new TextChange(new TextSpan(0, oldText.Length), "class C { }"))); // create a diff view var previewFactoryService = workspace.ExportProvider.GetExportedValue<IPreviewFactoryService>(); var diffView = (IWpfDifferenceViewer)previewFactoryService.CreateChangedDocumentPreviewViewAsync(oldDocument, newDocument, CancellationToken.None).PumpingWaitResult(); var foregroundService = new TestForegroundNotificationService(); var optionsService = workspace.Services.GetService<IOptionService>(); // set up tagger for both buffers var leftBuffer = diffView.LeftView.BufferGraph.GetTextBuffers(t => t.ContentType.IsOfType(ContentTypeNames.CSharpContentType)).First(); var leftWaiter = new ErrorSquiggleWaiter(); var leftTaggerSource = new DiagnosticsSquiggleTaggerProvider.TagSource(leftBuffer, foregroundService, diagnosticService, optionsService, leftWaiter); var rightBuffer = diffView.RightView.BufferGraph.GetTextBuffers(t => t.ContentType.IsOfType(ContentTypeNames.CSharpContentType)).First(); var rightWaiter = new ErrorSquiggleWaiter(); var rightTaggerSource = new DiagnosticsSquiggleTaggerProvider.TagSource(rightBuffer, foregroundService, diagnosticService, optionsService, rightWaiter); // wait up to 20 seconds for diagnostics taskSource.Task.Wait(20000); if (!taskSource.Task.IsCompleted) { // something is wrong FatalError.Report(new System.Exception("not finished after 20 seconds")); } // wait taggers leftWaiter.CreateWaitTask().PumpingWait(); rightWaiter.CreateWaitTask().PumpingWait(); // check left buffer var leftSnapshot = leftBuffer.CurrentSnapshot; var leftIntervalTree = leftTaggerSource.GetTagIntervalTreeForBuffer(leftBuffer); var leftSpans = leftIntervalTree.GetIntersectingSpans(new SnapshotSpan(leftSnapshot, 0, leftSnapshot.Length)); leftTaggerSource.TestOnly_Dispose(); Assert.Equal(1, leftSpans.Count); // check right buffer var rightSnapshot = rightBuffer.CurrentSnapshot; var rightIntervalTree = rightTaggerSource.GetTagIntervalTreeForBuffer(rightBuffer); var rightSpans = rightIntervalTree.GetIntersectingSpans(new SnapshotSpan(rightSnapshot, 0, rightSnapshot.Length)); rightTaggerSource.TestOnly_Dispose(); Assert.Equal(0, rightSpans == null ? 0 : rightSpans.Count); } } private class ErrorSquiggleWaiter : AsynchronousOperationListener { } } }
// // 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; using Microsoft.WindowsAzure.Management.Automation; using Microsoft.WindowsAzure.Management.Automation.Models; namespace Microsoft.WindowsAzure.Management.Automation { public static partial class ModuleOperationsExtensions { /// <summary> /// Create the module identified by module name. (see /// http://aka.ms/azureautomationsdk/moduleoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IModuleOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The create parameters for module. /// </param> /// <returns> /// The response model for the create module operation. /// </returns> public static ModuleCreateResponse Create(this IModuleOperations operations, string automationAccount, ModuleCreateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IModuleOperations)s).CreateAsync(automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create the module identified by module name. (see /// http://aka.ms/azureautomationsdk/moduleoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IModuleOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The create parameters for module. /// </param> /// <returns> /// The response model for the create module operation. /// </returns> public static Task<ModuleCreateResponse> CreateAsync(this IModuleOperations operations, string automationAccount, ModuleCreateParameters parameters) { return operations.CreateAsync(automationAccount, parameters, CancellationToken.None); } /// <summary> /// Delete the module by name. (see /// http://aka.ms/azureautomationsdk/moduleoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IModuleOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='moduleName'> /// Required. The module name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IModuleOperations operations, string automationAccount, string moduleName) { return Task.Factory.StartNew((object s) => { return ((IModuleOperations)s).DeleteAsync(automationAccount, moduleName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete the module by name. (see /// http://aka.ms/azureautomationsdk/moduleoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IModuleOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='moduleName'> /// Required. The module name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IModuleOperations operations, string automationAccount, string moduleName) { return operations.DeleteAsync(automationAccount, moduleName, CancellationToken.None); } /// <summary> /// Retrieve the module identified by module name. (see /// http://aka.ms/azureautomationsdk/moduleoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IModuleOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='moduleName'> /// Required. The module name. /// </param> /// <returns> /// The response model for the get module operation. /// </returns> public static ModuleGetResponse Get(this IModuleOperations operations, string automationAccount, string moduleName) { return Task.Factory.StartNew((object s) => { return ((IModuleOperations)s).GetAsync(automationAccount, moduleName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve the module identified by module name. (see /// http://aka.ms/azureautomationsdk/moduleoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IModuleOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='moduleName'> /// Required. The module name. /// </param> /// <returns> /// The response model for the get module operation. /// </returns> public static Task<ModuleGetResponse> GetAsync(this IModuleOperations operations, string automationAccount, string moduleName) { return operations.GetAsync(automationAccount, moduleName, CancellationToken.None); } /// <summary> /// Retrieve a list of modules. (see /// http://aka.ms/azureautomationsdk/moduleoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IModuleOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <returns> /// The response model for the list module operation. /// </returns> public static ModuleListResponse List(this IModuleOperations operations, string automationAccount) { return Task.Factory.StartNew((object s) => { return ((IModuleOperations)s).ListAsync(automationAccount); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of modules. (see /// http://aka.ms/azureautomationsdk/moduleoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IModuleOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <returns> /// The response model for the list module operation. /// </returns> public static Task<ModuleListResponse> ListAsync(this IModuleOperations operations, string automationAccount) { return operations.ListAsync(automationAccount, CancellationToken.None); } /// <summary> /// Retrieve next list of modules. (see /// http://aka.ms/azureautomationsdk/moduleoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IModuleOperations. /// </param> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <returns> /// The response model for the list module operation. /// </returns> public static ModuleListResponse ListNext(this IModuleOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IModuleOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve next list of modules. (see /// http://aka.ms/azureautomationsdk/moduleoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IModuleOperations. /// </param> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <returns> /// The response model for the list module operation. /// </returns> public static Task<ModuleListResponse> ListNextAsync(this IModuleOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } /// <summary> /// Create the module identified by module name. (see /// http://aka.ms/azureautomationsdk/moduleoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IModuleOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The update parameters for module. /// </param> /// <returns> /// The response model for the get module operation. /// </returns> public static ModuleGetResponse Update(this IModuleOperations operations, string automationAccount, ModuleUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IModuleOperations)s).UpdateAsync(automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create the module identified by module name. (see /// http://aka.ms/azureautomationsdk/moduleoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IModuleOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The update parameters for module. /// </param> /// <returns> /// The response model for the get module operation. /// </returns> public static Task<ModuleGetResponse> UpdateAsync(this IModuleOperations operations, string automationAccount, ModuleUpdateParameters parameters) { return operations.UpdateAsync(automationAccount, parameters, CancellationToken.None); } } }
using System; using System.Collections.Generic; using UnityEngine; namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] [RequireComponent (typeof(Camera))] public class PostEffectsBase : MonoBehaviour { protected bool supportHDRTextures = true; protected bool supportDX11 = false; protected bool isSupported = true; private List<Material> createdMaterials = new List<Material> (); protected Material CheckShaderAndCreateMaterial ( Shader s, Material m2Create) { if (!s) { Debug.Log("Missing shader in " + ToString ()); enabled = false; return null; } if (s.isSupported && m2Create && m2Create.shader == s) return m2Create; if (!s.isSupported) { NotSupported (); Debug.Log("The shader " + s.ToString() + " on effect "+ToString()+" is not supported on this platform!"); return null; } m2Create = new Material (s); createdMaterials.Add (m2Create); m2Create.hideFlags = HideFlags.DontSave; return m2Create; } protected Material CreateMaterial (Shader s, Material m2Create) { if (!s) { Debug.Log ("Missing shader in " + ToString ()); return null; } if (m2Create && (m2Create.shader == s) && (s.isSupported)) return m2Create; if (!s.isSupported) { return null; } m2Create = new Material (s); createdMaterials.Add (m2Create); m2Create.hideFlags = HideFlags.DontSave; return m2Create; } void OnEnable () { isSupported = true; } void OnDestroy () { RemoveCreatedMaterials (); } private void RemoveCreatedMaterials () { while (createdMaterials.Count > 0) { Material mat = createdMaterials[0]; createdMaterials.RemoveAt (0); #if UNITY_EDITOR DestroyImmediate (mat); #else Destroy(mat); #endif } } protected bool CheckSupport () { return CheckSupport (false); } public virtual bool CheckResources () { Debug.LogWarning ("CheckResources () for " + ToString() + " should be overwritten."); return isSupported; } protected void Start () { CheckResources (); } protected bool CheckSupport (bool needDepth) { isSupported = true; supportHDRTextures = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBHalf); supportDX11 = SystemInfo.graphicsShaderLevel >= 50 && SystemInfo.supportsComputeShaders; if (!SystemInfo.supportsImageEffects || !SystemInfo.supportsRenderTextures) { NotSupported (); return false; } if (needDepth && !SystemInfo.SupportsRenderTextureFormat (RenderTextureFormat.Depth)) { NotSupported (); return false; } if (needDepth) GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth; return true; } protected bool CheckSupport (bool needDepth, bool needHdr) { if (!CheckSupport(needDepth)) return false; if (needHdr && !supportHDRTextures) { NotSupported (); return false; } return true; } public bool Dx11Support () { return supportDX11; } protected void ReportAutoDisable () { Debug.LogWarning ("The image effect " + ToString() + " has been disabled as it's not supported on the current platform."); } // deprecated but needed for old effects to survive upgrading bool CheckShader (Shader s) { Debug.Log("The shader " + s.ToString () + " on effect "+ ToString () + " is not part of the Unity 3.2+ effects suite anymore. For best performance and quality, please ensure you are using the latest Standard Assets Image Effects (Pro only) package."); if (!s.isSupported) { NotSupported (); return false; } else { return false; } } protected void NotSupported () { enabled = false; isSupported = false; return; } protected void DrawBorder (RenderTexture dest, Material material) { float x1; float x2; float y1; float y2; RenderTexture.active = dest; bool invertY = true; // source.texelSize.y < 0.0ff; // Set up the simple Matrix GL.PushMatrix(); GL.LoadOrtho(); for (int i = 0; i < material.passCount; i++) { material.SetPass(i); float y1_; float y2_; if (invertY) { y1_ = 1.0f; y2_ = 0.0f; } else { y1_ = 0.0f; y2_ = 1.0f; } // left x1 = 0.0f; x2 = 0.0f + 1.0f/(dest.width*1.0f); y1 = 0.0f; y2 = 1.0f; GL.Begin(GL.QUADS); GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f); GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f); GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f); GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f); // right x1 = 1.0f - 1.0f/(dest.width*1.0f); x2 = 1.0f; y1 = 0.0f; y2 = 1.0f; GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f); GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f); GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f); GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f); // top x1 = 0.0f; x2 = 1.0f; y1 = 0.0f; y2 = 0.0f + 1.0f/(dest.height*1.0f); GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f); GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f); GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f); GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f); // bottom x1 = 0.0f; x2 = 1.0f; y1 = 1.0f - 1.0f/(dest.height*1.0f); y2 = 1.0f; GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f); GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f); GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f); GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f); GL.End(); } GL.PopMatrix(); } } }
#region Disclaimer/Info /////////////////////////////////////////////////////////////////////////////////////////////////// // Subtext WebLog // // Subtext is an open source weblog system that is a fork of the .TEXT // weblog system. // // For updated news and information please visit http://subtextproject.com/ // Subtext is hosted at Google Code at http://code.google.com/p/subtext/ // The development mailing list is at [email protected] // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Data.SqlClient; using System.Text.RegularExpressions; using Subtext.Extensibility; using Subtext.Extensibility.Interfaces; using Subtext.Framework.Components; using Subtext.Framework.Data; using Subtext.Framework.Exceptions; using Subtext.Framework.Providers; using Subtext.Framework.Routing; using Subtext.Framework.Services; using Subtext.Infrastructure; namespace Subtext.Framework.Infrastructure.Installation { /// <summary> /// Class used to help make determine whether an installation is required or not. /// </summary> public class InstallationManager : IInstallationManager { public InstallationManager(IInstaller installer, ICache cache) { Installer = installer; Cache = cache; } protected ICache Cache { get; set; } protected IInstaller Installer { get; set; } public void Install(Version assemblyVersion) { Installer.Install(assemblyVersion); ResetInstallationStatusCache(); } public void CreateWelcomeContent(ISubtextContext context, IEntryPublisher entryPublisher, Blog blog) { var repository = context.Repository; CreateWelcomeCategories(repository, blog); var adminUrlHelper = new AdminUrlHelper(context.UrlHelper); Entry article = CreateWelcomeArticle(blog, entryPublisher, adminUrlHelper); Entry entry = CreateWelcomeBlogPost(context, blog, entryPublisher, adminUrlHelper, article); CreateWelcomeComment(repository, adminUrlHelper, entry); } private static void CreateWelcomeComment(ObjectRepository repository, AdminUrlHelper adminUrlHelper, Entry entry) { string commentBody = ScriptHelper.UnpackEmbeddedScriptAsString("WelcomeComment.htm"); string feedbackUrl = adminUrlHelper.FeedbackList(); commentBody = string.Format(commentBody, feedbackUrl); var comment = new FeedbackItem(FeedbackType.Comment) { Title = "re: Welcome to Subtext!", Entry = entry, Author = "Subtext", Approved = true, Body = commentBody }; repository.Create(comment); } private static Entry CreateWelcomeBlogPost(ISubtextContext context, Blog blog, IEntryPublisher entryPublisher, AdminUrlHelper adminUrlHelper, IEntryIdentity article) { string body = ScriptHelper.UnpackEmbeddedScriptAsString("WelcomePost.htm"); string articleUrl = context.UrlHelper.EntryUrl(article); body = String.Format(body, articleUrl, adminUrlHelper.Home(), context.UrlHelper.HostAdminUrl("default.aspx")); var entry = new Entry(PostType.BlogPost) { Title = "Welcome to Subtext!", EntryName = "welcome-to-subtext", BlogId = blog.Id, Author = blog.Author, Body = body, DateCreatedUtc = DateTime.UtcNow, DateModifiedUtc = DateTime.UtcNow, IsActive = true, IncludeInMainSyndication = true, DisplayOnHomePage = true, AllowComments = true }; entryPublisher.Publish(entry); return entry; } private static Entry CreateWelcomeArticle(Blog blog, IEntryPublisher entryPublisher, AdminUrlHelper adminUrlHelper) { string body = ScriptHelper.UnpackEmbeddedScriptAsString("WelcomeArticle.htm"); body = String.Format(body, adminUrlHelper.ArticlesList()); var article = new Entry(PostType.Story) { EntryName = "welcome-to-subtext-article", Title = "Welcome to Subtext!", BlogId = blog.Id, Author = blog.Author, Body = body, DateCreatedUtc = DateTime.UtcNow, DateModifiedUtc = DateTime.UtcNow, IsActive = true, }; entryPublisher.Publish(article); return article; } private static void CreateWelcomeCategories(ObjectRepository repository, Blog blog) { repository.CreateLinkCategory(new LinkCategory { Title = "Programming", Description = "Blog posts related to programming", BlogId = blog.Id, IsActive = true, CategoryType = CategoryType.PostCollection, }); repository.CreateLinkCategory(new LinkCategory { Title = "Personal", Description = "Personal musings, random thoughts.", BlogId = blog.Id, IsActive = true, CategoryType = CategoryType.PostCollection }); } public void Upgrade(Version currentAssemblyVersion) { Installer.Upgrade(currentAssemblyVersion); ResetInstallationStatusCache(); } /// <summary> /// Determines whether an installation action is required by /// examining the specified unhandled Exception. /// </summary> /// <param name="unhandledException">Unhandled exception.</param> /// <param name="assemblyVersion">The version of the currently installed assembly.</param> /// <returns> /// <c>true</c> if an installation action is required; otherwise, <c>false</c>. /// </returns> public bool InstallationActionRequired(Version assemblyVersion, Exception unhandledException) { if (unhandledException is HostDataDoesNotExistException) { return true; } if (IsInstallationException(unhandledException)) { return true; } InstallationState status = GetInstallationStatus(assemblyVersion); switch (status) { case InstallationState.NeedsInstallation: case InstallationState.NeedsUpgrade: { return true; } } return false; } private static bool IsInstallationException(Exception exception) { var tableRegex = new Regex("Invalid object name '.*?'", RegexOptions.IgnoreCase | RegexOptions.Compiled); bool isSqlException = exception is SqlException; if (isSqlException && tableRegex.IsMatch(exception.Message)) { return true; } var spRegex = new Regex("'Could not find stored procedure '.*?'", RegexOptions.IgnoreCase | RegexOptions.Compiled); if (isSqlException && spRegex.IsMatch(exception.Message)) { return true; } return false; } public virtual InstallationState GetInstallationStatus(Version currentAssemblyVersion) { object cachedInstallationState = Cache["NeedsInstallation"]; if (cachedInstallationState != null) { return (InstallationState)cachedInstallationState; } var status = GetInstallationState(currentAssemblyVersion); Cache.Insert("NeedsInstallation", status); return status; } private InstallationState GetInstallationState(Version currentAssemblyVersion) { Version installationVersion = Installer.GetCurrentInstallationVersion(); if (installationVersion == null) { return InstallationState.NeedsInstallation; } if (Installer.NeedsUpgrade(installationVersion, currentAssemblyVersion)) { return InstallationState.NeedsUpgrade; } return InstallationState.Complete; } public bool InstallationActionRequired(InstallationState currentState) { bool needsUpgrade = (currentState == InstallationState.NeedsInstallation || currentState == InstallationState.NeedsUpgrade); return needsUpgrade; } public void ResetInstallationStatusCache() { object cachedInstallationState = Cache["NeedsInstallation"]; if (cachedInstallationState != null) { Cache.Remove("NeedsInstallation"); } } /// <summary> /// Determines whether the specified exception is due to a permission /// denied error. /// </summary> /// <param name="exception"></param> /// <returns></returns> public bool IsPermissionDeniedException(Exception exception) { var sqlexc = exception.InnerException as SqlException; return sqlexc != null && ( sqlexc.Number == (int)SqlErrorMessage.PermissionDeniedInDatabase || sqlexc.Number == (int)SqlErrorMessage.PermissionDeniedOnProcedure || sqlexc.Number == (int)SqlErrorMessage.PermissionDeniedInOnColumn || sqlexc.Number == (int)SqlErrorMessage.PermissionDeniedInOnObject ); } } }
using System; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using System.Collections.Generic; namespace Octokit { /// <summary> /// A client for GitHub's Repositories API. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/">Repositories API documentation</a> for more details. /// </remarks> public interface IRepositoriesClient { /// <summary> /// Client for managing pull requests. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/pulls/">Pull Requests API documentation</a> for more details /// </remarks> IPullRequestsClient PullRequest { get; } /// <summary> /// Client for managing branches in a repository. /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/branches/">Branches API documentation</a> for more details /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] IRepositoryBranchesClient Branch { get; } /// <summary> /// Client for managing commit comments in a repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/comments/">Repository Comments API documentation</a> for more information. /// </remarks> IRepositoryCommentsClient Comment { get; } /// <summary> /// Client for managing deploy keys in a repository. /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/keys/">Repository Deploy Keys API documentation</a> for more information. /// </remarks> IRepositoryDeployKeysClient DeployKeys { get; } /// <summary> /// Client for managing the contents of a repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/contents/">Repository Contents API documentation</a> for more information. /// </remarks> IRepositoryContentsClient Content { get; } /// <summary> /// Creates a new repository for the current user. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#create">API documentation</a> for more information. /// </remarks> /// <param name="newRepository">A <see cref="NewRepository"/> instance describing the new repository to create</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="Repository"/> instance for the created repository.</returns> Task<Repository> Create(NewRepository newRepository); /// <summary> /// Creates a new repository in the specified organization. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#create">API documentation</a> for more information. /// </remarks> /// <param name="organizationLogin">Login of the organization in which to create the repository</param> /// <param name="newRepository">A <see cref="NewRepository"/> instance describing the new repository to create</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="Repository"/> instance for the created repository</returns> Task<Repository> Create(string organizationLogin, NewRepository newRepository); /// <summary> /// Deletes the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#delete-a-repository">API documentation</a> for more information. /// Deleting a repository requires admin access. If OAuth is used, the `delete_repo` scope is required. /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task Delete(string owner, string name); /// <summary> /// Deletes the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#delete-a-repository">API documentation</a> for more information. /// Deleting a repository requires admin access. If OAuth is used, the `delete_repo` scope is required. /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task Delete(long repositoryId); /// <summary> /// Gets the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#get">API documentation</a> for more information. /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="Repository"/></returns> [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get")] Task<Repository> Get(string owner, string name); /// <summary> /// Gets the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#get">API documentation</a> for more information. /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="Repository"/></returns> [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get")] Task<Repository> Get(long repositoryId); /// <summary> /// Gets all public repositories. /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/#list-all-public-repositories">API documentation</a> for more information. /// The default page size on GitHub.com is 30. /// </remarks> /// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Makes a network request")] [ExcludeFromPaginationApiOptionsConventionTest("This API call uses the PublicRepositoryRequest.Since parameter for pagination")] Task<IReadOnlyList<Repository>> GetAllPublic(); /// <summary> /// Gets all public repositories since the integer Id of the last Repository that you've seen. /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/#list-all-public-repositories">API documentation</a> for more information. /// The default page size on GitHub.com is 30. /// </remarks> /// <param name="request">Search parameters of the last repository seen</param> /// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> [ExcludeFromPaginationApiOptionsConventionTest("This API call uses the PublicRepositoryRequest.Since parameter for pagination")] Task<IReadOnlyList<Repository>> GetAllPublic(PublicRepositoryRequest request); /// <summary> /// Gets all repositories owned by the current user. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-your-repositories">API documentation</a> for more information. /// The default page size on GitHub.com is 30. /// </remarks> /// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Makes a network request")] Task<IReadOnlyList<Repository>> GetAllForCurrent(); /// <summary> /// Gets all repositories owned by the current user. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-your-repositories">API documentation</a> for more information. /// </remarks> /// <param name="options">Options for changing the API response</param> /// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllForCurrent(ApiOptions options); /// <summary> /// Gets all repositories owned by the current user. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-your-repositories">API documentation</a> for more information. /// The default page size on GitHub.com is 30. /// </remarks> /// <param name="request">Search parameters to filter results on</param> /// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllForCurrent(RepositoryRequest request); /// <summary> /// Gets all repositories owned by the current user. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-your-repositories">API documentation</a> for more information. /// </remarks> /// <param name="request">Search parameters to filter results on</param> /// <param name="options">Options for changing the API response</param> /// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllForCurrent(RepositoryRequest request, ApiOptions options); /// <summary> /// Gets all repositories owned by the specified user. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-user-repositories">API documentation</a> for more information. /// The default page size on GitHub.com is 30. /// </remarks> /// <param name="login">The account name to search for</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllForUser(string login); /// <summary> /// Gets all repositories owned by the specified user. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-user-repositories">API documentation</a> for more information. /// </remarks> /// <param name="login">The account name to search for</param> /// <param name="options">Options for changing the API response</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllForUser(string login, ApiOptions options); /// <summary> /// Gets all repositories owned by the specified organization. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-organization-repositories">API documentation</a> for more information. /// The default page size on GitHub.com is 30. /// </remarks> /// <param name="organization">The organization name to search for</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllForOrg(string organization); /// <summary> /// Gets all repositories owned by the specified organization. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-organization-repositories">API documentation</a> for more information. /// </remarks> /// <param name="organization">The organization name to search for</param> /// <param name="options">Options for changing the API response</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllForOrg(string organization, ApiOptions options); /// <summary> /// A client for GitHub's Commit Status API. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/statuses/">Commit Status API documentation</a> for more /// details. Also check out the <a href="https://github.com/blog/1227-commit-status-api">blog post</a> /// that announced this feature. /// </remarks> ICommitStatusClient Status { get; } /// <summary> /// A client for GitHub's Repository Hooks API. /// </summary> /// <remarks>See <a href="http://developer.github.com/v3/repos/hooks/">Hooks API documentation</a> for more information.</remarks> IRepositoryHooksClient Hooks { get; } /// <summary> /// A client for GitHub's Repository Forks API. /// </summary> /// <remarks>See <a href="http://developer.github.com/v3/repos/forks/">Forks API documentation</a> for more information.</remarks> IRepositoryForksClient Forks { get; } /// <summary> /// A client for GitHub's Repo Collaborators. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/collaborators/">Collaborators API documentation</a> for more details /// </remarks> IRepoCollaboratorsClient Collaborator { get; } /// <summary> /// Client for GitHub's Repository Deployments API /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/deployments/">Deployments API documentation</a> for more details /// </remarks> IDeploymentsClient Deployment { get; } /// <summary> /// Client for GitHub's Repository Statistics API /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/statistics/">Statistics API documentation</a> for more details ///</remarks> IStatisticsClient Statistics { get; } /// <summary> /// Client for GitHub's Repository Commits API /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/commits/">Commits API documentation</a> for more details ///</remarks> IRepositoryCommitsClient Commit { get; } /// <summary> /// Access GitHub's Releases API. /// </summary> /// <remarks> /// Refer to the API documentation for more information: https://developer.github.com/v3/repos/releases/ /// </remarks> IReleasesClient Release { get; } /// <summary> /// Client for GitHub's Repository Merging API /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/merging/">Merging API documentation</a> for more details ///</remarks> IMergingClient Merging { get; } /// <summary> /// Gets all contributors for the specified repository. Does not include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(string owner, string name); /// <summary> /// Gets all contributors for the specified repository. Does not include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(long repositoryId); /// <summary> /// Gets all contributors for the specified repository. Does not include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="options">Options for changing the API response</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(string owner, string name, ApiOptions options); /// <summary> /// Gets all contributors for the specified repository. Does not include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="options">Options for changing the API response</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(long repositoryId, ApiOptions options); /// <summary> /// Gets all contributors for the specified repository. With the option to include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="includeAnonymous">True if anonymous contributors should be included in result; Otherwise false</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(string owner, string name, bool includeAnonymous); /// <summary> /// Gets all contributors for the specified repository. With the option to include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="includeAnonymous">True if anonymous contributors should be included in result; Otherwise false</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(long repositoryId, bool includeAnonymous); /// <summary> /// Gets all contributors for the specified repository. With the option to include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="includeAnonymous">True if anonymous contributors should be included in result; Otherwise false</param> /// <param name="options">Options for changing the API response</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(string owner, string name, bool includeAnonymous, ApiOptions options); /// <summary> /// Gets all contributors for the specified repository. With the option to include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="includeAnonymous">True if anonymous contributors should be included in result; Otherwise false</param> /// <param name="options">Options for changing the API response</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(long repositoryId, bool includeAnonymous, ApiOptions options); /// <summary> /// Gets all languages for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-languages">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <returns>All languages used in the repository and the number of bytes of each language.</returns> [ExcludeFromPaginationApiOptionsConventionTest("Pagination not supported by GitHub API (tested 29/08/2017)")] Task<IReadOnlyList<RepositoryLanguage>> GetAllLanguages(string owner, string name); /// <summary> /// Gets all languages for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-languages">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <returns>All languages used in the repository and the number of bytes of each language.</returns> [ExcludeFromPaginationApiOptionsConventionTest("Pagination not supported by GitHub API (tested 29/08/2017)")] Task<IReadOnlyList<RepositoryLanguage>> GetAllLanguages(long repositoryId); /// <summary> /// Gets all teams for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-teams">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <returns>All <see cref="T:Octokit.Team"/>s associated with the repository</returns> Task<IReadOnlyList<Team>> GetAllTeams(string owner, string name); /// <summary> /// Gets all teams for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-teams">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <returns>All <see cref="T:Octokit.Team"/>s associated with the repository</returns> Task<IReadOnlyList<Team>> GetAllTeams(long repositoryId); /// <summary> /// Gets all teams for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-teams">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="options">Options for changing the API response</param> /// <returns>All <see cref="T:Octokit.Team"/>s associated with the repository</returns> Task<IReadOnlyList<Team>> GetAllTeams(string owner, string name, ApiOptions options); /// <summary> /// Gets all teams for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-teams">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="options">Options for changing the API response</param> /// <returns>All <see cref="T:Octokit.Team"/>s associated with the repository</returns> Task<IReadOnlyList<Team>> GetAllTeams(long repositoryId, ApiOptions options); /// <summary> /// Gets all tags for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-tags">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <returns>All of the repositories tags.</returns> Task<IReadOnlyList<RepositoryTag>> GetAllTags(string owner, string name); /// <summary> /// Gets all tags for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-tags">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <returns>All of the repositories tags.</returns> Task<IReadOnlyList<RepositoryTag>> GetAllTags(long repositoryId); /// <summary> /// Gets all tags for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-tags">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="options">Options for changing the API response</param> /// <returns>All of the repositories tags.</returns> Task<IReadOnlyList<RepositoryTag>> GetAllTags(string owner, string name, ApiOptions options); /// <summary> /// Gets all tags for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-tags">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="options">Options for changing the API response</param> /// <returns>All of the repositories tags.</returns> Task<IReadOnlyList<RepositoryTag>> GetAllTags(long repositoryId, ApiOptions options); /// <summary> /// Updates the specified repository with the values given in <paramref name="update"/> /// </summary> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="update">New values to update the repository with</param> /// <returns>The updated <see cref="T:Octokit.Repository"/></returns> Task<Repository> Edit(string owner, string name, RepositoryUpdate update); /// <summary> /// Updates the specified repository with the values given in <paramref name="update"/> /// </summary> /// <param name="repositoryId">The Id of the repository</param> /// <param name="update">New values to update the repository with</param> /// <returns>The updated <see cref="T:Octokit.Repository"/></returns> Task<Repository> Edit(long repositoryId, RepositoryUpdate update); /// <summary> /// A client for GitHub's Repository Pages API. /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/pages/">Repository Pages API documentation</a> for more information. /// </remarks> IRepositoryPagesClient Page { get; } /// <summary> /// A client for GitHub's Repository Invitations API. /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/invitations/">Repository Invitations API documentation</a> for more information. /// </remarks> IRepositoryInvitationsClient Invitation { get; } /// <summary> /// Access GitHub's Repository Traffic API /// </summary> /// <remarks> /// Refer to the API documentation for more information: https://developer.github.com/v3/repos/traffic/ /// </remarks> IRepositoryTrafficClient Traffic { get; } /// <summary> /// Access GitHub's Repository Projects API /// </summary> /// <remarks> /// Refer to the API documentation for more information: https://developer.github.com/v3/repos/projects/ /// </remarks> IProjectsClient Project { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Text; using Xunit; namespace System.Diagnostics.Tests { public partial class FileVersionInfoTest : FileCleanupTestBase { // The extension is ".ildll" rather than ".dll" to prevent ILC from treating TestAssembly.dll as IL to subsume into executable. private const string TestAssemblyFileName = "System.Diagnostics.FileVersionInfo.TestAssembly.ildll"; private const string OriginalTestAssemblyFileName = "System.Diagnostics.FileVersionInfo.TestAssembly.dll"; // On Unix the internal name's extension is .exe if OutputType is exe even though the TargetExt is .dll. private readonly string OriginalTestAssemblyInternalName = PlatformDetection.IsWindows ? "System.Diagnostics.FileVersionInfo.TestAssembly.dll" : "System.Diagnostics.FileVersionInfo.TestAssembly.exe"; private const string TestCsFileName = "Assembly1.cs"; private const string TestNotFoundFileName = "notfound.dll"; [Fact] public void FileVersionInfo_CustomManagedAssembly() { // Assembly1.dll VerifyVersionInfo(Path.Combine(Directory.GetCurrentDirectory(), TestAssemblyFileName), new MyFVI() { Comments = "Have you played a Contoso amusement device today?", CompanyName = "The name of the company.", FileBuildPart = 2, FileDescription = "My File", FileMajorPart = 4, FileMinorPart = 3, FileName = Path.Combine(Directory.GetCurrentDirectory(), TestAssemblyFileName), FilePrivatePart = 1, FileVersion = "4.3.2.1", InternalName = OriginalTestAssemblyInternalName, IsDebug = false, IsPatched = false, IsPrivateBuild = false, IsPreRelease = false, IsSpecialBuild = false, Language = GetFileVersionLanguage(0x0000), LegalCopyright = "Copyright, you betcha!", LegalTrademarks = "TM", OriginalFilename = OriginalTestAssemblyInternalName, PrivateBuild = "", ProductBuildPart = 3, ProductMajorPart = 1, ProductMinorPart = 2, ProductName = "The greatest product EVER", ProductPrivatePart = 0, ProductVersion = "1.2.3-beta.4", SpecialBuild = "", }); } [Fact] public void FileVersionInfo_EmptyFVI() { // Assembly1.cs VerifyVersionInfo(Path.Combine(Directory.GetCurrentDirectory(), TestCsFileName), new MyFVI() { Comments = null, CompanyName = null, FileBuildPart = 0, FileDescription = null, FileMajorPart = 0, FileMinorPart = 0, FileName = Path.Combine(Directory.GetCurrentDirectory(), TestCsFileName), FilePrivatePart = 0, FileVersion = null, InternalName = null, IsDebug = false, IsPatched = false, IsPrivateBuild = false, IsPreRelease = false, IsSpecialBuild = false, Language = null, LegalCopyright = null, LegalTrademarks = null, OriginalFilename = null, PrivateBuild = null, ProductBuildPart = 0, ProductMajorPart = 0, ProductMinorPart = 0, ProductName = null, ProductPrivatePart = 0, ProductVersion = null, SpecialBuild = null, }); } [Fact] public void FileVersionInfo_CurrentDirectory_FileNotFound() { Assert.Throws<FileNotFoundException>(() => FileVersionInfo.GetVersionInfo(Directory.GetCurrentDirectory())); } [Fact] public void FileVersionInfo_NonExistentFile_FileNotFound() { Assert.Throws<FileNotFoundException>(() => FileVersionInfo.GetVersionInfo(Path.Combine(Directory.GetCurrentDirectory(), TestNotFoundFileName))); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Don't want to create temp file in app container current directory")] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "NetFX throws ArgumentException in this case")] public void FileVersionInfo_RelativePath_CorrectFilePath() { try { File.WriteAllText("kernelbase.dll", "bogus kernelbase.dll"); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo("kernelbase.dll"); // File name should be the full path to the local kernelbase.dll, not the relative path or the path to the system .dll Assert.Equal(Path.GetFullPath("kernelbase.dll"), fvi.FileName); // FileDescription should be null in the local kernelbase.dll Assert.Equal(null, fvi.FileDescription); } finally { File.Delete("kernelbase.dll"); } } // Additional Tests Wanted: // [] File exists but we don't have permission to read it // [] DLL has unknown codepage info // [] DLL language/codepage is 8-hex-digits (locale > 0x999) (different codepath) private void VerifyVersionInfo(string filePath, MyFVI expected) { FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(filePath); Assert.Equal(expected.Comments, fvi.Comments); Assert.Equal(expected.CompanyName, fvi.CompanyName); Assert.Equal(expected.FileBuildPart, fvi.FileBuildPart); Assert.Equal(expected.FileDescription, fvi.FileDescription); Assert.Equal(expected.FileMajorPart, fvi.FileMajorPart); Assert.Equal(expected.FileMinorPart, fvi.FileMinorPart); Assert.Equal(expected.FileName, fvi.FileName); Assert.Equal(expected.FilePrivatePart, fvi.FilePrivatePart); Assert.Equal(expected.FileVersion, fvi.FileVersion); Assert.Equal(expected.InternalName, fvi.InternalName); Assert.Equal(expected.IsDebug, fvi.IsDebug); Assert.Equal(expected.IsPatched, fvi.IsPatched); Assert.Equal(expected.IsPrivateBuild, fvi.IsPrivateBuild); Assert.Equal(expected.IsPreRelease, fvi.IsPreRelease); Assert.Equal(expected.IsSpecialBuild, fvi.IsSpecialBuild); Assert.Contains(fvi.Language, new[] { expected.Language, expected.Language2 }); Assert.Equal(expected.LegalCopyright, fvi.LegalCopyright); Assert.Equal(expected.LegalTrademarks, fvi.LegalTrademarks); Assert.Equal(expected.OriginalFilename, fvi.OriginalFilename); Assert.Equal(expected.PrivateBuild, fvi.PrivateBuild); Assert.Equal(expected.ProductBuildPart, fvi.ProductBuildPart); Assert.Equal(expected.ProductMajorPart, fvi.ProductMajorPart); Assert.Equal(expected.ProductMinorPart, fvi.ProductMinorPart); Assert.Equal(expected.ProductName, fvi.ProductName); Assert.Equal(expected.ProductPrivatePart, fvi.ProductPrivatePart); Assert.Equal(expected.ProductVersion, fvi.ProductVersion); Assert.Equal(expected.SpecialBuild, fvi.SpecialBuild); //ToString string nl = Environment.NewLine; Assert.Equal("File: " + fvi.FileName + nl + "InternalName: " + fvi.InternalName + nl + "OriginalFilename: " + fvi.OriginalFilename + nl + "FileVersion: " + fvi.FileVersion + nl + "FileDescription: " + fvi.FileDescription + nl + "Product: " + fvi.ProductName + nl + "ProductVersion: " + fvi.ProductVersion + nl + "Debug: " + fvi.IsDebug.ToString() + nl + "Patched: " + fvi.IsPatched.ToString() + nl + "PreRelease: " + fvi.IsPreRelease.ToString() + nl + "PrivateBuild: " + fvi.IsPrivateBuild.ToString() + nl + "SpecialBuild: " + fvi.IsSpecialBuild.ToString() + nl + "Language: " + fvi.Language + nl, fvi.ToString()); } internal class MyFVI { public string Comments; public string CompanyName; public int FileBuildPart; public string FileDescription; public int FileMajorPart; public int FileMinorPart; public string FileName; public int FilePrivatePart; public string FileVersion; public string InternalName; public bool IsDebug; public bool IsPatched; public bool IsPrivateBuild; public bool IsPreRelease; public bool IsSpecialBuild; public string Language; public string Language2; public string LegalCopyright; public string LegalTrademarks; public string OriginalFilename; public string PrivateBuild; public int ProductBuildPart; public int ProductMajorPart; public int ProductMinorPart; public string ProductName; public int ProductPrivatePart; public string ProductVersion; public string SpecialBuild; } static string GetUnicodeString(string str) { if (str == null) return "<null>"; StringBuilder buffer = new StringBuilder(); buffer.Append("\""); for (int i = 0; i < str.Length; i++) { char ch = str[i]; if (ch == '\r') { buffer.Append("\\r"); } else if (ch == '\n') { buffer.Append("\\n"); } else if (ch == '\\') { buffer.Append("\\"); } else if (ch == '\"') { buffer.Append("\\\""); } else if (ch == '\'') { buffer.Append("\\\'"); } else if (ch < 0x20 || ch >= 0x7f) { buffer.Append("\\u"); buffer.Append(((int)ch).ToString("x4")); } else { buffer.Append(ch); } } buffer.Append("\""); return (buffer.ToString()); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ReaderTest.cs"> // Copyright (c) 2014 Alexander Logger. // Copyright (c) 2000 - 2013 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org). // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.IO; using BigMath; using NUnit.Framework; using Raksha.Asn1.Cms; using Raksha.Crypto; using Raksha.Crypto.Generators; using Raksha.Crypto.Parameters; using Raksha.OpenSsl; using Raksha.Security; using Raksha.Tests.Utilities; namespace Raksha.Tests.OpenSsl { /** * basic class for reading test.pem - the password is "secret" */ [TestFixture] public class ReaderTest : SimpleTest { private const string OpenSslDsaPrefix = "Dsa.openssl_dsa_"; private const string OpenSslRsaPrefix = "Rsa.openssl_rsa_"; private const string OpenSslNamespace = "OpenSsl."; private class Password : IPasswordFinder { private readonly char[] _password; public Password(char[] word) { _password = (char[]) word.Clone(); } public char[] GetPassword() { return (char[]) _password.Clone(); } } public override string Name { get { return "PEMReaderTest"; } } public override void PerformTest() { IPasswordFinder pGet = new Password("secret".ToCharArray()); PemReader pemRd = OpenPemResource("test.pem", pGet); AsymmetricCipherKeyPair pair; object o; while ((o = pemRd.ReadObject()) != null) { // if (o is AsymmetricCipherKeyPair) // { // ackp = (AsymmetricCipherKeyPair)o; // // Console.WriteLine(ackp.Public); // Console.WriteLine(ackp.Private); // } // else // { // Console.WriteLine(o.ToString()); // } } // // pkcs 7 data // pemRd = OpenPemResource("pkcs7.pem", null); var d = (ContentInfo) pemRd.ReadObject(); if (!d.ContentType.Equals(CmsObjectIdentifiers.EnvelopedData)) { Fail("failed envelopedData check"); } /* { // // ECKey // pemRd = OpenPemResource("eckey.pem", null); // TODO Resolve return type issue with EC keys and fix PemReader to return parameters // ECNamedCurveParameterSpec spec = (ECNamedCurveParameterSpec)pemRd.ReadObject(); pair = (AsymmetricCipherKeyPair)pemRd.ReadObject(); ISigner sgr = SignerUtilities.GetSigner("ECDSA"); sgr.Init(true, pair.Private); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.BlockUpdate(message, 0, message.Length); byte[] sigBytes = sgr.GenerateSignature(); sgr.Init(false, pair.Public); sgr.BlockUpdate(message, 0, message.Length); if (!sgr.VerifySignature(sigBytes)) { Fail("EC verification failed"); } // TODO Resolve this issue with the algorithm name, study Java version // if (!((ECPublicKeyParameters) pair.Public).AlgorithmName.Equals("ECDSA")) // { // Fail("wrong algorithm name on public got: " + ((ECPublicKeyParameters) pair.Public).AlgorithmName); // } // // if (!((ECPrivateKeyParameters) pair.Private).AlgorithmName.Equals("ECDSA")) // { // Fail("wrong algorithm name on private got: " + ((ECPrivateKeyParameters) pair.Private).AlgorithmName); // } } */ // // writer/parser test // IAsymmetricCipherKeyPairGenerator kpGen = GeneratorUtilities.GetKeyPairGenerator("RSA"); kpGen.Init(new RsaKeyGenerationParameters(BigInteger.ValueOf(0x10001), new SecureRandom(), 768, 25)); pair = kpGen.GenerateKeyPair(); KeyPairTest("RSA", pair); // kpGen = KeyPairGenerator.getInstance("DSA"); // kpGen.initialize(512, new SecureRandom()); var pGen = new DsaParametersGenerator(); pGen.Init(512, 80, new SecureRandom()); kpGen = GeneratorUtilities.GetKeyPairGenerator("DSA"); kpGen.Init(new DsaKeyGenerationParameters(new SecureRandom(), pGen.GenerateParameters())); pair = kpGen.GenerateKeyPair(); KeyPairTest("DSA", pair); // // PKCS7 // var bOut = new MemoryStream(); var pWrt = new PemWriter(new StreamWriter(bOut)); pWrt.WriteObject(d); pWrt.Writer.Close(); pemRd = new PemReader(new StreamReader(new MemoryStream(bOut.ToArray(), false))); d = (ContentInfo) pemRd.ReadObject(); if (!d.ContentType.Equals(CmsObjectIdentifiers.EnvelopedData)) { Fail("failed envelopedData recode check"); } // OpenSSL test cases (as embedded resources) DoOpenSslDsaTest("unencrypted"); DoOpenSslRsaTest("unencrypted"); DoOpenSslTests("aes128"); DoOpenSslTests("aes192"); DoOpenSslTests("aes256"); DoOpenSslTests("blowfish"); DoOpenSslTests("des1"); DoOpenSslTests("des2"); DoOpenSslTests("des3"); DoOpenSslTests("rc2_128"); DoOpenSslDsaTest("rc2_40_cbc"); DoOpenSslRsaTest("rc2_40_cbc"); DoOpenSslDsaTest("rc2_64_cbc"); DoOpenSslRsaTest("rc2_64_cbc"); // TODO Figure out why exceptions differ for commented out cases DoDudPasswordTest("7fd98", 0, "Corrupted stream - out of bounds length found"); DoDudPasswordTest("ef677", 1, "Corrupted stream - out of bounds length found"); // doDudPasswordTest("800ce", 2, "cannot recognise object in stream"); DoDudPasswordTest("b6cd8", 3, "DEF length 81 object truncated by 56"); DoDudPasswordTest("28ce09", 4, "DEF length 110 object truncated by 28"); DoDudPasswordTest("2ac3b9", 5, "DER length more than 4 bytes: 11"); DoDudPasswordTest("2cba96", 6, "DEF length 100 object truncated by 35"); DoDudPasswordTest("2e3354", 7, "DEF length 42 object truncated by 9"); DoDudPasswordTest("2f4142", 8, "DER length more than 4 bytes: 14"); DoDudPasswordTest("2fe9bb", 9, "DER length more than 4 bytes: 65"); DoDudPasswordTest("3ee7a8", 10, "DER length more than 4 bytes: 57"); DoDudPasswordTest("41af75", 11, "malformed sequence in DSA private key"); DoDudPasswordTest("1704a5", 12, "corrupted stream detected"); // doDudPasswordTest("1c5822", 13, "corrupted stream detected"); // doDudPasswordTest("5a3d16", 14, "corrupted stream detected"); DoDudPasswordTest("8d0c97", 15, "corrupted stream detected"); DoDudPasswordTest("bc0daf", 16, "corrupted stream detected"); DoDudPasswordTest("aaf9c4d", 17, "Corrupted stream - out of bounds length found"); // encrypted private key test pGet = new Password("password".ToCharArray()); pemRd = OpenPemResource("enckey.pem", pGet); var privKey = (RsaPrivateCrtKeyParameters) pemRd.ReadObject(); if (!privKey.PublicExponent.Equals(new BigInteger("10001", 16))) { Fail("decryption of private key data check failed"); } // general PKCS8 test pGet = new Password("password".ToCharArray()); pemRd = OpenPemResource("pkcs8test.pem", pGet); while ((privKey = (RsaPrivateCrtKeyParameters) pemRd.ReadObject()) != null) { if (!privKey.PublicExponent.Equals(new BigInteger("10001", 16))) { Fail("decryption of private key data check failed"); } } } private void KeyPairTest(string name, AsymmetricCipherKeyPair pair) { var bOut = new MemoryStream(); var pWrt = new PemWriter(new StreamWriter(bOut)); pWrt.WriteObject(pair.Public); pWrt.Writer.Close(); var pemRd = new PemReader(new StreamReader(new MemoryStream(bOut.ToArray(), false))); var pubK = (AsymmetricKeyParameter) pemRd.ReadObject(); if (!pubK.Equals(pair.Public)) { Fail("Failed public key read: " + name); } bOut = new MemoryStream(); pWrt = new PemWriter(new StreamWriter(bOut)); pWrt.WriteObject(pair.Private); pWrt.Writer.Close(); pemRd = new PemReader(new StreamReader(new MemoryStream(bOut.ToArray(), false))); var kPair = (AsymmetricCipherKeyPair) pemRd.ReadObject(); if (!kPair.Private.Equals(pair.Private)) { Fail("Failed private key read: " + name); } if (!kPair.Public.Equals(pair.Public)) { Fail("Failed private key public read: " + name); } } private void DoOpenSslTests(string baseName) { DoOpenSslDsaModesTest(baseName); DoOpenSslRsaModesTest(baseName); } private void DoOpenSslDsaModesTest(string baseName) { DoOpenSslDsaTest(baseName + "_cbc"); DoOpenSslDsaTest(baseName + "_cfb"); DoOpenSslDsaTest(baseName + "_ecb"); DoOpenSslDsaTest(baseName + "_ofb"); } private void DoOpenSslRsaModesTest(string baseName) { DoOpenSslRsaTest(baseName + "_cbc"); DoOpenSslRsaTest(baseName + "_cfb"); DoOpenSslRsaTest(baseName + "_ecb"); DoOpenSslRsaTest(baseName + "_ofb"); } private void DoOpenSslDsaTest(string name) { string fileName = OpenSslDsaPrefix + name + ".pem"; DoOpenSslTestFile(fileName, typeof (DsaPrivateKeyParameters)); } private void DoOpenSslRsaTest(string name) { string fileName = OpenSslRsaPrefix + name + ".pem"; DoOpenSslTestFile(fileName, typeof (RsaPrivateCrtKeyParameters)); } private void DoOpenSslTestFile(string fileName, Type expectedPrivKeyType) { PemReader pr = OpenPemResource(fileName, new Password("changeit".ToCharArray())); var kp = pr.ReadObject() as AsymmetricCipherKeyPair; pr.Reader.Close(); if (kp == null) { Fail("Didn't find OpenSSL key"); } if (!expectedPrivKeyType.IsInstanceOfType(kp.Private)) { Fail("Returned key not of correct type"); } } private void DoDudPasswordTest(string password, int index, string message) { // illegal state exception check - in this case the wrong password will // cause an underlying class cast exception. try { IPasswordFinder pGet = new Password(password.ToCharArray()); PemReader pemRd = OpenPemResource("test.pem", pGet); while (pemRd.ReadObject() != null) { } Fail("issue not detected: " + index); } catch (IOException e) { if (e.Message.IndexOf(message, StringComparison.Ordinal) < 0) { Console.Error.WriteLine(message); Console.Error.WriteLine(e.Message); Fail("issue " + index + " exception thrown, but wrong message"); } } } private static PemReader OpenPemResource(string fileName, IPasswordFinder pGet) { Stream data = GetTestDataAsStream(OpenSslNamespace + fileName); TextReader tr = new StreamReader(data); return new PemReader(tr, pGet); } public static void Main(string[] args) { RunTest(new ReaderTest()); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
// 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.Configuration; using System.Diagnostics; using System.IO; namespace ChangeCopyrightInfo { /// <summary> /// Simple log /// </summary> public sealed class Log { /// <summary> /// Initializes a new instance of the class. /// </summary> private Log() { } private static string logFile = "WebsitePanel.Import.CsvBulk.log"; /// <summary> /// Initializes trace listeners. /// </summary> public static void Initialize(string fileName) { logFile = fileName; FileStream fileLog = new FileStream(logFile, FileMode.Append); TextWriterTraceListener fileListener = new TextWriterTraceListener(fileLog); fileListener.TraceOutputOptions = TraceOptions.DateTime; Trace.UseGlobalLock = true; Trace.Listeners.Clear(); Trace.Listeners.Add(fileListener); TextWriterTraceListener consoleListener = new TextWriterTraceListener(System.Console.Out); Trace.Listeners.Add(consoleListener); Trace.AutoFlush = true; } /// <summary> /// Write error to the log. /// </summary> /// <param name="message">Error message.</param> /// <param name="ex">Exception.</param> internal static void WriteError(string message, Exception ex) { try { string line = string.Format("[{0:G}] ERROR: {1}", DateTime.Now, message); Trace.WriteLine(line); Trace.WriteLine(ex); } catch { } } /// <summary> /// Write error to the log. /// </summary> /// <param name="message">Error message.</param> internal static void WriteError(string message) { try { string line = string.Format("[{0:G}] ERROR: {1}", DateTime.Now, message); Trace.WriteLine(line); } catch { } } /// <summary> /// Write to log /// </summary> /// <param name="message"></param> internal static void Write(string message) { try { string line = string.Format("[{0:G}] {1}", DateTime.Now, message); Trace.Write(line); } catch { } } /// <summary> /// Write line to log /// </summary> /// <param name="message"></param> internal static void WriteLine(string message) { try { string line = string.Format("[{0:G}] {1}", DateTime.Now, message); Trace.WriteLine(line); } catch { } } /// <summary> /// Write info message to log /// </summary> /// <param name="message"></param> internal static void WriteInfo(string message) { try { string line = string.Format("[{0:G}] INFO: {1}", DateTime.Now, message); Trace.WriteLine(line); } catch { } } /// <summary> /// Write start message to log /// </summary> /// <param name="message"></param> internal static void WriteStart(string message) { try { string line = string.Format("[{0:G}] START: {1}", DateTime.Now, message); Trace.WriteLine(line); } catch { } } /// <summary> /// Write end message to log /// </summary> /// <param name="message"></param> internal static void WriteEnd(string message) { try { string line = string.Format("[{0:G}] END: {1}", DateTime.Now, message); Trace.WriteLine(line); } catch { } } internal static void WriteApplicationStart() { try { string name = typeof(Log).Assembly.GetName().Name; string version = typeof(Log).Assembly.GetName().Version.ToString(3); string line = string.Format("[{0:G}] ***** {1} {2} Started *****", DateTime.Now, name, version); Trace.WriteLine(line); } catch { } } internal static void WriteApplicationEnd() { try { string name = typeof(Log).Assembly.GetName().Name; string line = string.Format("[{0:G}] ***** {1} Ended *****", DateTime.Now, name); Trace.WriteLine(line); } catch { } } /// <summary> /// Opens notepad to view log file. /// </summary> public static void ShowLogFile() { try { string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, logFile); Process.Start("notepad.exe", path); } catch { } } } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace Core.DocumentPickerWeb { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
using UnityEngine; using System.Collections; public class EnemySpawner : MonoBehaviour {public float delay; public float start; public float finish; public float totalDelay; public GameObject path; public GameObject baser; bool oncexx = true; //public GameObject [] pathPoints; public GameObject[] spawnList; public GameObject pathitem; public float spawnTime; bool once = false; float distance; bool once2 = true; public float x = -200f; public float y = 0f; public float z = 2200f; public GameObject graphicalPathObject; public Texture2D test; bool oncex = false; float timer = 0; bool oncey = true; public GameObject skull; private int spawnIndex = 0; // Use this for initialization void Start () { //CreateGraphicalPathObjects(); } //void OnGUI(){ //GUI.depth= -400; // GUI.Box(new Rect(0, 5, 100, 400), test); } // Update is called once per frame void Update (){ if(timer > totalDelay+1 && oncey == true){////////////starts attack after delay InvokeRepeating("Spawn", 0, spawnTime); oncey = false;} timer = timer+Time.deltaTime; //addin total delay = 5,10,15//always 15 in random mode//also once ////add in delay 0, 5, 10 if(once2==true&&timer>start+1 && timer<finish){///displays items once DrawPath (); for(int i = 0; i <spawnList.Length; i++){ Vector3 victor = new Vector3(x,y,z); GameObject test = Instantiate(spawnList[i], victor, Quaternion.identity) as GameObject; if(oncex == false){ Vector3 victor2 = new Vector3(-56,-40,1718); GameObject test1 = Instantiate(baser, victor2, Quaternion.identity) as GameObject; oncex = true;} Destroy(test.GetComponent<SmallShipStraighten>()); test.transform.tag = "Temp"; test.transform.Rotate(0f,90f,180f); Destroy(test.GetComponent<ShipSmoothMove>()); z = z - 200; } once2 = false; } if(timer>finish&&oncexx == true){///clean up DestroyItems(); oncexx = false; } } void Spawn() { //Spawn/Instantiate next enemy in spawnlist GameObject reference = Instantiate(spawnList[spawnIndex], transform.position, Quaternion.identity) as GameObject; reference.GetComponent<ShipSmoothMove>().pathPoints = path.GetComponent<PathStorage>().pathway; spawnIndex++; if(spawnIndex >= spawnList.Length) { CancelInvoke(); } //Set enemy path information //reference.SendMessage("SetPathPoints", path.GetComponent<PathStorage>().pathway ); } /* void CreateGraphicalPathObjects() { //Create object between transform.position and first waypoint Vector3 pathObjectPosition = ((pathPoints[0].transform.position - transform.position)*0.5f) + transform.position; Quaternion pathObjectOrientation = Quaternion.LookRotation(pathPoints[0].transform.position - transform.position); GameObject pathObject = Instantiate(graphicalPathObject, pathObjectPosition, pathObjectOrientation) as GameObject; Vector3 newScale = Vector3.one; newScale.z = (pathPoints[0].transform.position - transform.position).magnitude; pathObject.transform.localScale = newScale; Vector2 newTextureScale = Vector2.one; newTextureScale.y = (pathPoints[0].transform.position - transform.position).magnitude; pathObject.renderer.material.mainTextureScale = newTextureScale; for(int i = 1; i < pathPoints.Length; i++) { pathObjectPosition = ((pathPoints[i].transform.position - pathPoints[i-1].transform.position)*0.5f) + pathPoints[i-1].transform.position; pathObjectOrientation = Quaternion.LookRotation(pathPoints[i].transform.position - pathPoints[i-1].transform.position); pathObject = Instantiate(graphicalPathObject, pathObjectPosition, pathObjectOrientation) as GameObject; newScale = Vector3.one; //newScale += new Vector3(100f, 100f, 100f);//added newScale.z = (pathPoints[i].transform.position - pathPoints[i-1].transform.position).magnitude; pathObject.transform.localScale = newScale; newTextureScale = Vector2.one; //newTextureScale += new Vector2(0.1f, 0.1f);//added newTextureScale.y = (pathPoints[i].transform.position - pathPoints[i-1].transform.position).magnitude; pathObject.renderer.material.mainTextureScale = newTextureScale; } } */ void OnDrawGizmos() { //Gizmos.DrawLine(transform.position, pathPoints[0].transform.position); //Debug.DrawLine(transform.position, pathPoints[0].transform.position); //if(once == false){ // for(int i = 1; i < pathPoints.Length; i++){ /**{ //Gizmos.DrawLine(pathPoints[i-1].transform.position, pathPoints[i].transform.position); Vector3 test = new Vector3(); // Debug.DrawLine(pathPoints[i-1].transform.position, pathPoints[i].transform.position); distance = Vector3.Distance (pathPoints[i-1].transform.position, pathPoints[i].transform.position); distance = distance/200; for(float j = 0; j < 1; j= j + 1/distance){ test = Vector3.Lerp(pathPoints[i-1].transform.position, pathPoints[i].transform.position,j); GameObject pathitem1 = Instantiate(pathitem, test, Quaternion.identity) as GameObject; } once = true; } **/ //for(float j = 0; j < 1; j= j + 0.2f){ // test = Vector3.Lerp(transform.position, pathPoints[0].transform.position,j); // GameObject pathitem1 = Instantiate(pathitem, test, Quaternion.identity) as GameObject; // } //} //} } void DrawPath(){ if(once == false){ //LineRenderer pro = gameObject.GetComponent<LineRenderer>(); // pro.SetWidth(40f, 40f); // pro.SetVertexCount(20); // Vector3 victoria = new Vector3(5000f,5000f,5000f); for(int i = 0; i < path.GetComponent<PathStorage>().pathway.Length;i++){ GameObject pro = Instantiate(skull, path.GetComponent<PathStorage>().pathway[i].transform.position,Quaternion.identity) as GameObject; if(i+1 < path.GetComponent<PathStorage>().pathway.Length){ GameObject pro1 = Instantiate(skull, Vector3.Lerp (path.GetComponent<PathStorage>().pathway[i].transform.position,path.GetComponent<PathStorage>().pathway[i+1].transform.position,0.5f),Quaternion.identity) as GameObject;} } // for(int i = 0; i < path.GetComponent<PathStorage>().pathway.Length;i++){ // pro.SetPosition(i,path.GetComponent<PathStorage>().pathway[i].transform.position);} // for(int i = path.GetComponent<PathStorage>().pathway.Length;i<20;i++){ // pro.SetPosition(i,victoria);} once = true; } } void DestroyItems(){ //LineRenderer pro = gameObject.GetComponent<LineRenderer>(); //Destroy (pro); GameObject[] gos; gos = GameObject.FindGameObjectsWithTag("Temp"); foreach (GameObject go in gos) {Destroy (go);} GameObject prod = GameObject.FindGameObjectWithTag("Indicator"); Destroy (prod); GameObject[] gos2; gos2 = GameObject.FindGameObjectsWithTag("Skull"); foreach (GameObject go in gos2) {Destroy (go);} } }
using System; using System.Globalization; using System.Runtime.InteropServices; using System.Security; using System.Text; using System.Windows; using System.Windows.Automation.Provider; using System.Windows.Controls; using System.Windows.Interop; using System.Windows.Media; using MS.Internal; using MS.Win32; namespace System.Windows.Automation.Peers { /// public class ScrollViewerAutomationPeer : FrameworkElementAutomationPeer, IScrollProvider { /// public ScrollViewerAutomationPeer(ScrollViewer owner): base(owner) {} /// override protected string GetClassNameCore() { return "ScrollViewer"; } /// override protected AutomationControlType GetAutomationControlTypeCore() { return AutomationControlType.Pane; } /// override protected bool IsControlElementCore() { // Return true if ScrollViewer is not part of a ControlTemplate ScrollViewer sv = (ScrollViewer)Owner; DependencyObject templatedParent = sv.TemplatedParent; return templatedParent == null || templatedParent is ContentPresenter; // If the templatedParent is a ContentPresenter, this ScrollViewer is generated from a DataTemplate } /// override public object GetPattern(PatternInterface patternInterface) { if (patternInterface == PatternInterface.Scroll) { return this; } else { return base.GetPattern(patternInterface); } } //------------------------------------------------------------------- // // IScrollProvider // //------------------------------------------------------------------- /// <summary> /// Request to scroll horizontally and vertically by the specified amount. /// The ability to call this method and simultaneously scroll horizontally /// and vertically provides simple panning support. /// </summary> /// <see cref="IScrollProvider.Scroll"/> void IScrollProvider.Scroll(ScrollAmount horizontalAmount, ScrollAmount verticalAmount) { if(!IsEnabled()) throw new ElementNotEnabledException(); bool scrollHorizontally = (horizontalAmount != ScrollAmount.NoAmount); bool scrollVertically = (verticalAmount != ScrollAmount.NoAmount); ScrollViewer owner = (ScrollViewer)Owner; if (scrollHorizontally && !HorizontallyScrollable || scrollVertically && !VerticallyScrollable) { throw new InvalidOperationException(SR.Get(SRID.UIA_OperationCannotBePerformed)); } switch (horizontalAmount) { case ScrollAmount.LargeDecrement: owner.PageLeft(); break; case ScrollAmount.SmallDecrement: owner.LineLeft(); break; case ScrollAmount.SmallIncrement: owner.LineRight(); break; case ScrollAmount.LargeIncrement: owner.PageRight(); break; case ScrollAmount.NoAmount: break; default: throw new InvalidOperationException(SR.Get(SRID.UIA_OperationCannotBePerformed)); } switch (verticalAmount) { case ScrollAmount.LargeDecrement: owner.PageUp(); break; case ScrollAmount.SmallDecrement: owner.LineUp(); break; case ScrollAmount.SmallIncrement: owner.LineDown(); break; case ScrollAmount.LargeIncrement: owner.PageDown(); break; case ScrollAmount.NoAmount: break; default: throw new InvalidOperationException(SR.Get(SRID.UIA_OperationCannotBePerformed)); } } /// <summary> /// Request to set the current horizontal and Vertical scroll position by percent (0-100). /// Passing in the value of "-1", represented by the constant "NoScroll", will indicate that scrolling /// in that direction should be ignored. /// The ability to call this method and simultaneously scroll horizontally and vertically provides simple panning support. /// </summary> /// <see cref="IScrollProvider.SetScrollPercent"/> void IScrollProvider.SetScrollPercent(double horizontalPercent, double verticalPercent) { if(!IsEnabled()) throw new ElementNotEnabledException(); bool scrollHorizontally = (horizontalPercent != (double)ScrollPatternIdentifiers.NoScroll); bool scrollVertically = (verticalPercent != (double)ScrollPatternIdentifiers.NoScroll); ScrollViewer owner = (ScrollViewer)Owner; if (scrollHorizontally && !HorizontallyScrollable || scrollVertically && !VerticallyScrollable) { throw new InvalidOperationException(SR.Get(SRID.UIA_OperationCannotBePerformed)); } if (scrollHorizontally && (horizontalPercent < 0.0) || (horizontalPercent > 100.0)) { throw new ArgumentOutOfRangeException("horizontalPercent", SR.Get(SRID.ScrollViewer_OutOfRange, "horizontalPercent", horizontalPercent.ToString(CultureInfo.InvariantCulture), "0", "100")); } if (scrollVertically && (verticalPercent < 0.0) || (verticalPercent > 100.0)) { throw new ArgumentOutOfRangeException("verticalPercent", SR.Get(SRID.ScrollViewer_OutOfRange, "verticalPercent", verticalPercent.ToString(CultureInfo.InvariantCulture), "0", "100")); } if (scrollHorizontally) { owner.ScrollToHorizontalOffset((owner.ExtentWidth - owner.ViewportWidth) * (double)horizontalPercent * 0.01); } if (scrollVertically) { owner.ScrollToVerticalOffset((owner.ExtentHeight - owner.ViewportHeight) * (double)verticalPercent * 0.01); } } /// <summary> /// Get the current horizontal scroll position /// </summary> /// <see cref="IScrollProvider.HorizontalScrollPercent"/> double IScrollProvider.HorizontalScrollPercent { get { if (!HorizontallyScrollable) { return ScrollPatternIdentifiers.NoScroll; } ScrollViewer owner = (ScrollViewer)Owner; return (double)(owner.HorizontalOffset * 100.0 / (owner.ExtentWidth - owner.ViewportWidth)); } } /// <summary> /// Get the current vertical scroll position /// </summary> /// <see cref="IScrollProvider.VerticalScrollPercent"/> double IScrollProvider.VerticalScrollPercent { get { if (!VerticallyScrollable) { return ScrollPatternIdentifiers.NoScroll; } ScrollViewer owner = (ScrollViewer)Owner; return (double)(owner.VerticalOffset * 100.0 / (owner.ExtentHeight - owner.ViewportHeight)); } } /// <summary> /// Equal to the horizontal percentage of the entire control that is currently viewable. /// </summary> /// <see cref="IScrollProvider.HorizontalViewSize"/> double IScrollProvider.HorizontalViewSize { get { ScrollViewer owner = (ScrollViewer)Owner; if (owner.ScrollInfo == null || DoubleUtil.IsZero(owner.ExtentWidth)) { return 100.0; } return Math.Min(100.0, (double)(owner.ViewportWidth * 100.0 / owner.ExtentWidth)); } } /// <summary> /// Equal to the vertical percentage of the entire control that is currently viewable. /// </summary> /// <see cref="IScrollProvider.VerticalViewSize"/> double IScrollProvider.VerticalViewSize { get { ScrollViewer owner = (ScrollViewer)Owner; if (owner.ScrollInfo == null || DoubleUtil.IsZero(owner.ExtentHeight)) { return 100f; } return Math.Min(100.0, (double)(owner.ViewportHeight * 100.0 / owner.ExtentHeight)); } } /// <summary> /// True if control can scroll horizontally /// </summary> /// <see cref="IScrollProvider.HorizontallyScrollable"/> bool IScrollProvider.HorizontallyScrollable { get { return HorizontallyScrollable; } } /// <summary> /// True if control can scroll vertically /// </summary> /// <see cref="IScrollProvider.VerticallyScrollable"/> bool IScrollProvider.VerticallyScrollable { get { return VerticallyScrollable; } } private static bool AutomationIsScrollable(double extent, double viewport) { return DoubleUtil.GreaterThan(extent, viewport); } private static double AutomationGetScrollPercent(double extent, double viewport, double actualOffset) { if (!AutomationIsScrollable(extent, viewport)) { return ScrollPatternIdentifiers.NoScroll; } return (double)(actualOffset * 100.0 / (extent - viewport)); } private static double AutomationGetViewSize(double extent, double viewport) { if (DoubleUtil.IsZero(extent)) { return 100.0; } return Math.Min(100.0, (double)(viewport * 100.0 / extent)); } // Private *Scrollable properties used to determine scrollability for IScrollProvider implemenation. private bool HorizontallyScrollable { get { ScrollViewer owner = (ScrollViewer)Owner; return owner.ScrollInfo != null && DoubleUtil.GreaterThan(owner.ExtentWidth, owner.ViewportWidth); } } private bool VerticallyScrollable { get { ScrollViewer owner = (ScrollViewer)Owner; return owner.ScrollInfo != null && DoubleUtil.GreaterThan(owner.ExtentHeight, owner.ViewportHeight); } } // This helper synchronously fires automation PropertyChange events for every IScrollProvider property that has changed. // [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] internal void RaiseAutomationEvents(double extentX, double extentY, double viewportX, double viewportY, double offsetX, double offsetY) { IScrollProvider isp = (IScrollProvider)this; if (AutomationIsScrollable(extentX, viewportX) != isp.HorizontallyScrollable) { RaisePropertyChangedEvent( ScrollPatternIdentifiers.HorizontallyScrollableProperty, AutomationIsScrollable(extentX, viewportX), isp.HorizontallyScrollable); } if (AutomationIsScrollable(extentY, viewportY) != isp.VerticallyScrollable) { RaisePropertyChangedEvent( ScrollPatternIdentifiers.VerticallyScrollableProperty, AutomationIsScrollable(extentY, viewportY), isp.VerticallyScrollable); } if (AutomationGetViewSize(extentX, viewportX) != isp.HorizontalViewSize) { RaisePropertyChangedEvent( ScrollPatternIdentifiers.HorizontalViewSizeProperty, AutomationGetViewSize(extentX, viewportX), isp.HorizontalViewSize); } if (AutomationGetViewSize(extentY, viewportY) != isp.VerticalViewSize) { RaisePropertyChangedEvent( ScrollPatternIdentifiers.VerticalViewSizeProperty, AutomationGetViewSize(extentY, viewportY), isp.VerticalViewSize); } if (AutomationGetScrollPercent(extentX, viewportX, offsetX) != isp.HorizontalScrollPercent) { RaisePropertyChangedEvent( ScrollPatternIdentifiers.HorizontalScrollPercentProperty, AutomationGetScrollPercent(extentX, viewportX, offsetX), isp.HorizontalScrollPercent); } if (AutomationGetScrollPercent(extentY, viewportY, offsetY) != isp.VerticalScrollPercent) { RaisePropertyChangedEvent( ScrollPatternIdentifiers.VerticalScrollPercentProperty, AutomationGetScrollPercent(extentY, viewportY, offsetY), isp.VerticalScrollPercent); } } } }
// 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. #define CONTRACTS_FULL using System; using System.Diagnostics.Contracts; public class Foo { private int foo; public void Accessfoo() { Contract.Requires(foo > 5); Contract.Ensures(foo > Contract.OldValue(foo)+1); } private class Bar { internal void AccessFoofoo(Foo foo) { Contract.Requires(foo.foo > 5); } } } [ContractClass(typeof(CJ))] public interface J{ int M(int x); } //[ContractClassFor(typeof(J))] // Error: Need back link public class CJ{ public int M(int x){ return x; } } public class SpecPublicField{ [ContractPublicPropertyName("P")] private int x; public bool P { get { return true; } } } public class CantThrowNonVisibleException{ private class PrivateException : Exception {} public int M(int x){ if (x == 0) throw new PrivateException(); Contract.EndContractBlock(); return x; } } public class InvalidMethodsInPrecondition{ public int M(int x, out int y){ Contract.Requires(Contract.Result<int>() == x); // bad Contract.Requires(Contract.ValueAtReturn(out y) == x); // bad but not caught Contract.Requires(Contract.OldValue(x) == x); // bad y = 3; return x; } } public class InvalidMethodsInPostcondition{ private class MyException : Exception {} public int M(int x, out int y){ Contract.Ensures(Contract.Result<bool>() == true); // Error: wrong type Contract.Ensures(Contract.OldValue(3) == x); // Error: literal arg to Old Contract.EnsuresOnThrow<Exception>(Contract.Result<int>() > 0); // error result in exception ensures y = 3; return x; } int z; [ContractInvariantMethod] void ObjectInvariant() { z = 5; Contract.Invariant(z == 5); } } class Internal{ int x; public int M(int y){ Contract.Requires(x < y); // Error: x is not visible outside of this class return y; } } class BaseClassWithPrecondition{ public virtual int M(int x){ Contract.Requires(x != 3); return 3; } } class DerivedClassWithPrecondition : BaseClassWithPrecondition{ public override int M(int y){ Contract.Requires(0 < y); return 27; } } public class NonSealedClassWithPrivateInvariant{ bool b = true; private void ObjectInvariant(){ Contract.Invariant(b); } } [Pure] public class PureClass { public static int MethodInPureClass(int y) { return y; } } public class NotPureClass { public static int MethodInNotPureClass(int y) { return y; } } public class PurityTests{ public int P { get { return 3; } } [Pure] public int MarkedPure(int y) { return y; } public int NotMarkedPure(int y) { return y; } public int M(int x){ Contract.Requires(x <= MarkedPure(x)); // OK Contract.Requires(x <= PureClass.MethodInPureClass(x)); // OK Contract.Requires(x <= P); // OK: properties are pure by default Contract.Requires(x <= NotMarkedPure(x)); // Error Contract.Requires(x <= NotPureClass.MethodInNotPureClass(x)); // Error return x; } } public class CA1004 { public int x; public void M() { x = 5; Contract.Requires(x > 5); } } public class CA1005 { public int x; public void M() { x = 5; Contract.Ensures(x > 5); } [ContractModel] public int X { get { return x; } } public void N() { x = 5; Contract.Ensures(X > 5); // not warned about because we skip Model extraction in rewriter } } public class CA1006 { [ContractClass(typeof(CI))] interface I { } struct CI : I { } } class CA1008 { [ContractClass(typeof(CK))] public interface K{ int M(int x); } [ContractClassFor(typeof(K))] abstract public class CK{ // Error: Need to implement K public int M(int x){ return x; } } } class CA1009 { [ContractClass(typeof(Bad))] abstract class Abstract { } [ContractClassFor(typeof(Abstract))] abstract class Bad { } } class CA1010 { [ContractPublicPropertyName("F")] private int f; } class CA1020 { [ContractClass(typeof(CK))] public interface K{ int M(int x); } [ContractClassFor(typeof(K))] public class CK : K { public int M(int x){ return x; } } } class CA1042 { public class Invariant_NoFlags { bool pass1 = true; bool pass2 = true; bool pass3 = true; bool pass4 = true; [ContractInvariantMethod] void ObjectInvariant() { Contract.Invariant(pass1 == true); Contract.Invariant(pass2 == true, "pass2 must be true"); Contract.Invariant(pass3 == true, String.Empty); Contract.Invariant(pass4 == true, null); } public int CheckInvariant(bool shouldPass) { pass1 = shouldPass; pass2 = true; pass3 = true; pass4 = true; return 10; } public int CheckInvariantString(bool shouldPass) { pass1 = true; pass2 = shouldPass; pass3 = true; pass4 = true; return 10; } public int CheckInvariantStringEmpty(bool shouldPass) { pass1 = true; pass2 = true; pass3 = shouldPass; pass4 = true; return 10; } public int CheckInvariantStringNull(bool shouldPass) { pass1 = true; pass2 = true; pass3 = true; pass4 = shouldPass; return 10; } // Does not make sense; only call in non-rewritten binary [ContractInvariantMethod] public void CallContractInvariantMethod() { Contract.Invariant(pass1 == true); } public void runTest() { Console.WriteLine("Contract_class\\InvariantTest.cs"); try { Console.WriteLine("Assembly compiled with no flags"); Invariant_NoFlags test1 = new Invariant_NoFlags(); VerifyPass("001 CheckInvariant(true)", delegate { test1.CheckInvariant(true); }); VerifyPass("002 CheckInvariant(false)", delegate { test1.CheckInvariant(false); }); VerifyPass("003 CheckInvariantString(true)", delegate { test1.CheckInvariantString(true); }); VerifyPass("004 CheckInvariantString(false)", delegate { test1.CheckInvariantString(false); }); VerifyPass("005 CallContractInvariantMethod()", delegate { test1.CallContractInvariantMethod(); }); VerifyPass("006 CheckInvariant(false), SetHandled", delegate { test1.CheckInvariant(false); }); VerifyPass("007 CheckInvariantString(false), SetHandled", delegate { test1.CheckInvariantString(false); }); } finally { } } public void VerifyPass(string s, Action action) { } } } public class ContractModelAttribute : Attribute {}
using System; using UnityEngine; namespace UnitySampleAssets.ImageEffects { public enum LensflareStyle34 { Ghosting = 0, Anamorphic = 1, Combined = 2, } public enum TweakMode34 { Basic = 0, Complex = 1, } public enum HDRBloomMode { Auto = 0, On = 1, Off = 2, } public enum BloomScreenBlendMode { Screen = 0, Add = 1, } [ExecuteInEditMode] [RequireComponent(typeof(Camera))] [AddComponentMenu("Image Effects/Bloom and Glow/BloomAndFlares (3.5, Deprecated)")] public class BloomAndFlares : PostEffectsBase { public TweakMode34 tweakMode = 0; public BloomScreenBlendMode screenBlendMode = BloomScreenBlendMode.Add; public HDRBloomMode hdr = HDRBloomMode.Auto; private bool doHdr = false; public float sepBlurSpread = 1.5f; public float useSrcAlphaAsMask = 0.5f; public float bloomIntensity = 1.0f; public float bloomThreshold = 0.5f; public int bloomBlurIterations = 2; public bool lensflares = false; public int hollywoodFlareBlurIterations = 2; public LensflareStyle34 lensflareMode = (LensflareStyle34)1; public float hollyStretchWidth = 3.5f; public float lensflareIntensity = 1.0f; public float lensflareThreshold = 0.3f; public Color flareColorA = new Color(0.4f, 0.4f, 0.8f, 0.75f); public Color flareColorB = new Color(0.4f, 0.8f, 0.8f, 0.75f); public Color flareColorC = new Color(0.8f, 0.4f, 0.8f, 0.75f); public Color flareColorD = new Color(0.8f, 0.4f, 0.0f, 0.75f); public Texture2D lensFlareVignetteMask; public Shader lensFlareShader; private Material lensFlareMaterial; public Shader vignetteShader; private Material vignetteMaterial; public Shader separableBlurShader; private Material separableBlurMaterial; public Shader addBrightStuffOneOneShader; private Material addBrightStuffBlendOneOneMaterial; public Shader screenBlendShader; private Material screenBlend; public Shader hollywoodFlaresShader; private Material hollywoodFlaresMaterial; public Shader brightPassFilterShader; private Material brightPassFilterMaterial; public override bool CheckResources() { CheckSupport(false); screenBlend = CheckShaderAndCreateMaterial(screenBlendShader, screenBlend); lensFlareMaterial = CheckShaderAndCreateMaterial(lensFlareShader, lensFlareMaterial); vignetteMaterial = CheckShaderAndCreateMaterial(vignetteShader, vignetteMaterial); separableBlurMaterial = CheckShaderAndCreateMaterial(separableBlurShader, separableBlurMaterial); addBrightStuffBlendOneOneMaterial = CheckShaderAndCreateMaterial(addBrightStuffOneOneShader, addBrightStuffBlendOneOneMaterial); hollywoodFlaresMaterial = CheckShaderAndCreateMaterial(hollywoodFlaresShader, hollywoodFlaresMaterial); brightPassFilterMaterial = CheckShaderAndCreateMaterial(brightPassFilterShader, brightPassFilterMaterial); if (!isSupported) ReportAutoDisable(); return isSupported; } void OnRenderImage(RenderTexture source, RenderTexture destination) { if (CheckResources() == false) { Graphics.Blit(source, destination); return; } // screen blend is not supported when HDR is enabled (will cap values) doHdr = false; if (hdr == HDRBloomMode.Auto) doHdr = source.format == RenderTextureFormat.ARGBHalf && GetComponent<Camera>().hdr; else { doHdr = hdr == HDRBloomMode.On; } doHdr = doHdr && supportHDRTextures; BloomScreenBlendMode realBlendMode = screenBlendMode; if (doHdr) realBlendMode = BloomScreenBlendMode.Add; var rtFormat = (doHdr) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.Default; RenderTexture halfRezColor = RenderTexture.GetTemporary(source.width / 2, source.height / 2, 0, rtFormat); RenderTexture quarterRezColor = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0, rtFormat); RenderTexture secondQuarterRezColor = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0, rtFormat); RenderTexture thirdQuarterRezColor = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0, rtFormat); float widthOverHeight = (1.0f * source.width) / (1.0f * source.height); float oneOverBaseSize = 1.0f / 512.0f; // downsample Graphics.Blit(source, halfRezColor, screenBlend, 2); // <- 2 is stable downsample Graphics.Blit(halfRezColor, quarterRezColor, screenBlend, 2); // <- 2 is stable downsample RenderTexture.ReleaseTemporary(halfRezColor); // cut colors (thresholding) BrightFilter(bloomThreshold, useSrcAlphaAsMask, quarterRezColor, secondQuarterRezColor); quarterRezColor.DiscardContents(); // blurring if (bloomBlurIterations < 1) bloomBlurIterations = 1; for (int iter = 0; iter < bloomBlurIterations; iter++) { float spreadForPass = (1.0f + (iter * 0.5f)) * sepBlurSpread; separableBlurMaterial.SetVector("offsets", new Vector4(0.0f, spreadForPass * oneOverBaseSize, 0.0f, 0.0f)); RenderTexture src = iter == 0 ? secondQuarterRezColor : quarterRezColor; Graphics.Blit(src, thirdQuarterRezColor, separableBlurMaterial); src.DiscardContents(); separableBlurMaterial.SetVector("offsets", new Vector4((spreadForPass / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); Graphics.Blit(thirdQuarterRezColor, quarterRezColor, separableBlurMaterial); thirdQuarterRezColor.DiscardContents(); } // lens flares: ghosting, anamorphic or a combination if (lensflares) { if (lensflareMode == 0) { BrightFilter(lensflareThreshold, 0.0f, quarterRezColor, thirdQuarterRezColor); quarterRezColor.DiscardContents(); // smooth a little, this needs to be resolution dependent /* separableBlurMaterial.SetVector ("offsets", Vector4 (0.0ff, (2.0ff) / (1.0ff * quarterRezColor.height), 0.0ff, 0.0ff)); Graphics.Blit (thirdQuarterRezColor, secondQuarterRezColor, separableBlurMaterial); separableBlurMaterial.SetVector ("offsets", Vector4 ((2.0ff) / (1.0ff * quarterRezColor.width), 0.0ff, 0.0ff, 0.0ff)); Graphics.Blit (secondQuarterRezColor, thirdQuarterRezColor, separableBlurMaterial); */ // no ugly edges! Vignette(0.975f, thirdQuarterRezColor, secondQuarterRezColor); thirdQuarterRezColor.DiscardContents(); BlendFlares(secondQuarterRezColor, quarterRezColor); secondQuarterRezColor.DiscardContents(); } // (b) hollywood/anamorphic flares? else { // thirdQuarter has the brightcut unblurred colors // quarterRezColor is the blurred, brightcut buffer that will end up as bloom hollywoodFlaresMaterial.SetVector("_Threshhold", new Vector4(lensflareThreshold, 1.0f / (1.0f - lensflareThreshold), 0.0f, 0.0f)); hollywoodFlaresMaterial.SetVector("tintColor", new Vector4(flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * flareColorA.a * lensflareIntensity); Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, hollywoodFlaresMaterial, 2); thirdQuarterRezColor.DiscardContents(); Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, hollywoodFlaresMaterial, 3); secondQuarterRezColor.DiscardContents(); hollywoodFlaresMaterial.SetVector("offsets", new Vector4((sepBlurSpread * 1.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); hollywoodFlaresMaterial.SetFloat("stretchWidth", hollyStretchWidth); Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, hollywoodFlaresMaterial, 1); thirdQuarterRezColor.DiscardContents(); hollywoodFlaresMaterial.SetFloat("stretchWidth", hollyStretchWidth * 2.0f); Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, hollywoodFlaresMaterial, 1); secondQuarterRezColor.DiscardContents(); hollywoodFlaresMaterial.SetFloat("stretchWidth", hollyStretchWidth * 4.0f); Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, hollywoodFlaresMaterial, 1); thirdQuarterRezColor.DiscardContents(); if (lensflareMode == (LensflareStyle34)1) { for (int itera = 0; itera < hollywoodFlareBlurIterations; itera++) { separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, separableBlurMaterial); secondQuarterRezColor.DiscardContents(); separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, separableBlurMaterial); thirdQuarterRezColor.DiscardContents(); } AddTo(1.0f, secondQuarterRezColor, quarterRezColor); secondQuarterRezColor.DiscardContents(); } else { // (c) combined for (int ix = 0; ix < hollywoodFlareBlurIterations; ix++) { separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, separableBlurMaterial); secondQuarterRezColor.DiscardContents(); separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, separableBlurMaterial); thirdQuarterRezColor.DiscardContents(); } Vignette(1.0f, secondQuarterRezColor, thirdQuarterRezColor); secondQuarterRezColor.DiscardContents(); BlendFlares(thirdQuarterRezColor, secondQuarterRezColor); thirdQuarterRezColor.DiscardContents(); AddTo(1.0f, secondQuarterRezColor, quarterRezColor); secondQuarterRezColor.DiscardContents(); } } } // screen blend bloom results to color buffer screenBlend.SetFloat("_Intensity", bloomIntensity); screenBlend.SetTexture("_ColorBuffer", source); Graphics.Blit(quarterRezColor, destination, screenBlend, (int)realBlendMode); RenderTexture.ReleaseTemporary(quarterRezColor); RenderTexture.ReleaseTemporary(secondQuarterRezColor); RenderTexture.ReleaseTemporary(thirdQuarterRezColor); } private void AddTo(float intensity_, RenderTexture from, RenderTexture to) { addBrightStuffBlendOneOneMaterial.SetFloat("_Intensity", intensity_); Graphics.Blit(from, to, addBrightStuffBlendOneOneMaterial); } private void BlendFlares(RenderTexture from, RenderTexture to) { lensFlareMaterial.SetVector("colorA", new Vector4(flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * lensflareIntensity); lensFlareMaterial.SetVector("colorB", new Vector4(flareColorB.r, flareColorB.g, flareColorB.b, flareColorB.a) * lensflareIntensity); lensFlareMaterial.SetVector("colorC", new Vector4(flareColorC.r, flareColorC.g, flareColorC.b, flareColorC.a) * lensflareIntensity); lensFlareMaterial.SetVector("colorD", new Vector4(flareColorD.r, flareColorD.g, flareColorD.b, flareColorD.a) * lensflareIntensity); Graphics.Blit(from, to, lensFlareMaterial); } private void BrightFilter(float thresh, float useAlphaAsMask, RenderTexture from, RenderTexture to) { if (doHdr) brightPassFilterMaterial.SetVector("threshhold", new Vector4(thresh, 1.0f, 0.0f, 0.0f)); else brightPassFilterMaterial.SetVector("threshhold", new Vector4(thresh, 1.0f / (1.0f - thresh), 0.0f, 0.0f)); brightPassFilterMaterial.SetFloat("useSrcAlphaAsMask", useAlphaAsMask); Graphics.Blit(from, to, brightPassFilterMaterial); } private void Vignette(float amount, RenderTexture from, RenderTexture to) { if (lensFlareVignetteMask) { screenBlend.SetTexture("_ColorBuffer", lensFlareVignetteMask); Graphics.Blit(from, to, screenBlend, 3); } else { vignetteMaterial.SetFloat("vignetteIntensity", amount); Graphics.Blit(from, to, vignetteMaterial); } } } }
using System; using System.Collections.Generic; using System.Collections; using System.Text; using System.Xml; using System.Reflection; /** * This is a simple object to XML serializer. The SimpleWriter class * extends ObjectWriter. It takes a C# object and a XmlTextWriter object. * It writes (converts) an object to XML, and writes it using the XmlTextWriter * to the specified storage media. The object is represented in standard XML * defined by WOX. For more information about the XML representation * please visit: http://woxserializer.sourceforge.net/ * * Authors: Carlos R. Jaimez Gonzalez * Simon M. Lucas * Version: SimpleWriter.cs - 1.0 */ namespace wox.serial { public class SimpleWriter : ObjectWriter { Hashtable map; int count; bool writePrimitiveTypes = true; bool doStatic = true; // not much point writing out final values - at least yet - // the reader is not able to set them (though there's probably // a hidden way of doing this bool doFinal = false; public SimpleWriter() { //Console.Out.WriteLine("inside SimpleWriter..."); //System.out.println("inside SimpleWriter Constructor..."); map = new Hashtable(); count = 0; } /** * This method is the etry point to write an object in XML. It actually * returns a JDOM Element representing the object passed as parameter. * @param ob Object - The object to be serialized * @return org.jdom.Element - The serialized object */ public override void write(Object ob, XmlTextWriter el) { if (ob == null) { // a null object is represented by an empty Object tag with no attributes //<object /> //Console.Out.WriteLine("null object..."); el.WriteElementString(OBJECT, null); //return el; //return new Element(OBJECT); } //if the object is already in the map, print its IDREF and not the whole object //<object idref="5" /> //if (map.get(ob) != null) else if (map.ContainsKey(ob)) { //Console.Out.WriteLine("object already in the map..."); el.WriteStartElement(OBJECT); //el.WriteAttributeString(IDREF, (string)map[ob]); el.WriteAttributeString(IDREF, map[ob].ToString()); el.WriteEndElement(); //return el; //el = new Element(OBJECT); //el.setAttribute(IDREF, map.get(ob).toString()); //return el; } // a previously unseen object... else { // a previously unseen object... put is in the map //map.put(ob, new Integer(count++)); //Console.Out.WriteLine("adding the object to the map..."); map.Add(ob, count++); //check if the object can go to string (wrapper objects - Integer, Boolean, etc.) if (Util.stringable(ob)) { //Console.Out.WriteLine("object is stringable..."); //Console.Out.WriteLine("typeof object: " + ob.GetType()); el.WriteStartElement(OBJECT); //Console.Out.WriteLine("ob" + ob + ", " + ob.GetType().ToString()); String woxType = (String)mapCSharpToWOX[ob.GetType().ToString()]; //Console.Out.WriteLine("woxType: " + woxType); //get the wrapper type, because this is a root object //String woxWrapperType = (String)mapWrapper[woxType]; //el.WriteAttributeString(TYPE, woxWrapperType); el.WriteAttributeString(TYPE, woxType); el.WriteAttributeString(VALUE, stringify(ob)); el.WriteAttributeString(ID, map[ob].ToString()); el.WriteEndElement(); /*el = new Element(OBJECT); String woxType = (String)mapJavaToWOX.get(ob.getClass()); el.setAttribute(TYPE, woxType); el.setAttribute(VALUE, stringify(ob));*/ } else if (ob is System.Array) { //Console.Out.WriteLine("it is an array..." + ob.GetType().ToString()); writeArray(ob, el); } //this is to handle ArrayList objects (added 25 April) else if (ob is System.Collections.ArrayList) { writeArrayList(ob, el); } //this is to handle ArrayList objects (added 30 April) else if (ob is System.Collections.Hashtable) { writeHashtable(ob, el); } else { //Console.Out.WriteLine("it is another type of object..." + ob.GetType().ToString()); el.WriteStartElement(OBJECT); el.WriteAttributeString(TYPE, ob.GetType().ToString()); el.WriteAttributeString(ID, map[ob].ToString()); writeFields(ob, el); el.WriteEndElement(); /*el = new Element(OBJECT); el.setAttribute(TYPE, ob.getClass().getName()); writeFields(ob, el);*/ } //el.setAttribute(ID, map.get(ob).toString()); //el.WriteAttributeString(ID, map[ob].ToString()); //return el; } } public void writeHashtable(Object ob, XmlTextWriter el) { //Element el = new Element(ARRAYLIST); //Element el = new Element(OBJECT); el.WriteStartElement(OBJECT); //the type for this object is "map" el.WriteAttributeString(TYPE, MAP); el.WriteAttributeString(ID, map[ob].ToString()); //we already know it is an ArrayList, so, we get the underlying array //and pass it to the "writeObjectArrayGeneric" method to get it serialized Hashtable hashMap = (Hashtable)ob; //get the entry set IDictionaryEnumerator keys = hashMap.GetEnumerator(); //el.WriteAttributeString(LENGTH, "" + keys.); while (keys.MoveNext()) { //Console.Out.WriteLine("writing an entry..."); //Console.Out.WriteLine("*KEY* " + keys.Key + ", *OBJECT* " + keys.Value); writeMapEntry(keys.Entry, el); } el.WriteEndElement(); /*//for each element in the entry set I have to create an entry object Iterator it = keys.iterator(); while (it.hasNext()) { Map.Entry entryMap = (Map.Entry)it.next(); el.addContent(writeMapEntry(entryMap)); //System.out.println("*KEY* " + entryMap.getKey() + ", *OBJECT* " + entryMap.getValue()); } return el;*/ } public void writeMapEntry(Object ob, XmlTextWriter el) { //Element el = new Element(ARRAYLIST); //Element el = new Element(OBJECT); el.WriteStartElement(OBJECT); //the type for this object is "map" //el.setAttribute(TYPE, ENTRY); el.WriteAttributeString(TYPE, ENTRY); //lets cast the object to a Map.Entry DictionaryEntry entry = (DictionaryEntry)ob; writeMapEntryKey(entry.Key, el); writeMapEntryKey(entry.Value, el); el.WriteEndElement(); //return el; } public void writeMapEntryKey(Object ob, XmlTextWriter el) { //Element el = new Element(ARRAYLIST); /*Element el = new Element(FIELD); //the type for this object is "map" el.setAttribute(TYPE, KEY); el.addContent(write(ob)); return el;*/ //return write(ob); write(ob, el); } public void writeMapEntryValue(Object ob, XmlTextWriter el) { //Element el = new Element(ARRAYLIST); /*Element el = new Element(FIELD); //the type for this object is "map" el.setAttribute(TYPE, VALUE); el.addContent(write(ob)); return el;*/ write(ob, el); } public void writeArrayList(Object ob, XmlTextWriter el) { //Console.Out.WriteLine("it is an arraylist..."); el.WriteStartElement(OBJECT); el.WriteAttributeString(TYPE, ARRAYLIST); //we already know it is an ArrayList, so, we get the underlying array //and pass it to the "writeObjectArrayGeneric" method to get it serialized ArrayList list = (ArrayList)ob; Object obArray = list.ToArray(); writeObjectArrayGeneric(ob, obArray, el); } public void writeArray(Object ob, XmlTextWriter el) { //a primitive array is an array of any of the following: //byte, short, int, long, float, double, char, boolean, //Byte, Short, Integer, Long, Float, Double, Character, Boolean, and Class //These arrays can go easily to a string with spaces separating their elements. if (isPrimitiveArray(ob.GetType().ToString())) { //Console.Out.WriteLine("-----------------PRIMITIVE ARRAY------------------"); writePrimitiveArray(ob, el); } else { //Console.Out.WriteLine("-----------------NOT A PRIMITIVE ARRAY------------------"); writeObjectArray(ob, el); } } public void writeObjectArray(Object ob, XmlTextWriter el) { //Element el = new Element(ARRAY); //el.WriteStartElement(ARRAY); el.WriteStartElement(OBJECT); el.WriteAttributeString(TYPE, ARRAY); writeObjectArrayGeneric(ob, ob, el); } public void writeObjectArrayGeneric(Object obStored, Object ob, XmlTextWriter el) { //Element el = new Element(ARRAY); //el.WriteStartElement(ARRAY); //it gets the correct WOX type from the map, in case there is one //for example for int[][].class it will get int[][] //String woxType = (String)mapJavaToWOX.get(ob.getClass().getComponentType()); String woxType = (String)mapCSharpToWOX[ob.GetType().GetElementType().ToString()]; if (woxType == null) { //woxType = (String)mapArrayJavaToWOX.get(ob.getClass().getComponentType()); woxType = (String)mapArrayCSharpToWOX[ob.GetType().GetElementType().ToString()]; if (woxType != null) { //el.setAttribute(TYPE, woxType); //el.WriteAttributeString(TYPE, woxType); el.WriteAttributeString(ELEMENT_TYPE, woxType); } else { //this is for arrays of Object if (ob.GetType().GetElementType().ToString().Equals("System.Object")) { //el.WriteAttributeString(TYPE, "Object"); el.WriteAttributeString(ELEMENT_TYPE, "Object"); } //for the rest of the arrays, we use the appropriate data type else { //el.setAttribute(TYPE, ob.getClass().getComponentType().getName()); //el.WriteAttributeString(TYPE, ob.GetType().GetElementType().ToString()); el.WriteAttributeString(ELEMENT_TYPE, ob.GetType().GetElementType().ToString()); } } } else { //el.setAttribute(TYPE, woxType); //el.WriteAttributeString(TYPE, woxType); el.WriteAttributeString(ELEMENT_TYPE, woxType); } //int len = Array.getLength(ob); //el.setAttribute(LENGTH, "" + len); Array obArray = (Array)ob; int len = obArray.GetLength(0); el.WriteAttributeString(LENGTH, "" + len); el.WriteAttributeString(ID, map[obStored].ToString()); //Console.Out.WriteLine("array length: " + len); for (int i = 0; i < len; i++) { //el.addContent(write(Array.get(ob, i))); write(obArray.GetValue(i), el); } el.WriteEndElement(); //return el; } public void writePrimitiveArray(Object ob, XmlTextWriter el) { // Element el = new Element(ARRAY); /*el.WriteStartElement(OBJECT); el.WriteAttributeString(TYPE, ob.GetType().ToString()); el.WriteAttributeString(ID, map[ob].ToString());*/ //el.WriteStartElement(ARRAY); el.WriteStartElement(OBJECT); el.WriteAttributeString(TYPE, ARRAY); //el.setAttribute(TYPE, ob.getClass().getComponentType().getName()); //it gets the correct WOX type from the map, in case there is one //for example for int[][].class it will get int[][] //String woxType = (String)mapJavaToWOX.get(ob.getClass().getComponentType()); String woxType = (String)mapCSharpToWOX[ob.GetType().GetElementType().ToString()]; //el.setAttribute(TYPE, woxType); el.WriteAttributeString(ELEMENT_TYPE, woxType); //Console.Out.WriteLine("primitive array: " + woxType); //we need to get the lenght of the array, so, we cast it to an Array Array obArray = (Array)ob; int len = obArray.GetLength(0); //Console.Out.WriteLine("array length: " + len); //CJ this should not be here beacsue the lenght for the byte[] can be different //el.setAttribute(LENGTH, "" + len); if ((obArray is System.SByte[])) { //it is a Byte[] array //Console.Out.WriteLine("it is a SByte[] array"); /*if (ob instanceof Byte[]) { System.out.println("Byte[] array"); Byte[] arrayWrapperByte = (Byte[])ob; byte[] arrayPrimitiveByte = new byte[arrayWrapperByte.length]; for(int k=0; k<arrayWrapperByte.length; k++){ arrayPrimitiveByte[k] = arrayWrapperByte[k].byteValue(); } el.setText(byteArrayString(arrayPrimitiveByte, el)); } //it is a byte[] array else{ System.out.println("byte[] array"); el.setText(byteArrayString((byte[]) ob, el)); }*/ } else { //el.setAttribute(LENGTH, "" + len); //el.setText(arrayString(ob, len)); el.WriteAttributeString(LENGTH, "" + len); el.WriteAttributeString(ID, map[ob].ToString()); el.WriteString(arrayString(obArray, len)); el.WriteEndElement(); } //return el;*/ } //method modified to include base64 encoding /*public String byteArrayString(byte[] a, Element e) { byte[] target = EncodeBase64.encode(a); //set the lenght fro the new encoded array e.setAttribute(LENGTH, "" + target.length); String strTarget = new String(target); return strTarget; }*/ public String arrayString(Array obArray, int len) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) { if (i > 0) { sb.Append(" "); } //if it is an array of Class objects if (obArray is Type[]) { //we have to handle null values for arrays of Class objects Type arrayElement = (Type)obArray.GetValue(i); if (arrayElement != null) { //get the correct WOX type if it exists String woxType = (String)mapCSharpToWOX[arrayElement.ToString()]; if (woxType != null) { sb.Append(woxType); } else { //get the correct WOX array type if it exists woxType = (String)mapArrayCSharpToWOX[arrayElement.ToString()]; if (woxType != null) { sb.Append(woxType); } else { sb.Append(arrayElement.ToString()); } } } else { sb.Append("null"); } } //if it is an array of char, we must get its unicode representation (June 2007) else if (obArray is System.Char[]) { //we have to handle null values for arrays of Character //this is not necessary for arrays of primitive char because null values do not exist! Object arrayElement = obArray.GetValue(i); if (arrayElement != null) { Char myChar = (Char)obArray.GetValue(i); sb.Append(getUnicodeValue(myChar)); } else { sb.Append("null"); } } //if it is an array of boolean, we must convert "True" and "False" to lowercase else if (obArray is System.Boolean[]) { //we have to handle null values for arrays of Boolean //this is not necessary for arrays of primitive boolean because null values do not exist! Object arrayElement = obArray.GetValue(i); String booleanValue = ""; if (arrayElement != null) { Boolean myBool = (Boolean)obArray.GetValue(i); if (myBool.ToString().Equals("True")) { booleanValue = "true"; } else if (myBool.ToString().Equals("False")) { booleanValue = "false"; } sb.Append(booleanValue); } else { sb.Append("null"); } } //for the rest of data types, we just append the values as string //it also includes wrapper data types: Integer, Short, Boolean, etc. else { //we have to handle null values for arrays of wrappers and arrays of Class objects //this is not necessary for arrays of primitives because null values do not exist! //Object arrayElement = Array.get(ob, i); Object arrayElement = obArray.GetValue(i); if (arrayElement != null) { sb.Append(arrayElement.ToString()); } else { sb.Append("null"); } } } return sb.ToString(); } public void writeFields(Object o, XmlTextWriter parent) { // get the class of the object // get its fields // then get the value of each one // and call write to put the value in the Element Type cl = o.GetType(); FieldInfo[] fields = getFields(cl); String name = null; for (int i = 0; i < fields.Length; i++) { /*if ((doStatic || !Modifier.isStatic(fields[i].getModifiers())) && (doFinal || !Modifier.isFinal(fields[i].getModifiers())))*/ try { //fields[i].setAccessible(true); name = fields[i].Name; //Console.Out.WriteLine("name: " + name); //Console.Out.WriteLine("name: " + fields[i].Name + ", type: " + fields[i].FieldType + " ,value: " + fields[i].GetValue(person)); // need to handle shadowed fields in some way... // one way is to add info about the declaring class // but this will bloat the XML file if we di it for // every field - might be better to just do it for // the shadowed fields // name += "." + fields[i].getDeclaringClass().getName(); // fields[i]. //Object value = fields[i].get(o); //Console.Out.WriteLine("step 1"); Object value = fields[i].GetValue(o); //Console.Out.WriteLine("step 2"); //Element field = new Element(FIELD); parent.WriteStartElement(FIELD); //Console.Out.WriteLine("step 3"); //field.setAttribute(NAME, name); parent.WriteAttributeString(NAME, name); /*if (shadowed(fields, name)) { field.setAttribute(DECLARED, fields[i].getDeclaringClass().getName()); }*/ //if the field is a primitive data type (int, float, char, etc.) if (mapCSharpToWOX.ContainsKey(fields[i].FieldType.ToString())) { //Console.Out.WriteLine("it is a primitive: " + fields[i].FieldType); // this is not always necessary - so it's optional if (writePrimitiveTypes) { //field.setAttribute(TYPE, fields[i].getType().getName()); parent.WriteAttributeString(TYPE, (string)mapCSharpToWOX[fields[i].FieldType.ToString()]); } //if it is a char primitive, then we must store its unicode value (June 2007) if (fields[i].FieldType.ToString().Equals("System.Char")) { //System.out.println("IT IS A CHAR..."); Char myChar = (Char)value; String unicodeValue = getUnicodeValue(myChar); parent.WriteAttributeString(VALUE, unicodeValue); parent.WriteEndElement(); //parent.WriteEndElement(); //field.setAttribute(VALUE, unicodeValue); } //if it is a boolean primitive, "False" and "True" must be in lowercase else if (fields[i].FieldType.ToString().Equals("System.Boolean")) { String booleanValue = ""; if (value == null) { booleanValue = ""; } if (value.ToString().Equals("True")) { booleanValue = "true"; } else if (value.ToString().Equals("False")) { booleanValue = "false"; } parent.WriteAttributeString(VALUE, booleanValue); parent.WriteEndElement(); } //for the rest of the primitives, we store their values as string else { //field.setAttribute(VALUE, value.toString()); if (value == null) { value = ""; } parent.WriteAttributeString(VALUE, value.ToString()); parent.WriteEndElement(); } } //if the field is NOT a primitive data type (e.g. it is an object) else { //field.addContent(write(value)); write(value, parent); parent.WriteEndElement(); } //no -> parent.addContent(field); } catch (Exception e) { //Console.Out.WriteLine("error: " + e.Message); //e.printStackTrace(); //System.out.println(e); // at least comment on what went wrong //parent.addContent(new Comment(e.toString())); } } } private static String getUnicodeValue(char character) { int asciiValue = (int)character; //int asciiValue = Char. (int)character.charValue(); String hexValue = IntToHex(asciiValue); //String hexValue = Integer.toHexString(asciiValue); String unicodeValue = "\\u" + fillWithZeros(hexValue); //System.out.println("ASCII: " + asciiValue + ", HEX: " + hexValue + ", UNICODE: " + unicodeValue); return unicodeValue; } private static String fillWithZeros(String hexValue) { int len = hexValue.Length; switch (len) { case 1: return ("000" + hexValue); case 2: return ("00" + hexValue); case 3: return ("0" + hexValue); default: return hexValue; } } //to convert an int value to hexadecimal private static string IntToHex(int number) { return String.Format("{0:x}", number); } //to convert an hexadecimal value to int private static int HexToInt(string hexString) { return int.Parse(hexString, System.Globalization.NumberStyles.HexNumber, null); } public static String stringify(Object ob) { //if it is a Class, we only get the class name if (ob is Type) { //we cast it, so we are able to get its fully qualified name Type obType = (Type)ob; //Console.Out.WriteLine("it is a Type..."); //Console.Out.WriteLine("obType.ToString(): " + obType.ToString()); //Console.Out.WriteLine("obType.Name: " + obType.Name); //get the correct WOX type if it exists //String woxType = (String)mapJavaToWOX.get((Class)ob); //String woxType = (String)mapCSharpToWOX[ob.GetType().ToString()]; String woxType = (String)mapCSharpToWOX[obType.ToString()]; if (woxType != null) { return woxType; } else { //return ((Class) ob).getName(); //return ob.GetType().ToString(); return obType.ToString(); } } // if it is a Character we must get the unicode representation else if (ob is Char) { //Console.Out.WriteLine("object is char..."); return (getUnicodeValue((Char)ob)); } else if (ob is Boolean) { //Console.Out.WriteLine("object is bool..."); if (ob.ToString().Equals("True")) { return "true"; } else { return "false"; } } //if is is any of the other wrapper classes else { return ob.ToString(); } } public static FieldInfo[] getFields(Type c) { ArrayList v = new ArrayList(); while (!(c == null)) { // c.equals( Object.class ) ) { FieldInfo[] fields = c.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); for (int i = 0; i < fields.Length; i++) { //Console.Out.WriteLine("fields[" + i + "]: " + fields[i]); v.Add(fields[i]); } c = null; //c = c.getSuperclass(); } FieldInfo[] f = new FieldInfo[v.Count]; for (int i = 0; i < f.Length; i++) { f[i] = (FieldInfo)v[i]; } return f; /*Vector v = new Vector(); while (!(c == null)) { // c.equals( Object.class ) ) { Field[] fields = c.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { // System.out.println(fields[i]); v.addElement(fields[i]); } c = c.getSuperclass(); } Field[] f = new Field[v.size()]; for (int i = 0; i < f.length; i++) { f[i] = (Field)v.get(i); } return f;*/ } public bool isPrimitiveArray(String c) { for (int i = 0; i < primitiveArrays.Length; i++) { if (c.Equals(primitiveArrays[i])) { return true; } } return false; } } }
using System; using System.Drawing; using System.Collections; using System.Text; using System.ComponentModel; using System.Windows.Forms; using Zeus; using Zeus.Configuration; using Zeus.Projects; using Zeus.ErrorHandling; using Zeus.UserInterface; using Zeus.UserInterface.WinForms; namespace MyGeneration { /// <summary> /// Summary description for AddEditSavedObject. /// </summary> public class FormAddEditSavedObject : System.Windows.Forms.Form { private System.Windows.Forms.Button buttonOK; private System.Windows.Forms.Button buttonCancel; private SavedTemplateInput _savedObject; private ZeusModule _module = null; private ArrayList _extensions = new ArrayList(); private bool _isActivated = false; private bool _collectInChildProcess = false; private bool _insideRecording = false; private ZeusProcessStatusDelegate _executionCallback; private StringBuilder _collectedInput = new StringBuilder(); private System.Windows.Forms.Button buttonCollectInput; private System.Windows.Forms.Label labelName; private System.Windows.Forms.TextBox textBoxName; private System.Windows.Forms.Button buttonViewData; private FormViewSavedInput formViewSavedInput = new FormViewSavedInput(); private System.Windows.Forms.ErrorProvider errorProviderRequiredFields; private TreeNode _lastRecordedSelectedNode = null; private string _lastRecordedSelectedId = string.Empty; private System.Windows.Forms.Button buttonClearInput; private System.Windows.Forms.TreeView treeViewTemplates; private TemplateTreeBuilder treeBuilder = null; private System.Windows.Forms.Label labelTemplate; private IMyGenerationMDI mdi; private IContainer components; //public FormAddEditSavedObject(IMyGenerationMDI mdi) public FormAddEditSavedObject(bool collectInChildProcess) { InitializeComponent(); treeBuilder = new TemplateTreeBuilder(this.treeViewTemplates); _extensions.Add(".zeus"); _extensions.Add(".jgen"); _extensions.Add(".vbgen"); _extensions.Add(".csgen"); _executionCallback = new ZeusProcessStatusDelegate(ExecutionCallback); _collectInChildProcess = collectInChildProcess; } /// <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.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormAddEditSavedObject)); this.buttonCollectInput = new System.Windows.Forms.Button(); this.labelName = new System.Windows.Forms.Label(); this.buttonOK = new System.Windows.Forms.Button(); this.buttonCancel = new System.Windows.Forms.Button(); this.textBoxName = new System.Windows.Forms.TextBox(); this.buttonViewData = new System.Windows.Forms.Button(); this.errorProviderRequiredFields = new System.Windows.Forms.ErrorProvider(this.components); this.buttonClearInput = new System.Windows.Forms.Button(); this.treeViewTemplates = new System.Windows.Forms.TreeView(); this.labelTemplate = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.errorProviderRequiredFields)).BeginInit(); this.SuspendLayout(); // // buttonCollectInput // this.buttonCollectInput.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.buttonCollectInput.Location = new System.Drawing.Point(16, 431); this.buttonCollectInput.Name = "buttonCollectInput"; this.buttonCollectInput.Size = new System.Drawing.Size(136, 24); this.buttonCollectInput.TabIndex = 0; this.buttonCollectInput.Text = "Record Template Input"; this.buttonCollectInput.Click += new System.EventHandler(this.buttonCollectInput_Click); // // labelName // this.labelName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.labelName.Location = new System.Drawing.Point(16, 8); this.labelName.Name = "labelName"; this.labelName.Size = new System.Drawing.Size(564, 23); this.labelName.TabIndex = 1; this.labelName.Text = "Name:"; this.labelName.TextAlign = System.Drawing.ContentAlignment.BottomLeft; // // buttonOK // this.buttonOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonOK.Location = new System.Drawing.Point(456, 431); this.buttonOK.Name = "buttonOK"; this.buttonOK.Size = new System.Drawing.Size(56, 23); this.buttonOK.TabIndex = 3; this.buttonOK.Text = "OK"; this.buttonOK.Click += new System.EventHandler(this.buttonOK_Click); // // buttonCancel // this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonCancel.CausesValidation = false; this.buttonCancel.Location = new System.Drawing.Point(520, 431); this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.Size = new System.Drawing.Size(56, 23); this.buttonCancel.TabIndex = 4; this.buttonCancel.Text = "Cancel"; this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click); // // textBoxName // this.textBoxName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBoxName.Location = new System.Drawing.Point(16, 32); this.textBoxName.Name = "textBoxName"; this.textBoxName.Size = new System.Drawing.Size(560, 20); this.textBoxName.TabIndex = 5; this.textBoxName.Validating += new System.ComponentModel.CancelEventHandler(this.textBoxName_Validating); // // buttonViewData // this.buttonViewData.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.buttonViewData.Location = new System.Drawing.Point(304, 431); this.buttonViewData.Name = "buttonViewData"; this.buttonViewData.Size = new System.Drawing.Size(72, 23); this.buttonViewData.TabIndex = 6; this.buttonViewData.Text = "View Data"; this.buttonViewData.Click += new System.EventHandler(this.buttonViewData_Click); // // errorProviderRequiredFields // this.errorProviderRequiredFields.ContainerControl = this; // // buttonClearInput // this.buttonClearInput.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.buttonClearInput.Location = new System.Drawing.Point(160, 431); this.buttonClearInput.Name = "buttonClearInput"; this.buttonClearInput.Size = new System.Drawing.Size(136, 24); this.buttonClearInput.TabIndex = 7; this.buttonClearInput.Text = "Clear Template Input"; this.buttonClearInput.Click += new System.EventHandler(this.buttonClearInput_Click); // // treeViewTemplates // this.treeViewTemplates.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.treeViewTemplates.Location = new System.Drawing.Point(16, 72); this.treeViewTemplates.Name = "treeViewTemplates"; this.treeViewTemplates.Size = new System.Drawing.Size(560, 344); this.treeViewTemplates.TabIndex = 8; this.treeViewTemplates.Validating += new System.ComponentModel.CancelEventHandler(this.treeViewTemplates_Validating); this.treeViewTemplates.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeViewTemplates_AfterSelect); // // labelTemplate // this.labelTemplate.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.labelTemplate.Location = new System.Drawing.Point(16, 56); this.labelTemplate.Name = "labelTemplate"; this.labelTemplate.Size = new System.Drawing.Size(564, 16); this.labelTemplate.TabIndex = 10; this.labelTemplate.Text = "Template:"; this.labelTemplate.TextAlign = System.Drawing.ContentAlignment.BottomLeft; // // FormAddEditSavedObject // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(600, 461); this.Controls.Add(this.labelTemplate); this.Controls.Add(this.treeViewTemplates); this.Controls.Add(this.buttonClearInput); this.Controls.Add(this.buttonViewData); this.Controls.Add(this.textBoxName); this.Controls.Add(this.buttonCancel); this.Controls.Add(this.buttonOK); this.Controls.Add(this.labelName); this.Controls.Add(this.buttonCollectInput); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "FormAddEditSavedObject"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "AddEditSavedObject"; this.Load += new System.EventHandler(this.FormAddEditSavedObject_Load); this.Activated += new System.EventHandler(this.FormAddEditSavedObject_Activated); ((System.ComponentModel.ISupportInitialize)(this.errorProviderRequiredFields)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion public ZeusModule Module { get { return _module; } set { _module = value; } } public SavedTemplateInput SavedObject { get { return _savedObject; } set { _savedObject = value; if(_savedObject.SavedObjectName != null) { this.textBoxName.Text = _savedObject.SavedObjectName; this.Text = "Template Instance: " + _savedObject.SavedObjectName; } else { this.textBoxName.Text = string.Empty; this.Text = "Template Instance: [New] "; } LoadTemplates(_savedObject.TemplateUniqueID); this._lastRecordedSelectedNode = this.treeViewTemplates.SelectedNode; this._isActivated = false; this._insideRecording = false; } } private TemplateTreeNode SelectedTemplate { get { if (this.treeViewTemplates.SelectedNode != null) return this.treeViewTemplates.SelectedNode as TemplateTreeNode; else return null; } } private void buttonOK_Click(object sender, System.EventArgs e) { CancelEventArgs args = new CancelEventArgs(); this.textBoxName_Validating(this, args); this.treeViewTemplates_Validating(this, args); if (!args.Cancel) { if ((this.SavedObject.InputItems.Count > 0) || (MessageBox.Show("Are you sure you want to save without any recorded input?", "Warning: No Recorded Template Input", MessageBoxButtons.YesNo) == DialogResult.Yes) ) { if (SavedObject.SavedObjectName != null) { this.Module.SavedObjects.Remove(SavedObject.SavedObjectName); } this.SavedObject.SavedObjectName = this.textBoxName.Text; TemplateTreeNode item = this.SelectedTemplate; if (item != null) { this.SavedObject.TemplatePath = item.Tag.ToString(); this.SavedObject.TemplateUniqueID = item.UniqueId; } this.Module.SavedObjects[SavedObject.SavedObjectName] = SavedObject; this.DialogResult = DialogResult.OK; this.Close(); } } } private void buttonCancel_Click(object sender, System.EventArgs e) { this.Close(); } public TemplateTreeNode FindNodeByID(string id, TreeNode parentNode, bool returnFirst) { TemplateTreeNode selectedNode = null; foreach (TreeNode node in parentNode.Nodes) { if (node is TemplateTreeNode) { selectedNode = node as TemplateTreeNode; if (returnFirst) return selectedNode; if (selectedNode.UniqueId.ToLower() != id) { selectedNode = null; } else { return selectedNode; } } selectedNode = FindNodeByID(id, node, returnFirst); if (selectedNode != null) { return selectedNode; } } return selectedNode; } public void LoadTemplates(string selectedid) { treeViewTemplates.Nodes.Clear(); treeViewTemplates.HideSelection = false; treeBuilder = new TemplateTreeBuilder(treeViewTemplates); treeBuilder.LoadTemplates(); TemplateTreeNode selectedNode = null; string id = selectedid; if (id != null) id = id.ToLower(); selectedNode = FindNodeByID(id, treeViewTemplates.Nodes[0], false); if (selectedNode == null) { selectedNode = FindNodeByID(_lastRecordedSelectedId, treeViewTemplates.Nodes[0], false); if (selectedNode == null) { selectedNode = FindNodeByID(id, treeViewTemplates.Nodes[0], true); } } if (selectedNode != null) { _lastRecordedSelectedId = selectedNode.UniqueId.ToLower(); this.treeViewTemplates.SelectedNode = selectedNode; TreeNode parent = selectedNode.Parent; while (parent != null) { parent.Expand(); parent = parent.Parent; } } } private void SaveInput() { try { if (_collectInChildProcess) { this.buttonCollectInput.Enabled = false; this.Cursor = Cursors.WaitCursor; ZeusProcessManager.RecordProjectItem(this._module.RootProject.FilePath, _module.ProjectPath + "/" + SavedObject.SavedObjectName, this.SelectedTemplate.Tag.ToString(), _executionCallback); } else { //RecordProjectItem ZeusTemplate template = new ZeusTemplate(this.SelectedTemplate.Tag.ToString()); DefaultSettings settings = DefaultSettings.Instance; ZeusSimpleLog log = new ZeusSimpleLog(); ZeusContext context = new ZeusContext(); context.Log = log; SavedObject.TemplateUniqueID = template.UniqueID; SavedObject.TemplatePath = template.FilePath + template.FileName; settings.PopulateZeusContext(context); if (_module != null) { _module.PopulateZeusContext(context); _module.OverrideSavedData(SavedObject.InputItems); } if (template.Collect(context, settings.ScriptTimeout, SavedObject.InputItems)) { this._lastRecordedSelectedNode = this.SelectedTemplate; } if (log.HasExceptions) { throw log.Exceptions[0]; } } } catch (Exception ex) { mdi.ErrorsOccurred(ex); //ZeusDisplayError formError = new ZeusDisplayError(ex); //formError.SetControlsFromException(); //formError.ShowDialog(this); } Cursor.Current = Cursors.Default; } private void ExecutionCallback(ZeusProcessStatusEventArgs args) { if (args.Message != null) { if (this.InvokeRequired) { this.Invoke(_executionCallback, args); } else { /*if (_consoleWriteGeneratedDetails) { if (this._mdi.Console.DockContent.IsHidden) this._mdi.Console.DockContent.Show(_mdi.DockPanel); if (!this._mdi.Console.DockContent.IsActivated) this._mdi.Console.DockContent.Activate(); }*/ if (args.Message.StartsWith(ZeusProcessManagerTags.BEGIN_RECORDING_TAG)) { _collectedInput = new StringBuilder(); _insideRecording = true; } else if (args.Message.StartsWith(ZeusProcessManagerTags.END_RECORDING_TAG)) { this._savedObject.XML = _collectedInput.ToString(); _insideRecording = false; } else if (_insideRecording) { _collectedInput.AppendLine(args.Message); } if (!args.IsRunning) { this.Cursor = Cursors.Default; this.buttonCollectInput.Enabled = true; } } } } private void ClearInput() { if (MessageBox.Show(this, "Are you sure you want to clear the template's input collection?", "Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { SavedObject.InputItems.Clear(); } } public void DynamicGUI_Display(IZeusGuiControl gui, IZeusFunctionExecutioner executioner) { this.Cursor = Cursors.Default; try { DynamicForm df = new DynamicForm(gui as GuiController, executioner); DialogResult result = df.ShowDialog(this); if(result == DialogResult.Cancel) { gui.IsCanceled = true; } } catch (Exception ex) { mdi.ErrorsOccurred(ex); //ZeusDisplayError formError = new ZeusDisplayError(ex); //formError.SetControlsFromException(); //formError.ShowDialog(this); } Cursor.Current = Cursors.Default; } private void buttonCollectInput_Click(object sender, System.EventArgs e) { this.SaveInput(); } private void buttonClearInput_Click(object sender, System.EventArgs e) { this.ClearInput(); } private void listBoxTemplates_DoubleClick(object sender, System.EventArgs e) { this.SaveInput(); } private void buttonViewData_Click(object sender, System.EventArgs e) { formViewSavedInput.SavedObject = this.SavedObject; formViewSavedInput.ShowDialog(); } private void textBoxName_Validating(object sender, System.ComponentModel.CancelEventArgs e) { string x = this.SavedObject.SavedObjectName; if (x == null) x = string.Empty; if (textBoxName.Text.Trim().Length == 0) { e.Cancel = true; this.errorProviderRequiredFields.SetError(this.textBoxName, "Name is Required!"); } else if (this.Module.SavedObjects.Contains(this.textBoxName.Text) && (x.Trim() != this.textBoxName.Text.Trim())) { e.Cancel = true; this.errorProviderRequiredFields.SetError(this.textBoxName, "This name has already been difined in this folder"); } else { this.errorProviderRequiredFields.SetError(this.textBoxName, string.Empty); } } private void treeViewTemplates_Validating(object sender, System.ComponentModel.CancelEventArgs e) { if (this.SelectedTemplate == null) { e.Cancel = true; this.errorProviderRequiredFields.SetError(this.treeViewTemplates, "Template selection is Required!"); } else { this.errorProviderRequiredFields.SetError(this.treeViewTemplates, string.Empty); } } private void FormAddEditSavedObject_Load(object sender, System.EventArgs e) { this.errorProviderRequiredFields.SetError(this.textBoxName, string.Empty); this.errorProviderRequiredFields.SetIconAlignment(this.textBoxName, ErrorIconAlignment.TopRight); this.errorProviderRequiredFields.SetError(this.treeViewTemplates, string.Empty); this.errorProviderRequiredFields.SetIconAlignment(this.treeViewTemplates, ErrorIconAlignment.TopRight); this.textBoxName.Focus(); } private void FormAddEditSavedObject_Activated(object sender, System.EventArgs e) { if (!this._isActivated) { this.textBoxName.Focus(); this._isActivated = true; } } private void treeViewTemplates_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e) { if (this.SelectedTemplate != null) { _lastRecordedSelectedId = SelectedTemplate.UniqueId.ToLower(); } } } }
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 ys.samples.webapi.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; } } }
// // https://github.com/ServiceStack/ServiceStack.Text // ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers. // // Authors: // Demis Bellot ([email protected]) // // Copyright 2012 ServiceStack Ltd. // // Licensed under the same terms of ServiceStack: new BSD license. // using System; using System.Linq; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; using System.Threading; using ServiceStack.Text.Json; namespace ServiceStack.Text.Common { internal static class DeserializeListWithElements<TSerializer> where TSerializer : ITypeSerializer { internal static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer<TSerializer>(); private static Dictionary<Type, ParseListDelegate> ParseDelegateCache = new Dictionary<Type, ParseListDelegate>(); private delegate object ParseListDelegate(string value, Type createListType, ParseStringDelegate parseFn); public static Func<string, Type, ParseStringDelegate, object> GetListTypeParseFn( Type createListType, Type elementType, ParseStringDelegate parseFn) { ParseListDelegate parseDelegate; if (ParseDelegateCache.TryGetValue(elementType, out parseDelegate)) return parseDelegate.Invoke; var genericType = typeof(DeserializeListWithElements<,>).MakeGenericType(elementType, typeof(TSerializer)); #if NETFX_CORE var mi = genericType.GetRuntimeMethods().First(p => p.Name.Equals("ParseGenericList")); parseDelegate = (ParseListDelegate)mi.CreateDelegate(typeof(ParseListDelegate)); #else var mi = genericType.GetMethod("ParseGenericList", BindingFlags.Static | BindingFlags.Public); parseDelegate = (ParseListDelegate)Delegate.CreateDelegate(typeof(ParseListDelegate), mi); #endif Dictionary<Type, ParseListDelegate> snapshot, newCache; do { snapshot = ParseDelegateCache; newCache = new Dictionary<Type, ParseListDelegate>(ParseDelegateCache); newCache[elementType] = parseDelegate; } while (!ReferenceEquals( Interlocked.CompareExchange(ref ParseDelegateCache, newCache, snapshot), snapshot)); return parseDelegate.Invoke; } internal static string StripList(string value) { if (string.IsNullOrEmpty(value)) return null; const int startQuotePos = 1; const int endQuotePos = 2; var ret = value[0] == JsWriter.ListStartChar ? value.Substring(startQuotePos, value.Length - endQuotePos) : value; var pos = 0; Serializer.EatWhitespace(ret, ref pos); return ret.Substring(pos, ret.Length - pos); } public static List<string> ParseStringList(string value) { if ((value = StripList(value)) == null) return null; if (value == string.Empty) return new List<string>(); var to = new List<string>(); var valueLength = value.Length; var i = 0; while (i < valueLength) { var elementValue = Serializer.EatValue(value, ref i); var listValue = Serializer.UnescapeString(elementValue); to.Add(listValue); if (Serializer.EatItemSeperatorOrMapEndChar(value, ref i) && i == valueLength) { // If we ate a separator and we are at the end of the value, // it means the last element is empty => add default to.Add(null); } } return to; } public static List<int> ParseIntList(string value) { if ((value = StripList(value)) == null) return null; if (value == string.Empty) return new List<int>(); var intParts = value.Split(JsWriter.ItemSeperator); var intValues = new List<int>(intParts.Length); foreach (var intPart in intParts) { intValues.Add(int.Parse(intPart)); } return intValues; } } internal static class DeserializeListWithElements<T, TSerializer> where TSerializer : ITypeSerializer { private static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer<TSerializer>(); public static ICollection<T> ParseGenericList(string value, Type createListType, ParseStringDelegate parseFn) { if ((value = DeserializeListWithElements<TSerializer>.StripList(value)) == null) return null; var isReadOnly = createListType != null #if NETFX_CORE && (createListType.GetTypeInfo().IsGenericType && createListType.GetTypeInfo().GetGenericTypeDefinition() == typeof(ReadOnlyCollection<>)); #else && (createListType.IsGenericType && createListType.GetGenericTypeDefinition() == typeof(ReadOnlyCollection<>)); #endif var to = (createListType == null || isReadOnly) ? new List<T>() : (ICollection<T>)createListType.CreateInstance(); if (value == string.Empty) return to; var tryToParseItemsAsPrimitiveTypes = JsConfig.TryToParsePrimitiveTypeValues && typeof(T) == typeof(object); if (!string.IsNullOrEmpty(value)) { var valueLength = value.Length; var i = 0; Serializer.EatWhitespace(value, ref i); if (i < valueLength && value[i] == JsWriter.MapStartChar) { do { var itemValue = Serializer.EatTypeValue(value, ref i); to.Add((T)parseFn(itemValue)); Serializer.EatWhitespace(value, ref i); } while (++i < value.Length); } else { while (i < valueLength) { var startIndex = i; var elementValue = Serializer.EatValue(value, ref i); var listValue = elementValue; if (listValue != null) { if (tryToParseItemsAsPrimitiveTypes) { Serializer.EatWhitespace(value, ref startIndex); to.Add((T)DeserializeType<TSerializer>.ParsePrimitive(elementValue, value[startIndex])); } else { to.Add((T)parseFn(elementValue)); } } if (Serializer.EatItemSeperatorOrMapEndChar(value, ref i) && i == valueLength) { // If we ate a separator and we are at the end of the value, // it means the last element is empty => add default to.Add(default(T)); } } } } //TODO: 8-10-2011 -- this CreateInstance call should probably be moved over to ReflectionExtensions, //but not sure how you'd like to go about caching constructors with parameters -- I would probably build a NewExpression, .Compile to a LambdaExpression and cache return isReadOnly ? (ICollection<T>)Activator.CreateInstance(createListType, to) : to; } } internal static class DeserializeList<T, TSerializer> where TSerializer : ITypeSerializer { private readonly static ParseStringDelegate CacheFn; static DeserializeList() { CacheFn = GetParseFn(); } public static ParseStringDelegate Parse { get { return CacheFn; } } public static ParseStringDelegate GetParseFn() { var listInterface = typeof(T).GetTypeWithGenericInterfaceOf(typeof(IList<>)); if (listInterface == null) throw new ArgumentException(string.Format("Type {0} is not of type IList<>", typeof(T).FullName)); //optimized access for regularly used types if (typeof(T) == typeof(List<string>)) return DeserializeListWithElements<TSerializer>.ParseStringList; if (typeof(T) == typeof(List<int>)) return DeserializeListWithElements<TSerializer>.ParseIntList; #if NETFX_CORE var elementType = listInterface.GenericTypeArguments[0]; #else var elementType = listInterface.GetGenericArguments()[0]; #endif var supportedTypeParseMethod = DeserializeListWithElements<TSerializer>.Serializer.GetParseFn(elementType); if (supportedTypeParseMethod != null) { var createListType = typeof(T).HasAnyTypeDefinitionsOf(typeof(List<>), typeof(IList<>)) ? null : typeof(T); var parseFn = DeserializeListWithElements<TSerializer>.GetListTypeParseFn(createListType, elementType, supportedTypeParseMethod); return value => parseFn(value, createListType, supportedTypeParseMethod); } return null; } } internal static class DeserializeEnumerable<T, TSerializer> where TSerializer : ITypeSerializer { private readonly static ParseStringDelegate CacheFn; static DeserializeEnumerable() { CacheFn = GetParseFn(); } public static ParseStringDelegate Parse { get { return CacheFn; } } public static ParseStringDelegate GetParseFn() { var enumerableInterface = typeof(T).GetTypeWithGenericInterfaceOf(typeof(IEnumerable<>)); if (enumerableInterface == null) throw new ArgumentException(string.Format("Type {0} is not of type IEnumerable<>", typeof(T).FullName)); //optimized access for regularly used types if (typeof(T) == typeof(IEnumerable<string>)) return DeserializeListWithElements<TSerializer>.ParseStringList; if (typeof(T) == typeof(IEnumerable<int>)) return DeserializeListWithElements<TSerializer>.ParseIntList; #if NETFX_CORE var elementType = enumerableInterface.GenericTypeArguments[0]; #else var elementType = enumerableInterface.GetGenericArguments()[0]; #endif var supportedTypeParseMethod = DeserializeListWithElements<TSerializer>.Serializer.GetParseFn(elementType); if (supportedTypeParseMethod != null) { const Type createListTypeWithNull = null; //Use conversions outside this class. see: Queue var parseFn = DeserializeListWithElements<TSerializer>.GetListTypeParseFn( createListTypeWithNull, elementType, supportedTypeParseMethod); return value => parseFn(value, createListTypeWithNull, supportedTypeParseMethod); } return null; } } }
#region License //----------------------------------------------------------------------- // <copyright> // The MIT License (MIT) // // Copyright (c) 2014 Kirk S Woll // // 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> //----------------------------------------------------------------------- #endregion using System.Runtime.WootzJs; using WootzJs.Testing; namespace WootzJs.Compiler.Tests { public class MethodTests : TestFixture { [Test] public void StaticMethod() { var s = ClassWithStaticMethods.S(); AssertEquals(s, "foo"); } [Test] public void ExtensionMethod() { var s = 5.MyExtension(); AssertEquals(s, "5"); } [Test] public void OutParameter() { string x; ClassWithStaticMethods.OutParameter(out x); AssertEquals(x, "foo"); } [Test] public void TwoOutParameters() { string x; string y; ClassWithStaticMethods.TwoOutParameters(out x, out y); AssertEquals(x, "foo1"); AssertEquals(y, "foo2"); } [Test] public void RefParameter() { int x = 5; ClassWithStaticMethods.RefParameter(ref x); AssertEquals(x, 6); } [Test] public void TwoRefParameters() { int x = 5; int y = 6; ClassWithStaticMethods.TwoRefParameters(ref x, ref y); AssertEquals(x, 6); AssertEquals(y, 12); } [Test] public void RefAndOutParameter() { int x = 5; int y; ClassWithStaticMethods.RefAndOutParameter(ref x, out y); AssertEquals(x, 6); AssertEquals(y, 10); } [Test] public void InterfaceMethod() { ITestInterface test = new TestImplementation(); var s = test.Method(); AssertEquals(s, "foo"); } [Test] public void CollisionImplementationBothExplicit() { var o = new CollisionImplementationBothExplicit(); ITestInterface test = o; ITestInterface2 test2 = o; var s = test.Method(); var s2 = test2.Method(); AssertEquals(s, "ITestInterface"); AssertEquals(s2, "ITestInterface2"); } [Test] public void CollisionImplementationOneExplicit() { var o = new CollisionImplementationOneExplicit(); ITestInterface test = o; ITestInterface2 test2 = o; var s = test.Method(); var s2 = test2.Method(); AssertEquals(s, "ITestInterface"); AssertEquals(s2, "ITestInterface2"); } [Test] public void ExternMethod() { var max = ExternTest.max(8, 3, 9, 5); AssertEquals(max, 9); } [Test] public void NamedArguments() { var result = ClassWithStaticMethods.Add(one: 1, two: 2, three: 3, four: 4); AssertEquals(result, 4321); result = ClassWithStaticMethods.Add(two: 1, three: 2, four: 3); AssertEquals(result, 3210); result = ClassWithStaticMethods.Add(four: 1, three: 2, two: 3, one: 4); AssertEquals(result, 1234); } } public static class ClassWithStaticMethods { public static int Add(int one = 0, int two = 0, int three = 0, int four = 0) { return one + two*10 + three*100+ four*1000; } public static string S() { return "foo"; } public static string MyExtension(this int i) { return i.ToString(); } public static void OutParameter(out string s) { s = "foo"; } public static void TwoOutParameters(out string s1, out string s2) { s1 = "foo1"; s2 = "foo2"; } public static void RefParameter(ref int i) { i = i + 1; } public static void TwoRefParameters(ref int i, ref int j) { i = i + 1; j = j * 2; } public static void RefAndOutParameter(ref int i, out int j) { i = i + 1; j = 10; } } public interface ITestInterface { string Method(); } public class TestImplementation : ITestInterface { public string Method() { return "foo"; } } public interface ITestInterface2 { string Method(); } public class CollisionImplementationBothExplicit : ITestInterface, ITestInterface2 { string ITestInterface.Method() { return "ITestInterface"; } string ITestInterface2.Method() { return "ITestInterface2"; } } public class CollisionImplementationOneExplicit : ITestInterface, ITestInterface2 { public string Method() { return "ITestInterface"; } string ITestInterface2.Method() { return "ITestInterface2"; } } [Js(Name = "Math", Export = false)] public class ExternTest { public static extern int max(params int[] ints); } }
#pragma warning disable 109, 114, 219, 429, 168, 162 namespace haxe.lang { public class StringExt { public StringExt() { unchecked { #line 26 "C:\\HaxeToolkit\\haxe\\std/cs/internal/StringExt.hx" { } } #line default } public static string charAt(string me, int index) { if ( ((uint) index) >= me.Length) return ""; else return new string(me[index], 1); } public static global::haxe.lang.Null<int> charCodeAt(string me, int index) { if ( ((uint) index) >= me.Length) return default(haxe.lang.Null<int>); else return new haxe.lang.Null<int>((int)me[index], true); } public static int indexOf(string me, string str, global::haxe.lang.Null<int> startIndex) { uint sIndex = (startIndex.hasValue) ? ((uint) startIndex.@value) : 0; if (sIndex >= me.Length) return -1; return me.IndexOf(str, (int)sIndex); } public static int lastIndexOf(string me, string str, global::haxe.lang.Null<int> startIndex) { int sIndex = (startIndex.hasValue) ? (startIndex.@value) : (me.Length - 1); if (sIndex >= me.Length) sIndex = me.Length - 1; else if (sIndex < 0) return -1; //TestBaseTypes.hx@133 fix if (startIndex.hasValue) { for(int i = sIndex; i >= 0; i--) { bool found = true; for(int j = 0; j < str.Length; j++) { if(me[i + j] != str[j]) { found = false; break; } } if (found) return i; } return -1; } else { return me.LastIndexOf(str, sIndex); } } public static global::Array<object> split(string me, string delimiter) { string[] native; if (delimiter.Length == 0) { int len = me.Length; native = new string[len]; for (int i = 0; i < len; i++) native[i] = new string(me[i], 1); } else { native = me.Split(new string[] { delimiter }, System.StringSplitOptions.None); } return new Array<object>(native); } public static string substr(string me, int pos, global::haxe.lang.Null<int> len) { int meLen = me.Length; int targetLen = meLen; if (len.hasValue) { targetLen = len.@value; if (targetLen == 0) return ""; if( pos != 0 && targetLen < 0 ){ return ""; } } if( pos < 0 ){ pos = meLen + pos; if( pos < 0 ) pos = 0; } else if( targetLen < 0 ){ targetLen = meLen + targetLen - pos; } if( pos + targetLen > meLen ){ targetLen = meLen - pos; } if ( pos < 0 || targetLen <= 0 ) return ""; return me.Substring(pos, targetLen); } public static string substring(string me, int startIndex, global::haxe.lang.Null<int> endIndex) { int endIdx; int len = me.Length; if ( !endIndex.hasValue ) { endIdx = len; } else if ( (endIdx = endIndex.@value) < 0 ) { endIdx = 0; } else if ( endIdx > len ) { endIdx = len; } if ( startIndex < 0 ) { startIndex = 0; } else if ( startIndex > len ) { startIndex = len; } if ( startIndex > endIdx ) { int tmp = startIndex; startIndex = endIdx; endIdx = tmp; } return me.Substring(startIndex, endIdx - startIndex); } public static string toLowerCase(string me) { return me.ToLower(); } public static string toUpperCase(string me) { return me.ToUpper(); } public static string toNativeString(string me) { unchecked { #line 197 "C:\\HaxeToolkit\\haxe\\std/cs/internal/StringExt.hx" return me; } #line default } public static string fromCharCode(int code) { return new string( (char) code, 1 ); } } } #pragma warning disable 109, 114, 219, 429, 168, 162 namespace haxe.lang { public class StringRefl { static StringRefl() { #line 211 "C:\\HaxeToolkit\\haxe\\std/cs/internal/StringExt.hx" global::haxe.lang.StringRefl.fields = new global::Array<object>(new object[]{"length", "toUpperCase", "toLowerCase", "charAt", "charCodeAt", "indexOf", "lastIndexOf", "split", "substr", "substring"}); } public StringRefl() { unchecked { #line 209 "C:\\HaxeToolkit\\haxe\\std/cs/internal/StringExt.hx" { } } #line default } public static global::Array<object> fields; public static object handleGetField(string str, string f, bool throwErrors) { unchecked { #line 215 "C:\\HaxeToolkit\\haxe\\std/cs/internal/StringExt.hx" switch (f) { case "length": { #line 217 "C:\\HaxeToolkit\\haxe\\std/cs/internal/StringExt.hx" return str.Length; } case "toUpperCase":case "toLowerCase":case "charAt":case "charCodeAt":case "indexOf":case "lastIndexOf":case "split":case "substr":case "substring": { #line 219 "C:\\HaxeToolkit\\haxe\\std/cs/internal/StringExt.hx" return new global::haxe.lang.Closure(((object) (str) ), global::haxe.lang.Runtime.toString(f), ((int) (0) )); } default: { #line 221 "C:\\HaxeToolkit\\haxe\\std/cs/internal/StringExt.hx" if (throwErrors) { throw global::haxe.lang.HaxeException.wrap(global::haxe.lang.Runtime.concat(global::haxe.lang.Runtime.concat("Field not found: \'", f), "\' in String")); } else { #line 224 "C:\\HaxeToolkit\\haxe\\std/cs/internal/StringExt.hx" return default(object); } } } } #line default } public static object handleCallField(string str, string f, global::Array args) { unchecked { #line 230 "C:\\HaxeToolkit\\haxe\\std/cs/internal/StringExt.hx" global::Array _args = new global::Array<object>(new object[]{str}); if (( args == default(global::Array) )) { args = _args; } else { #line 234 "C:\\HaxeToolkit\\haxe\\std/cs/internal/StringExt.hx" args = ((global::Array) (global::haxe.lang.Runtime.callField(_args, "concat", 1204816148, new global::Array<object>(new object[]{args}))) ); } #line 236 "C:\\HaxeToolkit\\haxe\\std/cs/internal/StringExt.hx" return global::haxe.lang.Runtime.slowCallField(typeof(global::haxe.lang.StringExt), f, args); } #line default } } }
//--------------------------------------------------------------------------- // // File: ITextView.cs // // Description: An interface representing the presentation of an ITextContainer. // // History: // 9/17/2004 : [....] - Created // //--------------------------------------------------------------------------- using System.ComponentModel; // AsyncCompletedEventArgs using System.Collections.ObjectModel; // ReadOnlyCollection using System.Windows.Media; // GlyphRun namespace System.Windows.Documents { /// <summary> /// The TextView class exposes presentation information for /// a TextContainer. Its methods reveal document structure, including /// line layout, hit testing, and character bounding boxes. /// /// Layouts that support TextView must implement the IServiceProvider /// interface, and support GetService(typeof(TextView)) method calls. /// </summary> internal interface ITextView { //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods /// <summary> /// Returns an ITextPointer that matches the supplied Point /// in this TextView. /// </summary> /// <param name="point"> /// Point in pixel coordinates to test. /// </param> /// <param name="snapToText"> /// If true, this method should return the closest position as /// calculated by the control's heuristics. /// If false, this method should return null position, if the test /// point does not fall within any character bounding box. /// </param> /// <returns> /// A text position and its orientation matching or closest to the point. /// </returns> /// <exception cref="System.InvalidOperationException"> /// Throws InvalidOperationException if IsValid is false. /// </exception> /// <remarks> /// If there is no position that matches the supplied point and /// snapToText is True, this method returns an ITextPointer /// that is closest to the Point. /// However, If snapToText is False, the method returns NULL if the /// supplied point does not fall within the bounding box of /// a character. /// </remarks> ITextPointer GetTextPositionFromPoint(Point point, bool snapToText); /// <summary> /// Retrieves the height and offset of the object or character /// represented by the given TextPointer. /// </summary> /// <param name="position"> /// Position of an object/character. /// </param> /// <returns> /// The height and offset of the object or character /// represented by the given TextPointer. /// </returns> /// <exception cref="System.InvalidOperationException"> /// Throws InvalidOperationException if IsValid is false. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Throws ArgumentOutOfRangeException if incoming position is not /// part of this TextView (should call Contains first to check). /// </exception> /// <exception cref="System.ArgumentNullException"> /// Throws ArgumentNullException if position is invalid. /// </exception> /// <exception cref="System.ComponentModel.InvalidEnumArgumentException"> /// Throws InvalidEnumArgumentException if an invalid enum value for /// direction is passed. /// </exception> /// <remarks> /// The Width of the returned rectangle is always 0. /// /// If the content at the specified position is empty, then this /// method will return the expected height of a character placed /// at the specified position. /// </remarks> Rect GetRectangleFromTextPosition(ITextPointer position); /// <summary> /// Retrieves the height and offset of the object or character /// represented by the given TextPointer. /// </summary> /// <param name="position"> /// Position of an object/character. /// </param> /// <param name="transform"> /// Transform to be applied to returned Rect /// </param> /// <returns> /// The height and offset of the object or character /// represented by the given TextPointer. /// </returns> /// <exception cref="System.InvalidOperationException"> /// Throws InvalidOperationException if IsValid is false. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Throws ArgumentOutOfRangeException if incoming position is not /// part of this TextView (should call Contains first to check). /// </exception> /// <exception cref="System.ArgumentNullException"> /// Throws ArgumentNullException if position is invalid. /// </exception> /// <exception cref="System.ComponentModel.InvalidEnumArgumentException"> /// Throws InvalidEnumArgumentException if an invalid enum value for /// direction is passed. /// </exception> /// <remarks> /// The Width of the returned rectangle is always 0. /// If the content at the specified position is empty, then this /// method will return the expected height of a character placed /// at the specified position. /// This rectangle returned is completely untransformed to any ancestors. /// The transform parameter contains the aggregate of transforms that must be /// applied to the rectangle. /// </remarks> Rect GetRawRectangleFromTextPosition(ITextPointer position, out Transform transform); /// <summary> /// Returns tight bounding geometry for the given text range. /// </summary> /// <param name="startPosition">Start position of the range.</param> /// <param name="endPosition">End position of the range.</param> /// <returns>Geometry object containing tight bound.</returns> Geometry GetTightBoundingGeometryFromTextPositions(ITextPointer startPosition, ITextPointer endPosition); /// <summary> /// Returns an ITextPointer matching the given position /// advanced by the given number of lines. /// </summary> /// <param name="position"> /// Initial text position of an object/character. /// </param> /// <param name="suggestedX"> /// The suggestedX parameter is the suggested X offset, in pixels, of /// the TextPointer on the destination line; the function returns the /// position whose offset is closest to suggestedX. /// </param> /// <param name="count"> /// Number of lines to advance. Negative means move backwards. /// </param> /// <param name="newSuggestedX"> /// newSuggestedX is the offset at the position moved (useful when moving /// between columns or pages). /// </param> /// <param name="linesMoved"> /// linesMoved indicates the number of lines moved, which may be less /// than count if there is no more content. /// </param> /// <returns> /// ITextPointer matching the given position advanced by the /// given number of lines. /// </returns> /// <exception cref="System.InvalidOperationException"> /// Throws InvalidOperationException if IsValid is false. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Throws ArgumentOutOfRangeException if incoming position is not /// part of this TextView (should call Contains first to check). /// </exception> /// <exception cref="System.ArgumentNullException"> /// Throws ArgumentNullException if position is invalid. /// </exception> /// <exception cref="System.ComponentModel.InvalidEnumArgumentException"> /// Throws InvalidEnumArgumentException if an invalid enum value for /// direction is passed. /// </exception> /// <remarks> /// The count parameter may be negative, which means move backwards. /// /// If count is larger than the number of available lines in that /// direction, then the returned position will be on the last line /// (or first line if count is negative). /// /// If suggestedX is Double.NaN, then it will be ignored. /// </remarks> ITextPointer GetPositionAtNextLine(ITextPointer position, double suggestedX, int count, out double newSuggestedX, out int linesMoved); /// <summary> /// ITextPointer GetPositionAtNextPage(ITextPointer position, Point suggestedOffset, int count, out Point newSuggestedOffset, out int pagesMoved); /// <summary> /// Determines if the given position is at the edge of a caret unit /// in the specified direction. /// </summary> /// <param name="position"> /// Position to test. /// </param> /// <returns> /// Returns true if the specified position precedes or follows /// the first or last code point of a caret unit, respectively. /// </returns> /// <exception cref="System.InvalidOperationException"> /// Throws InvalidOperationException if IsValid is false. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Throws ArgumentOutOfRangeException if incoming position is not /// part of this TextView (should call Contains first to check). /// </exception> /// <exception cref="System.ArgumentNullException"> /// Throws ArgumentNullException if position is invalid. /// </exception> /// <remarks> /// "Caret Unit" is a group of one or more Unicode code points that /// map to a single rendered glyph. /// </remarks> bool IsAtCaretUnitBoundary(ITextPointer position); /// <summary> /// Finds the next position at the edge of a caret unit in /// specified direction. /// </summary> /// <param name="position"> /// Initial text position of an object/character. /// </param> /// <param name="direction"> /// If Forward, this method returns the "caret unit" position following /// the initial position. /// If Backward, this method returns the caret unit" position preceding /// the initial position. /// </param> /// <returns> /// The next caret unit break position in specified direction. /// </returns> /// <exception cref="System.InvalidOperationException"> /// Throws InvalidOperationException if IsValid is false. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Throws ArgumentOutOfRangeException if incoming position is not /// part of this TextView (should call Contains first to check). /// </exception> /// <exception cref="System.ArgumentNullException"> /// Throws ArgumentNullException if position is invalid. /// </exception> /// <exception cref="System.ComponentModel.InvalidEnumArgumentException"> /// Throws InvalidEnumArgumentException if an invalid enum value for /// direction is passed. /// </exception> /// <remarks> /// "Caret Unit" is a group of one or more Unicode code points that /// map to a single rendered glyph. /// /// If the given position is located between two caret units, this /// method returns a new position located at the opposite edge of /// the caret unit in the indicated direction. /// If position is located within a group of Unicode code points that /// map to a single caret unit, this method returns a new position at /// the edge of the caret unit indicated by direction. /// If position is located at the beginning or end of content -- there /// is no content in the indicated direction -- then this method returns /// position at the same location as the given position. /// </remarks> ITextPointer GetNextCaretUnitPosition(ITextPointer position, LogicalDirection direction); /// <summary> /// Returns the position at the edge of a caret unit after backspacing. /// </summary> /// <param name="position"> /// Initial text position of an object/character. /// </param> /// <returns> /// The the position at the edge of a caret unit after backspacing. /// </returns> /// <exception cref="System.InvalidOperationException"> /// Throws InvalidOperationException if IsValid is false. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Throws ArgumentOutOfRangeException if incoming position is not /// part of this TextView (should call Contains first to check). /// </exception> /// <exception cref="System.ArgumentNullException"> /// Throws ArgumentNullException if position is invalid. /// </exception> /// <exception cref="System.ComponentModel.InvalidEnumArgumentException"> /// Throws InvalidEnumArgumentException if an invalid enum value for /// direction is passed. /// </exception> ITextPointer GetBackspaceCaretUnitPosition(ITextPointer position); /// <summary> /// Returns a TextRange that spans the line on which the given /// position is located. /// </summary> /// <param name="position"> /// Any oriented text position on the line. /// </param> /// <returns> /// TextRange that spans the line on which the given position is located. /// </returns> /// <exception cref="System.InvalidOperationException"> /// Throws InvalidOperationException if IsValid is false. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Throws ArgumentOutOfRangeException if incoming position is not /// part of this TextView (should call Contains first to check). /// </exception> /// <exception cref="System.ArgumentNullException"> /// Throws ArgumentNullException if position is invalid. /// </exception> /// <exception cref="System.ComponentModel.InvalidEnumArgumentException"> /// Throws InvalidEnumArgumentException if an invalid enum value for /// direction is passed. /// </exception> TextSegment GetLineRange(ITextPointer position); /// <summary> /// Provides a collection of glyph properties corresponding to runs /// of Unicode code points. /// </summary> /// <param name="start"> /// A position preceding the first code point to examine. /// </param> /// <param name="end"> /// A position following the last code point to examine. /// </param> /// <returns> /// A collection of glyph property runs. /// </returns> /// <exception cref="System.InvalidOperationException"> /// Throws InvalidOperationException if IsValid is false. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Throws ArgumentOutOfRangeException if incoming position is not /// part of this TextView (should call Contains first to check). /// </exception> /// <exception cref="System.ArgumentNullException"> /// Throws ArgumentNullException if position is invalid. /// </exception> /// <remarks> /// A "glyph" in this context is the lowest level rendered representation /// of text. Each entry in the output array describes a constant run /// of properties on the glyphs corresponding to a range of Unicode /// code points. With this array, it's possible to enumerate the glyph /// properties for each code point in the specified text run. /// </remarks> ReadOnlyCollection<GlyphRun> GetGlyphRuns(ITextPointer start, ITextPointer end); /// <summary> /// Returns whether the position is contained in this view. /// </summary> /// <param name="position"> /// A position to test. /// </param> /// <returns> /// True if TextView contains specified text position. /// Otherwise returns false. /// </returns> /// <exception cref="System.InvalidOperationException"> /// Throws InvalidOperationException if IsValid is false. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Throws ArgumentOutOfRangeException if incoming position is not /// part of this TextView (should call Contains first to check). /// </exception> /// <exception cref="System.ArgumentNullException"> /// Throws ArgumentNullException if position is invalid. /// </exception> /// <exception cref="System.ComponentModel.InvalidEnumArgumentException"> /// Throws InvalidEnumArgumentException if an invalid enum value for /// direction is passed. /// </exception> /// <remarks> /// This method is used for multi-view (paginated) scenarios, /// when a position is not guaranteed to be in the current view. /// </remarks> bool Contains(ITextPointer position); /// <summary> /// void BringPositionIntoViewAsync(ITextPointer position, object userState); /// <summary> /// void BringPointIntoViewAsync(Point point, object userState); /// <summary> /// void BringLineIntoViewAsync(ITextPointer position, double suggestedX, int count, object userState); /// <summary> /// void BringPageIntoViewAsync(ITextPointer position, Point suggestedOffset, int count, object userState); /// <summary> /// Cancels all asynchronous calls made with the given userState. /// If userState is NULL, all asynchronous calls are cancelled. /// </summary> /// <param name="userState">Unique identifier for the asynchronous task.</param> void CancelAsync(object userState); /// <summary> /// Ensures the TextView is in a clean layout state and that it is /// possible to retrieve layout data. /// </summary> /// <remarks> /// This method may be expensive, because it may lead to a full /// layout update. /// </remarks> bool Validate(); /// <summary> /// Ensures this ITextView has a clean layout at the specified Point. /// </summary> /// <param name="point"> /// Location to validate. /// </param> /// <returns> /// True if the Point is validated, false otherwise. /// </returns> /// <remarks> /// Use this method before calling GetTextPositionFromPoint. /// </remarks> bool Validate(Point point); /// <summary> /// Ensures this ITextView has a clean layout at the specified ITextPointer. /// </summary> /// <param name="position"> /// Position to validate. /// </param> /// <returns> /// True if the position is validated, false otherwise. /// </returns> /// <remarks> /// Use this method before calling any of the methods on this class that /// take a ITextPointer parameter. /// </remarks> bool Validate(ITextPointer position); /// <summary> /// Called by the TextEditor after receiving user input. /// Implementors of this method should balance for minimum latency /// for the next few seconds. /// </summary> /// <remarks> /// For example, during the next few seconds it would be /// appropriate to examine much smaller chunks of text during background /// layout calculations, so that the latency of a keystroke repsonse is /// minimal. /// </remarks> void ThrottleBackgroundTasksForUserInput(); #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties /// <summary> /// A UIElement owning this text view. All coordinates are calculated relative to this element. /// </summary> UIElement RenderScope { get; } /// <summary> /// The container for the text being displayed in this view. /// TextPositions refer to positions within this TextContainer. /// </summary> ITextContainer TextContainer { get; } /// <summary> /// Whether the TextView object is in a valid layout state. /// </summary> /// <remarks> /// If False, Validate must be called before calling any other /// method on TextView. /// </remarks> bool IsValid { get; } /// <summary> /// Whether the TextView renders its own selection /// </summary> bool RendersOwnSelection { get; } /// <summary> /// Collection of TextSegments representing content of the TextView. /// </summary> ReadOnlyCollection<TextSegment> TextSegments { get; } #endregion Internal Properties //------------------------------------------------------ // // Internal Events // //------------------------------------------------------ #region Internal Events /// <summary> /// Fired when a BringPositionIntoViewAsync call has completed. /// </summary> event BringPositionIntoViewCompletedEventHandler BringPositionIntoViewCompleted; /// <summary> /// Fired when a BringPointIntoViewAsync call has completed. /// </summary> event BringPointIntoViewCompletedEventHandler BringPointIntoViewCompleted; /// <summary> /// Fired when a BringLineIntoViewAsync call has completed. /// </summary> event BringLineIntoViewCompletedEventHandler BringLineIntoViewCompleted; /// <summary> /// Fired when a BringPageIntoViewAsync call has completed. /// </summary> event BringPageIntoViewCompletedEventHandler BringPageIntoViewCompleted; /// <summary> /// Fired when TextView is updated and becomes valid. /// </summary> event EventHandler Updated; #endregion Internal Events } /// <summary> /// BringPositionIntoViewCompleted event handler. /// </summary> internal delegate void BringPositionIntoViewCompletedEventHandler(object sender, BringPositionIntoViewCompletedEventArgs e); /// <summary> /// BringPointIntoViewCompleted event handler. /// </summary> internal delegate void BringPointIntoViewCompletedEventHandler(object sender, BringPointIntoViewCompletedEventArgs e); /// <summary> /// BringLineIntoViewCompleted event handler. /// </summary> internal delegate void BringLineIntoViewCompletedEventHandler(object sender, BringLineIntoViewCompletedEventArgs e); /// <summary> /// BringLineIntoViewCompleted event handler. /// </summary> internal delegate void BringPageIntoViewCompletedEventHandler(object sender, BringPageIntoViewCompletedEventArgs e); /// <summary> /// Event arguments for the BringPositionIntoViewCompleted event. /// </summary> internal class BringPositionIntoViewCompletedEventArgs : AsyncCompletedEventArgs { /// <summary> /// Constructor. /// </summary> /// <param name="position">Position of an object/character.</param> /// <param name="succeeded">Whether operation was successful.</param> /// <param name="error">Error occurred during an asynchronous operation.</param> /// <param name="cancelled">Whether an asynchronous operation has been cancelled.</param> /// <param name="userState">Unique identifier for the asynchronous task.</param> public BringPositionIntoViewCompletedEventArgs(ITextPointer position, bool succeeded, Exception error, bool cancelled, object userState) : base(error, cancelled, userState) { //_position = position; //_succeeded = succeeded; } // Position of an object/character. //private readonly ITextPointer _position; // Whether operation was successful. //private readonly bool _succeeded; } /// <summary> /// Event arguments for the BringPointIntoViewCompleted event. /// </summary> internal class BringPointIntoViewCompletedEventArgs : AsyncCompletedEventArgs { /// <summary> /// Constructor. /// </summary> /// <param name="point">Point in pixel coordinates.</param> /// <param name="position">A text position and its orientation matching or closest to the point.</param> /// <param name="succeeded">Whether operation was successful.</param> /// <param name="error">Error occurred during an asynchronous operation.</param> /// <param name="cancelled">Whether an asynchronous operation has been cancelled.</param> /// <param name="userState">Unique identifier for the asynchronous task.</param> public BringPointIntoViewCompletedEventArgs(Point point, ITextPointer position, bool succeeded, Exception error, bool cancelled, object userState) : base(error, cancelled, userState) { _point = point; _position = position; //_succeeded = succeeded; } /// <summary> /// Point in pixel coordinates. /// </summary> public Point Point { get { // Raise an exception if the operation failed or was cancelled. this.RaiseExceptionIfNecessary(); return _point; } } /// <summary> /// A text position and its orientation matching or closest to the point. /// </summary> public ITextPointer Position { get { // Raise an exception if the operation failed or was cancelled. this.RaiseExceptionIfNecessary(); return _position; } } /// <summary> /// Point in pixel coordinates. /// </summary> private readonly Point _point; /// <summary> /// A text position and its orientation matching or closest to the point. /// </summary> private readonly ITextPointer _position; // Whether operation was successful. //private readonly bool _succeeded; } /// <summary> /// Event arguments for the BringLineIntoViewCompleted event. /// </summary> internal class BringLineIntoViewCompletedEventArgs : AsyncCompletedEventArgs { /// <summary> /// Constructor. /// </summary> /// <param name="position">Initial text position of an object/character.</param> /// <param name="suggestedX"> /// The suggestedX parameter is the suggested X offset, in pixels, of /// the TextPointer on the destination line. /// </param> /// <param name="count">Number of lines to advance. Negative means move backwards.</param> /// <param name="newPosition">ITextPointer matching the given position advanced by the given number of line.</param> /// <param name="newSuggestedX">The offset at the position moved (useful when moving between columns or pages).</param> /// <param name="linesMoved">Indicates the number of lines moved, which may be less than count if there is no more content.</param> /// <param name="succeeded">Whether operation was successful.</param> /// <param name="error">Error occurred during an asynchronous operation.</param> /// <param name="cancelled">Whether an asynchronous operation has been cancelled.</param> /// <param name="userState">Unique identifier for the asynchronous task.</param> public BringLineIntoViewCompletedEventArgs(ITextPointer position, double suggestedX, int count, ITextPointer newPosition, double newSuggestedX, int linesMoved, bool succeeded, Exception error, bool cancelled, object userState) : base(error, cancelled, userState) { _position = position; //_suggestedX = suggestedX; _count = count; _newPosition = newPosition; _newSuggestedX = newSuggestedX; //_linesMoved = linesMoved; //_succeeded = succeeded; } /// <summary> /// Initial text position of an object/character. /// </summary> public ITextPointer Position { get { // Raise an exception if the operation failed or was cancelled. this.RaiseExceptionIfNecessary(); return _position; } } /// <summary> /// Number of lines to advance. Negative means move backwards. /// </summary> public int Count { get { // Raise an exception if the operation failed or was cancelled. this.RaiseExceptionIfNecessary(); return _count; } } /// <summary> /// ITextPointer matching the given position advanced by the given number of line. /// </summary> public ITextPointer NewPosition { get { // Raise an exception if the operation failed or was cancelled. this.RaiseExceptionIfNecessary(); return _newPosition; } } /// <summary> /// The offset at the position moved (useful when moving between columns or pages). /// </summary> public double NewSuggestedX { get { // Raise an exception if the operation failed or was cancelled. this.RaiseExceptionIfNecessary(); return _newSuggestedX; } } /// <summary> /// Initial text position of an object/character. /// </summary> private readonly ITextPointer _position; // The suggestedX parameter is the suggested X offset, in pixels, of // the TextPointer on the destination line. //private readonly double _suggestedX; /// <summary> /// Number of lines to advance. Negative means move backwards. /// </summary> private readonly int _count; /// <summary> /// ITextPointer matching the given position advanced by the given number of line. /// </summary> private readonly ITextPointer _newPosition; /// <summary> /// The offset at the position moved (useful when moving between columns or pages). /// </summary> private readonly double _newSuggestedX; // Indicates the number of lines moved, which may be less than count if there is no more content. //private readonly int _linesMoved; // Whether operation was successful. //private readonly bool _succeeded; } /// <summary> /// internal class BringPageIntoViewCompletedEventArgs : AsyncCompletedEventArgs { /// <summary> /// Constructor. /// </summary> /// <param name="position">Initial text position of an object/character.</param> /// <param name="suggestedOffset"> /// The suggestedX parameter is the suggested X offset, in pixels, of /// the TextPointer on the destination line. /// </param> /// <param name="count">Number of lines to advance. Negative means move backwards.</param> /// <param name="newPosition">ITextPointer matching the given position advanced by the given number of line.</param> /// <param name="newSuggestedOffset">The offset at the position moved (useful when moving between columns or pages).</param> /// <param name="pagesMoved">Indicates the number of pages moved, which may be less than count if there is no more content.</param> /// <param name="succeeded">Whether operation was successful.</param> /// <param name="error">Error occurred during an asynchronous operation.</param> /// <param name="cancelled">Whether an asynchronous operation has been cancelled.</param> /// <param name="userState">Unique identifier for the asynchronous task.</param> public BringPageIntoViewCompletedEventArgs(ITextPointer position, Point suggestedOffset, int count, ITextPointer newPosition, Point newSuggestedOffset, int pagesMoved, bool succeeded, Exception error, bool cancelled, object userState) : base(error, cancelled, userState) { _position = position; //_suggestedX = suggestedX; _count = count; _newPosition = newPosition; _newSuggestedOffset = newSuggestedOffset; //_linesMoved = linesMoved; //_succeeded = succeeded; } /// <summary> /// Initial text position of an object/character. /// </summary> public ITextPointer Position { get { // Raise an exception if the operation failed or was cancelled. this.RaiseExceptionIfNecessary(); return _position; } } /// <summary> /// Number of lines to advance. Negative means move backwards. /// </summary> public int Count { get { // Raise an exception if the operation failed or was cancelled. this.RaiseExceptionIfNecessary(); return _count; } } /// <summary> /// ITextPointer matching the given position advanced by the given number of line. /// </summary> public ITextPointer NewPosition { get { // Raise an exception if the operation failed or was cancelled. this.RaiseExceptionIfNecessary(); return _newPosition; } } /// <summary> /// The offset at the position moved (useful when moving between columns or pages). /// </summary> public Point NewSuggestedOffset { get { // Raise an exception if the operation failed or was cancelled. this.RaiseExceptionIfNecessary(); return _newSuggestedOffset; } } /// <summary> /// Initial text position of an object/character. /// </summary> private readonly ITextPointer _position; // The suggestedX parameter is the suggested X offset, in pixels, of // the TextPointer on the destination line. //private readonly double _suggestedX; /// <summary> /// Number of lines to advance. Negative means move backwards. /// </summary> private readonly int _count; /// <summary> /// ITextPointer matching the given position advanced by the given number of line. /// </summary> private readonly ITextPointer _newPosition; /// <summary> /// The offset at the position moved (useful when moving between columns or pages). /// </summary> private readonly Point _newSuggestedOffset; // Indicates the number of lines moved, which may be less than count if there is no more content. //private readonly int _linesMoved; // Whether operation was successful. //private readonly bool _succeeded; } }
using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json.Linq; namespace FluentAssertions.Json { [TestClass] // ReSharper disable InconsistentNaming public class JTokenAssertionsSpecs { [TestMethod] public void When_both_values_are_the_same_or_equal_Be_should_succeed() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- var a = JToken.Parse("{\"id\":1}"); var b = JToken.Parse("{\"id\":1}"); //----------------------------------------------------------------------------------------------------------- // Act & Assert //----------------------------------------------------------------------------------------------------------- a.Should().Be(a); b.Should().Be(b); a.Should().Be(b); } [TestMethod] public void When_values_differ_NotBe_should_succeed() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- var a = JToken.Parse("{\"id\":1}"); var b = JToken.Parse("{\"id\":2}"); //----------------------------------------------------------------------------------------------------------- // Act & Assert //----------------------------------------------------------------------------------------------------------- a.Should().NotBeNull(); a.Should().NotBe(null); a.Should().NotBe(b); } [TestMethod] public void When_values_are_equal_or_equivalent_NotBe_should_fail() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- var a = JToken.Parse("{\"id\":1}"); var b = JToken.Parse("{\"id\":1}"); //----------------------------------------------------------------------------------------------------------- // Act & Assert //----------------------------------------------------------------------------------------------------------- a.Invoking(x => x.Should().NotBe(b)) .ShouldThrow<AssertFailedException>() .WithMessage($"Expected JSON document not to be {_formatter.ToString(b)}."); } [TestMethod] public void When_both_values_are_equal_BeEquivalentTo_should_succeed() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- var testCases = new Dictionary<string, string> { { "{friends:[{id:123,name:\"Corby Page\"},{id:456,name:\"Carter Page\"}]}", "{friends:[{name:\"Corby Page\",id:123},{id:456,name:\"Carter Page\"}]}" }, { "{id:2,admin:true}", "{admin:true,id:2}" } }; foreach (var testCase in testCases) { var actualJson = testCase.Key; var expectedJson = testCase.Value; var a = JToken.Parse(actualJson); var b = JToken.Parse(expectedJson); //----------------------------------------------------------------------------------------------------------- // Act & Assert //----------------------------------------------------------------------------------------------------------- a.Should().BeEquivalentTo(b); } } [TestMethod] public void When_values_differ_NotBeEquivalentTo_should_succeed() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- var testCases = new Dictionary<string, string> { { "{id:1,admin:true}", "{id:1,admin:false}" } }; foreach (var testCase in testCases) { var actualJson = testCase.Key; var expectedJson = testCase.Value; var a = JToken.Parse(actualJson); var b = JToken.Parse(expectedJson); //----------------------------------------------------------------------------------------------------------- // Act & Assert //----------------------------------------------------------------------------------------------------------- a.Should().NotBeEquivalentTo(b); } } [TestMethod] public void When_values_differ_Be_should_fail() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- var testCases = new Dictionary<string, string> { { "{id:1}", "{id:2}" } , { "{id:1,admin:true}", "{id:1,admin:false}" } }; foreach (var testCase in testCases) { var actualJson = testCase.Key; var expectedJson = testCase.Value; var a = JToken.Parse(actualJson); var b = JToken.Parse(expectedJson); var expectedMessage = $"Expected JSON document to be {_formatter.ToString(b)}, but found {_formatter.ToString(a)}."; //----------------------------------------------------------------------------------------------------------- // Act & Assert //----------------------------------------------------------------------------------------------------------- a.Should().Invoking(x => x.Be(b)) .ShouldThrow<AssertFailedException>() .WithMessage(expectedMessage); } } [TestMethod] public void When_values_differ_BeEquivalentTo_should_fail() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- var testCases = new Dictionary<string, string> { { "{id:1,admin:true}", "{id:1,admin:false}" } }; foreach (var testCase in testCases) { var actualJson = testCase.Key; var expectedJson = testCase.Value; var a = JToken.Parse(actualJson); var b = JToken.Parse(expectedJson); var expectedMessage = GetNotEquivalentMessage(a, b); //----------------------------------------------------------------------------------------------------------- // Act & Assert //----------------------------------------------------------------------------------------------------------- a.Should().Invoking(x => x.BeEquivalentTo(b)) .ShouldThrow<AssertFailedException>() .WithMessage(expectedMessage); } } [TestMethod] public void Fail_with_descriptive_message_when_child_element_differs() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- var subject = JToken.Parse("{child:{subject:'foo'}}"); var expected = JToken.Parse("{child:{expected:'bar'}}"); var expectedMessage = GetNotEquivalentMessage(subject, expected, "we want to test the failure {0}", "message"); //----------------------------------------------------------------------------------------------------------- // Act & Assert //----------------------------------------------------------------------------------------------------------- subject.Should().Invoking(x => x.BeEquivalentTo(expected, "we want to test the failure {0}", "message")) .ShouldThrow<AssertFailedException>() .WithMessage(expectedMessage); } [TestMethod] public void When_jtoken_has_value_HaveValue_should_succeed() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- var subject = JToken.Parse("{ 'id':42}"); //----------------------------------------------------------------------------------------------------------- // Act & Assert //----------------------------------------------------------------------------------------------------------- subject["id"].Should().HaveValue("42"); } [TestMethod] public void When_jtoken_not_has_value_HaveValue_should_fail() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- var subject = JToken.Parse("{ 'id':42}"); //----------------------------------------------------------------------------------------------------------- // Act & Assert //----------------------------------------------------------------------------------------------------------- subject["id"].Should().Invoking(x => x.HaveValue("43", "because foo")) .ShouldThrow<AssertFailedException>() .WithMessage("Expected JSON property \"id\" to have value \"43\" because foo, but found \"42\"."); } [TestMethod] public void When_jtoken_has_element_HaveElement_should_succeed() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- var subject = JToken.Parse("{ 'id':42}"); //----------------------------------------------------------------------------------------------------------- // Act & Assert //----------------------------------------------------------------------------------------------------------- subject.Should().HaveElement("id"); subject.Should().Invoking(x => x.HaveElement("name", "because foo")) .ShouldThrow<AssertFailedException>() .WithMessage($"Expected JSON document {_formatter.ToString(subject)} to have element \"name\" because foo, but no such element was found."); } [TestMethod] public void When_jtoken_not_has_element_HaveElement_should_fail() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- var subject = JToken.Parse("{ 'id':42}"); //----------------------------------------------------------------------------------------------------------- // Act & Assert //----------------------------------------------------------------------------------------------------------- subject.Should().Invoking(x => x.HaveElement("name", "because foo")) .ShouldThrow<AssertFailedException>() .WithMessage($"Expected JSON document {_formatter.ToString(subject)} to have element \"name\" because foo, but no such element was found."); } private static readonly JTokenFormatter _formatter = new JTokenFormatter(); private static string GetNotEquivalentMessage(JToken actual, JToken expected, string reason = null, params object[] reasonArgs) { var diff = ObjectDiffPatch.GenerateDiff(actual, expected); var key = diff.NewValues?.First ?? diff.OldValues?.First; var because = string.Empty; if (!string.IsNullOrWhiteSpace(reason)) because = " because " + string.Format(reason, reasonArgs); var expectedMessage = $"Expected JSON document {_formatter.ToString(actual, true)}" + $" to be equivalent to {_formatter.ToString(expected, true)}" + $"{because}, but differs at {key}."; return expectedMessage; } } }
using CSharpGuidelinesAnalyzer.Rules.Naming; using CSharpGuidelinesAnalyzer.Test.TestDataBuilders; using Microsoft.CodeAnalysis.Diagnostics; using Xunit; namespace CSharpGuidelinesAnalyzer.Test.Specs.Naming { public sealed class PrefixEventHandlersWithOnSpecs : CSharpGuidelinesAnalysisTestFixture { protected override string DiagnosticId => PrefixEventHandlersWithOnAnalyzer.DiagnosticId; [Fact] internal void When_event_is_bound_to_an_anonymous_method_it_must_be_skipped() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" public class X { public event EventHandler ValueChanged; } public class C { public void M() { X x = new X(); x.ValueChanged += new EventHandler(delegate(object s, EventArgs e) { }); } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_event_is_bound_to_a_lambda_body_it_must_be_skipped() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" public class X { public event EventHandler ValueChanged; } public class C { public void M() { X x = new X(); x.ValueChanged += (s, e) => { }; } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_event_is_bound_to_a_lambda_expression_it_must_be_skipped() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" public class X { public event EventHandler ValueChanged; } public class C { public void M() { X x = new X(); x.ValueChanged += (s, e) => M(); } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_event_is_unbound_from_a_misnamed_method_it_must_be_skipped() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" public class X { public event EventHandler ValueChanged; } public class C { public void M() { X x = new X(); x.ValueChanged -= HandleValueChangedOfX; } public void HandleValueChangedOfX(object sender, EventArgs e) { } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_remote_event_is_bound_to_a_method_that_matches_pattern_it_must_be_skipped() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" public class Coordinate { public event EventHandler ValueChanged; } public class C { private Coordinate _topLeft = new Coordinate(); public void M() { _topLeft.ValueChanged += TopLeftOnValueChanged; } public void TopLeftOnValueChanged(object sender, EventArgs e) { } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_remote_static_event_is_bound_to_a_method_that_matches_pattern_it_must_be_skipped() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" public static class Coordinate { public static event EventHandler ValueChanged; } public class C { public void M() { Coordinate.ValueChanged += CoordinateOnValueChanged; } public void CoordinateOnValueChanged(object sender, EventArgs e) { } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_remote_event_is_bound_to_a_method_that_does_not_match_pattern_it_must_be_reported() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" public class Coordinate { public event EventHandler ValueChanged; } public class C { private Coordinate _topLeft = new Coordinate(); public void M() { _topLeft.ValueChanged += [|HandleTopLeftValueChanged|]; } public void HandleTopLeftValueChanged(object sender, EventArgs e) { } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "Method 'HandleTopLeftValueChanged' that handles event 'ValueChanged' should be renamed to 'TopLeftOnValueChanged'"); } [Fact] internal void When_remote_event_is_bound_to_a_method_on_a_field_named_underscore_and_matches_pattern_it_must_be_skipped() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" public class Coordinate { public event EventHandler ValueChanged; } public class C { private Coordinate _ = new Coordinate(); public void M() { _.ValueChanged += OnValueChanged; } public void OnValueChanged(object sender, EventArgs e) { } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_local_event_is_bound_to_a_method_that_matches_pattern_it_must_be_skipped() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" public class C { public event EventHandler ValueChanged; public void M() { ValueChanged += OnValueChanged; } public void OnValueChanged(object sender, EventArgs e) { } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_local_static_event_is_bound_to_a_method_that_matches_pattern_it_must_be_skipped() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" public class C { public static event EventHandler ValueChanged; public void M() { ValueChanged += OnValueChanged; } public void OnValueChanged(object sender, EventArgs e) { } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_local_event_is_bound_to_a_method_that_does_not_match_pattern_it_must_be_reported() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" public class C { public event EventHandler ValueChanged; public void M() { ValueChanged += [|HandleValueChanged|]; } public void HandleValueChanged(object sender, EventArgs e) { } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "Method 'HandleValueChanged' that handles event 'ValueChanged' should be renamed to 'OnValueChanged'"); } [Fact] internal void When_local_event_is_bound_to_a_local_function_that_matches_pattern_it_must_be_skipped() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" public class C { public event EventHandler ValueChanged; public void M() { void L() { ValueChanged += OnValueChanged; } void OnValueChanged(object sender, EventArgs e) { } } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_local_event_is_bound_to_a_local_function_that_does_not_match_pattern_it_must_be_reported() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" public class C { public event EventHandler ValueChanged; public void M() { void L() { ValueChanged += [|HandleValueChanged|]; } void HandleValueChanged(object sender, EventArgs e) { } } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "Local function 'HandleValueChanged' that handles event 'ValueChanged' should be renamed to 'OnValueChanged'"); } protected override DiagnosticAnalyzer CreateAnalyzer() { return new PrefixEventHandlersWithOnAnalyzer(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. namespace Microsoft.PowerShell.Commands { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation; using System.Management.Automation.Internal; using Microsoft.PowerShell.Commands.Internal.Format; using System.IO; internal class TableView { private PSPropertyExpressionFactory _expressionFactory; private TypeInfoDataBase _typeInfoDatabase; private FormatErrorManager _errorManager; internal void Initialize(PSPropertyExpressionFactory expressionFactory, TypeInfoDataBase db) { _expressionFactory = expressionFactory; _typeInfoDatabase = db; // Initialize Format Error Manager. FormatErrorPolicy formatErrorPolicy = new FormatErrorPolicy(); formatErrorPolicy.ShowErrorsAsMessages = _typeInfoDatabase.defaultSettingsSection.formatErrorPolicy.ShowErrorsAsMessages; formatErrorPolicy.ShowErrorsInFormattedOutput = _typeInfoDatabase.defaultSettingsSection.formatErrorPolicy.ShowErrorsInFormattedOutput; _errorManager = new FormatErrorManager(formatErrorPolicy); } internal HeaderInfo GenerateHeaderInfo(PSObject input, TableControlBody tableBody, OutGridViewCommand parentCmdlet) { HeaderInfo headerInfo = new HeaderInfo(); // This verification is needed because the database returns "LastWriteTime" value for file system objects // as strings and it is used to detect this situation and use the actual field value. bool fileSystemObject = typeof(FileSystemInfo).IsInstanceOfType(input.BaseObject); if (tableBody != null) // If the tableBody is null, the TableControlBody info was not put into the database. { // Generate HeaderInfo from the type information database. List<TableRowItemDefinition> activeRowItemDefinitionList = GetActiveTableRowDefinition(tableBody, input); int col = 0; foreach (TableRowItemDefinition rowItem in activeRowItemDefinitionList) { ColumnInfo columnInfo = null; string displayName = null; TableColumnHeaderDefinition colHeader = null; // Retrieve a matching TableColumnHeaderDefinition if (col < tableBody.header.columnHeaderDefinitionList.Count) colHeader = tableBody.header.columnHeaderDefinitionList[col]; if (colHeader != null && colHeader.label != null) { displayName = _typeInfoDatabase.displayResourceManagerCache.GetTextTokenString(colHeader.label); } FormatToken token = null; if (rowItem.formatTokenList.Count > 0) { token = rowItem.formatTokenList[0]; } if (token != null) { FieldPropertyToken fpt = token as FieldPropertyToken; if (fpt != null) { if (displayName == null) { // Database does not provide a label(DisplayName) for the current property, use the expression value instead. displayName = fpt.expression.expressionValue; } if (fpt.expression.isScriptBlock) { PSPropertyExpression ex = _expressionFactory.CreateFromExpressionToken(fpt.expression); // Using the displayName as a propertyName for a stale PSObject. const string LastWriteTimePropertyName = "LastWriteTime"; // For FileSystem objects "LastWriteTime" property value should be used although the database indicates that a script should be executed to get the value. if (fileSystemObject && displayName.Equals(LastWriteTimePropertyName, StringComparison.OrdinalIgnoreCase)) { columnInfo = new OriginalColumnInfo(displayName, displayName, LastWriteTimePropertyName, parentCmdlet); } else { columnInfo = new ExpressionColumnInfo(displayName, displayName, ex); } } else { columnInfo = new OriginalColumnInfo(fpt.expression.expressionValue, displayName, fpt.expression.expressionValue, parentCmdlet); } } else { TextToken tt = token as TextToken; if (tt != null) { displayName = _typeInfoDatabase.displayResourceManagerCache.GetTextTokenString(tt); columnInfo = new OriginalColumnInfo(tt.text, displayName, tt.text, parentCmdlet); } } } if (columnInfo != null) { headerInfo.AddColumn(columnInfo); } col++; } } return headerInfo; } internal HeaderInfo GenerateHeaderInfo(PSObject input, OutGridViewCommand parentCmdlet) { HeaderInfo headerInfo = new HeaderInfo(); List<MshResolvedExpressionParameterAssociation> activeAssociationList; // Get properties from the default property set of the object activeAssociationList = AssociationManager.ExpandDefaultPropertySet(input, _expressionFactory); if (activeAssociationList.Count > 0) { // we got a valid set of properties from the default property set..add computername for // remoteobjects (if available) if (PSObjectHelper.ShouldShowComputerNameProperty(input)) { activeAssociationList.Add(new MshResolvedExpressionParameterAssociation(null, new PSPropertyExpression(RemotingConstants.ComputerNameNoteProperty))); } } else { // We failed to get anything from the default property set activeAssociationList = AssociationManager.ExpandAll(input); if (activeAssociationList.Count > 0) { // Remove PSComputerName and PSShowComputerName from the display as needed. AssociationManager.HandleComputerNameProperties(input, activeAssociationList); FilterActiveAssociationList(activeAssociationList); } else { // We were unable to retrieve any properties, so we leave an empty list activeAssociationList = new List<MshResolvedExpressionParameterAssociation>(); } } for (int k = 0; k < activeAssociationList.Count; k++) { string propertyName = null; MshResolvedExpressionParameterAssociation association = activeAssociationList[k]; // set the label of the column if (association.OriginatingParameter != null) { object key = association.OriginatingParameter.GetEntry(FormatParameterDefinitionKeys.LabelEntryKey); if (key != AutomationNull.Value) propertyName = (string)key; } if (propertyName == null) { propertyName = association.ResolvedExpression.ToString(); } ColumnInfo columnInfo = new OriginalColumnInfo(propertyName, propertyName, propertyName, parentCmdlet); headerInfo.AddColumn(columnInfo); } return headerInfo; } /// <summary> /// Method to filter resolved expressions as per table view needs. /// For v1.0, table view supports only 10 properties. /// /// This method filters and updates "activeAssociationList" instance property. /// </summary> /// <returns>None.</returns> /// <remarks>This method updates "activeAssociationList" instance property.</remarks> private void FilterActiveAssociationList(List<MshResolvedExpressionParameterAssociation> activeAssociationList) { // we got a valid set of properties from the default property set // make sure we do not have too many properties // NOTE: this is an arbitrary number, chosen to be a sensitive default int nMax = 256; if (activeAssociationList.Count > nMax) { List<MshResolvedExpressionParameterAssociation> tmp = new List<MshResolvedExpressionParameterAssociation>(activeAssociationList); activeAssociationList.Clear(); for (int k = 0; k < nMax; k++) activeAssociationList.Add(tmp[k]); } return; } private List<TableRowItemDefinition> GetActiveTableRowDefinition(TableControlBody tableBody, PSObject so) { if (tableBody.optionalDefinitionList.Count == 0) { // we do not have any override, use default return tableBody.defaultDefinition.rowItemDefinitionList; } // see if we have an override that matches TableRowDefinition matchingRowDefinition = null; var typeNames = so.InternalTypeNames; TypeMatch match = new TypeMatch(_expressionFactory, _typeInfoDatabase, typeNames); foreach (TableRowDefinition x in tableBody.optionalDefinitionList) { if (match.PerfectMatch(new TypeMatchItem(x, x.appliesTo))) { matchingRowDefinition = x; break; } } if (matchingRowDefinition == null) { matchingRowDefinition = match.BestMatch as TableRowDefinition; } if (matchingRowDefinition == null) { Collection<string> typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); if (typesWithoutPrefix != null) { match = new TypeMatch(_expressionFactory, _typeInfoDatabase, typesWithoutPrefix); foreach (TableRowDefinition x in tableBody.optionalDefinitionList) { if (match.PerfectMatch(new TypeMatchItem(x, x.appliesTo))) { matchingRowDefinition = x; break; } } if (matchingRowDefinition == null) { matchingRowDefinition = match.BestMatch as TableRowDefinition; } } } if (matchingRowDefinition == null) { // no matching override, use default return tableBody.defaultDefinition.rowItemDefinitionList; } // we have an override, we need to compute the merge of the active cells List<TableRowItemDefinition> activeRowItemDefinitionList = new List<TableRowItemDefinition>(); int col = 0; foreach (TableRowItemDefinition rowItem in matchingRowDefinition.rowItemDefinitionList) { // Check if the row is an override or not if (rowItem.formatTokenList.Count == 0) { // It's a place holder, use the default activeRowItemDefinitionList.Add(tableBody.defaultDefinition.rowItemDefinitionList[col]); } else { // Use the override activeRowItemDefinitionList.Add(rowItem); } col++; } return activeRowItemDefinitionList; } } }
/**************************************************************************** * Class Name : ErrorWarnInfoProvider.cs * Author : Kenneth J. Koteles * Created : 10/04/2007 2:14 PM * C# Version : .NET 2.0 * Description : This code is designed to create a new provider object to * work specifically with CSLA BusinessBase objects. In * addition to providing the red error icon for items in the * BrokenRulesCollection with Csla.Rules.RuleSeverity.Error, * this object also provides a yellow warning icon for items * with Csla.Rules.RuleSeverity.Warning and a blue * information icon for items with * Csla.Rules.RuleSeverity.Information. Since warnings * and information type items do not need to be fixed / * corrected prior to the object being saved, the tooltip * displayed when hovering over the respective icon contains * all the control's associated (by severity) broken rules. * Revised : 11/20/2007 8:32 AM * Change : Warning and information icons were not being updated for * dependant properties (controls without the focus) when * changes were being made to a related property (control with * the focus). Added a list of controls to be recursed * through each time a change was made to any control. This * obviously could result in performance issues; however, * there is no consistent way to question the BusinessObject * in order to get a list of dependant properties based on a * property name. It can be exposed to the UI (using * ValidationRules.GetRuleDescriptions()); however, it is up * to each developer to implement their own public method on * on the Business Object to do so. To make this generic for * all CSLA Business Objects, I cannot assume the developer * always exposes the dependant properties (nor do I know what * they'll call the method); therefore, this is the best I can * do right now. * Revised : 11/23/2007 9:02 AM * Change : Added new property ProcessDependantProperties to allow for * controlling when all controls are recursed through (for * dependant properties or not). Default value is 'false'. * This allows the developer to ba able to choose whether or * not to use the control in this manner (which could have * performance implications). * Revised : 10/05/2009, Jonny Bekkum * Change: Added initialization of controls list (controls attached to BindingSource) * and will update errors on all controls. Optimized retrieval of error, warn, info * messages and setting these on the controls. * Revised : 22/07/2012, Tiago Freitas Leal * Change: Adapt to Visual WebGUI. Use ResourceHandle instead of Icon. * The WebGUI's ErrorProvider doesn't allow simultaneous * Error / Warning / Infornation icons/messages. ****************************************************************************/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Text; using Csla.Core; using Csla.Rules; using Gizmox.WebGUI.Common.Resources; using Gizmox.WebGUI.Forms; using Gizmox.WebGUI.Forms.Design; namespace CslaContrib.WebGUI { /// <summary> /// WebGUI extender control that automatically /// displays error, warning, or information icons and /// text for the form controls based on the /// BrokenRulesCollection of a CSLA .NET business object. /// </summary> [ProvideProperty("IconAlignment", typeof (Control))] [ProvideProperty("Error", typeof (Control))] [ProvideProperty("IconPadding", typeof (Control))] [ToolboxItemFilter("CslaContrib.WebGUI", ToolboxItemFilterType.Require)] [ToolboxItemCategory("Components")] [ToolboxItem(true)] [ComplexBindingProperties("DataSource", "DataMember")] [DesignerCategory("")] [ToolboxBitmap(typeof (ErrorWarnInfoProvider), "ErrorWarnInfoProvider.bmp")] public class ErrorWarnInfoProvider : Gizmox.WebGUI.Forms.ErrorProvider, IExtenderProvider, ISupportInitialize { #region Private variables private readonly IContainer components; private readonly Gizmox.WebGUI.Forms.ErrorProvider _errorProviderInfo; private readonly Gizmox.WebGUI.Forms.ErrorProvider _errorProviderWarn; private readonly List<Control> _controls = new List<Control>(); private static readonly ResourceHandle DefaultIconInformation; private static readonly ResourceHandle DefaultIconWarning; private static readonly ResourceHandle DefaultIconError; private bool _showInformation = true; private bool _showWarning = true; private readonly Dictionary<string, string> _errorList = new Dictionary<string, string>(); private readonly Dictionary<string, string> _warningList = new Dictionary<string, string>(); private readonly Dictionary<string, string> _infoList = new Dictionary<string, string>(); private bool _isInitializing; #endregion #region Constructors /// <summary> /// Initializes the <see cref="ErrorWarnInfoProvider"/> class. /// </summary> static ErrorWarnInfoProvider() { DefaultIconInformation = new AssemblyResourceHandle(typeof(ErrorWarnInfoProvider), "CslaContrib.WebGUI.Resources.InformationIcon.png"); DefaultIconWarning = new AssemblyResourceHandle(typeof(ErrorWarnInfoProvider), "CslaContrib.WebGUI.Resources.WarningIcon.png"); DefaultIconError = new AssemblyResourceHandle(typeof(ErrorWarnInfoProvider), "CslaContrib.WebGUI.Resources.ErrorIcon.png"); } /// <summary> /// Initializes a new instance of the <see cref="ErrorWarnInfoProvider"/> class. /// </summary> public ErrorWarnInfoProvider() { components = new Container(); _errorProviderInfo = new Gizmox.WebGUI.Forms.ErrorProvider(components); _errorProviderWarn = new Gizmox.WebGUI.Forms.ErrorProvider(components); BlinkRate = 0; Icon = DefaultIconError; _errorProviderInfo.BlinkRate = 0; _errorProviderInfo.Icon = DefaultIconInformation; _errorProviderWarn.BlinkRate = 0; _errorProviderWarn.Icon = DefaultIconWarning; } /// <summary> /// Creates an instance of the object. /// </summary> /// <param name="container">The container of the control.</param> public ErrorWarnInfoProvider(IContainer container) : this() { container.Add(this); } /// <summary> /// Releases the unmanaged resources used by the <see cref="T:System.ComponentModel.Component"></see> and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #endregion #region IExtenderProvider Members /// <summary> /// Gets a value indicating whether the extender control /// can extend the specified control. /// </summary> /// <param name="extendee">The control to be extended.</param> /// <remarks> /// Any control implementing either a ReadOnly property or /// Enabled property can be extended. /// </remarks> bool IExtenderProvider.CanExtend(object extendee) { if ((extendee is Control && !(extendee is Form))) { return !(extendee is ToolBar); } return false; } #endregion #region Public properties /// <summary> /// Gets or sets the rate at which the error icon flashes. /// </summary> /// <returns>The rate, in milliseconds, at which the error icon should flash. The default is 250 milliseconds.</returns> /// /// <exception cref="T:System.ArgumentOutOfRangeException">The value is less than zero. </exception> /// /// <PermissionSet><IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/><IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/></PermissionSet> [Category("Behavior")] [DefaultValue(0)] [Description("The rate in milliseconds at which the error icon blinks.")] public new int BlinkRate { get { return base.BlinkRate; } set { if (value < 0) { throw new ArgumentOutOfRangeException(@"BlinkRate", value, @"Blink rate must be zero or more"); } base.BlinkRate = value; if (value == 0) { BlinkStyle = ErrorBlinkStyle.NeverBlink; } } } /// <summary> /// Gets or sets the rate at which the information icon flashes. /// </summary> /// <returns>The rate, in milliseconds, at which the information icon should flash. The default is 250 milliseconds.</returns> /// /// <exception cref="T:System.ArgumentOutOfRangeException">The value is less than zero. </exception> /// /// <PermissionSet><IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/><IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/></PermissionSet> [Category("Behavior")] [DefaultValue(0)] [Description("The rate in milliseconds at which the information icon blinks.")] public int BlinkRateInformation { get { return _errorProviderInfo.BlinkRate; } set { if (value < 0) throw new ArgumentOutOfRangeException(@"BlinkRateInformation", value, @"Blink rate must be zero or more"); _errorProviderInfo.BlinkRate = value; if (value == 0) _errorProviderInfo.BlinkStyle = ErrorBlinkStyle.NeverBlink; } } /// <summary> /// Gets or sets the rate at which the warning icon flashes. /// </summary> /// <returns>The rate, in milliseconds, at which the warning icon should flash. /// The default is 250 milliseconds.</returns> /// /// <exception cref="T:System.ArgumentOutOfRangeException">The value is less than zero. </exception> /// /// <PermissionSet><IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/><IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/></PermissionSet> [Category("Behavior")] [DefaultValue(0)] [Description("The rate in milliseconds at which the warning icon blinks.")] public int BlinkRateWarning { get { return _errorProviderWarn.BlinkRate; } set { if (value < 0) throw new ArgumentOutOfRangeException(@"BlinkRateWarning", value, @"Blink rate must be zero or more"); _errorProviderWarn.BlinkRate = value; if (value == 0) _errorProviderWarn.BlinkStyle = ErrorBlinkStyle.NeverBlink; } } /// <summary> /// Gets or sets a value indicating when the error icon flashes. /// </summary> /// <returns>One of the <see cref="T:Gizmox.WebGUI.Forms.ErrorBlinkStyle"/> values. /// The default is <see cref="F:Gizmox.WebGUI.Forms.ErrorBlinkStyle.BlinkIfDifferentError"/>.</returns> /// /// <exception cref="T:System.ComponentModel.InvalidEnumArgumentException">The assigned value is not one of the <see cref="T:Gizmox.WebGUI.Forms.ErrorBlinkStyle"/> values. </exception> /// /// <PermissionSet><IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/><IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/></PermissionSet> [Category("Behavior")] [DefaultValue(ErrorBlinkStyle.NeverBlink)] [Description("Controls whether the error icon blinks when an error is set.")] public new ErrorBlinkStyle BlinkStyle { get { return base.BlinkStyle; } set { base.BlinkStyle = value; } } /// <summary> /// Gets or sets a value indicating when the information icon flashes. /// </summary> /// <returns>One of the <see cref="T:Gizmox.WebGUI.Forms.ErrorBlinkStyle"/> values. /// The default is <see cref="F:Gizmox.WebGUI.Forms.ErrorBlinkStyle.BlinkIfDifferentError"/>.</returns> /// /// <exception cref="T:System.ComponentModel.InvalidEnumArgumentException">The assigned value is not one of the <see cref="T:Gizmox.WebGUI.Forms.ErrorBlinkStyle"/> values. </exception> /// /// <PermissionSet><IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/><IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/></PermissionSet> [Category("Behavior")] [DefaultValue(ErrorBlinkStyle.NeverBlink)] [Description("Controls whether the information icon blinks when information is set.")] public ErrorBlinkStyle BlinkStyleInformation { get { return _errorProviderInfo.BlinkStyle; } set { _errorProviderWarn.BlinkStyle = value; } } /// <summary> /// Gets or sets a value indicating when the warning icon flashes. /// </summary> /// <returns>One of the <see cref="T:Gizmox.WebGUI.Forms.ErrorBlinkStyle"/> values. The default is <see cref="F:Gizmox.WebGUI.Forms.ErrorBlinkStyle.BlinkIfDifferentError"/>.</returns> /// /// <exception cref="T:System.ComponentModel.InvalidEnumArgumentException">The assigned value is not one of the <see cref="T:Gizmox.WebGUI.Forms.ErrorBlinkStyle"/> values. </exception> /// /// <PermissionSet><IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/><IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/></PermissionSet> [Category("Behavior")] [DefaultValue(ErrorBlinkStyle.NeverBlink)] [Description("Controls whether the warning icon blinks when a warning is set.")] public ErrorBlinkStyle BlinkStyleWarning { get { return _errorProviderWarn.BlinkStyle; } set { _errorProviderWarn.BlinkStyle = value; } } /// <summary> /// Gets or sets the data source that the <see cref="T:Gizmox.WebGUI.Forms.ErrorProvider"></see> monitors. /// </summary> /// <value></value> /// <returns>A data source based on the <see cref="T:System.Collections.IList"></see> interface to be monitored for errors. Typically, this is a <see cref="T:System.Data.DataSet"></see> to be monitored for errors.</returns> /// <PermissionSet><IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/><IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/></PermissionSet> [DefaultValue((string) null)] public new object DataSource { get { return base.DataSource; } set { if (base.DataSource != value) { var bs1 = base.DataSource as BindingSource; if (bs1 != null) { bs1.CurrentItemChanged -= DataSource_CurrentItemChanged; } } base.DataSource = value; var bs = value as BindingSource; if (bs != null) { bs.CurrentItemChanged += DataSource_CurrentItemChanged; } } } /*private void UpdateBindingsAndProcessAllControls() { if (ContainerControl != null) { InitializeAllControls(ContainerControl.Controls); } ProcessAllControls(); }*/ /// <summary> /// Gets or sets the information icon. /// </summary> /// <value>The information icon.</value> [Category("Behavior")] [Description("The icon used to indicate information.")] public ResourceHandle IconInformation { get { return _errorProviderInfo.Icon; } set { if (value == null) value = DefaultIconInformation; _errorProviderInfo.Icon = value; } } /// <summary> /// Gets or sets the warning icon. /// </summary> /// <value>The warning icon.</value> [Category("Behavior")] [Description("The icon used to indicate a warning.")] public ResourceHandle IconWarning { get { return _errorProviderWarn.Icon; } set { if (value == null) value = DefaultIconWarning; _errorProviderWarn.Icon = value; } } /// <summary> /// Gets or sets the error icon. /// </summary> /// <value>The error icon.</value> [Category("Behavior")] [Description("The icon used to indicate an error.")] public ResourceHandle IconError { get { return Icon; } set { if (value == null) value = DefaultIconError; Icon = value; } } /// <summary> /// Gets or sets a value indicating whether broken rules with severity information should be visible. /// </summary> /// <value><c>true</c> if information is visible; otherwise, <c>false</c>.</value> [Category("Behavior")] [DefaultValue(true), Description("Determines if the information icon should be displayed when informations exists.")] public bool ShowInformation { get { return _showInformation; } set { _showInformation = value; } } /// <summary> /// Gets or sets a value indicating whether broken rules with severity Warning should be visible. /// </summary> /// <value><c>true</c> if Warning is visible; otherwise, <c>false</c>.</value> [Category("Behavior")] [DefaultValue(true), Description("Determines if the warning icon should be displayed when warnings exist.")] public bool ShowWarning { get { return _showWarning; } set { _showWarning = value; } } #endregion #region Methods /*/// <summary> /// Clears all errors associated with this component. /// </summary> /// <PermissionSet><IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/></PermissionSet> public new void Clear() { base.Clear(); _errorProviderInfo.Clear(); _errorProviderWarn.Clear(); }*/ /// <summary> /// Gets the information message. /// </summary> /// <param name="control">The control.</param> /// <returns></returns> public string GetInformation(Control control) { return _errorProviderInfo.GetError(control); } /// <summary> /// Gets the warning message. /// </summary> /// <param name="control">The control.</param> /// <returns></returns> public string GetWarning(Control control) { return _errorProviderWarn.GetError(control); } private void InitializeAllControls(Control.ControlCollection controls) { // clear internal _controls.Clear(); // run recursive initialize of controls Initialize(controls); } private void Initialize(Control.ControlCollection controls) { // We don't provide an extended property, so if the control is // not a Label then 'hook' the validating event here! foreach (Control control in controls) { if (control is Label) continue; // Initialize bindings foreach (Binding binding in control.DataBindings) { // get the Binding if appropriate if (binding.DataSource == DataSource) { _controls.Add(control); } } // Initialize any subcontrols if (control.Controls.Count > 0) { Initialize(control.Controls); } } } private void DataSource_CurrentItemChanged(object sender, EventArgs e) { Debug.Print("ErrorWarnInfo: CurrentItemChanged, {0}", DateTime.Now.Ticks); ProcessAllControls(); } private void ProcessAllControls() { if (_isInitializing) return; // get error/warn/info list from business object GetWarnInfoList(); // process controls in window ProcessControls(); } private void GetWarnInfoList() { _infoList.Clear(); _warningList.Clear(); _errorList.Clear(); var bs = (BindingSource) DataSource; if (bs == null) return; if (bs.Position == -1) return; // get the BusinessBase object var bb = bs.Current as BusinessBase; // we can only deal with CSLA BusinessBase objects if (bb != null) { foreach (BrokenRule br in bb.BrokenRulesCollection) { // we do not want to import result of object level broken rules if (br.Property == null) continue; switch (br.Severity) { case RuleSeverity.Error: if (_errorList.ContainsKey(br.Property)) { _errorList[br.Property] = String.Concat(_errorList[br.Property], Environment.NewLine, br.Description); } else { _errorList.Add(br.Property, br.Description); } break; case RuleSeverity.Warning: if (_warningList.ContainsKey(br.Property)) { _warningList[br.Property] = String.Concat(_warningList[br.Property], Environment.NewLine, br.Description); } else { _warningList.Add(br.Property, br.Description); } break; default: // consider it an Info if (_infoList.ContainsKey(br.Property)) { _infoList[br.Property] = String.Concat(_infoList[br.Property], Environment.NewLine, br.Description); } else { _infoList.Add(br.Property, br.Description); } break; } } } } private void ProcessControls() { foreach (Control control in _controls) { ProcessControl(control); } } /// <summary> /// Processes the control. /// </summary> /// <param name="control">The control.</param> private void ProcessControl(Control control) { if (control == null) throw new ArgumentNullException("control"); var sbError = new StringBuilder(); var sbWarn = new StringBuilder(); var sbInfo = new StringBuilder(); foreach (Binding binding in control.DataBindings) { // get the Binding if appropriate if (binding.DataSource == DataSource) { string propertyName = binding.BindingMemberInfo.BindingField; if (_errorList.ContainsKey(propertyName)) sbError.AppendLine(_errorList[propertyName]); if (_warningList.ContainsKey(propertyName)) sbWarn.AppendLine(_warningList[propertyName]); if (_infoList.ContainsKey(propertyName)) sbInfo.AppendLine(propertyName); } } bool bError = sbError.Length > 0; bool bWarn = sbWarn.Length > 0; bool bInfo = sbInfo.Length > 0; bWarn = _showWarning && bWarn; bInfo = _showInformation && bInfo; if (bError) { SetError(control, sbError.ToString()); } else if (bWarn) { _errorProviderWarn.SetError(control, sbWarn.ToString()); _errorProviderWarn.SetIconPadding(control, GetIconPadding(control)); _errorProviderWarn.SetIconAlignment(control, GetIconAlignment(control)); } else if (bInfo) { _errorProviderInfo.SetError(control, sbInfo.ToString()); _errorProviderInfo.SetIconPadding(control, GetIconPadding(control)); _errorProviderInfo.SetIconAlignment(control, GetIconAlignment(control)); } else _errorProviderInfo.SetError(control, string.Empty); } /*private void ResetBlinkStyleInformation() { BlinkStyleInformation = ErrorBlinkStyle.BlinkIfDifferentError; } private void ResetBlinkStyleWarning() { BlinkStyleWarning = ErrorBlinkStyle.BlinkIfDifferentError; } private void ResetIconInformation() { IconInformation = DefaultIconInformation; } private void ResetIconWarning() { IconWarning = DefaultIconWarning; } private void ResetIconError() { Icon = DefaultIconError; }*/ /// <summary> /// Sets the information message. /// </summary> /// <param name="control">The control.</param> /// <param name="message">The information message.</param> public void SetInformation(Control control, string message) { _errorProviderInfo.SetError(control, message); } /// <summary> /// Sets the warning message. /// </summary> /// <param name="control">The control.</param> /// <param name="message">The warning message.</param> public void SetWarning(Control control, string message) { _errorProviderWarn.SetError(control, message); } /*private bool ShouldSerializeIconInformation() { return (IconInformation != DefaultIconInformation); } private bool ShouldSerializeIconWarning() { return (IconWarning != DefaultIconWarning); } private bool ShouldSerializeIconError() { return (Icon != DefaultIconError); } private bool ShouldSerializeBlinkStyleInformation() { return (BlinkStyleInformation != ErrorBlinkStyle.BlinkIfDifferentError); } private bool ShouldSerializeBlinkStyleWarning() { return (BlinkStyleWarning != ErrorBlinkStyle.BlinkIfDifferentError); }*/ /// <summary> /// Provides a method to update the bindings of the <see cref="P:Gizmox.WebGUI.Forms.ErrorProvider.DataSource"></see>, <see cref="P:Gizmox.WebGUI.Forms.ErrorProvider.DataMember"></see>, and the error text. /// </summary> /// <PermissionSet><IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/><IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/></PermissionSet> public new void UpdateBinding() { base.UpdateBinding(); _errorProviderInfo.UpdateBinding(); _errorProviderWarn.UpdateBinding(); } #endregion #region ISupportInitialize Members void ISupportInitialize.BeginInit() { _isInitializing = true; } void ISupportInitialize.EndInit() { _isInitializing = false; if (ContainerControl != null) { InitializeAllControls(ContainerControl.Controls); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.Tracing; using Xunit; using System; using System.Collections.Generic; using System.Diagnostics; using System.Text.RegularExpressions; using System.Threading; namespace BasicEventSourceTests { /// <summary> /// Tests the user experience for common user errors. /// </summary> public class TestsUserErrors { /// <summary> /// Try to pass a user defined class (even with EventData) /// to a manifest based eventSource /// </summary> [Fact] public void Test_BadTypes_Manifest_UserClass() { var badEventSource = new BadEventSource_Bad_Type_UserClass(); Test_BadTypes_Manifest(badEventSource); } private void Test_BadTypes_Manifest(EventSource source) { try { var listener = new EventListenerListener(); var events = new List<Event>(); Debug.WriteLine("Adding delegate to onevent"); listener.OnEvent = delegate (Event data) { events.Add(data); }; listener.EventSourceCommand(source.Name, EventCommand.Enable); listener.Dispose(); // Confirm that we get exactly one event from this whole process, that has the error message we expect. Assert.Equal(events.Count, 1); Event _event = events[0]; Assert.Equal("EventSourceMessage", _event.EventName); string message = _event.PayloadString(0, "message"); // expected message: "ERROR: Exception in Command Processing for EventSource BadEventSource_Bad_Type_ByteArray: Unsupported type Byte[] in event source. " Assert.True(Regex.IsMatch(message, "Unsupported type")); } finally { source.Dispose(); } } /// <summary> /// Test the /// </summary> [Fact] public void Test_BadEventSource_MismatchedIds() { #if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864. // We expect only one session to be on when running the test but if a ETW session was left // hanging, it will confuse the EventListener tests. EtwListener.EnsureStopped(); #endif // USE_ETW TestUtilities.CheckNoEventSourcesRunning("Start"); var onStartups = new bool[] { false, true }; var listenerGenerators = new Func<Listener>[] { () => new EventListenerListener(), #if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864. () => new EtwListener() #endif // USE_ETW }; var settings = new EventSourceSettings[] { EventSourceSettings.Default, EventSourceSettings.EtwSelfDescribingEventFormat }; // For every interesting combination, run the test and see that we get a nice failure message. foreach (bool onStartup in onStartups) { foreach (Func<Listener> listenerGenerator in listenerGenerators) { foreach (EventSourceSettings setting in settings) { Test_Bad_EventSource_Startup(onStartup, listenerGenerator(), setting); } } } TestUtilities.CheckNoEventSourcesRunning("Stop"); } /// <summary> /// A helper that can run the test under a variety of conditions /// * Whether the eventSource is enabled at startup /// * Whether the listener is ETW or an EventListern /// * Whether the ETW output is self describing or not. /// </summary> private void Test_Bad_EventSource_Startup(bool onStartup, Listener listener, EventSourceSettings settings) { var eventSourceName = typeof(BadEventSource_MismatchedIds).Name; Debug.WriteLine("***** Test_BadEventSource_Startup(OnStartUp: " + onStartup + " Listener: " + listener + " Settings: " + settings + ")"); // Activate the source before the source exists (if told to). if (onStartup) listener.EventSourceCommand(eventSourceName, EventCommand.Enable); var events = new List<Event>(); listener.OnEvent = delegate (Event data) { events.Add(data); }; using (var source = new BadEventSource_MismatchedIds(settings)) { Assert.Equal(eventSourceName, source.Name); // activate the source after the source exists (if told to). if (!onStartup) listener.EventSourceCommand(eventSourceName, EventCommand.Enable); source.Event1(1); // Try to send something. } listener.Dispose(); // Confirm that we get exactly one event from this whole process, that has the error message we expect. Assert.Equal(events.Count, 1); Event _event = events[0]; Assert.Equal("EventSourceMessage", _event.EventName); string message = _event.PayloadString(0, "message"); Debug.WriteLine(String.Format("Message=\"{0}\"", message)); // expected message: "ERROR: Exception in Command Processing for EventSource BadEventSource_MismatchedIds: Event Event2 is given event ID 2 but 1 was passed to WriteEvent. " Assert.True(Regex.IsMatch(message, "Event Event2 is givien event ID 2 but 1 was passed to WriteEvent")); } [Fact] public void Test_Bad_WriteRelatedID_ParameterName() { #if true Debug.WriteLine("Test disabled because the fix it tests is not in CoreCLR yet."); #else BadEventSource_IncorrectWriteRelatedActivityIDFirstParameter bes = null; EventListenerListener listener = null; try { Guid oldGuid; Guid newGuid = Guid.NewGuid(); Guid newGuid2 = Guid.NewGuid(); EventSource.SetCurrentThreadActivityId(newGuid, out oldGuid); bes = new BadEventSource_IncorrectWriteRelatedActivityIDFirstParameter(); listener = new EventListenerListener(); var events = new List<Event>(); listener.OnEvent = delegate (Event data) { events.Add(data); }; listener.EventSourceCommand(bes.Name, EventCommand.Enable); bes.RelatedActivity(newGuid2, "Hello", 42, "AA", "BB"); // Confirm that we get exactly one event from this whole process, that has the error message we expect. Assert.Equal(events.Count, 1); Event _event = events[0]; Assert.Equal("EventSourceMessage", _event.EventName); string message = _event.PayloadString(0, "message"); // expected message: "EventSource expects the first parameter of the Event method to be of type Guid and to be named "relatedActivityId" when calling WriteEventWithRelatedActivityId." Assert.True(Regex.IsMatch(message, "EventSource expects the first parameter of the Event method to be of type Guid and to be named \"relatedActivityId\" when calling WriteEventWithRelatedActivityId.")); } finally { if (bes != null) { bes.Dispose(); } if (listener != null) { listener.Dispose(); } } #endif } } /// <summary> /// This EventSource has a common user error, and we want to make sure EventSource /// gives a reasonable experience in that case. /// </summary> internal class BadEventSource_MismatchedIds : EventSource { public BadEventSource_MismatchedIds(EventSourceSettings settings) : base(settings) { } public void Event1(int arg) { WriteEvent(1, arg); } // Error Used the same event ID for this event. public void Event2(int arg) { WriteEvent(1, arg); } } /// <summary> /// A manifest based provider with a bad type byte[] /// </summary> internal class BadEventSource_Bad_Type_ByteArray : EventSource { public void Event1(byte[] myArray) { WriteEvent(1, myArray); } } public sealed class BadEventSource_IncorrectWriteRelatedActivityIDFirstParameter : EventSource { public void E2() { this.Write("sampleevent", new { a = "a string" }); } [Event(7, Keywords = Keywords.Debug, Message = "Hello Message 7", Channel = EventChannel.Admin, Opcode = EventOpcode.Send)] public void RelatedActivity(Guid guid, string message, int value, string componentName, string instanceId) { WriteEventWithRelatedActivityId(7, guid, message, value, componentName, instanceId); } public class Keywords { public const EventKeywords Debug = (EventKeywords)0x0002; } } [EventData] public class UserClass { public int i; }; /// <summary> /// A manifest based provider with a bad type (only supported in self describing) /// </summary> internal class BadEventSource_Bad_Type_UserClass : EventSource { public void Event1(UserClass myClass) { WriteEvent(1, myClass); } } }
// 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.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.CodeFixes.FullyQualify; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.FullyQualify { public class FullyQualifyTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpFullyQualifyCodeFixProvider()); protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions) => FlattenActions(actions); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestTypeFromMultipleNamespaces1() { await TestInRegularAndScriptAsync( @"class Class { [|IDictionary|] Method() { Foo(); } }", @"class Class { System.Collections.IDictionary Method() { Foo(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestTypeFromMultipleNamespaces2() { await TestInRegularAndScriptAsync( @"class Class { [|IDictionary|] Method() { Foo(); } }", @"class Class { System.Collections.Generic.IDictionary Method() { Foo(); } }", index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestGenericWithNoArgs() { await TestInRegularAndScriptAsync( @"class Class { [|List|] Method() { Foo(); } }", @"class Class { System.Collections.Generic.List Method() { Foo(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestGenericWithCorrectArgs() { await TestInRegularAndScriptAsync( @"class Class { [|List<int>|] Method() { Foo(); } }", @"class Class { System.Collections.Generic.List<int> Method() { Foo(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestSmartTagDisplayText() { await TestSmartTagTextAsync( @"class Class { [|List<int>|] Method() { Foo(); } }", "System.Collections.Generic.List"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestGenericWithWrongArgs() { await TestMissingInRegularAndScriptAsync( @"class Class { [|List<int, string>|] Method() { Foo(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestGenericInLocalDeclaration() { await TestInRegularAndScriptAsync( @"class Class { void Foo() { [|List<int>|] a = new List<int>(); } }", @"class Class { void Foo() { System.Collections.Generic.List<int> a = new List<int>(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestGenericItemType() { await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class Class { List<[|Int32|]> l; }", @"using System.Collections.Generic; class Class { List<System.Int32> l; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestGenerateWithExistingUsings() { await TestInRegularAndScriptAsync( @"using System; class Class { [|List<int>|] Method() { Foo(); } }", @"using System; class Class { System.Collections.Generic.List<int> Method() { Foo(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestGenerateInNamespace() { await TestInRegularAndScriptAsync( @"namespace N { class Class { [|List<int>|] Method() { Foo(); } } }", @"namespace N { class Class { System.Collections.Generic.List<int> Method() { Foo(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestGenerateInNamespaceWithUsings() { await TestInRegularAndScriptAsync( @"namespace N { using System; class Class { [|List<int>|] Method() { Foo(); } } }", @"namespace N { using System; class Class { System.Collections.Generic.List<int> Method() { Foo(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestExistingUsing() { await TestActionCountAsync( @"using System.Collections.Generic; class Class { [|IDictionary|] Method() { Foo(); } }", count: 2); await TestInRegularAndScriptAsync( @"using System.Collections.Generic; class Class { [|IDictionary|] Method() { Foo(); } }", @"using System.Collections.Generic; class Class { System.Collections.IDictionary Method() { Foo(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestMissingIfUniquelyBound() { await TestMissingInRegularAndScriptAsync( @"using System; class Class { [|String|] Method() { Foo(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestMissingIfUniquelyBoundGeneric() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; class Class { [|List<int>|] Method() { Foo(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestOnEnum() { await TestInRegularAndScriptAsync( @"class Class { void Foo() { var a = [|Colors|].Red; } } namespace A { enum Colors { Red, Green, Blue } }", @"class Class { void Foo() { var a = A.Colors.Red; } } namespace A { enum Colors { Red, Green, Blue } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestOnClassInheritance() { await TestInRegularAndScriptAsync( @"class Class : [|Class2|] { } namespace A { class Class2 { } }", @"class Class : A.Class2 { } namespace A { class Class2 { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestOnImplementedInterface() { await TestInRegularAndScriptAsync( @"class Class : [|IFoo|] { } namespace A { interface IFoo { } }", @"class Class : A.IFoo { } namespace A { interface IFoo { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestAllInBaseList() { await TestInRegularAndScriptAsync( @"class Class : [|IFoo|], Class2 { } namespace A { class Class2 { } } namespace B { interface IFoo { } }", @"class Class : B.IFoo, Class2 { } namespace A { class Class2 { } } namespace B { interface IFoo { } }"); await TestInRegularAndScriptAsync( @"class Class : B.IFoo, [|Class2|] { } namespace A { class Class2 { } } namespace B { interface IFoo { } }", @"class Class : B.IFoo, A.Class2 { } namespace A { class Class2 { } } namespace B { interface IFoo { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestAttributeUnexpanded() { await TestInRegularAndScriptAsync( @"[[|Obsolete|]] class Class { }", @"[System.Obsolete] class Class { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestAttributeExpanded() { await TestInRegularAndScriptAsync( @"[[|ObsoleteAttribute|]] class Class { }", @"[System.ObsoleteAttribute] class Class { }"); } [WorkItem(527360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527360")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestExtensionMethods() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; class Foo { void Bar() { var values = new List<int>() { 1, 2, 3 }; values.[|Where|](i => i > 1); } }"); } [WorkItem(538018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538018")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestAfterNew() { await TestInRegularAndScriptAsync( @"class Class { void Foo() { List<int> l; l = new [|List<int>|](); } }", @"class Class { void Foo() { List<int> l; l = new System.Collections.Generic.List<int>(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestArgumentsInMethodCall() { await TestInRegularAndScriptAsync( @"class Class { void Test() { Console.WriteLine([|DateTime|].Today); } }", @"class Class { void Test() { Console.WriteLine(System.DateTime.Today); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestCallSiteArgs() { await TestInRegularAndScriptAsync( @"class Class { void Test([|DateTime|] dt) { } }", @"class Class { void Test(System.DateTime dt) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestUsePartialClass() { await TestInRegularAndScriptAsync( @"namespace A { public class Class { [|PClass|] c; } } namespace B { public partial class PClass { } }", @"namespace A { public class Class { B.PClass c; } } namespace B { public partial class PClass { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestGenericClassInNestedNamespace() { await TestInRegularAndScriptAsync( @"namespace A { namespace B { class GenericClass<T> { } } } namespace C { class Class { [|GenericClass<int>|] c; } }", @"namespace A { namespace B { class GenericClass<T> { } } } namespace C { class Class { A.B.GenericClass<int> c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestBeforeStaticMethod() { await TestInRegularAndScriptAsync( @"class Class { void Test() { [|Math|].Sqrt(); }", @"class Class { void Test() { System.Math.Sqrt(); }"); } [WorkItem(538136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538136")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestBeforeNamespace() { await TestInRegularAndScriptAsync( @"namespace A { class Class { [|C|].Test t; } } namespace B { namespace C { class Test { } } }", @"namespace A { class Class { B.C.Test t; } } namespace B { namespace C { class Test { } } }"); } [WorkItem(527395, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527395")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestSimpleNameWithLeadingTrivia() { await TestInRegularAndScriptAsync( @"class Class { void Test() { /*foo*/[|Int32|] i; } }", @"class Class { void Test() { /*foo*/System.Int32 i; } }", ignoreTrivia: false); } [WorkItem(527395, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527395")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestGenericNameWithLeadingTrivia() { await TestInRegularAndScriptAsync( @"class Class { void Test() { /*foo*/[|List<int>|] l; } }", @"class Class { void Test() { /*foo*/System.Collections.Generic.List<int> l; } }", ignoreTrivia: false); } [WorkItem(538740, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538740")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestFullyQualifyTypeName() { await TestInRegularAndScriptAsync( @"public class Program { public class Inner { } } class Test { [|Inner|] i; }", @"public class Program { public class Inner { } } class Test { Program.Inner i; }"); } [WorkItem(538740, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538740")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestFullyQualifyTypeName_NotForGenericType() { await TestMissingInRegularAndScriptAsync( @"class Program<T> { public class Inner { } } class Test { [|Inner|] i; }"); } [WorkItem(538764, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538764")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestFullyQualifyThroughAlias() { await TestInRegularAndScriptAsync( @"using Alias = System; class C { [|Int32|] i; }", @"using Alias = System; class C { Alias.Int32 i; }"); } [WorkItem(538763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538763")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestFullyQualifyPrioritizeTypesOverNamespaces1() { await TestInRegularAndScriptAsync( @"namespace Outer { namespace C { class C { } } } class Test { [|C|] c; }", @"namespace Outer { namespace C { class C { } } } class Test { Outer.C.C c; }"); } [WorkItem(538763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538763")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestFullyQualifyPrioritizeTypesOverNamespaces2() { await TestInRegularAndScriptAsync( @"namespace Outer { namespace C { class C { } } } class Test { [|C|] c; }", @"namespace Outer { namespace C { class C { } } } class Test { Outer.C c; }", index: 1); } [WorkItem(539853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539853")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task BugFix5950() { await TestAsync( @"using System.Console; WriteLine([|Expression|].Constant(123));", @"using System.Console; WriteLine(System.Linq.Expressions.Expression.Constant(123));", parseOptions: GetScriptOptions()); } [WorkItem(540318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540318")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestAfterAlias() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { System::[|Console|] :: WriteLine(""TEST""); } }"); } [WorkItem(540942, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540942")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestMissingOnIncompleteStatement() { await TestMissingInRegularAndScriptAsync( @"using System; using System.IO; class C { static void Main(string[] args) { [|Path|] } }"); } [WorkItem(542643, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542643")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestAssemblyAttribute() { await TestInRegularAndScriptAsync( @"[assembly: [|InternalsVisibleTo|](""Project"")]", @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Project"")]"); } [WorkItem(543388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543388")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestMissingOnAliasName() { await TestMissingInRegularAndScriptAsync( @"using [|GIBBERISH|] = Foo.GIBBERISH; class Program { static void Main(string[] args) { GIBBERISH x; } } namespace Foo { public class GIBBERISH { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestMissingOnAttributeOverloadResolutionError() { await TestMissingInRegularAndScriptAsync( @"using System.Runtime.InteropServices; class M { [[|DllImport|]()] static extern int? My(); }"); } [WorkItem(544950, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544950")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestNotOnAbstractConstructor() { await TestMissingInRegularAndScriptAsync( @"using System.IO; class Program { static void Main(string[] args) { var s = new [|Stream|](); } }"); } [WorkItem(545774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545774")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestAttribute() { var input = @"[ assembly : [|Guid|] ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] "; await TestActionCountAsync(input, 1); await TestInRegularAndScriptAsync( input, @"[assembly: System.Runtime.InteropServices.Guid(""9ed54f84-a89d-4fcd-a854-44251e925f09"")]"); } [WorkItem(546027, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546027")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TestGeneratePropertyFromAttribute() { await TestMissingInRegularAndScriptAsync( @"using System; [AttributeUsage(AttributeTargets.Class)] class MyAttrAttribute : Attribute { } [MyAttr(123, [|Version|] = 1)] class D { }"); } [WorkItem(775448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775448")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task ShouldTriggerOnCS0308() { // CS0308: The non-generic type 'A' cannot be used with type arguments await TestInRegularAndScriptAsync( @"using System.Collections; class Test { static void Main(string[] args) { [|IEnumerable<int>|] f; } }", @"using System.Collections; class Test { static void Main(string[] args) { System.Collections.Generic.IEnumerable<int> f; } }"); } [WorkItem(947579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947579")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task AmbiguousTypeFix() { await TestInRegularAndScriptAsync( @"using n1; using n2; class B { void M1() { [|var a = new A();|] } } namespace n1 { class A { } } namespace n2 { class A { } }", @"using n1; using n2; class B { void M1() { var a = new n1.A(); } } namespace n1 { class A { } } namespace n2 { class A { } }"); } [WorkItem(995857, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995857")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task NonPublicNamespaces() { await TestInRegularAndScriptAsync( @"namespace MS.Internal.Xaml { private class A { } } namespace System.Xaml { public class A { } } public class Program { static void M() { [|Xaml|] } }", @"namespace MS.Internal.Xaml { private class A { } } namespace System.Xaml { public class A { } } public class Program { static void M() { System.Xaml } }"); await TestInRegularAndScriptAsync( @"namespace MS.Internal.Xaml { public class A { } } namespace System.Xaml { public class A { } } public class Program { static void M() { [|Xaml|] } }", @"namespace MS.Internal.Xaml { public class A { } } namespace System.Xaml { public class A { } } public class Program { static void M() { MS.Internal.Xaml } }", index: 1); } [WorkItem(11071, "https://github.com/dotnet/roslyn/issues/11071")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task AmbiguousFixOrdering() { await TestInRegularAndScriptAsync( @"using n1; using n2; [[|Inner|].C] class B { } namespace n1 { namespace Inner { } } namespace n2 { namespace Inner { class CAttribute { } } }", @"using n1; using n2; [n2.Inner.C] class B { } namespace n1 { namespace Inner { } } namespace n2 { namespace Inner { class CAttribute { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TupleTest() { await TestInRegularAndScriptAsync( @"class Class { ([|IDictionary|], string) Method() { Foo(); } }", @"class Class { (System.Collections.IDictionary, string) Method() { Foo(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)] public async Task TupleWithOneName() { await TestInRegularAndScriptAsync( @"class Class { ([|IDictionary|] a, string) Method() { Foo(); } }", @"class Class { (System.Collections.IDictionary a, string) Method() { Foo(); } }"); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace East.Tool.UseCaseTranslator.WebAPI.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmCashTransactionItem { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmCashTransactionItem() : base() { Load += frmCashTransactionItem_Load; KeyPress += frmCashTransactionItem_KeyPress; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; public System.Windows.Forms.CheckBox _chkChannel_1; public System.Windows.Forms.CheckBox _chkChannel_2; public System.Windows.Forms.CheckBox _chkChannel_3; public System.Windows.Forms.CheckBox _chkChannel_4; public System.Windows.Forms.CheckBox _chkChannel_5; public System.Windows.Forms.CheckBox _chkChannel_6; public System.Windows.Forms.CheckBox _chkChannel_7; public System.Windows.Forms.CheckBox _chkChannel_8; public System.Windows.Forms.CheckBox _chkChannel_9; public System.Windows.Forms.CheckBox _chkType_2; public System.Windows.Forms.CheckBox _chkType_1; public System.Windows.Forms.CheckBox _chkType_0; private System.Windows.Forms.TextBox withEventsField_txtPrice; public System.Windows.Forms.TextBox txtPrice { get { return withEventsField_txtPrice; } set { if (withEventsField_txtPrice != null) { withEventsField_txtPrice.Enter -= txtPrice_Enter; withEventsField_txtPrice.KeyPress -= txtPrice_KeyPress; withEventsField_txtPrice.Leave -= txtPrice_Leave; } withEventsField_txtPrice = value; if (withEventsField_txtPrice != null) { withEventsField_txtPrice.Enter += txtPrice_Enter; withEventsField_txtPrice.KeyPress += txtPrice_KeyPress; withEventsField_txtPrice.Leave += txtPrice_Leave; } } } public System.Windows.Forms.ComboBox cmbQuantity; private System.Windows.Forms.Button withEventsField_cmdClose; public System.Windows.Forms.Button cmdClose { get { return withEventsField_cmdClose; } set { if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click -= cmdClose_Click; } withEventsField_cmdClose = value; if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click += cmdClose_Click; } } } public System.Windows.Forms.Panel picButtons; public System.Windows.Forms.Label _lbl_4; public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_0; public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_1; public System.Windows.Forms.Label _lbl_0; public System.Windows.Forms.Label _lbl_3; public System.Windows.Forms.Label _lbl_2; public System.Windows.Forms.Label _lbl_1; public System.Windows.Forms.Label lblStockItem; //Public WithEvents chkChannel As Microsoft.VisualBasic.Compatibility.VB6.CheckBoxArray //Public WithEvents chkType As Microsoft.VisualBasic.Compatibility.VB6.CheckBoxArray //Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray public RectangleShapeArray Shape1; public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer1; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(this.components); this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer(); this._Shape1_0 = new Microsoft.VisualBasic.PowerPacks.RectangleShape(); this._Shape1_1 = new Microsoft.VisualBasic.PowerPacks.RectangleShape(); this._chkChannel_1 = new System.Windows.Forms.CheckBox(); this._chkChannel_2 = new System.Windows.Forms.CheckBox(); this._chkChannel_3 = new System.Windows.Forms.CheckBox(); this._chkChannel_4 = new System.Windows.Forms.CheckBox(); this._chkChannel_5 = new System.Windows.Forms.CheckBox(); this._chkChannel_6 = new System.Windows.Forms.CheckBox(); this._chkChannel_7 = new System.Windows.Forms.CheckBox(); this._chkChannel_8 = new System.Windows.Forms.CheckBox(); this._chkChannel_9 = new System.Windows.Forms.CheckBox(); this._chkType_2 = new System.Windows.Forms.CheckBox(); this._chkType_1 = new System.Windows.Forms.CheckBox(); this._chkType_0 = new System.Windows.Forms.CheckBox(); this.txtPrice = new System.Windows.Forms.TextBox(); this.cmbQuantity = new System.Windows.Forms.ComboBox(); this.picButtons = new System.Windows.Forms.Panel(); this.cmdClose = new System.Windows.Forms.Button(); this._lbl_4 = new System.Windows.Forms.Label(); this._lbl_0 = new System.Windows.Forms.Label(); this._lbl_3 = new System.Windows.Forms.Label(); this._lbl_2 = new System.Windows.Forms.Label(); this._lbl_1 = new System.Windows.Forms.Label(); this.lblStockItem = new System.Windows.Forms.Label(); this.Shape1 = new _4PosBackOffice.NET.RectangleShapeArray(this.components); this.picButtons.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)this.Shape1).BeginInit(); this.SuspendLayout(); // //ShapeContainer1 // this.ShapeContainer1.Location = new System.Drawing.Point(0, 0); this.ShapeContainer1.Margin = new System.Windows.Forms.Padding(0); this.ShapeContainer1.Name = "ShapeContainer1"; this.ShapeContainer1.Shapes.AddRange(new Microsoft.VisualBasic.PowerPacks.Shape[] { this._Shape1_0, this._Shape1_1 }); this.ShapeContainer1.Size = new System.Drawing.Size(465, 311); this.ShapeContainer1.TabIndex = 21; this.ShapeContainer1.TabStop = false; // //_Shape1_0 // this._Shape1_0.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255))); this._Shape1_0.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque; this._Shape1_0.BorderColor = System.Drawing.SystemColors.WindowText; this._Shape1_0.FillColor = System.Drawing.Color.Black; this.Shape1.SetIndex(this._Shape1_0, Convert.ToInt16(0)); this._Shape1_0.Location = new System.Drawing.Point(3, 190); this._Shape1_0.Name = "_Shape1_0"; this._Shape1_0.Size = new System.Drawing.Size(196, 81); // //_Shape1_1 // this._Shape1_1.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255))); this._Shape1_1.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque; this._Shape1_1.BorderColor = System.Drawing.SystemColors.WindowText; this._Shape1_1.FillColor = System.Drawing.Color.Black; this.Shape1.SetIndex(this._Shape1_1, Convert.ToInt16(1)); this._Shape1_1.Location = new System.Drawing.Point(204, 111); this._Shape1_1.Name = "_Shape1_1"; this._Shape1_1.Size = new System.Drawing.Size(181, 186); // //_chkChannel_1 // this._chkChannel_1.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255))); this._chkChannel_1.Cursor = System.Windows.Forms.Cursors.Default; this._chkChannel_1.ForeColor = System.Drawing.SystemColors.ControlText; this._chkChannel_1.Location = new System.Drawing.Point(216, 115); this._chkChannel_1.Name = "_chkChannel_1"; this._chkChannel_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._chkChannel_1.Size = new System.Drawing.Size(166, 23); this._chkChannel_1.TabIndex = 11; this._chkChannel_1.Text = "1. POS"; this._chkChannel_1.UseVisualStyleBackColor = false; // //_chkChannel_2 // this._chkChannel_2.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255))); this._chkChannel_2.Cursor = System.Windows.Forms.Cursors.Default; this._chkChannel_2.ForeColor = System.Drawing.SystemColors.ControlText; this._chkChannel_2.Location = new System.Drawing.Point(216, 135); this._chkChannel_2.Name = "_chkChannel_2"; this._chkChannel_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._chkChannel_2.Size = new System.Drawing.Size(166, 19); this._chkChannel_2.TabIndex = 12; this._chkChannel_2.Text = "1. POS"; this._chkChannel_2.UseVisualStyleBackColor = false; // //_chkChannel_3 // this._chkChannel_3.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255))); this._chkChannel_3.Cursor = System.Windows.Forms.Cursors.Default; this._chkChannel_3.ForeColor = System.Drawing.SystemColors.ControlText; this._chkChannel_3.Location = new System.Drawing.Point(216, 155); this._chkChannel_3.Name = "_chkChannel_3"; this._chkChannel_3.RightToLeft = System.Windows.Forms.RightToLeft.No; this._chkChannel_3.Size = new System.Drawing.Size(166, 16); this._chkChannel_3.TabIndex = 13; this._chkChannel_3.Text = "1. POS"; this._chkChannel_3.UseVisualStyleBackColor = false; // //_chkChannel_4 // this._chkChannel_4.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255))); this._chkChannel_4.Cursor = System.Windows.Forms.Cursors.Default; this._chkChannel_4.ForeColor = System.Drawing.SystemColors.ControlText; this._chkChannel_4.Location = new System.Drawing.Point(216, 176); this._chkChannel_4.Name = "_chkChannel_4"; this._chkChannel_4.RightToLeft = System.Windows.Forms.RightToLeft.No; this._chkChannel_4.Size = new System.Drawing.Size(166, 16); this._chkChannel_4.TabIndex = 14; this._chkChannel_4.Text = "1. POS"; this._chkChannel_4.UseVisualStyleBackColor = false; // //_chkChannel_5 // this._chkChannel_5.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255))); this._chkChannel_5.Cursor = System.Windows.Forms.Cursors.Default; this._chkChannel_5.ForeColor = System.Drawing.SystemColors.ControlText; this._chkChannel_5.Location = new System.Drawing.Point(216, 198); this._chkChannel_5.Name = "_chkChannel_5"; this._chkChannel_5.RightToLeft = System.Windows.Forms.RightToLeft.No; this._chkChannel_5.Size = new System.Drawing.Size(166, 16); this._chkChannel_5.TabIndex = 15; this._chkChannel_5.Text = "1. POS"; this._chkChannel_5.UseVisualStyleBackColor = false; // //_chkChannel_6 // this._chkChannel_6.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255))); this._chkChannel_6.Cursor = System.Windows.Forms.Cursors.Default; this._chkChannel_6.ForeColor = System.Drawing.SystemColors.ControlText; this._chkChannel_6.Location = new System.Drawing.Point(216, 218); this._chkChannel_6.Name = "_chkChannel_6"; this._chkChannel_6.RightToLeft = System.Windows.Forms.RightToLeft.No; this._chkChannel_6.Size = new System.Drawing.Size(166, 17); this._chkChannel_6.TabIndex = 16; this._chkChannel_6.Text = "1. POS"; this._chkChannel_6.UseVisualStyleBackColor = false; // //_chkChannel_7 // this._chkChannel_7.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255))); this._chkChannel_7.Cursor = System.Windows.Forms.Cursors.Default; this._chkChannel_7.ForeColor = System.Drawing.SystemColors.ControlText; this._chkChannel_7.Location = new System.Drawing.Point(216, 240); this._chkChannel_7.Name = "_chkChannel_7"; this._chkChannel_7.RightToLeft = System.Windows.Forms.RightToLeft.No; this._chkChannel_7.Size = new System.Drawing.Size(166, 16); this._chkChannel_7.TabIndex = 17; this._chkChannel_7.Text = "1. POS"; this._chkChannel_7.UseVisualStyleBackColor = false; // //_chkChannel_8 // this._chkChannel_8.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255))); this._chkChannel_8.Cursor = System.Windows.Forms.Cursors.Default; this._chkChannel_8.ForeColor = System.Drawing.SystemColors.ControlText; this._chkChannel_8.Location = new System.Drawing.Point(216, 260); this._chkChannel_8.Name = "_chkChannel_8"; this._chkChannel_8.RightToLeft = System.Windows.Forms.RightToLeft.No; this._chkChannel_8.Size = new System.Drawing.Size(166, 16); this._chkChannel_8.TabIndex = 18; this._chkChannel_8.Text = "1. POS"; this._chkChannel_8.UseVisualStyleBackColor = false; // //_chkChannel_9 // this._chkChannel_9.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255))); this._chkChannel_9.Cursor = System.Windows.Forms.Cursors.Default; this._chkChannel_9.ForeColor = System.Drawing.SystemColors.ControlText; this._chkChannel_9.Location = new System.Drawing.Point(216, 278); this._chkChannel_9.Name = "_chkChannel_9"; this._chkChannel_9.RightToLeft = System.Windows.Forms.RightToLeft.No; this._chkChannel_9.Size = new System.Drawing.Size(166, 20); this._chkChannel_9.TabIndex = 19; this._chkChannel_9.Text = "1. POS"; this._chkChannel_9.UseVisualStyleBackColor = false; // //_chkType_2 // this._chkType_2.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255))); this._chkType_2.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this._chkType_2.Checked = true; this._chkType_2.CheckState = System.Windows.Forms.CheckState.Checked; this._chkType_2.Cursor = System.Windows.Forms.Cursors.Default; this._chkType_2.ForeColor = System.Drawing.SystemColors.ControlText; this._chkType_2.Location = new System.Drawing.Point(6, 246); this._chkType_2.Name = "_chkType_2"; this._chkType_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._chkType_2.Size = new System.Drawing.Size(187, 19); this._chkType_2.TabIndex = 9; this._chkType_2.Text = "Not Valid for Cheque Payments"; this._chkType_2.UseVisualStyleBackColor = false; // //_chkType_1 // this._chkType_1.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255))); this._chkType_1.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this._chkType_1.Checked = true; this._chkType_1.CheckState = System.Windows.Forms.CheckState.Checked; this._chkType_1.Cursor = System.Windows.Forms.Cursors.Default; this._chkType_1.ForeColor = System.Drawing.SystemColors.ControlText; this._chkType_1.Location = new System.Drawing.Point(6, 223); this._chkType_1.Name = "_chkType_1"; this._chkType_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._chkType_1.Size = new System.Drawing.Size(187, 17); this._chkType_1.TabIndex = 8; this._chkType_1.Text = "Not Valid for Debit Cards Payments"; this._chkType_1.UseVisualStyleBackColor = false; // //_chkType_0 // this._chkType_0.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255))); this._chkType_0.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this._chkType_0.Checked = true; this._chkType_0.CheckState = System.Windows.Forms.CheckState.Checked; this._chkType_0.Cursor = System.Windows.Forms.Cursors.Default; this._chkType_0.ForeColor = System.Drawing.SystemColors.ControlText; this._chkType_0.Location = new System.Drawing.Point(6, 201); this._chkType_0.Name = "_chkType_0"; this._chkType_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._chkType_0.Size = new System.Drawing.Size(187, 21); this._chkType_0.TabIndex = 7; this._chkType_0.Text = "Not Valid for Credit Card Payments"; this._chkType_0.UseVisualStyleBackColor = false; // //txtPrice // this.txtPrice.AcceptsReturn = true; this.txtPrice.BackColor = System.Drawing.SystemColors.Window; this.txtPrice.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtPrice.ForeColor = System.Drawing.SystemColors.WindowText; this.txtPrice.Location = new System.Drawing.Point(111, 87); this.txtPrice.MaxLength = 0; this.txtPrice.Name = "txtPrice"; this.txtPrice.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtPrice.Size = new System.Drawing.Size(79, 19); this.txtPrice.TabIndex = 5; this.txtPrice.Text = "0.00"; this.txtPrice.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //cmbQuantity // this.cmbQuantity.BackColor = System.Drawing.SystemColors.Window; this.cmbQuantity.Cursor = System.Windows.Forms.Cursors.Default; this.cmbQuantity.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbQuantity.ForeColor = System.Drawing.SystemColors.WindowText; this.cmbQuantity.Location = new System.Drawing.Point(111, 63); this.cmbQuantity.Name = "cmbQuantity"; this.cmbQuantity.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmbQuantity.Size = new System.Drawing.Size(79, 21); this.cmbQuantity.TabIndex = 3; // //picButtons // this.picButtons.BackColor = System.Drawing.Color.Blue; this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.picButtons.Controls.Add(this.cmdClose); this.picButtons.Cursor = System.Windows.Forms.Cursors.Default; this.picButtons.Dock = System.Windows.Forms.DockStyle.Top; this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText; this.picButtons.Location = new System.Drawing.Point(0, 0); this.picButtons.Name = "picButtons"; this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No; this.picButtons.Size = new System.Drawing.Size(465, 39); this.picButtons.TabIndex = 20; // //cmdClose // this.cmdClose.BackColor = System.Drawing.SystemColors.Control; this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default; this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdClose.Location = new System.Drawing.Point(303, 3); this.cmdClose.Name = "cmdClose"; this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdClose.Size = new System.Drawing.Size(73, 29); this.cmdClose.TabIndex = 21; this.cmdClose.TabStop = false; this.cmdClose.Text = "E&xit"; this.cmdClose.UseVisualStyleBackColor = false; // //_lbl_4 // this._lbl_4.BackColor = System.Drawing.Color.Transparent; this._lbl_4.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_4.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_4.Location = new System.Drawing.Point(6, 155); this._lbl_4.Name = "_lbl_4"; this._lbl_4.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_4.Size = new System.Drawing.Size(189, 34); this._lbl_4.TabIndex = 6; this._lbl_4.Text = "This Cash Transaction does not apply to the following payment methods."; // //_lbl_0 // this._lbl_0.BackColor = System.Drawing.Color.Transparent; this._lbl_0.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_0.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_0.Location = new System.Drawing.Point(207, 63); this._lbl_0.Name = "_lbl_0"; this._lbl_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_0.Size = new System.Drawing.Size(177, 43); this._lbl_0.TabIndex = 10; this._lbl_0.Text = "Disabled this Cash Transaction for the following checked Sale Channels."; // //_lbl_3 // this._lbl_3.AutoSize = true; this._lbl_3.BackColor = System.Drawing.Color.Transparent; this._lbl_3.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_3.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_3.Location = new System.Drawing.Point(73, 90); this._lbl_3.Name = "_lbl_3"; this._lbl_3.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_3.Size = new System.Drawing.Size(34, 13); this._lbl_3.TabIndex = 4; this._lbl_3.Text = "Price:"; this._lbl_3.TextAlign = System.Drawing.ContentAlignment.TopRight; // //_lbl_2 // this._lbl_2.AutoSize = true; this._lbl_2.BackColor = System.Drawing.Color.Transparent; this._lbl_2.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_2.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_2.Location = new System.Drawing.Point(39, 66); this._lbl_2.Name = "_lbl_2"; this._lbl_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_2.Size = new System.Drawing.Size(63, 13); this._lbl_2.TabIndex = 2; this._lbl_2.Text = "Shrink Size:"; this._lbl_2.TextAlign = System.Drawing.ContentAlignment.TopRight; // //_lbl_1 // this._lbl_1.AutoSize = true; this._lbl_1.BackColor = System.Drawing.Color.Transparent; this._lbl_1.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_1.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_1.Location = new System.Drawing.Point(6, 45); this._lbl_1.Name = "_lbl_1"; this._lbl_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_1.Size = new System.Drawing.Size(92, 13); this._lbl_1.TabIndex = 0; this._lbl_1.Text = "Stock Item Name:"; this._lbl_1.TextAlign = System.Drawing.ContentAlignment.TopRight; // //lblStockItem // this.lblStockItem.BackColor = System.Drawing.SystemColors.Control; this.lblStockItem.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblStockItem.Cursor = System.Windows.Forms.Cursors.Default; this.lblStockItem.ForeColor = System.Drawing.SystemColors.ControlText; this.lblStockItem.Location = new System.Drawing.Point(111, 45); this.lblStockItem.Name = "lblStockItem"; this.lblStockItem.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblStockItem.Size = new System.Drawing.Size(274, 17); this.lblStockItem.TabIndex = 1; this.lblStockItem.Text = "Label1"; // //frmCashTransactionItem // this.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(224)), Convert.ToInt32(Convert.ToByte(224)), Convert.ToInt32(Convert.ToByte(224))); this.ClientSize = new System.Drawing.Size(465, 311); this.ControlBox = false; this.Controls.Add(this._chkChannel_1); this.Controls.Add(this._chkChannel_2); this.Controls.Add(this._chkChannel_3); this.Controls.Add(this._chkChannel_4); this.Controls.Add(this._chkChannel_5); this.Controls.Add(this._chkChannel_6); this.Controls.Add(this._chkChannel_7); this.Controls.Add(this._chkChannel_8); this.Controls.Add(this._chkChannel_9); this.Controls.Add(this._chkType_2); this.Controls.Add(this._chkType_1); this.Controls.Add(this._chkType_0); this.Controls.Add(this.txtPrice); this.Controls.Add(this.cmbQuantity); this.Controls.Add(this.picButtons); this.Controls.Add(this._lbl_4); this.Controls.Add(this._lbl_0); this.Controls.Add(this._lbl_3); this.Controls.Add(this._lbl_2); this.Controls.Add(this._lbl_1); this.Controls.Add(this.lblStockItem); this.Controls.Add(this.ShapeContainer1); this.Cursor = System.Windows.Forms.Cursors.Default; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.KeyPreview = true; this.Location = new System.Drawing.Point(3, 22); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "frmCashTransactionItem"; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Edit a Cash Transaction Item"; this.picButtons.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)this.Shape1).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace ApplicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// VirtualNetworkGatewayConnectionsOperations operations. /// </summary> public partial interface IVirtualNetworkGatewayConnectionsOperations { /// <summary> /// Creates or updates a virtual network gateway connection in the /// specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update virtual network gateway /// connection operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<VirtualNetworkGatewayConnection>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnection parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the specified virtual network gateway connection by resource /// group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<VirtualNetworkGatewayConnection>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the specified virtual network Gateway connection. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The Put VirtualNetworkGatewayConnectionSharedKey operation sets the /// virtual network gateway connection shared key for passed virtual /// network gateway connection in the specified resource group through /// Network resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection name. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Set Virtual Network Gateway /// connection Shared key operation throughNetwork resource provider. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ConnectionSharedKey>> SetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The Get VirtualNetworkGatewayConnectionSharedKey operation /// retrieves information about the specified virtual network gateway /// connection shared key through Network resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection shared key name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ConnectionSharedKey>> GetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The List VirtualNetworkGatewayConnections operation retrieves all /// the virtual network gateways connections created. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<VirtualNetworkGatewayConnection>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The VirtualNetworkGatewayConnectionResetSharedKey operation resets /// the virtual network gateway connection shared key for passed /// virtual network gateway connection in the specified resource group /// through Network resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection reset shared key Name. /// </param> /// <param name='parameters'> /// Parameters supplied to the begin reset virtual network gateway /// connection shared key operation through network resource provider. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ConnectionResetSharedKey>> ResetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a virtual network gateway connection in the /// specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update virtual network gateway /// connection operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<VirtualNetworkGatewayConnection>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnection parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the specified virtual network Gateway connection. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The Put VirtualNetworkGatewayConnectionSharedKey operation sets the /// virtual network gateway connection shared key for passed virtual /// network gateway connection in the specified resource group through /// Network resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection name. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Set Virtual Network Gateway /// connection Shared key operation throughNetwork resource provider. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ConnectionSharedKey>> BeginSetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The VirtualNetworkGatewayConnectionResetSharedKey operation resets /// the virtual network gateway connection shared key for passed /// virtual network gateway connection in the specified resource group /// through Network resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection reset shared key Name. /// </param> /// <param name='parameters'> /// Parameters supplied to the begin reset virtual network gateway /// connection shared key operation through network resource provider. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ConnectionResetSharedKey>> BeginResetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The List VirtualNetworkGatewayConnections operation retrieves all /// the virtual network gateways connections created. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<VirtualNetworkGatewayConnection>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using OpenLiveWriter.Api.Sidebar; using OpenLiveWriter.Api.ImageEditing; using OpenLiveWriter.PostEditor.PostHtmlEditing.Commands; using OpenLiveWriter.PostEditor.PostHtmlEditing.ImageEditing.Decorators; using OpenLiveWriter.ApplicationFramework; using OpenLiveWriter.ApplicationFramework.ApplicationStyles; namespace OpenLiveWriter.PostEditor.PostHtmlEditing { /// <summary> /// Hosts the tab control for the image property editing form. /// </summary> public class ImagePropertyEditorControl : PrimaryWorkspaceControl { /// <summary> /// Required designer variable. /// </summary> private Container components = null; private PrimaryWorkspaceWorkspaceCommandBarLightweightControl commandBarLightweightControl; private TabLightweightControl tabLightweightControl; private ImageTabPageImageControl imageTabPageImage; private ImageTabPageLayoutControl imageTabPageLayout; private ImageTabPageEffectsControl imageTabPageEffects; private ImageTabPageUploadControl imageTabPageUpload; public ImagePropertyEditorControl() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // configure look and behavior AllowDragDropAutoScroll = false; AllPaintingInWmPaint = true; TopLayoutMargin = 2; ApplicationStyleManager.ApplicationStyleChanged += new EventHandler(ApplicationManager_ApplicationStyleChanged); // initialize tab lightweight control tabLightweightControl = new TabLightweightControl(this.components) ; tabLightweightControl.DrawSideAndBottomTabPageBorders = false ; tabLightweightControl.SmallTabs = true ; } public void Init(IBlogPostImageDataContext dataContext) { _imageDataContext = dataContext; // initialization constants const int TOP_INSET = 2; imageTabPageImage = new ImageTabPageImageControl() ; imageTabPageLayout = new ImageTabPageLayoutControl() ; imageTabPageEffects = new ImageTabPageEffectsControl() ; imageTabPageUpload = new ImageTabPageUploadControl() ; _tabPages = new ImageEditingTabPageControl[]{imageTabPageLayout, imageTabPageImage, imageTabPageEffects, imageTabPageUpload}; for(int i=0; i<_tabPages.Length; i++) { ImageEditingTabPageControl tabPage = _tabPages[i]; tabPage.DecoratorsManager = dataContext.DecoratorsManager; tabPage.TabStop = false ; tabPage.TabIndex = i ; Controls.Add( tabPage ) ; tabLightweightControl.SetTab( i, tabPage ) ; } // initial appearance of editor tabLightweightControl.SelectedTabNumber = 0 ; InitializeCommands(); InitializeToolbar(); _imageDataContext.DecoratorsManager.GetImageDecorator(BrightnessDecorator.Id).Command.StateChanged += new EventHandler(Command_StateChanged); // configure primary workspace // configure primary workspace SuspendLayout() ; TopLayoutMargin = TOP_INSET; LeftColumn.UpperPane.LightweightControl = tabLightweightControl; CenterColumn.Visible = false; RightColumn.Visible = false; ResumeLayout() ; } IBlogPostImageDataContext _imageDataContext; private void InitializeCommands() { commandContextManager = new CommandContextManager(ApplicationManager.CommandManager); commandContextManager.BeginUpdate() ; commandImageBrightness = new CommandImageBrightness(components) ; commandImageBrightness.Tag = _imageDataContext.DecoratorsManager.GetImageDecorator(BrightnessDecorator.Id); commandImageBrightness.Execute += new EventHandler(commandImageDecorator_Execute); commandContextManager.AddCommand( commandImageBrightness, CommandContext.Normal) ; commandImageRotate = new CommandImageRotate(components) ; commandImageRotate.Execute += new EventHandler(commandImageRotate_Execute); commandContextManager.AddCommand( commandImageRotate, CommandContext.Normal) ; commandImageReset = new CommandImageReset(components) ; commandImageReset.Execute += new EventHandler(commandImageReset_Execute); commandContextManager.AddCommand( commandImageReset, CommandContext.Normal) ; commandImageSaveDefaults = new CommandImageSaveDefaults(components) ; commandImageSaveDefaults.Execute += new EventHandler(commandImageSaveDefaults_Execute); commandContextManager.AddCommand( commandImageSaveDefaults, CommandContext.Normal) ; commandContextManager.EndUpdate() ; } CommandContextManager commandContextManager; Command commandImageBrightness; Command commandImageRotate; Command commandImageReset; Command commandImageSaveDefaults; private void InitializeToolbar() { CommandBarButtonEntry commandBarButtonEntryImageBrightness = new CommandBarButtonEntry(components) ; commandBarButtonEntryImageBrightness.CommandIdentifier = commandImageBrightness.Identifier ; CommandBarButtonEntry commandBarButtonEntryImageRotate = new CommandBarButtonEntry(components) ; commandBarButtonEntryImageRotate.CommandIdentifier = commandImageRotate.Identifier ; CommandBarButtonEntry commandBarButtonEntryImageReset = new CommandBarButtonEntry(components) ; commandBarButtonEntryImageReset.CommandIdentifier = commandImageReset.Identifier ; CommandBarButtonEntry commandBarButtonEntryImageSaveDefaults = new CommandBarButtonEntry(components) ; commandBarButtonEntryImageSaveDefaults.CommandIdentifier = commandImageSaveDefaults.Identifier ; CommandBarDefinition commandBarDefinition = new CommandBarDefinition(components) ; commandBarDefinition.LeftCommandBarEntries.Add( commandBarButtonEntryImageRotate ) ; commandBarDefinition.LeftCommandBarEntries.Add( commandBarButtonEntryImageBrightness ) ; commandBarDefinition.RightCommandBarEntries.Add( commandBarButtonEntryImageReset ) ; commandBarDefinition.RightCommandBarEntries.Add( commandBarButtonEntryImageSaveDefaults ) ; commandBarLightweightControl = new PrimaryWorkspaceWorkspaceCommandBarLightweightControl(components) ; commandBarLightweightControl.LightweightControlContainerControl = this ; commandBarLightweightControl.CommandManager = ApplicationManager.CommandManager ; commandBarLightweightControl.CommandBarDefinition = commandBarDefinition ; } public override CommandBarLightweightControl FirstCommandBarLightweightControl { get { return commandBarLightweightControl; } } public event EventHandler SaveDefaultsRequested; public event EventHandler ResetToDefaultsRequested; public event ImagePropertyEventHandler ImagePropertyChanged; private void ApplyImageDecorations() { ApplyImageDecorations(ImageDecoratorInvocationSource.ImagePropertiesEditor); } private void ApplyImageDecorations(ImageDecoratorInvocationSource source) { if(ImagePropertyChanged != null) { ImagePropertyChanged(this, new ImagePropertyEvent(ImagePropertyType.Decorators, this.ImageInfo, source)); } } public ImagePropertiesInfo ImageInfo { get { return imageInfo; } set { if(imageInfo != value) { imageInfo = value; //disable the image rotate command if the image is not a local image. commandImageRotate.Enabled = imageInfo != null && imageInfo.ImageSourceUri.IsFile; imageTabPageUpload.Visible = (this._imageDataContext != null) && (this._imageDataContext.ImageServiceId != null); } } } public ImagePropertiesInfo imageInfo; /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } ApplicationStyleManager.ApplicationStyleChanged -= new EventHandler(ApplicationManager_ApplicationStyleChanged); } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { components = new System.ComponentModel.Container(); } #endregion internal ImageEditingTabPageControl[] TabPages { get { return _tabPages; } } private ImageEditingTabPageControl[] _tabPages = new ImageEditingTabPageControl[0]; private void UpdateAppearance() { PerformLayout(); Invalidate(); } protected override void OnPaintBackground(PaintEventArgs pevent) { using ( Brush brush = new SolidBrush(ApplicationManager.ApplicationStyle.PrimaryWorkspaceCommandBarBottomColor) ) pevent.Graphics.FillRectangle( brush, ClientRectangle ) ; } /// <summary> /// Handle appearance preference changes. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ApplicationManager_ApplicationStyleChanged(object sender, EventArgs e) { UpdateAppearance() ; } private void commandImageDecorator_Execute(object sender, EventArgs e) { ImageDecorator imageDecorator = ((ImageDecorator)((Command)sender).Tag); //perform the execution so that the decorator is added to the list of active decorators imageDecorator.Command.PerformExecute(); //since this command was invoked explicitly via a command button, display the editor dialog. ImageDecoratorHelper.ShowImageDecoratorEditorDialog( FindForm(), imageDecorator, ImageInfo, new ApplyDecoratorCallback(ApplyImageDecorations) ); } private void commandImageRotate_Execute(object sender, EventArgs e) { ImageInfo.ImageRotation = ImageDecoratorUtils.GetFlipTypeRotated90(ImageInfo.ImageRotation); ApplyImageDecorations(); } private void commandImageReset_Execute(object sender, EventArgs e) { if(ResetToDefaultsRequested != null) { ResetToDefaultsRequested(this, EventArgs.Empty); } ApplyImageDecorations(ImageDecoratorInvocationSource.Reset); } private void commandImageSaveDefaults_Execute(object sender, EventArgs e) { if(SaveDefaultsRequested != null) { SaveDefaultsRequested(this, EventArgs.Empty); } } private void Command_StateChanged(object sender, EventArgs e) { commandImageBrightness.Enabled = _imageDataContext.DecoratorsManager.GetImageDecorator(BrightnessDecorator.Id).Command.Enabled; } } }
using System; using System.Linq; using System.Collections.Generic; using System.Threading; namespace Infrastructure { public abstract class AggregateRoot { private readonly List<Event> _changes = new List<Event>(); public abstract Guid Id { get; } public int Version { get; internal set; } public IEnumerable<Event> GetUncommittedChanges() { return _changes; } public void MarkChangesAsCommitted() { _changes.Clear(); } public void LoadsFromHistory(IEnumerable<Event> history) { foreach (var e in history) ApplyChange(e, false); } protected void ApplyChange(Event @event) { ApplyChange(@event, true); } // push atomic aggregate changes to local history for further processing (EventStore.SaveEvents) private void ApplyChange(Event @event, bool isNew) { this.AsDynamic().Apply(@event); if(isNew) _changes.Add(@event); } } public interface IRepository<T> where T : AggregateRoot, new() { void Save(AggregateRoot aggregate, int expectedVersion); T GetById(Guid id); } public class Repository<T> : IRepository<T> where T: AggregateRoot, new() //shortcut you can do as you see fit with new() { private readonly IEventStore _storage; public Repository(IEventStore storage) { _storage = storage; } public void Save(AggregateRoot aggregate, int expectedVersion) { _storage.SaveEvents(aggregate.Id, aggregate.GetUncommittedChanges(), expectedVersion); } public T GetById(Guid id) { var obj = new T();//lots of ways to do this var e = _storage.GetEventsForAggregate(id); obj.LoadsFromHistory(e); return obj; } } public interface Message { } public class Event : Message { public int Version; } public class Command : Message { } public class InMemoryBus : ICommandSender, IEventPublisher { private readonly Dictionary<Type, List<Action<Message>>> _routes = new Dictionary<Type, List<Action<Message>>>(); public void RegisterHandler<T>(Action<T> handler) where T : Message { List<Action<Message>> handlers; if(!_routes.TryGetValue(typeof(T), out handlers)) { handlers = new List<Action<Message>>(); _routes.Add(typeof(T), handlers); } handlers.Add((x => handler((T)x))); } public void Send<T>(T command) where T : Command { List<Action<Message>> handlers; if (_routes.TryGetValue(typeof(T), out handlers)) { if (handlers.Count != 1) throw new InvalidOperationException("cannot send to more than one handler"); handlers[0](command); } else { throw new InvalidOperationException("no handler registered"); } } public void Publish<T>(T @event) where T : Event { List<Action<Message>> handlers; if (!_routes.TryGetValue(@event.GetType(), out handlers)) return; foreach(var handler in handlers) { //dispatch on thread pool for added awesomeness var handler1 = handler; ThreadPool.QueueUserWorkItem(x => handler1(@event)); } } } public interface Handles<T> { void Handle(T message); } public interface ICommandSender { void Send<T>(T command) where T : Command; } public interface IEventPublisher { void Publish<T>(T @event) where T : Event; } public interface IEventStore { void SaveEvents(Guid aggregateId, IEnumerable<Event> events, int expectedVersion); List<Event> GetEventsForAggregate(Guid aggregateId); } public class EventStore : IEventStore { private readonly IEventPublisher _publisher; private struct EventDescriptor { public readonly Event EventData; public readonly Guid Id; public readonly int Version; public EventDescriptor(Guid id, Event eventData, int version) { EventData = eventData; Version = version; Id = id; } } public EventStore(IEventPublisher publisher) { _publisher = publisher; } private readonly Dictionary<Guid, List<EventDescriptor>> _current = new Dictionary<Guid, List<EventDescriptor>>(); public void SaveEvents(Guid aggregateId, IEnumerable<Event> events, int expectedVersion) { List<EventDescriptor> eventDescriptors; // try to get event descriptors list for given aggregate id // otherwise -> create empty dictionary if(!_current.TryGetValue(aggregateId, out eventDescriptors)) { eventDescriptors = new List<EventDescriptor>(); _current.Add(aggregateId,eventDescriptors); } // check whether latest event version matches current aggregate version // otherwise -> throw exception else if(eventDescriptors[eventDescriptors.Count - 1].Version != expectedVersion && expectedVersion != -1) { throw new ConcurrencyException(); } var i = expectedVersion; // iterate through current aggregate events increasing version with each processed event foreach (var @event in events) { i++; @event.Version = i; // push event to the event descriptors list for current aggregate eventDescriptors.Add(new EventDescriptor(aggregateId,@event,i)); // publish current event to the bus for further processing by subscribers _publisher.Publish(@event); } } // collect all processed events for given aggregate and return them as a list // used to build up an aggregate from its history (Domain.LoadsFromHistory) public List<Event> GetEventsForAggregate(Guid aggregateId) { List<EventDescriptor> eventDescriptors; if (!_current.TryGetValue(aggregateId, out eventDescriptors)) { throw new AggregateNotFoundException(); } return eventDescriptors.Select(desc => desc.EventData).ToList(); } } public class AggregateNotFoundException : Exception { } public class ConcurrencyException : Exception { } }
/* Project Orleans Cloud Service SDK ver. 1.0 Copyright (c) Microsoft Corporation All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Orleans.Runtime; using Orleans.Concurrency; using Orleans.Runtime.Configuration; namespace Orleans { /// <summary> /// Interface for Membership Table. /// </summary> public interface IMembershipTable { /// <summary> /// Initializes the membership table, will be called before all other methods /// </summary> /// <param name="globalConfiguration">the give global configuration</param> /// <param name="tryInitTableVersion">whether an attempt will be made to init the underlying table</param> /// <param name="traceLogger">the logger used by the membership table</param> Task InitializeMembershipTable(GlobalConfiguration globalConfiguration, bool tryInitTableVersion, TraceLogger traceLogger); /// <summary> /// Deletes all table entries of the given deploymentId /// </summary> Task DeleteMembershipTableEntries(string deploymentId); /// <summary> /// Atomically reads the Membership Table information about a given silo. /// The returned MembershipTableData includes one MembershipEntry entry for a given silo and the /// TableVersion for this table. The MembershipEntry and the TableVersion have to be read atomically. /// </summary> /// <param name="entry">The address of the silo whose membership information needs to be read.</param> /// <returns>The membership information for a given silo: MembershipTableData consisting one MembershipEntry entry and /// TableVersion, read atomically.</returns> Task<MembershipTableData> ReadRow(SiloAddress key); /// <summary> /// Atomically reads the full content of the Membership Table. /// The returned MembershipTableData includes all MembershipEntry entry for all silos in the table and the /// TableVersion for this table. The MembershipEntries and the TableVersion have to be read atomically. /// </summary> /// <returns>The membership information for a given table: MembershipTableData consisting multiple MembershipEntry entries and /// TableVersion, all read atomically.</returns> Task<MembershipTableData> ReadAll(); /// <summary> /// Atomically tries to insert (add) a new MembershipEntry for one silo and also update the TableVersion. /// If operation succeeds, the following changes would be made to the table: /// 1) New MembershipEntry will be added to the table. /// 2) The newly added MembershipEntry will also be added with the new unique automatically generated eTag. /// 3) TableVersion.Version in the table will be updated to the new TableVersion.Version. /// 4) TableVersion etag in the table will be updated to the new unique automatically generated eTag. /// All those changes to the table, insert of a new row and update of the table version and the associated etags, should happen atomically, or fail atomically with no side effects. /// The operation should fail in each of the following conditions: /// 1) A MembershipEntry for a given silo already exist in the table /// 2) Update of the TableVersion failed since the given TableVersion etag (as specified by the TableVersion.VersionEtag property) did not match the TableVersion etag in the table. /// </summary> /// <param name="entry">MembershipEntry to be inserted.</param> /// <param name="tableVersion">The new TableVersion for this table, along with its etag.</param> /// <returns>True if the insert operation succeeded and false otherwise.</returns> Task<bool> InsertRow(MembershipEntry entry, TableVersion tableVersion); /// <summary> /// Atomically tries to update the MembershipEntry for one silo and also update the TableVersion. /// If operation succeeds, the following changes would be made to the table: /// 1) The MembershipEntry for this silo will be updated to the new MembershipEntry (the old entry will be fully substitued by the new entry) /// 2) The eTag for the updated MembershipEntry will also be eTag with the new unique automatically generated eTag. /// 3) TableVersion.Version in the table will be updated to the new TableVersion.Version. /// 4) TableVersion etag in the table will be updated to the new unique automatically generated eTag. /// All those changes to the table, update of a new row and update of the table version and the associated etags, should happen atomically, or fail atomically with no side effects. /// The operation should fail in each of the following conditions: /// 1) A MembershipEntry for a given silo does not exist in the table /// 2) A MembershipEntry for a given silo exist in the table but its etag in the table does not match the provided etag. /// 3) Update of the TableVersion failed since the given TableVersion etag (as specified by the TableVersion.VersionEtag property) did not match the TableVersion etag in the table. /// </summary> /// <param name="entry">MembershipEntry to be updated.</param> /// <param name="etag">The etag for the given MembershipEntry.</param> /// <param name="tableVersion">The new TableVersion for this table, along with its etag.</param> /// <returns>True if the update operation succeeded and false otherwise.</returns> Task<bool> UpdateRow(MembershipEntry entry, string etag, TableVersion tableVersion); /// <summary> /// Updates the IAmAlive part (column) of the MembershipEntry for this silo. /// This operation should only update the IAmAlive collumn and not change other columns. /// This operation is a "dirty write" or "in place update" and is performed without etag validation. /// With regards to eTags update: /// This operation may automatically update the eTag associated with the given silo row, but it does not have to. It can also leave the etag not changed ("dirty write"). /// With regards to TableVersion: /// this operation should not change the TableVersion of the table. It should leave it untouched. /// There is no scenario where this operation could fail due to table semantical reasons. It can only fail due to network problems or table unavailability. /// </summary> /// <param name="entry"></param> /// <returns>Task representing the successful execution of this operation. </returns> Task UpdateIAmAlive(MembershipEntry entry); } /// <summary> /// Membership table interface for grain based implementation. /// </summary> [Unordered] public interface IMembershipTableGrain : IGrainWithGuidKey, IMembershipTable { } [Serializable] [Immutable] public class TableVersion { /// <summary> /// The version part of this TableVersion. Monotonically increasing number. /// </summary> public int Version { get; private set; } /// <summary> /// The etag of this TableVersion, used for validation of table update operations. /// </summary> public string VersionEtag { get; private set; } public TableVersion(int version, string eTag) { Version = version; VersionEtag = eTag; } public TableVersion Next() { return new TableVersion(Version + 1, VersionEtag); } public override string ToString() { return string.Format("<{0}, {1}>", Version, VersionEtag); } } [Serializable] public class MembershipTableData { public IReadOnlyList<Tuple<MembershipEntry, string>> Members { get; private set; } public TableVersion Version { get; private set; } public MembershipTableData(List<Tuple<MembershipEntry, string>> list, TableVersion version) { // put deads at the end, just for logging. list.Sort( (x, y) => { if (x.Item1.Status.Equals(SiloStatus.Dead)) return 1; // put Deads at the end return 1; }); Members = list.AsReadOnly(); Version = version; } public MembershipTableData(Tuple<MembershipEntry, string> tuple, TableVersion version) { Members = (new List<Tuple<MembershipEntry, string>> { tuple }).AsReadOnly(); Version = version; } public MembershipTableData(TableVersion version) { Members = (new List<Tuple<MembershipEntry, string>>()).AsReadOnly(); Version = version; } public Tuple<MembershipEntry, string> Get(SiloAddress silo) { return Members.First(tuple => tuple.Item1.SiloAddress.Equals(silo)); } public bool Contains(SiloAddress silo) { return Members.Any(tuple => tuple.Item1.SiloAddress.Equals(silo)); } public override string ToString() { int active = Members.Count(e => e.Item1.Status == SiloStatus.Active); int dead = Members.Count(e => e.Item1.Status == SiloStatus.Dead); int created = Members.Count(e => e.Item1.Status == SiloStatus.Created); int joining = Members.Count(e => e.Item1.Status == SiloStatus.Joining); int shuttingDown = Members.Count(e => e.Item1.Status == SiloStatus.ShuttingDown); int stopping = Members.Count(e => e.Item1.Status == SiloStatus.Stopping); string otherCounts = String.Format("{0}{1}{2}{3}", created > 0 ? (", " + created + " are Created") : "", joining > 0 ? (", " + joining + " are Joining") : "", shuttingDown > 0 ? (", " + shuttingDown + " are ShuttingDown") : "", stopping > 0 ? (", " + stopping + " are Stopping") : ""); return string.Format("{0} silos, {1} are Active, {2} are Dead{3}, Version={4}. All silos: {5}", Members.Count, active, dead, otherCounts, Version, Utils.EnumerableToString(Members, (tuple) => tuple.Item1.ToFullString())); } // return a copy of the table removing all dead appereances of dead nodes, except for the last one. public MembershipTableData SupressDuplicateDeads() { var dead = new Dictionary<string, Tuple<MembershipEntry, string>>(); // pick only latest Dead for each instance foreach (var next in this.Members.Where(item => item.Item1.Status == SiloStatus.Dead)) { var name = next.Item1.InstanceName; Tuple<MembershipEntry, string> prev = null; if (!dead.TryGetValue(name, out prev)) { dead[name] = next; } else { // later dead. if (next.Item1.SiloAddress.Generation.CompareTo(prev.Item1.SiloAddress.Generation) > 0) dead[name] = next; } } //now add back non-dead List<Tuple<MembershipEntry, string>> all = dead.Values.ToList(); all.AddRange(this.Members.Where(item => item.Item1.Status != SiloStatus.Dead)); return new MembershipTableData(all, this.Version); } } [Serializable] public class MembershipEntry { public SiloAddress SiloAddress { get; set; } public string HostName { get; set; } public SiloStatus Status { get; set; } public int ProxyPort { get; set; } public bool IsPrimary { get; set; } public string RoleName { get; set; } // Optional - only for Azure role public string InstanceName { get; set; } // Optional - only for Azure role public int UpdateZone { get; set; } // Optional - only for Azure role public int FaultZone { get; set; } // Optional - only for Azure role public DateTime StartTime { get; set; } // Time this silo was started. For diagnostics. public DateTime IAmAliveTime { get; set; } // Time this silo updated it was alive. For diagnostics. public List<Tuple<SiloAddress, DateTime>> SuspectTimes { get; set; } private static readonly List<Tuple<SiloAddress, DateTime>> emptyList = new List<Tuple<SiloAddress, DateTime>>(0); // partialUpdate arrivies via gossiping with other oracles. In such a case only take the status. internal void Update(MembershipEntry updatedSiloEntry) { SiloAddress = updatedSiloEntry.SiloAddress; Status = updatedSiloEntry.Status; //--- HostName = updatedSiloEntry.HostName; ProxyPort = updatedSiloEntry.ProxyPort; IsPrimary = updatedSiloEntry.IsPrimary; RoleName = updatedSiloEntry.RoleName; InstanceName = updatedSiloEntry.InstanceName; UpdateZone = updatedSiloEntry.UpdateZone; FaultZone = updatedSiloEntry.FaultZone; SuspectTimes = updatedSiloEntry.SuspectTimes; StartTime = updatedSiloEntry.StartTime; IAmAliveTime = updatedSiloEntry.IAmAliveTime; } internal List<Tuple<SiloAddress, DateTime>> GetFreshVotes(TimeSpan expiration) { if (SuspectTimes == null) return emptyList; DateTime now = DateTime.UtcNow; return SuspectTimes.FindAll(voter => { DateTime otherVoterTime = voter.Item2; // If now is smaller than otherVoterTime, than assume the otherVoterTime is fresh. // This could happen if clocks are not synchronized and the other voter clock is ahead of mine. if (now < otherVoterTime) return true; return now.Subtract(otherVoterTime) < expiration; }); } internal void AddSuspector(SiloAddress suspectingSilo, DateTime suspectingTime) { if (SuspectTimes == null) SuspectTimes = new List<Tuple<SiloAddress, DateTime>>(); var suspector = new Tuple<SiloAddress, DateTime>(suspectingSilo, suspectingTime); SuspectTimes.Add(suspector); } internal void TryUpdateStartTime(DateTime startTime) { if (StartTime.Equals(default(DateTime))) StartTime = startTime; } public override string ToString() { return string.Format("SiloAddress={0} Status={1}", SiloAddress.ToLongString(), Status); } internal string ToFullString(bool full = false) { if (!full) return ToString(); List<SiloAddress> suspecters = SuspectTimes == null ? null : SuspectTimes.Select(tuple => tuple.Item1).ToList(); List<DateTime> timestamps = SuspectTimes == null ? null : SuspectTimes.Select(tuple => tuple.Item2).ToList(); return string.Format("[SiloAddress={0} Status={1} HostName={2} ProxyPort={3} IsPrimary={4} " + "RoleName={5} InstanceName={6} UpdateZone={7} FaultZone={8} StartTime = {9} IAmAliveTime = {10} {11} {12}]", SiloAddress.ToLongString(), Status, HostName, ProxyPort, IsPrimary, RoleName, InstanceName, UpdateZone, FaultZone, TraceLogger.PrintDate(StartTime), TraceLogger.PrintDate(IAmAliveTime), suspecters == null ? "" : "Suspecters = " + Utils.EnumerableToString(suspecters, (SiloAddress sa) => sa.ToLongString()), timestamps == null ? "" : "SuspectTimes = " + Utils.EnumerableToString(timestamps, TraceLogger.PrintDate) ); } } }
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://github.com/jskeet/dotnet-protobufs/ // Original C++/Java/Python code: // http://code.google.com/p/protobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System.IO; using Google.ProtocolBuffers.TestProtos; using NUnit.Framework; namespace Google.ProtocolBuffers { [TestFixture] public class CodedOutputStreamTest { /// <summary> /// Writes the given value using WriteRawVarint32() and WriteRawVarint64() and /// checks that the result matches the given bytes /// </summary> private static void AssertWriteVarint(byte[] data, ulong value) { // Only do 32-bit write if the value fits in 32 bits. if ((value >> 32) == 0) { MemoryStream rawOutput = new MemoryStream(); CodedOutputStream output = CodedOutputStream.CreateInstance(rawOutput); output.WriteRawVarint32((uint) value); output.Flush(); Assert.AreEqual(data, rawOutput.ToArray()); // Also try computing size. Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint32Size((uint) value)); } { MemoryStream rawOutput = new MemoryStream(); CodedOutputStream output = CodedOutputStream.CreateInstance(rawOutput); output.WriteRawVarint64(value); output.Flush(); Assert.AreEqual(data, rawOutput.ToArray()); // Also try computing size. Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint64Size(value)); } // Try different buffer sizes. for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2) { // Only do 32-bit write if the value fits in 32 bits. if ((value >> 32) == 0) { MemoryStream rawOutput = new MemoryStream(); CodedOutputStream output = CodedOutputStream.CreateInstance(rawOutput, bufferSize); output.WriteRawVarint32((uint) value); output.Flush(); Assert.AreEqual(data, rawOutput.ToArray()); } { MemoryStream rawOutput = new MemoryStream(); CodedOutputStream output = CodedOutputStream.CreateInstance(rawOutput, bufferSize); output.WriteRawVarint64(value); output.Flush(); Assert.AreEqual(data, rawOutput.ToArray()); } } } /// <summary> /// Tests WriteRawVarint32() and WriteRawVarint64() /// </summary> [Test] public void WriteVarint() { AssertWriteVarint(new byte[] {0x00}, 0); AssertWriteVarint(new byte[] {0x01}, 1); AssertWriteVarint(new byte[] {0x7f}, 127); // 14882 AssertWriteVarint(new byte[] {0xa2, 0x74}, (0x22 << 0) | (0x74 << 7)); // 2961488830 AssertWriteVarint(new byte[] {0xbe, 0xf7, 0x92, 0x84, 0x0b}, (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | (0x0bL << 28)); // 64-bit // 7256456126 AssertWriteVarint(new byte[] {0xbe, 0xf7, 0x92, 0x84, 0x1b}, (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | (0x1bL << 28)); // 41256202580718336 AssertWriteVarint( new byte[] {0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49}, (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) | (0x43UL << 28) | (0x49L << 35) | (0x24UL << 42) | (0x49UL << 49)); // 11964378330978735131 AssertWriteVarint( new byte[] {0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01}, unchecked((ulong) ((0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) | (0x3bL << 28) | (0x56L << 35) | (0x00L << 42) | (0x05L << 49) | (0x26L << 56) | (0x01L << 63)))); } /// <summary> /// Parses the given bytes using WriteRawLittleEndian32() and checks /// that the result matches the given value. /// </summary> private static void AssertWriteLittleEndian32(byte[] data, uint value) { MemoryStream rawOutput = new MemoryStream(); CodedOutputStream output = CodedOutputStream.CreateInstance(rawOutput); output.WriteRawLittleEndian32(value); output.Flush(); Assert.AreEqual(data, rawOutput.ToArray()); // Try different buffer sizes. for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2) { rawOutput = new MemoryStream(); output = CodedOutputStream.CreateInstance(rawOutput, bufferSize); output.WriteRawLittleEndian32(value); output.Flush(); Assert.AreEqual(data, rawOutput.ToArray()); } } /// <summary> /// Parses the given bytes using WriteRawLittleEndian64() and checks /// that the result matches the given value. /// </summary> private static void AssertWriteLittleEndian64(byte[] data, ulong value) { MemoryStream rawOutput = new MemoryStream(); CodedOutputStream output = CodedOutputStream.CreateInstance(rawOutput); output.WriteRawLittleEndian64(value); output.Flush(); Assert.AreEqual(data, rawOutput.ToArray()); // Try different block sizes. for (int blockSize = 1; blockSize <= 16; blockSize *= 2) { rawOutput = new MemoryStream(); output = CodedOutputStream.CreateInstance(rawOutput, blockSize); output.WriteRawLittleEndian64(value); output.Flush(); Assert.AreEqual(data, rawOutput.ToArray()); } } /// <summary> /// Tests writeRawLittleEndian32() and writeRawLittleEndian64(). /// </summary> [Test] public void WriteLittleEndian() { AssertWriteLittleEndian32(new byte[] {0x78, 0x56, 0x34, 0x12}, 0x12345678); AssertWriteLittleEndian32(new byte[] {0xf0, 0xde, 0xbc, 0x9a}, 0x9abcdef0); AssertWriteLittleEndian64( new byte[]{0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12}, 0x123456789abcdef0L); AssertWriteLittleEndian64( new byte[]{0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a}, 0x9abcdef012345678UL); } [Test] public void WriteWholeMessage() { TestAllTypes message = TestUtil.GetAllSet(); byte[] rawBytes = message.ToByteArray(); TestUtil.AssertEqualBytes(TestUtil.GoldenMessage.ToByteArray(), rawBytes); // Try different block sizes. for (int blockSize = 1; blockSize < 256; blockSize *= 2) { MemoryStream rawOutput = new MemoryStream(); CodedOutputStream output = CodedOutputStream.CreateInstance(rawOutput, blockSize); message.WriteTo(output); output.Flush(); TestUtil.AssertEqualBytes(rawBytes, rawOutput.ToArray()); } } /// <summary> /// Tests writing a whole message with every packed field type. Ensures the /// wire format of packed fields is compatible with C++. /// </summary> [Test] public void WriteWholePackedFieldsMessage() { TestPackedTypes message = TestUtil.GetPackedSet(); byte[] rawBytes = message.ToByteArray(); TestUtil.AssertEqualBytes(TestUtil.GetGoldenPackedFieldsMessage().ToByteArray(), rawBytes); } [Test] public void EncodeZigZag32() { Assert.AreEqual(0, CodedOutputStream.EncodeZigZag32( 0)); Assert.AreEqual(1, CodedOutputStream.EncodeZigZag32(-1)); Assert.AreEqual(2, CodedOutputStream.EncodeZigZag32( 1)); Assert.AreEqual(3, CodedOutputStream.EncodeZigZag32(-2)); Assert.AreEqual(0x7FFFFFFE, CodedOutputStream.EncodeZigZag32(0x3FFFFFFF)); Assert.AreEqual(0x7FFFFFFF, CodedOutputStream.EncodeZigZag32(unchecked((int)0xC0000000))); Assert.AreEqual(0xFFFFFFFE, CodedOutputStream.EncodeZigZag32(0x7FFFFFFF)); Assert.AreEqual(0xFFFFFFFF, CodedOutputStream.EncodeZigZag32(unchecked((int)0x80000000))); } [Test] public void EncodeZigZag64() { Assert.AreEqual(0, CodedOutputStream.EncodeZigZag64( 0)); Assert.AreEqual(1, CodedOutputStream.EncodeZigZag64(-1)); Assert.AreEqual(2, CodedOutputStream.EncodeZigZag64( 1)); Assert.AreEqual(3, CodedOutputStream.EncodeZigZag64(-2)); Assert.AreEqual(0x000000007FFFFFFEL, CodedOutputStream.EncodeZigZag64(unchecked((long)0x000000003FFFFFFFUL))); Assert.AreEqual(0x000000007FFFFFFFL, CodedOutputStream.EncodeZigZag64(unchecked((long)0xFFFFFFFFC0000000UL))); Assert.AreEqual(0x00000000FFFFFFFEL, CodedOutputStream.EncodeZigZag64(unchecked((long)0x000000007FFFFFFFUL))); Assert.AreEqual(0x00000000FFFFFFFFL, CodedOutputStream.EncodeZigZag64(unchecked((long)0xFFFFFFFF80000000UL))); Assert.AreEqual(0xFFFFFFFFFFFFFFFEL, CodedOutputStream.EncodeZigZag64(unchecked((long)0x7FFFFFFFFFFFFFFFUL))); Assert.AreEqual(0xFFFFFFFFFFFFFFFFL, CodedOutputStream.EncodeZigZag64(unchecked((long)0x8000000000000000UL))); } [Test] public void RoundTripZigZag32() { // Some easier-to-verify round-trip tests. The inputs (other than 0, 1, -1) // were chosen semi-randomly via keyboard bashing. Assert.AreEqual(0, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(0))); Assert.AreEqual(1, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(1))); Assert.AreEqual(-1, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(-1))); Assert.AreEqual(14927, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(14927))); Assert.AreEqual(-3612, CodedInputStream.DecodeZigZag32(CodedOutputStream.EncodeZigZag32(-3612))); } [Test] public void RoundTripZigZag64() { Assert.AreEqual(0, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(0))); Assert.AreEqual(1, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(1))); Assert.AreEqual(-1, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-1))); Assert.AreEqual(14927, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(14927))); Assert.AreEqual(-3612, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-3612))); Assert.AreEqual(856912304801416L, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(856912304801416L))); Assert.AreEqual(-75123905439571256L, CodedInputStream.DecodeZigZag64(CodedOutputStream.EncodeZigZag64(-75123905439571256L))); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Schema { // SUMMARY // ======= // For each Xml type, there is a set of Clr types that can represent it. Some of these mappings involve // loss of fidelity. For example, xsd:dateTime can be represented as System.DateTime, but only at the expense // of normalizing the time zone. And xs:duration can be represented as System.TimeSpan, but only at the expense // of discarding variations such as "P50H", "P1D26H", "P2D2H", all of which are normalized as "P2D2H". // // Implementations of this class convert between the various Clr representations of Xml types. Note that // in *no* case is the Xml type ever modified. Only the Clr type is changed. This means that in cases where // the Xml type is part of the representation (such as XmlAtomicValue), the destination value is guaranteed // to have the same Xml type. // // For all converters, converting to typeof(object) is identical to converting to XmlSchemaType.Datatype.ValueType. // // // ATOMIC MAPPINGS // =============== // // ----------------------------------------------------------------------------------------------------------- // Source/Destination System.String Other Clr Type // ----------------------------------------------------------------------------------------------------------- // System.String No-op conversion. Use Xsd rules to convert from the string // to primitive, full-fidelity Clr type (use // XmlConvert where possible). Use Clr rules // to convert to destination type. // ----------------------------------------------------------------------------------------------------------- // Other Clr Type Use Clr rules to convert from Use Clr rules to convert from source to // source type to primitive, full- destination type. // fidelity Clr type. Use Xsd rules // to convert to a string (use // XmlConvert where possible). // ----------------------------------------------------------------------------------------------------------- // // // LIST MAPPINGS // ============= // The following Clr types can be used to represent Xsd list types: IList, ICollection, IEnumerable, Type[], // String. // // ----------------------------------------------------------------------------------------------------------- // Source/Destination System.String Clr List Type // ----------------------------------------------------------------------------------------------------------- // System.String No-op conversion Tokenize the string by whitespace, create a // String[] from tokens, and follow List => List // rules. // ----------------------------------------------------------------------------------------------------------- // Clr List Type Follow List => String[] rules, Create destination list having the same length // then concatenate strings from array, as the source list. For each item in the // separating adjacent strings with a source list, call the atomic converter to // single space character. convert to the destination type. The destination // item type for IList, ICollection, IEnumerable // is typeof(object). The destination item type // for Type[] is Type. // ----------------------------------------------------------------------------------------------------------- // // // UNION MAPPINGS // ============== // Union types may only be represented using System.Xml.Schema.XmlAtomicValue or System.String. Either the // source type or the destination type must therefore always be either System.String or // System.Xml.Schema.XmlAtomicValue. // // ----------------------------------------------------------------------------------------------------------- // Source/Destination System.String XmlAtomicValue Other Clr Type // ----------------------------------------------------------------------------------------------------------- // System.String No-op conversion Follow System.String=> Call ParseValue in order to determine // Other Clr Type rules. the member type. Call ChangeType on // the member type's converter to convert // to desired Clr type. // ----------------------------------------------------------------------------------------------------------- // XmlAtomicValue Follow XmlAtomicValue No-op conversion. Call ReadValueAs, where destinationType // => Other Clr Type is the desired Clr type. // rules. // ----------------------------------------------------------------------------------------------------------- // Other Clr Type InvalidCastException InvalidCastException InvalidCastException // ----------------------------------------------------------------------------------------------------------- // // // EXAMPLES // ======== // // ----------------------------------------------------------------------------------------------------------- // Source Destination // Xml Type Value Type Conversion Steps Explanation // ----------------------------------------------------------------------------------------------------------- // xs:int "10" Byte "10" => 10M => (byte) 10 Primitive, full-fidelity for xs:int // is a truncated decimal // ----------------------------------------------------------------------------------------------------------- // xs:int "10.10" Byte FormatException xs:integer parsing rules do not // allow fractional parts // ----------------------------------------------------------------------------------------------------------- // xs:int 10.10M Byte 10.10M => (byte) 10 Default Clr rules truncate when // converting from Decimal to Byte // ----------------------------------------------------------------------------------------------------------- // xs:int 10.10M Decimal 10.10M => 10.10M Decimal => Decimal is no-op // ----------------------------------------------------------------------------------------------------------- // xs:int 10.10M String 10.10M => 10M => "10" // ----------------------------------------------------------------------------------------------------------- // xs:int "hello" String "hello" => "hello" String => String is no-op // ----------------------------------------------------------------------------------------------------------- // xs:byte "300" Int32 "300" => 300M => (int) 300 // ----------------------------------------------------------------------------------------------------------- // xs:byte 300 Byte 300 => 300M => OverflowException Clr overflows when converting from // Decimal to Byte // ----------------------------------------------------------------------------------------------------------- // xs:byte 300 XmlAtomicValue new XmlAtomicValue(xs:byte, 300) Invalid atomic value created // ----------------------------------------------------------------------------------------------------------- // xs:double 1.234f String 1.234f => 1.2339999675750732d => Converting a Single value to a Double // "1.2339999675750732" value zero-extends it in base-2, so // "garbage" digits appear when it's // converted to base-10. // ----------------------------------------------------------------------------------------------------------- // xs:int* {1, "2", String {1, "2", 3.1M} => Delegate to xs:int converter to // 3.1M} {"1", "2", "3"} => "1 2 3" convert each item to a string. // ----------------------------------------------------------------------------------------------------------- // xs:int* "1 2 3" Int32[] "1 2 3" => {"1", "2", "3"} => // {1, 2, 3} // ----------------------------------------------------------------------------------------------------------- // xs:int* {1, "2", Object[] {1, "2", 3.1M} => xs:int converter uses Int32 by default, // 3.1M} {(object)1, (object)2, (object)3} so returns boxed Int32 values. // ----------------------------------------------------------------------------------------------------------- // (xs:int | "1 2001" XmlAtomicValue[] "1 2001" => {(xs:int) 1, // xs:gYear)* (xs:gYear) 2001} // ----------------------------------------------------------------------------------------------------------- // (xs:int* | "1 2001" String "1 2001" No-op conversion even though // xs:gYear*) ParseValue would fail if it were called. // ----------------------------------------------------------------------------------------------------------- // (xs:int* | "1 2001" Int[] XmlSchemaException ParseValue fails. // xs:gYear*) // ----------------------------------------------------------------------------------------------------------- // internal static class XmlUntypedConverter { public static bool ToBoolean(string value) { if (value == null) throw new ArgumentNullException(nameof(value)); return XmlConvert.ToBoolean((string)value); } private static DateTime UntypedAtomicToDateTime(string value) { return (DateTime)(new XsdDateTime(value, XsdDateTimeFlags.AllXsd)); } public static DateTime ToDateTime(string value) { if (value == null) throw new ArgumentNullException(nameof(value)); return UntypedAtomicToDateTime((string)value); } public static double ToDouble(string value) { if (value == null) throw new ArgumentNullException(nameof(value)); return XmlConvert.ToDouble((string)value); } public static int ToInt32(string value) { if (value == null) throw new ArgumentNullException(nameof(value)); return XmlConvert.ToInt32((string)value); } public static long ToInt64(string value) { if (value == null) throw new ArgumentNullException(nameof(value)); return XmlConvert.ToInt64((string)value); } private static readonly Type DecimalType = typeof(decimal); private static readonly Type Int32Type = typeof(int); private static readonly Type Int64Type = typeof(long); private static readonly Type StringType = typeof(string); private static readonly Type ByteType = typeof(byte); private static readonly Type Int16Type = typeof(short); private static readonly Type SByteType = typeof(sbyte); private static readonly Type UInt16Type = typeof(ushort); private static readonly Type UInt32Type = typeof(uint); private static readonly Type UInt64Type = typeof(ulong); private static readonly Type DoubleType = typeof(double); private static readonly Type SingleType = typeof(float); private static readonly Type DateTimeType = typeof(DateTime); private static readonly Type DateTimeOffsetType = typeof(DateTimeOffset); private static readonly Type BooleanType = typeof(bool); private static readonly Type ByteArrayType = typeof(Byte[]); private static readonly Type XmlQualifiedNameType = typeof(XmlQualifiedName); private static readonly Type UriType = typeof(Uri); private static readonly Type TimeSpanType = typeof(TimeSpan); private static string Base64BinaryToString(byte[] value) { return Convert.ToBase64String(value); } private static string DateTimeToString(DateTime value) { return (new XsdDateTime(value, XsdDateTimeFlags.DateTime)).ToString(); } private static string DateTimeOffsetToString(DateTimeOffset value) { return (new XsdDateTime(value, XsdDateTimeFlags.DateTime)).ToString(); } private static string QNameToString(XmlQualifiedName qname, IXmlNamespaceResolver nsResolver) { string prefix; if (nsResolver == null) return string.Concat("{", qname.Namespace, "}", qname.Name); prefix = nsResolver.LookupPrefix(qname.Namespace); if (prefix == null) throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeNoPrefix, qname.ToString(), qname.Namespace)); return (prefix.Length != 0) ? string.Concat(prefix, ":", qname.Name) : qname.Name; } private static string AnyUriToString(Uri value) { return value.OriginalString; } public static string ToString(object value, IXmlNamespaceResolver nsResolver) { if (value == null) throw new ArgumentNullException(nameof(value)); Type sourceType = value.GetType(); if (sourceType == BooleanType) return XmlConvert.ToString((bool)value); if (sourceType == ByteType) return XmlConvert.ToString((byte)value); if (sourceType == ByteArrayType) return Base64BinaryToString((byte[])value); if (sourceType == DateTimeType) return DateTimeToString((DateTime)value); if (sourceType == DateTimeOffsetType) return DateTimeOffsetToString((DateTimeOffset)value); if (sourceType == DecimalType) return XmlConvert.ToString((decimal)value); if (sourceType == DoubleType) return XmlConvert.ToString((double)value); if (sourceType == Int16Type) return XmlConvert.ToString((short)value); if (sourceType == Int32Type) return XmlConvert.ToString((int)value); if (sourceType == Int64Type) return XmlConvert.ToString((long)value); if (sourceType == SByteType) return XmlConvert.ToString((sbyte)value); if (sourceType == SingleType) return XmlConvert.ToString((float)value); if (sourceType == StringType) return ((string)value); if (sourceType == TimeSpanType) return XmlConvert.ToString((TimeSpan)value); if (sourceType == UInt16Type) return XmlConvert.ToString((ushort)value); if (sourceType == UInt32Type) return XmlConvert.ToString((uint)value); if (sourceType == UInt64Type) return XmlConvert.ToString((ulong)value); Uri valueAsUri = value as Uri; if (valueAsUri != null) return AnyUriToString(valueAsUri); XmlQualifiedName valueAsXmlQualifiedName = value as XmlQualifiedName; if (valueAsXmlQualifiedName != null) return QNameToString(valueAsXmlQualifiedName, nsResolver); throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeToString, sourceType.Name)); } private static byte[] StringToBase64Binary(string value) { return Convert.FromBase64String(XmlConvertEx.TrimString(value)); } private static short Int32ToInt16(int value) { if (value < (int)Int16.MinValue || value > (int)Int16.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "Int16" })); return (short)value; } private static byte Int32ToByte(int value) { if (value < (int)Byte.MinValue || value > (int)Byte.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "Byte" })); return (byte)value; } private static ulong DecimalToUInt64(decimal value) { if (value < (decimal)UInt64.MinValue || value > (decimal)UInt64.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "UInt64" })); return (ulong)value; } private static sbyte Int32ToSByte(int value) { if (value < (int)SByte.MinValue || value > (int)SByte.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "SByte" })); return (sbyte)value; } private static DateTimeOffset UntypedAtomicToDateTimeOffset(string value) { return (DateTimeOffset)(new XsdDateTime(value, XsdDateTimeFlags.AllXsd)); } private static XmlQualifiedName StringToQName(string value, IXmlNamespaceResolver nsResolver) { string prefix, localName, ns; value = value.Trim(); // Parse prefix:localName try { ValidateNames.ParseQNameThrow(value, out prefix, out localName); } catch (XmlException e) { throw new FormatException(e.Message); } // Throw error if no namespaces are in scope if (nsResolver == null) throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeNoNamespace, value, prefix)); // Lookup namespace ns = nsResolver.LookupNamespace(prefix); if (ns == null) throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeNoNamespace, value, prefix)); // Create XmlQualifiedName return new XmlQualifiedName(localName, ns); } private static ushort Int32ToUInt16(int value) { if (value < (int)UInt16.MinValue || value > (int)UInt16.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "UInt16" })); return (ushort)value; } private static uint Int64ToUInt32(long value) { if (value < (long)UInt32.MinValue || value > (long)UInt32.MaxValue) throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, new string[] { XmlConvert.ToString(value), "UInt32" })); return (uint)value; } public static object ChangeType(string value, Type destinationType, IXmlNamespaceResolver nsResolver) { if (value == null) throw new ArgumentNullException(nameof(value)); if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); if (destinationType == BooleanType) return XmlConvert.ToBoolean((string)value); if (destinationType == ByteType) return Int32ToByte(XmlConvert.ToInt32((string)value)); if (destinationType == ByteArrayType) return StringToBase64Binary((string)value); if (destinationType == DateTimeType) return UntypedAtomicToDateTime((string)value); if (destinationType == DateTimeOffsetType) return XmlConvert.ToDateTimeOffset((string)value); if (destinationType == DecimalType) return XmlConvert.ToDecimal((string)value); if (destinationType == DoubleType) return XmlConvert.ToDouble((string)value); if (destinationType == Int16Type) return Int32ToInt16(XmlConvert.ToInt32((string)value)); if (destinationType == Int32Type) return XmlConvert.ToInt32((string)value); if (destinationType == Int64Type) return XmlConvert.ToInt64((string)value); if (destinationType == SByteType) return Int32ToSByte(XmlConvert.ToInt32((string)value)); if (destinationType == SingleType) return XmlConvert.ToSingle((string)value); if (destinationType == TimeSpanType) return XmlConvert.ToTimeSpan((string)value); if (destinationType == UInt16Type) return Int32ToUInt16(XmlConvert.ToInt32((string)value)); if (destinationType == UInt32Type) return Int64ToUInt32(XmlConvert.ToInt64((string)value)); if (destinationType == UInt64Type) return DecimalToUInt64(XmlConvert.ToDecimal((string)value)); if (destinationType == UriType) return XmlConvertEx.ToUri((string)value); if (destinationType == XmlQualifiedNameType) return StringToQName((string)value, nsResolver); if (destinationType == StringType) return ((string)value); throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeFromString, destinationType.Name)); } } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2015 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion -- License Terms -- #if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT #define UNITY #endif using System; using System.Collections; using System.Runtime.Serialization; namespace MsgPack.Serialization.CollectionSerializers { /// <summary> /// Provides basic features for non-dictionary non-generic collection serializers. /// </summary> /// <typeparam name="TCollection">The type of the collection.</typeparam> /// <remarks> /// This class provides framework to implement variable collection serializer, and this type seals some virtual members to maximize future backward compatibility. /// If you cannot use this class, you can implement your own serializer which inherits <see cref="MessagePackSerializer{T}"/> and implements <see cref="ICollectionInstanceFactory"/>. /// </remarks> public abstract class NonGenericEnumerableMessagePackSerializerBase<TCollection> : MessagePackSerializer<TCollection>, ICollectionInstanceFactory where TCollection : IEnumerable { private readonly IMessagePackSingleObjectSerializer _itemSerializer; internal IMessagePackSingleObjectSerializer ItemSerializer { get { return this._itemSerializer; } } /// <summary> /// Initializes a new instance of the <see cref="NonGenericEnumerableMessagePackSerializerBase{TCollection}"/> class. /// </summary> /// <param name="ownerContext">A <see cref="SerializationContext"/> which owns this serializer.</param> /// <param name="schema"> /// The schema for collection itself or its items for the member this instance will be used to. /// <c>null</c> will be considered as <see cref="PolymorphismSchema.Default"/>. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="ownerContext"/> is <c>null</c>. /// </exception> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by base .ctor" )] protected NonGenericEnumerableMessagePackSerializerBase( SerializationContext ownerContext, PolymorphismSchema schema ) : base( ownerContext ) { this._itemSerializer = ownerContext.GetSerializer( typeof( object ), ( schema ?? PolymorphismSchema.Default ).ItemSchema ); } /// <summary> /// Creates a new collection instance with specified initial capacity. /// </summary> /// <param name="initialCapacity"> /// The initial capacy of creating collection. /// Note that this parameter may <c>0</c> for non-empty collection. /// </param> /// <returns> /// New collection instance. This value will not be <c>null</c>. /// </returns> /// <remarks> /// An author of <see cref="Unpacker" /> could implement unpacker for non-MessagePack format, /// so implementer of this interface should not rely on that <paramref name="initialCapacity" /> reflects actual items count. /// For example, JSON unpacker cannot supply collection items count efficiently. /// </remarks> /// <seealso cref="ICollectionInstanceFactory.CreateInstance"/> protected abstract TCollection CreateInstance( int initialCapacity ); object ICollectionInstanceFactory.CreateInstance( int initialCapacity ) { return this.CreateInstance( initialCapacity ); } /// <summary> /// Deserializes collection items with specified <see cref="Unpacker"/> and stores them to <paramref name="collection"/>. /// </summary> /// <param name="unpacker"><see cref="Unpacker"/> which unpacks values of resulting object tree. This value will not be <c>null</c>.</param> /// <param name="collection">Collection that the items to be stored. This value will not be <c>null</c>.</param> /// <exception cref="SerializationException"> /// Failed to deserialize object due to invalid unpacker state, stream content, or so. /// </exception> /// <exception cref="NotSupportedException"> /// <typeparamref name="TCollection"/> is not collection. /// </exception> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "By design" )] protected internal sealed override void UnpackToCore( Unpacker unpacker, TCollection collection ) { if ( !unpacker.IsArrayHeader ) { throw SerializationExceptions.NewIsNotArrayHeader(); } this.UnpackToCore( unpacker, collection, UnpackHelpers.GetItemsCount( unpacker ) ); } internal void UnpackToCore( Unpacker unpacker, TCollection collection, int itemsCount ) { for ( var i = 0; i < itemsCount; i++ ) { if ( !unpacker.Read() ) { throw SerializationExceptions.NewMissingItem( i ); } object item; if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader ) { item = this._itemSerializer.UnpackFrom( unpacker ); } else { using ( var subtreeUnpacker = unpacker.ReadSubtree() ) { item = this._itemSerializer.UnpackFrom( subtreeUnpacker ); } } this.AddItem( collection, item ); } } /// <summary> /// When implemented by derive class, /// adds the deserialized item to the collection on <typeparamref name="TCollection"/> specific manner /// to implement <see cref="UnpackToCore(Unpacker,TCollection)"/>. /// </summary> /// <param name="collection">The collection to be added.</param> /// <param name="item">The item to be added.</param> /// <exception cref="NotSupportedException"> /// This implementation always throws it. /// </exception> protected virtual void AddItem( TCollection collection, object item ) { throw SerializationExceptions.NewUnpackToIsNotSupported( typeof( TCollection ), null ); } } #if UNITY internal abstract class UnityNonGenericEnumerableMessagePackSerializerBase : NonGenericMessagePackSerializer, ICollectionInstanceFactory { private readonly IMessagePackSingleObjectSerializer _itemSerializer; internal IMessagePackSingleObjectSerializer ItemSerializer { get { return this._itemSerializer; } } protected UnityNonGenericEnumerableMessagePackSerializerBase( SerializationContext ownerContext, Type targetType, PolymorphismSchema schema ) : base( ownerContext, targetType ) { this._itemSerializer = ownerContext.GetSerializer( typeof( object ), ( schema ?? PolymorphismSchema.Default ).ItemSchema ); } protected abstract object CreateInstance( int initialCapacity ); object ICollectionInstanceFactory.CreateInstance( int initialCapacity ) { return this.CreateInstance( initialCapacity ); } protected internal sealed override void UnpackToCore( Unpacker unpacker, object collection ) { if ( !unpacker.IsArrayHeader ) { throw SerializationExceptions.NewIsNotArrayHeader(); } this.UnpackToCore( unpacker, collection, UnpackHelpers.GetItemsCount( unpacker ) ); } internal void UnpackToCore( Unpacker unpacker, object collection, int itemsCount ) { for ( var i = 0; i < itemsCount; i++ ) { if ( !unpacker.Read() ) { throw SerializationExceptions.NewMissingItem( i ); } object item; if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader ) { item = this._itemSerializer.UnpackFrom( unpacker ); } else { using ( var subtreeUnpacker = unpacker.ReadSubtree() ) { item = this._itemSerializer.UnpackFrom( subtreeUnpacker ); } } this.AddItem( collection, item ); } } protected virtual void AddItem( object collection, object item ) { throw SerializationExceptions.NewUnpackToIsNotSupported( this.TargetType, null ); } } #endif // UNITY }
#region Header // -------------------------------------------------------------------------- // Tethys.Silverlight // ========================================================================== // // This library contains common for .Net Windows applications. // // =========================================================================== // // <copyright file="SerialPortEncoding.cs" company="Tethys"> // Copyright 1998-2015 by Thomas Graf // All rights reserved. // Licensed under the Apache License, Version 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. // </copyright> // // System ... Microsoft .Net Framework 4 // Tools .... Microsoft Visual Studio 2013 // // --------------------------------------------------------------------------- #endregion namespace Tethys.IO { using System; using System.Text; /// <summary> /// Represents an ASCII character encoding of Unicode characters. /// In difference to ASCIIEncoding this encoding class supports the special /// characters handling that is needed for a proper XModem file transmission. /// </summary> public class SerialPortEncoding : Encoding { /// <summary> /// The code page. /// </summary> private const int GermanCodePage = 1252; #region PUBLIC PROPERTIES /// <summary> /// Gets the name for this encoding that can be used with mail agent body tags. /// Not supported by SerialPortEncoding. /// </summary> public override string BodyName { get { return string.Empty; } } // BodyName /// <summary> /// When overridden in a derived class, gets the code page identifier of this encoding. /// </summary> public override int CodePage { get { return 0; } } // CodePage /// <summary> /// Gets the human-readable description of the encoding. /// </summary> public override string EncodingName { get { return "Special Encoding for serial port"; } } // EncodingName /// <summary> /// Gets the name for this encoding that can be used with mail agent header tags. /// </summary> public override string HeaderName { get { return string.Empty; } } // HeaderName /// <summary> /// Gets an indication whether this encoding can be used for display by browser clients. /// </summary> public override bool IsBrowserDisplay { get { return false; } } // IsBrowserDisplay /// <summary> /// Gets an indication whether this encoding can be used for saving by browser clients. /// </summary> public override bool IsBrowserSave { get { return false; } } // IsBrowserSave /// <summary> /// Gets and indication whether this encoding can be used for display by mail and news clients. /// </summary> public override bool IsMailNewsDisplay { get { return false; } } // IsMailNewsDisplay /// <summary> /// Gets an indication whether this encoding can be used for saving by mail and news clients. /// </summary> public override bool IsMailNewsSave { get { return false; } } // IsMailNewsSave /// <summary> /// Gets the name registered with the Internet Assigned Numbers Authority (IANA) for this encoding. /// </summary> public override string WebName { get { return string.Empty; } } // WebName /// <summary> /// Gets the Windows operating system code page that most closely corresponds to this encoding. /// </summary> public override int WindowsCodePage { get { return 0; } } // WindowsCodePage #endregion // PUBLIC PROPERTIES //// --------------------------------------------------------------------- #region BASIC CLASS METHODS /// <summary> /// Tests whether the specified object is a SerialPortEncoding object /// and is equivalent to this SerialPortEncoding object. /// </summary> /// <param name="obj">operand to be compared to the object</param> /// <returns>The function returns true if the two operands are identical.</returns> public override bool Equals(object obj) { if (obj == null) { return false; } // if // TG: ALWAYS return false; } // Equals() /// <summary> /// Returns the hash code for this instance. /// </summary> /// <remarks> /// This is only a DUMMY - we don't need this method here. /// </remarks> /// <returns>The hash code.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations", Justification = "This is ok here.")] public override int GetHashCode() { throw new NotSupportedException("SerialPortEncoding does not support GetHashCode()."); } // GetHashCode() #endregion // BASIC CLASS METHODS //// --------------------------------------------------------------------- #region CORE FUNCTIONS /// <summary> /// Calculates the number of bytes required to store the results of /// encoding the characters from a specified String. /// </summary> /// <param name="s">The <see cref="T:System.String" /> containing the /// set of characters to encode.</param> /// <returns> /// The byte count. /// </returns> public override int GetByteCount(string s) { return GetEncoding(GermanCodePage).GetByteCount(s); } // GetByteCount() /// <summary> /// Calculates the number of bytes required to store the results of /// encoding a set of characters from a specified Unicode character array. /// </summary> /// <param name="chars">The Unicode character array to encode.</param> /// <param name="index">The index of the first character in chars to encode.</param> /// <param name="count">The number of characters to encode.</param> /// <returns>The byte count.</returns> public override int GetByteCount(char[] chars, int index, int count) { return GetEncoding(GermanCodePage).GetByteCount(chars, index, count); } // GetByteCount() /// <summary> /// Encodes a specified range of elements from a Unicode character array, /// and stores the results in a specified range of elements in a byte /// array. /// </summary> /// <param name="chars">The character array containing the set of characters to encode.</param> /// <param name="charIndex">The index of the first character to encode.</param> /// <param name="charCount">The number of characters to encode.</param> /// <param name="bytes">The byte array to contain the resulting sequence of bytes.</param> /// <param name="byteIndex">The index at which to start writing the resulting sequence of bytes.</param> /// <returns> /// The actual number of bytes written into <paramref name="bytes" />. /// </returns> public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { return GetEncoding(GermanCodePage).GetBytes(chars, charIndex, charCount, bytes, byteIndex); } // GetBytes() /// <summary> /// Encodes a specified range of characters from a String and stores the /// results in a specified range of elements in a byte array. /// </summary> /// <param name="s">The string of characters to encode.</param> /// <param name="charIndex">The index of the first character in chars to /// encode.</param> /// <param name="charCount">The number of characters to encode. </param> /// <param name="bytes">The byte array where the encoded results are stored.</param> /// <param name="byteIndex">The index of the first element in bytes where /// the encoded results are stored.</param> /// <returns>The bytes.</returns> public override int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { return GetEncoding(GermanCodePage).GetBytes(s, charIndex, charCount, bytes, byteIndex); } // GetBytes() /// <summary> /// Encodes a specified character array into a byte array. /// </summary> /// <param name="chars">The character array to encode. </param> /// <returns> /// A byte array containing the encoded representation of the /// specified range of characters in chars. /// </returns> public override byte[] GetBytes(char[] chars) { return GetBytes(chars, 0, chars.Length); } // GetBytes() /// <summary> /// Encodes a specified String into an array of bytes. /// </summary> /// <param name="s">The character string to encode. </param> /// <returns> /// A byte array containing the encoded representation of the /// specified range of characters in chars. /// </returns> public override byte[] GetBytes(string s) { return GetBytes(s.ToCharArray(), 0, s.Length); } // GetBytes() /// <summary> /// Encodes a range of characters from a character array into a byte array. /// </summary> /// <param name="chars">The character array to encode. </param> /// <param name="index">The starting index of the character array to encode. </param> /// <param name="count">The number of characters to encode.</param> /// <returns> /// A byte array containing the encoded representation of the /// specified range of characters in chars. /// </returns> public override byte[] GetBytes(char[] chars, int index, int count) { return GetEncoding(GermanCodePage).GetBytes(chars, index, count); } // GetBytes() /// <summary> /// Calculates the number of characters that would result from decoding a /// specified range of elements in a byte array. /// </summary> /// <param name="bytes">The byte array to decode.</param> /// <param name="index">The index of the first byte in bytes to decode.</param> /// <param name="count">The number of bytes to decode.</param> /// <returns> /// The number of characters that would result from decoding the /// specified range of elements in bytes. /// </returns> public override int GetCharCount(byte[] bytes, int index, int count) { if (bytes == null) { throw new ArgumentNullException("bytes"); } // if if (index < 0) { throw new ArgumentOutOfRangeException("index", index, "index must be >= 0"); } // if if (index + count > bytes.Length) { throw new ArgumentOutOfRangeException("index", index, "index + count must be <= length"); } // if return GetEncoding(GermanCodePage).GetCharCount(bytes, index, count); } // GetCharCount() /// <summary> /// Decodes a specified range of elements from a byte array, and stores the /// result into a specified range of elements in a Unicode character array. /// </summary> /// <param name="bytes">The byte array to decode. </param> /// <param name="byteIndex">The index of the first element in bytes to decode. </param> /// <param name="byteCount">The number of elements to decode. </param> /// <param name="chars">The character array where the decoded results are stored. </param> /// <param name="charIndex">The index of the first element in chars to store decoded results. </param> /// <returns> /// The number of characters stored in chars. /// </returns> public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { for (int i = 0; i < byteCount; i++) { chars[charIndex + i] = (char)bytes[byteIndex + i]; } // for return byteCount; } // GetChars() /// <summary> /// Calculates the maximum number of bytes required to encode a /// specified number of characters. /// </summary> /// <param name="charCount">The number of characters to encode.</param> /// <returns> /// The maximum number of bytes required to encode charCount number of /// characters. /// </returns> public override int GetMaxByteCount(int charCount) { if (charCount < 0) { throw new ArgumentOutOfRangeException("charCount", charCount, "charCount must be >= 0"); } // if // we have a 1:1 mapping return charCount; } // GetMaxByteCount() /// <summary> /// Calculates the maximum number of characters that can result from /// decoding a specified number of bytes. /// </summary> /// <param name="byteCount">The number of bytes to decode. </param> /// <returns>The maximum number of characters that can result from /// decoding byteCount number of bytes.</returns> public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) { throw new ArgumentOutOfRangeException("byteCount", byteCount, "byteCount must be >= 0"); } // if // we have a 1:1 mapping return byteCount; } // GetMaxCharCount() #endregion // CORE FUNCTIONS } // SerialPortEncoding } // Tethys.IO // =================================== // Tethys: end of serialportencoding.cs // ===================================
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Reflection; using System.CommandLine; using System.Runtime.InteropServices; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; using Internal.CommandLine; namespace ILCompiler { internal class Program { private Dictionary<string, string> _inputFilePaths = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); private Dictionary<string, string> _referenceFilePaths = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); private string _outputFilePath; private bool _isCppCodegen; private bool _isVerbose; private string _dgmlLogFileName; private bool _generateFullDgmlLog; private TargetArchitecture _targetArchitecture; private string _targetArchitectureStr; private TargetOS _targetOS; private string _targetOSStr; private OptimizationMode _optimizationMode; private bool _enableDebugInfo; private string _systemModuleName = "System.Private.CoreLib"; private bool _multiFile; private bool _useSharedGenerics; private string _mapFileName; private string _singleMethodTypeName; private string _singleMethodName; private IReadOnlyList<string> _singleMethodGenericArgs; private IReadOnlyList<string> _codegenOptions = Array.Empty<string>(); private IReadOnlyList<string> _rdXmlFilePaths = Array.Empty<string>(); private bool _help; private Program() { } private void Help(string helpText) { Console.WriteLine(); Console.Write("Microsoft (R) .NET Native IL Compiler"); Console.Write(" "); Console.Write(typeof(Program).GetTypeInfo().Assembly.GetName().Version); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(helpText); } private void InitializeDefaultOptions() { #if FXCORE // We could offer this as a command line option, but then we also need to // load a different RyuJIT, so this is a future nice to have... if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) _targetOS = TargetOS.Windows; else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) _targetOS = TargetOS.Linux; else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) _targetOS = TargetOS.OSX; else throw new NotImplementedException(); switch (RuntimeInformation.ProcessArchitecture) { case Architecture.X86: _targetArchitecture = TargetArchitecture.X86; break; case Architecture.X64: _targetArchitecture = TargetArchitecture.X64; break; case Architecture.Arm: _targetArchitecture = TargetArchitecture.ARM; break; case Architecture.Arm64: _targetArchitecture = TargetArchitecture.ARM64; break; default: throw new NotImplementedException(); } #else _targetOS = TargetOS.Windows; _targetArchitecture = TargetArchitecture.X64; #endif } private ArgumentSyntax ParseCommandLine(string[] args) { IReadOnlyList<string> inputFiles = Array.Empty<string>(); IReadOnlyList<string> referenceFiles = Array.Empty<string>(); bool optimize = false; bool waitForDebugger = false; AssemblyName name = typeof(Program).GetTypeInfo().Assembly.GetName(); ArgumentSyntax argSyntax = ArgumentSyntax.Parse(args, syntax => { syntax.ApplicationName = name.Name.ToString(); // HandleHelp writes to error, fails fast with crash dialog and lacks custom formatting. syntax.HandleHelp = false; syntax.HandleErrors = true; syntax.DefineOption("h|help", ref _help, "Help message for ILC"); syntax.DefineOptionList("r|reference", ref referenceFiles, "Reference file(s) for compilation"); syntax.DefineOption("o|out", ref _outputFilePath, "Output file path"); syntax.DefineOption("O", ref optimize, "Enable optimizations"); syntax.DefineOption("g", ref _enableDebugInfo, "Emit debugging information"); syntax.DefineOption("cpp", ref _isCppCodegen, "Compile for C++ code-generation"); syntax.DefineOption("dgmllog", ref _dgmlLogFileName, "Save result of dependency analysis as DGML"); syntax.DefineOption("fulllog", ref _generateFullDgmlLog, "Save detailed log of dependency analysis"); syntax.DefineOption("verbose", ref _isVerbose, "Enable verbose logging"); syntax.DefineOption("systemmodule", ref _systemModuleName, "System module name (default: System.Private.CoreLib)"); syntax.DefineOption("multifile", ref _multiFile, "Compile only input files (do not compile referenced assemblies)"); syntax.DefineOption("waitfordebugger", ref waitForDebugger, "Pause to give opportunity to attach debugger"); syntax.DefineOption("usesharedgenerics", ref _useSharedGenerics, "Enable shared generics"); syntax.DefineOptionList("codegenopt", ref _codegenOptions, "Define a codegen option"); syntax.DefineOptionList("rdxml", ref _rdXmlFilePaths, "RD.XML file(s) for compilation"); syntax.DefineOption("map", ref _mapFileName, "Generate a map file"); syntax.DefineOption("targetarch", ref _targetArchitectureStr, "Target architecture for cross compilation"); syntax.DefineOption("targetos", ref _targetOSStr, "Target OS for cross compilation"); syntax.DefineOption("singlemethodtypename", ref _singleMethodTypeName, "Single method compilation: name of the owning type"); syntax.DefineOption("singlemethodname", ref _singleMethodName, "Single method compilation: name of the method"); syntax.DefineOptionList("singlemethodgenericarg", ref _singleMethodGenericArgs, "Single method compilation: generic arguments to the method"); syntax.DefineParameterList("in", ref inputFiles, "Input file(s) to compile"); }); if (waitForDebugger) { Console.WriteLine("Waiting for debugger to attach. Press ENTER to continue"); Console.ReadLine(); } _optimizationMode = optimize ? OptimizationMode.Blended : OptimizationMode.None; foreach (var input in inputFiles) Helpers.AppendExpandedPaths(_inputFilePaths, input, true); foreach (var reference in referenceFiles) Helpers.AppendExpandedPaths(_referenceFilePaths, reference, false); return argSyntax; } private int Run(string[] args) { InitializeDefaultOptions(); ArgumentSyntax syntax = ParseCommandLine(args); if (_help) { Help(syntax.GetHelpText()); return 1; } if (_outputFilePath == null) throw new CommandLineException("Output filename must be specified (/out <file>)"); // // Set target Architecture and OS // if (_targetArchitectureStr != null) { if (_targetArchitectureStr.Equals("x86", StringComparison.OrdinalIgnoreCase)) _targetArchitecture = TargetArchitecture.X86; else if (_targetArchitectureStr.Equals("x64", StringComparison.OrdinalIgnoreCase)) _targetArchitecture = TargetArchitecture.X64; else if (_targetArchitectureStr.Equals("arm", StringComparison.OrdinalIgnoreCase)) _targetArchitecture = TargetArchitecture.ARM; else if (_targetArchitectureStr.Equals("armel", StringComparison.OrdinalIgnoreCase)) _targetArchitecture = TargetArchitecture.ARMEL; else if (_targetArchitectureStr.Equals("arm64", StringComparison.OrdinalIgnoreCase)) _targetArchitecture = TargetArchitecture.ARM64; else throw new CommandLineException("Target architecture is not supported"); } if (_targetOSStr != null) { if (_targetOSStr.Equals("windows", StringComparison.OrdinalIgnoreCase)) _targetOS = TargetOS.Windows; else if (_targetOSStr.Equals("linux", StringComparison.OrdinalIgnoreCase)) _targetOS = TargetOS.Linux; else if (_targetOSStr.Equals("osx", StringComparison.OrdinalIgnoreCase)) _targetOS = TargetOS.OSX; else throw new CommandLineException("Target OS is not supported"); } // // Initialize type system context // SharedGenericsMode genericsMode = _useSharedGenerics ? SharedGenericsMode.CanonicalReferenceTypes : SharedGenericsMode.Disabled; var typeSystemContext = new CompilerTypeSystemContext(new TargetDetails(_targetArchitecture, _targetOS, TargetAbi.CoreRT), genericsMode); // // TODO: To support our pre-compiled test tree, allow input files that aren't managed assemblies since // some tests contain a mixture of both managed and native binaries. // // See: https://github.com/dotnet/corert/issues/2785 // // When we undo this this hack, replace this foreach with // typeSystemContext.InputFilePaths = _inputFilePaths; // Dictionary<string, string> inputFilePaths = new Dictionary<string, string>(); foreach (var inputFile in _inputFilePaths) { try { var module = typeSystemContext.GetModuleFromPath(inputFile.Value); inputFilePaths.Add(inputFile.Key, inputFile.Value); } catch (TypeSystemException.BadImageFormatException) { // Keep calm and carry on. } } typeSystemContext.InputFilePaths = inputFilePaths; typeSystemContext.ReferenceFilePaths = _referenceFilePaths; typeSystemContext.SetSystemModule(typeSystemContext.GetModuleForSimpleName(_systemModuleName)); if (typeSystemContext.InputFilePaths.Count == 0) throw new CommandLineException("No input files specified"); // // Initialize compilation group and compilation roots // // Single method mode? MethodDesc singleMethod = CheckAndParseSingleMethodModeArguments(typeSystemContext); CompilationModuleGroup compilationGroup; List<ICompilationRootProvider> compilationRoots = new List<ICompilationRootProvider>(); if (singleMethod != null) { // Compiling just a single method compilationGroup = new SingleMethodCompilationModuleGroup(singleMethod); compilationRoots.Add(new SingleMethodRootProvider(singleMethod)); } else { // Either single file, or multifile library, or multifile consumption. EcmaModule entrypointModule = null; foreach (var inputFile in typeSystemContext.InputFilePaths) { EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value); if (module.PEReader.PEHeaders.IsExe) { if (entrypointModule != null) throw new Exception("Multiple EXE modules"); entrypointModule = module; } compilationRoots.Add(new ExportedMethodsRootProvider(module)); } if (entrypointModule != null) { LibraryInitializers libraryInitializers = new LibraryInitializers(typeSystemContext, _isCppCodegen); compilationRoots.Add(new MainMethodRootProvider(entrypointModule, libraryInitializers.LibraryInitializerMethods)); } if (_multiFile) { List<EcmaModule> inputModules = new List<EcmaModule>(); foreach (var inputFile in typeSystemContext.InputFilePaths) { EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value); if (entrypointModule == null) { // This is a multifile production build - we need to root all methods compilationRoots.Add(new LibraryRootProvider(module)); } inputModules.Add(module); } if (entrypointModule == null) compilationGroup = new MultiFileSharedCompilationModuleGroup(typeSystemContext, inputModules); else compilationGroup = new MultiFileLeafCompilationModuleGroup(typeSystemContext, inputModules); } else { if (entrypointModule == null) throw new Exception("No entrypoint module"); compilationRoots.Add(new ExportedMethodsRootProvider((EcmaModule)typeSystemContext.SystemModule)); compilationGroup = new SingleFileCompilationModuleGroup(typeSystemContext); } foreach (var rdXmlFilePath in _rdXmlFilePaths) { compilationRoots.Add(new RdXmlRootProvider(typeSystemContext, rdXmlFilePath)); } } // // Compile // CompilationBuilder builder; if (_isCppCodegen) builder = new CppCodegenCompilationBuilder(typeSystemContext, compilationGroup); else builder = new RyuJitCompilationBuilder(typeSystemContext, compilationGroup); var logger = _isVerbose ? new Logger(Console.Out, true) : Logger.Null; DependencyTrackingLevel trackingLevel = _dgmlLogFileName == null ? DependencyTrackingLevel.None : (_generateFullDgmlLog ? DependencyTrackingLevel.All : DependencyTrackingLevel.First); ICompilation compilation = builder .UseBackendOptions(_codegenOptions) .UseLogger(logger) .UseDependencyTracking(trackingLevel) .UseCompilationRoots(compilationRoots) .UseOptimizationMode(_optimizationMode) .UseDebugInfo(_enableDebugInfo) .ToCompilation(); ObjectDumper dumper = _mapFileName != null ? new ObjectDumper(_mapFileName) : null; compilation.Compile(_outputFilePath, dumper); if (_dgmlLogFileName != null) compilation.WriteDependencyLog(_dgmlLogFileName); return 0; } private TypeDesc FindType(CompilerTypeSystemContext context, string typeName) { ModuleDesc systemModule = context.SystemModule; TypeDesc foundType = systemModule.GetTypeByCustomAttributeTypeName(typeName); if (foundType == null) throw new CommandLineException($"Type '{typeName}' not found"); TypeDesc classLibCanon = systemModule.GetType("System", "__Canon", false); TypeDesc classLibUniCanon = systemModule.GetType("System", "__UniversalCanon", false); return foundType.ReplaceTypesInConstructionOfType( new TypeDesc[] { classLibCanon, classLibUniCanon }, new TypeDesc[] { context.CanonType, context.UniversalCanonType }); } private MethodDesc CheckAndParseSingleMethodModeArguments(CompilerTypeSystemContext context) { if (_singleMethodName == null && _singleMethodTypeName == null && _singleMethodGenericArgs == null) return null; if (_singleMethodName == null || _singleMethodTypeName == null) throw new CommandLineException("Both method name and type name are required parameters for single method mode"); TypeDesc owningType = FindType(context, _singleMethodTypeName); // TODO: allow specifying signature to distinguish overloads MethodDesc method = owningType.GetMethod(_singleMethodName, null); if (method == null) throw new CommandLineException($"Method '{_singleMethodName}' not found in '{_singleMethodTypeName}'"); if (method.HasInstantiation != (_singleMethodGenericArgs != null) || (method.HasInstantiation && (method.Instantiation.Length != _singleMethodGenericArgs.Count))) { throw new CommandLineException( $"Expected {method.Instantiation.Length} generic arguments for method '{_singleMethodName}' on type '{_singleMethodTypeName}'"); } if (method.HasInstantiation) { List<TypeDesc> genericArguments = new List<TypeDesc>(); foreach (var argString in _singleMethodGenericArgs) genericArguments.Add(FindType(context, argString)); method = method.MakeInstantiatedMethod(genericArguments.ToArray()); } return method; } private static int Main(string[] args) { #if DEBUG return new Program().Run(args); #else try { return new Program().Run(args); } catch (Exception e) { Console.Error.WriteLine("Error: " + e.Message); Console.Error.WriteLine(e.ToString()); return 1; } #endif } } }
using System; using System.IO; using System.ComponentModel; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using ChargeBee.Internal; using ChargeBee.Api; using ChargeBee.Models.Enums; using ChargeBee.Filters.Enums; namespace ChargeBee.Models { public class QuotedSubscription : Resource { public QuotedSubscription() { } public QuotedSubscription(Stream stream) { using (StreamReader reader = new StreamReader(stream)) { JObj = JToken.Parse(reader.ReadToEnd()); apiVersionCheck (JObj); } } public QuotedSubscription(TextReader reader) { JObj = JToken.Parse(reader.ReadToEnd()); apiVersionCheck (JObj); } public QuotedSubscription(String jsonString) { JObj = JToken.Parse(jsonString); apiVersionCheck (JObj); } #region Methods #endregion #region Properties public string Id { get { return GetValue<string>("id", true); } } public string PlanId { get { return GetValue<string>("plan_id", false); } } public int PlanQuantity { get { return GetValue<int>("plan_quantity", false); } } public int? PlanUnitPrice { get { return GetValue<int?>("plan_unit_price", false); } } public int? SetupFee { get { return GetValue<int?>("setup_fee", false); } } public int? BillingPeriod { get { return GetValue<int?>("billing_period", false); } } public BillingPeriodUnitEnum? BillingPeriodUnit { get { return GetEnum<BillingPeriodUnitEnum>("billing_period_unit", false); } } public DateTime? StartDate { get { return GetDateTime("start_date", false); } } public DateTime? TrialEnd { get { return GetDateTime("trial_end", false); } } public int? RemainingBillingCycles { get { return GetValue<int?>("remaining_billing_cycles", false); } } public string PoNumber { get { return GetValue<string>("po_number", false); } } public AutoCollectionEnum? AutoCollection { get { return GetEnum<AutoCollectionEnum>("auto_collection", false); } } public string PlanQuantityInDecimal { get { return GetValue<string>("plan_quantity_in_decimal", false); } } public string PlanUnitPriceInDecimal { get { return GetValue<string>("plan_unit_price_in_decimal", false); } } public DateTime? ChangesScheduledAt { get { return GetDateTime("changes_scheduled_at", false); } } public ChangeOptionEnum? ChangeOption { get { return GetEnum<ChangeOptionEnum>("change_option", false); } } public int? ContractTermBillingCycleOnRenewal { get { return GetValue<int?>("contract_term_billing_cycle_on_renewal", false); } } public List<QuotedSubscriptionAddon> Addons { get { return GetResourceList<QuotedSubscriptionAddon>("addons"); } } public List<QuotedSubscriptionEventBasedAddon> EventBasedAddons { get { return GetResourceList<QuotedSubscriptionEventBasedAddon>("event_based_addons"); } } public List<QuotedSubscriptionCoupon> Coupons { get { return GetResourceList<QuotedSubscriptionCoupon>("coupons"); } } public List<QuotedSubscriptionSubscriptionItem> SubscriptionItems { get { return GetResourceList<QuotedSubscriptionSubscriptionItem>("subscription_items"); } } public List<QuotedSubscriptionItemTier> ItemTiers { get { return GetResourceList<QuotedSubscriptionItemTier>("item_tiers"); } } public QuotedSubscriptionQuotedContractTerm QuotedContractTerm { get { return GetSubResource<QuotedSubscriptionQuotedContractTerm>("quoted_contract_term"); } } #endregion public enum BillingPeriodUnitEnum { UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a dotnet-client version incompatibility. We suggest you to upgrade to the latest version */ [EnumMember(Value = "day")] Day, [EnumMember(Value = "week")] Week, [EnumMember(Value = "month")] Month, [EnumMember(Value = "year")] Year, } public enum ChangeOptionEnum { UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a dotnet-client version incompatibility. We suggest you to upgrade to the latest version */ [EnumMember(Value = "end_of_term")] EndOfTerm, [EnumMember(Value = "specific_date")] SpecificDate, [EnumMember(Value = "immediately")] Immediately, } #region Subclasses public class QuotedSubscriptionAddon : Resource { public string Id { get { return GetValue<string>("id", true); } } public int? Quantity { get { return GetValue<int?>("quantity", false); } } public int? UnitPrice { get { return GetValue<int?>("unit_price", false); } } public int? Amount { get { return GetValue<int?>("amount", false); } } public DateTime? TrialEnd { get { return GetDateTime("trial_end", false); } } public int? RemainingBillingCycles { get { return GetValue<int?>("remaining_billing_cycles", false); } } public string QuantityInDecimal { get { return GetValue<string>("quantity_in_decimal", false); } } public string UnitPriceInDecimal { get { return GetValue<string>("unit_price_in_decimal", false); } } public string AmountInDecimal { get { return GetValue<string>("amount_in_decimal", false); } } } public class QuotedSubscriptionEventBasedAddon : Resource { public enum OnEventEnum { UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a dotnet-client version incompatibility. We suggest you to upgrade to the latest version */ [EnumMember(Value = "subscription_creation")] SubscriptionCreation, [EnumMember(Value = "subscription_trial_start")] SubscriptionTrialStart, [EnumMember(Value = "plan_activation")] PlanActivation, [EnumMember(Value = "subscription_activation")] SubscriptionActivation, [EnumMember(Value = "contract_termination")] ContractTermination, } public string Id { get { return GetValue<string>("id", true); } } public int Quantity { get { return GetValue<int>("quantity", true); } } public int UnitPrice { get { return GetValue<int>("unit_price", true); } } public int? ServicePeriodInDays { get { return GetValue<int?>("service_period_in_days", false); } } public OnEventEnum OnEvent { get { return GetEnum<OnEventEnum>("on_event", true); } } public bool ChargeOnce { get { return GetValue<bool>("charge_once", true); } } public string QuantityInDecimal { get { return GetValue<string>("quantity_in_decimal", false); } } public string UnitPriceInDecimal { get { return GetValue<string>("unit_price_in_decimal", false); } } } public class QuotedSubscriptionCoupon : Resource { public string CouponId { get { return GetValue<string>("coupon_id", true); } } } public class QuotedSubscriptionSubscriptionItem : Resource { public enum ItemTypeEnum { UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a dotnet-client version incompatibility. We suggest you to upgrade to the latest version */ [EnumMember(Value = "plan")] Plan, [EnumMember(Value = "addon")] Addon, [EnumMember(Value = "charge")] Charge, } public enum ChargeOnOptionEnum { UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a dotnet-client version incompatibility. We suggest you to upgrade to the latest version */ [EnumMember(Value = "immediately")] Immediately, [EnumMember(Value = "on_event")] OnEvent, } public string ItemPriceId { get { return GetValue<string>("item_price_id", true); } } public ItemTypeEnum ItemType { get { return GetEnum<ItemTypeEnum>("item_type", true); } } public int? Quantity { get { return GetValue<int?>("quantity", false); } } public string QuantityInDecimal { get { return GetValue<string>("quantity_in_decimal", false); } } public string MeteredQuantity { get { return GetValue<string>("metered_quantity", false); } } public DateTime? LastCalculatedAt { get { return GetDateTime("last_calculated_at", false); } } public int? UnitPrice { get { return GetValue<int?>("unit_price", false); } } public string UnitPriceInDecimal { get { return GetValue<string>("unit_price_in_decimal", false); } } public int? Amount { get { return GetValue<int?>("amount", false); } } public string AmountInDecimal { get { return GetValue<string>("amount_in_decimal", false); } } public int? FreeQuantity { get { return GetValue<int?>("free_quantity", false); } } public string FreeQuantityInDecimal { get { return GetValue<string>("free_quantity_in_decimal", false); } } public DateTime? TrialEnd { get { return GetDateTime("trial_end", false); } } public int? BillingCycles { get { return GetValue<int?>("billing_cycles", false); } } public int? ServicePeriodDays { get { return GetValue<int?>("service_period_days", false); } } public ChargeOnEventEnum? ChargeOnEvent { get { return GetEnum<ChargeOnEventEnum>("charge_on_event", false); } } public bool? ChargeOnce { get { return GetValue<bool?>("charge_once", false); } } public ChargeOnOptionEnum? ChargeOnOption { get { return GetEnum<ChargeOnOptionEnum>("charge_on_option", false); } } } public class QuotedSubscriptionItemTier : Resource { public string ItemPriceId { get { return GetValue<string>("item_price_id", true); } } public int StartingUnit { get { return GetValue<int>("starting_unit", true); } } public int? EndingUnit { get { return GetValue<int?>("ending_unit", false); } } public int Price { get { return GetValue<int>("price", true); } } public string StartingUnitInDecimal { get { return GetValue<string>("starting_unit_in_decimal", false); } } public string EndingUnitInDecimal { get { return GetValue<string>("ending_unit_in_decimal", false); } } public string PriceInDecimal { get { return GetValue<string>("price_in_decimal", false); } } } public class QuotedSubscriptionQuotedContractTerm : Resource { public enum ActionAtTermEndEnum { UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a dotnet-client version incompatibility. We suggest you to upgrade to the latest version */ [EnumMember(Value = "renew")] Renew, [EnumMember(Value = "evergreen")] Evergreen, [EnumMember(Value = "cancel")] Cancel, [EnumMember(Value = "renew_once")] RenewOnce, } public DateTime ContractStart { get { return (DateTime)GetDateTime("contract_start", true); } } public DateTime ContractEnd { get { return (DateTime)GetDateTime("contract_end", true); } } public int BillingCycle { get { return GetValue<int>("billing_cycle", true); } } public ActionAtTermEndEnum ActionAtTermEnd { get { return GetEnum<ActionAtTermEndEnum>("action_at_term_end", true); } } public long TotalContractValue { get { return GetValue<long>("total_contract_value", true); } } public int? CancellationCutoffPeriod { get { return GetValue<int?>("cancellation_cutoff_period", false); } } } #endregion } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // This source file is machine generated. Please do not change the code manually. using System; using System.Collections.Generic; using System.IO.Packaging; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Spreadsheet; namespace DocumentFormat.OpenXml.Office.Excel { /// <summary> /// <para>Defines the Macrosheet Class. The root element of MacroSheetPart.</para> /// <para> When the object is serialized out as xml, its qualified name is xne:macrosheet.</para> /// </summary> /// <remarks> /// The following table lists the possible child types: /// <list type="bullet"> ///<item><description>DocumentFormat.OpenXml.Spreadsheet.SheetProperties &lt;x:sheetPr></description></item> ///<item><description>DocumentFormat.OpenXml.Spreadsheet.SheetDimension &lt;x:dimension></description></item> ///<item><description>DocumentFormat.OpenXml.Spreadsheet.SheetViews &lt;x:sheetViews></description></item> ///<item><description>DocumentFormat.OpenXml.Spreadsheet.SheetFormatProperties &lt;x:sheetFormatPr></description></item> ///<item><description>DocumentFormat.OpenXml.Spreadsheet.Columns &lt;x:cols></description></item> ///<item><description>DocumentFormat.OpenXml.Spreadsheet.SheetData &lt;x:sheetData></description></item> ///<item><description>DocumentFormat.OpenXml.Spreadsheet.SheetProtection &lt;x:sheetProtection></description></item> ///<item><description>DocumentFormat.OpenXml.Spreadsheet.AutoFilter &lt;x:autoFilter></description></item> ///<item><description>DocumentFormat.OpenXml.Spreadsheet.SortState &lt;x:sortState></description></item> ///<item><description>DocumentFormat.OpenXml.Spreadsheet.DataConsolidate &lt;x:dataConsolidate></description></item> ///<item><description>DocumentFormat.OpenXml.Spreadsheet.CustomSheetViews &lt;x:customSheetViews></description></item> ///<item><description>DocumentFormat.OpenXml.Spreadsheet.PhoneticProperties &lt;x:phoneticPr></description></item> ///<item><description>DocumentFormat.OpenXml.Spreadsheet.ConditionalFormatting &lt;x:conditionalFormatting></description></item> ///<item><description>DocumentFormat.OpenXml.Spreadsheet.PrintOptions &lt;x:printOptions></description></item> ///<item><description>DocumentFormat.OpenXml.Spreadsheet.PageMargins &lt;x:pageMargins></description></item> ///<item><description>DocumentFormat.OpenXml.Spreadsheet.PageSetup &lt;x:pageSetup></description></item> ///<item><description>DocumentFormat.OpenXml.Spreadsheet.HeaderFooter &lt;x:headerFooter></description></item> ///<item><description>DocumentFormat.OpenXml.Spreadsheet.RowBreaks &lt;x:rowBreaks></description></item> ///<item><description>DocumentFormat.OpenXml.Spreadsheet.ColumnBreaks &lt;x:colBreaks></description></item> ///<item><description>DocumentFormat.OpenXml.Spreadsheet.CustomProperties &lt;x:customProperties></description></item> ///<item><description>DocumentFormat.OpenXml.Spreadsheet.Drawing &lt;x:drawing></description></item> ///<item><description>DocumentFormat.OpenXml.Spreadsheet.LegacyDrawing &lt;x:legacyDrawing></description></item> ///<item><description>DocumentFormat.OpenXml.Spreadsheet.LegacyDrawingHeaderFooter &lt;x:legacyDrawingHF></description></item> ///<item><description>DocumentFormat.OpenXml.Spreadsheet.Picture &lt;x:picture></description></item> ///<item><description>DocumentFormat.OpenXml.Spreadsheet.OleObjects &lt;x:oleObjects></description></item> ///<item><description>DocumentFormat.OpenXml.Spreadsheet.DrawingHeaderFooter &lt;x:drawingHF></description></item> ///<item><description>DocumentFormat.OpenXml.Spreadsheet.ExtensionList &lt;x:extLst></description></item> /// </list> /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Spreadsheet.SheetProperties))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Spreadsheet.SheetDimension))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Spreadsheet.SheetViews))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Spreadsheet.SheetFormatProperties))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Spreadsheet.Columns))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Spreadsheet.SheetData))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Spreadsheet.SheetProtection))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Spreadsheet.AutoFilter))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Spreadsheet.SortState))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Spreadsheet.DataConsolidate))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Spreadsheet.CustomSheetViews))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Spreadsheet.PhoneticProperties))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Spreadsheet.ConditionalFormatting))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Spreadsheet.PrintOptions))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Spreadsheet.PageMargins))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Spreadsheet.PageSetup))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Spreadsheet.HeaderFooter))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Spreadsheet.RowBreaks))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Spreadsheet.ColumnBreaks))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Spreadsheet.CustomProperties))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Spreadsheet.Drawing))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Spreadsheet.LegacyDrawing))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Spreadsheet.LegacyDrawingHeaderFooter))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Spreadsheet.Picture))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Spreadsheet.OleObjects))] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Spreadsheet.DrawingHeaderFooter),(FileFormatVersions)2)] [ChildElementInfo(typeof(DocumentFormat.OpenXml.Spreadsheet.ExtensionList))] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class Macrosheet : OpenXmlPartRootElement { private const string tagName = "macrosheet"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 32; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12600; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } /// <summary> /// Macrosheet constructor. /// </summary> /// <param name="ownerPart">The owner part of the Macrosheet.</param> internal Macrosheet(MacroSheetPart ownerPart) : base (ownerPart ) { } /// <summary> /// Loads the DOM from the MacroSheetPart. /// </summary> /// <param name="openXmlPart">Specifies the part to be loaded.</param> public void Load(MacroSheetPart openXmlPart) { LoadFromPart(openXmlPart); } /// <summary> /// Gets the MacroSheetPart associated with this element. /// </summary> public MacroSheetPart MacroSheetPart { get { return OpenXmlPart as MacroSheetPart; } internal set { OpenXmlPart = value; } } /// <summary> ///Initializes a new instance of the Macrosheet class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Macrosheet(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Macrosheet class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public Macrosheet(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the Macrosheet class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public Macrosheet(string outerXml) : base(outerXml) { } /// <summary> /// Initializes a new instance of the Macrosheet class. /// </summary> public Macrosheet() : base () { } /// <summary> /// Saves the DOM into the MacroSheetPart. /// </summary> /// <param name="openXmlPart">Specifies the part to save to.</param> public void Save(MacroSheetPart openXmlPart) { base.SaveToPart(openXmlPart); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] internal override OpenXmlElement ElementFactory(byte namespaceId, string name) { if( 22 == namespaceId && "sheetPr" == name) return new DocumentFormat.OpenXml.Spreadsheet.SheetProperties(); if( 22 == namespaceId && "dimension" == name) return new DocumentFormat.OpenXml.Spreadsheet.SheetDimension(); if( 22 == namespaceId && "sheetViews" == name) return new DocumentFormat.OpenXml.Spreadsheet.SheetViews(); if( 22 == namespaceId && "sheetFormatPr" == name) return new DocumentFormat.OpenXml.Spreadsheet.SheetFormatProperties(); if( 22 == namespaceId && "cols" == name) return new DocumentFormat.OpenXml.Spreadsheet.Columns(); if( 22 == namespaceId && "sheetData" == name) return new DocumentFormat.OpenXml.Spreadsheet.SheetData(); if( 22 == namespaceId && "sheetProtection" == name) return new DocumentFormat.OpenXml.Spreadsheet.SheetProtection(); if( 22 == namespaceId && "autoFilter" == name) return new DocumentFormat.OpenXml.Spreadsheet.AutoFilter(); if( 22 == namespaceId && "sortState" == name) return new DocumentFormat.OpenXml.Spreadsheet.SortState(); if( 22 == namespaceId && "dataConsolidate" == name) return new DocumentFormat.OpenXml.Spreadsheet.DataConsolidate(); if( 22 == namespaceId && "customSheetViews" == name) return new DocumentFormat.OpenXml.Spreadsheet.CustomSheetViews(); if( 22 == namespaceId && "phoneticPr" == name) return new DocumentFormat.OpenXml.Spreadsheet.PhoneticProperties(); if( 22 == namespaceId && "conditionalFormatting" == name) return new DocumentFormat.OpenXml.Spreadsheet.ConditionalFormatting(); if( 22 == namespaceId && "printOptions" == name) return new DocumentFormat.OpenXml.Spreadsheet.PrintOptions(); if( 22 == namespaceId && "pageMargins" == name) return new DocumentFormat.OpenXml.Spreadsheet.PageMargins(); if( 22 == namespaceId && "pageSetup" == name) return new DocumentFormat.OpenXml.Spreadsheet.PageSetup(); if( 22 == namespaceId && "headerFooter" == name) return new DocumentFormat.OpenXml.Spreadsheet.HeaderFooter(); if( 22 == namespaceId && "rowBreaks" == name) return new DocumentFormat.OpenXml.Spreadsheet.RowBreaks(); if( 22 == namespaceId && "colBreaks" == name) return new DocumentFormat.OpenXml.Spreadsheet.ColumnBreaks(); if( 22 == namespaceId && "customProperties" == name) return new DocumentFormat.OpenXml.Spreadsheet.CustomProperties(); if( 22 == namespaceId && "drawing" == name) return new DocumentFormat.OpenXml.Spreadsheet.Drawing(); if( 22 == namespaceId && "legacyDrawing" == name) return new DocumentFormat.OpenXml.Spreadsheet.LegacyDrawing(); if( 22 == namespaceId && "legacyDrawingHF" == name) return new DocumentFormat.OpenXml.Spreadsheet.LegacyDrawingHeaderFooter(); if( 22 == namespaceId && "picture" == name) return new DocumentFormat.OpenXml.Spreadsheet.Picture(); if( 22 == namespaceId && "oleObjects" == name) return new DocumentFormat.OpenXml.Spreadsheet.OleObjects(); if( 22 == namespaceId && "drawingHF" == name) return new DocumentFormat.OpenXml.Spreadsheet.DrawingHeaderFooter(); if( 22 == namespaceId && "extLst" == name) return new DocumentFormat.OpenXml.Spreadsheet.ExtensionList(); return null; } private static readonly string[] eleTagNames = { "sheetPr","dimension","sheetViews","sheetFormatPr","cols","sheetData","sheetProtection","autoFilter","sortState","dataConsolidate","customSheetViews","phoneticPr","conditionalFormatting","printOptions","pageMargins","pageSetup","headerFooter","rowBreaks","colBreaks","customProperties","drawing","legacyDrawing","legacyDrawingHF","picture","oleObjects","drawingHF","extLst" }; private static readonly byte[] eleNamespaceIds = { 22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22 }; internal override string[] ElementTagNames { get{ return eleTagNames; } } internal override byte[] ElementNamespaceIds { get{ return eleNamespaceIds; } } internal override OpenXmlCompositeType OpenXmlCompositeType { get {return OpenXmlCompositeType.OneSequence;} } /// <summary> /// <para> Sheet Properties.</para> /// <para> Represents the following element tag in the schema: x:sheetPr </para> /// </summary> /// <remark> /// xmlns:x = http://schemas.openxmlformats.org/spreadsheetml/2006/main /// </remark> public DocumentFormat.OpenXml.Spreadsheet.SheetProperties SheetProperties { get { return GetElement<DocumentFormat.OpenXml.Spreadsheet.SheetProperties>(0); } set { SetElement(0, value); } } /// <summary> /// <para> Macro Sheet Dimensions.</para> /// <para> Represents the following element tag in the schema: x:dimension </para> /// </summary> /// <remark> /// xmlns:x = http://schemas.openxmlformats.org/spreadsheetml/2006/main /// </remark> public DocumentFormat.OpenXml.Spreadsheet.SheetDimension SheetDimension { get { return GetElement<DocumentFormat.OpenXml.Spreadsheet.SheetDimension>(1); } set { SetElement(1, value); } } /// <summary> /// <para> Macro Sheet Views.</para> /// <para> Represents the following element tag in the schema: x:sheetViews </para> /// </summary> /// <remark> /// xmlns:x = http://schemas.openxmlformats.org/spreadsheetml/2006/main /// </remark> public DocumentFormat.OpenXml.Spreadsheet.SheetViews SheetViews { get { return GetElement<DocumentFormat.OpenXml.Spreadsheet.SheetViews>(2); } set { SetElement(2, value); } } /// <summary> /// <para> Sheet Format Properties.</para> /// <para> Represents the following element tag in the schema: x:sheetFormatPr </para> /// </summary> /// <remark> /// xmlns:x = http://schemas.openxmlformats.org/spreadsheetml/2006/main /// </remark> public DocumentFormat.OpenXml.Spreadsheet.SheetFormatProperties SheetFormatProperties { get { return GetElement<DocumentFormat.OpenXml.Spreadsheet.SheetFormatProperties>(3); } set { SetElement(3, value); } } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<Macrosheet>(deep); } } /// <summary> /// <para>Worksheet Sort Map. The root element of WorksheetSortMapPart.</para> /// <para> When the object is serialized out as xml, its qualified name is xne:worksheetSortMap.</para> /// </summary> /// <remarks> /// The following table lists the possible child types: /// <list type="bullet"> ///<item><description>RowSortMap &lt;xne:rowSortMap></description></item> ///<item><description>ColumnSortMap &lt;xne:colSortMap></description></item> /// </list> /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [ChildElementInfo(typeof(RowSortMap))] [ChildElementInfo(typeof(ColumnSortMap))] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class WorksheetSortMap : OpenXmlPartRootElement { private const string tagName = "worksheetSortMap"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 32; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12601; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } /// <summary> /// WorksheetSortMap constructor. /// </summary> /// <param name="ownerPart">The owner part of the WorksheetSortMap.</param> internal WorksheetSortMap(WorksheetSortMapPart ownerPart) : base (ownerPart ) { } /// <summary> /// Loads the DOM from the WorksheetSortMapPart. /// </summary> /// <param name="openXmlPart">Specifies the part to be loaded.</param> public void Load(WorksheetSortMapPart openXmlPart) { LoadFromPart(openXmlPart); } /// <summary> /// Gets the WorksheetSortMapPart associated with this element. /// </summary> public WorksheetSortMapPart WorksheetSortMapPart { get { return OpenXmlPart as WorksheetSortMapPart; } internal set { OpenXmlPart = value; } } /// <summary> ///Initializes a new instance of the WorksheetSortMap class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public WorksheetSortMap(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the WorksheetSortMap class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public WorksheetSortMap(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the WorksheetSortMap class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public WorksheetSortMap(string outerXml) : base(outerXml) { } /// <summary> /// Initializes a new instance of the WorksheetSortMap class. /// </summary> public WorksheetSortMap() : base () { } /// <summary> /// Saves the DOM into the WorksheetSortMapPart. /// </summary> /// <param name="openXmlPart">Specifies the part to save to.</param> public void Save(WorksheetSortMapPart openXmlPart) { base.SaveToPart(openXmlPart); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] internal override OpenXmlElement ElementFactory(byte namespaceId, string name) { if( 32 == namespaceId && "rowSortMap" == name) return new RowSortMap(); if( 32 == namespaceId && "colSortMap" == name) return new ColumnSortMap(); return null; } private static readonly string[] eleTagNames = { "rowSortMap","colSortMap" }; private static readonly byte[] eleNamespaceIds = { 32,32 }; internal override string[] ElementTagNames { get{ return eleTagNames; } } internal override byte[] ElementNamespaceIds { get{ return eleNamespaceIds; } } internal override OpenXmlCompositeType OpenXmlCompositeType { get {return OpenXmlCompositeType.OneSequence;} } /// <summary> /// <para> Row Sort Map.</para> /// <para> Represents the following element tag in the schema: xne:rowSortMap </para> /// </summary> /// <remark> /// xmlns:xne = http://schemas.microsoft.com/office/excel/2006/main /// </remark> public RowSortMap RowSortMap { get { return GetElement<RowSortMap>(0); } set { SetElement(0, value); } } /// <summary> /// <para> Column Sort Map.</para> /// <para> Represents the following element tag in the schema: xne:colSortMap </para> /// </summary> /// <remark> /// xmlns:xne = http://schemas.microsoft.com/office/excel/2006/main /// </remark> public ColumnSortMap ColumnSortMap { get { return GetElement<ColumnSortMap>(1); } set { SetElement(1, value); } } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<WorksheetSortMap>(deep); } } /// <summary> /// <para>Defines the ReferenceSequence Class.</para> ///<para>This class is only available in Office2010.</para> /// <para> When the object is serialized out as xml, its qualified name is xne:sqref.</para> /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] [OfficeAvailability(FileFormatVersions.Office2010)] public partial class ReferenceSequence : OpenXmlLeafTextElement { private const string tagName = "sqref"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 32; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12602; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((2 & (int)version) > 0) { return true; } return false; } /// <summary> /// Initializes a new instance of the ReferenceSequence class. /// </summary> public ReferenceSequence():base(){} /// <summary> /// Initializes a new instance of the ReferenceSequence class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public ReferenceSequence(string text):base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new ListValue<StringValue>(){ InnerText = text }; } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<ReferenceSequence>(deep); } } /// <summary> /// <para>Defines the Formula Class.</para> ///<para>This class is only available in Office2010.</para> /// <para> When the object is serialized out as xml, its qualified name is xne:f.</para> /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] [OfficeAvailability(FileFormatVersions.Office2010)] public partial class Formula : OpenXmlLeafTextElement { private const string tagName = "f"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 32; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12603; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((2 & (int)version) > 0) { return true; } return false; } /// <summary> /// Initializes a new instance of the Formula class. /// </summary> public Formula():base(){} /// <summary> /// Initializes a new instance of the Formula class with the specified text content. /// </summary> /// <param name="text">Specifies the text content of the element.</param> public Formula(string text):base(text) { } internal override OpenXmlSimpleType InnerTextToValue(string text) { return new StringValue(){ InnerText = text }; } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<Formula>(deep); } } /// <summary> /// <para>Row Sort Map.</para> /// <para> When the object is serialized out as xml, its qualified name is xne:rowSortMap.</para> /// </summary> /// <remarks> /// The following table lists the possible child types: /// <list type="bullet"> ///<item><description>RowSortMapItem &lt;xne:row></description></item> /// </list> /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [ChildElementInfo(typeof(RowSortMapItem))] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class RowSortMap : OpenXmlCompositeElement { private const string tagName = "rowSortMap"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 32; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12604; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } private static string[] attributeTagNames = { "ref","count" }; private static byte[] attributeNamespaceIds = { 0,0 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> Reference.</para> /// <para>Represents the following attribute in the schema: ref </para> /// </summary> [SchemaAttr(0, "ref")] public StringValue Ref { get { return (StringValue)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// <para> Count.</para> /// <para>Represents the following attribute in the schema: count </para> /// </summary> [SchemaAttr(0, "count")] public UInt32Value Count { get { return (UInt32Value)Attributes[1]; } set { Attributes[1] = value; } } /// <summary> /// Initializes a new instance of the RowSortMap class. /// </summary> public RowSortMap():base(){} /// <summary> ///Initializes a new instance of the RowSortMap class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public RowSortMap(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the RowSortMap class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public RowSortMap(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the RowSortMap class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public RowSortMap(string outerXml) : base(outerXml) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] internal override OpenXmlElement ElementFactory(byte namespaceId, string name) { if( 32 == namespaceId && "row" == name) return new RowSortMapItem(); return null; } internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 0 == namespaceId && "ref" == name) return new StringValue(); if( 0 == namespaceId && "count" == name) return new UInt32Value(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<RowSortMap>(deep); } } /// <summary> /// <para>Column Sort Map.</para> /// <para> When the object is serialized out as xml, its qualified name is xne:colSortMap.</para> /// </summary> /// <remarks> /// The following table lists the possible child types: /// <list type="bullet"> ///<item><description>ColumnSortMapItem &lt;xne:col></description></item> /// </list> /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [ChildElementInfo(typeof(ColumnSortMapItem))] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class ColumnSortMap : OpenXmlCompositeElement { private const string tagName = "colSortMap"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 32; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12605; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } private static string[] attributeTagNames = { "ref","count" }; private static byte[] attributeNamespaceIds = { 0,0 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> Reference.</para> /// <para>Represents the following attribute in the schema: ref </para> /// </summary> [SchemaAttr(0, "ref")] public StringValue Ref { get { return (StringValue)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// <para> Count.</para> /// <para>Represents the following attribute in the schema: count </para> /// </summary> [SchemaAttr(0, "count")] public UInt32Value Count { get { return (UInt32Value)Attributes[1]; } set { Attributes[1] = value; } } /// <summary> /// Initializes a new instance of the ColumnSortMap class. /// </summary> public ColumnSortMap():base(){} /// <summary> ///Initializes a new instance of the ColumnSortMap class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ColumnSortMap(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ColumnSortMap class with the specified child elements. /// </summary> /// <param name="childElements">Specifies the child elements.</param> public ColumnSortMap(params OpenXmlElement[] childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the ColumnSortMap class from outer XML. /// </summary> /// <param name="outerXml">Specifies the outer XML of the element.</param> public ColumnSortMap(string outerXml) : base(outerXml) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] internal override OpenXmlElement ElementFactory(byte namespaceId, string name) { if( 32 == namespaceId && "col" == name) return new ColumnSortMapItem(); return null; } internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 0 == namespaceId && "ref" == name) return new StringValue(); if( 0 == namespaceId && "count" == name) return new UInt32Value(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<ColumnSortMap>(deep); } } /// <summary> /// <para>Row.</para> /// <para> When the object is serialized out as xml, its qualified name is xne:row.</para> /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class RowSortMapItem : SortMapItemType { private const string tagName = "row"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 32; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12606; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } /// <summary> /// Initializes a new instance of the RowSortMapItem class. /// </summary> public RowSortMapItem():base(){} /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<RowSortMapItem>(deep); } } /// <summary> /// <para>Column.</para> /// <para> When the object is serialized out as xml, its qualified name is xne:col.</para> /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public partial class ColumnSortMapItem : SortMapItemType { private const string tagName = "col"; /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } private const byte tagNsId = 32; internal override byte NamespaceId { get { return tagNsId; } } internal const int ElementTypeIdConst = 12607; /// <summary> /// Gets the type ID of the element. /// </summary> internal override int ElementTypeId { get { return ElementTypeIdConst; } } /// <summary> /// Whether this element is available in a specific version of Office Application. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { if((7 & (int)version) > 0) { return true; } return false; } /// <summary> /// Initializes a new instance of the ColumnSortMapItem class. /// </summary> public ColumnSortMapItem():base(){} /// <summary> /// Creates a duplicate of this node. /// </summary> /// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param> /// <returns>Returns the cloned node. </returns> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<ColumnSortMapItem>(deep); } } /// <summary> /// Defines the SortMapItemType class. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")] public abstract partial class SortMapItemType : OpenXmlLeafElement { private static string[] attributeTagNames = { "newVal","oldVal" }; private static byte[] attributeNamespaceIds = { 0,0 }; internal override string[] AttributeTagNames { get{ return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get{ return attributeNamespaceIds; } } /// <summary> /// <para> New Value.</para> /// <para>Represents the following attribute in the schema: newVal </para> /// </summary> [SchemaAttr(0, "newVal")] public UInt32Value NewVal { get { return (UInt32Value)Attributes[0]; } set { Attributes[0] = value; } } /// <summary> /// <para> Old Value.</para> /// <para>Represents the following attribute in the schema: oldVal </para> /// </summary> [SchemaAttr(0, "oldVal")] public UInt32Value OldVal { get { return (UInt32Value)Attributes[1]; } set { Attributes[1] = value; } } internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if( 0 == namespaceId && "newVal" == name) return new UInt32Value(); if( 0 == namespaceId && "oldVal" == name) return new UInt32Value(); return base.AttributeFactory(namespaceId, name); } /// <summary> /// Initializes a new instance of the SortMapItemType class. /// </summary> protected SortMapItemType(){} } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="MessageListenerAdapter.cs" company="The original author or authors."> // Copyright 2002-2012 the original author or authors. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on // an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. // </copyright> // -------------------------------------------------------------------------------------------------------------------- #region Using Directives using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Common.Logging; using RabbitMQ.Client; using Spring.Messaging.Amqp.Core; using Spring.Messaging.Amqp.Rabbit.Connection; using Spring.Messaging.Amqp.Rabbit.Core; using Spring.Messaging.Amqp.Rabbit.Support; using Spring.Messaging.Amqp.Support.Converter; using Spring.Objects.Support; using Spring.Util; #endregion namespace Spring.Messaging.Amqp.Rabbit.Listener.Adapter { /// <summary> /// Message listener adapter that delegates the handling of messages to target /// listener methods via reflection, with flexible message type conversion. /// Allows listener methods to operate on message content types, completely /// independent from the Rabbit API. /// </summary> /// <remarks> /// <para>By default, the content of incoming messages gets extracted before /// being passed into the target listener method, to let the target method /// operate on message content types such as String or byte array instead of /// the raw Message. Message type conversion is delegated to a Spring /// <see cref="IMessageConverter"/>. By default, a <see cref="SimpleMessageConverter"/> /// will be used. (If you do not want such automatic message conversion taking /// place, then be sure to set the <see cref="MessageConverter"/> property /// to <code>null</code>.) /// </para> /// <para>If a target listener method returns a non-null object (typically of a /// message content type such as <code>String</code> or byte array), it will get /// wrapped in a Rabbit <code>Message</code> and sent to the exchange of the incoming message /// with the routing key that comes from the Rabbit ReplyTo property if available or via the /// <see cref="ResponseRoutingKey"/> property. /// </para> /// <para> /// The sending of response messages is only available when /// using the <see cref="IChannelAwareMessageListener"/> entry point (typically through a /// Spring message listener container). Usage as a MessageListener /// does <i>not</i> support the generation of response messages. /// </para> /// <para>Consult the reference documentation for examples of method signatures compliant with this /// adapter class. /// </para> /// </remarks> /// <author>Mark Pollack</author> /// <author>Mark Pollack (.NET)</author> /// <author>Juergen Hoeller</author> /// <author>Mark Fisher</author> /// <author>Dave Syer</author> /// <author>Joe Fitzgerald (.NET)</author> public class MessageListenerAdapter : IMessageListener, IChannelAwareMessageListener { /// <summary> /// The default handler method name. /// </summary> public static string ORIGINAL_DEFAULT_LISTENER_METHOD = "HandleMessage"; /// <summary> /// The default response routing key. /// </summary> private static readonly string DEFAULT_RESPONSE_ROUTING_KEY = string.Empty; /// <summary> /// The default encoding. /// </summary> private static string DEFAULT_ENCODING = "UTF-8"; #region Fields /// <summary> /// The Logger. /// </summary> private static readonly ILog Logger = LogManager.GetCurrentClassLogger(); /// <summary> /// The handler object. /// </summary> private object handlerObject; /// <summary> /// The default listener method. /// </summary> private string defaultListenerMethod = ORIGINAL_DEFAULT_LISTENER_METHOD; /// <summary> /// The default response routing key. /// </summary> private string responseRoutingKey = DEFAULT_RESPONSE_ROUTING_KEY; /// <summary> /// The response exchange. /// </summary> private string responseExchange = string.Empty; /// <summary> /// Flag for mandatory publish. /// </summary> private volatile bool mandatoryPublish; /// <summary> /// Flag for immediate publish. /// </summary> private volatile bool immediatePublish; /// <summary> /// The message converter. /// </summary> private IMessageConverter messageConverter; /// <summary> /// The message properties converter. /// </summary> private volatile IMessagePropertiesConverter messagePropertiesConverter = new DefaultMessagePropertiesConverter(); /// <summary> /// The encoding. /// </summary> private string encoding = DEFAULT_ENCODING; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="MessageListenerAdapter"/> class with default settings. /// </summary> public MessageListenerAdapter() { this.InitDefaultStrategies(); this.handlerObject = this; } /// <summary>Initializes a new instance of the <see cref="MessageListenerAdapter"/> class for the given handler object</summary> /// <param name="handlerObject">The delegate object.</param> public MessageListenerAdapter(object handlerObject) { this.InitDefaultStrategies(); this.handlerObject = handlerObject; } /// <summary>Initializes a new instance of the <see cref="MessageListenerAdapter"/> class.</summary> /// <param name="handlerObject">The handler object.</param> /// <param name="messageConverter">The message converter.</param> public MessageListenerAdapter(object handlerObject, IMessageConverter messageConverter) { this.InitDefaultStrategies(); this.handlerObject = handlerObject; this.messageConverter = messageConverter; } #endregion #region Properties /// <summary> /// Gets or sets the handler object to delegate message listening to. /// </summary> /// <remarks> /// Specified listener methods have to be present on this target object. /// If no explicit handler object has been specified, listener /// methods are expected to present on this adapter instance, that is, /// on a custom subclass of this adapter, defining listener methods. /// </remarks> /// <value>The handler object.</value> public object HandlerObject { get { return this.handlerObject; } set { AssertUtils.ArgumentNotNull(value, "HandlerObject must not be null"); this.handlerObject = value; } } /// <summary> /// Sets Encoding. /// </summary> public string Encoding { set { this.encoding = value; } } /// <summary> /// Gets or sets the default handler method to delegate to, /// for the case where no specific listener method has been determined. /// Out-of-the-box value is <see cref="ORIGINAL_DEFAULT_LISTENER_METHOD"/> ("HandleMessage"}. /// </summary> /// <value>The default handler method.</value> public string DefaultListenerMethod { get { return this.defaultListenerMethod; } set { this.defaultListenerMethod = value; } } /// <summary> /// Sets the routing key to use when sending response messages. This will be applied /// in case of a request message that does not carry a "ReplyTo" property. /// Response destinations are only relevant for listener methods that return /// result objects, which will be wrapped in a response message and sent to a /// response destination. /// </summary> /// <value>The default ReplyTo value.</value> public string ResponseRoutingKey { set { this.responseRoutingKey = value; } } /// <summary> /// Sets ResponseExchange. Set the exchange to use when sending response messages. This is only used if the exchange from the received message is null. /// </summary> public string ResponseExchange { set { this.responseExchange = value; } } /// <summary> /// Gets or sets the message converter that will convert incoming Rabbit messages to /// listener method arguments, and objects returned from listener /// methods back to Rabbit messages. /// </summary> /// <remarks> /// <para>The default converter is a {@link SimpleMessageConverter}, which is able /// to handle Byte arrays and strings. /// </para> /// </remarks> /// <value>The message converter.</value> public IMessageConverter MessageConverter { get { return this.messageConverter; } set { this.messageConverter = value; } } /// <summary> /// Sets a value indicating whether MandatoryPublish. /// </summary> public bool MandatoryPublish { set { this.mandatoryPublish = value; } } /// <summary> /// Sets a value indicating whether ImmediatePublish. /// </summary> public bool ImmediatePublish { set { this.immediatePublish = value; } } #endregion /// <summary>Rabbit <see cref="IMessageListener"/> entry point. /// <para>Delegates the message to the target listener method, with appropriate /// conversion of the message arguments</para> /// </summary> /// <remarks>In case of an exception, the <see cref="HandleListenerException"/> method will be invoked.<b>Note</b> /// Does not support sending response messages based on /// result objects returned from listener methods. Use the<see cref="IChannelAwareMessageListener"/> entry point (typically through a Spring /// message listener container) for handling result objects as well.</remarks> /// <param name="message">The incoming message.</param> public void OnMessage(Message message) { try { this.OnMessage(message, null); } catch (Exception e) { this.HandleListenerException(e); } } /// <summary>Spring <see cref="IChannelAwareMessageListener"/> entry point. /// <para> /// Delegates the message to the target listener method, with appropriate /// conversion of the message argument. If the target method returns a /// non-null object, wrap in a Rabbit message and send it back.</para> /// </summary> /// <param name="message">The incoming message.</param> /// <param name="channel">The channel to operate on.</param> public void OnMessage(Message message, IModel channel) { if (this.handlerObject != this) { if (this.handlerObject is IChannelAwareMessageListener) { if (channel != null) { ((IChannelAwareMessageListener)this.handlerObject).OnMessage(message, channel); return; } else if (!(this.handlerObject is IMessageListener)) { throw new AmqpIllegalStateException( "MessageListenerAdapter cannot handle a " + "IChannelAwareMessageListener delegate if it hasn't been invoked with a Channel itself"); } } if (this.handlerObject is IMessageListener) { ((IMessageListener)this.handlerObject).OnMessage(message); return; } } // Regular case: find a handler method reflectively. var convertedMessage = this.ExtractMessage(message); if (this.handlerObject is Func<string, string> && convertedMessage is string) { var anonymousResult = ((Func<string, string>)this.handlerObject).Invoke((string)convertedMessage); if (anonymousResult != null) { this.HandleResult(anonymousResult, message, channel); return; } } var methodName = this.GetListenerMethodName(message, convertedMessage); if (methodName == null) { throw new AmqpIllegalStateException( "No default listener method specified: " + "Either specify a non-null value for the 'DefaultListenerMethod' property or " + "override the 'GetListenerMethodName' method."); } // Invoke the handler method with appropriate arguments. var listenerArguments = this.BuildListenerArguments(convertedMessage); var result = this.InvokeListenerMethod(methodName, listenerArguments); if (result != null) { this.HandleResult(result, message, channel); } else { Logger.Trace(m => m("No result object given - no result to handle")); } } /// <summary> /// Initialize the default implementations for the adapter's strategies. /// </summary> protected virtual void InitDefaultStrategies() { this.MessageConverter = new SimpleMessageConverter(); } /// <summary>Handle the given exception that arose during listener execution. /// The default implementation logs the exception at error level. /// <para>This method only applies when used with <see cref="IMessageListener"/>. /// In case of the Spring <see cref="IChannelAwareMessageListener"/> mechanism, /// exceptions get handled by the caller instead.</para> /// </summary> /// <param name="ex">The exception to handle.</param> protected virtual void HandleListenerException(Exception ex) { Logger.Error(m => m("Listener execution failed"), ex); } /// <summary>Extract the message body from the given message.</summary> /// <param name="message">The message.</param> /// <returns>the content of the message, to be passed into the /// listener method as argument</returns> private object ExtractMessage(Message message) { var converter = this.MessageConverter; if (converter != null) { return converter.FromMessage(message); } return message; } /// <summary>Gets the name of the listener method that is supposed to /// handle the given message. /// The default implementation simply returns the configured /// default listener method, if any.</summary> /// <param name="originalMessage">The EMS request message.</param> /// <param name="extractedMessage">The converted Rabbit request message, /// to be passed into the listener method as argument.</param> /// <returns>the name of the listener method (never /// <code>null</code> /// )</returns> protected virtual string GetListenerMethodName(Message originalMessage, object extractedMessage) { return this.DefaultListenerMethod; } /// <summary>The build listener arguments.</summary> /// <param name="extractedMessage">The extracted Message.</param> /// Build an array of arguments to be passed into the target listener method. Allows for multiple method arguments to /// be built from a single message object. /// <para> /// The default implementation builds an array with the given message object as sole element. This means that the /// extracted message will always be passed into a <i>single</i> method argument, even if it is an array, with the /// target method having a corresponding single argument of the array's type declared.</para> /// <para>This can be overridden to treat special message content such as arrays differently, for example passing in each /// element of the message array as distinct method argument. /// @param extractedMessage the content of the message /// @return the array of arguments to be passed into the listener method (each element of the array corresponding to /// a distinct method argument)</para> /// <returns>The System.Object[].</returns> protected object[] BuildListenerArguments(object extractedMessage) { return new[] { extractedMessage }; } /// <summary>Invokes the specified listener method.</summary> /// <param name="methodName">The name of the listener method.</param> /// <param name="arguments">The message arguments to be passed in.</param> /// <returns>The result returned from the listener method.</returns> protected object InvokeListenerMethod(string methodName, object[] arguments) { try { var methodInvoker = new MethodInvoker(); methodInvoker.TargetObject = this.handlerObject; methodInvoker.TargetMethod = methodName; methodInvoker.Arguments = arguments; methodInvoker.Prepare(); var result = methodInvoker.Invoke(); if (result == MethodInvoker.Void) { return null; } return result; } catch (TargetInvocationException ex) { var targetEx = ex.InnerException; if (targetEx is IOException) { throw new AmqpIOException(targetEx); } else { throw new ListenerExecutionFailedException("Listener method '" + methodName + "' threw exception", targetEx); } } catch (Exception ex) { throw new ListenerExecutionFailedException(this.BuildInvocationFailureMessage(methodName, arguments), ex); } } private string BuildInvocationFailureMessage(string methodName, object[] arguments) { return "Failed to invoke target method '" + methodName + "' with argument types = [" + StringUtils.CollectionToCommaDelimitedString(this.GetArgumentTypes(arguments)) + "], values = [" + StringUtils.CollectionToCommaDelimitedString(arguments) + "]"; } private List<string> GetArgumentTypes(object[] arguments) { var argumentTypes = new List<string>(); if (arguments != null) { for (int i = 0; i < arguments.Length; i++) { argumentTypes.Add(arguments[i].GetType().ToString()); } } return argumentTypes; } /// <summary>Handles the given result object returned from the listener method, sending a response message back. </summary> /// <param name="result">The result object to handle (never /// <code>null</code> /// ).</param> /// <param name="request">The original request message.</param> /// <param name="channel">The channel to operate on (may be /// <code>null</code> /// ).</param> protected virtual void HandleResult(object result, Message request, IModel channel) { if (channel != null) { Logger.Debug(m => m("Listener method returned result [{0}] - generating response message for it", result)); var response = this.BuildMessage(channel, result); this.PostProcessResponse(request, response); var replyTo = this.GetReplyToAddress(request); this.SendResponse(channel, replyTo, response); } else { Logger.Warn(m => m("Listener method returned result [{0}]: not generating response message for it because of no Rabbit Channel given", result)); } } /// <summary>Get the received exchange.</summary> /// <param name="request">The request.</param> /// <returns>The received exchange.</returns> protected string GetReceivedExchange(Message request) { return request.MessageProperties.ReceivedExchange; } /// <summary>Builds a Rabbit message to be sent as response based on the given result object.</summary> /// <param name="channel">The Rabbit Channel to operate on.</param> /// <param name="result">The content of the message, as returned from the listener method.</param> /// <returns>the Rabbit /// <code>Message</code> /// (never /// <code>null</code> /// )</returns> /// <exception cref="MessageConversionException">If there was an error in message conversion</exception> protected Message BuildMessage(IModel channel, object result) { var converter = this.MessageConverter; if (converter != null) { return converter.ToMessage(result, new MessageProperties()); } if (!(result is Message)) { throw new MessageConversionException("No IMessageConverter specified - cannot handle message [" + result + "]"); } return (Message)result; } /// <summary>Post-process the given response message before it will be sent. The default implementation /// sets the response's correlation id to the request message's correlation id.</summary> /// <param name="request">The original incoming message.</param> /// <param name="response">The outgoing Rabbit message about to be sent.</param> protected virtual void PostProcessResponse(Message request, Message response) { var correlation = request.MessageProperties.CorrelationId.ToStringWithEncoding("UTF-8"); if (string.IsNullOrWhiteSpace(correlation)) { if (!string.IsNullOrWhiteSpace(request.MessageProperties.MessageId)) { correlation = request.MessageProperties.MessageId; } } response.MessageProperties.CorrelationId = correlation.ToByteArrayWithEncoding("UTF-8"); } /// <summary>Determine a response destination for the given message.</summary> /// <remarks><para>The default implementation first checks the Rabbit ReplyTo /// property of the supplied request; if that is not /// <code>null</code> /// it is returned; if it is /// <code>null</code> /// , then the configured<see cref="ResponseRoutingKey"/> default response routing key} /// is returned; if this too is /// <code>null</code> /// , then an<see cref="InvalidOperationException"/>is thrown.</para> /// </remarks> /// <param name="request">The original incoming message.</param> /// <returns>the response destination (never /// <code>null</code> /// )</returns> /// <exception cref="InvalidOperationException">if no destination can be determined.</exception> protected virtual Address GetReplyToAddress(Message request) { var replyTo = request.MessageProperties.ReplyToAddress; if (replyTo == null) { if (string.IsNullOrEmpty(this.responseExchange)) { throw new AmqpException("Cannot determine ReplyTo message property value: Request message does not contain reply-to property, and no default response Exchange was set."); } replyTo = new Address(null, this.responseExchange, this.responseRoutingKey); } return replyTo; } /// <summary>Sends the given response message to the given destination.</summary> /// <param name="channel">The channel to operate on.</param> /// <param name="replyTo">The replyto property to determine where to send a response.</param> /// <param name="message">The outgoing message about to be sent.</param> protected virtual void SendResponse(IModel channel, Address replyTo, Message message) { this.PostProcessChannel(channel, message); try { Logger.Debug(m => m("Publishing response to exchange = [{0}], routingKey = [{1}]", replyTo.ExchangeName, replyTo.RoutingKey)); channel.BasicPublish( replyTo.ExchangeName, replyTo.RoutingKey, this.mandatoryPublish, this.immediatePublish, this.messagePropertiesConverter.FromMessageProperties(channel, message.MessageProperties, this.encoding), message.Body); } catch (Exception ex) { throw RabbitUtils.ConvertRabbitAccessException(ex); } } /// <summary>Post-process the given message producer before using it to send the response. /// The default implementation is empty.</summary> /// <param name="channel">The channel that will be used to send the message.</param> /// <param name="response">The outgoing message about to be sent.</param> protected virtual void PostProcessChannel(IModel channel, Message response) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; /// <summary> /// StringBuilder.ctor(String,Int32) /// </summary> public class StringBuilderctor5 { public static int Main() { StringBuilderctor5 sbctor5 = new StringBuilderctor5(); TestLibrary.TestFramework.BeginTestCase("StringBuilderctor5"); if (sbctor5.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; return retVal; } #region PositiveTest public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1:Initialize StringBuilder with capacity and string 1"); try { string strValue = null; int capacity = this.GetInt32(1, 256); StringBuilder sb = new StringBuilder(strValue, capacity); if (sb == null) { TestLibrary.TestFramework.LogError("007.1", "StringBuilder was null"); retVal = false; } else if (!sb.ToString().Equals(String.Empty)) { TestLibrary.TestFramework.LogError("007.2", "Expected value of StringBuilder.ToString = String.Empty, actual: " + sb.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2:Initialize StringBuilder with capacity and string 2"); try { string strValue = string.Empty; int capacity = this.GetInt32(1, 256); StringBuilder sb = new StringBuilder(strValue, capacity); if (sb == null) { TestLibrary.TestFramework.LogError("003.1", "StringBuilder was null"); retVal = false; } else if (!sb.ToString().Equals(strValue)) { TestLibrary.TestFramework.LogError("003.2", "Expected value of StringBuilder.ToString = " + strValue + ", actual: " + sb.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3:Initialize StringBuilder with capacity and string 3"); try { string strValue = TestLibrary.Generator.GetString(-55, false, 8, 256); int capacity = this.GetInt32(1, strValue.Length); StringBuilder sb = new StringBuilder(strValue, capacity); if (sb == null) { TestLibrary.TestFramework.LogError("005.1", "StringBuilder was null"); retVal = false; } else if (!sb.ToString().Equals(strValue)) { TestLibrary.TestFramework.LogError("005.2", "Expected value of StringBuilder.ToString = " + strValue + ", actual: " + sb.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4:Initialize StringBuilder with capacity and string 4"); try { string strValue = string.Empty; int capacity = 0; StringBuilder sb = new StringBuilder(strValue, capacity); if (sb == null) { TestLibrary.TestFramework.LogError("007.1", "StringBuilder was null"); retVal = false; } else if (!sb.ToString().Equals(strValue)) { TestLibrary.TestFramework.LogError("007.2", "Expected value of StringBuilder.ToString = " + strValue + ", actual: " + sb.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5:Initialize StringBuilder with capacity and string 5"); try { string strValue = TestLibrary.Generator.GetString(-55, false, 8, 256); int capacity = 0; StringBuilder sb = new StringBuilder(strValue, capacity); if (sb == null) { TestLibrary.TestFramework.LogError("009.0", "StringBuilder was null"); retVal = false; } else if (!sb.ToString().Equals(strValue)) { TestLibrary.TestFramework.LogError("009.1", "Initializer string was "+strValue+", StringBuilder.ToString returned "+sb.ToString()); retVal = false; } else if (sb.Capacity == 0) { TestLibrary.TestFramework.LogError("009.2", "StringBuilder.Capacity returned 0 for non-empty string"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpect exception:" + e); retVal = false; } return retVal; } #endregion #region NegativeTest public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1:The capacity is less than zero"); try { string strValue = TestLibrary.Generator.GetString(-55, false, 8, 256); int capacity = this.GetInt32(1, Int32.MaxValue) * (-1); StringBuilder sb = new StringBuilder(strValue, capacity); TestLibrary.TestFramework.LogError("N001", "The capacity is less than zero but not throw exception"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N002", "Unexpect exception:" + e); retVal = false; } return retVal; } #endregion #region HelpMethod private Int32 GetInt32(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } #endregion }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.IO; using System; using System.Text; using System.Runtime.InteropServices; using System.Linq; public class DBClass : MonoBehaviour { //bool m_addItemInProgress = false; bool m_removeItemInProgress = false; ArrayList AddItemInProgressList = new ArrayList(); int AddItemInProgressInx = 0; void Start() { AddItemInProgressList.Clear(); AddItemInProgressInx = 0; AddItemInProgressList.Add(false); } void Update() { } public delegate void CreateClassDelegate(string error); public void CreateClass(string className, string organization, CreateClassDelegate callback) { EntityDBVitaClass profile = new EntityDBVitaClass(className, organization); VitaDynamoDB vitaDynamoDB = GameObject.Find("AWS").GetComponent<VitaDynamoDB>(); vitaDynamoDB.AddEntity<EntityDBVitaClass>(profile, (result, error) => { if (callback != null) callback(error); }); } public IEnumerator AddClasses(List<EntityDBVitaClass> classes) { // TODO: Add bulk Add() function // this function is used for backup/restore purposes. In normal operation, use Create() instead int waitCount = classes.Count; foreach (var c in classes) { VitaDynamoDB vitaDynamoDB = GameObject.Find("AWS").GetComponent<VitaDynamoDB>(); vitaDynamoDB.AddEntity<EntityDBVitaClass>(c, (result, error) => { waitCount--; if (!string.IsNullOrEmpty(error)) { if (!string.IsNullOrEmpty(error)) { Debug.LogErrorFormat("AddClasses() failed - {0}", c.classname); return; } } }); } while (waitCount > 0) yield return new WaitForEndOfFrame(); } public delegate void GetClassDelegate(EntityDBVitaClass c, string error); public void GetClass(string className, GetClassDelegate callback) { VitaDynamoDB vitaDynamoDB = GameObject.Find("AWS").GetComponent<VitaDynamoDB>(); vitaDynamoDB.GetEntity<EntityDBVitaClass>(className, "", null, (result, error) => { EntityDBVitaClass c = (EntityDBVitaClass)result; if (string.IsNullOrEmpty(error)) { c.FixNullLists(); } if (callback != null) callback(c, error); }); } public delegate void GetAllClassesDelegate(List<EntityDBVitaClass> classes, string error); public void GetAllClasses(GetAllClassesDelegate callback) { VitaDynamoDB vitaDynamoDB = GameObject.Find("AWS").GetComponent<VitaDynamoDB>(); vitaDynamoDB.GetAllEntities<EntityDBVitaClass>(EntityDBVitaClass.tableName, null, (result, error) => { List<EntityDBVitaClass> classes = new List<EntityDBVitaClass>(); if (string.IsNullOrEmpty(error)) { classes = (List<EntityDBVitaClass>)result; classes.Sort((a, b) => a.classname.CompareTo(b.classname)); classes.ForEach((a) => a.FixNullLists()); } if (callback != null) callback(classes, error); }); } public void GetAllClassesInOrganization(string organization, GetAllClassesDelegate callback) { GetAllClasses((list, error) => { List<EntityDBVitaClass> classes = new List<EntityDBVitaClass>(); if (string.IsNullOrEmpty(error)) { list.ForEach((a) => { if (a.organization == organization) classes.Add(a); }); } if (callback != null) callback(classes, error); }); } public delegate void DeleteClassDelegate(string error); public void DeleteClass(string className, DeleteClassDelegate callback) { GetClass(className, (c, error) => { if (!string.IsNullOrEmpty(error)) { if (callback != null) callback(error); return; } DeleteClass(className, c.teacher, callback); }); } public void DeleteClass(string className, string teacher, DeleteClassDelegate callback) { Debug.LogFormat("DeleteClass() - {0} - {1}", className, teacher); VitaDynamoDB vitaDynamoDB = GameObject.Find("AWS").GetComponent<VitaDynamoDB>(); vitaDynamoDB.DeleteEntity<EntityDBVitaClass>(className,"", (result, error2) => { if (callback != null) callback(error2); }); } public delegate void UpdateClassnameDelegate(string error); public void UpdateClassname(string oldName, string newName, UpdateClassnameDelegate callback) { #if false GetClass(oldName, (c, error) => { if (!string.IsNullOrEmpty(error)) { if (callback != null) callback(error); return; } //Debug.LogFormat("UpdateUserName() - {0} - {1} - {2} - {3}", profile.username, profile.password, profile.organization, profile.type); DeleteClass(oldName, error2 => { if (!string.IsNullOrEmpty(error2)) { if (callback != null) callback(error2); return; } c.classname = newName; VitaDynamoDB vitaDynamoDB = GameObject.Find("AWS").GetComponent<VitaDynamoDB>(); vitaDynamoDB.AddEntity<EntityDBVitaProfile>(c, (result, error3) => { if (callback != null) callback(error3); }); }); }); #else Debug.LogWarningFormat("TODO - UpdateClassname() - this function needs to be implemented. Currently does nothing"); if (callback != null) callback(""); #endif } delegate void AddItemFunction(string name, string item, AddStudentToClassDelegate callback); IEnumerator WaitTillAddItemDone(AddItemFunction func, string username, string item, AddStudentToClassDelegate callback) { //while (m_addItemInProgress) while (AddItemInProgressList.Count > AddItemInProgressInx && (bool)AddItemInProgressList[AddItemInProgressInx] ) { yield return new WaitForEndOfFrame(); } func(username, item, callback); } public delegate void AddStudentToClassDelegate(string error); public void AddStudentToClass(string className, string student, AddStudentToClassDelegate callback) { //if (m_addItemInProgress) if(AddItemInProgressList.Count > AddItemInProgressInx && (bool)AddItemInProgressList[AddItemInProgressInx]) { StartCoroutine(WaitTillAddItemDone(AddStudentToClass, className, student, callback)); AddItemInProgressList.Add(false); return; } AddItemInProgressList[AddItemInProgressInx] = true; //m_addItemInProgress = true; GetClass(className, (ob, getAllError) => { if (!string.IsNullOrEmpty(getAllError)) { //m_addItemInProgress = false; AddItemInProgressInx++; AddItemInProgressList[AddItemInProgressInx -1] = true; if(AddItemInProgressList.Count <= AddItemInProgressInx) AddItemInProgressList.Add(false); if (callback != null) callback(getAllError); return; } EntityDBVitaClass c = ob; if(c.students.Contains(student)) { //m_addItemInProgress = false; AddItemInProgressInx++; AddItemInProgressList[AddItemInProgressInx -1] = true; if(AddItemInProgressList.Count <= AddItemInProgressInx) AddItemInProgressList.Add(false); Debug.Log("Student already exists : " + student); } else { c.students.Add(student); VitaDynamoDB vitaDynamoDB = GameObject.Find("AWS").GetComponent<VitaDynamoDB>(); vitaDynamoDB.AddEntity<EntityDBVitaClass>(c, (result, error) => { //m_addItemInProgress = false; AddItemInProgressInx++; AddItemInProgressList[AddItemInProgressInx -1] = true; if(AddItemInProgressList.Count <= AddItemInProgressInx) AddItemInProgressList.Add(false); if (callback != null) callback(error); }); } }); } public delegate void UpdateClassDelegate(string error); public void UpdateClassTeacher(string className, string teacher, UpdateClassDelegate callback) { GetClass(className, (c, error) => { if (!string.IsNullOrEmpty(error)) { if (callback != null) callback(error); return; } EntityDBVitaClass newClass = c; newClass.teacher = teacher; VitaDynamoDB vitaDynamoDB = GameObject.Find("AWS").GetComponent<VitaDynamoDB>(); vitaDynamoDB.AddEntity<EntityDBVitaClass>(newClass, (result, error2) => { if (callback != null) callback(error2); }); }); } delegate void RemoveItemFunction(string username, string item, bool removeAll, ItemDelegate callback); IEnumerator WaitTillRemoveItemDone(RemoveItemFunction func, string username, string item, bool removeAll, ItemDelegate callback) { while (m_removeItemInProgress) { yield return new WaitForEndOfFrame(); } func(username, item, removeAll, callback); } public delegate void ItemDelegate(string error); public void RemoveStudentFromClass(string classname, string studentName, ItemDelegate callback) { RemoveStudentFromClass(classname, studentName, false, callback); } public void RemoveAllStudentsFromClass(string classname, ItemDelegate callback) { RemoveStudentFromClass(classname, " ", true, callback); } void RemoveStudentFromClass(string classname, string studentName, bool removeAll, ItemDelegate callback) { if (m_removeItemInProgress) { StartCoroutine(WaitTillRemoveItemDone(RemoveStudentFromClass, classname, studentName, removeAll, callback)); return; } m_removeItemInProgress = true; GetClass(classname, (cl, error) => { if (!string.IsNullOrEmpty(error)) { m_removeItemInProgress = false; if (callback != null) callback(error); return; } EntityDBVitaClass objcl = cl; if (removeAll) { objcl.students = null; } else { objcl.students.Remove(studentName); if(objcl.students.Count == 0) { objcl.students = null; } } VitaDynamoDB vitaDynamoDB = GameObject.Find("AWS").GetComponent<VitaDynamoDB>(); vitaDynamoDB.AddEntity<EntityDBVitaClass>(objcl, (result, error2) => { m_removeItemInProgress = false; if (callback != null) callback(error2); }); }); } public void RemoveStudentFromAllClasses(string studentName, string organization, ItemDelegate callback) { GetAllClassesInOrganization(organization, (list, error) => { if (!string.IsNullOrEmpty(error)) { if (callback != null) callback(error); return; } List<EntityDBVitaClass> classes = new List<EntityDBVitaClass>(); list.ForEach(c => { if (c.students.Contains(studentName)) { classes.Add(c); } }); int classCount = classes.Count; if(classCount == 0) { if (callback != null) callback(""); return; } foreach (var c in classes) { RemoveStudentFromClass(c.classname, studentName, error2 => { classCount--; if (!string.IsNullOrEmpty(error2)) { if (callback != null) callback(error2); return; } if (classCount == 0) { if (callback != null) callback(error2); return; } }); } }); } }
// 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 Xunit; using System.Linq; using System.Runtime.CompilerServices; using static System.TestHelpers; namespace System.SpanTests { public static partial class SpanTests { [Fact] public static void ClearEmpty() { var span = Span<byte>.Empty; span.Clear(); } [Fact] public static void ClearEmptyWithReference() { var span = Span<string>.Empty; span.Clear(); } [Fact] public static void ClearByteLonger() { const byte initial = 5; var actual = new byte[2048]; for (int i = 0; i < actual.Length; i++) { actual[i] = initial; } var expected = new byte[actual.Length]; var span = new Span<byte>(actual); span.Clear(); Assert.Equal<byte>(expected, actual); } [Fact] public static void ClearByteUnaligned() { const byte initial = 5; const int length = 32; var actualFull = new byte[length]; for (int i = 0; i < length; i++) { actualFull[i] = initial; } var expectedFull = new byte[length]; var start = 1; var expectedSpan = new Span<byte>(expectedFull, start, length - start - 1); var actualSpan = new Span<byte>(actualFull, start, length - start - 1); actualSpan.Clear(); byte[] actual = actualSpan.ToArray(); byte[] expected = expectedSpan.ToArray(); Assert.Equal<byte>(expected, actual); Assert.Equal(initial, actualFull[0]); Assert.Equal(initial, actualFull[length - 1]); } [Fact] public static unsafe void ClearByteUnalignedFixed() { const byte initial = 5; const int length = 32; var actualFull = new byte[length]; for (int i = 0; i < length; i++) { actualFull[i] = initial; } var expectedFull = new byte[length]; var start = 1; var expectedSpan = new Span<byte>(expectedFull, start, length - start - 1); fixed (byte* p = actualFull) { var actualSpan = new Span<byte>(p + start, length - start - 1); actualSpan.Clear(); byte[] actual = actualSpan.ToArray(); byte[] expected = expectedSpan.ToArray(); Assert.Equal<byte>(expected, actual); Assert.Equal(initial, actualFull[0]); Assert.Equal(initial, actualFull[length - 1]); } } [Fact] public static void ClearIntPtrOffset() { IntPtr initial = IntPtr.Zero + 5; const int length = 32; var actualFull = new IntPtr[length]; for (int i = 0; i < length; i++) { actualFull[i] = initial; } var expectedFull = new IntPtr[length]; var start = 2; var expectedSpan = new Span<IntPtr>(expectedFull, start, length - start - 1); var actualSpan = new Span<IntPtr>(actualFull, start, length - start - 1); actualSpan.Clear(); IntPtr[] actual = actualSpan.ToArray(); IntPtr[] expected = expectedSpan.ToArray(); Assert.Equal<IntPtr>(expected, actual); Assert.Equal(initial, actualFull[0]); Assert.Equal(initial, actualFull[length - 1]); } [Fact] public static void ClearIntPtrLonger() { IntPtr initial = IntPtr.Zero + 5; var actual = new IntPtr[2048]; for (int i = 0; i < actual.Length; i++) { actual[i] = initial; } var expected = new IntPtr[actual.Length]; var span = new Span<IntPtr>(actual); span.Clear(); Assert.Equal<IntPtr>(expected, actual); } [Fact] public static void ClearValueTypeWithoutReferences() { int[] actual = { 1, 2, 3 }; int[] expected = { 0, 0, 0 }; var span = new Span<int>(actual); span.Clear(); Assert.Equal<int>(expected, actual); } [Fact] public static void ClearValueTypeWithoutReferencesLonger() { int[] actual = new int[2048]; for (int i = 0; i < actual.Length; i++) { actual[i] = i + 1; } int[] expected = new int[actual.Length]; var span = new Span<int>(actual); span.Clear(); Assert.Equal<int>(expected, actual); } [Fact] public static void ClearValueTypeWithoutReferencesPointerSize() { long[] actual = new long[15]; for (int i = 0; i < actual.Length; i++) { actual[i] = i + 1; } long[] expected = new long[actual.Length]; var span = new Span<long>(actual); span.Clear(); Assert.Equal<long>(expected, actual); } [Fact] public static void ClearReferenceType() { string[] actual = { "a", "b", "c" }; string[] expected = { null, null, null }; var span = new Span<string>(actual); span.Clear(); Assert.Equal<string>(expected, actual); } [Fact] public static void ClearReferenceTypeLonger() { string[] actual = new string[2048]; for (int i = 0; i < actual.Length; i++) { actual[i] = (i + 1).ToString(); } string[] expected = new string[actual.Length]; var span = new Span<string>(actual); span.Clear(); Assert.Equal<string>(expected, actual); } [Fact] public static void ClearReferenceTypeSlice() { // A string array [ ""1", ..., "20" ] string[] baseline = Enumerable.Range(1, 20).Select(i => i.ToString()).ToArray(); for (int i = 0; i < 16; i++) { // Going to clear array.Slice(1, i) manually, // then compare it against array.Slice(1, i).Clear(). // Test is written this way to allow detecting overrunning bounds. string[] expected = (string[])baseline.Clone(); for (int j = 1; j <= i; j++) { expected[j] = null; } string[] actual = (string[])baseline.Clone(); actual.AsSpan(1, i).Clear(); Assert.Equal(expected, actual); } } [Fact] public static void ClearEnumType() { TestEnum[] actual = { TestEnum.E0, TestEnum.E1, TestEnum.E2 }; TestEnum[] expected = { default, default, default }; var span = new Span<TestEnum>(actual); span.Clear(); Assert.Equal<TestEnum>(expected, actual); } [Fact] public static void ClearValueTypeWithReferences() { TestValueTypeWithReference[] actual = { new TestValueTypeWithReference() { I = 1, S = "a" }, new TestValueTypeWithReference() { I = 2, S = "b" }, new TestValueTypeWithReference() { I = 3, S = "c" } }; TestValueTypeWithReference[] expected = { default, default, default }; var span = new Span<TestValueTypeWithReference>(actual); span.Clear(); Assert.Equal<TestValueTypeWithReference>(expected, actual); } // NOTE: ClearLongerThanUintMaxValueBytes test is constrained to run on Windows and MacOSX because it causes // problems on Linux due to the way deferred memory allocation works. On Linux, the allocation can // succeed even if there is not enough memory but then the test may get killed by the OOM killer at the // time the memory is accessed which triggers the full memory allocation. [Fact] [OuterLoop] [PlatformSpecific(TestPlatforms.Windows | TestPlatforms.OSX)] static unsafe void ClearLongerThanUintMaxValueBytes() { if (sizeof(IntPtr) == sizeof(long)) { // Arrange IntPtr bytes = (IntPtr)(((long)int.MaxValue) * sizeof(int)); int length = (int)(((long)bytes) / sizeof(int)); if (!AllocationHelper.TryAllocNative(bytes, out IntPtr memory)) { Console.WriteLine($"Span.Clear test {nameof(ClearLongerThanUintMaxValueBytes)} skipped (could not alloc memory)."); return; } try { Span<int> span = new Span<int>(memory.ToPointer(), length); span.Fill(5); // Act span.Clear(); // Assert using custom code for perf and to avoid allocating extra memory ref int data = ref Unsafe.AsRef<int>(memory.ToPointer()); for (int i = 0; i < length; i++) { var actual = Unsafe.Add(ref data, i); if (actual != 0) { Assert.Equal(0, actual); } } } finally { AllocationHelper.ReleaseNative(ref memory); } } } } }