context
stringlengths
2.52k
185k
gt
stringclasses
1 value
namespace Microsoft.Protocols.TestSuites.MS_OXCFXICS { using System; using System.Collections.Generic; /// <summary> /// The MessageChangePartial element represents the difference /// in message content since the last download, as identified by /// the initial ICS state. /// MessageChangePartial = [groupInfo] [PidTagIncrSyncGroupId] /// IncrSyncChgPartial messageChangeHeader /// *( PidTagIncrementalSyncMessagePartial propList ) /// MessageChildren /// </summary> public class MessageChangePartial : MessageChange { /// <summary> /// A groupInfo value. /// Provides a definition for the property group mapping. /// </summary> private GroupInfo groupInfo; /// <summary> /// A messageChangeHeader value. /// Contains a fixed set of information about the message change that follows this element in the FastTransfer stream. /// </summary> private MessageChangeHeader messageChangeHeader; /// <summary> /// A list of propList values. /// </summary> private List<PropList> propListList; /// <summary> /// A uint value after PidTagIncrSyncGroupId. /// Specifies an identifier of a property group mapping. /// </summary> private uint? incrSyncGroupId; /// <summary> /// A uint value after PidTagIncrementalSyncMessagePartial. /// Specifies an index of a property group within /// a property group mapping currently in context. /// </summary> private uint? incrementalSyncMessagePartial; /// <summary> /// Initializes a new instance of the MessageChangePartial class. /// </summary> /// <param name="stream">A FastTransferStream object.</param> public MessageChangePartial(FastTransferStream stream) : base(stream) { } /// <summary> /// Gets the last modification time in the messageChangeHeader. /// </summary> public override DateTime LastModificationTime { get { return this.MessageChangeHeader.LastModificationTime; } } /// <summary> /// Gets a value indicating whether has PidTagMid. /// </summary> public override bool HasPidTagMid { get { return this.MessageChangeHeader.HasPidTagMid; } } /// <summary> /// Gets a value indicating whether has PidTagMessageSize. /// </summary> public override bool HasPidTagMessageSize { get { return this.MessageChangeHeader.HasPidTagMessageSize; } } /// <summary> /// Gets a value indicating whether has PidTagChangeNumber. /// </summary> public override bool HasPidTagChangeNumber { get { return this.MessageChangeHeader.HasPidTagChangeNumber; } } /// <summary> /// Gets the sourceKey property. /// </summary> public override byte[] SourceKey { get { return this.MessageChangeHeader.SourceKey; } } /// <summary> /// Gets a value indicating the PidTagChangeKey. /// </summary> public override byte[] PidTagChangeKey { get { return this.messageChangeHeader.PidTagChangeKey; } } /// <summary> /// Gets a value indicating the PidTagChangeNumber. /// </summary> public override long PidTagChangeNumber { get { return this.messageChangeHeader.PidTagChangeNumber; } } /// <summary> /// Gets a value indicating the PidTagMid. /// </summary> public override long PidTagMid { get { return this.messageChangeHeader.PidTagMid; } } /// <summary> /// Gets or sets incrementalSyncMessagePartial. /// </summary> public uint? IncrementalSyncMessagePartial { get { return this.incrementalSyncMessagePartial; } set { this.incrementalSyncMessagePartial = value; } } /// <summary> /// Gets or sets incrSyncGroupId. /// </summary> public uint? IncrSyncGroupId { get { return this.incrSyncGroupId; } set { this.incrSyncGroupId = value; } } /// <summary> /// Gets or sets groupInfo. /// </summary> public GroupInfo GroupInfo { get { return this.groupInfo; } set { this.groupInfo = value; } } /// <summary> /// Gets or sets propList list. /// </summary> public List<PropList> PropListList { get { return this.propListList; } set { this.propListList = value; } } /// <summary> /// Gets or sets messageChangeHeader. /// </summary> public MessageChangeHeader MessageChangeHeader { get { return this.messageChangeHeader; } set { this.messageChangeHeader = value; } } /// <summary> /// Gets or sets MessageChildren. /// </summary> public MessageChildren MessageChildren { get; set; } /// <summary> /// Verify that a stream's current position contains a serialized MessageChangePartial. /// </summary> /// <param name="stream">A FastTransferStream.</param> /// <returns>If the stream's current position contains /// a serialized MessageChangePartial, return true, else false.</returns> public static new bool Verify(FastTransferStream stream) { return GroupInfo.Verify(stream) || stream.VerifyMetaProperty(MetaProperties.MetaTagIncrSyncGroupId) || stream.VerifyMarker(Markers.PidTagIncrSyncChgPartial); } /// <summary> /// Deserialize fields from a FastTransferStream. /// </summary> /// <param name="stream">A FastTransferStream.</param> public override void Deserialize(FastTransferStream stream) { if (GroupInfo.Verify(stream)) { this.groupInfo = new GroupInfo(stream); } if (stream.VerifyMetaProperty(MetaProperties.MetaTagIncrSyncGroupId)) { stream.ReadMarker(); this.incrSyncGroupId = stream.ReadUInt32(); } if (stream.ReadMarker(Markers.PidTagIncrSyncChgPartial)) { this.messageChangeHeader = new MessageChangeHeader(stream); this.propListList = new List<PropList>(); while (stream.VerifyMetaProperty(MetaProperties.MetaTagIncrementalSyncMessagePartial)) { stream.ReadMarker(); this.incrementalSyncMessagePartial = stream.ReadUInt32(); this.propListList.Add(new PropList(stream)); } this.MessageChildren = new MessageChildren(stream); return; } AdapterHelper.Site.Assert.Fail("The stream cannot be deserialized successfully."); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Research.DataStructures; using System.Diagnostics; using Microsoft.Research.CodeAnalysis; using Microsoft.Research.AbstractDomains; namespace Microsoft.Research.MoveNextGeneric { /// <summary> /// The analyzer that collects the state machine information of an iterator. It does so by using an forward analysis /// over the move next method of concern. The main interface of the analyzer is AnalyzeMoveNext, which returns information /// of the statemachine. /// </summary> public class MoveNextStateAnalyzer { public MoveNextStateAnalyzer() { } public const int DefaultCase = -999; static class TypeBindings<Local, Parameter, Method, Field, Property, Type, Attribute, Assembly, Expression, Variable, ILogOptions> where Variable : IEquatable<Variable> where Type : IEquatable<Type> where Expression: IEquatable<Expression> where ILogOptions: IFrameworkLogOptions { /// <summary> /// The main analysis, which most importantly is a visitor. When the visitor visits an assume statement, we try /// to determine whether this corresponds to a case statement in the global switch this.__state. /// /// </summary> public class Analysis : MSILVisitor<APC, Local, Parameter, Method, Field, Type, Variable, Variable, INumericalAbstractDomain<BoxedExpression>, INumericalAbstractDomain<BoxedExpression>>, IValueAnalysis<APC, INumericalAbstractDomain<BoxedExpression>, IVisitMSIL<APC, Local, Parameter, Method, Field, Type, Variable, Variable, INumericalAbstractDomain<BoxedExpression>, INumericalAbstractDomain<BoxedExpression>>, Variable, IExpressionContext<APC, Local, Parameter, Method, Field, Type, Expression, Variable>> { #region Private fields /// <summary> /// Context we got from the upcall to Visitor. This lets us find out things about Variables and Expressions /// </summary> internal IExpressionContext<APC, Local, Parameter, Method, Field, Type, Expression, Variable> context; /// <summary> /// An analysis likely needs access to a meta data decoder to make sense of types etc. /// </summary> internal IMethodDriver<APC, Local, Parameter, Method, Field, Property, Type, Attribute, Assembly, Expression, Variable, ILogOptions> mdriver; internal MoveNextStateAnalyzer parent; private Dictionary<int, Set<APC>> stateInfo = new Dictionary<int,Set<APC>>(); private Set<string> returnValues = Set<string>.Empty; private BoxedExpressionDecoder<Type, Expression> decoderForExpressions; private Microsoft.Research.AbstractDomains.Expressions.IExpressionEncoder<BoxedExpression> encoderForExpressions; #endregion Private fields public Analysis(IMethodDriver<APC, Local, Parameter, Method, Field, Property, Type, Attribute, Assembly, Expression, Variable, ILogOptions> mdriver, MoveNextStateAnalyzer parent) { this.parent = parent; this.mdriver = mdriver; this.decoderForExpressions = BoxedExpressionDecoder.Decoder(new AnalysisWrapper.TypeBindings<Local, Parameter, Method, Field, Property, Type, Attribute, Assembly, Expression, Variable>.ValueExpDecoder(this.mdriver.Context, this.mdriver.MetaDataDecoder)); this.encoderForExpressions = BoxedExpressionEncoder.Encoder(this.mdriver.MetaDataDecoder, this.mdriver.Context); } public StateMachineInformation<Local> MoveNextPreAnalysisResult { get { return new StateMachineInformation<Local>(this.stateInfo, this.returnValues); } } public INumericalAbstractDomain<BoxedExpression> InitialValue() { INumericalAbstractDomain<BoxedExpression> result = new AbstractDomains.Numerical.IntervalEnvironment<BoxedExpression>(decoderForExpressions, encoderForExpressions); return result; } #region IValueAnalysis<APC,INumericalAbstractDomain<Expression>,IVisitMSIL<APC,Local,Parameter,Method,Field,Type,Expression,Variable,INumericalAbstractDomain<Expression>,INumericalAbstractDomain<Expression>>,Variable,Expression,IExpressionContext<APC,Method,Type,Expression,Variable>> Members /// <summary> /// Here, we return the transfer function. Since we implement this via MSILVisitor, we just return this. /// </summary> /// <param name="context">The expression context is an interface we can use to find out more about expressions, such as their type etc.</param> /// <returns>The transfer function.</returns> public IVisitMSIL<APC, Local, Parameter, Method, Field, Type, Variable, Variable, INumericalAbstractDomain<BoxedExpression>, INumericalAbstractDomain<BoxedExpression>> Visitor(IExpressionContext<APC, Local, Parameter, Method, Field, Type, Expression, Variable> context) { // store away the context for future reference this.context = context; return this; } /// <summary> /// Must implement the join/widen operation /// </summary> /// <param name="edge"></param> /// <param name="newState"></param> /// <param name="prevState"></param> /// <param name="weaker">should return false if result is less than or equal prevState.</param> /// <param name="widen">true if this is a widen operation. For our INumericalAbstractDomain<Expression>, this makes no difference</param> public INumericalAbstractDomain<BoxedExpression> Join(Pair<APC, APC> edge, INumericalAbstractDomain<BoxedExpression> newState, INumericalAbstractDomain<BoxedExpression> prevState, out bool weaker, bool widen) { INumericalAbstractDomain<BoxedExpression> result = (INumericalAbstractDomain<BoxedExpression>)prevState.Join(newState); weaker = !prevState.LessEqual(newState); return result; } public bool IsBottom(APC pc, INumericalAbstractDomain<BoxedExpression> state) { return state.IsBottom; } public INumericalAbstractDomain<BoxedExpression> ImmutableVersion(INumericalAbstractDomain<BoxedExpression> state) { return state; } public INumericalAbstractDomain<BoxedExpression> MutableVersion(INumericalAbstractDomain<BoxedExpression> state) { return (INumericalAbstractDomain<BoxedExpression>)state.Clone(); } public void Dump(Pair<INumericalAbstractDomain<BoxedExpression>, System.IO.TextWriter> stateAndWriter) { var tw = stateAndWriter.Two; tw.Write("numerical INumericalAbstractDomain<Expression>: {0} ", stateAndWriter.One); } /// <summary> /// This method is called by the underlying driver of the fixpoint computation. It provides delegates for future lookup /// of the abstract state at given pcs. /// </summary> /// <returns>Return true only if you want the fixpoint computation to eagerly cache each pc state.</returns> public Predicate<APC> CacheStates(IFixpointInfo<APC, INumericalAbstractDomain<BoxedExpression>> fixpointInfo) { return PCsAtBranches; } private bool PCsAtBranches(APC pc) { return false; } public INumericalAbstractDomain<BoxedExpression> ParallelAssign(Pair<APC, APC> edge, IFunctionalMap<Variable, FList<Variable>> sourceTargetMap, INumericalAbstractDomain<BoxedExpression> state) { var refinedMap = RefineMapToExpressions(edge.One, sourceTargetMap); state.AssignInParallel(refinedMap); return state; } private Dictionary<BoxedExpression, FList<BoxedExpression>> RefineMapToExpressions(APC pc, IFunctionalMap<Variable, FList<Variable>> sourceTargetMap) { var result = new Dictionary<BoxedExpression, FList<BoxedExpression>>(sourceTargetMap.Count); foreach (Variable v in sourceTargetMap.Keys) { BoxedExpression vRefined = ToBoxedExpression(pc, v); result[vRefined] = FList<Variable>.Map<BoxedExpression>(delegate(Variable target) { return BoxedExpression.For(this.mdriver.Context.For(target), this.decoderForExpressions.Outdecoder); }, sourceTargetMap[v]); } return result; } protected BoxedExpression ToBoxedExpression(APC pc, Variable var) { return BoxedExpression.For(this.mdriver.Context.Refine(pc, var), this.decoderForExpressions.Outdecoder); } protected override INumericalAbstractDomain<BoxedExpression> Default(APC pc, INumericalAbstractDomain<BoxedExpression> data) { return data; } bool IsEnumeratorStatePredicate(APC pc, Variable condition, out int stateValue, out bool OpIsEq) { stateValue = -100; OpIsEq = false; IFullExpressionDecoder<Type, Expression> decoder = this.mdriver.ExpressionDecoder; Expression exp = this.context.Refine(pc, condition); BinaryOperator op; Expression left, right; if (decoder.IsBinaryOperator(exp, out op, out left, out right)) { if (op == BinaryOperator.Ceq || op == BinaryOperator.Cne_Un || op == BinaryOperator.Cobjeq) { if (op == BinaryOperator.Cne_Un) OpIsEq = false; else OpIsEq = true; object o; if (decoder.IsVariable(left, out o)) { string path = this.context.AccessPath(pc, (Variable)o); if (path != null) { if (path.Contains(".<>") && path.EndsWith("state")) { object value; Type type; if (decoder.IsConstant(right, out value, out type)) { if (type.Equals(this.mdriver.MetaDataDecoder.System_UInt32) || type.Equals(this.mdriver.MetaDataDecoder.System_Int32)) { stateValue = (int)value; return true; } } } } } } } return false; } public override INumericalAbstractDomain<BoxedExpression> Assume(APC pc, string tag, Variable condition, INumericalAbstractDomain<BoxedExpression> data) { BoxedExpression boxedCondition = BoxedExpression.For(this.context.Refine(pc, condition), this.decoderForExpressions.Outdecoder); if (tag == "false") { data.TestFalse(boxedCondition); } else if (tag == "true") { data.TestTrue(boxedCondition); } Variable varForThisDotState = ThisDotState(pc); BoxedExpression boxedThisDotState = BoxedExpression.For(this.context.Refine(pc, varForThisDotState), this.decoderForExpressions.Outdecoder); AbstractDomains.Numerical.Interval interval = data.BoundsFor(boxedThisDotState); AbstractDomains.Numerical.Rational rat; if (interval.TryGetSingletonValue(out rat)) { long lv; if (rat.TryInt64(out lv)) { int state = (int)lv; if (this.stateInfo.ContainsKey(state)) { this.stateInfo[state].Add(pc); } else { this.stateInfo[state] = new Set<APC>(pc); } } } return base.Assume(pc, tag, condition, data); } private Variable ThisDotState(APC pc) { Parameter pThis = this.mdriver.MetaDataDecoder.This(this.mdriver.CurrentMethod); Variable thisValue; if (this.context.TryParameterValue(pc, pThis, out thisValue)) { Variable addrThisDotState; if (this.context.TryFieldAddress(pc, thisValue, this.StateField, out addrThisDotState)) { Variable result; if (this.context.TryLoadIndirect(pc, addrThisDotState, out result)) { return result; } } } return default(Variable); } private Field stateField = default(Field); private Field StateField { get { if (stateField == null) { Type closureType = this.mdriver.MetaDataDecoder.DeclaringType(this.mdriver.CurrentMethod); foreach (Field f in this.mdriver.MetaDataDecoder.Fields(closureType)) { string fname = this.mdriver.MetaDataDecoder.Name(f); if (fname.Contains("<>") && fname.EndsWith("state")) { stateField = f; break; } } } return stateField; } } #endregion } } /// <summary> /// Main interface method of the analyzer. It returns state machine information, given a method driver. /// </summary> /// <param name="fullMethodName">The name of the method, should always be "MoveNext".</param> /// <param name="driver">A method analysis driver.</param> /// <returns></returns> public StateMachineInformation<Local> AnalyzeMoveNext<Local, Parameter, Method, Field, Property, Type, Attribute, Assembly, Expression, Variable, ILogOptions>( string fullMethodName, IMethodDriver<APC, Local, Parameter, Method, Field, Property, Type, Attribute, Assembly, Expression, Variable, ILogOptions> driver ) where Variable : IEquatable<Variable> where Expression : IEquatable<Expression> where Type : IEquatable<Type> where ILogOptions : IFrameworkLogOptions { TypeBindings<Local, Parameter, Method, Field, Property, Type, Attribute, Assembly, Expression, Variable, ILogOptions>.Analysis analysis = new TypeBindings<Local, Parameter, Method, Field, Property, Type, Attribute, Assembly, Expression, Variable, ILogOptions>.Analysis(driver, this); driver.CreateForward(analysis)(analysis.InitialValue()); return analysis.MoveNextPreAnalysisResult; } } /// <summary> /// Encapsulates information regarding the iterator state machine: what the states are, what their entry point(s) /// are and the access path of the return value, which is typically a local variable. /// /// An entry point for state i is the program point of the case statement of the global switch in a movenext method: /// switch (this.__state)... L: case 1: ...., where L is the entry point for state 1. /// </summary> /// <typeparam name="Local"></typeparam> public class StateMachineInformation<Local> { Dictionary<int, Set<APC>> stateInfo; public Dictionary<int, Set<APC>> StateInfo { get { return stateInfo; } } IEnumerable<string> returnValues; public StateMachineInformation(Dictionary<int, Set<APC>> stateInfo, IEnumerable<string> returnValues) { this.stateInfo = stateInfo; this.returnValues = returnValues; } /// <summary> /// Orderred "visible" state. A state is visible if this.__state can take this value when the movenext /// method is not running. This excludes internal states such as -1. Order the integer values of /// the states since the smallest (0) is the initial state. /// /// Not every state that has an entry is a visible state, namely, DefaultCase is not. It has a case /// statement entry, which should never be visited. /// </summary> public IEnumerable<int> OrderedVisibleStates { get { foreach (int state in stateInfo.Keys.OrderBy(delegate(int key) { return key; })) { if (state == MoveNextStateAnalyzer.DefaultCase) continue; yield return state; } } } public Set<APC> EntryPointForState(int state) { if (this.stateInfo.ContainsKey(state)) return this.stateInfo[state]; return Set<APC>.Empty; } } }
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 MyWebAPIServer.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; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Xml.Schema; using System.Collections; using System.Diagnostics; using System.Globalization; namespace System.Xml { // Represents an element. public class XmlElement : XmlLinkedNode { XmlName name; XmlAttributeCollection attributes; XmlLinkedNode lastChild; // == this for empty elements otherwise it is the last child internal XmlElement(XmlName name, bool empty, XmlDocument doc) : base(doc) { Debug.Assert(name != null); this.parentNode = null; if (!doc.IsLoading) { XmlDocument.CheckName(name.Prefix); XmlDocument.CheckName(name.LocalName); } if (name.LocalName.Length == 0) throw new ArgumentException(SR.Xdom_Empty_LocalName); this.name = name; if (empty) { this.lastChild = this; } } protected internal XmlElement(string prefix, string localName, string namespaceURI, XmlDocument doc) : this(doc.AddXmlName(prefix, localName, namespaceURI), true, doc) { } internal XmlName XmlName { get { return name; } set { name = value; } } // Creates a duplicate of this node. public override XmlNode CloneNode(bool deep) { Debug.Assert(OwnerDocument != null); XmlDocument doc = OwnerDocument; bool OrigLoadingStatus = doc.IsLoading; doc.IsLoading = true; XmlElement element = doc.CreateElement(Prefix, LocalName, NamespaceURI); doc.IsLoading = OrigLoadingStatus; if (element.IsEmpty != this.IsEmpty) element.IsEmpty = this.IsEmpty; if (HasAttributes) { foreach (XmlAttribute attr in Attributes) { XmlAttribute newAttr = (XmlAttribute)(attr.CloneNode(true)); if (attr is XmlUnspecifiedAttribute && attr.Specified == false) ((XmlUnspecifiedAttribute)newAttr).SetSpecified(false); element.Attributes.InternalAppendAttribute(newAttr); } } if (deep) element.CopyChildren(doc, this, deep); return element; } // Gets the name of the node. public override string Name { get { return name.Name; } } // Gets the name of the current node without the namespace prefix. public override string LocalName { get { return name.LocalName; } } // Gets the namespace URI of this node. public override string NamespaceURI { get { return name.NamespaceURI; } } // Gets or sets the namespace prefix of this node. public override string Prefix { get { return name.Prefix; } set { name = name.OwnerDocument.AddXmlName(value, LocalName, NamespaceURI); } } // Gets the type of the current node. public override XmlNodeType NodeType { get { return XmlNodeType.Element; } } public override XmlNode ParentNode { get { return this.parentNode; } } // Gets the XmlDocument that contains this node. public override XmlDocument OwnerDocument { get { return name.OwnerDocument; } } internal override bool IsContainer { get { return true; } } //the function is provided only at Load time to speed up Load process internal override XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc) { XmlNodeChangedEventArgs args = doc.GetInsertEventArgsForLoad(newChild, this); if (args != null) doc.BeforeEvent(args); XmlLinkedNode newNode = (XmlLinkedNode)newChild; if (lastChild == null || lastChild == this) { // if LastNode == null newNode.next = newNode; lastChild = newNode; // LastNode = newNode; newNode.SetParentForLoad(this); } else { XmlLinkedNode refNode = lastChild; // refNode = LastNode; newNode.next = refNode.next; refNode.next = newNode; lastChild = newNode; // LastNode = newNode; if (refNode.IsText && newNode.IsText) { NestTextNodes(refNode, newNode); } else { newNode.SetParentForLoad(this); } } if (args != null) doc.AfterEvent(args); return newNode; } // Gets or sets whether the element does not have any children. public bool IsEmpty { get { return lastChild == this; } set { if (value) { if (lastChild != this) { RemoveAllChildren(); lastChild = this; } } else { if (lastChild == this) { lastChild = null; } } } } internal override XmlLinkedNode LastNode { get { return lastChild == this ? null : lastChild; } set { lastChild = value; } } internal override bool IsValidChildType(XmlNodeType type) { switch (type) { case XmlNodeType.Element: case XmlNodeType.Text: case XmlNodeType.EntityReference: case XmlNodeType.Comment: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.ProcessingInstruction: case XmlNodeType.CDATA: return true; default: return false; } } // Gets a XmlAttributeCollection containing the list of attributes for this node. public override XmlAttributeCollection Attributes { get { if (attributes == null) { lock (OwnerDocument.objLock) { if (attributes == null) { attributes = new XmlAttributeCollection(this); } } } return attributes; } } // Gets a value indicating whether the current node // has any attributes. public virtual bool HasAttributes { get { if (this.attributes == null) return false; else return this.attributes.Count > 0; } } // Returns the value for the attribute with the specified name. public virtual string GetAttribute(string name) { XmlAttribute attr = GetAttributeNode(name); if (attr != null) return attr.Value; return String.Empty; } // Sets the value of the attribute // with the specified name. public virtual void SetAttribute(string name, string value) { XmlAttribute attr = GetAttributeNode(name); if (attr == null) { attr = OwnerDocument.CreateAttribute(name); attr.Value = value; Attributes.InternalAppendAttribute(attr); } else { attr.Value = value; } } // Removes an attribute by name. public virtual void RemoveAttribute(string name) { if (HasAttributes) Attributes.RemoveNamedItem(name); } // Returns the XmlAttribute with the specified name. public virtual XmlAttribute GetAttributeNode(string name) { if (HasAttributes) return Attributes[name]; return null; } // Adds the specified XmlAttribute. public virtual XmlAttribute SetAttributeNode(XmlAttribute newAttr) { if (newAttr.OwnerElement != null) throw new InvalidOperationException(SR.Xdom_Attr_InUse); return (XmlAttribute)Attributes.SetNamedItem(newAttr); } // Removes the specified XmlAttribute. public virtual XmlAttribute RemoveAttributeNode(XmlAttribute oldAttr) { if (HasAttributes) return (XmlAttribute)Attributes.Remove(oldAttr); return null; } // Returns a XmlNodeList containing // a list of all descendant elements that match the specified name. public virtual XmlNodeList GetElementsByTagName(string name) { return new XmlElementList(this, name); } // // DOM Level 2 // // Returns the value for the attribute with the specified LocalName and NamespaceURI. public virtual string GetAttribute(string localName, string namespaceURI) { XmlAttribute attr = GetAttributeNode(localName, namespaceURI); if (attr != null) return attr.Value; return String.Empty; } // Sets the value of the attribute with the specified name // and namespace. public virtual string SetAttribute(string localName, string namespaceURI, string value) { XmlAttribute attr = GetAttributeNode(localName, namespaceURI); if (attr == null) { attr = OwnerDocument.CreateAttribute(string.Empty, localName, namespaceURI); attr.Value = value; Attributes.InternalAppendAttribute(attr); } else { attr.Value = value; } return value; } // Removes an attribute specified by LocalName and NamespaceURI. public virtual void RemoveAttribute(string localName, string namespaceURI) { RemoveAttributeNode(localName, namespaceURI); } // Returns the XmlAttribute with the specified LocalName and NamespaceURI. public virtual XmlAttribute GetAttributeNode(string localName, string namespaceURI) { if (HasAttributes) return Attributes[localName, namespaceURI]; return null; } // Adds the specified XmlAttribute. public virtual XmlAttribute SetAttributeNode(string localName, string namespaceURI) { XmlAttribute attr = GetAttributeNode(localName, namespaceURI); if (attr == null) { attr = OwnerDocument.CreateAttribute(string.Empty, localName, namespaceURI); Attributes.InternalAppendAttribute(attr); } return attr; } // Removes the XmlAttribute specified by LocalName and NamespaceURI. public virtual XmlAttribute RemoveAttributeNode(string localName, string namespaceURI) { if (HasAttributes) { XmlAttribute attr = GetAttributeNode(localName, namespaceURI); Attributes.Remove(attr); return attr; } return null; } // Returns a XmlNodeList containing // a list of all descendant elements that match the specified name. public virtual XmlNodeList GetElementsByTagName(string localName, string namespaceURI) { return new XmlElementList(this, localName, namespaceURI); } // Determines whether the current node has the specified attribute. public virtual bool HasAttribute(string name) { return GetAttributeNode(name) != null; } // Determines whether the current node has the specified // attribute from the specified namespace. public virtual bool HasAttribute(string localName, string namespaceURI) { return GetAttributeNode(localName, namespaceURI) != null; } // Saves the current node to the specified XmlWriter. public override void WriteTo(XmlWriter w) { if (GetType() == typeof(XmlElement)) { // Use the non-recursive version (for XmlElement only) WriteElementTo(w, this); } else { // Use the (potentially) recursive version WriteStartElement(w); if (IsEmpty) { w.WriteEndElement(); } else { WriteContentTo(w); w.WriteFullEndElement(); } } } // This method is copied from System.Xml.Linq.ElementWriter.WriteElement but adapted to DOM private static void WriteElementTo(XmlWriter writer, XmlElement e) { XmlNode root = e; XmlNode n = e; while (true) { e = n as XmlElement; // Only use the inlined write logic for XmlElement, not for derived classes if (e != null && e.GetType() == typeof(XmlElement)) { // Write the element e.WriteStartElement(writer); // Write the element's content if (e.IsEmpty) { // No content; use a short end element <a /> writer.WriteEndElement(); } else if (e.lastChild == null) { // No actual content; use a full end element <a></a> writer.WriteFullEndElement(); } else { // There are child node(s); move to first child n = e.FirstChild; Debug.Assert(n != null); continue; } } else { // Use virtual dispatch (might recurse) n.WriteTo(writer); } // Go back to the parent after writing the last child while (n != root && n == n.ParentNode.LastChild) { n = n.ParentNode; Debug.Assert(n != null); writer.WriteFullEndElement(); } if (n == root) break; n = n.NextSibling; Debug.Assert(n != null); } } // Writes the start of the element (and its attributes) to the specified writer private void WriteStartElement(XmlWriter w) { w.WriteStartElement(Prefix, LocalName, NamespaceURI); if (HasAttributes) { XmlAttributeCollection attrs = Attributes; for (int i = 0; i < attrs.Count; i += 1) { XmlAttribute attr = attrs[i]; attr.WriteTo(w); } } } // Saves all the children of the node to the specified XmlWriter. public override void WriteContentTo(XmlWriter w) { for (XmlNode node = FirstChild; node != null; node = node.NextSibling) { node.WriteTo(w); } } // Removes the attribute node with the specified index from the attribute collection. public virtual XmlNode RemoveAttributeAt(int i) { if (HasAttributes) return attributes.RemoveAt(i); return null; } // Removes all attributes from the element. public virtual void RemoveAllAttributes() { if (HasAttributes) { attributes.RemoveAll(); } } // Removes all the children and/or attributes // of the current node. public override void RemoveAll() { //remove all the children base.RemoveAll(); //remove all the attributes RemoveAllAttributes(); } internal void RemoveAllChildren() { base.RemoveAll(); } // Gets or sets the markup representing just // the children of this node. public override string InnerXml { get { return base.InnerXml; } set { RemoveAllChildren(); XmlLoader loader = new XmlLoader(); loader.LoadInnerXmlElement(this, value); } } // Gets or sets the concatenated values of the // node and all its children. public override string InnerText { get { return base.InnerText; } set { XmlLinkedNode linkedNode = LastNode; if (linkedNode != null && //there is one child linkedNode.NodeType == XmlNodeType.Text && //which is text node linkedNode.next == linkedNode) // and it is the only child { //this branch is for perf reason, event fired when TextNode.Value is changed. linkedNode.Value = value; } else { RemoveAllChildren(); AppendChild(OwnerDocument.CreateTextNode(value)); } } } public override XmlNode NextSibling { get { if (this.parentNode != null && this.parentNode.LastNode != this) return next; return null; } } internal override void SetParent(XmlNode node) { this.parentNode = node; } internal override string GetXPAttribute(string localName, string ns) { if (ns == OwnerDocument.strReservedXmlns) return null; XmlAttribute attr = GetAttributeNode(localName, ns); if (attr != null) return attr.Value; return string.Empty; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Runtime.Serialization; using Chauffeur.Jenkins.Client; namespace Chauffeur.Jenkins.Model { [DataContract(Name = "build", Namespace = "")] public class Build : IUrl { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Build" /> class. /// </summary> public Build() { this.Culprits = new List<User>(); this.Actions = new List<Action>(); } #endregion #region Public Properties /// <summary> /// Gets or sets the actions. /// </summary> /// <value> /// The actions. /// </value> [DataMember(Name = "actions")] public IList<Action> Actions { get; set; } /// <summary> /// Gets or sets the artifacts. /// </summary> /// <value> /// The artifacts. /// </value> [DataMember(Name = "artifacts")] public IList<Artifact> Artifacts { get; set; } /// <summary> /// Gets or sets a value indicating whether this <see cref="Build" /> is building. /// </summary> /// <value> /// <c>true</c> if building; otherwise, <c>false</c>. /// </value> [DataMember(Name = "building")] public bool Building { get; set; } /// <summary> /// Gets or sets the built on. /// </summary> /// <value> /// The built on. /// </value> [DataMember(Name = "builtOn")] public string BuiltOn { get; set; } /// <summary> /// Gets or sets the change set. /// </summary> /// <value> /// The change set. /// </value> [DataMember(Name = "changeSet")] public ChangeSet ChangeSet { get; set; } /// <summary> /// Gets or sets the culprits. /// </summary> /// <value> /// The culprits. /// </value> [DataMember(Name = "culprits")] public IList<User> Culprits { get; set; } /// <summary> /// Gets or sets the description. /// </summary> /// <value> /// The description. /// </value> [DataMember(Name = "description")] public string Description { get; set; } /// <summary> /// Gets or sets the display name. /// </summary> /// <value> /// The display name. /// </value> [DataMember(Name = "displayName")] public string DisplayName { get; set; } /// <summary> /// Gets or sets the duration. /// </summary> /// <value> /// The duration. /// </value> [DataMember(Name = "duration")] public int Duration { get; set; } /// <summary> /// Gets or sets the full name of the display. /// </summary> /// <value> /// The full name of the display. /// </value> [DataMember(Name = "fullDisplayName")] public string FullDisplayName { get; set; } /// <summary> /// Gets or sets the identifier. /// </summary> /// <value> /// The identifier. /// </value> [DataMember(Name = "id")] public string Id { get; set; } /// <summary> /// Gets or sets a value indicating whether [keep log]. /// </summary> /// <value> /// <c>true</c> if [keep log]; otherwise, <c>false</c>. /// </value> [DataMember(Name = "keepLog")] public bool KeepLog { get; set; } /// <summary> /// Gets or sets the number. /// </summary> /// <value> /// The number. /// </value> [DataMember(Name = "number")] public int Number { get; set; } /// <summary> /// Gets or sets the result. /// </summary> /// <value> /// The result. /// </value> [DataMember(Name = "result")] public string Result { get; set; } #endregion #region IUrl Members /// <summary> /// Gets or sets the URL. /// </summary> /// <value> /// The URL. /// </value> [DataMember(Name = "url")] public Uri Url { get; set; } #endregion #region Public Methods /// <summary> /// Returns a <see cref="System.String" /> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String" /> that represents this instance. /// </returns> public override string ToString() { return this.FullDisplayName ?? this.Number.ToString(CultureInfo.InvariantCulture); } #endregion } [DataContract(Name = "cause", Namespace = "")] public class Cause { #region Public Properties /// <summary> /// Gets or sets the short description. /// </summary> /// <value> /// The short description. /// </value> [DataMember(Name = "shortDescription")] public string ShortDescription { get; set; } /// <summary> /// Gets or sets the upstream build. /// </summary> /// <value> /// The upstream build. /// </value> [DataMember(Name = "upstreamBuild")] public string UpstreamBuild { get; set; } /// <summary> /// Gets or sets the upstream project. /// </summary> /// <value> /// The upstream project. /// </value> [DataMember(Name = "upstreamProject")] public string UpstreamProject { get; set; } /// <summary> /// Gets or sets the upstream URL. /// </summary> /// <value> /// The upstream URL. /// </value> [DataMember(Name = "upstreamUrl")] public Uri UpstreamUrl { get; set; } /// <summary> /// Gets or sets the user identifier. /// </summary> /// <value> /// The user identifier. /// </value> [DataMember(Name = "userId")] public string UserId { get; set; } /// <summary> /// Gets or sets the name of the user. /// </summary> /// <value> /// The name of the user. /// </value> [DataMember(Name = "userName")] public string UserName { get; set; } #endregion } [DataContract(Name = "action", Namespace = "")] public class Action { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Action" /> class. /// </summary> public Action() { this.Causes = new List<Cause>(); } #endregion #region Public Properties /// <summary> /// Gets or sets the causes. /// </summary> /// <value> /// The causes. /// </value> [DataMember(Name = "causes")] public IList<Cause> Causes { get; set; } #endregion } [DataContract(Name = "artifact", Namespace = "")] public class Artifact { #region Public Properties /// <summary> /// Gets or sets the display path. /// </summary> /// <value> /// The display path. /// </value> [DataMember(Name = "displayPath")] public string DisplayPath { get; set; } /// <summary> /// Gets or sets the name of the file. /// </summary> /// <value> /// The name of the file. /// </value> [DataMember(Name = "fileName")] public string FileName { get; set; } /// <summary> /// Gets or sets the relative path. /// </summary> /// <value> /// The relative path. /// </value> [DataMember(Name = "relativePath")] public string RelativePath { get; set; } #endregion } [DataContract(Name = "changeSet", Namespace = "")] public class ChangeSet { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ChangeSet" /> class. /// </summary> public ChangeSet() { this.Items = new List<ChangeSetItem>(); } #endregion #region Public Properties /// <summary> /// Gets or sets the items. /// </summary> /// <value> /// The items. /// </value> [DataMember(Name = "items")] public IList<ChangeSetItem> Items { get; set; } #endregion } [DataContract(Name = "changeSetItem", Namespace = "")] public class ChangeSetItem { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ChangeSetItem" /> class. /// </summary> public ChangeSetItem() { this.Paths = new List<ChangeSetPath>(); } #endregion #region Public Properties /// <summary> /// Gets or sets the affected paths. /// </summary> /// <value> /// The affected paths. /// </value> [DataMember(Name = "affectedPaths")] public IList<string> AffectedPaths { get; set; } /// <summary> /// Gets or sets the author. /// </summary> /// <value> /// The author. /// </value> [DataMember(Name = "author")] public User Author { get; set; } /// <summary> /// Gets or sets the comment. /// </summary> /// <value> /// The comment. /// </value> [DataMember(Name = "comment")] public string Comment { get; set; } /// <summary> /// Gets or sets the date. /// </summary> /// <value> /// The date. /// </value> [DataMember(Name = "date")] public string Date { get; set; } /// <summary> /// Gets or sets the identifier. /// </summary> /// <value> /// The identifier. /// </value> [DataMember(Name = "id")] public string Id { get; set; } /// <summary> /// Gets or sets the message. /// </summary> /// <value> /// The message. /// </value> [DataMember(Name = "msg")] public string Message { get; set; } /// <summary> /// Gets or sets the paths. /// </summary> /// <value> /// The paths. /// </value> [DataMember(Name = "items")] public IList<ChangeSetPath> Paths { get; set; } /// <summary> /// Gets or sets the user. /// </summary> /// <value> /// The user. /// </value> [DataMember(Name = "user")] public string User { get; set; } /// <summary> /// Gets or sets the version. /// </summary> /// <value> /// The version. /// </value> [DataMember(Name = "version")] public string Version { get; set; } #endregion } [DataContract(Name = "changeSetPath", Namespace = "")] public class ChangeSetPath { #region Public Properties /// <summary> /// Gets or sets the type of the edit. /// </summary> /// <value> /// The type of the edit. /// </value> [DataMember(Name = "editType")] public string EditType { get; set; } /// <summary> /// Gets or sets the file. /// </summary> /// <value> /// The file. /// </value> [DataMember(Name = "path")] public string Path { get; set; } #endregion } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Management.Tools.Vhd.Model { using System; using System.Collections.Generic; using System.Linq; public class IndexRange : IEquatable<IndexRange> { static IndexRangeComparer comparer = new IndexRangeComparer(); public static IEnumerable<IndexRange> SubstractRanges(IEnumerable<IndexRange> source, IEnumerable<IndexRange> ranges) { var onlyInSource = source.Where(e => !ranges.Any(r => r.Intersects(e))); var irs = from ur in ranges from r in source where r.Intersects(ur) from ir in r.Subtract(ur) select ir; var result = irs.Distinct(new IndexRangeComparer()).ToList(); result.AddRange(onlyInSource); result.Sort((r1, r2) => r1.CompareTo(r2)); return result; } public static IndexRange FromLength(long startIndex, long length) { return new IndexRange(startIndex, startIndex + length - 1); } public IndexRange(long startIndex, long endIndex) { this.StartIndex = startIndex; this.EndIndex = endIndex; } public bool After(IndexRange range) { if(Intersects(range)) { return false; } return (this.StartIndex > range.EndIndex); } public IEnumerable<IndexRange> Subtract(IndexRange range) { if(this.Equals(range)) { return new List<IndexRange>(); } if(!this.Intersects(range)) { return new List<IndexRange> {this}; } var intersection = this.Intersection(range); if(this.Equals(intersection)) { return new List<IndexRange>(); } if(intersection.StartIndex == this.StartIndex) { return new List<IndexRange> {new IndexRange(intersection.EndIndex + 1, this.EndIndex)}; } if (intersection.EndIndex == this.EndIndex) { return new List<IndexRange> { new IndexRange(this.StartIndex, intersection.StartIndex - 1)}; } return new List<IndexRange> { new IndexRange(this.StartIndex, intersection.StartIndex - 1), new IndexRange(intersection.EndIndex + 1, this.EndIndex) }; } public bool Abuts(IndexRange range) { return !this.Intersects(range) && this.Gap(range) == null; } public IndexRange Gap(IndexRange range) { if(this.Intersects(range)) return null; if(this.CompareTo(range) > 0) { var r = new IndexRange(range.EndIndex + 1, this.StartIndex - 1); if(r.Length <= 0) return null; return r; } var result = new IndexRange(this.EndIndex + 1, range.StartIndex - 1); if(result.Length <= 0) return null; return result; } public int CompareTo(IndexRange range) { return this.StartIndex != range.StartIndex ? this.StartIndex.CompareTo(range.StartIndex) : this.EndIndex.CompareTo(range.EndIndex); } public IndexRange Merge(IndexRange range) { if(!this.Abuts(range)) { throw new ArgumentOutOfRangeException("range", "Ranges must be adjacent."); } if(this.CompareTo(range) > 0) { return new IndexRange(range.StartIndex, this.EndIndex); } return new IndexRange(this.StartIndex, range.EndIndex); } public IEnumerable<IndexRange> PartitionBy(int size) { if(this.Length <= size) { return new List<IndexRange> {this}; } var result = new List<IndexRange>(); long count = this.Length/size; long remainder = this.Length%size; for (long i = 0; i < count; i++) { result.Add(IndexRange.FromLength(this.StartIndex + i*size, size)); } if(remainder != 0) { result.Add(IndexRange.FromLength(this.StartIndex + count*size, remainder)); } return result; } public IndexRange Intersection(IndexRange range) { if(!this.Intersects(range)) { return null; } var start = Math.Max(range.StartIndex, this.StartIndex); var end = Math.Min(range.EndIndex, this.EndIndex); return new IndexRange(start, end); } public bool Intersects(IndexRange range) { var start = Math.Max(range.StartIndex, this.StartIndex); var end = Math.Min(range.EndIndex, this.EndIndex); return start <= end; } public bool Includes(IndexRange range) { return this.Includes(range.StartIndex) && this.Includes(range.EndIndex); } public long EndIndex { get; private set; } public long StartIndex { get; private set; } public bool Includes(long value) { return value >= StartIndex && value <= EndIndex; } public long Length { get { return EndIndex - StartIndex + 1; } } public bool Equals(IndexRange other) { return other != null && this.StartIndex == other.StartIndex && this.EndIndex == other.EndIndex; } public override string ToString() { return String.Format("[{0},{1}]", StartIndex, EndIndex); } public override bool Equals(object obj) { var range = obj as IndexRange; return range != null && comparer.Equals(this, range); } public override int GetHashCode() { return comparer.GetHashCode(this); } } }
using System; using System.Collections; using System.ComponentModel; using System.Threading; using System.Windows.Threading; using System.Windows.Automation; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows; using System.Windows.Input; using System.Windows.Media; using MS.Utility; // Disable CS3001: Warning as Error: not CLS-compliant #pragma warning disable 3001 namespace System.Windows.Controls { /// <summary> /// RadioButton implements option button with two states: true or false /// </summary> [Localizability(LocalizationCategory.RadioButton)] public class RadioButton : ToggleButton { #region Constructors static RadioButton() { DefaultStyleKeyProperty.OverrideMetadata(typeof(RadioButton), new FrameworkPropertyMetadata(typeof(RadioButton))); _dType = DependencyObjectType.FromSystemTypeInternal(typeof(RadioButton)); KeyboardNavigation.AcceptsReturnProperty.OverrideMetadata(typeof(RadioButton), new FrameworkPropertyMetadata(MS.Internal.KnownBoxes.BooleanBoxes.FalseBox)); } /// <summary> /// Default RadioButton constructor /// </summary> /// <remarks> /// Automatic determination of current Dispatcher. Use alternative constructor /// that accepts a Dispatcher for best performance. /// </remarks> public RadioButton() : base() { } #endregion #region private helpers private static void OnGroupNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { RadioButton radioButton = (RadioButton)d; string groupName = e.NewValue as string; string currentlyRegisteredGroupName = _currentlyRegisteredGroupName.GetValue(radioButton); if (groupName != currentlyRegisteredGroupName) { // Unregister the old group name if set if (!string.IsNullOrEmpty(currentlyRegisteredGroupName)) Unregister(currentlyRegisteredGroupName, radioButton); // Register the new group name is set if (!string.IsNullOrEmpty(groupName)) Register(groupName, radioButton); } } private static void Register(string groupName, RadioButton radioButton) { if (_groupNameToElements == null) _groupNameToElements = new Hashtable(1); lock (_groupNameToElements) { ArrayList elements = (ArrayList)_groupNameToElements[groupName]; if (elements == null) { elements = new ArrayList(1); _groupNameToElements[groupName] = elements; } else { // There were some elements there, remove dead ones PurgeDead(elements, null); } elements.Add(new WeakReference(radioButton)); } _currentlyRegisteredGroupName.SetValue(radioButton, groupName); } private static void Unregister(string groupName, RadioButton radioButton) { if (_groupNameToElements == null) return; lock (_groupNameToElements) { // Get all elements bound to this key and remove this element ArrayList elements = (ArrayList)_groupNameToElements[groupName]; if (elements != null) { PurgeDead(elements, radioButton); if (elements.Count == 0) { _groupNameToElements.Remove(groupName); } } } _currentlyRegisteredGroupName.SetValue(radioButton, null); } private static void PurgeDead(ArrayList elements, object elementToRemove) { for (int i = 0; i < elements.Count; ) { WeakReference weakReference = (WeakReference)elements[i]; object element = weakReference.Target; if (element == null || element == elementToRemove) { elements.RemoveAt(i); } else { i++; } } } private void UpdateRadioButtonGroup() { string groupName = GroupName; if (!string.IsNullOrEmpty(groupName)) { Visual rootScope = KeyboardNavigation.GetVisualRoot(this); if (_groupNameToElements == null) _groupNameToElements = new Hashtable(1); lock (_groupNameToElements) { // Get all elements bound to this key and remove this element ArrayList elements = (ArrayList)_groupNameToElements[groupName]; for (int i = 0; i < elements.Count; ) { WeakReference weakReference = (WeakReference)elements[i]; RadioButton rb = weakReference.Target as RadioButton; if (rb == null) { // Remove dead instances elements.RemoveAt(i); } else { // Uncheck all checked RadioButtons different from the current one if (rb != this && (rb.IsChecked == true) && rootScope == KeyboardNavigation.GetVisualRoot(rb)) rb.UncheckRadioButton(); i++; } } } } else // Logical parent should be the group { DependencyObject parent = this.Parent; if (parent != null) { // Traverse logical children IEnumerable children = LogicalTreeHelper.GetChildren(parent); IEnumerator itor = children.GetEnumerator(); while (itor.MoveNext()) { RadioButton rb = itor.Current as RadioButton; if (rb != null && rb != this && string.IsNullOrEmpty(rb.GroupName) && (rb.IsChecked == true)) rb.UncheckRadioButton(); } } } } private void UncheckRadioButton() { SetCurrentValueInternal(IsCheckedProperty, MS.Internal.KnownBoxes.BooleanBoxes.FalseBox); } #endregion #region Properties and Events /// <summary> /// The DependencyID for the GroupName property. /// Default Value: "String.Empty" /// </summary> public static readonly DependencyProperty GroupNameProperty = DependencyProperty.Register( "GroupName", typeof(string), typeof(RadioButton), new FrameworkPropertyMetadata(String.Empty, new PropertyChangedCallback(OnGroupNameChanged))); /// <summary> /// GroupName determine mutually excusive radiobutton groups /// </summary> [DefaultValue("")] [Localizability(LocalizationCategory.NeverLocalize)] // cannot be localized public string GroupName { get { return (string)GetValue(GroupNameProperty); } set { SetValue(GroupNameProperty, value); } } #endregion #region Override methods /// <summary> /// Creates AutomationPeer (<see cref="UIElement.OnCreateAutomationPeer"/>) /// </summary> protected override System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer() { return new System.Windows.Automation.Peers.RadioButtonAutomationPeer(this); } /// <summary> /// This method is invoked when the IsChecked becomes true. /// </summary> /// <param name="e">RoutedEventArgs.</param> protected override void OnChecked(RoutedEventArgs e) { // If RadioButton is checked we should uncheck the others in the same group UpdateRadioButtonGroup(); base.OnChecked(e); } /// <summary> /// This override method is called from OnClick(). /// RadioButton implements its own toggle behavior /// </summary> protected internal override void OnToggle() { SetCurrentValueInternal(IsCheckedProperty, MS.Internal.KnownBoxes.BooleanBoxes.TrueBox); } /// <summary> /// The Access key for this control was invoked. /// </summary> /// <param name="e"></param> protected override void OnAccessKey(AccessKeyEventArgs e) { if (!IsKeyboardFocused) { Focus(); } base.OnAccessKey(e); } #endregion #region Accessibility #endregion Accessibility #region DTypeThemeStyleKey // Returns the DependencyObjectType for the registered ThemeStyleKey's default // value. Controls will override this method to return approriate types. internal override DependencyObjectType DTypeThemeStyleKey { get { return _dType; } } private static DependencyObjectType _dType; #endregion DTypeThemeStyleKey #region private data [ThreadStatic] private static Hashtable _groupNameToElements; private static readonly UncommonField<string> _currentlyRegisteredGroupName = new UncommonField<string>(); #endregion private data } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Management.Automation.Language; using System.Text; using System.Collections; using System.Collections.Generic; using System.Management.Automation; using System.Management.Automation.Internal; using Dbg = System.Management.Automation.Diagnostics; // // Now define the set of commands for manipulating modules. // namespace Microsoft.PowerShell.Commands { #region Module Specification class /// <summary> /// Represents module specification written in a module manifest (i.e. in RequiredModules member/field). /// /// Module manifest allows 2 forms of module specification: /// 1. string - module name /// 2. hashtable - [string]ModuleName (required) + [Version]ModuleVersion/RequiredVersion (required) + [Guid]GUID (optional) /// /// so we have a constructor that takes a string and a constructor that takes a hashtable /// (so that LanguagePrimitives.ConvertTo can cast a string or a hashtable to this type) /// </summary> public class ModuleSpecification { /// <summary> /// Default constructor /// </summary> public ModuleSpecification() { } /// <summary> /// Construct a module specification from the module name. /// </summary> /// <param name="moduleName">The module name.</param> public ModuleSpecification(string moduleName) { if (string.IsNullOrEmpty(moduleName)) { throw new ArgumentNullException("moduleName"); } this.Name = moduleName; // Alias name of miniumVersion this.Version = null; this.RequiredVersion = null; this.MaximumVersion = null; this.Guid = null; } /// <summary> /// Construct a module specification from a hashtable. /// Keys can be ModuleName, ModuleVersion, and Guid. /// ModuleName must be convertible to <see cref="string"/>. /// ModuleVersion must be convertible to <see cref="Version"/>. /// Guid must be convertible to <see cref="Guid"/>. /// </summary> /// <param name="moduleSpecification">The module specification as a hashtable.</param> public ModuleSpecification(Hashtable moduleSpecification) { if (moduleSpecification == null) { throw new ArgumentNullException("moduleSpecification"); } var exception = ModuleSpecificationInitHelper(this, moduleSpecification); if (exception != null) { throw exception; } } /// <summary> /// Initialize moduleSpecification from hashtable. Return exception object, if hashtable cannot be converted. /// Return null, in the success case. /// </summary> /// <param name="moduleSpecification">object to initalize</param> /// <param name="hashtable">contains info about object to initialize.</param> /// <returns></returns> internal static Exception ModuleSpecificationInitHelper(ModuleSpecification moduleSpecification, Hashtable hashtable) { StringBuilder badKeys = new StringBuilder(); try { foreach (DictionaryEntry entry in hashtable) { if (entry.Key.ToString().Equals("ModuleName", StringComparison.OrdinalIgnoreCase)) { moduleSpecification.Name = LanguagePrimitives.ConvertTo<string>(entry.Value); } else if (entry.Key.ToString().Equals("ModuleVersion", StringComparison.OrdinalIgnoreCase)) { moduleSpecification.Version = LanguagePrimitives.ConvertTo<Version>(entry.Value); } else if (entry.Key.ToString().Equals("RequiredVersion", StringComparison.OrdinalIgnoreCase)) { moduleSpecification.RequiredVersion = LanguagePrimitives.ConvertTo<Version>(entry.Value); } else if (entry.Key.ToString().Equals("MaximumVersion", StringComparison.OrdinalIgnoreCase)) { moduleSpecification.MaximumVersion = LanguagePrimitives.ConvertTo<String>(entry.Value); ModuleCmdletBase.GetMaximumVersion(moduleSpecification.MaximumVersion); } else if (entry.Key.ToString().Equals("GUID", StringComparison.OrdinalIgnoreCase)) { moduleSpecification.Guid = LanguagePrimitives.ConvertTo<Guid?>(entry.Value); } else { if (badKeys.Length > 0) badKeys.Append(", "); badKeys.Append("'"); badKeys.Append(entry.Key.ToString()); badKeys.Append("'"); } } } // catch all exceptions here, we are going to report them via return value. // Example of catched exception: one of convertions to Version failed. catch (Exception e) { return e; } string message; if (badKeys.Length != 0) { message = StringUtil.Format(Modules.InvalidModuleSpecificationMember, "ModuleName, ModuleVersion, RequiredVersion, GUID", badKeys); return new ArgumentException(message); } if (string.IsNullOrEmpty(moduleSpecification.Name)) { message = StringUtil.Format(Modules.RequiredModuleMissingModuleName); return new MissingMemberException(message); } if (moduleSpecification.RequiredVersion == null && moduleSpecification.Version == null && moduleSpecification.MaximumVersion == null) { message = StringUtil.Format(Modules.RequiredModuleMissingModuleVersion); return new MissingMemberException(message); } if (moduleSpecification.RequiredVersion != null && moduleSpecification.Version != null) { message = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, "ModuleVersion", "RequiredVersion"); return new ArgumentException(message); } if (moduleSpecification.RequiredVersion != null && moduleSpecification.MaximumVersion != null) { message = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, "MaxiumVersion", "RequiredVersion"); return new ArgumentException(message); } return null; } internal ModuleSpecification(PSModuleInfo moduleInfo) { if (moduleInfo == null) { throw new ArgumentNullException("moduleInfo"); } this.Name = moduleInfo.Name; this.Version = moduleInfo.Version; this.Guid = moduleInfo.Guid; } /// <summary> /// Implements ToString() for a module specification. If the specification /// just contains a Name, then that is returned as is. Otherwise, the object is /// formatted as a PowerSHell hashtable. /// </summary> /// <returns></returns> public override string ToString() { string moduleSpecString = string.Empty; if (Guid == null && Version == null && RequiredVersion == null && MaximumVersion == null) { moduleSpecString = Name; } else { moduleSpecString = "@{ ModuleName = '" + Name + "'"; if (Guid != null) { moduleSpecString += "; Guid = '{" + Guid + "}' "; } if (RequiredVersion != null) { moduleSpecString += "; RequiredVersion = '" + RequiredVersion + "'"; } else { if (Version != null) { moduleSpecString += "; ModuleVersion = '" + Version + "'"; } if (MaximumVersion != null) { moduleSpecString += "; MaximumVersion = '" + MaximumVersion + "'"; } } moduleSpecString += " }"; } return moduleSpecString; } /// <summary> /// Parse the specified string into a ModuleSpecification object /// </summary> /// <param name="input">The module specification string</param> /// <param name="result">the ModuleSpecification object</param> /// <returns></returns> public static bool TryParse(string input, out ModuleSpecification result) { result = null; try { Hashtable hashtable; if (Parser.TryParseAsConstantHashtable(input, out hashtable)) { result = new ModuleSpecification(hashtable); return true; } } catch { // Ignoring the exceptions to return false } return false; } /// <summary> /// The module name. /// </summary> public string Name { get; internal set; } /// <summary> /// The module GUID, if specified. /// </summary> public Guid? Guid { get; internal set; } /// <summary> /// The module version number if specified, otherwise null. /// </summary> public Version Version { get; internal set; } /// <summary> /// The module maxVersion number if specified, otherwise null. /// </summary> public String MaximumVersion { get; internal set; } /// <summary> /// The exact version of the module if specified, otherwise null. /// </summary> public Version RequiredVersion { get; internal set; } } internal class ModuleSpecificationComparer : IEqualityComparer<ModuleSpecification> { public bool Equals(ModuleSpecification x, ModuleSpecification y) { bool result = false; if (x == null && y == null) { result = true; } else if (x != null && y != null) { if (x.Name != null && y.Name != null) { result = x.Name.Equals(y.Name, StringComparison.OrdinalIgnoreCase); } else { result = true; } if (result) { if (x.Guid.HasValue && y.Guid.HasValue) { result = x.Guid.Equals(y.Guid); } } if (result) { if (x.Version != null && y.Version != null) { result = x.Version.Equals(y.Version); } else if (x.Version != null || y.Version != null) { result = false; } if (x.MaximumVersion != null && y.MaximumVersion != null) { result = x.MaximumVersion.Equals(y.MaximumVersion); } else if (x.MaximumVersion != null || y.MaximumVersion != null) { result = false; } if (result && x.RequiredVersion != null && y.RequiredVersion != null) { result = x.RequiredVersion.Equals(y.RequiredVersion); } else if (result && (x.RequiredVersion != null || y.RequiredVersion != null)) { result = false; } } } return result; } public int GetHashCode(ModuleSpecification obj) { int result = 0; if (obj != null) { if (obj.Name != null) { result = result ^ obj.Name.GetHashCode(); } if (obj.Guid.HasValue) { result = result ^ obj.Guid.GetHashCode(); } if (obj.Version != null) { result = result ^ obj.Version.GetHashCode(); } if (obj.MaximumVersion != null) { result = result ^ obj.MaximumVersion.GetHashCode(); } if (obj.RequiredVersion != null) { result = result ^ obj.RequiredVersion.GetHashCode(); } } return result; } } #endregion } // Microsoft.PowerShell.Commands
/* Copyright Microsoft Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 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 2 License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using MileageStats.Domain.Contracts; using MileageStats.Domain.Contracts.Data; using MileageStats.Domain.Handlers; using MileageStats.Domain.Models; using MileageStats.Web.Models; using Moq; using Xunit; namespace MileageStats.Domain.Tests { public class WhenCanAddVehicle { private readonly Mock<IVehicleRepository> _vehicleRepo; private readonly Mock<IVehicleManufacturerRepository> _manufacturerRepo; private const int UserId = 99; private const int DefaultVehicleId = 1; public WhenCanAddVehicle() { _vehicleRepo = new Mock<IVehicleRepository>(); _manufacturerRepo = new Mock<IVehicleManufacturerRepository>(); } [Fact] public void ThenNoValidationErrorsAreReturned() { var vehicleForm = new VehicleFormModel { Name = "vehicle" }; var vehicles = new List<Vehicle> { new Vehicle() }; _vehicleRepo .Setup(vr => vr.GetVehicles(UserId)) .Returns(vehicles); var subhandler = MockCanValidateVehicleYearMakeAndModel(vehicleForm); var handler = new CanAddVehicle(_vehicleRepo.Object, subhandler); var actual = handler.Execute(UserId, vehicleForm); Assert.Empty(actual); } [Fact] public void WithTooManyVehicles_ThenReturnsValidationResult() { var vehicleForm = new VehicleFormModel { Name = "vehicle" }; var vehicles = Enumerable .Range(0, CanAddVehicle.MaxNumberOfVehiclesPerUser) .Select(i => new Vehicle()); _vehicleRepo .Setup(vr => vr.GetVehicles(UserId)) .Returns(vehicles); var subhandler = MockCanValidateVehicleYearMakeAndModel(vehicleForm); var handler = new CanAddVehicle(_vehicleRepo.Object, subhandler); var actual = handler.Execute(UserId, vehicleForm).ToList(); Assert.Equal(1, actual.Count); Assert.Contains("maximum number", actual[0].Message, StringComparison.CurrentCultureIgnoreCase); } [Fact] public void WithMissingYearForMake_ThenReturnsValidationResult() { var vehicleForm = new VehicleFormModel { Name = "vehicle", MakeName = "Test" }; _manufacturerRepo .Setup(x => x.IsValidYear(It.IsAny<int>())) .Returns(true); _manufacturerRepo .Setup(x => x.IsValidMake(It.IsAny<int>(), It.IsAny<string>())) .Returns(true); _manufacturerRepo .Setup(x => x.IsValidModel(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<string>())) .Returns(true); var handler = new CanValidateVehicleYearMakeAndModel(_manufacturerRepo.Object); var actual = handler.Execute(vehicleForm).ToList(); Assert.Equal(1, actual.Count); Assert.Contains("missing", actual[0].Message, StringComparison.CurrentCultureIgnoreCase); Assert.Contains("year", actual[0].Message, StringComparison.CurrentCultureIgnoreCase); Assert.Contains("make", actual[0].Message, StringComparison.CurrentCultureIgnoreCase); } [Fact] public void WithMissingYearForModel_ThenReturnsValidationResult() { var vehicleForm = new VehicleFormModel { Name = "vehicle", ModelName = "Test" }; _manufacturerRepo .Setup(x => x.IsValidYear(It.IsAny<int>())) .Returns(true); _manufacturerRepo .Setup(x => x.IsValidMake(It.IsAny<int>(), It.IsAny<string>())) .Returns(true); _manufacturerRepo .Setup(x => x.IsValidModel(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<string>())) .Returns(true); var handler = new CanValidateVehicleYearMakeAndModel(_manufacturerRepo.Object); var actual = handler.Execute(vehicleForm).ToList(); Assert.Equal(1, actual.Count); Assert.Contains("missing", actual[0].Message, StringComparison.CurrentCultureIgnoreCase); Assert.Contains("year", actual[0].Message, StringComparison.CurrentCultureIgnoreCase); Assert.Contains("model", actual[0].Message, StringComparison.CurrentCultureIgnoreCase); } [Fact] public void WithMissingMakeForModel_ThenReturnsValidationResult() { var vehicleForm = new VehicleFormModel { Name = "vehicle", Year = 1975, ModelName = "Test" }; _manufacturerRepo .Setup(x => x.IsValidYear(It.IsAny<int>())) .Returns(true); _manufacturerRepo .Setup(x => x.IsValidMake(It.IsAny<int>(), It.IsAny<string>())) .Returns(true); _manufacturerRepo .Setup(x => x.IsValidModel(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<string>())) .Returns(true); var handler = new CanValidateVehicleYearMakeAndModel(_manufacturerRepo.Object); var actual = handler.Execute(vehicleForm).ToList(); Assert.Equal(1, actual.Count); Assert.Contains("missing", actual[0].Message, StringComparison.CurrentCultureIgnoreCase); Assert.Contains("make", actual[0].Message, StringComparison.CurrentCultureIgnoreCase); Assert.Contains("model", actual[0].Message, StringComparison.CurrentCultureIgnoreCase); } [Fact] public void WithInvalidYear_ThenReturnsValidationResult() { var vehicleForm = new VehicleFormModel { Name = "vehicle", Year = 2100, }; SetupManufacturerRepo(isYearValid: false); var handler = new CanValidateVehicleYearMakeAndModel(_manufacturerRepo.Object); var actual = handler.Execute(vehicleForm).ToList(); Assert.Equal(1, actual.Count); Assert.Contains("not valid", actual[0].Message, StringComparison.CurrentCultureIgnoreCase); Assert.Contains("year", actual[0].Message, StringComparison.CurrentCultureIgnoreCase); } [Fact] public void WithInvalidMake_ThenReturnsValidationResult() { var vehicleForm = new VehicleFormModel { Name = "vehicle", Year = 1, MakeName = "Test", ModelName = "Test" }; SetupManufacturerRepo(isMakeValid: false); var handler = new CanValidateVehicleYearMakeAndModel(_manufacturerRepo.Object); var actual = handler.Execute(vehicleForm).ToList(); Assert.Equal(1, actual.Count); Assert.Contains("not valid", actual[0].Message, StringComparison.CurrentCultureIgnoreCase); Assert.Contains("make", actual[0].Message, StringComparison.CurrentCultureIgnoreCase); } [Fact] public void WithInvalidModel_ThenReturnsValidationResult() { var vehicleForm = new VehicleFormModel { Name = "vehicle", Year = 1, MakeName = "Test", ModelName = "Test" }; SetupManufacturerRepo(isModelValid: false); var handler = new CanValidateVehicleYearMakeAndModel(_manufacturerRepo.Object); var actual = handler.Execute(vehicleForm).ToList(); Assert.Equal(1, actual.Count); Assert.Contains("not valid", actual[0].Message, StringComparison.CurrentCultureIgnoreCase); Assert.Contains("model", actual[0].Message, StringComparison.CurrentCultureIgnoreCase); } private static CanValidateVehicleYearMakeAndModel MockCanValidateVehicleYearMakeAndModel(VehicleFormModel vehicleForm) { var subhandler = new Mock<CanValidateVehicleYearMakeAndModel>(null); subhandler .Setup(h => h.Execute(vehicleForm)) .Returns(Enumerable.Empty<ValidationResult>()); return subhandler.Object; } void SetupManufacturerRepo(bool isYearValid = true, bool isMakeValid = true, bool isModelValid = true) { _manufacturerRepo .Setup(x => x.IsValidYear(It.IsAny<int>())) .Returns(isYearValid); _manufacturerRepo .Setup(x => x.IsValidMake(It.IsAny<int>(), It.IsAny<string>())) .Returns(isMakeValid); _manufacturerRepo .Setup(x => x.IsValidModel(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<string>())) .Returns(isModelValid); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Net.Http; using System.Runtime.InteropServices; using System.Text; using Xunit; using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle; namespace System.Net.Http.WinHttpHandlerUnitTests { public class WinHttpRequestStreamTests { public WinHttpRequestStreamTests() { TestControl.ResetAll(); } [Fact] public void CanWrite_WhenCreated_ReturnsTrue() { Stream stream = MakeRequestStream(); bool result = stream.CanWrite; Assert.True(result); } [Fact] public void CanWrite_WhenDisposed_ReturnsFalse() { Stream stream = MakeRequestStream(); stream.Dispose(); bool result = stream.CanWrite; Assert.False(result); } [Fact] public void CanSeek_Always_ReturnsFalse() { Stream stream = MakeRequestStream(); bool result = stream.CanSeek; Assert.False(result); } [Fact] public void CanRead_Always_ReturnsFalse() { Stream stream = MakeRequestStream(); bool result = stream.CanRead; Assert.False(result); } [Fact] public void Length_WhenCreated_ThrowsNotSupportedException() { Stream stream = MakeRequestStream(); Assert.Throws<NotSupportedException>(() => { long result = stream.Length; }); } [Fact] public void Length_WhenDisposed_ThrowsObjectDisposedException() { Stream stream = MakeRequestStream(); stream.Dispose(); Assert.Throws<ObjectDisposedException>(() => { long result = stream.Length; }); } [Fact] public void Position_WhenCreatedDoGet_ThrowsNotSupportedException() { Stream stream = MakeRequestStream(); Assert.Throws<NotSupportedException>(() => { long result = stream.Position; }); } [Fact] public void Position_WhenDisposedDoGet_ThrowsObjectDisposedException() { Stream stream = MakeRequestStream(); stream.Dispose(); Assert.Throws<ObjectDisposedException>(() => { long result = stream.Position; }); } [Fact] public void Position_WhenCreatedDoSet_ThrowsNotSupportedException() { Stream stream = MakeRequestStream(); Assert.Throws<NotSupportedException>(() => { stream.Position = 0; }); } [Fact] public void Position_WhenDisposedDoSet_ThrowsObjectDisposedExceptionException() { Stream stream = MakeRequestStream(); stream.Dispose(); Assert.Throws<ObjectDisposedException>(() => { stream.Position = 0; }); } [Fact] public void Seek_WhenCreated_ThrowsNotSupportedException() { Stream stream = MakeRequestStream(); Assert.Throws<NotSupportedException>(() => { stream.Seek(0, SeekOrigin.Begin); }); } [Fact] public void Seek_WhenDisposed_ThrowsObjectDisposedException() { Stream stream = MakeRequestStream(); stream.Dispose(); Assert.Throws<ObjectDisposedException>(() => { stream.Seek(0, SeekOrigin.Begin); }); } [Fact] public void SetLength_WhenCreated_ThrowsNotSupportedException() { Stream stream = MakeRequestStream(); Assert.Throws<NotSupportedException>(() => { stream.SetLength(0); }); } [Fact] public void SetLength_WhenDisposed_ThrowsObjectDisposedException() { Stream stream = MakeRequestStream(); stream.Dispose(); Assert.Throws<ObjectDisposedException>(() => { stream.SetLength(0); }); } [Fact] public void Read_WhenCreated_ThrowsNotSupportedException() { Stream stream = MakeRequestStream(); Assert.Throws<NotSupportedException>(() => { stream.Read(new byte[1], 0, 1); }); } [Fact] public void Read_WhenDisposed_ThrowsObjectDisposedException() { Stream stream = MakeRequestStream(); stream.Dispose(); Assert.Throws<ObjectDisposedException>(() => { stream.Read(new byte[1], 0, 1); }); } [Fact] public void Write_BufferIsNull_ThrowsArgumentNullException() { Stream stream = MakeRequestStream(); Assert.Throws<ArgumentNullException>(() => { stream.Write(null, 0, 1); }); } [Fact] public void Write_OffsetIsNegative_ThrowsArgumentOutOfRangeException() { Stream stream = MakeRequestStream(); Assert.Throws<ArgumentOutOfRangeException>(() => { stream.Write(new byte[1], -1, 1); }); } [Fact] public void Write_CountIsNegative_ThrowsArgumentOutOfRangeException() { Stream stream = MakeRequestStream(); Assert.Throws<ArgumentOutOfRangeException>(() => { stream.Write(new byte[1], 0, -1); }); } [Fact] public void Write_OffsetPlusCountExceedsBufferLength_ThrowsArgumentException() { Stream stream = MakeRequestStream(); Assert.Throws<ArgumentException>(() => { stream.Write(new byte[1], 0, 3); }); } [Fact] public void Write_OffsetPlusCountMaxValueExceedsBufferLength_ThrowsArgumentException() { Stream stream = MakeRequestStream(); Assert.Throws<ArgumentException>(() => { stream.Write(new byte[1], int.MaxValue, int.MaxValue); }); } [Fact] public void Write_WhenDisposed_ThrowsObjectDisposedException() { Stream stream = MakeRequestStream(); stream.Dispose(); Assert.Throws<ObjectDisposedException>(() => { stream.Write(new byte[1], 0, 1); }); } [Fact] public void Write_NetworkFails_ThrowsIOException() { Stream stream = MakeRequestStream(); TestControl.Fail.WinHttpWriteData = true; Assert.Throws<IOException>(() => { stream.Write(new byte[1], 0, 1); }); } [Fact] public void Write_NoOffset_AllDataIsWritten() { Stream stream = MakeRequestStream(); string data = "Test Data"; byte[] buffer = Encoding.ASCII.GetBytes(data); stream.Write(buffer, 0, buffer.Length); byte[] serverBytes = TestServer.RequestBody; Assert.True(ByteArraysEqual(buffer, 0, buffer.Length, serverBytes, 0, serverBytes.Length)); } [Fact] public void Write_UsingOffset_DataFromOffsetIsWritten() { Stream stream = MakeRequestStream(); string data = "Test Data"; byte[] buffer = Encoding.ASCII.GetBytes(data); int offset = 5; stream.Write(buffer, offset, buffer.Length - offset); byte[] serverBytes = TestServer.RequestBody; Assert.True(ByteArraysEqual(buffer, offset, buffer.Length - offset, serverBytes, 0, serverBytes.Length)); } internal Stream MakeRequestStream() { SafeWinHttpHandle requestHandle = new FakeSafeWinHttpHandle(true); return new WinHttpRequestStream(requestHandle, false); } private bool ByteArraysEqual(byte[] array1, int offset1, int length1, byte[] array2, int offset2, int length2) { if (length1 != length2) { return false; } for (int i = 0; i < length1; i++) { if (array1[offset1 + i] != array2[offset2 + i]) { return false; } } return true; } } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010-2017 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion -- License Terms -- using System; using System.Diagnostics; #if NETSTANDARD1_1 using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; #endif // NETSTANDARD1_1 using System.Reflection; using System.Reflection.Emit; using System.Security; using System.Threading; using MsgPack.Serialization.AbstractSerializers; namespace MsgPack.Serialization.EmittingSerializers { /// <summary> /// Defines common features and interfaces for <see cref="SerializationMethodGeneratorManager"/>. /// </summary> internal sealed class SerializationMethodGeneratorManager { /// <summary> /// Get the appropriate <see cref="SerializationMethodGeneratorManager"/> for the current configuration. /// </summary> /// <returns> /// The appropriate <see cref="SerializationMethodGeneratorManager"/> for the current configuration. /// This value will not be <c>null</c>. /// </returns> public static SerializationMethodGeneratorManager Get() { #if DEBUG && !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 return Get( SerializerDebugging.DumpEnabled ? SerializationMethodGeneratorOption.CanDump : SerializationMethodGeneratorOption.Fast ); #else return Get( SerializationMethodGeneratorOption.Fast ); #endif // DEBUG && !SILVERLIGHT && !NETSTANDARD1_1 && !NETSTANDARD1_3 } /// <summary> /// Get the appropriate <see cref="SerializationMethodGeneratorManager"/> for specified options. /// </summary> /// <param name="option"><see cref="SerializationMethodGeneratorOption"/>.</param> /// <returns> /// The appropriate <see cref="SerializationMethodGeneratorManager"/> for specified options. /// This value will not be <c>null</c>. /// </returns> public static SerializationMethodGeneratorManager Get( SerializationMethodGeneratorOption option ) { switch ( option ) { #if !SILVERLIGHT #if !NETSTANDARD1_1 && !NETSTANDARD1_3 case SerializationMethodGeneratorOption.CanDump: { return CanDump; } #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 case SerializationMethodGeneratorOption.CanCollect: { return CanCollect; } #endif // !SILVERLIGHT default: { return Fast; } } } private static readonly ConstructorInfo _debuggableAttributeCtor = typeof( DebuggableAttribute ).GetConstructor( new[] { typeof( bool ), typeof( bool ) } ); private static readonly object[] _debuggableAttributeCtorArguments = { true, true }; private static int _assemblySequence = -1; #if !SILVERLIGHT private static SerializationMethodGeneratorManager _canCollect = Create( false, true, null ); /// <summary> /// Get the singleton instance for can-collect mode. /// </summary> public static SerializationMethodGeneratorManager CanCollect { get { return _canCollect; } } #if !NETSTANDARD1_1 && !NETSTANDARD1_3 private static SerializationMethodGeneratorManager _canDump = Create( true, false, null ); /// <summary> /// Get the singleton instance for can-dump mode. /// </summary> public static SerializationMethodGeneratorManager CanDump { get { return _canDump; } } #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 #endif // !SILVERLIGHT private static SerializationMethodGeneratorManager _fast = Create( false, false, null ); /// <summary> /// Get the singleton instance for fast mode. /// </summary> public static SerializationMethodGeneratorManager Fast { get { return _fast; } } private static SerializationMethodGeneratorManager Create( bool isDebuggable, bool isCollectable, AssemblyBuilder assemblyBuilder ) { try { return new SerializationMethodGeneratorManager( isDebuggable, isCollectable, assemblyBuilder ); } catch ( PlatformNotSupportedException ) { return null; } } internal static void Refresh() { #if !SILVERLIGHT _canCollect = Create( false, true, null ); #if !NETSTANDARD1_1 && !NETSTANDARD1_3 _canDump = Create( true, false, null ); #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 #endif // !SILVERLIGHT _fast = Create( false, false, null ); } // ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable private readonly AssemblyBuilder _assembly; private readonly ModuleBuilder _module; private readonly bool _isDebuggable; #if NET35 [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "isCollectable", Justification = "Used in other platforms" )] #endif // NET35 #if !NET35 [SecuritySafeCritical] #endif // !NET35 private SerializationMethodGeneratorManager( bool isDebuggable, bool isCollectable, AssemblyBuilder assemblyBuilder ) { this._isDebuggable = isDebuggable; string assemblyName; if ( assemblyBuilder != null ) { assemblyName = #if !NETSTANDARD1_1 && !NETSTANDARD1_3 assemblyBuilder.GetName( false ).Name; #else assemblyBuilder.GetName().Name; #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 this._assembly = assemblyBuilder; } else { assemblyName = typeof( SerializationMethodGeneratorManager ).Namespace + ".GeneratedSerealizers" + Interlocked.Increment( ref _assemblySequence ); var dedicatedAssemblyBuilder = #if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 AppDomain.CurrentDomain.DefineDynamicAssembly( new AssemblyName( assemblyName ), isDebuggable ? AssemblyBuilderAccess.RunAndSave #if !NET35 : ( isCollectable ? AssemblyBuilderAccess.RunAndCollect : AssemblyBuilderAccess.Run ) #else : AssemblyBuilderAccess.Run #endif // !NET35 #if DEBUG , SerializerDebugging.DumpDirectory #endif // DEBUG ); #else AssemblyBuilder.DefineDynamicAssembly( new AssemblyName( assemblyName ), isCollectable ? AssemblyBuilderAccess.RunAndCollect : AssemblyBuilderAccess.Run ); #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 SetUpAssemblyBuilderAttributes( dedicatedAssemblyBuilder, isDebuggable ); this._assembly = dedicatedAssemblyBuilder; } #if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 if ( isDebuggable ) { this._module = this._assembly.DefineDynamicModule( assemblyName, assemblyName + ".dll", true ); } else { this._module = this._assembly.DefineDynamicModule( assemblyName, true ); } #else this._module = this._assembly.DefineDynamicModule( assemblyName ); #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !NETSTANDARD2_0 } internal static void SetUpAssemblyBuilderAttributes( AssemblyBuilder dedicatedAssemblyBuilder, bool isDebuggable ) { if ( isDebuggable ) { dedicatedAssemblyBuilder.SetCustomAttribute( new CustomAttributeBuilder( _debuggableAttributeCtor, _debuggableAttributeCtorArguments ) ); } else { dedicatedAssemblyBuilder.SetCustomAttribute( new CustomAttributeBuilder( // ReSharper disable once AssignNullToNotNullAttribute typeof( DebuggableAttribute ).GetConstructor( new[] { typeof( DebuggableAttribute.DebuggingModes ) } ), new object[] { DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints } ) ); } dedicatedAssemblyBuilder.SetCustomAttribute( new CustomAttributeBuilder( // ReSharper disable once AssignNullToNotNullAttribute typeof( System.Runtime.CompilerServices.CompilationRelaxationsAttribute ).GetConstructor( new[] { typeof( int ) } ), new object[] { 8 } ) ); #if !NET35 && !NETSTANDARD1_1 && !NETSTANDARD1_3 dedicatedAssemblyBuilder.SetCustomAttribute( new CustomAttributeBuilder( // ReSharper disable once AssignNullToNotNullAttribute typeof( SecurityRulesAttribute ).GetConstructor( new[] { typeof( SecurityRuleSet ) } ), new object[] { SecurityRuleSet.Level2 }, new[] { typeof( SecurityRulesAttribute ).GetProperty( "SkipVerificationInFullTrust" ) }, new object[] { true } ) ); #endif // !NET35 && !NETSTANDARD1_1 && !NETSTANDARD1_3 } /// <summary> /// Get the dumpable <see cref="SerializationMethodGeneratorManager"/> with specified brandnew assembly builder. /// </summary> /// <param name="assemblyBuilder">An assembly builder which will store all generated types.</param> /// <returns> /// The appropriate <see cref="SerializationMethodGeneratorManager"/> to generate pre-cimplied serializers. /// This value will not be <c>null</c>. /// </returns> public static SerializationMethodGeneratorManager Get( AssemblyBuilder assemblyBuilder ) { return new SerializationMethodGeneratorManager( true, false, assemblyBuilder ); } /// <summary> /// Creates new <see cref="SerializerEmitter"/> which corresponds to the specified <see cref="EmitterFlavor"/>. /// </summary> /// <param name="specification">The specification of the serializer.</param> /// <param name="baseClass">Type of the base class of the serializer.</param> /// <returns>New <see cref="SerializerEmitter"/> which corresponds to the specified <see cref="EmitterFlavor"/>.</returns> public SerializerEmitter CreateObjectEmitter( SerializerSpecification specification, Type baseClass ) { Contract.Requires( specification != null ); Contract.Requires( baseClass != null ); Contract.Ensures( Contract.Result<SerializerEmitter>() != null ); return new SerializerEmitter( this._module, specification, baseClass, this._isDebuggable ); } /// <summary> /// Creates new <see cref="SerializerEmitter"/> which corresponds to the specified <see cref="EmitterFlavor"/>. /// </summary> /// <param name="context">The <see cref="SerializationContext"/>.</param> /// <param name="specification">The specification of the serializer.</param> /// <returns>New <see cref="SerializerEmitter"/> which corresponds to the specified <see cref="EmitterFlavor"/>.</returns> public SerializerEmitter CreateEnumEmitter( SerializationContext context, SerializerSpecification specification ) { Contract.Requires( context != null ); Contract.Requires( specification != null ); Contract.Ensures( Contract.Result<SerializerEmitter>() != null ); return new SerializerEmitter( context, this._module, specification, this._isDebuggable ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.CompilerServices; namespace System.Threading.Tasks { // Task type used to implement: Task ContinueWith(Action<Task,...>) internal sealed class ContinuationTaskFromTask : Task { private Task? m_antecedent; public ContinuationTaskFromTask( Task antecedent, Delegate action, object? state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(action, state, Task.InternalCurrentIfAttached(creationOptions), default, creationOptions, internalOptions, null) { Debug.Assert(action is Action<Task> || action is Action<Task, object?>, "Invalid delegate type in ContinuationTaskFromTask"); m_antecedent = antecedent; } /// <summary> /// Evaluates the value selector of the Task which is passed in as an object and stores the result. /// </summary> internal override void InnerInvoke() { // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. Task? antecedent = m_antecedent; Debug.Assert(antecedent != null, "No antecedent was set for the ContinuationTaskFromTask."); m_antecedent = null; // Notify the debugger we're completing an asynchronous wait on a task antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate Debug.Assert(m_action != null); if (m_action is Action<Task> action) { action(antecedent); return; } if (m_action is Action<Task, object?> actionWithState) { actionWithState(antecedent, m_stateObject); return; } Debug.Fail("Invalid m_action in ContinuationTaskFromTask"); } } // Task type used to implement: Task<TResult> ContinueWith(Func<Task,...>) internal sealed class ContinuationResultTaskFromTask<TResult> : Task<TResult> { private Task? m_antecedent; public ContinuationResultTaskFromTask( Task antecedent, Delegate function, object? state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(function, state, Task.InternalCurrentIfAttached(creationOptions), default, creationOptions, internalOptions, null) { Debug.Assert(function is Func<Task, TResult> || function is Func<Task, object?, TResult>, "Invalid delegate type in ContinuationResultTaskFromTask"); m_antecedent = antecedent; } /// <summary> /// Evaluates the value selector of the Task which is passed in as an object and stores the result. /// </summary> internal override void InnerInvoke() { // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. Task? antecedent = m_antecedent; Debug.Assert(antecedent != null, "No antecedent was set for the ContinuationResultTaskFromTask."); m_antecedent = null; // Notify the debugger we're completing an asynchronous wait on a task antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate Debug.Assert(m_action != null); if (m_action is Func<Task, TResult> func) { m_result = func(antecedent); return; } if (m_action is Func<Task, object?, TResult> funcWithState) { m_result = funcWithState(antecedent, m_stateObject); return; } Debug.Fail("Invalid m_action in ContinuationResultTaskFromTask"); } } // Task type used to implement: Task ContinueWith(Action<Task<TAntecedentResult>,...>) internal sealed class ContinuationTaskFromResultTask<TAntecedentResult> : Task { private Task<TAntecedentResult>? m_antecedent; public ContinuationTaskFromResultTask( Task<TAntecedentResult> antecedent, Delegate action, object? state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(action, state, Task.InternalCurrentIfAttached(creationOptions), default, creationOptions, internalOptions, null) { Debug.Assert(action is Action<Task<TAntecedentResult>> || action is Action<Task<TAntecedentResult>, object?>, "Invalid delegate type in ContinuationTaskFromResultTask"); m_antecedent = antecedent; } /// <summary> /// Evaluates the value selector of the Task which is passed in as an object and stores the result. /// </summary> internal override void InnerInvoke() { // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. Task<TAntecedentResult>? antecedent = m_antecedent; Debug.Assert(antecedent != null, "No antecedent was set for the ContinuationTaskFromResultTask."); m_antecedent = null; // Notify the debugger we're completing an asynchronous wait on a task antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate Debug.Assert(m_action != null); if (m_action is Action<Task<TAntecedentResult>> action) { action(antecedent); return; } if (m_action is Action<Task<TAntecedentResult>, object?> actionWithState) { actionWithState(antecedent, m_stateObject); return; } Debug.Fail("Invalid m_action in ContinuationTaskFromResultTask"); } } // Task type used to implement: Task<TResult> ContinueWith(Func<Task<TAntecedentResult>,...>) internal sealed class ContinuationResultTaskFromResultTask<TAntecedentResult, TResult> : Task<TResult> { private Task<TAntecedentResult>? m_antecedent; public ContinuationResultTaskFromResultTask( Task<TAntecedentResult> antecedent, Delegate function, object? state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(function, state, Task.InternalCurrentIfAttached(creationOptions), default, creationOptions, internalOptions, null) { Debug.Assert(function is Func<Task<TAntecedentResult>, TResult> || function is Func<Task<TAntecedentResult>, object?, TResult>, "Invalid delegate type in ContinuationResultTaskFromResultTask"); m_antecedent = antecedent; } /// <summary> /// Evaluates the value selector of the Task which is passed in as an object and stores the result. /// </summary> internal override void InnerInvoke() { // Get and null out the antecedent. This is crucial to avoid a memory // leak with long chains of continuations. Task<TAntecedentResult>? antecedent = m_antecedent; Debug.Assert(antecedent != null, "No antecedent was set for the ContinuationResultTaskFromResultTask."); m_antecedent = null; // Notify the debugger we're completing an asynchronous wait on a task antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); // Invoke the delegate Debug.Assert(m_action != null); if (m_action is Func<Task<TAntecedentResult>, TResult> func) { m_result = func(antecedent); return; } if (m_action is Func<Task<TAntecedentResult>, object?, TResult> funcWithState) { m_result = funcWithState(antecedent, m_stateObject); return; } Debug.Fail("Invalid m_action in ContinuationResultTaskFromResultTask"); } } // For performance reasons, we don't just have a single way of representing // a continuation object. Rather, we have a hierarchy of types: // - TaskContinuation: abstract base that provides a virtual Run method // - StandardTaskContinuation: wraps a task,options,and scheduler, and overrides Run to process the task with that configuration // - AwaitTaskContinuation: base for continuations created through TaskAwaiter; targets default scheduler by default // - TaskSchedulerAwaitTaskContinuation: awaiting with a non-default TaskScheduler // - SynchronizationContextAwaitTaskContinuation: awaiting with a "current" sync ctx /// <summary>Represents a continuation.</summary> internal abstract class TaskContinuation { /// <summary>Inlines or schedules the continuation.</summary> /// <param name="completedTask">The antecedent task that has completed.</param> /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param> internal abstract void Run(Task completedTask, bool canInlineContinuationTask); /// <summary>Tries to run the task on the current thread, if possible; otherwise, schedules it.</summary> /// <param name="task">The task to run</param> /// <param name="needsProtection"> /// true if we need to protect against multiple threads racing to start/cancel the task; otherwise, false. /// </param> protected static void InlineIfPossibleOrElseQueue(Task task, bool needsProtection) { Debug.Assert(task != null); Debug.Assert(task.m_taskScheduler != null); // Set the TASK_STATE_STARTED flag. This only needs to be done // if the task may be canceled or if someone else has a reference to it // that may try to execute it. if (needsProtection) { if (!task.MarkStarted()) return; // task has been previously started or canceled. Stop processing. } else { task.m_stateFlags |= Task.TASK_STATE_STARTED; } // Try to inline it but queue if we can't try { if (!task.m_taskScheduler.TryRunInline(task, taskWasPreviouslyQueued: false)) { task.m_taskScheduler.InternalQueueTask(task); } } catch (Exception e) { // Either TryRunInline() or QueueTask() threw an exception. Record the exception, marking the task as Faulted. // However if it was a ThreadAbortException coming from TryRunInline we need to skip here, // because it would already have been handled in Task.Execute() TaskSchedulerException tse = new TaskSchedulerException(e); task.AddException(tse); task.Finish(false); // Don't re-throw. } } // // This helper routine is targeted by the debugger. // internal abstract Delegate[]? GetDelegateContinuationsForDebugger(); } /// <summary>Provides the standard implementation of a task continuation.</summary> internal class StandardTaskContinuation : TaskContinuation { /// <summary>The unstarted continuation task.</summary> internal readonly Task m_task; /// <summary>The options to use with the continuation task.</summary> internal readonly TaskContinuationOptions m_options; /// <summary>The task scheduler with which to run the continuation task.</summary> private readonly TaskScheduler m_taskScheduler; /// <summary>Initializes a new continuation.</summary> /// <param name="task">The task to be activated.</param> /// <param name="options">The continuation options.</param> /// <param name="scheduler">The scheduler to use for the continuation.</param> internal StandardTaskContinuation(Task task, TaskContinuationOptions options, TaskScheduler scheduler) { Debug.Assert(task != null, "TaskContinuation ctor: task is null"); Debug.Assert(scheduler != null, "TaskContinuation ctor: scheduler is null"); m_task = task; m_options = options; m_taskScheduler = scheduler; if (AsyncCausalityTracer.LoggingOn) AsyncCausalityTracer.TraceOperationCreation(m_task, "Task.ContinueWith: " + task.m_action!.Method.Name); if (Task.s_asyncDebuggingEnabled) Task.AddToActiveTasks(m_task); } /// <summary>Invokes the continuation for the target completion task.</summary> /// <param name="completedTask">The completed task.</param> /// <param name="canInlineContinuationTask">Whether the continuation can be inlined.</param> internal override void Run(Task completedTask, bool canInlineContinuationTask) { Debug.Assert(completedTask != null); Debug.Assert(completedTask.IsCompleted, "ContinuationTask.Run(): completedTask not completed"); // Check if the completion status of the task works with the desired // activation criteria of the TaskContinuationOptions. TaskContinuationOptions options = m_options; bool isRightKind = completedTask.IsCompletedSuccessfully ? (options & TaskContinuationOptions.NotOnRanToCompletion) == 0 : (completedTask.IsCanceled ? (options & TaskContinuationOptions.NotOnCanceled) == 0 : (options & TaskContinuationOptions.NotOnFaulted) == 0); // If the completion status is allowed, run the continuation. Task continuationTask = m_task; if (isRightKind) { // If the task was cancel before running (e.g a ContinueWhenAll with a cancelled caancelation token) // we will still flow it to ScheduleAndStart() were it will check the status before running // We check here to avoid faulty logs that contain a join event to an operation that was already set as completed. if (!continuationTask.IsCanceled && AsyncCausalityTracer.LoggingOn) { // Log now that we are sure that this continuation is being ran AsyncCausalityTracer.TraceOperationRelation(continuationTask, CausalityRelation.AssignDelegate); } continuationTask.m_taskScheduler = m_taskScheduler; // Either run directly or just queue it up for execution, depending // on whether synchronous or asynchronous execution is wanted. if (canInlineContinuationTask && // inlining is allowed by the caller (options & TaskContinuationOptions.ExecuteSynchronously) != 0) // synchronous execution was requested by the continuation's creator { InlineIfPossibleOrElseQueue(continuationTask, needsProtection: true); } else { try { continuationTask.ScheduleAndStart(needsProtection: true); } catch (TaskSchedulerException) { // No further action is necessary -- ScheduleAndStart() already transitioned the // task to faulted. But we want to make sure that no exception is thrown from here. } } } // Otherwise, the final state of this task does not match the desired // continuation activation criteria; cancel it to denote this. else continuationTask.InternalCancel(false); } internal override Delegate[]? GetDelegateContinuationsForDebugger() { if (m_task.m_action == null) { return m_task.GetDelegateContinuationsForDebugger(); } return new Delegate[] { m_task.m_action }; } } /// <summary>Task continuation for awaiting with a current synchronization context.</summary> internal sealed class SynchronizationContextAwaitTaskContinuation : AwaitTaskContinuation { /// <summary>SendOrPostCallback delegate to invoke the action.</summary> private static readonly SendOrPostCallback s_postCallback = state => { Debug.Assert(state is Action); ((Action)state)(); }; /// <summary>Cached delegate for PostAction</summary> private static ContextCallback? s_postActionCallback; /// <summary>The context with which to run the action.</summary> private readonly SynchronizationContext m_syncContext; /// <summary>Initializes the SynchronizationContextAwaitTaskContinuation.</summary> /// <param name="context">The synchronization context with which to invoke the action. Must not be null.</param> /// <param name="action">The action to invoke. Must not be null.</param> /// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param> internal SynchronizationContextAwaitTaskContinuation( SynchronizationContext context, Action action, bool flowExecutionContext) : base(action, flowExecutionContext) { Debug.Assert(context != null); m_syncContext = context; } /// <summary>Inlines or schedules the continuation.</summary> /// <param name="task">The antecedent task, which is ignored.</param> /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param> internal sealed override void Run(Task task, bool canInlineContinuationTask) { // If we're allowed to inline, run the action on this thread. if (canInlineContinuationTask && m_syncContext == SynchronizationContext.Current) { RunCallback(GetInvokeActionCallback(), m_action, ref Task.t_currentTask); } // Otherwise, Post the action back to the SynchronizationContext. else { TplEventSource log = TplEventSource.Log; if (log.IsEnabled()) { m_continuationId = Task.NewId(); log.AwaitTaskContinuationScheduled((task.ExecutingTaskScheduler ?? TaskScheduler.Default).Id, task.Id, m_continuationId); } RunCallback(GetPostActionCallback(), this, ref Task.t_currentTask); } // Any exceptions will be handled by RunCallback. } /// <summary>Calls InvokeOrPostAction(false) on the supplied SynchronizationContextAwaitTaskContinuation.</summary> /// <param name="state">The SynchronizationContextAwaitTaskContinuation.</param> private static void PostAction(object? state) { Debug.Assert(state is SynchronizationContextAwaitTaskContinuation); var c = (SynchronizationContextAwaitTaskContinuation)state; TplEventSource log = TplEventSource.Log; if (log.TasksSetActivityIds && c.m_continuationId != 0) { c.m_syncContext.Post(s_postCallback, GetActionLogDelegate(c.m_continuationId, c.m_action)); } else { c.m_syncContext.Post(s_postCallback, c.m_action); // s_postCallback is manually cached, as the compiler won't in a SecurityCritical method } } private static Action GetActionLogDelegate(int continuationId, Action action) { return () => { Guid savedActivityId; Guid activityId = TplEventSource.CreateGuidForTaskID(continuationId); System.Diagnostics.Tracing.EventSource.SetCurrentThreadActivityId(activityId, out savedActivityId); try { action(); } finally { System.Diagnostics.Tracing.EventSource.SetCurrentThreadActivityId(savedActivityId); } }; } /// <summary>Gets a cached delegate for the PostAction method.</summary> /// <returns> /// A delegate for PostAction, which expects a SynchronizationContextAwaitTaskContinuation /// to be passed as state. /// </returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] private static ContextCallback GetPostActionCallback() => s_postActionCallback ??= PostAction; } /// <summary>Task continuation for awaiting with a task scheduler.</summary> internal sealed class TaskSchedulerAwaitTaskContinuation : AwaitTaskContinuation { /// <summary>The scheduler on which to run the action.</summary> private readonly TaskScheduler m_scheduler; /// <summary>Initializes the TaskSchedulerAwaitTaskContinuation.</summary> /// <param name="scheduler">The task scheduler with which to invoke the action. Must not be null.</param> /// <param name="action">The action to invoke. Must not be null.</param> /// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param> internal TaskSchedulerAwaitTaskContinuation( TaskScheduler scheduler, Action action, bool flowExecutionContext) : base(action, flowExecutionContext) { Debug.Assert(scheduler != null); m_scheduler = scheduler; } /// <summary>Inlines or schedules the continuation.</summary> /// <param name="ignored">The antecedent task, which is ignored.</param> /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param> internal sealed override void Run(Task ignored, bool canInlineContinuationTask) { // If we're targeting the default scheduler, we can use the faster path provided by the base class. if (m_scheduler == TaskScheduler.Default) { base.Run(ignored, canInlineContinuationTask); } else { // We permit inlining if the caller allows us to, and // either we're on a thread pool thread (in which case we're fine running arbitrary code) // or we're already on the target scheduler (in which case we'll just ask the scheduler // whether it's ok to run here). We include the IsThreadPoolThread check here, whereas // we don't in AwaitTaskContinuation.Run, since here it expands what's allowed as opposed // to in AwaitTaskContinuation.Run where it restricts what's allowed. bool inlineIfPossible = canInlineContinuationTask && (TaskScheduler.InternalCurrent == m_scheduler || Thread.CurrentThread.IsThreadPoolThread); // Create the continuation task task. If we're allowed to inline, try to do so. // The target scheduler may still deny us from executing on this thread, in which case this'll be queued. Task task = CreateTask(state => { try { ((Action)state!)(); } catch (Exception exception) { Task.ThrowAsync(exception, targetContext: null); } }, m_action, m_scheduler); if (inlineIfPossible) { InlineIfPossibleOrElseQueue(task, needsProtection: false); } else { // We need to run asynchronously, so just schedule the task. try { task.ScheduleAndStart(needsProtection: false); } catch (TaskSchedulerException) { } // No further action is necessary, as ScheduleAndStart already transitioned task to faulted } } } } /// <summary>Base task continuation class used for await continuations.</summary> internal class AwaitTaskContinuation : TaskContinuation, IThreadPoolWorkItem { /// <summary>The ExecutionContext with which to run the continuation.</summary> private readonly ExecutionContext? m_capturedContext; /// <summary>The action to invoke.</summary> protected readonly Action m_action; protected int m_continuationId; /// <summary>Initializes the continuation.</summary> /// <param name="action">The action to invoke. Must not be null.</param> /// <param name="flowExecutionContext">Whether to capture and restore ExecutionContext.</param> internal AwaitTaskContinuation(Action action, bool flowExecutionContext) { Debug.Assert(action != null); m_action = action; if (flowExecutionContext) { m_capturedContext = ExecutionContext.Capture(); } } /// <summary>Creates a task to run the action with the specified state on the specified scheduler.</summary> /// <param name="action">The action to run. Must not be null.</param> /// <param name="state">The state to pass to the action. Must not be null.</param> /// <param name="scheduler">The scheduler to target.</param> /// <returns>The created task.</returns> protected Task CreateTask(Action<object?> action, object? state, TaskScheduler scheduler) { Debug.Assert(action != null); Debug.Assert(scheduler != null); return new Task( action, state, null, default, TaskCreationOptions.None, InternalTaskOptions.QueuedByRuntime, scheduler) { CapturedContext = m_capturedContext }; } /// <summary>Inlines or schedules the continuation onto the default scheduler.</summary> /// <param name="task">The antecedent task, which is ignored.</param> /// <param name="canInlineContinuationTask">true if inlining is permitted; otherwise, false.</param> internal override void Run(Task task, bool canInlineContinuationTask) { // For the base AwaitTaskContinuation, we allow inlining if our caller allows it // and if we're in a "valid location" for it. See the comments on // IsValidLocationForInlining for more about what's valid. For performance // reasons we would like to always inline, but we don't in some cases to avoid // running arbitrary amounts of work in suspected "bad locations", like UI threads. if (canInlineContinuationTask && IsValidLocationForInlining) { RunCallback(GetInvokeActionCallback(), m_action, ref Task.t_currentTask); // any exceptions from m_action will be handled by s_callbackRunAction } else { TplEventSource log = TplEventSource.Log; if (log.IsEnabled()) { m_continuationId = Task.NewId(); log.AwaitTaskContinuationScheduled((task.ExecutingTaskScheduler ?? TaskScheduler.Default).Id, task.Id, m_continuationId); } // We couldn't inline, so now we need to schedule it ThreadPool.UnsafeQueueUserWorkItemInternal(this, preferLocal: true); } } /// <summary> /// Gets whether the current thread is an appropriate location to inline a continuation's execution. /// </summary> /// <remarks> /// Returns whether SynchronizationContext is null and we're in the default scheduler. /// If the await had a SynchronizationContext/TaskScheduler where it began and the /// default/ConfigureAwait(true) was used, then we won't be on this path. If, however, /// ConfigureAwait(false) was used, or the SynchronizationContext and TaskScheduler were /// naturally null/Default, then we might end up here. If we do, we need to make sure /// that we don't execute continuations in a place that isn't set up to handle them, e.g. /// running arbitrary amounts of code on the UI thread. It would be "correct", but very /// expensive, to always run the continuations asynchronously, incurring lots of context /// switches and allocations and locks and the like. As such, we employ the heuristic /// that if the current thread has a non-null SynchronizationContext or a non-default /// scheduler, then we better not run arbitrary continuations here. /// </remarks> internal static bool IsValidLocationForInlining { get { // If there's a SynchronizationContext, we'll be conservative and say // this is a bad location to inline. SynchronizationContext? ctx = SynchronizationContext.Current; if (ctx != null && ctx.GetType() != typeof(SynchronizationContext)) return false; // Similarly, if there's a non-default TaskScheduler, we'll be conservative // and say this is a bad location to inline. TaskScheduler? sched = TaskScheduler.InternalCurrent; return sched == null || sched == TaskScheduler.Default; } } void IThreadPoolWorkItem.Execute() { TplEventSource log = TplEventSource.Log; ExecutionContext? context = m_capturedContext; if (!log.IsEnabled() && context == null) { m_action(); return; } Guid savedActivityId = default; if (log.TasksSetActivityIds && m_continuationId != 0) { Guid activityId = TplEventSource.CreateGuidForTaskID(m_continuationId); System.Diagnostics.Tracing.EventSource.SetCurrentThreadActivityId(activityId, out savedActivityId); } try { // We're not inside of a task, so t_currentTask doesn't need to be specially maintained. // We're on a thread pool thread with no higher-level callers, so exceptions can just propagate. ExecutionContext.CheckThreadPoolAndContextsAreDefault(); // If there's no execution context or Default, just invoke the delegate as ThreadPool is on Default context. // We don't have to use ExecutionContext.Run for the Default context here as there is no extra processing after the delegate if (context == null || context.IsDefault) { m_action(); } // If there is an execution context, get the cached delegate and run the action under the context. else { ExecutionContext.RunForThreadPoolUnsafe(context, s_invokeAction, m_action); } // ThreadPoolWorkQueue.Dispatch handles notifications and reset context back to default } finally { if (log.TasksSetActivityIds && m_continuationId != 0) { System.Diagnostics.Tracing.EventSource.SetCurrentThreadActivityId(savedActivityId); } } } /// <summary>Cached delegate that invokes an Action passed as an object parameter.</summary> private static readonly ContextCallback s_invokeContextCallback = (state) => { Debug.Assert(state is Action); ((Action)state)(); }; private static readonly Action<Action> s_invokeAction = (action) => action(); [MethodImpl(MethodImplOptions.AggressiveInlining)] protected static ContextCallback GetInvokeActionCallback() => s_invokeContextCallback; /// <summary>Runs the callback synchronously with the provided state.</summary> /// <param name="callback">The callback to run.</param> /// <param name="state">The state to pass to the callback.</param> /// <param name="currentTask">A reference to Task.t_currentTask.</param> protected void RunCallback(ContextCallback callback, object? state, ref Task? currentTask) { Debug.Assert(callback != null); Debug.Assert(currentTask == Task.t_currentTask); // Pretend there's no current task, so that no task is seen as a parent // and TaskScheduler.Current does not reflect false information Task? prevCurrentTask = currentTask; try { if (prevCurrentTask != null) currentTask = null; ExecutionContext? context = m_capturedContext; if (context == null) { // If there's no captured context, just run the callback directly. callback(state); } else { // Otherwise, use the captured context to do so. ExecutionContext.RunInternal(context, callback, state); } } catch (Exception exception) // we explicitly do not request handling of dangerous exceptions like AVs { Task.ThrowAsync(exception, targetContext: null); } finally { // Restore the current task information if (prevCurrentTask != null) currentTask = prevCurrentTask; } } /// <summary>Invokes or schedules the action to be executed.</summary> /// <param name="action">The action to invoke or queue.</param> /// <param name="allowInlining"> /// true to allow inlining, or false to force the action to run asynchronously. /// </param> /// <remarks> /// No ExecutionContext work is performed used. This method is only used in the /// case where a raw Action continuation delegate was stored into the Task, which /// only happens in Task.SetContinuationForAwait if execution context flow was disabled /// via using TaskAwaiter.UnsafeOnCompleted or a similar path. /// </remarks> internal static void RunOrScheduleAction(Action action, bool allowInlining) { ref Task? currentTask = ref Task.t_currentTask; Task? prevCurrentTask = currentTask; // If we're not allowed to run here, schedule the action if (!allowInlining || !IsValidLocationForInlining) { UnsafeScheduleAction(action, prevCurrentTask); return; } // Otherwise, run it, making sure that t_currentTask is null'd out appropriately during the execution try { if (prevCurrentTask != null) currentTask = null; action(); } catch (Exception exception) { Task.ThrowAsync(exception, targetContext: null); } finally { if (prevCurrentTask != null) currentTask = prevCurrentTask; } } /// <summary>Invokes or schedules the action to be executed.</summary> /// <param name="box">The <see cref="IAsyncStateMachineBox"/> that needs to be invoked or queued.</param> /// <param name="allowInlining"> /// true to allow inlining, or false to force the box's action to run asynchronously. /// </param> internal static void RunOrScheduleAction(IAsyncStateMachineBox box, bool allowInlining) { // Same logic as in the RunOrScheduleAction(Action, ...) overload, except invoking // box.Invoke instead of action(). ref Task? currentTask = ref Task.t_currentTask; Task? prevCurrentTask = currentTask; // If we're not allowed to run here, schedule the action if (!allowInlining || !IsValidLocationForInlining) { // If logging is disabled, we can simply queue the box itself as a custom work // item, and its work item execution will just invoke its MoveNext. However, if // logging is enabled, there is pre/post-work we need to do around logging to // match what's done for other continuations, and that requires flowing additional // information into the continuation, which we don't want to burden other cases of the // box with... so, in that case we just delegate to the AwaitTaskContinuation-based // path that already handles this, albeit at the expense of allocating the ATC // object, and potentially forcing the box's delegate into existence, when logging // is enabled. if (TplEventSource.Log.IsEnabled()) { UnsafeScheduleAction(box.MoveNextAction, prevCurrentTask); } else { ThreadPool.UnsafeQueueUserWorkItemInternal(box, preferLocal: true); } return; } // Otherwise, run it, making sure that t_currentTask is null'd out appropriately during the execution try { if (prevCurrentTask != null) currentTask = null; box.MoveNext(); } catch (Exception exception) { Task.ThrowAsync(exception, targetContext: null); } finally { if (prevCurrentTask != null) currentTask = prevCurrentTask; } } /// <summary>Schedules the action to be executed. No ExecutionContext work is performed used.</summary> /// <param name="action">The action to invoke or queue.</param> /// <param name="task">The task scheduling the action.</param> internal static void UnsafeScheduleAction(Action action, Task? task) { AwaitTaskContinuation atc = new AwaitTaskContinuation(action, flowExecutionContext: false); TplEventSource log = TplEventSource.Log; if (log.IsEnabled() && task != null) { atc.m_continuationId = Task.NewId(); log.AwaitTaskContinuationScheduled((task.ExecutingTaskScheduler ?? TaskScheduler.Default).Id, task.Id, atc.m_continuationId); } ThreadPool.UnsafeQueueUserWorkItemInternal(atc, preferLocal: true); } internal override Delegate[] GetDelegateContinuationsForDebugger() { Debug.Assert(m_action != null); return new Delegate[] { AsyncMethodBuilderCore.TryGetStateMachineForDebugger(m_action) }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading.Tasks; using Xunit; namespace System.Linq.Tests { public class SelectTests : EnumerableTests { [Fact] public void SameResultsRepeatCallsStringQuery() { var q1 = from x1 in new string[] { "Alen", "Felix", null, null, "X", "Have Space", "Clinton", "" } select x1; ; var q2 = from x2 in new int[] { 55, 49, 9, -100, 24, 25, -1, 0 } select x2; var q = from x3 in q1 from x4 in q2 select new { a1 = x3, a2 = x4 }; Assert.Equal(q.Select(e => e.a1), q.Select(e => e.a1)); } [Fact] public void SingleElement() { var source = new[] { new { name = "Prakash", custID = 98088 } }; string[] expected = { "Prakash" }; Assert.Equal(expected, source.Select(e => e.name)); } [Fact] public void SelectProperty() { var source = new[]{ new { name="Prakash", custID=98088 }, new { name="Bob", custID=29099 }, new { name="Chris", custID=39033 }, new { name=(string)null, custID=30349 }, new { name="Prakash", custID=39030 } }; string[] expected = { "Prakash", "Bob", "Chris", null, "Prakash" }; Assert.Equal(expected, source.Select(e => e.name)); } [Fact] public void EmptyWithIndexedSelector() { Assert.Equal(Enumerable.Empty<int>(), Enumerable.Empty<string>().Select((s, i) => s.Length + i)); } [Fact] public void EnumerateFromDifferentThread() { var selected = Enumerable.Range(0, 100).Where(i => i > 3).Select(i => i.ToString()); Task[] tasks = new Task[4]; for (int i = 0; i != 4; ++i) tasks[i] = Task.Run(() => selected.ToList()); Task.WaitAll(tasks); } [Fact] public void SingleElementIndexedSelector() { var source = new[] { new { name = "Prakash", custID = 98088 } }; string[] expected = { "Prakash" }; Assert.Equal(expected, source.Select((e, index) => e.name)); } [Fact] public void SelectPropertyPassingIndex() { var source = new[]{ new { name="Prakash", custID=98088 }, new { name="Bob", custID=29099 }, new { name="Chris", custID=39033 }, new { name=(string)null, custID=30349 }, new { name="Prakash", custID=39030 } }; string[] expected = { "Prakash", "Bob", "Chris", null, "Prakash" }; Assert.Equal(expected, source.Select((e, i) => e.name)); } [Fact] public void SelectPropertyUsingIndex() { var source = new[]{ new { name="Prakash", custID=98088 }, new { name="Bob", custID=29099 }, new { name="Chris", custID=39033 } }; string[] expected = { "Prakash", null, null }; Assert.Equal(expected, source.Select((e, i) => i == 0 ? e.name : null)); } [Fact] public void SelectPropertyPassingIndexOnLast() { var source = new[]{ new { name="Prakash", custID=98088}, new { name="Bob", custID=29099 }, new { name="Chris", custID=39033 }, new { name="Robert", custID=39033 }, new { name="Allen", custID=39033 }, new { name="Chuck", custID=39033 } }; string[] expected = { null, null, null, null, null, "Chuck" }; Assert.Equal(expected, source.Select((e, i) => i == 5 ? e.name : null)); } [Fact] [OuterLoop] public void Overflow() { var selected = new FastInfiniteEnumerator<int>().Select((e, i) => e); using (var en = selected.GetEnumerator()) Assert.Throws<OverflowException>(() => { while (en.MoveNext()) { } }); } [Fact] public void Select_SourceIsNull_ArgumentNullExceptionThrown() { IEnumerable<int> source = null; Func<int, int> selector = i => i + 1; Assert.Throws<ArgumentNullException>("source", () => source.Select(selector)); } [Fact] public void Select_SelectorIsNull_ArgumentNullExceptionThrown_Indexed() { IEnumerable<int> source = Enumerable.Range(1, 10); Func<int, int, int> selector = null; Assert.Throws<ArgumentNullException>("selector", () => source.Select(selector)); } [Fact] public void Select_SourceIsNull_ArgumentNullExceptionThrown_Indexed() { IEnumerable<int> source = null; Func<int, int, int> selector = (e, i) => i + 1; Assert.Throws<ArgumentNullException>("source", () => source.Select(selector)); } [Fact] public void Select_SelectorIsNull_ArgumentNullExceptionThrown() { IEnumerable<int> source = Enumerable.Range(1, 10); Func<int, int> selector = null; Assert.Throws<ArgumentNullException>("selector", () => source.Select(selector)); } [Fact] public void Select_SourceIsAnArray_ExecutionIsDeferred() { bool funcCalled = false; Func<int>[] source = new Func<int>[] { () => { funcCalled = true; return 1; } }; IEnumerable<int> query = source.Select(d => d()); Assert.False(funcCalled); } [Fact] public void Select_SourceIsAList_ExecutionIsDeferred() { bool funcCalled = false; List<Func<int>> source = new List<Func<int>>() { () => { funcCalled = true; return 1; } }; IEnumerable<int> query = source.Select(d => d()); Assert.False(funcCalled); } [Fact] public void Select_SourceIsIReadOnlyCollection_ExecutionIsDeferred() { bool funcCalled = false; IReadOnlyCollection<Func<int>> source = new ReadOnlyCollection<Func<int>>(new List<Func<int>>() { () => { funcCalled = true; return 1; } }); IEnumerable<int> query = source.Select(d => d()); Assert.False(funcCalled); } [Fact] public void Select_SourceIsICollection_ExecutionIsDeferred() { bool funcCalled = false; ICollection<Func<int>> source = new LinkedList<Func<int>>(new List<Func<int>>() { () => { funcCalled = true; return 1; } }); IEnumerable<int> query = source.Select(d => d()); Assert.False(funcCalled); } [Fact] public void Select_SourceIsIEnumerable_ExecutionIsDeferred() { bool funcCalled = false; IEnumerable<Func<int>> source = Enumerable.Repeat((Func<int>)(() => { funcCalled = true; return 1; }), 1); IEnumerable<int> query = source.Select(d => d()); Assert.False(funcCalled); } [Fact] public void SelectSelect_SourceIsAnArray_ExecutionIsDefered() { bool funcCalled = false; Func<int>[] source = new Func<int>[] { () => { funcCalled = true; return 1; } }; IEnumerable<int> query = source.Select(d => d).Select(d => d()); Assert.False(funcCalled); } [Fact] public void SelectSelect_SourceIsAList_ExecutionIsDefered() { bool funcCalled = false; List<Func<int>> source = new List<Func<int>>() { () => { funcCalled = true; return 1; } }; IEnumerable<int> query = source.Select(d => d).Select(d => d()); Assert.False(funcCalled); } [Fact] public void SelectSelect_SourceIsIReadOnlyCollection_ExecutionIsDeferred() { bool funcCalled = false; IReadOnlyCollection<Func<int>> source = new ReadOnlyCollection<Func<int>>(new List<Func<int>>() { () => { funcCalled = true; return 1; } }); IEnumerable<int> query = source.Select(d => d).Select(d => d()); Assert.False(funcCalled); } [Fact] public void SelectSelect_SourceIsICollection_ExecutionIsDeferred() { bool funcCalled = false; ICollection<Func<int>> source = new LinkedList<Func<int>>(new List<Func<int>>() { () => { funcCalled = true; return 1; } }); IEnumerable<int> query = source.Select(d => d).Select(d => d()); Assert.False(funcCalled); } [Fact] public void SelectSelect_SourceIsIEnumerable_ExecutionIsDefered() { bool funcCalled = false; IEnumerable<Func<int>> source = Enumerable.Repeat((Func<int>)(() => { funcCalled = true; return 1; }), 1); IEnumerable<int> query = source.Select(d => d).Select(d => d()); Assert.False(funcCalled); } [Fact] public void Select_SourceIsAnArray_ReturnsExpectedValues() { int[] source = new[] { 1, 2, 3, 4, 5 }; Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); int index = 0; foreach (var item in query) { var expected = selector(source[index]); Assert.Equal(expected, item); index++; } Assert.Equal(source.Length, index); } [Fact] public void Select_SourceIsAList_ReturnsExpectedValues() { List<int> source = new List<int> { 1, 2, 3, 4, 5 }; Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); int index = 0; foreach (var item in query) { var expected = selector(source[index]); Assert.Equal(expected, item); index++; } Assert.Equal(source.Count, index); } [Fact] public void Select_SourceIsIReadOnlyCollection_ReturnsExpectedValues() { IReadOnlyCollection<int> source = new ReadOnlyCollection<int>(new List<int> { 1, 2, 3, 4, 5 }); Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); int index = 0; foreach (var item in query) { index++; var expected = selector(index); Assert.Equal(expected, item); } Assert.Equal(source.Count, index); } [Fact] public void Select_SourceIsICollection_ReturnsExpectedValues() { ICollection<int> source = new LinkedList<int>(new List<int> { 1, 2, 3, 4, 5 }); Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); int index = 0; foreach (var item in query) { index++; var expected = selector(index); Assert.Equal(expected, item); } Assert.Equal(source.Count, index); } [Fact] public void Select_SourceIsIEnumerable_ReturnsExpectedValues() { int nbOfItems = 5; IEnumerable<int> source = Enumerable.Range(1, nbOfItems); Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); int index = 0; foreach (var item in query) { index++; var expected = selector(index); Assert.Equal(expected, item); } Assert.Equal(nbOfItems, index); } [Fact] public void Select_SourceIsAnArray_CurrentIsDefaultOfTAfterEnumeration() { int[] source = new[] { 1 }; Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); var enumerator = query.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.Equal(default(int), enumerator.Current); } [Fact] public void Select_SourceIsAList_CurrentIsDefaultOfTAfterEnumeration() { List<int> source = new List<int>() { 1 }; Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); var enumerator = query.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.Equal(default(int), enumerator.Current); } [Fact] public void Select_SourceIsIReadOnlyCollection_CurrentIsDefaultOfTAfterEnumeration() { IReadOnlyCollection<int> source = new ReadOnlyCollection<int>(new List<int>() { 1 }); Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); var enumerator = query.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.Equal(default(int), enumerator.Current); } [Fact] public void Select_SourceIsICollection_CurrentIsDefaultOfTAfterEnumeration() { ICollection<int> source = new LinkedList<int>(new List<int>() { 1 }); Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); var enumerator = query.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.Equal(default(int), enumerator.Current); } [Fact] public void Select_SourceIsIEnumerable_CurrentIsDefaultOfTAfterEnumeration() { IEnumerable<int> source = Enumerable.Repeat(1, 1); Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector); var enumerator = query.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.Equal(default(int), enumerator.Current); } [Fact] public void SelectSelect_SourceIsAnArray_ReturnsExpectedValues() { Func<int, int> selector = i => i + 1; int[] source = new[] { 1, 2, 3, 4, 5 }; IEnumerable<int> query = source.Select(selector).Select(selector); int index = 0; foreach (var item in query) { var expected = selector(selector(source[index])); Assert.Equal(expected, item); index++; } Assert.Equal(source.Length, index); } [Fact] public void SelectSelect_SourceIsAList_ReturnsExpectedValues() { List<int> source = new List<int> { 1, 2, 3, 4, 5 }; Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector).Select(selector); int index = 0; foreach (var item in query) { var expected = selector(selector(source[index])); Assert.Equal(expected, item); index++; } Assert.Equal(source.Count, index); } [Fact] public void SelectSelect_SourceIsIReadOnlyCollection_ReturnsExpectedValues() { IReadOnlyCollection<int> source = new ReadOnlyCollection<int>(new List<int> { 1, 2, 3, 4, 5 }); Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector).Select(selector); int index = 0; foreach (var item in query) { index++; var expected = selector(selector(index)); Assert.Equal(expected, item); } Assert.Equal(source.Count, index); } [Fact] public void SelectSelect_SourceIsICollection_ReturnsExpectedValues() { ICollection<int> source = new LinkedList<int>(new List<int> { 1, 2, 3, 4, 5 }); Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector).Select(selector); int index = 0; foreach (var item in query) { index++; var expected = selector(selector(index)); Assert.Equal(expected, item); } Assert.Equal(source.Count, index); } [Fact] public void SelectSelect_SourceIsIEnumerable_ReturnsExpectedValues() { int nbOfItems = 5; IEnumerable<int> source = Enumerable.Range(1, 5); Func<int, int> selector = i => i + 1; IEnumerable<int> query = source.Select(selector).Select(selector); int index = 0; foreach (var item in query) { index++; var expected = selector(selector(index)); Assert.Equal(expected, item); } Assert.Equal(nbOfItems, index); } [Fact] public void Select_SourceIsEmptyEnumerable_ReturnedCollectionHasNoElements() { IEnumerable<int> source = Enumerable.Empty<int>(); bool wasSelectorCalled = false; IEnumerable<int> result = source.Select(i => { wasSelectorCalled = true; return i + 1; }); bool hadItems = false; foreach (var item in result) { hadItems = true; } Assert.False(hadItems); Assert.False(wasSelectorCalled); } [Fact] public void Select_ExceptionThrownFromSelector_ExceptionPropagatedToTheCaller() { int[] source = new[] { 1, 2, 3, 4, 5 }; Func<int, int> selector = i => { throw new InvalidOperationException(); }; var result = source.Select(selector); var enumerator = result.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); } [Fact] public void Select_ExceptionThrownFromSelector_IteratorCanBeUsedAfterExceptionIsCaught() { int[] source = new[] { 1, 2, 3, 4, 5 }; Func<int, int> selector = i => { if (i == 1) throw new InvalidOperationException(); return i + 1; }; var result = source.Select(selector); var enumerator = result.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); enumerator.MoveNext(); Assert.Equal(3 /* 2 + 1 */, enumerator.Current); } [Fact] public void Select_ExceptionThrownFromCurrentOfSourceIterator_ExceptionPropagatedToTheCaller() { IEnumerable<int> source = new ThrowsOnCurrent(); Func<int, int> selector = i => i + 1; var result = source.Select(selector); var enumerator = result.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); } [Fact] public void Select_ExceptionThrownFromCurrentOfSourceIterator_IteratorCanBeUsedAfterExceptionIsCaught() { IEnumerable<int> source = new ThrowsOnCurrent(); Func<int, int> selector = i => i + 1; var result = source.Select(selector); var enumerator = result.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); enumerator.MoveNext(); Assert.Equal(3 /* 2 + 1 */, enumerator.Current); } /// <summary> /// Test enumerator - throws InvalidOperationException from Current after MoveNext called once. /// </summary> private class ThrowsOnCurrent : TestEnumerator { public override int Current { get { var current = base.Current; if (current == 1) throw new InvalidOperationException(); return current; } } } [Fact] public void Select_ExceptionThrownFromMoveNextOfSourceIterator_ExceptionPropagatedToTheCaller() { IEnumerable<int> source = new ThrowsOnMoveNext(); Func<int, int> selector = i => i + 1; var result = source.Select(selector); var enumerator = result.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); } [Fact] public void Select_ExceptionThrownFromMoveNextOfSourceIterator_IteratorCanBeUsedAfterExceptionIsCaught() { IEnumerable<int> source = new ThrowsOnMoveNext(); Func<int, int> selector = i => i + 1; var result = source.Select(selector); var enumerator = result.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); enumerator.MoveNext(); Assert.Equal(3 /* 2 + 1 */, enumerator.Current); } [Fact] public void Select_ExceptionThrownFromGetEnumeratorOnSource_ExceptionPropagatedToTheCaller() { IEnumerable<int> source = new ThrowsOnGetEnumerator(); Func<int, int> selector = i => i + 1; var result = source.Select(selector); var enumerator = result.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); } [Fact] public void Select_ExceptionThrownFromGetEnumeratorOnSource_CurrentIsSetToDefaultOfItemTypeAndIteratorCanBeUsedAfterExceptionIsCaught() { IEnumerable<int> source = new ThrowsOnGetEnumerator(); Func<int, string> selector = i => i.ToString(); var result = source.Select(selector); var enumerator = result.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); string currentValue = enumerator.Current; Assert.Equal(default(string), currentValue); Assert.True(enumerator.MoveNext()); Assert.Equal("1", enumerator.Current); } [Fact] public void Select_SourceListGetsModifiedDuringIteration_ExceptionIsPropagated() { List<int> source = new List<int>() { 1, 2, 3, 4, 5 }; Func<int, int> selector = i => i + 1; var result = source.Select(selector); var enumerator = result.GetEnumerator(); Assert.True(enumerator.MoveNext()); Assert.Equal(2 /* 1 + 1 */, enumerator.Current); source.Add(6); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); } [Fact] public void Select_GetEnumeratorCalledTwice_DifferentInstancesReturned() { int[] source = new[] { 1, 2, 3, 4, 5 }; var query = source.Select(i => i + 1); var enumerator1 = query.GetEnumerator(); var enumerator2 = query.GetEnumerator(); Assert.Same(query, enumerator1); Assert.NotSame(enumerator1, enumerator2); enumerator1.Dispose(); enumerator2.Dispose(); } [Fact] public void Select_ResetCalledOnEnumerator_ExceptionThrown() { int[] source = new[] { 1, 2, 3, 4, 5 }; Func<int, int> selector = i => i + 1; var result = source.Select(selector); var enumerator = result.GetEnumerator(); Assert.Throws<NotSupportedException>(() => enumerator.Reset()); } [Fact] public void ForcedToEnumeratorDoesntEnumerate() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Select(i => i); // Don't insist on this behaviour, but check its correct if it happens var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void ForcedToEnumeratorDoesntEnumerateIndexed() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).Select((e, i) => i); // Don't insist on this behaviour, but check its correct if it happens var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void ForcedToEnumeratorDoesntEnumerateArray() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).ToArray().Select(i => i); var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void ForcedToEnumeratorDoesntEnumerateList() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).ToList().Select(i => i); var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void ForcedToEnumeratorDoesntEnumerateIList() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).ToList().AsReadOnly().Select(i => i); var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void ForcedToEnumeratorDoesntEnumerateIPartition() { var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).ToList().AsReadOnly().Select(i => i).Skip(1); var en = iterator as IEnumerator<int>; Assert.False(en != null && en.MoveNext()); } [Fact] public void Select_SourceIsArray_Count() { var source = new[] { 1, 2, 3, 4 }; Assert.Equal(source.Length, source.Select(i => i * 2).Count()); } [Fact] public void Select_SourceIsAList_Count() { var source = new List<int> { 1, 2, 3, 4 }; Assert.Equal(source.Count, source.Select(i => i * 2).Count()); } [Fact] public void Select_SourceIsAnIList_Count() { var souce = new List<int> { 1, 2, 3, 4 }.AsReadOnly(); Assert.Equal(souce.Count, souce.Select(i => i * 2).Count()); } [Fact] public void Select_SourceIsArray_Skip() { var source = new[] { 1, 2, 3, 4 }.Select(i => i * 2); Assert.Equal(new[] { 6, 8 }, source.Skip(2)); Assert.Equal(new[] { 6, 8 }, source.Skip(2).Skip(-1)); Assert.Equal(new[] { 6, 8 }, source.Skip(1).Skip(1)); Assert.Equal(new[] { 2, 4, 6, 8 }, source.Skip(-1)); Assert.Empty(source.Skip(4)); Assert.Empty(source.Skip(20)); } [Fact] public void Select_SourceIsList_Skip() { var source = new List<int> { 1, 2, 3, 4 }.Select(i => i * 2); Assert.Equal(new[] { 6, 8 }, source.Skip(2)); Assert.Equal(new[] { 6, 8 }, source.Skip(2).Skip(-1)); Assert.Equal(new[] { 6, 8 }, source.Skip(1).Skip(1)); Assert.Equal(new[] { 2, 4, 6, 8 }, source.Skip(-1)); Assert.Empty(source.Skip(4)); Assert.Empty(source.Skip(20)); } [Fact] public void Select_SourceIsIList_Skip() { var source = new List<int> { 1, 2, 3, 4 }.AsReadOnly().Select(i => i * 2); Assert.Equal(new[] { 6, 8 }, source.Skip(2)); Assert.Equal(new[] { 6, 8 }, source.Skip(2).Skip(-1)); Assert.Equal(new[] { 6, 8 }, source.Skip(1).Skip(1)); Assert.Equal(new[] { 2, 4, 6, 8 }, source.Skip(-1)); Assert.Empty(source.Skip(4)); Assert.Empty(source.Skip(20)); } [Fact] public void Select_SourceIsArray_Take() { var source = new[] { 1, 2, 3, 4 }.Select(i => i * 2); Assert.Equal(new[] { 2, 4 }, source.Take(2)); Assert.Equal(new[] { 2, 4 }, source.Take(3).Take(2)); Assert.Empty(source.Take(-1)); Assert.Equal(new[] { 2, 4, 6, 8 }, source.Take(4)); Assert.Equal(new[] { 2, 4, 6, 8 }, source.Take(40)); } [Fact] public void Select_SourceIsList_Take() { var source = new List<int> { 1, 2, 3, 4 }.Select(i => i * 2); Assert.Equal(new[] { 2, 4 }, source.Take(2)); Assert.Equal(new[] { 2, 4 }, source.Take(3).Take(2)); Assert.Empty(source.Take(-1)); Assert.Equal(new[] { 2, 4, 6, 8 }, source.Take(4)); Assert.Equal(new[] { 2, 4, 6, 8 }, source.Take(40)); } [Fact] public void Select_SourceIsIList_Take() { var source = new List<int> { 1, 2, 3, 4 }.AsReadOnly().Select(i => i * 2); Assert.Equal(new[] { 2, 4 }, source.Take(2)); Assert.Equal(new[] { 2, 4 }, source.Take(3).Take(2)); Assert.Empty(source.Take(-1)); Assert.Equal(new[] { 2, 4, 6, 8 }, source.Take(4)); Assert.Equal(new[] { 2, 4, 6, 8 }, source.Take(40)); } [Fact] public void Select_SourceIsArray_ElementAt() { var source = new[] { 1, 2, 3, 4 }.Select(i => i * 2); for (int i = 0; i != 4; ++i) Assert.Equal(i * 2 + 2, source.ElementAt(i)); Assert.Throws<ArgumentOutOfRangeException>("index", () => source.ElementAt(-1)); Assert.Throws<ArgumentOutOfRangeException>("index", () => source.ElementAt(4)); Assert.Throws<ArgumentOutOfRangeException>("index", () => source.ElementAt(40)); Assert.Equal(6, source.Skip(1).ElementAt(1)); Assert.Throws<ArgumentOutOfRangeException>("index", () => source.Skip(2).ElementAt(9)); } [Fact] public void Select_SourceIsList_ElementAt() { var source = new List<int> { 1, 2, 3, 4 }.Select(i => i * 2); for (int i = 0; i != 4; ++i) Assert.Equal(i * 2 + 2, source.ElementAt(i)); Assert.Throws<ArgumentOutOfRangeException>("index", () => source.ElementAt(-1)); Assert.Throws<ArgumentOutOfRangeException>("index", () => source.ElementAt(4)); Assert.Throws<ArgumentOutOfRangeException>("index", () => source.ElementAt(40)); Assert.Equal(6, source.Skip(1).ElementAt(1)); Assert.Throws<ArgumentOutOfRangeException>("index", () => source.Skip(2).ElementAt(9)); } [Fact] public void Select_SourceIsIList_ElementAt() { var source = new List<int> { 1, 2, 3, 4 }.AsReadOnly().Select(i => i * 2); for (int i = 0; i != 4; ++i) Assert.Equal(i * 2 + 2, source.ElementAt(i)); Assert.Throws<ArgumentOutOfRangeException>("index", () => source.ElementAt(-1)); Assert.Throws<ArgumentOutOfRangeException>("index", () => source.ElementAt(4)); Assert.Throws<ArgumentOutOfRangeException>("index", () => source.ElementAt(40)); Assert.Equal(6, source.Skip(1).ElementAt(1)); Assert.Throws<ArgumentOutOfRangeException>("index", () => source.Skip(2).ElementAt(9)); } [Fact] public void Select_SourceIsArray_ElementAtOrDefault() { var source = new[] { 1, 2, 3, 4 }.Select(i => i * 2); for (int i = 0; i != 4; ++i) Assert.Equal(i * 2 + 2, source.ElementAtOrDefault(i)); Assert.Equal(0, source.ElementAtOrDefault(-1)); Assert.Equal(0, source.ElementAtOrDefault(4)); Assert.Equal(0, source.ElementAtOrDefault(40)); Assert.Equal(6, source.Skip(1).ElementAtOrDefault(1)); Assert.Equal(0, source.Skip(2).ElementAtOrDefault(9)); } [Fact] public void Select_SourceIsList_ElementAtOrDefault() { var source = new List<int> { 1, 2, 3, 4 }.Select(i => i * 2); for (int i = 0; i != 4; ++i) Assert.Equal(i * 2 + 2, source.ElementAtOrDefault(i)); Assert.Equal(0, source.ElementAtOrDefault(-1)); Assert.Equal(0, source.ElementAtOrDefault(4)); Assert.Equal(0, source.ElementAtOrDefault(40)); Assert.Equal(6, source.Skip(1).ElementAtOrDefault(1)); Assert.Equal(0, source.Skip(2).ElementAtOrDefault(9)); } [Fact] public void Select_SourceIsIList_ElementAtOrDefault() { var source = new List<int> { 1, 2, 3, 4 }.AsReadOnly().Select(i => i * 2); for (int i = 0; i != 4; ++i) Assert.Equal(i * 2 + 2, source.ElementAtOrDefault(i)); Assert.Equal(0, source.ElementAtOrDefault(-1)); Assert.Equal(0, source.ElementAtOrDefault(4)); Assert.Equal(0, source.ElementAtOrDefault(40)); Assert.Equal(6, source.Skip(1).ElementAtOrDefault(1)); Assert.Equal(0, source.Skip(2).ElementAtOrDefault(9)); } [Fact] public void Select_SourceIsArray_First() { var source = new[] { 1, 2, 3, 4 }.Select(i => i * 2); Assert.Equal(2, source.First()); Assert.Equal(2, source.FirstOrDefault()); Assert.Equal(6, source.Skip(2).First()); Assert.Equal(6, source.Skip(2).FirstOrDefault()); Assert.Throws<InvalidOperationException>(() => source.Skip(4).First()); Assert.Throws<InvalidOperationException>(() => source.Skip(14).First()); Assert.Equal(0, source.Skip(4).FirstOrDefault()); Assert.Equal(0, source.Skip(14).FirstOrDefault()); var empty = new int[0].Select(i => i * 2); Assert.Throws<InvalidOperationException>(() => empty.First()); Assert.Equal(0, empty.FirstOrDefault()); } [Fact] public void Select_SourceIsList_First() { var source = new List<int> { 1, 2, 3, 4 }.Select(i => i * 2); Assert.Equal(2, source.First()); Assert.Equal(2, source.FirstOrDefault()); Assert.Equal(6, source.Skip(2).First()); Assert.Equal(6, source.Skip(2).FirstOrDefault()); Assert.Throws<InvalidOperationException>(() => source.Skip(4).First()); Assert.Throws<InvalidOperationException>(() => source.Skip(14).First()); Assert.Equal(0, source.Skip(4).FirstOrDefault()); Assert.Equal(0, source.Skip(14).FirstOrDefault()); var empty = new List<int>().Select(i => i * 2); Assert.Throws<InvalidOperationException>(() => empty.First()); Assert.Equal(0, empty.FirstOrDefault()); } [Fact] public void Select_SourceIsIList_First() { var source = new List<int> { 1, 2, 3, 4 }.AsReadOnly().Select(i => i * 2); Assert.Equal(2, source.First()); Assert.Equal(2, source.FirstOrDefault()); Assert.Equal(6, source.Skip(2).First()); Assert.Equal(6, source.Skip(2).FirstOrDefault()); Assert.Throws<InvalidOperationException>(() => source.Skip(4).First()); Assert.Throws<InvalidOperationException>(() => source.Skip(14).First()); Assert.Equal(0, source.Skip(4).FirstOrDefault()); Assert.Equal(0, source.Skip(14).FirstOrDefault()); var empty = new List<int>().AsReadOnly().Select(i => i * 2); Assert.Throws<InvalidOperationException>(() => empty.First()); Assert.Equal(0, empty.FirstOrDefault()); } [Fact] public void Select_SourceIsArray_Last() { var source = new[] { 1, 2, 3, 4 }.Select(i => i * 2); Assert.Equal(8, source.Last()); Assert.Equal(8, source.LastOrDefault()); Assert.Equal(6, source.Take(3).Last()); Assert.Equal(6, source.Take(3).LastOrDefault()); var empty = new int[0].Select(i => i * 2); Assert.Throws<InvalidOperationException>(() => empty.Last()); Assert.Equal(0, empty.LastOrDefault()); Assert.Throws<InvalidOperationException>(() => empty.Skip(1).Last()); Assert.Equal(0, empty.Skip(1).LastOrDefault()); } [Fact] public void Select_SourceIsList_Last() { var source = new List<int> { 1, 2, 3, 4 }.Select(i => i * 2); Assert.Equal(8, source.Last()); Assert.Equal(8, source.LastOrDefault()); Assert.Equal(6, source.Take(3).Last()); Assert.Equal(6, source.Take(3).LastOrDefault()); var empty = new List<int>().Select(i => i * 2); Assert.Throws<InvalidOperationException>(() => empty.Last()); Assert.Equal(0, empty.LastOrDefault()); Assert.Throws<InvalidOperationException>(() => empty.Skip(1).Last()); Assert.Equal(0, empty.Skip(1).LastOrDefault()); } [Fact] public void Select_SourceIsIList_Last() { var source = new List<int> { 1, 2, 3, 4 }.AsReadOnly().Select(i => i * 2); Assert.Equal(8, source.Last()); Assert.Equal(8, source.LastOrDefault()); Assert.Equal(6, source.Take(3).Last()); Assert.Equal(6, source.Take(3).LastOrDefault()); var empty = new List<int>().AsReadOnly().Select(i => i * 2); Assert.Throws<InvalidOperationException>(() => empty.Last()); Assert.Equal(0, empty.LastOrDefault()); Assert.Throws<InvalidOperationException>(() => empty.Skip(1).Last()); Assert.Equal(0, empty.Skip(1).LastOrDefault()); } [Fact] public void Select_SourceIsArray_SkipRepeatCalls() { var source = new[] { 1, 2, 3, 4 }.Select(i => i * 2).Skip(1); Assert.Equal(source, source); } [Fact] public void Select_SourceIsArraySkipSelect() { var source = new[] { 1, 2, 3, 4 }.Select(i => i * 2).Skip(1).Select(i => i + 1); Assert.Equal(new[] { 5, 7, 9 }, source); } [Fact] public void Select_SourceIsArrayTakeTake() { var source = new[] { 1, 2, 3, 4 }.Select(i => i * 2).Take(2).Take(1); Assert.Equal(new[] { 2 }, source); Assert.Equal(new[] { 2 }, source.Take(10)); } [Fact] public void Select_SourceIsListSkipTakeCount() { Assert.Equal(3, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Take(3).Count()); Assert.Equal(4, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Take(9).Count()); Assert.Equal(2, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Skip(2).Count()); Assert.Equal(0, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Skip(8).Count()); } [Fact] public void Select_SourceIsListSkipTakeToArray() { Assert.Equal(new[] { 2, 4, 6 }, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Take(3).ToArray()); Assert.Equal(new[] { 2, 4, 6, 8 }, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Take(9).ToArray()); Assert.Equal(new[] { 6, 8 }, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Skip(2).ToArray()); Assert.Empty(new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Skip(8).ToArray()); } [Fact] public void Select_SourceIsListSkipTakeToList() { Assert.Equal(new[] { 2, 4, 6 }, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Take(3).ToList()); Assert.Equal(new[] { 2, 4, 6, 8 }, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Take(9).ToList()); Assert.Equal(new[] { 6, 8 }, new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Skip(2).ToList()); Assert.Empty(new List<int> { 1, 2, 3, 4 }.Select(i => i * 2).Skip(8).ToList()); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Compute.Tests { using System; using System.Collections.Generic; using System.Linq; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Xunit; public class VMScaleSetPriorityTests : VMScaleSetTestsBase { #region Priority Tests /// <summary> /// Covers following Operations: /// Create RG /// Create Storage Account /// Create Network Resources /// Get VMScaleSet Model View /// Get VMScaleSet Instance View /// List VMScaleSets in a RG /// List Available Skus /// Delete VMScaleSet /// Delete RG /// </summary> [Fact] [Trait("Name", "TestVMScaleSetScenarioOperations_Accept_Regular")] public void TestVMScaleSetPriorityOperations_Accept_Regular() { using (MockContext context = MockContext.Start(this.GetType())) { TestVMScaleSetPriorityOperationsInternal(context, VirtualMachinePriorityTypes.Regular); } } /// <summary> /// Covers following Operations: /// Create RG /// Create Storage Account /// Create Network Resources /// Create Low Priority VMScaleSet with no EvictionPolicy specified /// Get VMScaleSet Model View /// Get VMScaleSet Instance View /// List VMScaleSets in a RG /// List Available Skus /// Delete VMScaleSet /// Delete RG /// </summary> [Fact] [Trait("Name", "TestVMScaleSetScenarioOperations_Accept_Low")] public void TestVMScaleSetPriorityOperations_Accept_Low() { using (MockContext context = MockContext.Start(this.GetType())) { // Create low priority scaleset with no eviction policy specified. Eviction policy is defaulted to Deallocate. TestVMScaleSetPriorityOperationsInternal(context, VirtualMachinePriorityTypes.Low, hasManagedDisks: true); } } /// <summary> /// Covers following Operations: /// Create RG /// Create Storage Account /// Create Network Resources /// Create Azure Spot VMScaleSet with no EvictionPolicy specified /// Get VMScaleSet Model View /// Get VMScaleSet Instance View /// List VMScaleSets in a RG /// List Available Skus /// Delete VMScaleSet /// Delete RG /// </summary> [Fact] [Trait("Name", "TestVMScaleSetScenarioOperations_Accept_Spot")] public void TestVMScaleSetScenarioOperations_Accept_Spot() { using (MockContext context = MockContext.Start(this.GetType())) { // Create Azure Spot scaleset with no eviction policy specified. Eviction policy is defaulted to Deallocate. TestVMScaleSetPriorityOperationsInternal(context, VirtualMachinePriorityTypes.Spot, hasManagedDisks: true); } } /// <summary> /// Covers following Operations: /// Create RG /// Create Storage Account /// Create Network Resources /// Create Low Priority VMScaleSet with 'Delete' EvictionPolicy specified /// Delete VMScaleSet /// Delete RG /// </summary> [Fact] [Trait("Name", "TestVMScaleSetEvictionPolicyOperations_Accept_DeleteEvictionPolicy")] public void TestVMScaleSetEvictionPolicyOperations_Accept_DeleteEvictionPolicy() { using (MockContext context = MockContext.Start(this.GetType())) { // Create low priority scaleset with 'delete' eviction policy specified TestVMScaleSetPriorityOperationsInternal(context, VirtualMachinePriorityTypes.Low, evictionPolicy: VirtualMachineEvictionPolicyTypes.Delete, hasManagedDisks: true); } } #endregion #region Variable Pricing Tests /// <summary> /// Covers following Operations: /// Create RG /// Create Storage Account /// Create Network Resources /// Get VMScaleSet Model View /// Get VMScaleSet Instance View /// List VMScaleSets in a RG /// List Available Skus /// Delete VMScaleSet /// Delete RG /// </summary> [Fact] [Trait("Name", "TestVMScaleSetVariablePricedLowPriorityVM_Accept_DefaultMaxPrice")] public void TestVMScaleSetVariablePricedLowPriorityVM_Accept_DefaultMaxPrice() { using (MockContext context = MockContext.Start(this.GetType())) { TestVMScaleSetPriorityOperationsInternal(context, VirtualMachinePriorityTypes.Low, new BillingProfile { MaxPrice = -1 }, hasManagedDisks: true); } } /// <summary> /// Covers following Operations: /// Create RG /// Create Storage Account /// Create Network Resources /// Get VMScaleSet Model View /// Get VMScaleSet Instance View /// List VMScaleSets in a RG /// List Available Skus /// Delete VMScaleSet /// Delete RG /// </summary> [Fact] [Trait("Name", "TestVMScaleSetVariablePricedLowPriorityVM_Accept_UserSpecifiedMaxPrice")] public void TestVMScaleSetVariablePricedLowPriorityVM_Accept_UserSpecifiedMaxPrice() { using (MockContext context = MockContext.Start(this.GetType())) { TestVMScaleSetPriorityOperationsInternal(context, VirtualMachinePriorityTypes.Low, new BillingProfile { MaxPrice = 100 }, hasManagedDisks: true); } } #endregion private void TestVMScaleSetPriorityOperationsInternal( MockContext context, string priority, BillingProfile billingProfile = null, string evictionPolicy = null, bool hasManagedDisks = false, IList<string> zones = null ) { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); // Create resource group var rgName = TestUtilities.GenerateName(TestPrefix); var vmssName = TestUtilities.GenerateName("vmss"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachineScaleSet inputVMScaleSet; try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "centralus"); EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); m_CrpClient.VirtualMachineScaleSets.Delete(rgName, "VMScaleSetDoesNotExist"); var getResponse = CreateVMScaleSet_NoAsyncTracking( rgName, vmssName, storageAccountOutput, imageRef, out inputVMScaleSet, null, (vmScaleSet) => { vmScaleSet.Overprovision = true; vmScaleSet.VirtualMachineProfile.Priority = priority; vmScaleSet.VirtualMachineProfile.EvictionPolicy = evictionPolicy; vmScaleSet.VirtualMachineProfile.BillingProfile = billingProfile; vmScaleSet.Sku.Name = VirtualMachineSizeTypes.StandardA1; vmScaleSet.Sku.Tier = "Standard"; vmScaleSet.Sku.Capacity = 2; }, createWithManagedDisks: hasManagedDisks, zones: zones); ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks); var getInstanceViewResponse = m_CrpClient.VirtualMachineScaleSets.GetInstanceView(rgName, vmssName); Assert.NotNull(getInstanceViewResponse); ValidateVMScaleSetInstanceView(inputVMScaleSet, getInstanceViewResponse); var listResponse = m_CrpClient.VirtualMachineScaleSets.List(rgName); ValidateVMScaleSet( inputVMScaleSet, listResponse.FirstOrDefault(x => x.Name == vmssName), hasManagedDisks); var listSkusResponse = m_CrpClient.VirtualMachineScaleSets.ListSkus(rgName, vmssName); Assert.NotNull(listSkusResponse); Assert.False(listSkusResponse.Count() == 0); Assert.Same(inputVMScaleSet.VirtualMachineProfile.Priority.ToString(), priority); m_CrpClient.VirtualMachineScaleSets.Delete(rgName, vmssName); } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); //Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose //of the test to cover deletion. CSM does persistent retrying over all RG resources. m_ResourcesClient.ResourceGroups.Delete(rgName); } } } }
// 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.Diagnostics; namespace ExcelDna.Integration { // CAUTION: The ExcelReference class is also called via reflection by the ExcelDna.Loader marshaler. public class ExcelReference : IEquatable<ExcelReference> { struct ExcelRectangle : IEquatable<ExcelRectangle> { public readonly int RowFirst; public readonly int RowLast; public readonly int ColumnFirst; public readonly int ColumnLast; internal ExcelRectangle(int rowFirst, int rowLast, int columnFirst, int columnLast) { // CONSIDER: Throw or truncate for errors RowFirst = Clamp(rowFirst, 0, ExcelDnaUtil.ExcelLimits.MaxRows - 1); RowLast = Clamp(rowLast, 0, ExcelDnaUtil.ExcelLimits.MaxRows - 1); ColumnFirst = Clamp(columnFirst, 0, ExcelDnaUtil.ExcelLimits.MaxColumns - 1); ColumnLast = Clamp(columnLast, 0, ExcelDnaUtil.ExcelLimits.MaxColumns - 1); // CONSIDER: Swap or truncate rect ?? //if (RowLast < RowFirst) RowLast = RowFirst; //if (ColumnLast < ColumnFirst) ColumnLast = RowFirst; } static int Clamp(int value, int min, int max) { Debug.Assert(min <= max); if (value < min) return min; if (value > max) return max; return value; } public override bool Equals(object obj) { if (obj.GetType() != typeof (ExcelRectangle)) return false; return Equals((ExcelRectangle) obj); } public bool Equals(ExcelRectangle other) { return other.RowFirst == RowFirst && other.RowLast == RowLast && other.ColumnFirst == ColumnFirst && other.ColumnLast == ColumnLast; } public override int GetHashCode() { unchecked { int result = RowFirst; result = (result*397) ^ RowLast; result = (result*397) ^ ColumnFirst; result = (result*397) ^ ColumnLast; return result; } } } readonly IntPtr sheetId; // Save first rectangle explicitly, to avoid array if we don't need one. readonly ExcelRectangle rectangle; ExcelRectangle[] furtherRectangles; // Can't make readonly (yet) since we still have the obsolete 'AddReference' public ExcelReference(int row, int column) : this(row, row, column, column) { } // DOCUMENT: If no SheetId is given, assume the Active (Front) Sheet public ExcelReference(int rowFirst, int rowLast, int columnFirst, int columnLast) : this(rowFirst, rowLast, columnFirst, columnLast, IntPtr.Zero) { try { ExcelReference r = (ExcelReference)XlCall.Excel(XlCall.xlSheetId); sheetId = r.sheetId; } catch { // CONSIDER: throw or 'default' behaviour? } } public ExcelReference(int rowFirst, int rowLast, int columnFirst, int columnLast, IntPtr sheetId) { this.sheetId = sheetId; rectangle = new ExcelRectangle(rowFirst, rowLast, columnFirst, columnLast); } // TODO: Consider how to deal with invalid sheetName. I presume xlSheetId will fail. // Perhaps throw a custom exception...? public ExcelReference(int rowFirst, int rowLast, int columnFirst, int columnLast, string sheetName) { ExcelReference sheetRef = (ExcelReference)XlCall.Excel(XlCall.xlSheetId, sheetName); this.sheetId = sheetRef.SheetId; rectangle = new ExcelRectangle(rowFirst, rowLast, columnFirst, columnLast); } public ExcelReference(int[][] rectangles, IntPtr sheetId) { this.sheetId = sheetId; int rectCount = rectangles.Length; int[] rect = rectangles[0]; rectangle = new ExcelRectangle(rect[0], rect[1], rect[2], rect[3]); int furtherRectangleCount = rectCount - 1; if (furtherRectangleCount > 0) { furtherRectangles = new ExcelRectangle[furtherRectangleCount]; for (int i = 0; i < furtherRectangleCount; i++) { rect = rectangles[i + 1]; Debug.Assert(rect.Length == 4); furtherRectangles[i] = new ExcelRectangle(rect[0], rect[1], rect[2], rect[3]); } } } // THROWS: OverFlowException if the arguments exceed the allowed size // or if the number of Inner References exceeds 65000 [Obsolete("An ExcelReference should never be modified.")] public void AddReference(int rowFirst, int rowLast, int columnFirst, int columnLast) { ExcelRectangle rect = new ExcelRectangle(rowFirst, rowLast, columnFirst, columnLast); if (furtherRectangles == null) { furtherRectangles = new ExcelRectangle[1]; furtherRectangles[0] = rect; return; } if (furtherRectangles.Length >= ushort.MaxValue - 1) throw new OverflowException("Maximum number of references exceeded"); ExcelRectangle[] newRectangles = new ExcelRectangle[furtherRectangles.Length + 1]; Array.Copy(furtherRectangles, newRectangles, furtherRectangles.Length); newRectangles[newRectangles.Length - 1] = rect; furtherRectangles = newRectangles; } public int RowFirst { get { return rectangle.RowFirst; } } public int RowLast { get { return rectangle.RowLast; } } public int ColumnFirst { get { return rectangle.ColumnFirst; } } public int ColumnLast { get { return rectangle.ColumnLast; } } public IntPtr SheetId { get { return sheetId; } } // TODO: Document the fact that the returned list is a copy, and does not modify the list of Rectangles in the ExcelReference. public List<ExcelReference> InnerReferences { get { List<ExcelReference> inner = new List<ExcelReference>(); // Add ourselves - which is the first one inner.Add(new ExcelReference(RowFirst, RowLast, ColumnFirst, ColumnLast, SheetId)); // And then all the others if (furtherRectangles != null) { foreach (ExcelRectangle rect in furtherRectangles) { inner.Add(new ExcelReference(rect.RowFirst, rect.RowLast, rect.ColumnFirst, rect.ColumnLast, SheetId)); } } return inner; } } public object GetValue() { return XlCall.Excel(XlCall.xlCoerce, this); } // DOCUMENT: Strange behaviour with SetValue...??? public bool SetValue(object value) { return (bool)XlCall.Excel(XlCall.xlSet, this, value); } // CAUTION: These 'private' functions are called via reflection by the ExcelDna.Loader marshaler // Returns arrays containing all the inner rectangles (including the one we pretend is outside). private int[][] GetRectangles() { int rectangleCount = GetRectangleCount(); int furtherRectangleCount = rectangleCount - 1; int[][] intRects = new int[rectangleCount][]; intRects[0] = new int[] { RowFirst, RowLast, ColumnFirst, ColumnLast }; for (int i = 0; i < furtherRectangleCount; i++) { // We only get here if there are further rectangles Debug.Assert(furtherRectangles != null); ExcelRectangle rect = furtherRectangles[i]; intRects[i+1] = new int[] {rect.RowFirst, rect.RowLast, rect.ColumnFirst, rect.ColumnLast}; } return intRects; } private int GetRectangleCount() { if (furtherRectangles == null) return 1; return furtherRectangles.Length + 1; } // Structural equality implementation public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof (ExcelReference)) return false; return Equals((ExcelReference) obj); } public bool Equals(ExcelReference other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; // Implement equality check based on contents. if (!rectangle.Equals(other.rectangle)) return false; if (!sheetId.Equals(other.sheetId)) return false; // Count will implicitly check null furtherRectangle arrays on either side too int rectangleCount = GetRectangleCount(); if (rectangleCount != other.GetRectangleCount()) return false; int furtherRectangleCount = rectangleCount - 1; for (int i = 0; i < furtherRectangleCount; i++) { if (!furtherRectangles[i].Equals(other.furtherRectangles[i])) return false; } return true; } // We need to take some care with the Hash Code here, since we use the ExcelReference with structural comparison // in some Dictionaries. public override int GetHashCode() { // One of the ideas from http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode const int b = 378551; int a = 63689; int hash = 0; unchecked { hash = hash * a + rectangle.GetHashCode(); a = a * b; if (furtherRectangles != null) { for (int i = 0; i < furtherRectangles.Length; i++) { hash = hash * a + furtherRectangles[i].GetHashCode(); a = a * b; } } hash *= 397; } return hash ^ sheetId.GetHashCode(); } public override string ToString() { return string.Format("({0},{1} : {2},{3}) - {4}", RowFirst, ColumnFirst, RowLast, ColumnLast, SheetId); } public static bool operator ==(ExcelReference left, ExcelReference right) { if (ReferenceEquals(left, right)) return true; if ((object)left == null || (object)right == null) return false; return left.Equals(right); } public static bool operator !=(ExcelReference left, ExcelReference right) { return !(left == right); } } }
using System; using System.Linq; using System.Collections; using System.Globalization; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using UnityEngine; namespace Zios{ public static class StringExtension{ //============================ // Conversion //============================ public static string ToLetterSequence(this string current){ char lastDigit = current[current.Length-1]; if(current.Length > 1 && current[current.Length-2] == ' ' && char.IsLetter(lastDigit)){ char nextLetter = (char)(char.ToUpper(lastDigit)+1); return current.TrimEnd(lastDigit) + nextLetter; } return current + " B"; } public static string ToMD5(this string current){ byte[] bytes = Encoding.UTF8.GetBytes(current); byte[] hash = MD5.Create().ComputeHash(bytes); return BitConverter.ToString(hash).Replace("-",""); } public static string ToCapitalCase(this string current){ return current[0].ToString().ToUpper() + current.Substring(1); } public static string ToTitleCase(this string current){ string text = Regex.Replace(current,"(\\B[A-Z])"," $1"); text = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(text); text = text.Replace("3 D","3D").Replace("2 D","2D"); return text; } public static string ToPascalCase(this string current){ return current.ToTitleCase().Remove(" "); } public static string ToCamelCase(this string current){ return current[0].ToString().ToLower() + current.Substring(1).Remove(" "); } public static short ToShort(this string current){ if(current.IsEmpty()){return 0;} return Convert.ToInt16(current); } public static int ToInt(this string current){ if(current.IsEmpty()){return 0;} return Convert.ToInt32(current); } public static float ToFloat(this string current){ if(current.IsEmpty()){return 0;} return Convert.ToSingle(current); } public static double ToDouble(this string current){ if(current.IsEmpty()){return 0;} return Convert.ToDouble(current); } public static bool ToBool(this string current){ if(current.IsEmpty()){return false;} string lower = current.ToLower(); return lower != "false" && lower != "f" && lower != "0"; } public static T ToEnum<T>(this string current){ return (T)Enum.Parse(typeof(T),current,true); } public static byte ToByte(this string current){return (byte)current[0];} public static byte[] ToStringBytes(this string current){return Encoding.ASCII.GetBytes(current);} public static string Serialize(this string current){return current;} public static string Deserialize(this string current,string value){return value;} public static Type Deserialize<Type>(this string current){ if(typeof(Type) == typeof(Texture2D)){return (Type)new Texture2D(1,1).Deserialize(current).Box();} else if(typeof(Type) == typeof(GUIContent)){return (Type)new GUIContent().Deserialize(current).Box();} else if(typeof(Type) == typeof(Vector3)){return (Type)Vector3.zero.Deserialize(current).Box();} else if(typeof(Type) == typeof(Color)){return (Type)Color.white.Deserialize(current).Box();} else if(typeof(Type) == typeof(float)){return (Type)new Single().Deserialize(current).Box();} else if(typeof(Type) == typeof(int)){return (Type)new Int32().Deserialize(current).Box();} else if(typeof(Type) == typeof(bool)){return (Type)new Boolean().Deserialize(current).Box();} else if(typeof(Type) == typeof(string)){return (Type)String.Empty.Deserialize(current).Box();} else if(typeof(Type) == typeof(byte)){return (Type)new Byte().Deserialize(current).Box();} else if(typeof(Type) == typeof(short)){return (Type)new Int16().Deserialize(current).Box();} else if(typeof(Type) == typeof(double)){return (Type)new Double().Deserialize(current).Box();} else if(typeof(Type).IsCollection()){return (Type)new Type[0].Deserialize(current).Box();} return default(Type); } //============================ // Conversion - Unity //============================ public static Rect ToRect(this string current,string separator=","){ var values = current.Split(separator).ConvertAll<float>(); return new Rect(values[0],values[1],values[2],values[3]); } public static RectOffset ToRectOffset(this string current,string separator=" "){ var values = current.Split(separator).ConvertAll<int>(); return new RectOffset(values[0],values[1],values[2],values[3]); } public static GUIContent ToContent(this string current){return new GUIContent(current);} public static Color ToColor(this string current,string separator=",",bool? normalized=null){ current = current.Remove("#").Remove("0x").Trim(); if(current.Contains(separator)){ var parts = current.Split(separator).ConvertAll<float>(); normalized = normalized.IsNull() ? current.Contains(".") : normalized; if(!normalized.As<bool>()){ parts = parts.Select(x=>x/255.0f).ToArray(); } float r = parts[0]; float g = parts[1]; float b = parts[2]; float a = parts.Length > 3 ? parts[3] : 1; return new Color(r,g,b,a); } else if(current.Length == 8 || current.Length == 6 || current.Length == 3){ if(current.Length == 3){ current += current; } float r = (float)Convert.ToInt32(current.Substring(0,2),16) / 255.0f; float g = (float)Convert.ToInt32(current.Substring(2,2),16) / 255.0f; float b = (float)Convert.ToInt32(current.Substring(4,2),16) / 255.0f; float a = current.Length == 8 ? (float)Convert.ToInt32(current.Substring(6,2),16) / 255.0f : 1; return new Color(r,g,b,a); } else{ var message = "[StringExtension] Color strings can only be converted from Hexidecimal or comma/space separated Decimal -- " + current; throw new Exception(message); } } public static Vector2 ToVector2(this string current,string separator=","){ if(!current.Contains(separator)){return Vector2.zero;} var values = current.Trim("(",")").Split(separator).ConvertAll<float>().ToArray(); return new Vector2(values[0],values[1]); } public static Vector3 ToVector3(this string current,string separator=","){ if(!current.Contains(separator)){return Vector3.zero;} var values = current.Trim("(",")").Split(separator).ConvertAll<float>().ToArray(); return new Vector3(values[0],values[1],values[2]); } public static Vector4 ToVector4(this string current,string separator=","){ if(!current.Contains(separator)){return Vector4.zero;} var values = current.Trim("(",")").Split(separator).ConvertAll<float>().ToArray(); return new Vector4(values[0],values[1],values[2],values[3]); } //============================ // Standard //============================ public static string Trim(this string current,params string[] values){ foreach(string value in values){ current = current.TrimLeft(value); current = current.TrimRight(value); } return current; } public static string TrimRight(this string current,params string[] values){ foreach(string value in values){current = current.TrimRight(value,true);} return current; } public static string TrimLeft(this string current,params string[] values){ foreach(string value in values){current = current.TrimLeft(value,true);} return current; } public static string TrimRight(this string current,string value,bool ignoreCase){ if(value.IsEmpty()){return current;} while(current.EndsWith(value,ignoreCase)){ current = current.Substring(0,current.Length - value.Length); } return current; } public static string TrimLeft(this string current,string value,bool ignoreCase){ if(value.IsEmpty()){return current;} while(current.StartsWith(value,ignoreCase)){ current = current.Substring(value.Length); } return current; } public static bool Matches(this string current,string value,bool ignoreCase=false){ if(ignoreCase){return current.ToLower() == value.ToLower();} return current == value; } public static bool MatchesAny(this string current,params string[] values){ foreach(string value in values){ if(current.Matches(value,true)){return true;} } return false; } public static string Replace(this string current,string search,string replace,bool ignoreCase){ if(ignoreCase){ search = Regex.Escape(search); replace = Regex.Escape(replace); string output = Regex.Replace(current,search,replace,RegexOptions.IgnoreCase | RegexOptions.Multiline); return Regex.Unescape(output); } return current.Replace(search,replace); } public static string ReplaceFirst(this string current,string search,string replace,bool ignoreCase=false){ int position = current.IndexOf(search,ignoreCase); if(position == -1){ return current; } return current.Substring(0,position) + replace + current.Substring(position + search.Length); } public static string ReplaceLast(this string current,string search,string replace,bool ignoreCase=false){ int position = current.LastIndexOf(search,ignoreCase); if(position == -1){ return current; } return current.Substring(0,position) + replace + current.Substring(position + search.Length); } public static int IndexOf(this string current,string value,int start,bool ignoreCase){ if(ignoreCase){ return current.IndexOf(value,start,StringComparison.OrdinalIgnoreCase); } return current.IndexOf(value,start); } public static int IndexOf(this string current,string value,bool ignoreCase){ return current.IndexOf(value,0,ignoreCase); } public static int IndexOf(this string current,string value,int start,int occurrence,bool ignoreCase){ while(occurrence > 0){ start = current.IndexOf(value,start+1,ignoreCase)+1; occurrence -= 1; } return Mathf.Max(start-1,-1); } public static int LastIndexOf(this string current,string value,int start,bool ignoreCase){ if(ignoreCase){ return current.LastIndexOf(value,start,StringComparison.OrdinalIgnoreCase); } return current.LastIndexOf(value,start); } public static int LastIndexOf(this string current,string value,bool ignoreCase){ return current.LastIndexOf(value,current.Length-1,ignoreCase); } public static int LastIndexOf(this string current,string value,int start,int occurrence,bool ignoreCase){ while(occurrence > 0){ start = current.LastIndexOf(value,start+1,ignoreCase)+1; occurrence -= 1; } return Mathf.Max(start-1,-1); } public static bool StartsWith(this string current,string value,bool ignoreCase){ if(ignoreCase){ return current.StartsWith(value,StringComparison.OrdinalIgnoreCase); } return current.StartsWith(value); } public static bool EndsWith(this string current,string value,bool ignoreCase){ if(ignoreCase){ return current.EndsWith(value,StringComparison.OrdinalIgnoreCase); } return current.EndsWith(value); } public static bool Has(this string current,string value,bool ignoreCase){return current.Contains(value,ignoreCase);} public static bool HasAny(this string current,params string[] values){return current.ContainsAny(values);} public static bool HasAll(this string current,params string[] values){return current.ContainsAll(values);} public static bool Contains(this string current,string value,bool ignoreCase){ return current.IndexOf(value,ignoreCase) >= 0; } public static bool ContainsAny(this string current,params string[] values){ foreach(string name in values){ if(current.Contains(name,true)){return true;} } return false; } public static bool ContainsAll(this string current,params string[] values){ foreach(string name in values){ if(!current.Contains(name,true)){return false;} } return true; } public static string Remove(this string current,params string[] values){ string result = current; foreach(string value in values){ result = result.Replace(value,"",true); } return result; } public static string[] Split(this string current,string value){ if(value.Length == 0 || !current.Contains(value)){return new string[1]{current};} return current.Split(new string[]{value},StringSplitOptions.None); } //============================ // Checks //============================ public static bool IsEmpty(this string text){ return string.IsNullOrEmpty(text); } public static bool IsInt(this string text){ short number; return short.TryParse(text,out number); } public static bool IsFloat(this string text){ float number; return float.TryParse(text,out number); } public static bool IsNumber(this string current){ double result; return double.TryParse(current,out result); } public static bool IsColor(this string current,string separator=",",bool? normalized=null){ try{ current.ToColor(separator,normalized); return true; } catch{ return false; } } public static bool IsColorData(this string current){ return current.ContainsAny(",","#"); } public static bool IsEnum<T>(this string current,bool ignoreCase=true){ try{ var result = (T)Enum.Parse(typeof(T),current,ignoreCase); return !result.IsNull(); } catch{return false;} } //============================ // Path //============================ public static string FixPath(this string current){ return current.Replace("\\","/"); } public static string GetDirectory(this string current){ int last = current.FixPath().LastIndexOf('/'); if(last < 0){ if(current.Contains(".")){return "";} return current; } return current.Substring(0,last); } public static string GetAssetPath(this string current){ if(!current.Contains("Assets")){return current;} return "Assets" + current.FixPath().Split("/Assets")[1]; } public static string GetPathTerm(this string current){ return current.FixPath().Split("/").LastOrDefault() ?? ""; } public static string GetFileName(this string current){ var term = current.FixPath().Split("/").LastOrDefault(); if(term.Contains(".")){return term.Replace("."+current.GetFileExtension(),"");} return ""; } public static string GetFileExtension(this string current){ var term = current.FixPath().Split("/").LastOrDefault(); if(term.Contains(".")){return term.Split(".").Last();} return term; } //============================ // Extension //============================ public static string AddLine(this string current,string value){ return current + value + "\r\n"; } public static string[] GetLines(this string current){ return current.Remove("\r").Split("\n"); } public static string Implode(this string current,string separator=" "){ StringBuilder builder = new StringBuilder(current.Length * 2); foreach(char letter in current){ builder.Append(letter); builder.Append(separator); } return builder.ToString(); } public static string Cut(this string current,int startIndex=0,int endIndex=-1){ return current.Substring(startIndex,endIndex - startIndex + 1); } public static string Cut(this string current,string start="",string end="",int offset=0,bool ignoreCase=true,int endCount=1){ int startIndex = start == "" ? 0 : current.IndexOf(start,offset,ignoreCase); if(startIndex != -1){ if(end == ""){return current.Substring(startIndex);} int endIndex = current.IndexOf(end,startIndex + 1,ignoreCase); if(endIndex == -1){return current.Substring(startIndex);} while(endCount > 1){ endIndex = current.IndexOf(end,endIndex + 1,ignoreCase); --endCount; } int distance = endIndex - startIndex + end.Length; return current.Substring(startIndex,distance); } return ""; } public static string Parse(this string current,string start="",string end="",int offset=0,bool ignoreCase=true,int endCount=1){ string value = current.Cut(start,end,offset,ignoreCase,endCount); if(value.IsEmpty()){return "";} return value.Substring(start.Length).TrimRight(end).Trim(); } public static string FindFirst(this string current,params string[] values){ int index = -1; string first = ""; foreach(string value in values){ int currentIndex = current.IndexOf(value,true); if(currentIndex != -1 && (index == -1 || currentIndex < index)){ index = currentIndex; first = value; } } return first; } public static string StripMarkup(this string current){ return Regex.Replace(current,"<.*?>",string.Empty); } public static string Pack(this string current){ return current.Remove("\r","\n","'","\"","{","}","[","]","(",")","\t"," "); } public static string Condense(this string current){ while(current.ContainsAny("\t\t"," ")){ current = current.Replace("\t\t","\t").Replace(" "," "); } return current; } public static string Truncate(this string current,int maxLength){ return current.Length <= maxLength ? current : current.Substring(0,maxLength); } public static string TrySplit(this string current,string value,int index=0){ return current.TrySplit(value[0],index); } public static string TrySplit(this string current,char value,int index=0){ if(current.Contains(value.ToString())){ return current.Split(value)[index]; } return current; } public static string SetDefault(this string current,string value){ if(current.IsEmpty()){return value;} return current; } } }
using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using gView.SDEWrapper.a10; using gView.Framework.Data; using gView.Framework.Geometry; namespace gView.Interoperability.Sde.a10 { internal class SdeFeatureCursor : FeatureCursor { private SdeDataset _dataset; private SdeQueryInfo _queryInfo; private SdeStream _stream = null; private ArcSdeConnection _connection; private string _errMsg = ""; private List<IField> _queryFields = null; private ISpatialFilter _spatialFilter = null; public SdeFeatureCursor(SdeDataset dataset, ITableClass tc, IQueryFilter filter) : base((tc is IFeatureClass) && ((IFeatureClass)tc).SpatialReference != null ? ((IFeatureClass)tc).SpatialReference : filter.ContextLayerDefaultSpatialReference, (filter != null) ? filter.FeatureSpatialReference : null) { try { if (filter != null && !filter.SubFields.Contains("*")) filter.AddField(tc.IDFieldName, false); filter.fieldPrefix = tc.Name + "."; filter.fieldPostfix = ""; if (filter is ISpatialFilter && (((ISpatialFilter)filter).SpatialRelation != spatialRelation.SpatialRelationMapEnvelopeIntersects)) { if (tc is IFeatureClass) filter.AddField(((IFeatureClass)tc).ShapeFieldName); _spatialFilter = (ISpatialFilter)filter; } Int32 err_no = 0; _dataset = dataset; if (_dataset == null) return; //_connection = _dataset.AllocConnection(); _connection = new ArcSdeConnection(dataset.ConnectionString); if (!_connection.Open(this._dataset)) return; _queryInfo = new SdeQueryInfo(_connection, tc, filter); if (_queryInfo.ErrorMessage != "") { Dispose(); return; } //if (Wrapper10.SE_stream_create(_connection.SeConnection, ref _stream) != 0) //{ // Dispose(); // return; //} //_connection.ResetStream(); _stream = _connection.CreateStream(); // SE_stream_set_state sollte auch aufgerufen werden (siehe mapsde.c von UMN) if (Wrapper10.SE_stream_set_state( _stream.SeStream, CONST.SE_DEFAULT_STATE_ID, CONST.SE_DEFAULT_STATE_ID, CONST.SE_STATE_DIFF_NOCHECK) != 0) { Dispose(); return; } if ((err_no = Wrapper10.SE_stream_query_with_info(_stream.SeStream, _queryInfo.SeQueryInfo)) != 0) { Dispose(); return; } if (_queryInfo.IsSpatial) { SE_FILTER se_filter = _queryInfo.Filter_Shape; if ((err_no = Wrapper10.SE_stream_set_spatial_constraints(_stream.SeStream, CONST.SE_SPATIAL_FIRST, false, 1, ref se_filter)) != 0) { _errMsg = Wrapper10.GetErrorMsg(_connection.SeConnection, err_no); Dispose(); return; } } else { /* SE_FILTER se_filter = _queryInfo.Filter_Id; if (Wrapper10.SE_stream_set_spatial_constraints(_stream, CONST.SE_SPATIAL_FIRST, false, 1, ref se_filter) != 0) { Release(); return; } * */ } if (Wrapper10.SE_stream_execute(_stream.SeStream) != 0) { Dispose(); return; } _queryFields = _queryInfo.QueryFields; _queryInfo.Dispose(); _queryInfo = null; } catch (Exception ex) { _errMsg = ex.Message + "\n" + ex.StackTrace; Dispose(); } } #region IFeatureCursor Member int i = 0; public override IFeature NextFeature { get { while (true) { if (_connection == null) return null; Int32 err_no; err_no = Wrapper10.SE_stream_fetch(_stream.SeStream); if (err_no == CONST.SE_FINISHED) { Dispose(); return null; } if (err_no != 0) { _errMsg = Wrapper10.GetErrorMsg(_connection.SeConnection, err_no); Dispose(); return null; } i++; IFeature feature = FetchNextFeature(); Transform(feature); if (_spatialFilter != null && feature != null && feature.Shape != null) { if (!gView.Framework.Geometry.SpatialRelation.Check(_spatialFilter, feature.Shape)) continue; } return feature; } } } #endregion #region ICursor Member public override void Dispose() { base.Dispose(); if (_queryInfo != null) { _queryInfo.Dispose(); _queryInfo = null; } if (_stream != null) { _stream.Free(); _stream = null; } if (_connection != null) { try { _connection.Close(); } catch { } _connection = null; } } #endregion private IFeature FetchNextFeature() { try { Feature feat = new Feature(); System.Int16 index = 1; foreach (IField field in _queryFields) { switch (field.type) { case FieldType.ID: feat.OID = FetchInteger(index); feat.Fields.Add(new FieldValue(field.name, feat.OID)); break; case FieldType.Shape: feat.Shape = FetchShape(index); break; case FieldType.boolean: feat.Fields.Add(new FieldValue(field.name, "???")); break; case FieldType.character: feat.Fields.Add(new FieldValue(field.name, "???")); break; case FieldType.Date: feat.Fields.Add(new FieldValue(field.name, FetchDate(index))); break; case FieldType.Double: feat.Fields.Add(new FieldValue(field.name, FetchDouble(index))); break; case FieldType.Float: feat.Fields.Add(new FieldValue(field.name, FetchFloat(index))); break; case FieldType.biginteger: case FieldType.integer: feat.Fields.Add(new FieldValue(field.name, FetchInteger(index))); break; case FieldType.smallinteger: feat.Fields.Add(new FieldValue(field.name, FetchSmallInteger(index))); break; case FieldType.String: feat.Fields.Add(new FieldValue(field.name, FetchString(index, field.size))); break; case FieldType.NString: feat.Fields.Add(new FieldValue(field.name, FetchNString(index, field.size))); break; } index++; } return feat; } catch { return null; } } private int FetchInteger(System.Int16 index) { System.Int32 val = 0; System.Int32 err_no = Wrapper10.SE_stream_get_integer(_stream.SeStream, index, ref val); if (err_no == 0) return val; return 0; } private short FetchSmallInteger(System.Int16 index) { System.Int16 val = 0; System.Int32 err_no = Wrapper10.SE_stream_get_smallint(_stream.SeStream, index, ref val); if (err_no == 0) return val; return 0; } private double FetchDouble(System.Int16 index) { System.Double val = 0; System.Int32 err_no = Wrapper10.SE_stream_get_double(_stream.SeStream, index, ref val); if (err_no == 0) return val; return 0; } private float FetchFloat(System.Int16 index) { float val = 0; System.Int32 err_no = Wrapper10.SE_stream_get_float(_stream.SeStream, index, ref val); if (err_no == 0) return val; return 0; } private string FetchString(System.Int16 index, int size) { try { byte[] buffer = new byte[size + 1]; System.Int32 err_no = Wrapper10.SE_stream_get_string(_stream.SeStream, index, buffer); if (err_no == -1004) return String.Empty; //return null; if (err_no != 0) return "<ERROR>:" + Wrapper10.GetErrorMsg(_connection.SeConnection, err_no); return System.Text.Encoding.UTF7.GetString(buffer).Replace("\0", ""); } catch (Exception ex) { return "<EXCEPTION>:" + ex.Message; } } private string FetchNString(System.Int16 index, int size) { try { byte[] buffer = new byte[(size + 1) * 2]; System.Int32 err_no = Wrapper10.SE_stream_get_nstring(_stream.SeStream, index, buffer); if (err_no == -1004) return String.Empty; //return null; if (err_no != 0) return "<ERROR>:" + Wrapper10.GetErrorMsg(_connection.SeConnection, err_no); return System.Text.Encoding.Unicode.GetString(buffer).Replace("\0", ""); } catch (Exception ex) { return "<EXCEPTION>:" + ex.Message; } } private DateTime? FetchDate(System.Int16 index) { tm TM = new tm(); System.Int32 err_no = Wrapper10.SE_stream_get_date(_stream.SeStream, index, ref TM); if (err_no == -1004) return null; if (err_no != 0) return new DateTime(1, 1, 1); return new DateTime( TM.tm_year + 1900, TM.tm_mon + 1, TM.tm_mday); } private IGeometry FetchShape(System.Int16 index) { unsafe { System.Int32 err_no = 0; SE_SHAPE shape_val = new SE_SHAPE(); System.Int32* part_offsets = null; System.Int32* subp_offsets = null; SE_POINT* points = null; try { err_no = Wrapper10.SE_shape_create(new SE_COORDREF(), ref shape_val); if (err_no != 0) return null; err_no = Wrapper10.SE_stream_get_shape(_stream.SeStream, index, shape_val); if (err_no != 0) return null; Int32 shapeType = 0, numPoints = 0, numParts = 0, numSubparts = 0; err_no = Wrapper10.SE_shape_get_type(shape_val, ref shapeType); if (err_no != 0 || shapeType == CONST.SG_NIL_SHAPE) return null; err_no = Wrapper10.SE_shape_get_num_points(shape_val, 0, 0, ref numPoints); if (err_no != 0) return null; err_no = Wrapper10.SE_shape_get_num_parts(shape_val, ref numParts, ref numSubparts); if (err_no != 0) return null; part_offsets = (System.Int32*)Marshal.AllocHGlobal(((int)numParts + 1) * sizeof(System.Int32)); subp_offsets = (System.Int32*)Marshal.AllocHGlobal(((int)numSubparts + 1) * sizeof(System.Int32)); points = (SE_POINT*)Marshal.AllocHGlobal((int)numPoints * sizeof(SE_POINT)); part_offsets[numParts] = (int)numSubparts; subp_offsets[numSubparts] = (int)numPoints; err_no = Wrapper10.SE_shape_get_all_points( shape_val, SE_ROTATION_TYPE.SE_DEFAULT_ROTATION, (IntPtr)part_offsets, (IntPtr)subp_offsets, (IntPtr)points, (IntPtr)null, (IntPtr)null); if (err_no != 0) return null; IGeometry ret = null; switch (shapeType) { case CONST.SG_POINT_SHAPE: if (numPoints == 1) { ret = new Point(points[0].x, points[0].y); } else if (numPoints > 1) { MultiPoint mPoint_ = new MultiPoint(); for (int i = 0; i < numPoints; i++) mPoint_.AddPoint(new Point(points[i].x, points[i].y)); ret = mPoint_; } break; case CONST.SG_MULTI_POINT_SHAPE: MultiPoint mPoint = new MultiPoint(); for (int i = 0; i < numPoints; i++) mPoint.AddPoint(new Point(points[i].x, points[i].y)); ret = mPoint; break; case CONST.SG_LINE_SHAPE: case CONST.SG_SIMPLE_LINE_SHAPE: case CONST.SG_MULTI_LINE_SHAPE: case CONST.SG_MULTI_SIMPLE_LINE_SHAPE: Polyline polyline = new Polyline(); for (int s = 0; s < numSubparts; s++) { Path path = new Path(); int to = subp_offsets[s + 1]; for (int i = subp_offsets[s]; i < to; i++) { path.AddPoint(new Point(points[i].x, points[i].y)); } polyline.AddPath(path); } ret = polyline; break; case CONST.SG_AREA_SHAPE: case CONST.SG_MULTI_AREA_SHAPE: Polygon polygon = new Polygon(); for (int s = 0; s < numSubparts; s++) { Ring ring = new Ring(); int to = subp_offsets[s + 1]; for (int i = subp_offsets[s]; i < to; i++) { ring.AddPoint(new Point(points[i].x, points[i].y)); } polygon.AddRing(ring); } ret = polygon; break; } return ret; } catch { return null; } finally { if (part_offsets != null) Marshal.FreeHGlobal((System.IntPtr)part_offsets); if (subp_offsets != null) Marshal.FreeHGlobal((System.IntPtr)subp_offsets); if (points != null) Marshal.FreeHGlobal((System.IntPtr)points); if (shape_val.handle != IntPtr.Zero) Wrapper10.SE_shape_free(shape_val); } } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using VideoIndexerOrchestrationWeb.Areas.HelpPage.ModelDescriptions; using VideoIndexerOrchestrationWeb.Areas.HelpPage.Models; namespace VideoIndexerOrchestrationWeb.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; namespace Amazon.RDS.Model { /// <summary> /// <para> Option settings are the actual settings being applied or configured for that option. It is used when you modify an option group or /// describe option groups. For example, the NATIVE_NETWORK_ENCRYPTION option has a setting called SQLNET.ENCRYPTION_SERVER that can have /// several different values. </para> /// </summary> public class OptionSetting { private string name; private string value; private string defaultValue; private string description; private string applyType; private string dataType; private string allowedValues; private bool? isModifiable; private bool? isCollection; /// <summary> /// The name of the option that has settings that you can set. /// /// </summary> public string Name { get { return this.name; } set { this.name = value; } } /// <summary> /// Sets the Name property /// </summary> /// <param name="name">The value to set for the Name property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionSetting WithName(string name) { this.name = name; return this; } // Check to see if Name property is set internal bool IsSetName() { return this.name != null; } /// <summary> /// The current value of the option setting. /// /// </summary> public string Value { get { return this.value; } set { this.value = value; } } /// <summary> /// Sets the Value property /// </summary> /// <param name="value">The value to set for the Value property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionSetting WithValue(string value) { this.value = value; return this; } // Check to see if Value property is set internal bool IsSetValue() { return this.value != null; } /// <summary> /// The default value of the option setting. /// /// </summary> public string DefaultValue { get { return this.defaultValue; } set { this.defaultValue = value; } } /// <summary> /// Sets the DefaultValue property /// </summary> /// <param name="defaultValue">The value to set for the DefaultValue property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionSetting WithDefaultValue(string defaultValue) { this.defaultValue = defaultValue; return this; } // Check to see if DefaultValue property is set internal bool IsSetDefaultValue() { return this.defaultValue != null; } /// <summary> /// The description of the option setting. /// /// </summary> public string Description { get { return this.description; } set { this.description = value; } } /// <summary> /// Sets the Description property /// </summary> /// <param name="description">The value to set for the Description property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionSetting WithDescription(string description) { this.description = description; return this; } // Check to see if Description property is set internal bool IsSetDescription() { return this.description != null; } /// <summary> /// The DB engine specific parameter type. /// /// </summary> public string ApplyType { get { return this.applyType; } set { this.applyType = value; } } /// <summary> /// Sets the ApplyType property /// </summary> /// <param name="applyType">The value to set for the ApplyType property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionSetting WithApplyType(string applyType) { this.applyType = applyType; return this; } // Check to see if ApplyType property is set internal bool IsSetApplyType() { return this.applyType != null; } /// <summary> /// The data type of the option setting. /// /// </summary> public string DataType { get { return this.dataType; } set { this.dataType = value; } } /// <summary> /// Sets the DataType property /// </summary> /// <param name="dataType">The value to set for the DataType property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionSetting WithDataType(string dataType) { this.dataType = dataType; return this; } // Check to see if DataType property is set internal bool IsSetDataType() { return this.dataType != null; } /// <summary> /// The allowed values of the option setting. /// /// </summary> public string AllowedValues { get { return this.allowedValues; } set { this.allowedValues = value; } } /// <summary> /// Sets the AllowedValues property /// </summary> /// <param name="allowedValues">The value to set for the AllowedValues property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionSetting WithAllowedValues(string allowedValues) { this.allowedValues = allowedValues; return this; } // Check to see if AllowedValues property is set internal bool IsSetAllowedValues() { return this.allowedValues != null; } /// <summary> /// A Boolean value that, when true, indicates the option setting can be modified from the default. /// /// </summary> public bool IsModifiable { get { return this.isModifiable ?? default(bool); } set { this.isModifiable = value; } } /// <summary> /// Sets the IsModifiable property /// </summary> /// <param name="isModifiable">The value to set for the IsModifiable property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionSetting WithIsModifiable(bool isModifiable) { this.isModifiable = isModifiable; return this; } // Check to see if IsModifiable property is set internal bool IsSetIsModifiable() { return this.isModifiable.HasValue; } /// <summary> /// Indicates if the option setting is part of a collection. /// /// </summary> public bool IsCollection { get { return this.isCollection ?? default(bool); } set { this.isCollection = value; } } /// <summary> /// Sets the IsCollection property /// </summary> /// <param name="isCollection">The value to set for the IsCollection property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionSetting WithIsCollection(bool isCollection) { this.isCollection = isCollection; return this; } // Check to see if IsCollection property is set internal bool IsSetIsCollection() { return this.isCollection.HasValue; } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/spanner/v1/mutation.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Cloud.Spanner.V1 { /// <summary>Holder for reflection information generated from google/spanner/v1/mutation.proto</summary> public static partial class MutationReflection { #region Descriptor /// <summary>File descriptor for google/spanner/v1/mutation.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static MutationReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiBnb29nbGUvc3Bhbm5lci92MS9tdXRhdGlvbi5wcm90bxIRZ29vZ2xlLnNw", "YW5uZXIudjEaHGdvb2dsZS9hcGkvYW5ub3RhdGlvbnMucHJvdG8aHGdvb2ds", "ZS9wcm90b2J1Zi9zdHJ1Y3QucHJvdG8aHGdvb2dsZS9zcGFubmVyL3YxL2tl", "eXMucHJvdG8ixgMKCE11dGF0aW9uEjMKBmluc2VydBgBIAEoCzIhLmdvb2ds", "ZS5zcGFubmVyLnYxLk11dGF0aW9uLldyaXRlSAASMwoGdXBkYXRlGAIgASgL", "MiEuZ29vZ2xlLnNwYW5uZXIudjEuTXV0YXRpb24uV3JpdGVIABI9ChBpbnNl", "cnRfb3JfdXBkYXRlGAMgASgLMiEuZ29vZ2xlLnNwYW5uZXIudjEuTXV0YXRp", "b24uV3JpdGVIABI0CgdyZXBsYWNlGAQgASgLMiEuZ29vZ2xlLnNwYW5uZXIu", "djEuTXV0YXRpb24uV3JpdGVIABI0CgZkZWxldGUYBSABKAsyIi5nb29nbGUu", "c3Bhbm5lci52MS5NdXRhdGlvbi5EZWxldGVIABpTCgVXcml0ZRINCgV0YWJs", "ZRgBIAEoCRIPCgdjb2x1bW5zGAIgAygJEioKBnZhbHVlcxgDIAMoCzIaLmdv", "b2dsZS5wcm90b2J1Zi5MaXN0VmFsdWUaQwoGRGVsZXRlEg0KBXRhYmxlGAEg", "ASgJEioKB2tleV9zZXQYAiABKAsyGS5nb29nbGUuc3Bhbm5lci52MS5LZXlT", "ZXRCCwoJb3BlcmF0aW9uQnwKFWNvbS5nb29nbGUuc3Bhbm5lci52MUINTXV0", "YXRpb25Qcm90b1ABWjhnb29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29n", "bGVhcGlzL3NwYW5uZXIvdjE7c3Bhbm5lcqoCF0dvb2dsZS5DbG91ZC5TcGFu", "bmVyLlYxYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.StructReflection.Descriptor, global::Google.Cloud.Spanner.V1.KeysReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Spanner.V1.Mutation), global::Google.Cloud.Spanner.V1.Mutation.Parser, new[]{ "Insert", "Update", "InsertOrUpdate", "Replace", "Delete" }, new[]{ "Operation" }, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Spanner.V1.Mutation.Types.Write), global::Google.Cloud.Spanner.V1.Mutation.Types.Write.Parser, new[]{ "Table", "Columns", "Values" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Spanner.V1.Mutation.Types.Delete), global::Google.Cloud.Spanner.V1.Mutation.Types.Delete.Parser, new[]{ "Table", "KeySet" }, null, null, null)}) })); } #endregion } #region Messages /// <summary> /// A modification to one or more Cloud Spanner rows. Mutations can be /// applied to a Cloud Spanner database by sending them in a /// [Commit][google.spanner.v1.Spanner.Commit] call. /// </summary> public sealed partial class Mutation : pb::IMessage<Mutation> { private static readonly pb::MessageParser<Mutation> _parser = new pb::MessageParser<Mutation>(() => new Mutation()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Mutation> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Spanner.V1.MutationReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Mutation() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Mutation(Mutation other) : this() { switch (other.OperationCase) { case OperationOneofCase.Insert: Insert = other.Insert.Clone(); break; case OperationOneofCase.Update: Update = other.Update.Clone(); break; case OperationOneofCase.InsertOrUpdate: InsertOrUpdate = other.InsertOrUpdate.Clone(); break; case OperationOneofCase.Replace: Replace = other.Replace.Clone(); break; case OperationOneofCase.Delete: Delete = other.Delete.Clone(); break; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Mutation Clone() { return new Mutation(this); } /// <summary>Field number for the "insert" field.</summary> public const int InsertFieldNumber = 1; /// <summary> /// Insert new rows in a table. If any of the rows already exist, /// the write or transaction fails with error `ALREADY_EXISTS`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Spanner.V1.Mutation.Types.Write Insert { get { return operationCase_ == OperationOneofCase.Insert ? (global::Google.Cloud.Spanner.V1.Mutation.Types.Write) operation_ : null; } set { operation_ = value; operationCase_ = value == null ? OperationOneofCase.None : OperationOneofCase.Insert; } } /// <summary>Field number for the "update" field.</summary> public const int UpdateFieldNumber = 2; /// <summary> /// Update existing rows in a table. If any of the rows does not /// already exist, the transaction fails with error `NOT_FOUND`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Spanner.V1.Mutation.Types.Write Update { get { return operationCase_ == OperationOneofCase.Update ? (global::Google.Cloud.Spanner.V1.Mutation.Types.Write) operation_ : null; } set { operation_ = value; operationCase_ = value == null ? OperationOneofCase.None : OperationOneofCase.Update; } } /// <summary>Field number for the "insert_or_update" field.</summary> public const int InsertOrUpdateFieldNumber = 3; /// <summary> /// Like [insert][google.spanner.v1.Mutation.insert], except that if the row already exists, then /// its column values are overwritten with the ones provided. Any /// column values not explicitly written are preserved. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Spanner.V1.Mutation.Types.Write InsertOrUpdate { get { return operationCase_ == OperationOneofCase.InsertOrUpdate ? (global::Google.Cloud.Spanner.V1.Mutation.Types.Write) operation_ : null; } set { operation_ = value; operationCase_ = value == null ? OperationOneofCase.None : OperationOneofCase.InsertOrUpdate; } } /// <summary>Field number for the "replace" field.</summary> public const int ReplaceFieldNumber = 4; /// <summary> /// Like [insert][google.spanner.v1.Mutation.insert], except that if the row already exists, it is /// deleted, and the column values provided are inserted /// instead. Unlike [insert_or_update][google.spanner.v1.Mutation.insert_or_update], this means any values not /// explicitly written become `NULL`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Spanner.V1.Mutation.Types.Write Replace { get { return operationCase_ == OperationOneofCase.Replace ? (global::Google.Cloud.Spanner.V1.Mutation.Types.Write) operation_ : null; } set { operation_ = value; operationCase_ = value == null ? OperationOneofCase.None : OperationOneofCase.Replace; } } /// <summary>Field number for the "delete" field.</summary> public const int DeleteFieldNumber = 5; /// <summary> /// Delete rows from a table. Succeeds whether or not the named /// rows were present. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Spanner.V1.Mutation.Types.Delete Delete { get { return operationCase_ == OperationOneofCase.Delete ? (global::Google.Cloud.Spanner.V1.Mutation.Types.Delete) operation_ : null; } set { operation_ = value; operationCase_ = value == null ? OperationOneofCase.None : OperationOneofCase.Delete; } } private object operation_; /// <summary>Enum of possible cases for the "operation" oneof.</summary> public enum OperationOneofCase { None = 0, Insert = 1, Update = 2, InsertOrUpdate = 3, Replace = 4, Delete = 5, } private OperationOneofCase operationCase_ = OperationOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OperationOneofCase OperationCase { get { return operationCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void ClearOperation() { operationCase_ = OperationOneofCase.None; operation_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Mutation); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Mutation other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Insert, other.Insert)) return false; if (!object.Equals(Update, other.Update)) return false; if (!object.Equals(InsertOrUpdate, other.InsertOrUpdate)) return false; if (!object.Equals(Replace, other.Replace)) return false; if (!object.Equals(Delete, other.Delete)) return false; if (OperationCase != other.OperationCase) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (operationCase_ == OperationOneofCase.Insert) hash ^= Insert.GetHashCode(); if (operationCase_ == OperationOneofCase.Update) hash ^= Update.GetHashCode(); if (operationCase_ == OperationOneofCase.InsertOrUpdate) hash ^= InsertOrUpdate.GetHashCode(); if (operationCase_ == OperationOneofCase.Replace) hash ^= Replace.GetHashCode(); if (operationCase_ == OperationOneofCase.Delete) hash ^= Delete.GetHashCode(); hash ^= (int) operationCase_; return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (operationCase_ == OperationOneofCase.Insert) { output.WriteRawTag(10); output.WriteMessage(Insert); } if (operationCase_ == OperationOneofCase.Update) { output.WriteRawTag(18); output.WriteMessage(Update); } if (operationCase_ == OperationOneofCase.InsertOrUpdate) { output.WriteRawTag(26); output.WriteMessage(InsertOrUpdate); } if (operationCase_ == OperationOneofCase.Replace) { output.WriteRawTag(34); output.WriteMessage(Replace); } if (operationCase_ == OperationOneofCase.Delete) { output.WriteRawTag(42); output.WriteMessage(Delete); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (operationCase_ == OperationOneofCase.Insert) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Insert); } if (operationCase_ == OperationOneofCase.Update) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Update); } if (operationCase_ == OperationOneofCase.InsertOrUpdate) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(InsertOrUpdate); } if (operationCase_ == OperationOneofCase.Replace) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Replace); } if (operationCase_ == OperationOneofCase.Delete) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Delete); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Mutation other) { if (other == null) { return; } switch (other.OperationCase) { case OperationOneofCase.Insert: Insert = other.Insert; break; case OperationOneofCase.Update: Update = other.Update; break; case OperationOneofCase.InsertOrUpdate: InsertOrUpdate = other.InsertOrUpdate; break; case OperationOneofCase.Replace: Replace = other.Replace; break; case OperationOneofCase.Delete: Delete = other.Delete; break; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { global::Google.Cloud.Spanner.V1.Mutation.Types.Write subBuilder = new global::Google.Cloud.Spanner.V1.Mutation.Types.Write(); if (operationCase_ == OperationOneofCase.Insert) { subBuilder.MergeFrom(Insert); } input.ReadMessage(subBuilder); Insert = subBuilder; break; } case 18: { global::Google.Cloud.Spanner.V1.Mutation.Types.Write subBuilder = new global::Google.Cloud.Spanner.V1.Mutation.Types.Write(); if (operationCase_ == OperationOneofCase.Update) { subBuilder.MergeFrom(Update); } input.ReadMessage(subBuilder); Update = subBuilder; break; } case 26: { global::Google.Cloud.Spanner.V1.Mutation.Types.Write subBuilder = new global::Google.Cloud.Spanner.V1.Mutation.Types.Write(); if (operationCase_ == OperationOneofCase.InsertOrUpdate) { subBuilder.MergeFrom(InsertOrUpdate); } input.ReadMessage(subBuilder); InsertOrUpdate = subBuilder; break; } case 34: { global::Google.Cloud.Spanner.V1.Mutation.Types.Write subBuilder = new global::Google.Cloud.Spanner.V1.Mutation.Types.Write(); if (operationCase_ == OperationOneofCase.Replace) { subBuilder.MergeFrom(Replace); } input.ReadMessage(subBuilder); Replace = subBuilder; break; } case 42: { global::Google.Cloud.Spanner.V1.Mutation.Types.Delete subBuilder = new global::Google.Cloud.Spanner.V1.Mutation.Types.Delete(); if (operationCase_ == OperationOneofCase.Delete) { subBuilder.MergeFrom(Delete); } input.ReadMessage(subBuilder); Delete = subBuilder; break; } } } } #region Nested types /// <summary>Container for nested types declared in the Mutation message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { /// <summary> /// Arguments to [insert][google.spanner.v1.Mutation.insert], [update][google.spanner.v1.Mutation.update], [insert_or_update][google.spanner.v1.Mutation.insert_or_update], and /// [replace][google.spanner.v1.Mutation.replace] operations. /// </summary> public sealed partial class Write : pb::IMessage<Write> { private static readonly pb::MessageParser<Write> _parser = new pb::MessageParser<Write>(() => new Write()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Write> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Spanner.V1.Mutation.Descriptor.NestedTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Write() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Write(Write other) : this() { table_ = other.table_; columns_ = other.columns_.Clone(); values_ = other.values_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Write Clone() { return new Write(this); } /// <summary>Field number for the "table" field.</summary> public const int TableFieldNumber = 1; private string table_ = ""; /// <summary> /// Required. The table whose rows will be written. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Table { get { return table_; } set { table_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "columns" field.</summary> public const int ColumnsFieldNumber = 2; private static readonly pb::FieldCodec<string> _repeated_columns_codec = pb::FieldCodec.ForString(18); private readonly pbc::RepeatedField<string> columns_ = new pbc::RepeatedField<string>(); /// <summary> /// The names of the columns in [table][google.spanner.v1.Mutation.Write.table] to be written. /// /// The list of columns must contain enough columns to allow /// Cloud Spanner to derive values for all primary key columns in the /// row(s) to be modified. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<string> Columns { get { return columns_; } } /// <summary>Field number for the "values" field.</summary> public const int ValuesFieldNumber = 3; private static readonly pb::FieldCodec<global::Google.Protobuf.WellKnownTypes.ListValue> _repeated_values_codec = pb::FieldCodec.ForMessage(26, global::Google.Protobuf.WellKnownTypes.ListValue.Parser); private readonly pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.ListValue> values_ = new pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.ListValue>(); /// <summary> /// The values to be written. `values` can contain more than one /// list of values. If it does, then multiple rows are written, one /// for each entry in `values`. Each list in `values` must have /// exactly as many entries as there are entries in [columns][google.spanner.v1.Mutation.Write.columns] /// above. Sending multiple lists is equivalent to sending multiple /// `Mutation`s, each containing one `values` entry and repeating /// [table][google.spanner.v1.Mutation.Write.table] and [columns][google.spanner.v1.Mutation.Write.columns]. Individual values in each list are /// encoded as described [here][google.spanner.v1.TypeCode]. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.ListValue> Values { get { return values_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Write); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Write other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Table != other.Table) return false; if(!columns_.Equals(other.columns_)) return false; if(!values_.Equals(other.values_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Table.Length != 0) hash ^= Table.GetHashCode(); hash ^= columns_.GetHashCode(); hash ^= values_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Table.Length != 0) { output.WriteRawTag(10); output.WriteString(Table); } columns_.WriteTo(output, _repeated_columns_codec); values_.WriteTo(output, _repeated_values_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Table.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Table); } size += columns_.CalculateSize(_repeated_columns_codec); size += values_.CalculateSize(_repeated_values_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Write other) { if (other == null) { return; } if (other.Table.Length != 0) { Table = other.Table; } columns_.Add(other.columns_); values_.Add(other.values_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Table = input.ReadString(); break; } case 18: { columns_.AddEntriesFrom(input, _repeated_columns_codec); break; } case 26: { values_.AddEntriesFrom(input, _repeated_values_codec); break; } } } } } /// <summary> /// Arguments to [delete][google.spanner.v1.Mutation.delete] operations. /// </summary> public sealed partial class Delete : pb::IMessage<Delete> { private static readonly pb::MessageParser<Delete> _parser = new pb::MessageParser<Delete>(() => new Delete()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Delete> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Spanner.V1.Mutation.Descriptor.NestedTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Delete() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Delete(Delete other) : this() { table_ = other.table_; KeySet = other.keySet_ != null ? other.KeySet.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Delete Clone() { return new Delete(this); } /// <summary>Field number for the "table" field.</summary> public const int TableFieldNumber = 1; private string table_ = ""; /// <summary> /// Required. The table whose rows will be deleted. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Table { get { return table_; } set { table_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "key_set" field.</summary> public const int KeySetFieldNumber = 2; private global::Google.Cloud.Spanner.V1.KeySet keySet_; /// <summary> /// Required. The primary keys of the rows within [table][google.spanner.v1.Mutation.Delete.table] to delete. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Spanner.V1.KeySet KeySet { get { return keySet_; } set { keySet_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Delete); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Delete other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Table != other.Table) return false; if (!object.Equals(KeySet, other.KeySet)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Table.Length != 0) hash ^= Table.GetHashCode(); if (keySet_ != null) hash ^= KeySet.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Table.Length != 0) { output.WriteRawTag(10); output.WriteString(Table); } if (keySet_ != null) { output.WriteRawTag(18); output.WriteMessage(KeySet); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Table.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Table); } if (keySet_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(KeySet); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Delete other) { if (other == null) { return; } if (other.Table.Length != 0) { Table = other.Table; } if (other.keySet_ != null) { if (keySet_ == null) { keySet_ = new global::Google.Cloud.Spanner.V1.KeySet(); } KeySet.MergeFrom(other.KeySet); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Table = input.ReadString(); break; } case 18: { if (keySet_ == null) { keySet_ = new global::Google.Cloud.Spanner.V1.KeySet(); } input.ReadMessage(keySet_); break; } } } } } } #endregion } #endregion } #endregion Designer generated code
using System; #if FRB_MDX using Microsoft.DirectX; using Microsoft.DirectX.Direct3D; using Keys = Microsoft.DirectX.DirectInput.Key; #else using Microsoft.Xna.Framework.Input; #endif using FlatRedBall.Graphics; using FlatRedBall.Input; using System.Collections.Generic; namespace FlatRedBall.Gui { /// <summary> /// Summary description for OkCancelWindow. /// </summary> public class OkCancelWindow : Window, FlatRedBall.Gui.IInputReceiver { #region Fields Button mOkButton; Button cancelButton; TextField textField = new TextField(); public Window callingWindow; IInputReceiver mNextInTabSequence; List<Keys> mIgnoredKeys = new List<Keys>(); #endregion #region Properties public string Message { set{ textField.DisplayText = value; } } public string OkText { set{ mOkButton.Text = value; } get{ return mOkButton.Text; } } public string CancelText { set{ cancelButton.Text = value; } get { return cancelButton.Text; } } public new float ScaleX { get{ return (float)mScaleX; } set { mScaleX = value; if(mCloseButton != null) mCloseButton.SetPositionTL(2*mScaleX - 1.1f, 1.1f); Update(); } } public new float ScaleY { get{ return (float)mScaleY; } set { mScaleY = value; if(mCloseButton != null) mCloseButton.SetPositionTL(2*mScaleX - 1.1f, 1.1f); Update(); } } public bool TakingInput { get { return true; } } public IInputReceiver NextInTabSequence { get { return mNextInTabSequence; } set { mNextInTabSequence = value; } } public List<Keys> IgnoredKeys { get { return mIgnoredKeys; } } #endregion #region Events #region XML Docs /// <summary> /// Event raised when the OkCancelWindow gets keyboard input. /// </summary> #endregion public event GuiMessage GainFocus; public event FocusUpdateDelegate FocusUpdate; public event GuiMessage OkClick = null; public event GuiMessage CancelClick = null; #endregion #region Delegate and delegate calling methods public static void OkButtonClicked(Window callingWindow) { Button okButtonClicked = callingWindow as Button; OkCancelWindow okCancelWindow = callingWindow.Parent as OkCancelWindow; okCancelWindow.Visible = false; if(okCancelWindow.OkClick != null) { if(okCancelWindow.callingWindow != null) okCancelWindow.OkClick(okCancelWindow.callingWindow); else okCancelWindow.OkClick(okCancelWindow); } InputManager.ReceivingInput = null; } public static void CancelButtonClicked(Window callingWindow) { Button cancelButtonClicked = callingWindow as Button; OkCancelWindow okCancelWindow = callingWindow.Parent as OkCancelWindow; okCancelWindow.Visible = false; if(okCancelWindow.CancelClick != null) { if(okCancelWindow.callingWindow != null) okCancelWindow.CancelClick(okCancelWindow.callingWindow); else okCancelWindow.CancelClick(okCancelWindow); } InputManager.ReceivingInput = null; } public void OnFocusUpdate() { if (FocusUpdate != null) FocusUpdate(this); } #endregion #region Methods #region Constructor public OkCancelWindow(Cursor cursor) : base(cursor) { mOkButton = new Button(mCursor); AddWindow(mOkButton); mOkButton.ScaleY = 1.2f; mOkButton.Text = "Ok"; mOkButton.Click += new GuiMessage(OkButtonClicked); cancelButton = new Button(mCursor); AddWindow(cancelButton); cancelButton.ScaleY = 1.2f; cancelButton.Text = "Cancel"; cancelButton.Click += new GuiMessage(CancelButtonClicked); } #endregion #region Public Methods public void Activate(string textToDisplay, string Name) { // TextField textField = new TextField(); Visible = true; mName = Name; ScaleX = 13; ScaleY = 13; // textDisplay.SetDimensions(ScaleY - 4, -ScaleY + 4, -ScaleX + 1, ScaleX - 1, 0); textField.DisplayText = textToDisplay; } public override void ClearEvents() { base.ClearEvents(); OkClick = null; CancelClick = null; } public void LoseFocus() { } public void OnGainFocus() { if (GainFocus != null) GainFocus(this); } public void ReceiveInput() { #if FRB_MDX if (InputManager.Keyboard.KeyReleased(Keys.Return)) #else if (InputManager.Keyboard.KeyReleased(Keys.Enter)) #endif { mOkButton.OnClick(); } if (InputManager.Keyboard.KeyReleased(Keys.Escape)) { cancelButton.OnClick(); } } public void Update() { float top = this.ScaleY; float right = this.ScaleX; double tempTop, tempBottom, tempLeft, tempRight; for (int i = 0; i < base.mChildren.Count; i++) { if (mChildren[i] != mOkButton && mChildren[i] != cancelButton) { tempTop = mChildren[i].WorldUnitRelativeY + mChildren[i].ScaleY + 2.4f; tempBottom = mChildren[i].WorldUnitRelativeY - mChildren[i].ScaleY - 2.5f; tempLeft = mChildren[i].WorldUnitRelativeX - mChildren[i].ScaleX - .3f; tempRight = mChildren[i].WorldUnitRelativeX + mChildren[i].ScaleX + .3f; if (tempTop > top) top = (float)tempTop; if (tempBottom < -top) top = -(float)tempBottom; if (tempRight > right) right = (float)tempRight; if (tempLeft < -right) right = -(float)tempLeft; } } if (top < 3) top = 3; if (right < 6) right = 6; this.mScaleX = right; this.mScaleY = top; textField.SetDimensions( (float)ScaleY - 2, (float)-ScaleY + 4, (float)(mWorldUnitX - ScaleX + 1), (float)(mWorldUnitX + ScaleX - 1), 0); textField.mZ = 100; textField.RelativeToCamera = true; mOkButton.SetPositionTL(right / 2.0f, 2 * top - 1.5f); mOkButton.ScaleX = right / 2.0f - .3f; cancelButton.SetPositionTL(3 * right / 2.0f, 2 * top - 1.5f); cancelButton.ScaleX = right / 2.0f - .3f; } #endregion #region Internal Methods internal override void DrawSelfAndChildren(Camera camera) { #if !SILVERLIGHT base.DrawSelfAndChildren(camera); textField.SetDimensions( (float)(mWorldUnitY + ScaleY - .5f), (float)(mWorldUnitY - ScaleY + 4), (float)(mWorldUnitX - ScaleX + 1), (float)(mWorldUnitX + ScaleX - 1), 100); textField.TextHeight = GuiManager.TextHeight; textField.RelativeToCamera = false; TextManager.mRedForVertexBuffer = TextManager.mGreenForVertexBuffer = TextManager.mBlueForVertexBuffer = 20; TextManager.mScaleForVertexBuffer = GuiManager.TextHeight / 2.0f; TextManager.mSpacingForVertexBuffer = GuiManager.TextSpacing; TextManager.mNewLineDistanceForVertexBuffer = 2.0f; textField.mZ = camera.Z + 100 * FlatRedBall.Math.MathFunctions.ForwardVector3.Z; TextManager.Draw(textField); #endif } internal override int GetNumberOfVerticesToDraw() { return base.GetNumberOfVerticesToDraw() + textField.DisplayText.Replace("\n", "").Replace(" ", "").Length * 6; } #endregion #endregion } }
// This is a copy of the 7-zip LZMA // compression library. using System; namespace LZMA { public class BinTree : InWindow, IMatchFinder { UInt32 _cyclicBufferPos; UInt32 _cyclicBufferSize = 0; UInt32 _matchMaxLen; UInt32[] _son; UInt32[] _hash; UInt32 _cutValue = 0xFF; UInt32 _hashMask; UInt32 _hashSizeSum = 0; bool HASH_ARRAY = true; const UInt32 kHash2Size = 1 << 10; const UInt32 kHash3Size = 1 << 16; const UInt32 kBT2HashSize = 1 << 16; const UInt32 kStartMaxLen = 1; const UInt32 kHash3Offset = kHash2Size; const UInt32 kEmptyHashValue = 0; const UInt32 kMaxValForNormalize = ((UInt32)1 << 31) - 1; UInt32 kNumHashDirectBytes = 0; UInt32 kMinMatchCheck = 4; UInt32 kFixHashSize = kHash2Size + kHash3Size; public void SetType(int numHashBytes) { HASH_ARRAY = (numHashBytes > 2); if (HASH_ARRAY) { kNumHashDirectBytes = 0; kMinMatchCheck = 4; kFixHashSize = kHash2Size + kHash3Size; } else { kNumHashDirectBytes = 2; kMinMatchCheck = 2 + 1; kFixHashSize = 0; } } public new void SetStream(System.IO.Stream stream) { base.SetStream(stream); } public new void ReleaseStream() { base.ReleaseStream(); } public new void Init() { base.Init(); for (UInt32 i = 0; i < _hashSizeSum; i++) _hash[i] = kEmptyHashValue; _cyclicBufferPos = 0; ReduceOffsets(-1); } public new void MovePos() { if (++_cyclicBufferPos >= _cyclicBufferSize) _cyclicBufferPos = 0; base.MovePos(); if (_pos == kMaxValForNormalize) Normalize(); } public new Byte GetIndexByte(Int32 index) { return base.GetIndexByte(index); } public new UInt32 GetMatchLen(Int32 index, UInt32 distance, UInt32 limit) { return base.GetMatchLen(index, distance, limit); } public new UInt32 GetNumAvailableBytes() { return base.GetNumAvailableBytes(); } public void Create(UInt32 historySize, UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter) { if (historySize > kMaxValForNormalize - 256) throw new Exception(); _cutValue = 16 + (matchMaxLen >> 1); UInt32 windowReservSize = (historySize + keepAddBufferBefore + matchMaxLen + keepAddBufferAfter) / 2 + 256; base.Create(historySize + keepAddBufferBefore, matchMaxLen + keepAddBufferAfter, windowReservSize); _matchMaxLen = matchMaxLen; UInt32 cyclicBufferSize = historySize + 1; if (_cyclicBufferSize != cyclicBufferSize) _son = new UInt32[(_cyclicBufferSize = cyclicBufferSize) * 2]; UInt32 hs = kBT2HashSize; if (HASH_ARRAY) { hs = historySize - 1; hs |= (hs >> 1); hs |= (hs >> 2); hs |= (hs >> 4); hs |= (hs >> 8); hs >>= 1; hs |= 0xFFFF; if (hs > (1 << 24)) hs >>= 1; _hashMask = hs; hs++; hs += kFixHashSize; } if (hs != _hashSizeSum) _hash = new UInt32[_hashSizeSum = hs]; } public UInt32 GetMatches(UInt32[] distances) { UInt32 lenLimit; if (_pos + _matchMaxLen <= _streamPos) lenLimit = _matchMaxLen; else { lenLimit = _streamPos - _pos; if (lenLimit < kMinMatchCheck) { MovePos(); return 0; } } UInt32 offset = 0; UInt32 matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0; UInt32 cur = _bufferOffset + _pos; UInt32 maxLen = kStartMaxLen; // to avoid items for len < hashSize; UInt32 hashValue, hash2Value = 0, hash3Value = 0; if (HASH_ARRAY) { UInt32 temp = CRC.Table[_bufferBase[cur]] ^ _bufferBase[cur + 1]; hash2Value = temp & (kHash2Size - 1); temp ^= ((UInt32)(_bufferBase[cur + 2]) << 8); hash3Value = temp & (kHash3Size - 1); hashValue = (temp ^ (CRC.Table[_bufferBase[cur + 3]] << 5)) & _hashMask; } else hashValue = _bufferBase[cur] ^ ((UInt32)(_bufferBase[cur + 1]) << 8); UInt32 curMatch = _hash[kFixHashSize + hashValue]; if (HASH_ARRAY) { UInt32 curMatch2 = _hash[hash2Value]; UInt32 curMatch3 = _hash[kHash3Offset + hash3Value]; _hash[hash2Value] = _pos; _hash[kHash3Offset + hash3Value] = _pos; if (curMatch2 > matchMinPos) if (_bufferBase[_bufferOffset + curMatch2] == _bufferBase[cur]) { distances[offset++] = maxLen = 2; distances[offset++] = _pos - curMatch2 - 1; } if (curMatch3 > matchMinPos) if (_bufferBase[_bufferOffset + curMatch3] == _bufferBase[cur]) { if (curMatch3 == curMatch2) offset -= 2; distances[offset++] = maxLen = 3; distances[offset++] = _pos - curMatch3 - 1; curMatch2 = curMatch3; } if (offset != 0 && curMatch2 == curMatch) { offset -= 2; maxLen = kStartMaxLen; } } _hash[kFixHashSize + hashValue] = _pos; UInt32 ptr0 = (_cyclicBufferPos << 1) + 1; UInt32 ptr1 = (_cyclicBufferPos << 1); UInt32 len0, len1; len0 = len1 = kNumHashDirectBytes; if (kNumHashDirectBytes != 0) { if (curMatch > matchMinPos) { if (_bufferBase[_bufferOffset + curMatch + kNumHashDirectBytes] != _bufferBase[cur + kNumHashDirectBytes]) { distances[offset++] = maxLen = kNumHashDirectBytes; distances[offset++] = _pos - curMatch - 1; } } } UInt32 count = _cutValue; while(true) { if(curMatch <= matchMinPos || count-- == 0) { _son[ptr0] = _son[ptr1] = kEmptyHashValue; break; } UInt32 delta = _pos - curMatch; UInt32 cyclicPos = ((delta <= _cyclicBufferPos) ? (_cyclicBufferPos - delta) : (_cyclicBufferPos - delta + _cyclicBufferSize)) << 1; UInt32 pby1 = _bufferOffset + curMatch; UInt32 len = Math.Min(len0, len1); if (_bufferBase[pby1 + len] == _bufferBase[cur + len]) { while(++len != lenLimit) if (_bufferBase[pby1 + len] != _bufferBase[cur + len]) break; if (maxLen < len) { distances[offset++] = maxLen = len; distances[offset++] = delta - 1; if (len == lenLimit) { _son[ptr1] = _son[cyclicPos]; _son[ptr0] = _son[cyclicPos + 1]; break; } } } if (_bufferBase[pby1 + len] < _bufferBase[cur + len]) { _son[ptr1] = curMatch; ptr1 = cyclicPos + 1; curMatch = _son[ptr1]; len1 = len; } else { _son[ptr0] = curMatch; ptr0 = cyclicPos; curMatch = _son[ptr0]; len0 = len; } } MovePos(); return offset; } public void Skip(UInt32 num) { do { UInt32 lenLimit; if (_pos + _matchMaxLen <= _streamPos) lenLimit = _matchMaxLen; else { lenLimit = _streamPos - _pos; if (lenLimit < kMinMatchCheck) { MovePos(); continue; } } UInt32 matchMinPos = (_pos > _cyclicBufferSize) ? (_pos - _cyclicBufferSize) : 0; UInt32 cur = _bufferOffset + _pos; UInt32 hashValue; if (HASH_ARRAY) { UInt32 temp = CRC.Table[_bufferBase[cur]] ^ _bufferBase[cur + 1]; UInt32 hash2Value = temp & (kHash2Size - 1); _hash[hash2Value] = _pos; temp ^= ((UInt32)(_bufferBase[cur + 2]) << 8); UInt32 hash3Value = temp & (kHash3Size - 1); _hash[kHash3Offset + hash3Value] = _pos; hashValue = (temp ^ (CRC.Table[_bufferBase[cur + 3]] << 5)) & _hashMask; } else hashValue = _bufferBase[cur] ^ ((UInt32)(_bufferBase[cur + 1]) << 8); UInt32 curMatch = _hash[kFixHashSize + hashValue]; _hash[kFixHashSize + hashValue] = _pos; UInt32 ptr0 = (_cyclicBufferPos << 1) + 1; UInt32 ptr1 = (_cyclicBufferPos << 1); UInt32 len0, len1; len0 = len1 = kNumHashDirectBytes; UInt32 count = _cutValue; while (true) { if (curMatch <= matchMinPos || count-- == 0) { _son[ptr0] = _son[ptr1] = kEmptyHashValue; break; } UInt32 delta = _pos - curMatch; UInt32 cyclicPos = ((delta <= _cyclicBufferPos) ? (_cyclicBufferPos - delta) : (_cyclicBufferPos - delta + _cyclicBufferSize)) << 1; UInt32 pby1 = _bufferOffset + curMatch; UInt32 len = Math.Min(len0, len1); if (_bufferBase[pby1 + len] == _bufferBase[cur + len]) { while (++len != lenLimit) if (_bufferBase[pby1 + len] != _bufferBase[cur + len]) break; if (len == lenLimit) { _son[ptr1] = _son[cyclicPos]; _son[ptr0] = _son[cyclicPos + 1]; break; } } if (_bufferBase[pby1 + len] < _bufferBase[cur + len]) { _son[ptr1] = curMatch; ptr1 = cyclicPos + 1; curMatch = _son[ptr1]; len1 = len; } else { _son[ptr0] = curMatch; ptr0 = cyclicPos; curMatch = _son[ptr0]; len0 = len; } } MovePos(); } while (--num != 0); } void NormalizeLinks(UInt32[] items, UInt32 numItems, UInt32 subValue) { for (UInt32 i = 0; i < numItems; i++) { UInt32 value = items[i]; if (value <= subValue) value = kEmptyHashValue; else value -= subValue; items[i] = value; } } void Normalize() { UInt32 subValue = _pos - _cyclicBufferSize; NormalizeLinks(_son, _cyclicBufferSize * 2, subValue); NormalizeLinks(_hash, _hashSizeSum, subValue); ReduceOffsets((Int32)subValue); } public void SetCutValue(UInt32 cutValue) { _cutValue = cutValue; } } }
using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.SqlServerCe; using System.Collections; using System.Windows.Forms; using DowUtils; namespace Factotum{ public class EDucerModel : IEntity { public static event EventHandler<EntityChangedEventArgs> Changed; public static event EventHandler MeterModelAssignmentsChanged; protected virtual void OnChanged(Guid? ID) { // Copy to a temporary variable to be thread-safe. EventHandler<EntityChangedEventArgs> temp = Changed; if (temp != null) temp(this, new EntityChangedEventArgs(ID)); } protected virtual void OnMeterModelAssignmentsChanged() { EventHandler temp = MeterModelAssignmentsChanged; if (temp != null) temp(this, new EventArgs()); } // Mapped database columns // Use Guid?s for Primary Keys and foreign keys (whether they're nullable or not). // Use int?, decimal?, etc for numbers (whether they're nullable or not). // Strings, images, etc, are reference types already private Guid? DmdDBid; private string DmdName; private decimal? DmdFrequency; private decimal? DmdSize; private bool DmdIsLclChg; private bool DmdUsedInOutage; private bool DmdIsActive; // Textbox limits public static int DmdNameCharLimit = 50; public static int DmdFrequencyCharLimit = 6; public static int DmdSizeCharLimit = 6; // Field-specific error message strings (normally just needed for textbox data) private string DmdNameErrMsg; private string DmdFrequencyErrMsg; private string DmdSizeErrMsg; // Form level validation message private string DmdErrMsg; //-------------------------------------------------------- // Field Properties //-------------------------------------------------------- // Primary key accessor public Guid? ID { get { return DmdDBid; } } public string DucerModelName { get { return DmdName; } set { DmdName = Util.NullifyEmpty(value); } } public decimal? DucerModelFrequency { get { return DmdFrequency; } set { DmdFrequency = value; } } public decimal? DucerModelSize { get { return DmdSize; } set { DmdSize = value; } } public bool DucerModelIsLclChg { get { return DmdIsLclChg; } set { DmdIsLclChg = value; } } public bool DucerModelUsedInOutage { get { return DmdUsedInOutage; } set { DmdUsedInOutage = value; } } public bool DucerModelIsActive { get { return DmdIsActive; } set { DmdIsActive = value; } } //----------------------------------------------------------------- // Field Level Error Messages. // Include one for every text column // In cases where we need to ensure data consistency, we may need // them for other types. //----------------------------------------------------------------- public string DucerModelNameErrMsg { get { return DmdNameErrMsg; } } public string DucerModelFrequencyErrMsg { get { return DmdFrequencyErrMsg; } } public string DucerModelSizeErrMsg { get { return DmdSizeErrMsg; } } //-------------------------------------- // Form level Error Message //-------------------------------------- public string DucerModelErrMsg { get { return DmdErrMsg; } set { DmdErrMsg = Util.NullifyEmpty(value); } } //-------------------------------------- // Textbox Name Length Validation //-------------------------------------- public bool DucerModelNameLengthOk(string s) { if (s == null) return true; if (s.Length > DmdNameCharLimit) { DmdNameErrMsg = string.Format("Transducer Model Names cannot exceed {0} characters", DmdNameCharLimit); return false; } else { DmdNameErrMsg = null; return true; } } public bool DucerModelFrequencyLengthOk(string s) { if (s == null) return true; if (s.Length > DmdFrequencyCharLimit) { DmdFrequencyErrMsg = string.Format("Transducer Model Frequencies cannot exceed {0} characters", DmdFrequencyCharLimit); return false; } else { DmdFrequencyErrMsg = null; return true; } } public bool DucerModelSizeLengthOk(string s) { if (s == null) return true; if (s.Length > DmdSizeCharLimit) { DmdSizeErrMsg = string.Format("Transducer Model Sizes cannot exceed {0} characters", DmdSizeCharLimit); return false; } else { DmdSizeErrMsg = null; return true; } } //-------------------------------------- // Field-Specific Validation // sets and clears error messages //-------------------------------------- public bool DucerModelNameValid(string name) { bool existingIsInactive; if (!DucerModelNameLengthOk(name)) return false; // KEEP, MODIFY OR REMOVE THIS AS REQUIRED // YOU MAY NEED THE NAME TO BE UNIQUE FOR A SPECIFIC PARENT, ETC.. if (NameExists(name, DmdDBid, out existingIsInactive)) { DmdNameErrMsg = existingIsInactive ? "A Transducer Model with that name exists but its status has been set to inactive." : "That Transducer Model Name is already in use."; return false; } DmdNameErrMsg = null; return true; } public bool DucerModelFrequencyValid(string value) { decimal result; if (Util.IsNullOrEmpty(value)) { DmdFrequencyErrMsg = null; return true; } if (decimal.TryParse(value, out result) && result > 0 && result <= 100) { DmdFrequencyErrMsg = null; return true; } DmdFrequencyErrMsg = string.Format("Please enter a positive number less than 100"); return false; } public bool DucerModelSizeValid(string value) { decimal result; if (Util.IsNullOrEmpty(value)) { DmdSizeErrMsg = null; return true; } if (decimal.TryParse(value, out result) && result > 0 && result < 10) { DmdSizeErrMsg = null; return true; } DmdSizeErrMsg = string.Format("Please enter a positive number less than 10"); return false; } //-------------------------------------- // Constructors //-------------------------------------- // Default constructor. Field defaults must be set here. // Any defaults set by the database will be overridden. public EDucerModel() { this.DmdIsLclChg = false; this.DmdUsedInOutage = false; this.DmdIsActive = true; } // Constructor which loads itself from the supplied id. // If the id is null, this gives the same result as using the default constructor. public EDucerModel(Guid? id) : this() { Load(id); } //-------------------------------------- // Public Methods //-------------------------------------- //---------------------------------------------------- // Load the object from the database given a Guid? //---------------------------------------------------- public void Load(Guid? id) { if (id == null) return; SqlCeCommand cmd = Globals.cnn.CreateCommand(); SqlCeDataReader dr; cmd.CommandType = CommandType.Text; cmd.CommandText = @"Select DmdDBid, DmdName, DmdFrequency, DmdSize, DmdIsLclChg, DmdUsedInOutage, DmdIsActive from DucerModels where DmdDBid = @p0"; cmd.Parameters.Add(new SqlCeParameter("@p0", id)); if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); dr = cmd.ExecuteReader(); // The query should return one record. // If it doesn't return anything (no match) the object is not affected if (dr.Read()) { // For all nullable values, replace dbNull with null DmdDBid = (Guid?)dr[0]; DmdName = (string)dr[1]; DmdFrequency = (decimal?)dr[2]; DmdSize = (decimal?)dr[3]; DmdIsLclChg = (bool)dr[4]; DmdUsedInOutage = (bool)dr[5]; DmdIsActive = (bool)dr[6]; } dr.Close(); } //-------------------------------------- // Save the current record if it's valid //-------------------------------------- public Guid? Save() { if (!Valid()) { // Note: We're returning null if we fail, // so don't just assume you're going to get your id back // and set your id to the result of this function call. return null; } SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; if (ID == null) { // we are inserting a new record // If this is not a master db, set the local change flag to true. if (!Globals.IsMasterDB) DmdIsLclChg = true; // first ask the database for a new Guid cmd.CommandText = "Select Newid()"; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); DmdDBid = (Guid?)(cmd.ExecuteScalar()); // Replace any nulls with dbnull cmd.Parameters.AddRange(new SqlCeParameter[] { new SqlCeParameter("@p0", DmdDBid), new SqlCeParameter("@p1", DmdName), new SqlCeParameter("@p2", DmdFrequency), new SqlCeParameter("@p3", DmdSize), new SqlCeParameter("@p4", DmdIsLclChg), new SqlCeParameter("@p5", DmdUsedInOutage), new SqlCeParameter("@p6", DmdIsActive) }); cmd.CommandText = @"Insert Into DucerModels ( DmdDBid, DmdName, DmdFrequency, DmdSize, DmdIsLclChg, DmdUsedInOutage, DmdIsActive ) values (@p0,@p1,@p2,@p3,@p4,@p5,@p6)"; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); if (cmd.ExecuteNonQuery() != 1) { throw new Exception("Unable to insert Transducer Models row"); } } else { // we are updating an existing record // Replace any nulls with dbnull cmd.Parameters.AddRange(new SqlCeParameter[] { new SqlCeParameter("@p0", DmdDBid), new SqlCeParameter("@p1", DmdName), new SqlCeParameter("@p2", DmdFrequency), new SqlCeParameter("@p3", DmdSize), new SqlCeParameter("@p4", DmdIsLclChg), new SqlCeParameter("@p5", DmdUsedInOutage), new SqlCeParameter("@p6", DmdIsActive)}); cmd.CommandText = @"Update DucerModels set DmdName = @p1, DmdFrequency = @p2, DmdSize = @p3, DmdIsLclChg = @p4, DmdUsedInOutage = @p5, DmdIsActive = @p6 Where DmdDBid = @p0"; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); if (cmd.ExecuteNonQuery() != 1) { throw new Exception("Unable to update Transducer models row"); } } OnChanged(ID); return ID; } //-------------------------------------- // Validate the current record //-------------------------------------- // Make this public so that the UI can check validation itself // if it chooses to do so. This is also called by the Save function. public bool Valid() { // First check each field to see if it's valid from the UI perspective if (!DucerModelNameValid(DucerModelName)) return false; // Check form to make sure all required fields have been filled in if (!RequiredFieldsFilled()) return false; // Check for incorrect field interactions... return true; } //-------------------------------------- // Delete the current record //-------------------------------------- public bool Delete(bool promptUser) { // If the current object doesn't reference a database record, there's nothing to do. if (DmdDBid == null) { DucerModelErrMsg = "Unable to delete. Record not found."; return false; } if (!DmdIsLclChg && !Globals.IsMasterDB) { DucerModelErrMsg = "Unable to delete this Transducer Model because it was not added during this outage.\r\nYou may wish to inactivate it instead."; return false; } if (HasChildren()) { DucerModelErrMsg = "Unable to delete because this Transducer Model is referenced by Transducers."; return false; } DialogResult rslt = DialogResult.None; if (promptUser) { rslt = MessageBox.Show("Are you sure?", "Factotum: Deleting...", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); } if (!promptUser || rslt == DialogResult.OK) { SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = @"Delete from DucerModels where DmdDBid = @p0"; cmd.Parameters.Add("@p0", DmdDBid); if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); int rowsAffected = cmd.ExecuteNonQuery(); // Todo: figure out how I really want to do this. // Is there a problem with letting the database try to do cascading deletes? // How should the user be notified of the problem?? if (rowsAffected < 1) { DucerModelErrMsg = "Unable to delete. Please try again later."; return false; } else { DucerModelErrMsg = null; OnChanged(ID); return true; } } else { return false; } } private bool HasChildren() { SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandText = @"Select DcrDBid from Ducers where DcrDmdID = @p0"; cmd.Parameters.Add("@p0", DmdDBid); if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); object result = cmd.ExecuteScalar(); return result != null; } //-------------------------------------------------------------------- // Static listing methods which return collections of ducermodels //-------------------------------------------------------------------- // This helper function builds the collection for you based on the flags you send it // I originally had a flag that would let you indicate inactive items by appending '(inactive)' // to the name. This was a bad idea, because sometimes the objects in this collection // will get modified and saved back to the database -- with the extra text appended to the name. public static EDucerModelCollection ListByName( bool showactive, bool showinactive, bool addNoSelection) { EDucerModel ducermodel; EDucerModelCollection ducermodels = new EDucerModelCollection(); SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; string qry = @"Select DmdDBid, DmdName, DmdFrequency, DmdSize, DmdIsLclChg, DmdUsedInOutage, DmdIsActive from DucerModels"; if (showactive && !showinactive) qry += " where DmdIsActive = 1"; else if (!showactive && showinactive) qry += " where DmdIsActive = 0"; qry += " order by DmdName"; cmd.CommandText = qry; if (addNoSelection) { // Insert a default item with name "<No Selection>" ducermodel = new EDucerModel(); ducermodel.DmdName = "<No Selection>"; ducermodels.Add(ducermodel); } SqlCeDataReader dr; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); dr = cmd.ExecuteReader(); // Build new objects and add them to the collection while (dr.Read()) { ducermodel = new EDucerModel((Guid?)dr[0]); ducermodel.DmdName = (string)(dr[1]); ducermodel.DmdFrequency = (decimal?)(dr[2]); ducermodel.DmdSize = (decimal?)(dr[3]); ducermodel.DmdIsLclChg = (bool)(dr[4]); ducermodel.DmdUsedInOutage = (bool)(dr[5]); ducermodel.DmdIsActive = (bool)(dr[6]); ducermodels.Add(ducermodel); } // Finish up dr.Close(); return ducermodels; } // Get a Default data view with all columns that a user would likely want to see. // You can bind this view to a DataGridView, hide the columns you don't need, filter, etc. // I decided not to indicate inactive in the names of inactive items. The 'user' // can always show the inactive column if they wish. public static DataView GetDefaultDataView() { DataSet ds = new DataSet(); DataView dv; SqlCeDataAdapter da = new SqlCeDataAdapter(); SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; // Changing the booleans to 'Yes' and 'No' eliminates the silly checkboxes and // makes the column sortable. // You'll likely want to modify this query further, joining in other tables, etc. string qry = @"Select DmdDBid as ID, DmdName as DucerModelName, DmdFrequency as DucerModelFrequency, DmdSize as DucerModelSize, CASE WHEN DmdIsLclChg = 0 THEN 'No' ELSE 'Yes' END as DucerModelIsLclChg, CASE WHEN DmdUsedInOutage = 0 THEN 'No' ELSE 'Yes' END as DucerModelUsedInOutage, CASE WHEN DmdIsActive = 0 THEN 'No' ELSE 'Yes' END as DucerModelIsActive from DucerModels"; cmd.CommandText = qry; da.SelectCommand = cmd; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); da.Fill(ds); dv = new DataView(ds.Tables[0]); return dv; } // Get a data table for use with a checked list box that allows the user to // check off the ducer models that work with a given meter. public static DataTable GetWithAssignmentsForMeterModel(Guid? meterModelID, bool showinactive) { // If we are passed a null meter model id, such as for a newly created record, // we still want to run the query and return the table. DataSet ds = new DataSet(); SqlCeDataAdapter da = new SqlCeDataAdapter(); SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; string qry = @" Select DmdDBid as ID, DmdName as DucerModelName, DmdIsActive as DucerModelIsActive, Max(Case MeterDucers.MtdMmlID when @p1 then 1 else 0 end) as IsAssigned From DucerModels left outer join MeterDucers on DucerModels.DmdDBid = MeterDucers.MtdDmdID"; if (!showinactive) qry += @" where DmdIsActive = 1"; qry += @" Group by DmdName, DmdDBid, DmdIsActive"; cmd.CommandText = qry; cmd.Parameters.Add("@p1", meterModelID == null ? Guid.Empty : meterModelID); da.SelectCommand = cmd; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); da.Fill(ds); return ds.Tables[0]; } public static void UpdateAssignmentsToMeterModel(Guid? meterModelID, DataTable assignments) { SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; // First delete any existing assignments cmd.CommandText = "Delete from MeterDucers where MtdMmlID = @p1"; cmd.Parameters.Add("@p1", meterModelID); if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); cmd.ExecuteNonQuery(); cmd = Globals.cnn.CreateCommand(); cmd.Parameters.Add("@p1", meterModelID); cmd.Parameters.Add("@p2", ""); cmd.CommandText = @" Insert Into MeterDucers (MtdMmlID, MtdDmdID) values (@p1, @p2)"; // Now insert the current ducer assignments for (int dmRow = 0; dmRow < assignments.Rows.Count; dmRow++) { if (Convert.ToBoolean(assignments.Rows[dmRow]["IsAssigned"])) { cmd.Parameters["@p2"].Value = (Guid)assignments.Rows[dmRow]["ID"]; if (cmd.ExecuteNonQuery() != 1) { throw new Exception("Unable to assign Transducer to meter"); } } } EDucerModel ducerMdl = new EDucerModel(); ducerMdl.OnMeterModelAssignmentsChanged(); } //-------------------------------------- // Private utilities //-------------------------------------- // Check if the name exists for any records besides the current one // This is used to show an error when the user tabs away from the field. // We don't want to show an error if the user has left the field blank. // If it's a required field, we'll catch it when the user hits save. private bool NameExists(string name, Guid? id, out bool existingIsInactive) { existingIsInactive = false; if (Util.IsNullOrEmpty(name)) return false; SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.Parameters.Add(new SqlCeParameter("@p1", name)); if (id == null) { cmd.CommandText = "Select DmdIsActive from DucerModels where DmdName = @p1"; } else { cmd.CommandText = "Select DmdIsActive from DucerModels where DmdName = @p1 and DmdDBid != @p0"; cmd.Parameters.Add(new SqlCeParameter("@p0", id)); } if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); object val = cmd.ExecuteScalar(); bool exists = (val != null); if (exists) existingIsInactive = !(bool)val; return exists; } // Check for required fields, setting the individual error messages private bool RequiredFieldsFilled() { bool allFilled = true; if (DucerModelName == null) { DmdNameErrMsg = "A unique Transducer Model Name is required"; allFilled = false; } else { DmdNameErrMsg = null; } if (DucerModelFrequency == null) { DmdFrequencyErrMsg = "A Transducer Model Frequency is required"; allFilled = false; } else { DmdFrequencyErrMsg = null; } if (DucerModelSize == null) { DmdSizeErrMsg = "A Transducer Model Size is required"; allFilled = false; } else { DmdSizeErrMsg = null; } return allFilled; } } //-------------------------------------- // DucerModel Collection class //-------------------------------------- public class EDucerModelCollection : CollectionBase { //this event is fired when the collection's items have changed public event EventHandler Changed; //this is the constructor of the collection. public EDucerModelCollection() { } //the indexer of the collection public EDucerModel this[int index] { get { return (EDucerModel)this.List[index]; } } //this method fires the Changed event. protected virtual void OnChanged(EventArgs e) { if (Changed != null) { Changed(this, e); } } public bool ContainsID(Guid? ID) { if (ID == null) return false; foreach (EDucerModel ducermodel in InnerList) { if (ducermodel.ID == ID) return true; } return false; } //returns the index of an item in the collection public int IndexOf(EDucerModel item) { return InnerList.IndexOf(item); } //adds an item to the collection public void Add(EDucerModel item) { this.List.Add(item); OnChanged(EventArgs.Empty); } //inserts an item in the collection at a specified index public void Insert(int index, EDucerModel item) { this.List.Insert(index, item); OnChanged(EventArgs.Empty); } //removes an item from the collection. public void Remove(EDucerModel item) { this.List.Remove(item); OnChanged(EventArgs.Empty); } } }
using System; using System.Collections.Generic; using System.Linq; using Qwack.Core.Basic; using Qwack.Core.Curves; using Qwack.Core.Instruments; using Qwack.Core.Instruments.Asset; using Qwack.Core.Cubes; using Qwack.Dates; using Qwack.Math.Interpolation; using Qwack.Models; using Qwack.Models.Models; using Qwack.Providers.Json; using Xunit; using Qwack.Utils.Parallel; using Qwack.Transport.BasicTypes; using static Qwack.Core.Basic.Consts.Cubes; namespace Qwack.Core.Tests.AssetModel { public class FxDeltaFacts { [Fact] public void FxDeltaOnUSDTrade() { ParallelUtils.Instance.MultiThreaded = false; var startDate = new DateTime(2018, 07, 28); var cal = TestProviderHelper.CalendarProvider.Collection["LON"]; var zar = TestProviderHelper.CurrencyProvider["ZAR"]; var usd = TestProviderHelper.CurrencyProvider["USD"]; var curvePillars = new[] { "1W", "1M", "3M", "6M", "1Y" }; var curvePillarDates = curvePillars.Select(l => startDate.AddPeriod(RollType.F, cal, new Frequency(l))).ToArray(); var curvePoints = new[] { 100.0, 100, 100, 100, 100 }; var curve = new BasicPriceCurve(startDate, curvePillarDates, curvePoints, PriceCurveType.LME,TestProviderHelper.CurrencyProvider, curvePillars) { Currency = usd, CollateralSpec = "CURVE", Name = "Coconuts" }; var fxMatrix = new FxMatrix(TestProviderHelper.CurrencyProvider); var fxSpot = 15; var rates = new Dictionary<Currency, double> { { zar, fxSpot } }; var discoMap = new Dictionary<Currency, string> { { zar, "ZAR.CURVE" }, { usd, "USD.CURVE" } }; var fxPair = new FxPair() { Domestic = usd, Foreign = zar, PrimaryCalendar = cal, SpotLag = new Frequency("0b") }; fxMatrix.Init(usd, startDate, rates, new List<FxPair> { fxPair }, discoMap); var irPillars = new[] { startDate, startDate.AddYears(10) }; var zarRates = new[] { 0.0, 0.0 }; var usdRates = new[] { 0.0, 0.0 }; var zarCurve = new IrCurve(irPillars, zarRates, startDate, "ZAR.CURVE", Interpolator1DType.Linear, zar, "CURVE"); var usdCurve = new IrCurve(irPillars, usdRates, startDate, "USD.CURVE", Interpolator1DType.Linear, usd, "CURVE"); var fModel = new FundingModel(startDate, new[] { zarCurve, usdCurve }, TestProviderHelper.CurrencyProvider, TestProviderHelper.CalendarProvider); fModel.SetupFx(fxMatrix); var aModel = new AssetFxModel(startDate, fModel); aModel.AddPriceCurve("Coconuts", curve); var periodCode = "SEP-18"; var (Start, End) = periodCode.ParsePeriod(); var fixingDates = Start.BusinessDaysInPeriod(End, cal).ToArray(); var settleDate = fixingDates.Last().AddPeriod(RollType.F, cal, new Frequency("5b")); var fxFwd = aModel.FundingModel.GetFxAverage(fixingDates, usd, zar); var assetFwd = curve.GetAveragePriceForDates(fixingDates); var fairStrike = assetFwd; var strike = fairStrike - 10; var nominal = 1000; var asianSwap = AssetProductFactory.CreateMonthlyAsianSwap(periodCode, strike, "Coconuts", cal, cal, new Frequency("5b"), usd, TradeDirection.Long, new Frequency("0b"), nominal, DateGenerationType.BusinessDays); asianSwap.TradeId = "aLovelyBunch"; foreach (var sw in asianSwap.Swaplets) { sw.DiscountCurve = "USD.CURVE"; sw.FxConversionType = FxConversionType.None; } var pv = asianSwap.PV(aModel, false); var expectedPV = (fairStrike - strike) * nominal; Assert.Equal(expectedPV, pv, 8); var portfolio = new Portfolio() { Instruments = new List<IInstrument> { asianSwap } }; var pfPvCube = portfolio.PV(aModel, usd); var pfPv = (double)pfPvCube.GetAllRows().First().Value; Assert.Equal(expectedPV, pfPv, 8); //expected fx delta is just PV in USD var deltaCube = portfolio.FxDelta(aModel, zar, TestProviderHelper.CurrencyProvider); var dAgg = deltaCube.Pivot(TradeId, AggregationAction.Sum); var delta = (double)dAgg.GetAllRows().First().Value; Assert.Equal(expectedPV, delta, 4); } [Fact] public void FxDeltaOnCompoZARTrade() { var startDate = new DateTime(2018, 07, 28); var cal = TestProviderHelper.CalendarProvider.Collection["LON"]; var zar = TestProviderHelper.CurrencyProvider["ZAR"]; var usd = TestProviderHelper.CurrencyProvider["USD"]; var curvePillars = new[] { "1W", "1M", "3M", "6M", "1Y" }; var curvePillarDates = curvePillars.Select(l => startDate.AddPeriod(RollType.F, cal, new Frequency(l))).ToArray(); var curvePoints = new[] { 100.0, 100, 100, 100, 100 }; var curve = new BasicPriceCurve(startDate, curvePillarDates, curvePoints, PriceCurveType.LME,TestProviderHelper.CurrencyProvider, curvePillars) { Currency = usd, CollateralSpec = "CURVE", Name = "Coconuts" }; var fxMatrix = new FxMatrix(TestProviderHelper.CurrencyProvider); var fxSpot = 15; var rates = new Dictionary<Currency, double> { { zar, fxSpot } }; var discoMap = new Dictionary<Currency, string> { { zar, "ZAR.CURVE" }, { usd, "USD.CURVE" } }; var fxPair = new FxPair() { Domestic = usd, Foreign = zar, PrimaryCalendar = cal, SpotLag = new Frequency("0b") }; fxMatrix.Init(usd, startDate, rates, new List<FxPair> { fxPair }, discoMap); var irPillars = new[] { startDate, startDate.AddYears(10) }; var zarRates = new[] { 0.0, 0.0 }; var usdRates = new[] { 0.0, 0.0 }; var zarCurve = new IrCurve(irPillars, zarRates, startDate, "ZAR.CURVE", Interpolator1DType.Linear, zar, "CURVE"); var usdCurve = new IrCurve(irPillars, usdRates, startDate, "USD.CURVE", Interpolator1DType.Linear, usd, "CURVE"); var fModel = new FundingModel(startDate, new[] { zarCurve, usdCurve }, TestProviderHelper.CurrencyProvider, TestProviderHelper.CalendarProvider); fModel.SetupFx(fxMatrix); var aModel = new AssetFxModel(startDate, fModel); aModel.AddPriceCurve("Coconuts", curve); var periodCode = "SEP-18"; var (Start, End) = periodCode.ParsePeriod(); var fixingDates = Start.BusinessDaysInPeriod(End, cal).ToArray(); var settleDate = fixingDates.Last().AddPeriod(RollType.F, cal, new Frequency("5b")); var fxFwd = aModel.FundingModel.GetFxAverage(fixingDates, usd, zar); var assetFwd = curve.GetAveragePriceForDates(fixingDates); var fairStrike = assetFwd* fxFwd; var strike = fairStrike - 10; var nominal = 1000; var asianSwap = AssetProductFactory.CreateMonthlyAsianSwap(periodCode, strike, "Coconuts", cal, cal, new Frequency("5b"), zar, TradeDirection.Long, new Frequency("0b"), nominal, DateGenerationType.BusinessDays); asianSwap.TradeId = "aLovelyBunch"; asianSwap.MetaData.Add("Booo", "Baaa"); foreach (var sw in asianSwap.Swaplets) { sw.DiscountCurve = "USD.CURVE"; sw.FxConversionType = FxConversionType.None; } var pv = asianSwap.PV(aModel, false); var expectedPV = (fairStrike - strike) * nominal; Assert.Equal(expectedPV, pv, 8); var portfolio = new Portfolio() { Instruments = new List<IInstrument> { asianSwap } }; var pfPvCube = portfolio.PV(aModel, zar); var pfPv = (double)pfPvCube.GetAllRows().First().Value; Assert.Equal(expectedPV, pfPv, 8); //test meta data feeds to cube var booix = pfPvCube.GetColumnIndex("Booo"); Assert.Equal("Baaa", (string)pfPvCube.GetAllRows().First().MetaData[booix]); //expected fx delta is just asset delta in ZAR var deltaCube = portfolio.FxDelta(aModel, zar, TestProviderHelper.CurrencyProvider); var dAgg = deltaCube.Pivot(TradeId, AggregationAction.Sum); var delta = (double)dAgg.GetAllRows().First().Value; Assert.Equal(nominal * assetFwd, delta, 4); //change intrinsic value, fx delta does not change as intrinsic is in ZAR strike = fairStrike - 20; asianSwap = AssetProductFactory.CreateMonthlyAsianSwap(periodCode, strike, "Coconuts", cal, cal, new Frequency("5b"), zar, TradeDirection.Long, new Frequency("0b"), nominal, DateGenerationType.BusinessDays); asianSwap.TradeId = "aLovelyBunch"; foreach (var sw in asianSwap.Swaplets) { sw.DiscountCurve = "USD.CURVE"; sw.FxConversionType = FxConversionType.None; } pv = asianSwap.PV(aModel, false); expectedPV = (fairStrike - strike) * nominal; Assert.Equal(expectedPV, pv, 8); deltaCube = portfolio.FxDelta(aModel, zar, TestProviderHelper.CurrencyProvider); dAgg = deltaCube.Pivot(TradeId, AggregationAction.Sum); delta = (double)dAgg.GetAllRows().First().Value; Assert.Equal(nominal * assetFwd, delta, 4); } } }
/* * Copyright 2013 ThirdMotion, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @class strange.extensions.signal.impl.Signal * * This is actually a series of classes defining the Base concrete form for all Signals. * * Signals are a type-safe approach to communication that essentially replace the * standard EventDispatcher model. Signals can be injected/mapped just like any other * object -- as Singletons, as instances, or as values. Signals can even be mapped * across Contexts to provide an effective and type-safe way of communicating * between the parts of your application. * * Signals in Strange use the Action Class as the underlying mechanism for type safety. * Unity's C# implementation currently allows up to FOUR parameters in an Action, therefore * SIGNALS ARE LIMITED TO FOUR PARAMETERS. If you require more than four, consider * creating a value object to hold additional values. * * Examples: //BASIC SIGNAL CREATION/DISPATCH //Create a new signal Signal signalWithNoParameters = new Signal(); //Add a listener signalWithNoParameters.AddListener(callbackWithNoParameters); //This would throw a compile-time error signalWithNoParameters.AddListener(callbackWithOneParameter); //Dispatch signalWithNoParameters.Dispatch(); //Remove the listener signalWithNoParameters.RemoveListener(callbackWithNoParameters); //SIGNAL WITH PARAMETERS //Create a new signal with two parameters Signal<int, string> signal = new Signal<int, string>(); //Add a listener signal.AddListener(callbackWithParamsIntAndString); //Add a listener for the duration of precisely one Dispatch signal.AddOnce(anotherCallbackWithParamsIntAndString); //These all throw compile-time errors signal.AddListener(callbackWithParamsStringAndInt); signal.AddListener(callbackWithOneParameter); signal.AddListener(callbackWithNoParameters); //Dispatch signal.Dispatch(42, "zaphod"); //Remove the first listener. The listener added by AddOnce has been automatically removed. signal.RemoveListener(callbackWithParamsIntAndString); * * @see strange.extensions.signal.api.IBaseSignal * @see strange.extensions.signal.impl.BasrSignal */ using System; using System.Collections.Generic; using System.Linq; namespace strange.extensions.signal.impl { /// Base concrete form for a Signal with no parameters public class Signal : BaseSignal { public event Action Listener = delegate { }; public event Action OnceListener = delegate { }; public void AddListener(Action callback) { Listener = this.AddUnique(Listener, callback); } public void AddOnce(Action callback) { OnceListener = this.AddUnique(OnceListener, callback); } public void RemoveListener(Action callback) { Listener -= callback; } public override List<Type> GetTypes() { return new List<Type>(); } public void Dispatch() { Listener(); OnceListener(); OnceListener = delegate { }; base.Dispatch(null); } private Action AddUnique(Action listeners, Action callback) { if (!listeners.GetInvocationList().Contains(callback)) { listeners += callback; } return listeners; } } /// Base concrete form for a Signal with one parameter public class Signal<T> : BaseSignal { public event Action<T> Listener = delegate { }; public event Action<T> OnceListener = delegate { }; public void AddListener(Action<T> callback) { Listener = this.AddUnique(Listener, callback); } public void AddOnce(Action<T> callback) { OnceListener = this.AddUnique(OnceListener, callback); } public void RemoveListener(Action<T> callback) { Listener -= callback; } public override List<Type> GetTypes() { List<Type> retv = new List<Type>(); retv.Add(typeof(T)); return retv; } public void Dispatch(T type1) { Listener(type1); OnceListener(type1); OnceListener = delegate { }; object[] outv = { type1 }; base.Dispatch(outv); } private Action<T> AddUnique(Action<T> listeners, Action<T> callback) { if (!listeners.GetInvocationList().Contains(callback)) { listeners += callback; } return listeners; } } /// Base concrete form for a Signal with two parameters public class Signal<T, U> : BaseSignal { public event Action<T, U> Listener = delegate { }; public event Action<T, U> OnceListener = delegate { }; public void AddListener(Action<T, U> callback) { Listener = this.AddUnique(Listener, callback); } public void AddOnce(Action<T, U> callback) { OnceListener = this.AddUnique(OnceListener, callback); } public void RemoveListener(Action<T, U> callback) { Listener -= callback; } public override List<Type> GetTypes() { List<Type> retv = new List<Type>(); retv.Add(typeof(T)); retv.Add(typeof(U)); return retv; } public void Dispatch(T type1, U type2) { Listener(type1, type2); OnceListener(type1, type2); OnceListener = delegate { }; object[] outv = { type1, type2 }; base.Dispatch(outv); } private Action<T, U> AddUnique(Action<T, U> listeners, Action<T, U> callback) { if (!listeners.GetInvocationList().Contains(callback)) { listeners += callback; } return listeners; } } /// Base concrete form for a Signal with three parameters public class Signal<T, U, V> : BaseSignal { public event Action<T, U, V> Listener = delegate { }; public event Action<T, U, V> OnceListener = delegate { }; public void AddListener(Action<T, U, V> callback) { Listener = this.AddUnique(Listener, callback); } public void AddOnce(Action<T, U, V> callback) { OnceListener = this.AddUnique(OnceListener, callback); } public void RemoveListener(Action<T, U, V> callback) { Listener -= callback; } public override List<Type> GetTypes() { List<Type> retv = new List<Type>(); retv.Add(typeof(T)); retv.Add(typeof(U)); retv.Add(typeof(V)); return retv; } public void Dispatch(T type1, U type2, V type3) { Listener(type1, type2, type3); OnceListener(type1, type2, type3); OnceListener = delegate { }; object[] outv = { type1, type2, type3 }; base.Dispatch(outv); } private Action<T, U, V> AddUnique(Action<T, U, V> listeners, Action<T, U, V> callback) { if (!listeners.GetInvocationList().Contains(callback)) { listeners += callback; } return listeners; } } /// Base concrete form for a Signal with four parameters public class Signal<T, U, V, W> : BaseSignal { public event Action<T, U, V, W> Listener = delegate { }; public event Action<T, U, V, W> OnceListener = delegate { }; public void AddListener(Action<T, U, V, W> callback) { Listener = this.AddUnique(Listener, callback); } public void AddOnce(Action<T, U, V, W> callback) { OnceListener = this.AddUnique(OnceListener, callback); } public void RemoveListener(Action<T, U, V, W> callback) { Listener -= callback; } public override List<Type> GetTypes() { List<Type> retv = new List<Type>(); retv.Add(typeof(T)); retv.Add(typeof(U)); retv.Add(typeof(V)); retv.Add(typeof(W)); return retv; } public void Dispatch(T type1, U type2, V type3, W type4) { Listener(type1, type2, type3, type4); OnceListener(type1, type2, type3, type4); OnceListener = delegate { }; object[] outv = { type1, type2, type3, type4 }; base.Dispatch(outv); } private Action<T, U, V, W> AddUnique(Action<T, U, V, W> listeners, Action<T, U, V, W> callback) { if (!listeners.GetInvocationList().Contains(callback)) { listeners += callback; } return listeners; } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using JetBrains.Annotations; using JoinRpg.Data.Write.Interfaces; using JoinRpg.DataModel; using JoinRpg.DataModel.Extensions; using JoinRpg.Domain; using JoinRpg.Interfaces; using JoinRpg.Services.Interfaces; using JoinRpg.Services.Interfaces.Notification; namespace JoinRpg.Services.Impl { [UsedImplicitly] public class AccommodationInviteServiceImpl : DbServiceImplBase, IAccommodationInviteService { public AccommodationInviteServiceImpl(IUnitOfWork unitOfWork, IEmailService emailService, ICurrentUserAccessor currentUserAccessor) : base(unitOfWork, currentUserAccessor) => EmailService = emailService; private IEmailService EmailService { get; } private async Task<AccommodationInvite?> CreateAccommodationInvite(int projectId, int senderClaimId, int receiverClaimId, int accommodationRequestId) { //todo: make null result descriptive var receiverCurrentAccommodationRequest = await UnitOfWork .GetDbSet<Claim>() .Where(claim => claim.ClaimId == receiverClaimId) .Select(claim => claim.AccommodationRequest) .Include(request => request.Subjects) .FirstOrDefaultAsync().ConfigureAwait(false); var senderAccommodationRequest = await UnitOfWork.GetDbSet<AccommodationRequest>() .Where(request => request.Id == accommodationRequestId) .Include(request => request.Subjects) .Include(request => request.AccommodationType) .Include(c => c.Project) .FirstOrDefaultAsync().ConfigureAwait(false); //we not allow invitation to/from already settled members if (receiverCurrentAccommodationRequest?.AccommodationId != null || senderAccommodationRequest?.AccommodationId != null) { return null; } //invite only claims with same type of room, or claims with out room type at all if (receiverCurrentAccommodationRequest?.AccommodationTypeId != senderAccommodationRequest?.AccommodationTypeId && receiverCurrentAccommodationRequest?.AccommodationTypeId != null) { return null; } var newDwellersCount = receiverCurrentAccommodationRequest?.Subjects.Count ?? 1; var canInvite = senderAccommodationRequest.Subjects.Count + newDwellersCount <= senderAccommodationRequest.AccommodationType.Capacity; canInvite = canInvite && (senderAccommodationRequest.AccommodationTypeId == receiverCurrentAccommodationRequest?.AccommodationTypeId || receiverCurrentAccommodationRequest == null); if (!canInvite) { return null; } var inviteRequest = new AccommodationInvite { ProjectId = projectId, FromClaimId = senderClaimId, ToClaimId = receiverClaimId, IsAccepted = AccommodationRequest.InviteState.Unanswered, }; _ = UnitOfWork.GetDbSet<AccommodationInvite>().Add(inviteRequest); await UnitOfWork.SaveChangesAsync().ConfigureAwait(false); //todo email it var receiver = await UnitOfWork .GetDbSet<Claim>() .Where(claim => claim.ClaimId == receiverClaimId) .ToArrayAsync().ConfigureAwait(false); await EmailService .Email(await CreateInviteEmail<NewInviteEmail>(receiver, senderAccommodationRequest.Project).ConfigureAwait(false)) .ConfigureAwait(false); return inviteRequest; } private async Task<T> CreateInviteEmail<T>(Claim[] recipients, Project project) where T : InviteEmailModel, new() { return new T() { Initiator = await GetCurrentUser().ConfigureAwait(false), ProjectName = project.ProjectName, Recipients = recipients.GetInviteSubscriptions(), RecipientClaims = recipients, Text = new MarkdownString(), }; } private async Task<IEnumerable<AccommodationInvite>?> CreateAccommodationInviteToAccommodationRequest(int projectId, int senderClaimId, int receiverAccommodationRequestId, int accommodationRequestId) { //todo: make null result descriptive var receiverCurrentAccommodationRequest = await UnitOfWork .GetDbSet<AccommodationRequest>() .Where(request => request.Id == receiverAccommodationRequestId) .Include(request => request.Subjects) .FirstOrDefaultAsync().ConfigureAwait(false); var senderAccommodationRequest = await UnitOfWork.GetDbSet<AccommodationRequest>() .Where(request => request.Id == accommodationRequestId) .Include(request => request.Subjects) .Include(request => request.AccommodationType) .FirstOrDefaultAsync().ConfigureAwait(false); //we not allow invitation to/from already settled members if (receiverCurrentAccommodationRequest?.AccommodationId != null || senderAccommodationRequest?.AccommodationId != null) { return null; } //invite only claims with same type of room, or claims with out room type at all if (receiverCurrentAccommodationRequest?.AccommodationTypeId != senderAccommodationRequest?.AccommodationTypeId && receiverCurrentAccommodationRequest?.AccommodationTypeId != null) { return null; } var newDwellersCount = receiverCurrentAccommodationRequest?.Subjects.Count ?? 1; var canInvite = senderAccommodationRequest?.Subjects.Count + newDwellersCount <= senderAccommodationRequest?.AccommodationType.Capacity; canInvite = canInvite && (senderAccommodationRequest.AccommodationTypeId == receiverCurrentAccommodationRequest?.AccommodationTypeId || receiverCurrentAccommodationRequest == null); if (!canInvite) { return null; } var receiversClaims = await UnitOfWork .GetDbSet<Claim>() .Where(claim => claim.AccommodationRequest_Id == receiverAccommodationRequestId) .Include(c => c.Player) .ToArrayAsync() .ConfigureAwait(false); var result = new List<AccommodationInvite>(); foreach (var receiverClaim in receiversClaims) { var inviteRequest = new AccommodationInvite { ProjectId = projectId, FromClaimId = senderClaimId, ToClaimId = receiverClaim.ClaimId, IsAccepted = AccommodationRequest.InviteState.Unanswered, }; _ = UnitOfWork.GetDbSet<AccommodationInvite>().Add(inviteRequest); result.Add(inviteRequest); } await UnitOfWork.SaveChangesAsync().ConfigureAwait(false); await EmailService .Email(await CreateInviteEmail<NewInviteEmail>(receiversClaims, senderAccommodationRequest.Project).ConfigureAwait(false)) .ConfigureAwait(false); return result; } public async Task<IEnumerable<AccommodationInvite?>?> CreateAccommodationInviteToGroupOrClaim( int projectId, int senderClaimId, string receiverClaimOrAccommodationRequestId, int accommodationRequestId, string accommodationRequestPrefix) { // TODO: Search for and reuse previously cancelled invitation(s) to the same person(s) if (receiverClaimOrAccommodationRequestId.StartsWith(accommodationRequestPrefix)) { return await CreateAccommodationInviteToAccommodationRequest(projectId, senderClaimId, int.Parse(receiverClaimOrAccommodationRequestId[2..]), accommodationRequestId).ConfigureAwait(false); } return new[] { await CreateAccommodationInvite(projectId, senderClaimId, int.Parse(receiverClaimOrAccommodationRequestId), accommodationRequestId).ConfigureAwait(false), }; } /// <inheritdoc /> public async Task<AccommodationInvite?> AcceptAccommodationInvite(int projectId, int inviteId) { //todo: make null result descriptive var inviteRequest = await UnitOfWork.GetDbSet<AccommodationInvite>() .Where(invite => invite.Id == inviteId) .Include(invite => invite.To) .Include(invite => invite.From) .FirstOrDefaultAsync().ConfigureAwait(false); var receiverAccommodationRequest = await GetAccommodationRequestByClaim(inviteRequest.ToClaimId).ConfigureAwait(false); var senderAccommodationRequest = await GetAccommodationRequestByClaim(inviteRequest.FromClaimId) .ConfigureAwait(false); var roomFreeSpace = (senderAccommodationRequest.AccommodationId != null) ? senderAccommodationRequest.Accommodation.GetRoomFreeSpace() : senderAccommodationRequest.GetAbstractRoomFreeSpace(); var canInvite = roomFreeSpace >= (receiverAccommodationRequest?.Subjects.Count ?? 0); if (!canInvite) { return null; } _ = (receiverAccommodationRequest?.Subjects.Remove(inviteRequest.To)); senderAccommodationRequest.Subjects.Add(inviteRequest.To); inviteRequest.To.AccommodationRequest = senderAccommodationRequest; if (receiverAccommodationRequest != null) { foreach (var claim in receiverAccommodationRequest.Subjects.ToList()) { await DeclineOtherInvite(claim.ClaimId, inviteId).ConfigureAwait(false); senderAccommodationRequest.Subjects.Add(claim); } _ = UnitOfWork.GetDbSet<AccommodationRequest>().Remove(receiverAccommodationRequest); } inviteRequest.IsAccepted = AccommodationRequest.InviteState.Accepted; inviteRequest.ResolveDescription = ResolveDescription.Accepted; await UnitOfWork.SaveChangesAsync().ConfigureAwait(false); var receivers = await UnitOfWork.GetDbSet<Claim>() .Where(claim => inviteRequest.FromClaimId == claim.ClaimId) .Include(claim => claim.Player) .ToArrayAsync() .ConfigureAwait(false); await EmailService .Email(await CreateInviteEmail<AcceptInviteEmail>(receivers, inviteRequest.Project).ConfigureAwait(false)) .ConfigureAwait(false); return inviteRequest; } public async Task<AccommodationInvite?> CancelOrDeclineAccommodationInvite(int inviteId, AccommodationRequest.InviteState newState) { var acceptedStates = new[] { AccommodationRequest.InviteState.Declined, AccommodationRequest.InviteState.Canceled, }; if (!acceptedStates.Contains(newState)) { return null; } //todo: make null result descriptive var inviteRequest = await UnitOfWork.GetDbSet<AccommodationInvite>() .Where(invite => invite.Id == inviteId) .Include(invite => invite.Project) .FirstOrDefaultAsync().ConfigureAwait(false); if (inviteRequest == null) { throw new Exception("Invite request not found."); } inviteRequest.IsAccepted = newState; inviteRequest.ResolveDescription = newState == AccommodationRequest.InviteState.Canceled ? ResolveDescription.Canceled : ResolveDescription.Declined; await UnitOfWork.SaveChangesAsync().ConfigureAwait(false); var receivers = await UnitOfWork .GetDbSet<Claim>() .Where(claim => claim.ClaimId == inviteRequest.FromClaimId || claim.ClaimId == inviteRequest.ToClaimId) .Include(c => c.Player) .ToArrayAsync() .ConfigureAwait(false); await EmailService .Email(await CreateInviteEmail<DeclineInviteEmail>(receivers, inviteRequest.Project).ConfigureAwait(false)) .ConfigureAwait(false); return inviteRequest; } public async Task DeclineAllClaimInvites(int claimId) { var inviteRequests = await UnitOfWork.GetDbSet<AccommodationInvite>() .Where(invite => invite.ToClaimId == claimId || invite.FromClaimId == claimId) .ToListAsync() .ConfigureAwait(false); if (inviteRequests.Count == 0) { return; } var claims = new List<int>(); foreach (var accommodationInvite in inviteRequests) { claims.Add(accommodationInvite.FromClaimId); claims.Add(accommodationInvite.ToClaimId); accommodationInvite.IsAccepted = AccommodationRequest.InviteState.Declined; accommodationInvite.ResolveDescription = ResolveDescription.ClaimCanceled; } await UnitOfWork.SaveChangesAsync().ConfigureAwait(false); claims = claims.Distinct().ToList(); _ = claims.Remove(claimId); var receivers = await UnitOfWork .GetDbSet<Claim>() .Where(claim => claims.Contains(claim.ClaimId)) .Include(c => c.Player) .ToArrayAsync() .ConfigureAwait(false); var firstClaim = receivers.First(); var project = await UnitOfWork.GetDbSet<Project>() .Where(proj => proj.ProjectId == firstClaim.ProjectId) .FirstOrDefaultAsync().ConfigureAwait(false); await EmailService .Email(await CreateInviteEmail<DeclineInviteEmail>(receivers, project).ConfigureAwait(false)) .ConfigureAwait(false); } private async Task<AccommodationRequest> GetAccommodationRequestByClaim(int claimId) => await UnitOfWork.GetDbSet<AccommodationRequest>() .Where(request => request.Subjects.Any(subject => subject.ClaimId == claimId)) .Where(request => request.IsAccepted == AccommodationRequest.InviteState.Accepted) .Include(request => request.Subjects) .Include(request => request.AccommodationType) .Include(request => request.Accommodation) .FirstOrDefaultAsync().ConfigureAwait(false); private async Task DeclineOtherInvite(int claimId, int inviteId) { var inviteRequests = await UnitOfWork.GetDbSet<AccommodationInvite>() .Where(invite => invite.ToClaimId == claimId) .Where(invite => invite.Id != inviteId) .ToListAsync().ConfigureAwait(false); var stateToDecline = new[] { AccommodationRequest.InviteState.Unanswered }; foreach (var accommodationInvite in inviteRequests) { if (!stateToDecline.Contains(accommodationInvite.IsAccepted)) { continue; } accommodationInvite.IsAccepted = AccommodationRequest.InviteState.Declined; accommodationInvite.ResolveDescription = ResolveDescription.DeclinedWithAcceptOther; } await UnitOfWork.SaveChangesAsync().ConfigureAwait(false); } } }
namespace KabMan.Client { partial class frmSAN { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmSAN)); this.barManager1 = new DevExpress.XtraBars.BarManager(this.components); this.bar1 = new DevExpress.XtraBars.Bar(); this.btnNeu = new DevExpress.XtraBars.BarButtonItem(); this.btnDetail = new DevExpress.XtraBars.BarButtonItem(); this.btnLoeschen = new DevExpress.XtraBars.BarButtonItem(); this.btnSchliessen = new DevExpress.XtraBars.BarButtonItem(); this.barDockControlTop = new DevExpress.XtraBars.BarDockControl(); this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl(); this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl(); this.barDockControlRight = new DevExpress.XtraBars.BarDockControl(); this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl(); this.gridControl1 = new DevExpress.XtraGrid.GridControl(); this.gridView1 = new DevExpress.XtraGrid.Views.Grid.GridView(); this.gridColumn1 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn2 = new DevExpress.XtraGrid.Columns.GridColumn(); this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup(); this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem(); ((System.ComponentModel.ISupportInitialize)(this.barManager1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit(); this.layoutControl1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.gridControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.gridView1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit(); this.SuspendLayout(); // // barManager1 // this.barManager1.AllowCustomization = false; this.barManager1.AllowQuickCustomization = false; this.barManager1.AllowShowToolbarsPopup = false; this.barManager1.Bars.AddRange(new DevExpress.XtraBars.Bar[] { this.bar1}); this.barManager1.DockControls.Add(this.barDockControlTop); this.barManager1.DockControls.Add(this.barDockControlBottom); this.barManager1.DockControls.Add(this.barDockControlLeft); this.barManager1.DockControls.Add(this.barDockControlRight); this.barManager1.Form = this; this.barManager1.Items.AddRange(new DevExpress.XtraBars.BarItem[] { this.btnNeu, this.btnDetail, this.btnLoeschen, this.btnSchliessen}); this.barManager1.MaxItemId = 4; // // bar1 // this.bar1.Appearance.BackColor = System.Drawing.Color.WhiteSmoke; this.bar1.Appearance.BackColor2 = System.Drawing.Color.WhiteSmoke; this.bar1.Appearance.BorderColor = System.Drawing.Color.Gainsboro; this.bar1.Appearance.Options.UseBackColor = true; this.bar1.Appearance.Options.UseBorderColor = true; this.bar1.Appearance.Options.UseForeColor = true; this.bar1.BarName = "Tools"; this.bar1.DockCol = 0; this.bar1.DockRow = 0; this.bar1.DockStyle = DevExpress.XtraBars.BarDockStyle.Top; this.bar1.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.btnNeu), new DevExpress.XtraBars.LinkPersistInfo(this.btnDetail), new DevExpress.XtraBars.LinkPersistInfo(this.btnLoeschen), new DevExpress.XtraBars.LinkPersistInfo(this.btnSchliessen, true)}); this.bar1.OptionsBar.AllowQuickCustomization = false; this.bar1.OptionsBar.DrawDragBorder = false; this.bar1.OptionsBar.UseWholeRow = true; resources.ApplyResources(this.bar1, "bar1"); // // btnNeu // resources.ApplyResources(this.btnNeu, "btnNeu"); this.btnNeu.Glyph = global::KabMan.Client.Properties.Resources.neu; this.btnNeu.Id = 0; this.btnNeu.Name = "btnNeu"; this.btnNeu.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.btnNeu_ItemClick); // // btnDetail // resources.ApplyResources(this.btnDetail, "btnDetail"); this.btnDetail.Glyph = global::KabMan.Client.Properties.Resources.detail; this.btnDetail.Id = 1; this.btnDetail.Name = "btnDetail"; this.btnDetail.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.btnDetail_ItemClick); // // btnLoeschen // resources.ApplyResources(this.btnLoeschen, "btnLoeschen"); this.btnLoeschen.Glyph = global::KabMan.Client.Properties.Resources.loeschen; this.btnLoeschen.Id = 2; this.btnLoeschen.Name = "btnLoeschen"; this.btnLoeschen.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.btnLoeschen_ItemClick); // // btnSchliessen // resources.ApplyResources(this.btnSchliessen, "btnSchliessen"); this.btnSchliessen.Glyph = global::KabMan.Client.Properties.Resources.exit; this.btnSchliessen.Id = 3; this.btnSchliessen.Name = "btnSchliessen"; this.btnSchliessen.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.btnSchliessen_ItemClick); // // layoutControl1 // this.layoutControl1.AllowCustomizationMenu = false; this.layoutControl1.Appearance.DisabledLayoutGroupCaption.ForeColor = System.Drawing.SystemColors.GrayText; this.layoutControl1.Appearance.DisabledLayoutGroupCaption.Options.UseForeColor = true; this.layoutControl1.Appearance.DisabledLayoutItem.ForeColor = System.Drawing.SystemColors.GrayText; this.layoutControl1.Appearance.DisabledLayoutItem.Options.UseForeColor = true; this.layoutControl1.Controls.Add(this.gridControl1); resources.ApplyResources(this.layoutControl1, "layoutControl1"); this.layoutControl1.Name = "layoutControl1"; this.layoutControl1.Root = this.layoutControlGroup1; // // gridControl1 // resources.ApplyResources(this.gridControl1, "gridControl1"); this.gridControl1.MainView = this.gridView1; this.gridControl1.Name = "gridControl1"; this.gridControl1.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] { this.gridView1}); this.gridControl1.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.gridControl1_MouseDoubleClick); // // gridView1 // this.gridView1.Appearance.ColumnFilterButton.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.ColumnFilterButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212))))); this.gridView1.Appearance.ColumnFilterButton.BorderColor = System.Drawing.Color.Silver; this.gridView1.Appearance.ColumnFilterButton.ForeColor = System.Drawing.Color.Gray; this.gridView1.Appearance.ColumnFilterButton.Options.UseBackColor = true; this.gridView1.Appearance.ColumnFilterButton.Options.UseBorderColor = true; this.gridView1.Appearance.ColumnFilterButton.Options.UseForeColor = true; this.gridView1.Appearance.ColumnFilterButtonActive.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212))))); this.gridView1.Appearance.ColumnFilterButtonActive.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223))))); this.gridView1.Appearance.ColumnFilterButtonActive.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212))))); this.gridView1.Appearance.ColumnFilterButtonActive.ForeColor = System.Drawing.Color.Blue; this.gridView1.Appearance.ColumnFilterButtonActive.Options.UseBackColor = true; this.gridView1.Appearance.ColumnFilterButtonActive.Options.UseBorderColor = true; this.gridView1.Appearance.ColumnFilterButtonActive.Options.UseForeColor = true; this.gridView1.Appearance.Empty.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243))))); this.gridView1.Appearance.Empty.Options.UseBackColor = true; this.gridView1.Appearance.EvenRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223))))); this.gridView1.Appearance.EvenRow.BackColor2 = System.Drawing.Color.GhostWhite; this.gridView1.Appearance.EvenRow.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.EvenRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.gridView1.Appearance.EvenRow.Options.UseBackColor = true; this.gridView1.Appearance.EvenRow.Options.UseForeColor = true; this.gridView1.Appearance.FilterCloseButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.gridView1.Appearance.FilterCloseButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(118)))), ((int)(((byte)(170)))), ((int)(((byte)(225))))); this.gridView1.Appearance.FilterCloseButton.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.gridView1.Appearance.FilterCloseButton.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.FilterCloseButton.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.gridView1.Appearance.FilterCloseButton.Options.UseBackColor = true; this.gridView1.Appearance.FilterCloseButton.Options.UseBorderColor = true; this.gridView1.Appearance.FilterCloseButton.Options.UseForeColor = true; this.gridView1.Appearance.FilterPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(80)))), ((int)(((byte)(135))))); this.gridView1.Appearance.FilterPanel.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.gridView1.Appearance.FilterPanel.ForeColor = System.Drawing.Color.White; this.gridView1.Appearance.FilterPanel.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.gridView1.Appearance.FilterPanel.Options.UseBackColor = true; this.gridView1.Appearance.FilterPanel.Options.UseForeColor = true; this.gridView1.Appearance.FixedLine.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(58)))), ((int)(((byte)(58))))); this.gridView1.Appearance.FixedLine.Options.UseBackColor = true; this.gridView1.Appearance.FocusedCell.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(225))))); this.gridView1.Appearance.FocusedCell.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.FocusedCell.Options.UseBackColor = true; this.gridView1.Appearance.FocusedCell.Options.UseForeColor = true; this.gridView1.Appearance.FocusedRow.BackColor = System.Drawing.Color.Navy; this.gridView1.Appearance.FocusedRow.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(50)))), ((int)(((byte)(50)))), ((int)(((byte)(178))))); this.gridView1.Appearance.FocusedRow.ForeColor = System.Drawing.Color.White; this.gridView1.Appearance.FocusedRow.Options.UseBackColor = true; this.gridView1.Appearance.FocusedRow.Options.UseForeColor = true; this.gridView1.Appearance.FooterPanel.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.FooterPanel.BorderColor = System.Drawing.Color.Silver; this.gridView1.Appearance.FooterPanel.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.FooterPanel.Options.UseBackColor = true; this.gridView1.Appearance.FooterPanel.Options.UseBorderColor = true; this.gridView1.Appearance.FooterPanel.Options.UseForeColor = true; this.gridView1.Appearance.GroupButton.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.GroupButton.BorderColor = System.Drawing.Color.Silver; this.gridView1.Appearance.GroupButton.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.GroupButton.Options.UseBackColor = true; this.gridView1.Appearance.GroupButton.Options.UseBorderColor = true; this.gridView1.Appearance.GroupButton.Options.UseForeColor = true; this.gridView1.Appearance.GroupFooter.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202))))); this.gridView1.Appearance.GroupFooter.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202))))); this.gridView1.Appearance.GroupFooter.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.GroupFooter.Options.UseBackColor = true; this.gridView1.Appearance.GroupFooter.Options.UseBorderColor = true; this.gridView1.Appearance.GroupFooter.Options.UseForeColor = true; this.gridView1.Appearance.GroupPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(110)))), ((int)(((byte)(165))))); this.gridView1.Appearance.GroupPanel.BackColor2 = System.Drawing.Color.White; this.gridView1.Appearance.GroupPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold); this.gridView1.Appearance.GroupPanel.ForeColor = System.Drawing.Color.White; this.gridView1.Appearance.GroupPanel.Options.UseBackColor = true; this.gridView1.Appearance.GroupPanel.Options.UseFont = true; this.gridView1.Appearance.GroupPanel.Options.UseForeColor = true; this.gridView1.Appearance.GroupRow.BackColor = System.Drawing.Color.Gray; this.gridView1.Appearance.GroupRow.ForeColor = System.Drawing.Color.Silver; this.gridView1.Appearance.GroupRow.Options.UseBackColor = true; this.gridView1.Appearance.GroupRow.Options.UseForeColor = true; this.gridView1.Appearance.HeaderPanel.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.HeaderPanel.BorderColor = System.Drawing.Color.Silver; this.gridView1.Appearance.HeaderPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold); this.gridView1.Appearance.HeaderPanel.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.HeaderPanel.Options.UseBackColor = true; this.gridView1.Appearance.HeaderPanel.Options.UseBorderColor = true; this.gridView1.Appearance.HeaderPanel.Options.UseFont = true; this.gridView1.Appearance.HeaderPanel.Options.UseForeColor = true; this.gridView1.Appearance.HideSelectionRow.BackColor = System.Drawing.Color.Gray; this.gridView1.Appearance.HideSelectionRow.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.gridView1.Appearance.HideSelectionRow.Options.UseBackColor = true; this.gridView1.Appearance.HideSelectionRow.Options.UseForeColor = true; this.gridView1.Appearance.HorzLine.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.HorzLine.Options.UseBackColor = true; this.gridView1.Appearance.OddRow.BackColor = System.Drawing.Color.White; this.gridView1.Appearance.OddRow.BackColor2 = System.Drawing.Color.White; this.gridView1.Appearance.OddRow.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.OddRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.BackwardDiagonal; this.gridView1.Appearance.OddRow.Options.UseBackColor = true; this.gridView1.Appearance.OddRow.Options.UseForeColor = true; this.gridView1.Appearance.Preview.BackColor = System.Drawing.Color.White; this.gridView1.Appearance.Preview.ForeColor = System.Drawing.Color.Navy; this.gridView1.Appearance.Preview.Options.UseBackColor = true; this.gridView1.Appearance.Preview.Options.UseForeColor = true; this.gridView1.Appearance.Row.BackColor = System.Drawing.Color.White; this.gridView1.Appearance.Row.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.Row.Options.UseBackColor = true; this.gridView1.Appearance.Row.Options.UseForeColor = true; this.gridView1.Appearance.RowSeparator.BackColor = System.Drawing.Color.White; this.gridView1.Appearance.RowSeparator.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243))))); this.gridView1.Appearance.RowSeparator.Options.UseBackColor = true; this.gridView1.Appearance.SelectedRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(10)))), ((int)(((byte)(10)))), ((int)(((byte)(138))))); this.gridView1.Appearance.SelectedRow.ForeColor = System.Drawing.Color.White; this.gridView1.Appearance.SelectedRow.Options.UseBackColor = true; this.gridView1.Appearance.SelectedRow.Options.UseForeColor = true; this.gridView1.Appearance.VertLine.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.VertLine.Options.UseBackColor = true; this.gridView1.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] { this.gridColumn1, this.gridColumn2}); this.gridView1.GridControl = this.gridControl1; this.gridView1.Name = "gridView1"; this.gridView1.OptionsBehavior.AllowIncrementalSearch = true; this.gridView1.OptionsBehavior.Editable = false; this.gridView1.OptionsCustomization.AllowFilter = false; this.gridView1.OptionsMenu.EnableColumnMenu = false; this.gridView1.OptionsMenu.EnableFooterMenu = false; this.gridView1.OptionsMenu.EnableGroupPanelMenu = false; this.gridView1.OptionsView.EnableAppearanceEvenRow = true; this.gridView1.OptionsView.EnableAppearanceOddRow = true; this.gridView1.OptionsView.ShowGroupPanel = false; this.gridView1.OptionsView.ShowIndicator = false; // // gridColumn1 // resources.ApplyResources(this.gridColumn1, "gridColumn1"); this.gridColumn1.FieldName = "Id"; this.gridColumn1.Name = "gridColumn1"; // // gridColumn2 // resources.ApplyResources(this.gridColumn2, "gridColumn2"); this.gridColumn2.FieldName = "San"; this.gridColumn2.Name = "gridColumn2"; // // layoutControlGroup1 // resources.ApplyResources(this.layoutControlGroup1, "layoutControlGroup1"); this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] { this.layoutControlItem1}); this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0); this.layoutControlGroup1.Name = "layoutControlGroup1"; this.layoutControlGroup1.Size = new System.Drawing.Size(431, 237); this.layoutControlGroup1.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0); this.layoutControlGroup1.TextVisible = false; // // layoutControlItem1 // this.layoutControlItem1.Control = this.gridControl1; resources.ApplyResources(this.layoutControlItem1, "layoutControlItem1"); this.layoutControlItem1.Location = new System.Drawing.Point(0, 0); this.layoutControlItem1.Name = "layoutControlItem1"; this.layoutControlItem1.Size = new System.Drawing.Size(429, 235); this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem1.TextSize = new System.Drawing.Size(0, 0); this.layoutControlItem1.TextToControlDistance = 0; this.layoutControlItem1.TextVisible = false; // // frmSAN // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.layoutControl1); this.Controls.Add(this.barDockControlLeft); this.Controls.Add(this.barDockControlRight); this.Controls.Add(this.barDockControlBottom); this.Controls.Add(this.barDockControlTop); this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "frmSAN"; this.ShowInTaskbar = false; this.Load += new System.EventHandler(this.frmSAN_Load); this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.frmSAN_KeyPress); ((System.ComponentModel.ISupportInitialize)(this.barManager1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit(); this.layoutControl1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.gridControl1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.gridView1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit(); this.ResumeLayout(false); } #endregion private DevExpress.XtraBars.BarManager barManager1; private DevExpress.XtraBars.Bar bar1; private DevExpress.XtraBars.BarDockControl barDockControlTop; private DevExpress.XtraBars.BarDockControl barDockControlBottom; private DevExpress.XtraBars.BarDockControl barDockControlLeft; private DevExpress.XtraBars.BarDockControl barDockControlRight; private DevExpress.XtraLayout.LayoutControl layoutControl1; private DevExpress.XtraGrid.GridControl gridControl1; private DevExpress.XtraGrid.Views.Grid.GridView gridView1; private DevExpress.XtraGrid.Columns.GridColumn gridColumn1; private DevExpress.XtraGrid.Columns.GridColumn gridColumn2; private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1; private DevExpress.XtraBars.BarButtonItem btnNeu; private DevExpress.XtraBars.BarButtonItem btnDetail; private DevExpress.XtraBars.BarButtonItem btnLoeschen; private DevExpress.XtraBars.BarButtonItem btnSchliessen; } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using AttendanceServices.Areas.HelpPage.ModelDescriptions; using AttendanceServices.Areas.HelpPage.Models; namespace AttendanceServices.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
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 PowerBIRestDemo.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; } } }
/* * CP28598.cs - Hebrew (ISO) code page. * * Copyright (c) 2002 Southern Storm Software, Pty Ltd * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Generated from "ibm-916.ucm". namespace I18N.MidEast { using System; using I18N.Common; public class CP28598 : ByteEncoding { public CP28598() : base(28598, ToChars, "Hebrew (ISO)", "iso-8859-8", "iso-8859-8", "iso-8859-8", true, true, true, true, 1255) {} private static readonly char[] ToChars = { '\u0000', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\u0007', '\u0008', '\u0009', '\u000A', '\u000B', '\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001A', '\u001B', '\u001C', '\u001D', '\u001E', '\u001F', '\u0020', '\u0021', '\u0022', '\u0023', '\u0024', '\u0025', '\u0026', '\u0027', '\u0028', '\u0029', '\u002A', '\u002B', '\u002C', '\u002D', '\u002E', '\u002F', '\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035', '\u0036', '\u0037', '\u0038', '\u0039', '\u003A', '\u003B', '\u003C', '\u003D', '\u003E', '\u003F', '\u0040', '\u0041', '\u0042', '\u0043', '\u0044', '\u0045', '\u0046', '\u0047', '\u0048', '\u0049', '\u004A', '\u004B', '\u004C', '\u004D', '\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u0053', '\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059', '\u005A', '\u005B', '\u005C', '\u005D', '\u005E', '\u005F', '\u0060', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065', '\u0066', '\u0067', '\u0068', '\u0069', '\u006A', '\u006B', '\u006C', '\u006D', '\u006E', '\u006F', '\u0070', '\u0071', '\u0072', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077', '\u0078', '\u0079', '\u007A', '\u007B', '\u007C', '\u007D', '\u007E', '\u007F', '\u0080', '\u0081', '\u0082', '\u0083', '\u0084', '\u0085', '\u0086', '\u0087', '\u0088', '\u0089', '\u008A', '\u008B', '\u008C', '\u008D', '\u008E', '\u008F', '\u0090', '\u0091', '\u0092', '\u0093', '\u0094', '\u0095', '\u0096', '\u0097', '\u0098', '\u0099', '\u009A', '\u009B', '\u009C', '\u009D', '\u009E', '\u009F', '\u00A0', '\u003F', '\u00A2', '\u00A3', '\u00A4', '\u00A5', '\u00A6', '\u00A7', '\u00A8', '\u00A9', '\u00D7', '\u00AB', '\u00AC', '\u00AD', '\u00AE', '\u203E', '\u00B0', '\u00B1', '\u00B2', '\u00B3', '\u00B4', '\u00B5', '\u00B6', '\u2022', '\u00B8', '\u00B9', '\u00F7', '\u00BB', '\u00BC', '\u00BD', '\u00BE', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u2017', '\u05D0', '\u05D1', '\u05D2', '\u05D3', '\u05D4', '\u05D5', '\u05D6', '\u05D7', '\u05D8', '\u05D9', '\u05DA', '\u05DB', '\u05DC', '\u05DD', '\u05DE', '\u05DF', '\u05E0', '\u05E1', '\u05E2', '\u05E3', '\u05E4', '\u05E5', '\u05E6', '\u05E7', '\u05E8', '\u05E9', '\u05EA', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', }; protected override void ToBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(chars[charIndex++]); if(ch >= 161) switch(ch) { case 0x00A2: case 0x00A3: case 0x00A4: case 0x00A5: case 0x00A6: case 0x00A7: case 0x00A8: case 0x00A9: case 0x00AB: case 0x00AC: case 0x00AD: case 0x00AE: case 0x00B0: case 0x00B1: case 0x00B2: case 0x00B3: case 0x00B4: case 0x00B5: case 0x00B6: case 0x00B8: case 0x00B9: case 0x00BB: case 0x00BC: case 0x00BD: case 0x00BE: break; case 0x00D7: ch = 0xAA; break; case 0x00F7: ch = 0xBA; break; case 0x05D0: case 0x05D1: case 0x05D2: case 0x05D3: case 0x05D4: case 0x05D5: case 0x05D6: case 0x05D7: case 0x05D8: case 0x05D9: case 0x05DA: case 0x05DB: case 0x05DC: case 0x05DD: case 0x05DE: case 0x05DF: case 0x05E0: case 0x05E1: case 0x05E2: case 0x05E3: case 0x05E4: case 0x05E5: case 0x05E6: case 0x05E7: case 0x05E8: case 0x05E9: case 0x05EA: ch -= 0x04F0; break; case 0x2017: ch = 0xDF; break; case 0x2022: ch = 0xB7; break; case 0x203E: ch = 0xAF; break; default: { if(ch >= 0xFF01 && ch <= 0xFF5E) ch -= 0xFEE0; else ch = 0x3F; } break; } bytes[byteIndex++] = (byte)ch; --charCount; } } protected override void ToBytes(String s, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(s[charIndex++]); if(ch >= 161) switch(ch) { case 0x00A2: case 0x00A3: case 0x00A4: case 0x00A5: case 0x00A6: case 0x00A7: case 0x00A8: case 0x00A9: case 0x00AB: case 0x00AC: case 0x00AD: case 0x00AE: case 0x00B0: case 0x00B1: case 0x00B2: case 0x00B3: case 0x00B4: case 0x00B5: case 0x00B6: case 0x00B8: case 0x00B9: case 0x00BB: case 0x00BC: case 0x00BD: case 0x00BE: break; case 0x00D7: ch = 0xAA; break; case 0x00F7: ch = 0xBA; break; case 0x05D0: case 0x05D1: case 0x05D2: case 0x05D3: case 0x05D4: case 0x05D5: case 0x05D6: case 0x05D7: case 0x05D8: case 0x05D9: case 0x05DA: case 0x05DB: case 0x05DC: case 0x05DD: case 0x05DE: case 0x05DF: case 0x05E0: case 0x05E1: case 0x05E2: case 0x05E3: case 0x05E4: case 0x05E5: case 0x05E6: case 0x05E7: case 0x05E8: case 0x05E9: case 0x05EA: ch -= 0x04F0; break; case 0x2017: ch = 0xDF; break; case 0x2022: ch = 0xB7; break; case 0x203E: ch = 0xAF; break; default: { if(ch >= 0xFF01 && ch <= 0xFF5E) ch -= 0xFEE0; else ch = 0x3F; } break; } bytes[byteIndex++] = (byte)ch; --charCount; } } }; // class CP28598 public class ENCiso_8859_8 : CP28598 { public ENCiso_8859_8() : base() {} }; // class ENCiso_8859_8 }; // namespace I18N.MidEast
// // This file is part of the game Voxalia, created by FreneticXYZ. // This code is Copyright (C) 2016 FreneticXYZ under the terms of the MIT license. // See README.md or LICENSE.txt for contents of the MIT license. // If these are not available, see https://opensource.org/licenses/MIT // using System; using System.Linq; using System.Collections.Generic; using Voxalia.Shared.BlockShapes; using BEPUphysics.CollisionShapes.ConvexShapes; using BEPUphysics.BroadPhaseEntries.MobileCollidables; using BEPUphysics.CollisionShapes; using BEPUutilities; using FreneticScript; using Voxalia.Shared.ModelManagement; namespace Voxalia.Shared { /// <summary> /// Handles the block 'shapes' engine, the engine that powers all the potential 3D shapes a block can be in. /// </summary> public class BlockShapeRegistry { /// <summary> /// The internal array of block shape details. /// </summary> public static BlockShapeDetails[] BSD = new BlockShapeDetails[256]; /// <summary> /// All names of all BSDs. /// </summary> public static Dictionary<string, int> BSD_Names = new Dictionary<string, int>(); static bool inited = false; public static void Init() { if (inited) { return; } inited = true; for (int i = 0; i < 256; i++) { BSD[i] = new BSD0(); } Register(0, new BSD0(), "default", "block", "standard", "cube", "plain"); BSD[1] = new BSD01_5(0.84f); BSD[2] = new BSD01_5(0.68f); BSD[3] = new BSD01_5(0.50f); BSD[4] = new BSD01_5(0.34f); BSD[5] = new BSD01_5(0.13f); BSD[6] = new BSD06_10(0.84f); BSD[7] = new BSD06_10(0.68f); BSD[8] = new BSD06_10(0.50f); BSD[9] = new BSD06_10(0.34f); BSD[10] = new BSD06_10(0.13f); BSD[11] = new BSD11_15(0.84f); BSD[12] = new BSD11_15(0.68f); BSD[13] = new BSD11_15(0.50f); BSD[14] = new BSD11_15(0.34f); BSD[15] = new BSD11_15(0.13f); BSD[16] = new BSD16_20(0.84f); BSD[17] = new BSD16_20(0.68f); BSD[18] = new BSD16_20(0.50f); BSD[19] = new BSD16_20(0.34f); BSD[20] = new BSD16_20(0.13f); BSD[21] = new BSD21_25(0.84f); BSD[22] = new BSD21_25(0.68f); BSD[23] = new BSD21_25(0.50f); BSD[24] = new BSD21_25(0.34f); BSD[25] = new BSD21_25(0.13f); BSD[26] = new BSD26_30(0.84f); BSD[27] = new BSD26_30(0.68f); BSD[28] = new BSD26_30(0.50f); BSD[29] = new BSD26_30(0.34f); BSD[30] = new BSD26_30(0.13f); BSD[31] = new BSD31(); BSD[32] = new BSD32(); BSD[33] = new BSD33(); BSD[34] = new BSD34(); // ... BSD[39] = new BSD39a76(1f); // ... BSD[52] = new BSD52a127(0.25f, 0.75f, 0.5f); BSD[53] = new BSD53_54(0.25f, 0.75f, 0.5f); BSD[54] = new BSD53_54(0f, 1f, 1f); BSD[55] = new BSD55(); BSD[56] = new BSD56(); BSD[57] = new BSD57(); BSD[58] = new BSD58(); // ... BSD[64] = new BSD64_68(MaterialSide.BOTTOM, MaterialSide.XP, MaterialSide.XM, MaterialSide.YP, MaterialSide.YM, MaterialSide.TOP); BSD[65] = new BSD64_68(MaterialSide.XP, MaterialSide.XM, MaterialSide.YP, MaterialSide.YM, MaterialSide.TOP, MaterialSide.BOTTOM); BSD[66] = new BSD64_68(MaterialSide.XM, MaterialSide.YP, MaterialSide.YM, MaterialSide.TOP, MaterialSide.BOTTOM, MaterialSide.XP); BSD[67] = new BSD64_68(MaterialSide.YP, MaterialSide.YM, MaterialSide.TOP, MaterialSide.BOTTOM, MaterialSide.XP, MaterialSide.XM); BSD[68] = new BSD64_68(MaterialSide.YM, MaterialSide.TOP, MaterialSide.BOTTOM, MaterialSide.XP, MaterialSide.XM, MaterialSide.YP); // ... BSD[72] = new BSD72(); BSD[73] = new BSD73(); BSD[74] = new BSD74(); BSD[75] = new BSD75(); BSD[76] = new BSD39a76(0.5f); // ... BSD[80] = new BSD80(); BSD[81] = new BSD81(); BSD[82] = new BSD82(); BSD[83] = new BSD83(); // ... BSD[127] = new BSD52a127(0f, 1f, 1f); // ... // Final setup int[] DB_TID = MaterialHelpers.ALL_MATS[(int)Material.DEBUG].TID; int lim = 0; for (int i = 0; i < DB_TID.Length; i++) { if (DB_TID[i] > lim) { lim = DB_TID[i]; } } int[] rlok = new int[lim + 1]; for (int i = 0; i < DB_TID.Length; i++) { rlok[DB_TID[i]] = i; } for (int i = 0; i < 256; i++) { if (i > 0 && BSD[i] is BSD0) { continue; } BSD[i].Preparse(rlok); } } public static int GetBSDFor(string name) { byte ret; if (byte.TryParse(name, out ret)) { return ret; } int iret; if (BSD_Names.TryGetValue(name.ToLowerFast(), out iret)) { return iret; } return 0; } static void Register(int ID, BlockShapeDetails bsd, params string[] names) { BSD[ID] = bsd; foreach (string str in names) { BSD_Names.Add(str, ID); } } } public class BlockShapeSubDetails { public List<Vector3>[] Verts = new List<Vector3>[64]; public List<Vector3>[] Norms = new List<Vector3>[64]; public Vector3[][] TCrds = new Vector3[64][]; } /// <summary> /// Represents the details of a single block shape option. /// </summary> public abstract class BlockShapeDetails { public const double SHRINK_CONSTANT = 0.9; public double LightDamage = 1.0; public abstract List<Vector3> GetVertices(Vector3 blockPos, bool XP, bool XM, bool YP, bool YM, bool TOP, bool BOTTOM); public abstract List<Vector3> GetNormals(Vector3 blockPos, bool XP, bool XM, bool YP, bool YM, bool TOP, bool BOTTOM); public abstract List<Vector3> GetTCoords(Vector3 blockPos, Material mat, bool XP, bool XM, bool YP, bool YM, bool TOP, bool BOTTOM); public abstract bool OccupiesXP(); public abstract bool OccupiesYP(); public abstract bool OccupiesXM(); public abstract bool OccupiesYM(); public abstract bool OccupiesTOP(); public abstract bool OccupiesBOTTOM(); public BlockShapeSubDetails BSSD = new BlockShapeSubDetails(); public BlockDamage DamageMode = BlockDamage.NONE; public void Preparse(int[] rlok) { DB_RLOK = rlok; for (int i = 0; i < 64; i++) { BSSD.Verts[i] = GetVertices(Vector3.Zero, (i & 1) == 1, (i & 2) == 2, (i & 4) == 4, (i & 8) == 8, (i & 16) == 16, (i & 32) == 32); BSSD.Norms[i] = GetNormals(Vector3.Zero, (i & 1) == 1, (i & 2) == 2, (i & 4) == 4, (i & 8) == 8, (i & 16) == 16, (i & 32) == 32); BSSD.TCrds[i] = GetTCoords(Vector3.Zero, Material.DEBUG, (i & 1) == 1, (i & 2) == 2, (i & 4) == 4, (i & 8) == 8, (i & 16) == 16, (i & 32) == 32).ToArray(); } FinishParse(); Damaged = new BlockShapeDetails[4]; BlockShapeDetails prev = this; Damaged[0] = this; for (int i = 1; i < Damaged.Length; i++) { Damaged[i] = (BlockShapeDetails)prev.MemberwiseClone(); Damaged[i].DamageMode = (BlockDamage)i; Damaged[i].Damage(); Damaged[i].FinishParse(); prev = Damaged[i]; } } public void FinishParse() { Location offset; BEPUphysics.CollisionShapes.EntityShape es = GetShape(DamageMode, out offset, false); Coll = es.GetCollidableInstance(); Coll.LocalPosition = -offset.ToBVector(); } private void Damage() { if (!CanSubdiv) { return; } if ((int)DamageMode > 1) { return; // Placeholder until simplify is added. } Subdivide(); } public bool CanSubdiv = true; private void Subdivide() { // TODO: Save TCs and work with them properly. Shape p = new Shape(); Dictionary<Location, Point> ps = new Dictionary<Location, Point>(); for (int i = 0; i < BSSD.Verts[0].Count; i++) { Location t = new Location(BSSD.Verts[0][i]); if (!ps.ContainsKey(t)) { ps.Add(t, new Point(BSSD.Verts[0][i])); } } for (int i = 0; i < BSSD.Verts[0].Count; i += 3) { Point a = ps[new Location(BSSD.Verts[0][i])]; Point b = ps[new Location(BSSD.Verts[0][i + 1])]; Point c = ps[new Location(BSSD.Verts[0][i + 2])]; if (i + 3 < BSSD.Verts[0].Count) { Point a2 = ps[new Location(BSSD.Verts[0][i + 3])]; Point b2 = ps[new Location(BSSD.Verts[0][i + 4])]; Point c2 = ps[new Location(BSSD.Verts[0][i + 5])]; bool ac = a2 == a || a2 == b || a2 == c; bool bc = b2 == a || b2 == b || b2 == c; bool cc = c2 == a || c2 == b || c2 == c; if (ac && bc && cc) { SysConsole.Output(OutputType.WARNING, this + " has weird setup: " + a + ", " + b + ", " + c); p.AddFace(SubdivisionUtilities.CreateFaceF(p.AllEdges, a, b, c)); } else if (ac && cc) { p.AddFace(SubdivisionUtilities.CreateFaceF(p.AllEdges, a, b, b2, c)); i += 3; } else if (ac && bc) { p.AddFace(SubdivisionUtilities.CreateFaceF(p.AllEdges, a, b, c, c2)); i += 3; } else if (bc && cc) { p.AddFace(SubdivisionUtilities.CreateFaceF(p.AllEdges, a, b, c, a2)); i += 3; } else { p.AddFace(SubdivisionUtilities.CreateFaceF(p.AllEdges, a, b, c)); } } else { p.AddFace(SubdivisionUtilities.CreateFaceF(p.AllEdges, a, b, c)); } } CatmullClarkSubdivider cmcs = new CatmullClarkSubdivider(); Shape res = cmcs.Subdivide(p); List<Vector3> vecs = new List<Vector3>(); List<Vector3> norms = new List<Vector3>(); List<Vector3> Tcs = new List<Vector3>(); foreach (Face face in res.Faces) { for (int i = 0; i < 3; i++) { vecs.Add(face.AllPoints[i].Position); norms.Add(face.Normal); Tcs.Add(new Vector3(0, 0, BSSD.TCrds[0][0].Z)); } } BSSD = new BlockShapeSubDetails(); Vector3[] tcrds = Tcs.ToArray(); for (int i = 0; i < BSSD.Verts.Length; i++) { BSSD.Verts[i] = vecs; BSSD.Norms[i] = norms; BSSD.TCrds[i] = tcrds; } } public BlockShapeDetails[] Damaged; private int[] DB_RLOK; public Vector3[] GetTCoordsQuick(int index, Material mat) { // NOTE: This method is called very often by the client. Any optimization here will be very useful! Vector3[] set = BSSD.TCrds[index]; int len = set.Length; Vector3[] vecs = new Vector3[len]; Vector3 temp; int[] helper = MaterialHelpers.ALL_MATS[(int)mat].TID; for (int i = 0; i < len; i++) { temp = set[i]; temp.Z = helper[DB_RLOK[(int)temp.Z]]; vecs[i] = temp; } return vecs; } public bool BackTextureAllowed = true; public EntityShape BlockShapeCache; public EntityShape ShrunkBlockShapeCache; public Location OffsetCache; public Location ShrunkOffsetCache; public EntityCollidable Coll = null; public virtual KeyValuePair<List<Vector4>, List<Vector4>> GetStretchData(Vector3 blockpos, List<Vector3> vertices, BlockInternal XP, BlockInternal XM, BlockInternal YP, BlockInternal YM, BlockInternal ZP, BlockInternal ZM, bool bxp, bool bxm, bool byp, bool bym, bool bzp, bool bzm) { List<Vector4> stretchvals = new List<Vector4>(); List<Vector4> stretchweis = new List<Vector4>(); for (int i = 0; i < vertices.Count; i++) { stretchvals.Add(new Vector4(0, 0, 0, 0)); stretchweis.Add(new Vector4(0, 0, 0, 0)); } return new KeyValuePair<List<Vector4>, List<Vector4>>(stretchvals, stretchweis); } public virtual EntityShape GetShape(BlockDamage damage, out Location offset, bool shrink) { if (damage != DamageMode) { return Damaged[(int)damage].GetShape(damage, out offset, shrink); } if ((shrink ? ShrunkBlockShapeCache : BlockShapeCache) != null) { offset = (shrink ? ShrunkOffsetCache : OffsetCache); return (shrink ? ShrunkBlockShapeCache : BlockShapeCache); } List<Vector3> vecs = GetVertices(new Vector3(0, 0, 0), false, false, false, false, false, false); Vector3 offs; if (vecs.Count == 0) { throw new Exception("No vertices for shape " + this); } if (shrink) { for (int i = 0; i < vecs.Count; i++) { vecs[i] = (vecs[i] - new Vector3(0.5f, 0.5f, 0.5f)) * SHRINK_CONSTANT + new Vector3(0.5f, 0.5f, 0.5f); } } ConvexHullShape shape = new ConvexHullShape(vecs, out offs) { CollisionMargin = 0 }; offset = new Location(offs); if (shrink) { ShrunkBlockShapeCache = shape; ShrunkOffsetCache = offset; } else { BlockShapeCache = shape; OffsetCache = offset; } return shape; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Semver; using Umbraco.Core.Configuration; using Umbraco.Core.Persistence.DatabaseModelDefinitions; using Umbraco.Core.Persistence.SqlSyntax; using Umbraco.Core.Services; namespace Umbraco.Core.Persistence.Migrations.Initial { public class DatabaseSchemaResult { public DatabaseSchemaResult() { Errors = new List<Tuple<string, string>>(); TableDefinitions = new List<TableDefinition>(); ValidTables = new List<string>(); ValidColumns = new List<string>(); ValidConstraints = new List<string>(); ValidIndexes = new List<string>(); } public List<Tuple<string, string>> Errors { get; set; } public List<TableDefinition> TableDefinitions { get; set; } public List<string> ValidTables { get; set; } public List<string> ValidColumns { get; set; } public List<string> ValidConstraints { get; set; } public List<string> ValidIndexes { get; set; } internal IEnumerable<DbIndexDefinition> DbIndexDefinitions { get; set; } /// <summary> /// Checks in the db which version is installed based on the migrations that have been run /// </summary> /// <param name="migrationEntryService"></param> /// <returns></returns> public SemVersion DetermineInstalledVersionByMigrations(IMigrationEntryService migrationEntryService) { SemVersion mostrecent = null; if (ValidTables.Any(x => x.InvariantEquals("umbracoMigration"))) { var allMigrations = migrationEntryService.GetAll(Constants.System.UmbracoMigrationName); mostrecent = allMigrations.OrderByDescending(x => x.Version).Select(x => x.Version).FirstOrDefault(); } return mostrecent ?? new SemVersion(new Version(0, 0, 0)); } /// <summary> /// Determines the version of the currently installed database by detecting the current database structure /// </summary> /// <returns> /// A <see cref="Version"/> with Major and Minor values for /// non-empty database, otherwise "0.0.0" for empty databases. /// </returns> public Version DetermineInstalledVersion() { //If (ValidTables.Count == 0) database is empty and we return -> new Version(0, 0, 0); if (ValidTables.Count == 0) return new Version(0, 0, 0); //If Errors is empty or if TableDefinitions tables + columns correspond to valid tables + columns then we're at current version if (Errors.Any() == false || (TableDefinitions.All(x => ValidTables.Contains(x.Name)) && TableDefinitions.SelectMany(definition => definition.Columns).All(x => ValidColumns.Contains(x.Name)))) return UmbracoVersion.Current; //If Errors contains umbracoApp or umbracoAppTree its pre-6.0.0 -> new Version(4, 10, 0); if (Errors.Any(x => x.Item1.Equals("Table") && (x.Item2.InvariantEquals("umbracoApp") || x.Item2.InvariantEquals("umbracoAppTree")))) { //If Errors contains umbracoUser2app or umbracoAppTree foreignkey to umbracoApp exists its pre-4.8.0 -> new Version(4, 7, 0); if (Errors.Any(x => x.Item1.Equals("Constraint") && (x.Item2.InvariantContains("umbracoUser2app_umbracoApp") || x.Item2.InvariantContains("umbracoAppTree_umbracoApp")))) { return new Version(4, 7, 0); } return new Version(4, 8, 0); } //if the error is for umbracoServer if (Errors.Any(x => x.Item1.Equals("Table") && (x.Item2.InvariantEquals("umbracoServer")))) { return new Version(6, 0, 0); } //if the error indicates a problem with the column cmsMacroProperty.macroPropertyType then it is not version 7 // since these columns get removed in v7 if (Errors.Any(x => x.Item1.Equals("Column") && (x.Item2.InvariantEquals("cmsMacroProperty,macroPropertyType")))) { //if the error is for this IX_umbracoNodeTrashed which is added in 6.2 AND in 7.1 but we do not have the above columns // then it must mean that we aren't on 6.2 so must be 6.1 if (Errors.Any(x => x.Item1.Equals("Index") && (x.Item2.InvariantEquals("IX_umbracoNodeTrashed")))) { return new Version(6, 1, 0); } else { //if there are no errors for that index, then the person must have 6.2 installed return new Version(6, 2, 0); } } //if the error indicates a problem with the constraint FK_cmsContent_cmsContentType_nodeId then it is not version 7.2 // since this gets added in 7.2.0 so it must be the previous version if (Errors.Any(x => x.Item1.Equals("Constraint") && (x.Item2.InvariantEquals("FK_cmsContent_cmsContentType_nodeId")))) { return new Version(7, 0, 0); } //if the error is for umbracoAccess it must be the previous version to 7.3 since that is when it is added if (Errors.Any(x => x.Item1.Equals("Table") && (x.Item2.InvariantEquals("umbracoAccess")))) { return new Version(7, 2, 0); } //if the error is for umbracoDeployChecksum it must be the previous version to 7.4 since that is when it is added if (Errors.Any(x => x.Item1.Equals("Table") && (x.Item2.InvariantEquals("umbracoDeployChecksum")))) { return new Version(7, 3, 0); } //if the error is for umbracoRedirectUrl it must be the previous version to 7.5 since that is when it is added if (Errors.Any(x => x.Item1.Equals("Table") && (x.Item2.InvariantEquals("umbracoRedirectUrl")))) { return new Version(7, 4, 0); } //if the error indicates a problem with the column cmsMacroProperty.uniquePropertyId then it is not version 7.6 since that is when it is added if (Errors.Any(x => x.Item1.Equals("Column") && (x.Item2.InvariantEquals("cmsMacroProperty,uniquePropertyId")))) { return new Version(7, 5, 0); } //if the error is for umbracoUserGroup it must be the previous version to 7.7 since that is when it is added if (Errors.Any(x => x.Item1.Equals("Table") && (x.Item2.InvariantEquals("umbracoUserStartNode")))) { return new Version(7, 6, 0); } //if the error is for cmsMedia it must be the previous version to 7.8 since that is when it is added if (Errors.Any(x => x.Item1.Equals("Table") && (x.Item2.InvariantEquals("cmsMedia")))) { return new Version(7, 7, 0); } return UmbracoVersion.Current; } /// <summary> /// Gets a summary of the schema validation result /// </summary> /// <returns>A string containing a human readable string with a summary message</returns> public string GetSummary() { var sb = new StringBuilder(); if (Errors.Any() == false) { sb.AppendLine("The database schema validation didn't find any errors."); return sb.ToString(); } //Table error summary if (Errors.Any(x => x.Item1.Equals("Table"))) { sb.AppendLine("The following tables were found in the database, but are not in the current schema:"); sb.AppendLine(string.Join(",", Errors.Where(x => x.Item1.Equals("Table")).Select(x => x.Item2))); sb.AppendLine(" "); } //Column error summary if (Errors.Any(x => x.Item1.Equals("Column"))) { sb.AppendLine("The following columns were found in the database, but are not in the current schema:"); sb.AppendLine(string.Join(",", Errors.Where(x => x.Item1.Equals("Column")).Select(x => x.Item2))); sb.AppendLine(" "); } //Constraint error summary if (Errors.Any(x => x.Item1.Equals("Constraint"))) { sb.AppendLine("The following constraints (Primary Keys, Foreign Keys and Indexes) were found in the database, but are not in the current schema:"); sb.AppendLine(string.Join(",", Errors.Where(x => x.Item1.Equals("Constraint")).Select(x => x.Item2))); sb.AppendLine(" "); } //Index error summary if (Errors.Any(x => x.Item1.Equals("Index"))) { sb.AppendLine("The following indexes were found in the database, but are not in the current schema:"); sb.AppendLine(string.Join(",", Errors.Where(x => x.Item1.Equals("Index")).Select(x => x.Item2))); sb.AppendLine(" "); } //Unknown constraint error summary if (Errors.Any(x => x.Item1.Equals("Unknown"))) { sb.AppendLine("The following unknown constraints (Primary Keys, Foreign Keys and Indexes) were found in the database, but are not in the current schema:"); sb.AppendLine(string.Join(",", Errors.Where(x => x.Item1.Equals("Unknown")).Select(x => x.Item2))); sb.AppendLine(" "); } if (SqlSyntaxContext.SqlSyntaxProvider is MySqlSyntaxProvider) { sb.AppendLine("Please note that the constraints could not be validated because the current dataprovider is MySql."); } return sb.ToString(); } } }
// // DateParser.cs // // Author: Jeffrey Stedfast <jeff@xamarin.com> // // Copyright (c) 2013-2015 Xamarin Inc. (www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.Text; using System.Collections.Generic; #if PORTABLE using Encoding = Portable.Text.Encoding; #endif namespace MimeKit.Utils { [Flags] enum DateTokenFlags : byte { None = 0, NonNumeric = (1 << 0), NonWeekday = (1 << 1), NonMonth = (1 << 2), NonTime = (1 << 3), NonAlphaZone = (1 << 4), NonNumericZone = (1 << 5), HasColon = (1 << 6), HasSign = (1 << 7), } class DateToken { public DateTokenFlags Flags { get; private set; } public int StartIndex { get; private set; } public int Length { get; private set; } public bool IsNumeric { get { return (Flags & DateTokenFlags.NonNumeric) == 0; } } public bool IsWeekday { get { return (Flags & DateTokenFlags.NonWeekday) == 0; } } public bool IsMonth { get { return (Flags & DateTokenFlags.NonMonth) == 0; } } public bool IsTimeOfDay { get { return (Flags & DateTokenFlags.NonTime) == 0 && (Flags & DateTokenFlags.HasColon) != 0; } } public bool IsNumericZone { get { return (Flags & DateTokenFlags.NonNumericZone) == 0 && (Flags & DateTokenFlags.HasSign) != 0; } } public bool IsAlphaZone { get { return (Flags & DateTokenFlags.NonAlphaZone) == 0; } } public bool IsTimeZone { get { return IsNumericZone || IsAlphaZone; } } public DateToken (DateTokenFlags flags, int startIndex, int length) { StartIndex = startIndex; Length = length; Flags = flags; } } /// <summary> /// Utility methods to parse and format rfc822 date strings. /// </summary> /// <remarks> /// Utility methods to parse and format rfc822 date strings. /// </remarks> public static class DateUtils { const string MonthCharacters = "JanuaryFebruaryMarchAprilMayJuneJulyAugustSeptemberOctoberNovemberDecember"; const string WeekdayCharacters = "SundayMondayTuesdayWednesdayThursdayFridaySaturday"; const string AlphaZoneCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const string NumericZoneCharacters = "+-0123456789"; const string NumericCharacters = "0123456789"; const string TimeCharacters = "0123456789:"; static readonly string[] Months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; static readonly string[] WeekDays = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; static readonly StringComparer icase = StringComparer.OrdinalIgnoreCase; static readonly Dictionary<string, int> timezones; static readonly DateTokenFlags[] datetok; static DateUtils () { timezones = new Dictionary<string, int> { { "UT", 0 }, { "UTC", 0 }, { "GMT", 0 }, { "EDT", -400 }, { "EST", -500 }, { "CDT", -500 }, { "CST", -600 }, { "MDT", -600 }, { "MST", -700 }, { "PDT", -700 }, { "PST", -800 }, // Note: rfc822 got the signs backwards for the military // timezones so some sending clients may mistakenly use the // wrong values. { "A", 100 }, { "B", 200 }, { "C", 300 }, { "D", 400 }, { "E", 500 }, { "F", 600 }, { "G", 700 }, { "H", 800 }, { "I", 900 }, { "K", 1000 }, { "L", 1100 }, { "M", 1200 }, { "N", -100 }, { "O", -200 }, { "P", -300 }, { "Q", -400 }, { "R", -500 }, { "S", -600 }, { "T", -700 }, { "U", -800 }, { "V", -900 }, { "W", -1000 }, { "X", -1100 }, { "Y", -1200 }, { "Z", 0 }, }; datetok = new DateTokenFlags[256]; var any = new char[2]; for (int c = 0; c < 256; c++) { if (c >= 0x41 && c <= 0x5a) { any[1] = (char) (c + 0x20); any[0] = (char) c; } else if (c >= 0x61 && c <= 0x7a) { any[0] = (char) (c - 0x20); any[1] = (char) c; } if (NumericZoneCharacters.IndexOf ((char) c) == -1) datetok[c] |= DateTokenFlags.NonNumericZone; if (AlphaZoneCharacters.IndexOf ((char) c) == -1) datetok[c] |= DateTokenFlags.NonAlphaZone; if (WeekdayCharacters.IndexOfAny (any) == -1) datetok[c] |= DateTokenFlags.NonWeekday; if (NumericCharacters.IndexOf ((char) c) == -1) datetok[c] |= DateTokenFlags.NonNumeric; if (MonthCharacters.IndexOfAny (any) == -1) datetok[c] |= DateTokenFlags.NonMonth; if (TimeCharacters.IndexOf ((char) c) == -1) datetok[c] |= DateTokenFlags.NonTime; } datetok[':'] |= DateTokenFlags.HasColon; datetok['+'] |= DateTokenFlags.HasSign; datetok['-'] |= DateTokenFlags.HasSign; } static bool TryGetWeekday (DateToken token, byte[] text, out DayOfWeek weekday) { weekday = DayOfWeek.Sunday; if (!token.IsWeekday || token.Length < 3) return false; var name = Encoding.ASCII.GetString (text, token.StartIndex, token.Length); if (name.Length > 3) name = name.Substring (0, 3); for (int day = 0; day < WeekDays.Length; day++) { if (icase.Compare (WeekDays[day], name) == 0) { weekday = (DayOfWeek) day; return true; } } return false; } static bool TryGetDayOfMonth (DateToken token, byte[] text, out int day) { int endIndex = token.StartIndex + token.Length; int index = token.StartIndex; day = 0; if (!token.IsNumeric) return false; if (!ParseUtils.TryParseInt32 (text, ref index, endIndex, out day)) return false; if (day <= 0 || day > 31) return false; return true; } static bool TryGetMonth (DateToken token, byte[] text, out int month) { month = 0; if (!token.IsMonth || token.Length < 3) return false; var name = Encoding.ASCII.GetString (text, token.StartIndex, token.Length); if (name.Length > 3) name = name.Substring (0, 3); for (int i = 0; i < Months.Length; i++) { if (icase.Compare (Months[i], name) == 0) { month = i + 1; return true; } } return false; } static bool TryGetYear (DateToken token, byte[] text, out int year) { int endIndex = token.StartIndex + token.Length; int index = token.StartIndex; year = 0; if (!token.IsNumeric) return false; if (!ParseUtils.TryParseInt32 (text, ref index, endIndex, out year)) return false; if (year < 100) year += (year < 70) ? 2000 : 1900; return year >= 1969; } static bool TryGetTimeOfDay (DateToken token, byte[] text, out int hour, out int minute, out int second) { int endIndex = token.StartIndex + token.Length; int index = token.StartIndex; hour = minute = second = 0; if (!token.IsTimeOfDay) return false; if (!ParseUtils.TryParseInt32 (text, ref index, endIndex, out hour) || hour > 23) return false; if (index >= endIndex || text[index++] != (byte) ':') return false; if (!ParseUtils.TryParseInt32 (text, ref index, endIndex, out minute) || minute > 59) return false; // Allow just hh:mm (i.e. w/o the :ss?) if (index >= endIndex || text[index++] != (byte) ':') return true; if (!ParseUtils.TryParseInt32 (text, ref index, endIndex, out second) || second > 59) return false; return index == endIndex; } static bool TryGetTimeZone (DateToken token, byte[] text, out int tzone) { tzone = 0; if (token.IsNumericZone) { if ((token.Flags & DateTokenFlags.HasSign) == 0) return false; int endIndex = token.StartIndex + token.Length; int index = token.StartIndex; int sign; if (text[index] == (byte) '-') sign = -1; else if (text[index] == (byte) '+') sign = 1; else return false; index++; if (!ParseUtils.TryParseInt32 (text, ref index, endIndex, out tzone) || index != endIndex) return false; tzone *= sign; } else if (token.IsAlphaZone) { if (token.Length > 3) return false; var name = Encoding.ASCII.GetString (text, token.StartIndex, token.Length); if (!timezones.TryGetValue (name, out tzone)) return false; } else { return false; } return true; } static bool IsTokenDelimeter (byte c) { return c == (byte) '-' || c == (byte) '/' || c == (byte) ',' || c.IsWhitespace (); } static IEnumerable<DateToken> TokenizeDate (byte[] text, int startIndex, int length) { int endIndex = startIndex + length; int index = startIndex; DateTokenFlags mask; int start; while (index < endIndex) { if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, false)) break; if (index >= endIndex) break; // get the initial mask for this token if ((mask = datetok[text[index]]) != DateTokenFlags.None) { start = index++; // find the end of this token while (index < endIndex && !IsTokenDelimeter (text[index])) mask |= datetok[text[index++]]; yield return new DateToken (mask, start, index - start); } // skip over the token delimeter index++; } yield break; } static bool TryParseStandardDateFormat (IList<DateToken> tokens, byte[] text, out DateTimeOffset date) { int day, month, year, tzone; int hour, minute, second; DayOfWeek weekday; //bool haveWeekday; int n = 0; date = new DateTimeOffset (); // we need at least 5 tokens, 6 if we have a weekday if (tokens.Count < 5) return false; // Note: the weekday is not required if (TryGetWeekday (tokens[n], text, out weekday)) { if (tokens.Count < 6) return false; //haveWeekday = true; n++; } if (!TryGetDayOfMonth (tokens[n++], text, out day)) return false; if (!TryGetMonth (tokens[n++], text, out month)) return false; if (!TryGetYear (tokens[n++], text, out year)) return false; if (!TryGetTimeOfDay (tokens[n++], text, out hour, out minute, out second)) return false; if (!TryGetTimeZone (tokens[n], text, out tzone)) tzone = 0; while (tzone < -1400) tzone += 2400; while (tzone > 1400) tzone -= 2400; int minutes = tzone % 100; int hours = tzone / 100; var offset = new TimeSpan (hours, minutes, 0); date = new DateTimeOffset (year, month, day, hour, minute, second, offset); return true; } static bool TryParseUnknownDateFormat (IList<DateToken> tokens, byte[] text, out DateTimeOffset date) { int? day = null, month = null, year = null, tzone = null; int hour = 0, minute = 0, second = 0; bool numericMonth = false; bool haveWeekday = false; bool haveTime = false; DayOfWeek weekday; TimeSpan offset; for (int i = 0; i < tokens.Count; i++) { int value; if (!haveWeekday && tokens[i].IsWeekday) { if (TryGetWeekday (tokens[i], text, out weekday)) { haveWeekday = true; continue; } } if ((month == null || numericMonth) && tokens[i].IsMonth) { if (TryGetMonth (tokens[i], text, out value)) { if (numericMonth) { numericMonth = false; day = month; } month = value; continue; } } if (!haveTime && tokens[i].IsTimeOfDay) { if (TryGetTimeOfDay (tokens[i], text, out hour, out minute, out second)) { haveTime = true; continue; } } if (tzone == null && tokens[i].IsTimeZone) { if (TryGetTimeZone (tokens[i], text, out value)) { tzone = value; continue; } } if (tokens[i].IsNumeric) { if (tokens[i].Length == 4) { if (year == null && TryGetYear (tokens[i], text, out value)) year = value; continue; } if (tokens[i].Length > 2) continue; // Note: we likely have either YYYY[-/]MM[-/]DD or MM[-/]DD[-/]YY int endIndex = tokens[i].StartIndex + tokens[i].Length; int index = tokens[i].StartIndex; ParseUtils.TryParseInt32 (text, ref index, endIndex, out value); if (month == null && value > 0 && value <= 12) { numericMonth = true; month = value; continue; } if (day == null && value > 0 && value <= 31) { day = value; continue; } if (year == null && value >= 69) { year = 1900 + value; continue; } } // WTF is this?? } if (year == null || month == null || day == null) { date = new DateTimeOffset (); return false; } if (!haveTime) hour = minute = second = 0; if (tzone != null) { int minutes = tzone.Value % 100; int hours = tzone.Value / 100; offset = new TimeSpan (hours, minutes, 0); } else { offset = new TimeSpan (0); } date = new DateTimeOffset (year.Value, month.Value, day.Value, hour, minute, second, offset); return true; } /// <summary> /// Tries to parse the given input buffer into a new <see cref="System.DateTimeOffset"/> instance. /// </summary> /// <remarks> /// Parses an rfc822 date and time from the supplied buffer starting at the given index /// and spanning across the specified number of bytes. /// </remarks> /// <returns><c>true</c>, if the date was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="buffer">The input buffer.</param> /// <param name="startIndex">The starting index of the input buffer.</param> /// <param name="length">The number of bytes in the input buffer to parse.</param> /// <param name="date">The parsed date.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="buffer"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="startIndex"/> and <paramref name="length"/> do not specify /// a valid range in the byte array. /// </exception> public static bool TryParse (byte[] buffer, int startIndex, int length, out DateTimeOffset date) { if (buffer == null) throw new ArgumentNullException ("buffer"); if (startIndex < 0 || startIndex > buffer.Length) throw new ArgumentOutOfRangeException ("startIndex"); if (length < 0 || length > (buffer.Length - startIndex)) throw new ArgumentOutOfRangeException ("length"); var tokens = new List<DateToken> (TokenizeDate (buffer, startIndex, length)); if (TryParseStandardDateFormat (tokens, buffer, out date)) return true; if (TryParseUnknownDateFormat (tokens, buffer, out date)) return true; date = new DateTimeOffset (); return false; } /// <summary> /// Tries to parse the given input buffer into a new <see cref="System.DateTimeOffset"/> instance. /// </summary> /// <remarks> /// Parses an rfc822 date and time from the supplied buffer starting at the given index /// and spanning across the specified number of bytes. /// </remarks> /// <returns><c>true</c>, if the date was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="buffer">The input buffer.</param> /// <param name="startIndex">The starting index of the input buffer.</param> /// <param name="length">The number of bytes in the input buffer to parse.</param> /// <param name="date">The parsed date.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="buffer"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="startIndex"/> and <paramref name="length"/> do not specify /// a valid range in the byte array. /// </exception> [Obsolete ("Use TryParse (byte[] buffer, int startIndex, int length, out DateTimeOffset date) instead.")] public static bool TryParseDateTime (byte[] buffer, int startIndex, int length, out DateTimeOffset date) { return TryParse (buffer, startIndex, length, out date); } /// <summary> /// Tries to parse the given input buffer into a new <see cref="System.DateTimeOffset"/> instance. /// </summary> /// <remarks> /// Parses an rfc822 date and time from the supplied buffer starting at the specified index. /// </remarks> /// <returns><c>true</c>, if the date was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="buffer">The input buffer.</param> /// <param name="startIndex">The starting index of the input buffer.</param> /// <param name="date">The parsed date.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="buffer"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="startIndex"/> is not within the range of the byte array. /// </exception> public static bool TryParse (byte[] buffer, int startIndex, out DateTimeOffset date) { if (buffer == null) throw new ArgumentNullException ("buffer"); if (startIndex < 0 || startIndex > buffer.Length) throw new ArgumentOutOfRangeException ("startIndex"); int length = buffer.Length - startIndex; var tokens = new List<DateToken> (TokenizeDate (buffer, startIndex, length)); if (TryParseStandardDateFormat (tokens, buffer, out date)) return true; if (TryParseUnknownDateFormat (tokens, buffer, out date)) return true; date = new DateTimeOffset (); return false; } /// <summary> /// Tries to parse the given input buffer into a new <see cref="System.DateTimeOffset"/> instance. /// </summary> /// <remarks> /// Parses an rfc822 date and time from the supplied buffer starting at the specified index. /// </remarks> /// <returns><c>true</c>, if the date was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="buffer">The input buffer.</param> /// <param name="startIndex">The starting index of the input buffer.</param> /// <param name="date">The parsed date.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="buffer"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="startIndex"/> is not within the range of the byte array. /// </exception> [Obsolete ("Use TryParse (byte[] buffer, int startIndex, out DateTimeOffset date) instead.")] public static bool TryParseDateTime (byte[] buffer, int startIndex, out DateTimeOffset date) { return TryParse (buffer, startIndex, out date); } /// <summary> /// Tries to parse the given input buffer into a new <see cref="System.DateTimeOffset"/> instance. /// </summary> /// <remarks> /// Parses an rfc822 date and time from the specified buffer. /// </remarks> /// <returns><c>true</c>, if the date was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="buffer">The input buffer.</param> /// <param name="date">The parsed date.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="buffer"/> is <c>null</c>. /// </exception> public static bool TryParse (byte[] buffer, out DateTimeOffset date) { if (buffer == null) throw new ArgumentNullException ("buffer"); var tokens = new List<DateToken> (TokenizeDate (buffer, 0, buffer.Length)); if (TryParseStandardDateFormat (tokens, buffer, out date)) return true; if (TryParseUnknownDateFormat (tokens, buffer, out date)) return true; date = new DateTimeOffset (); return false; } /// <summary> /// Tries to parse the given input buffer into a new <see cref="System.DateTimeOffset"/> instance. /// </summary> /// <remarks> /// Parses an rfc822 date and time from the specified buffer. /// </remarks> /// <returns><c>true</c>, if the date was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="buffer">The input buffer.</param> /// <param name="date">The parsed date.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="buffer"/> is <c>null</c>. /// </exception> [Obsolete ("Use TryParse (byte[] buffer, out DateTimeOffset date) instead.")] public static bool TryParseDateTime (byte[] buffer, out DateTimeOffset date) { return TryParse (buffer, out date); } /// <summary> /// Tries to parse the given input buffer into a new <see cref="System.DateTimeOffset"/> instance. /// </summary> /// <remarks> /// Parses an rfc822 date and time from the specified text. /// </remarks> /// <returns><c>true</c>, if the date was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="text">The input text.</param> /// <param name="date">The parsed date.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="text"/> is <c>null</c>. /// </exception> public static bool TryParse (string text, out DateTimeOffset date) { if (text == null) throw new ArgumentNullException ("text"); var buffer = Encoding.UTF8.GetBytes (text); var tokens = new List<DateToken> (TokenizeDate (buffer, 0, buffer.Length)); if (TryParseStandardDateFormat (tokens, buffer, out date)) return true; if (TryParseUnknownDateFormat (tokens, buffer, out date)) return true; date = new DateTimeOffset (); return false; } /// <summary> /// Tries to parse the given input buffer into a new <see cref="System.DateTimeOffset"/> instance. /// </summary> /// <remarks> /// Parses an rfc822 date and time from the specified text. /// </remarks> /// <returns><c>true</c>, if the date was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="text">The input text.</param> /// <param name="date">The parsed date.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="text"/> is <c>null</c>. /// </exception> [Obsolete ("Use TryParse (string text, out DateTimeOffset date) instead.")] public static bool TryParseDateTime (string text, out DateTimeOffset date) { return TryParse (text, out date); } // Note: this method exists because BouncyCastle's DerUtcTime.ParseDateString() fails // to parse date strings where the seconds value is not in the range 0 -> 59. // See https://github.com/jstedfast/MimeKit/issues/103 for details. internal static DateTime Parse (string text, string format) { int hour = 0, minute = 0, second = 0; int year = 0, month = 0, day = 0; TimeSpan offset; int timezone; int i = 0; while (i < text.Length && i < format.Length && format[i] != 'z') { if (text[i] < '0' || text[i] > '9') throw new FormatException (); int digit = text[i] - '0'; switch (format[i]) { case 'y': year = (year * 10) + digit; break; case 'M': month = (month * 10) + digit; break; case 'd': day = (day * 10) + digit; break; case 'H': hour = (hour * 10) + digit; break; case 'm': minute = (minute * 10) + digit; break; case 's': second = (second * 10) + digit; break; } i++; } minute += second / 60; second = second % 60; hour += minute / 60; minute = minute % 60; if (!timezones.TryGetValue (text.Substring (i), out timezone)) timezone = 0; offset = new TimeSpan (timezone / 100, timezone % 100, 0); return new DateTime (year, month, day, hour, minute, second, DateTimeKind.Utc).Add (offset); } /// <summary> /// Formats the <see cref="System.DateTimeOffset"/> as an rfc822 date string. /// </summary> /// <remarks> /// Formats the date and time in the format specified by rfc822, suitable for use /// in the Date header of MIME messages. /// </remarks> /// <returns>The formatted string.</returns> /// <param name="date">The date.</param> public static string FormatDate (DateTimeOffset date) { return string.Format ("{0}, {1:00} {2} {3:0000} {4:00}:{5:00}:{6:00} {7:+00;-00}{8:00}", WeekDays[(int) date.DayOfWeek], date.Day, Months[date.Month - 1], date.Year, date.Hour, date.Minute, date.Second, date.Offset.Hours, date.Offset.Minutes); } } }
using System; using System.Diagnostics; using System.Collections.Generic; using System.Text; using System.IO; using System.Globalization; using System.Threading; namespace ICSimulator { public class Simulator { public static Rand rand; // the network (this owns the Routers, the Nodes and the Links) public static Network network; public static Controller controller; public static Stats stats; public const int DIR_UP = 0; public const int DIR_RIGHT = 1; public const int DIR_DOWN = 2; public const int DIR_LEFT = 3; public const int DIR_BLOCKED = -1; public const int DIR_NONE = -99; // simulator state public static ulong CurrentRound = 0; public static bool Warming = false; public static ulong CurrentBarrier = 0; // MT workloads // ready callback and deferred-callback queue public delegate void Ready(); private static PrioQueue<Simulator.Ready> m_deferQueue = new PrioQueue<Simulator.Ready>(); public static void Main(string[] args) { System.Diagnostics.Process.Start("hostname"); Thread.CurrentThread.Priority = ThreadPriority.BelowNormal; Init(args); RunSimulationRun(); Finish(); } public static void Init(string[] args) { Config config = new Config(); config.read(args); rand = new Rand(Config.rand_seed); CurrentRound = 0; controller = Controller.construct(); if (Config.ScalableRingClustered) network = new RC_Network(Config.network_nrX, Config.network_nrY); else if (Config.topology == Topology.HR_16drop) network = new HR_16drop_Network(Config.network_nrX, Config.network_nrY); else if (Config.topology == Topology.HR_4drop) network = new HR_4drop_Network(Config.network_nrX, Config.network_nrY); else if (Config.topology == Topology.HR_8drop) network = new HR_8drop_Network(Config.network_nrX, Config.network_nrY); else if (Config.topology == Topology.HR_8_16drop) network = new HR_8_16drop_Network(Config.network_nrX, Config.network_nrY); else if (Config.topology == Topology.HR_8_8drop) network = new HR_8_8drop_Network(Config.network_nrX, Config.network_nrY); else if (Config.topology == Topology.HR_16_8drop) network = new HR_16_8drop_Network(Config.network_nrX, Config.network_nrY); else if (Config.topology == Topology.HR_32_8drop) network = new HR_32_8drop_Network(Config.network_nrX, Config.network_nrY); else if (Config.topology == Topology.HR_buffered) network = new HR_buffered_Network(Config.network_nrX, Config.network_nrY); else if (Config.topology == Topology.SingleRing) network = new SingleRing_Network(Config.network_nrX, Config.network_nrY); else if (Config.topology == Topology.MeshOfRings) network = new MeshOfRings_Network(Config.network_nrX, Config.network_nrY); else if (Config.topology == Topology.BufRingNetwork) network = new BufRingNetwork(Config.network_nrX, Config.network_nrY); else if (Config.topology == Topology.BufRingNetworkMulti) network = new BufRingMultiNetwork(Config.network_nrX, Config.network_nrY); else network = new Network(Config.network_nrX, Config.network_nrY); network.setup(); Warming = true; } public static void Finish() { if (network.isLivelocked()) Simulator.stats.livelock.Add(); if (!Config.ignore_livelock && network.isLivelocked()) Console.WriteLine("STOPPED DUE TO LIVELOCK."); Simulator.stats.Finish(); using (TextWriter tw = new StreamWriter(Config.output)) { Simulator.stats.DumpJSON(tw); //Simulator.stats.Report(tw); } if (Config.matlab != "") using (TextWriter tw = new StreamWriter(Config.matlab)) { Simulator.stats.DumpMATLAB(tw); } Simulator.network.close(); } public static void RunSimulationRun() { if (File.Exists(Config.output)) { Console.WriteLine("Output file {0} exists; exiting.", Config.output); Environment.Exit(0); } if (Config.RouterEvaluation) RouterEval.evaluate(); else RunSimulation(); Console.WriteLine("simulation finished"); } public static bool DoStep() { // handle pending deferred-callbacks first while (!m_deferQueue.Empty && m_deferQueue.MinPrio <= Simulator.CurrentRound) { m_deferQueue.Dequeue() (); // dequeue and call the callback } if (CurrentRound == (ulong)Config.warmup_cyc) { Console.WriteLine("done warming"); //Console.WriteLine("warmup_cyc {0}",Config.warmup_cyc); //throw new Exception("done warming"); Simulator.stats.Reset(); controller.resetStat(); WarmingStats(); Warming = false; } if (!Warming) Simulator.stats.cycle.Add(); if (CurrentRound % 100000 == 0) ProgressUpdate(); CurrentRound++; network.doStep(); if (Config.simpleLivelock) Router.livelockFreedom(); controller.doStep(); return !network.isFinished() && (Config.ignore_livelock || !network.isLivelocked()); } public static void RunSimulation() { while (DoStep()) ; } //static bool isLivelock = false; static void ProgressUpdate() { if (!Config.progress) return; Console.Out.WriteLine("cycle {0}: {1} flits injected, {2} flits arrived, avg total latency {3}", CurrentRound, Simulator.stats.inject_flit.Count, Simulator.stats.eject_flit.Count, Simulator.stats.total_latency.Avg); Console.WriteLine("TimeStamp = {0}",DateTime.Now); } static void WarmingStats() { // TODO: update this for new caches /* int l1_warmblocks = 0, l1_totblocks = 0; int l2_warmblocks = 0, l2_totblocks = 0; foreach (Node n in network.nodes) { l1_warmblocks += n.cpu.Sets.WarmBlocks; l1_totblocks += n.cpu.Sets.TotalBlocks; l2_warmblocks += n.SharedCache.Sets.WarmBlocks; l2_totblocks += n.SharedCache.Sets.TotalBlocks; } Simulator.stats.l1_warmblocks.Add((ulong)l1_warmblocks); Simulator.stats.l1_totblocks.Add((ulong)l1_totblocks); Simulator.stats.l2_warmblocks.Add((ulong)l2_warmblocks); Simulator.stats.l2_totblocks.Add((ulong)l2_totblocks); */ } public static void Defer(Simulator.Ready cb, ulong cyc) { m_deferQueue.Enqueue(cb, cyc); } public static ulong distance(Coord c1, Coord c2) { return (ulong)(Math.Abs(c1.x - c2.x) + Math.Abs(c1.y - c2.y)); } public static ulong distance(Coord c1, int x, int y) { return (ulong)(Math.Abs(c1.x - x) + Math.Abs(c1.y - y)); } // helpers public static bool hasNeighbor(int dir, Router router) { int x, y; x = router.coord.x; y = router.coord.y; switch (dir) { case DIR_DOWN: y--; break; case DIR_UP: y++; break; case DIR_LEFT: x--; break; case DIR_RIGHT: x++; break; } return x >= 0 && x < Config.network_nrX && y >= 0 && y < Config.network_nrY; } } }
/* * This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson, * the work of Kim Sheffield and the fyiReporting project. * * Prior Copyrights: * _________________________________________________________ * |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others| * | (http://reportfu.org) | * ========================================================= * _________________________________________________________ * |Copyright (C) 2004-2008 fyiReporting Software, LLC | * |For additional information, email info@fyireporting.com | * |or visit the website www.fyiReporting.com. | * ========================================================= * * License: * * 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.Xml; using System.Collections; using System.Collections.Specialized; using System.Threading; using Reporting.Rdl; namespace Reporting.Rdl { ///<summary> /// A report expression: includes original source, parsed expression and type information. ///</summary> [Serializable] internal class DynamicExpression: IExpr { string _Source; // source of expression IExpr _Expr; // expression after parse TypeCode _Type; ReportLink _rl; internal DynamicExpression(Report rpt, ReportLink p, string expr, Row row) { _Source=expr; _Expr = null; _rl = p; _Type = DoParse(rpt); } internal TypeCode DoParse(Report rpt) { // optimization: avoid expression overhead if this isn't really an expression if (_Source == null) { _Expr = new Constant<string>(""); //Originally Plain Constant return _Expr.GetTypeCode(); } else if (_Source == string.Empty || // empty expression _Source[0] != '=') // if 1st char not '=' { _Expr = new Constant<string>(_Source); // this is a constant value return _Expr.GetTypeCode(); } Parser p = new Parser(new System.Collections.Generic.List<ICacheData>()); // find the fields that are part of the DataRegion (if there is one) IDictionary fields=null; ReportLink dr = _rl.Parent; Grouping grp= null; // remember if in a table group or detail group or list group Matrix m=null; while (dr != null) { if (dr is Grouping) p.NoAggregateFunctions = true; else if (dr is TableGroup) grp = ((TableGroup) dr).Grouping; else if (dr is Matrix) { m = (Matrix) dr; // if matrix we need to pass special break; } else if (dr is Details) { grp = ((Details) dr).Grouping; } else if (dr is List) { grp = ((List) dr).Grouping; break; } else if (dr is DataRegion || dr is DataSetDefn) break; dr = dr.Parent; } if (dr != null) { if (dr is DataSetDefn) { DataSetDefn d = (DataSetDefn) dr; if (d.Fields != null) fields = d.Fields.Items; } else // must be a DataRegion { DataRegion d = (DataRegion) dr; if (d.DataSetDefn != null && d.DataSetDefn.Fields != null) fields = d.DataSetDefn.Fields.Items; } } NameLookup lu = new NameLookup(fields, rpt.ReportDefinition.LUReportParameters, rpt.ReportDefinition.LUReportItems, rpt.ReportDefinition.LUGlobals, rpt.ReportDefinition.LUUser, rpt.ReportDefinition.LUAggrScope, grp, m, rpt.ReportDefinition.CodeModules, rpt.ReportDefinition.Classes, rpt.ReportDefinition.DataSetsDefn, rpt.ReportDefinition.CodeType); try { _Expr = p.Parse(lu, _Source); } catch (Exception e) { _Expr = new Constant<string>(e.Message); //Originally ConstantError // Invalid expression rpt.rl.LogError(8, ErrorText(e.Message)); } // Optimize removing any expression that always result in a constant try { _Expr = _Expr.ConstantOptimization(); } catch(Exception ex) { rpt.rl.LogError(4, "Expression:" + _Source + "\r\nConstant Optimization exception:\r\n" + ex.Message + "\r\nStack trace:\r\n" + ex.StackTrace ); } return _Expr.GetTypeCode(); } private string ErrorText(string msg) { ReportLink rl = _rl.Parent; while (rl != null) { if (rl is ReportItem) break; rl = rl.Parent; } string prefix="Expression"; if (rl != null) { ReportItem ri = rl as ReportItem; if (ri.Name != null) prefix = ri.Name.Nm + " expression"; } return prefix + " '" + _Source + "' failed to parse: " + msg; } private void ReportError(Report rpt, int severity, string err) { rpt.rl.LogError(severity, err); } internal string Source { get { return _Source; } } internal IExpr Expr { get { return _Expr; } } internal TypeCode Type { get { return _Type; } } #region IExpr Members public System.TypeCode GetTypeCode() { return _Expr.GetTypeCode(); } public bool IsConstant() { return _Expr.IsConstant(); } public IExpr ConstantOptimization() { return this; } public object Evaluate(Report rpt, Row row) { try { return _Expr.Evaluate(rpt, row); } catch (Exception e) { string err; if (e.InnerException != null) err = String.Format("Exception evaluating {0}. {1}. {2}", _Source, e.Message, e.InnerException.Message); else err = String.Format("Exception evaluating {0}. {1}", _Source, e.Message); ReportError(rpt, 4, err); return null; } } public string EvaluateString(Report rpt, Row row) { try { return _Expr.EvaluateString(rpt, row); } catch (Exception e) { string err = String.Format("Exception evaluating {0}. {1}", _Source, e.Message); ReportError(rpt, 4, err); return null; } } public double EvaluateDouble(Report rpt, Row row) { try { return _Expr.EvaluateDouble(rpt, row); } catch (Exception e) { string err = String.Format("Exception evaluating {0}. {1}", _Source, e.Message); ReportError(rpt, 4, err); return double.NaN; } } public decimal EvaluateDecimal(Report rpt, Row row) { try { return _Expr.EvaluateDecimal(rpt, row); } catch (Exception e) { string err = String.Format("Exception evaluating {0}. {1}", _Source, e.Message); ReportError(rpt, 4, err); return decimal.MinValue; } } public int EvaluateInt32(Report rpt, Row row) { try { return _Expr.EvaluateInt32(rpt, row); } catch (Exception e) { string err = String.Format("Exception evaluating {0}. {1}", _Source, e.Message); ReportError(rpt, 4, err); return int.MinValue; } } public DateTime EvaluateDateTime(Report rpt, Row row) { try { return _Expr.EvaluateDateTime(rpt, row); } catch (Exception e) { string err = String.Format("Exception evaluating {0}. {1}", _Source, e.Message); ReportError(rpt, 4, err); return DateTime.MinValue; } } public bool EvaluateBoolean(Report rpt, Row row) { try { return _Expr.EvaluateBoolean(rpt, row); } catch (Exception e) { string err = String.Format("Exception evaluating {0}. {1}", _Source, e.Message); ReportError(rpt, 4, err); return false; } } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Web.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>(); } /// <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 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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and 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)) { 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="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <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, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [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; } } }
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 DI08.Areas.HelpPage.Models; namespace DI08.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); } } } }
/* XML-RPC.NET proxy class code generator Copyright (c) 2003, Joe Bork <joe@headblender.com> Portions Copyright (c) 2001-2003, Charles Cook <ccook@cookcomputing.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Headblender.XmlRpc { using System; using System.Collections; using System.Reflection; using System.Globalization; using System.Text; using System.IO; using System.CodeDom; using System.CodeDom.Compiler; using ActiveForumsTapatalk.XmlRpc; public sealed class XmlRpcProxyCodeGenOptions { private string GenNamespace = ""; private string GenTypeName = ""; private bool GenImplicitAsync = false; private bool GenFlattenInterfaces = false; public XmlRpcProxyCodeGenOptions() { GenNamespace = ""; GenTypeName = ""; GenImplicitAsync = false; GenFlattenInterfaces = false; } public XmlRpcProxyCodeGenOptions( string initNamespace, string initTypeName, bool initImplicitAsync, bool flattenInterfaces) { GenNamespace = initNamespace; GenTypeName = initTypeName; GenImplicitAsync = initImplicitAsync; GenFlattenInterfaces = flattenInterfaces; } public string Namespace { get { return GenNamespace; } set { GenNamespace = value; } } public string TypeName { get { return GenTypeName; } set { GenTypeName = value; } } public bool ImplicitAsync { get { return GenImplicitAsync; } set { GenImplicitAsync = value; } } public bool FlattenInterfaces { get { return GenFlattenInterfaces; } set { GenFlattenInterfaces = value; } } } public sealed class XmlRpcProxyCodeGen { const string DEFAULT_RET = "xrtReturn"; const string DEFAULT_TEMP = "xrtTemp"; const string DEFAULT_ARR = "xrtArray"; const string DEFAULT_CALLBACK = "xrtCallback"; const string DEFAULT_STATUS = "xrtStatus"; const string DEFAULT_RESULT = "xrtResult"; const string DEFAULT_SUFFIX = "RpcProxy"; const string DEFAULT_END = "End"; const string DEFAULT_BEGIN = "Begin"; private XmlRpcProxyCodeGen() { // no public constructor where all public methods are static } private delegate void BuildMethodDelegate( CodeTypeDeclaration declaration, string methodName, string rpcMethodName, Type[] argTypes, string[] argNames, Type returnType, Type implementationType); public static string CreateCode( Type proxyType, ICodeGenerator generator) { return CreateCode(proxyType, generator, new XmlRpcProxyCodeGenOptions()); } public static string CreateCode( Type proxyType, ICodeGenerator generator, XmlRpcProxyCodeGenOptions options) { if (options == null) { throw new ArgumentNullException( "options", "The options parameter cannot be null"); } CodeCompileUnit ccu = CreateCodeCompileUnit(proxyType, generator, options); CodeGeneratorOptions cgo = new CodeGeneratorOptions(); cgo.BlankLinesBetweenMembers = true; cgo.BracingStyle = "C"; StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); generator.GenerateCodeFromCompileUnit(ccu, sw, cgo); string ret = sw.ToString(); return ret; } public static CodeCompileUnit CreateCodeCompileUnit( Type proxyType, ICodeGenerator generator) { return CreateCodeCompileUnit(proxyType, generator, new XmlRpcProxyCodeGenOptions()); } public static CodeCompileUnit CreateCodeCompileUnit( Type proxyType, ICodeGenerator generator, XmlRpcProxyCodeGenOptions options) { if (options == null) { throw new ArgumentNullException( "options", "The options parameter cannot be null"); } // create unique names string baseName = proxyType.Name; // string leading "I" if (baseName.StartsWith("I") == true) { baseName = baseName.Remove(0,1); } string moduleName = String.Format( CultureInfo.InvariantCulture, "{0}{1}.dll", baseName, DEFAULT_SUFFIX); string assemblyName = ""; if (options.Namespace.Length > 0) { assemblyName = options.Namespace; } else { assemblyName = String.Format( CultureInfo.InvariantCulture, "{0}{1}", baseName, DEFAULT_SUFFIX); } string typeName = ""; if (options.TypeName.Length > 0) { typeName = options.TypeName; } else { typeName = assemblyName; } bool implicitAsync = options.ImplicitAsync; bool flattenInterfaces = options.FlattenInterfaces; CodeCompileUnit ccu = BuildCompileUnit( proxyType, assemblyName, moduleName, typeName, implicitAsync, flattenInterfaces); return ccu; } private static CodeCompileUnit BuildCompileUnit( Type proxyType, string assemblyName, string moduleName, string typeName, bool implicitAsync, bool flattenInterfaces) { string urlString = GetXmlRpcUrl(proxyType); Hashtable methods = GetXmlRpcMethods(proxyType, flattenInterfaces); Hashtable beginMethods = GetXmlRpcBeginMethods(proxyType, flattenInterfaces); Hashtable endMethods = GetXmlRpcEndMethods(proxyType, flattenInterfaces); // if there are no Begin and End methods, // we can implicitly generate them if ((beginMethods.Count == 0) && (endMethods.Count == 0) && (implicitAsync == true)) { beginMethods = GetXmlRpcMethods(proxyType, flattenInterfaces); endMethods = GetXmlRpcMethods(proxyType, flattenInterfaces); } CodeCompileUnit ccu = new CodeCompileUnit(); CodeNamespace cn = new CodeNamespace(assemblyName); cn.Imports.Add(new CodeNamespaceImport("System")); cn.Imports.Add(new CodeNamespaceImport(proxyType.Namespace)); cn.Imports.Add(new CodeNamespaceImport("ActiveForumsTapatalk.XmlRpc")); CodeTypeDeclaration ctd = new CodeTypeDeclaration(typeName); // its a class ctd.IsClass = true; // class is public and sealed ctd.TypeAttributes = TypeAttributes.Public | TypeAttributes.Sealed; // class derives from XmlRpcClientProtocol ctd.BaseTypes.Add(typeof(XmlRpcClientProtocol)); // and implements I(itf) ctd.BaseTypes.Add(proxyType); BuildConstructor(ctd, typeof(XmlRpcClientProtocol), urlString); BuildMethods(ctd, methods, new BuildMethodDelegate(BuildStandardMethod)); BuildMethods(ctd, beginMethods, new BuildMethodDelegate(BuildBeginMethod)); BuildMethods(ctd, endMethods, new BuildMethodDelegate(BuildEndMethod)); cn.Types.Add(ctd); ccu.Namespaces.Add(cn); return ccu; } private static void BuildMethods( CodeTypeDeclaration declaration, Hashtable methods, BuildMethodDelegate buildDelegate) { foreach (DictionaryEntry de in methods) { MethodData mthdData = (MethodData)de.Value; MethodInfo mi = mthdData.mi; Type[] argTypes = new Type[mi.GetParameters().Length]; string[] argNames = new string[mi.GetParameters().Length]; for(int i = 0; i < mi.GetParameters().Length; i++) { argTypes[i] = mi.GetParameters()[i].ParameterType; argNames[i] = mi.GetParameters()[i].Name; } //buildDelegate(declaration, mi.Name, mthdData.xmlRpcName, argTypes, argNames, mi.ReturnType); string n = (string)de.Key; buildDelegate( declaration, n, mthdData.xmlRpcName, argTypes, argNames, mi.ReturnType, mthdData.implementationType); } } private static void BuildStandardMethod( CodeTypeDeclaration declaration, string methodName, string rpcMethodName, Type[] argTypes, string[] argNames, Type returnType, Type implementationType) { CodeMemberMethod cmm = new CodeMemberMethod(); // set the attributes and name // normal, unqualified type names are public cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmm.ImplementationTypes.Add(implementationType); cmm.Name = methodName; // set the return type CodeTypeReference ctrReturn = new CodeTypeReference(returnType); cmm.ReturnType = ctrReturn; MakeParameterList(cmm, argTypes, argNames); // add an XmlRpcMethod attribute to the type CodeAttributeDeclaration cad = new CodeAttributeDeclaration(); cad.Name = typeof(XmlRpcMethodAttribute).FullName; CodeAttributeArgument caa = new CodeAttributeArgument(); CodePrimitiveExpression cpe = new CodePrimitiveExpression(rpcMethodName); caa.Value = cpe; cad.Arguments.Add(caa); cmm.CustomAttributes.Add(cad); // generate the method body: // if non-void return, declared locals for processing return value if (returnType != typeof(void)) { // add some local variables MakeTempVariable(cmm, typeof(System.Object)); MakeReturnVariable(cmm, returnType); } MakeTempParameterArray(cmm, argTypes, argNames); // construct a call to the base Invoke method CodeThisReferenceExpression ctre = new CodeThisReferenceExpression(); CodeMethodReferenceExpression cmre = new CodeMethodReferenceExpression(ctre, "Invoke"); CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression(); cmie.Method = cmre; cmie.Parameters.Add(new CodePrimitiveExpression(methodName)); cmie.Parameters.Add(new CodeVariableReferenceExpression(DEFAULT_ARR)); if (returnType != typeof(void)) { // assign the result to tempRetVal CodeAssignStatement casTemp = new CodeAssignStatement(); casTemp.Left = new CodeVariableReferenceExpression(DEFAULT_TEMP); casTemp.Right = cmie; cmm.Statements.Add(casTemp); } else { // discard return type cmm.Statements.Add(cmie); } MakeReturnStatement(cmm, returnType); // add the finished method to the type declaration.Members.Add(cmm); } private static void BuildBeginMethod( CodeTypeDeclaration declaration, string methodName, string rpcMethodName, Type[] argTypes, string[] argNames, Type returnType, Type implementationType) { string beginMethodName = ""; CodeMemberMethod cmm = new CodeMemberMethod(); // set the attributes and name cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; if (methodName.StartsWith(DEFAULT_BEGIN) == true) { // strip method name prefix cmm.Name = methodName.Substring(DEFAULT_BEGIN.Length, methodName.Length - DEFAULT_BEGIN.Length); } beginMethodName = String.Format(CultureInfo.InvariantCulture, "{0}{1}", DEFAULT_BEGIN, methodName); cmm.Name = beginMethodName; //!cmm.ImplementationTypes.Add(implementationType); // set the return type (always IAsyncResult) cmm.ReturnType = new CodeTypeReference(typeof(System.IAsyncResult)); MakeParameterList(cmm, argTypes, argNames); // add callback and state params cmm.Parameters.Add(new CodeParameterDeclarationExpression( typeof(System.AsyncCallback), DEFAULT_CALLBACK) ); cmm.Parameters.Add(new CodeParameterDeclarationExpression( typeof(System.Object), DEFAULT_STATUS) ); MakeReturnVariable(cmm, typeof(System.IAsyncResult)); MakeTempParameterArray(cmm, argTypes, argNames); // construct a call to the base beginInvoke method CodeThisReferenceExpression ctre = new CodeThisReferenceExpression(); CodeMethodReferenceExpression cmre = new CodeMethodReferenceExpression(ctre, "BeginInvoke"); CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression(); cmie.Method = cmre; cmie.Parameters.Add(new CodePrimitiveExpression(methodName)); cmie.Parameters.Add(new CodeVariableReferenceExpression(DEFAULT_ARR)); cmie.Parameters.Add(new CodeVariableReferenceExpression(DEFAULT_CALLBACK)); cmie.Parameters.Add(new CodeVariableReferenceExpression(DEFAULT_STATUS)); // assign the result to RetVal CodeAssignStatement casTemp = new CodeAssignStatement(); casTemp.Left = new CodeVariableReferenceExpression(DEFAULT_RET); casTemp.Right = cmie; cmm.Statements.Add(casTemp); // return retVal CodeMethodReturnStatement cmrsCast = new CodeMethodReturnStatement(); cmrsCast.Expression = new CodeVariableReferenceExpression(DEFAULT_RET); cmm.Statements.Add(cmrsCast); // add the finished method to the type declaration.Members.Add(cmm); } private static void BuildEndMethod( CodeTypeDeclaration declaration, string methodName, string rpcMethodName, Type[] argTypes, string[] argNames, Type returnType, Type implementationType) { string endMethodName = ""; CodeMemberMethod cmm = new CodeMemberMethod(); // set the attributes and name cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final; if (methodName.StartsWith(DEFAULT_END) == true) { // strip method name prefix cmm.Name = methodName.Substring(DEFAULT_END.Length, methodName.Length - DEFAULT_END.Length); } endMethodName = String.Format(CultureInfo.InvariantCulture, "{0}{1}", DEFAULT_END, methodName); cmm.Name = endMethodName; //!cmm.ImplementationTypes.Add(implementationType); // set the return type CodeTypeReference ctrReturn = new CodeTypeReference(returnType); cmm.ReturnType = ctrReturn; // set the parameter list (always a single IAsyncResult) CodeParameterDeclarationExpression cpde = new CodeParameterDeclarationExpression(); cpde.Name = DEFAULT_RESULT; cpde.Type = new CodeTypeReference(typeof(System.IAsyncResult)); cmm.Parameters.Add(cpde); // generate the method body: // if non-void return, declared locals for processing return value if (returnType != typeof(void)) { // add some local variables: MakeTempVariable(cmm, typeof(System.Object)); MakeReturnVariable(cmm, returnType); } // construct a call to the base EndInvoke method CodeThisReferenceExpression ctre = new CodeThisReferenceExpression(); CodeMethodReferenceExpression cmre = new CodeMethodReferenceExpression(ctre, "EndInvoke"); CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression(); cmie.Method = cmre; cmie.Parameters.Add(new CodeVariableReferenceExpression(DEFAULT_RESULT)); CodeIndexerExpression cie = new CodeIndexerExpression(); cie.TargetObject = cmie; cie.Indices.Add(new CodePrimitiveExpression(0)); if (returnType != typeof(void)) { // assign the result to tempRetVal CodeAssignStatement casTemp = new CodeAssignStatement(); casTemp.Left = new CodeVariableReferenceExpression(DEFAULT_TEMP); //!casTemp.Right = cie; casTemp.Right = cmie; cmm.Statements.Add(casTemp); } else { // discard return type //!cmm.Statements.Add(cie); cmm.Statements.Add(cmie); } MakeReturnStatement(cmm, returnType); // add the finished method to the type declaration.Members.Add(cmm); } private static void BuildConstructor( CodeTypeDeclaration declaration, Type baseType, string urlStr) { CodeConstructor cc = new CodeConstructor(); if (urlStr != null && urlStr.Length > 0) { // add an XmlRpcUrl attribute to the type CodeAttributeDeclaration cad = new CodeAttributeDeclaration(); cad.Name = typeof(XmlRpcUrlAttribute).FullName; CodeAttributeArgument caa = new CodeAttributeArgument(); CodePrimitiveExpression cpe = new CodePrimitiveExpression(urlStr); caa.Value = cpe; cad.Arguments.Add(caa); declaration.CustomAttributes.Add(cad); } // call the base constructor: cc.Attributes = MemberAttributes.Public; // add the constructor to the type declaration.Members.Add(cc); } // ========================================================================== private static string GetXmlRpcUrl(Type proxyType) { Attribute attr = Attribute.GetCustomAttribute( proxyType, typeof(XmlRpcUrlAttribute)); if (attr == null) return null; XmlRpcUrlAttribute xruAttr = attr as XmlRpcUrlAttribute; string url = xruAttr.Uri; return url; } private static Hashtable GetXmlRpcMethods(Type proxyType, bool flatten) { Hashtable ret = new Hashtable(); RecurseGetXmlRpcMethods(proxyType, ref ret, flatten); return ret; } private static void RecurseGetXmlRpcMethods(Type proxyType, ref Hashtable h, bool flatten) { if (!proxyType.IsInterface) throw new Exception("type not interface"); foreach(MethodInfo mi in proxyType.GetMethods()) { string xmlRpcName = GetXmlRpcMethodName(mi); if (xmlRpcName == null) continue; string n = mi.Name; if (h.Contains(n) == true) { throw new Exception("duplicate method name encountered in type hierarchy"); } // add new method h.Add(n, new MethodData(mi, xmlRpcName, mi.ReturnType, proxyType)); } if (flatten == true) { Type[] ifs = proxyType.GetInterfaces(); for (int i = 0; i < ifs.Length; ++i) { RecurseGetXmlRpcMethods(ifs[i], ref h, flatten); } } } private static Hashtable GetXmlRpcBeginMethods(Type proxyType, bool flatten) { Hashtable ret = new Hashtable(); RecurseGetXmlRpcBeginMethods(proxyType, ref ret, flatten); return ret; } private static void RecurseGetXmlRpcBeginMethods(Type proxyType, ref Hashtable h, bool flatten) { if (!proxyType.IsInterface) throw new Exception("type not interface"); foreach(MethodInfo mi in proxyType.GetMethods()) { Attribute attr = Attribute.GetCustomAttribute(mi, typeof(XmlRpcBeginAttribute)); if (attr == null) continue; string rpcMethod = ((XmlRpcBeginAttribute)attr).Method; if (rpcMethod.Length == 0) { if (!mi.Name.StartsWith("Begin") || mi.Name.Length <= 5) throw new Exception(String.Format( CultureInfo.InvariantCulture, "method {0} has invalid signature for begin method", mi.Name)); rpcMethod = mi.Name.Substring(5); } int paramCount = mi.GetParameters().Length; int i; for (i = 0; i < paramCount; i++) { Type paramType = mi.GetParameters()[0].ParameterType; if (paramType == typeof(System.AsyncCallback)) break; } if (paramCount > 1) { if (i < paramCount - 2) throw new Exception(String.Format( CultureInfo.InvariantCulture, "method {0} has invalid signature for begin method", mi.Name)); if (i == (paramCount - 2)) { Type paramType = mi.GetParameters()[i+1].ParameterType; if (paramType != typeof(System.Object)) throw new Exception(String.Format( CultureInfo.InvariantCulture, "method {0} has invalid signature for begin method", mi.Name)); } } string n = mi.Name; if (h.Contains(n) == true) { throw new Exception("duplicate begin method name encountered in type hierarchy"); } h.Add(n, new MethodData(mi, rpcMethod, null, null)); } if (flatten == true) { Type[] ifs = proxyType.GetInterfaces(); for (int i = 0; i < ifs.Length; ++i) { RecurseGetXmlRpcBeginMethods(ifs[i], ref h, flatten); } } } private static Hashtable GetXmlRpcEndMethods(Type proxyType, bool flatten) { Hashtable ret = new Hashtable(); RecurseGetXmlRpcEndMethods(proxyType, ref ret, flatten); return ret; } private static void RecurseGetXmlRpcEndMethods(Type proxyType, ref Hashtable h, bool flatten) { if (!proxyType.IsInterface) throw new Exception("type not interface"); foreach(MethodInfo mi in proxyType.GetMethods()) { Attribute attr = Attribute.GetCustomAttribute(mi, typeof(XmlRpcEndAttribute)); if (attr == null) continue; if (mi.GetParameters().Length != 1) throw new Exception(String.Format( CultureInfo.InvariantCulture, "method {0} has invalid signature for end method", mi.Name)); Type paramType = mi.GetParameters()[0].ParameterType; if (paramType != typeof(System.IAsyncResult)) throw new Exception(String.Format( CultureInfo.InvariantCulture, "method {0} has invalid signature for end method", mi.Name)); string n = mi.Name; if (h.Contains(n) == true) { throw new Exception("duplicate end method name encountered in type hierarchy"); } h.Add(h, new MethodData(mi, "", null, null)); } if (flatten == true) { Type[] ifs = proxyType.GetInterfaces(); for (int i = 0; i < ifs.Length; ++i) { RecurseGetXmlRpcEndMethods(ifs[i], ref h, flatten); } } } private static string GetXmlRpcMethodName(MethodInfo mi) { Attribute attr = Attribute.GetCustomAttribute(mi, typeof(XmlRpcMethodAttribute)); if (attr == null) return null; XmlRpcMethodAttribute xrmAttr = attr as XmlRpcMethodAttribute; string rpcMethod = xrmAttr.Method; if (rpcMethod.Length == 0) { rpcMethod = mi.Name; } return rpcMethod; } private class MethodData { public MethodData(MethodInfo Mi, string XmlRpcName, Type ReturnType, Type ImplementationType) { m_mi = Mi; m_xmlRpcName = XmlRpcName; m_returnType = ReturnType; m_implementationType = ImplementationType; } private MethodInfo m_mi; private string m_xmlRpcName; private Type m_returnType; private Type m_implementationType; public MethodInfo mi { get { return m_mi; } set { m_mi = value; } } public string xmlRpcName { get { return m_xmlRpcName; } set { m_xmlRpcName = value; } } public Type returnType { get { return m_returnType; } set { m_returnType = value; } } public Type implementationType { get { return m_implementationType; } set { m_implementationType = value; } } } // ========================================================================== private static void MakeParameterList(CodeMemberMethod method, Type[] types, string[] names) { // set the parameter list for (int i = 0; i < types.Length; ++i) { CodeParameterDeclarationExpression cpde = new CodeParameterDeclarationExpression(); cpde.Name = names[i]; CodeTypeReference ctr = new CodeTypeReference(types[i]); cpde.Type = ctr; method.Parameters.Add(cpde); } } private static void MakeReturnVariable(CodeMemberMethod method, Type returnType) { // return variable CodeVariableDeclarationStatement cvdsRet = new CodeVariableDeclarationStatement(); cvdsRet.Name = DEFAULT_RET; cvdsRet.Type = new CodeTypeReference(returnType); if (returnType.IsValueType == false) { cvdsRet.InitExpression = new CodePrimitiveExpression(null); } method.Statements.Add(cvdsRet); } private static void MakeTempVariable(CodeMemberMethod method, Type tempType) { // temp object variable CodeVariableDeclarationStatement cvdsTemp = new CodeVariableDeclarationStatement(); cvdsTemp.Name = DEFAULT_TEMP; cvdsTemp.Type = new CodeTypeReference(tempType); if (tempType.IsValueType == false) { cvdsTemp.InitExpression = new CodePrimitiveExpression(null); } method.Statements.Add(cvdsTemp); } private static void MakeTempParameterArray(CodeMemberMethod method, Type[] types, string[] names) { // declare array variable to store method args CodeVariableDeclarationStatement cvdsArr = new CodeVariableDeclarationStatement(); cvdsArr.Name = DEFAULT_ARR; CodeTypeReference ctrArrType = new CodeTypeReference(typeof(System.Object)); CodeTypeReference ctrArr = new CodeTypeReference(ctrArrType, 1); cvdsArr.Type = ctrArr; // gen code to initialize the array CodeArrayCreateExpression cace = new CodeArrayCreateExpression(typeof(System.Object), 1); // create array initializers for (int i = 0; i < types.Length; ++i) { CodeArgumentReferenceExpression care = new CodeArgumentReferenceExpression(); care.ParameterName = names[i]; cace.Initializers.Add(care); } cvdsArr.InitExpression = cace; method.Statements.Add(cvdsArr); } private static void MakeReturnStatement(CodeMemberMethod method, Type returnType) { if (returnType != typeof(void)) { // create a cast statement CodeCastExpression cce = new CodeCastExpression( returnType, new CodeVariableReferenceExpression(DEFAULT_TEMP) ); CodeAssignStatement casCast = new CodeAssignStatement(); casCast.Left = new CodeVariableReferenceExpression(DEFAULT_RET); casCast.Right = cce; method.Statements.Add(casCast); // return retVal CodeMethodReturnStatement cmrsCast = new CodeMethodReturnStatement(); cmrsCast.Expression = new CodeVariableReferenceExpression(DEFAULT_RET); method.Statements.Add(cmrsCast); } else { // construct an undecorated return statement method.Statements.Add(new CodeMethodReturnStatement()); } } } }
/* * Copyright 2009 ZXing 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. */ using System; using System.Text; #if (SILVERLIGHT4 || SILVERLIGHT5 || NET40 || NET45 || NET46 || NET47 || NETFX_CORE || NETSTANDARD) && !NETSTANDARD1_0 using System.Numerics; #else using BigIntegerLibrary; #endif using ZXing.Common; namespace ZXing.PDF417.Internal { /// <summary> /// <p>This class contains the methods for decoding the PDF417 codewords.</p> /// /// <author>SITA Lab (kevin.osullivan@sita.aero)</author> /// </summary> internal static class DecodedBitStreamParser { private enum Mode { ALPHA, LOWER, MIXED, PUNCT, ALPHA_SHIFT, PUNCT_SHIFT } private const int TEXT_COMPACTION_MODE_LATCH = 900; private const int BYTE_COMPACTION_MODE_LATCH = 901; private const int NUMERIC_COMPACTION_MODE_LATCH = 902; private const int BYTE_COMPACTION_MODE_LATCH_6 = 924; private const int ECI_USER_DEFINED = 925; private const int ECI_GENERAL_PURPOSE = 926; private const int ECI_CHARSET = 927; private const int BEGIN_MACRO_PDF417_CONTROL_BLOCK = 928; private const int BEGIN_MACRO_PDF417_OPTIONAL_FIELD = 923; private const int MACRO_PDF417_TERMINATOR = 922; private const int MODE_SHIFT_TO_BYTE_COMPACTION_MODE = 913; private const int MAX_NUMERIC_CODEWORDS = 15; private const int PL = 25; private const int LL = 27; private const int AS = 27; private const int ML = 28; private const int AL = 28; private const int PS = 29; private const int PAL = 29; private static readonly char[] PUNCT_CHARS = ";<>@[\\]_`~!\r\t,:\n-.$/\"|*()?{}'".ToCharArray(); private static readonly char[] MIXED_CHARS = "0123456789&\r\t,:#-.$/+%*=^".ToCharArray(); #if (SILVERLIGHT4 || SILVERLIGHT5 || NET40 || NET45 || NET46 || NET47 || NETFX_CORE || NETSTANDARD) && !NETSTANDARD1_0 /// <summary> /// Table containing values for the exponent of 900. /// This is used in the numeric compaction decode algorithm. /// </summary> private static readonly BigInteger[] EXP900; static DecodedBitStreamParser() { EXP900 = new BigInteger[16]; EXP900[0] = BigInteger.One; BigInteger nineHundred = new BigInteger(900); EXP900[1] = nineHundred; for (int i = 2; i < EXP900.Length; i++) { EXP900[i] = BigInteger.Multiply(EXP900[i - 1], nineHundred); } } #else /// <summary> /// Table containing values for the exponent of 900. /// This is used in the numeric compaction decode algorithm. /// </summary> private static readonly BigInteger[] EXP900; static DecodedBitStreamParser() { EXP900 = new BigInteger[16]; EXP900[0] = BigInteger.One; BigInteger nineHundred = new BigInteger(900); EXP900[1] = nineHundred; for (int i = 2; i < EXP900.Length; i++) { EXP900[i] = BigInteger.Multiplication(EXP900[i - 1], nineHundred); } } #endif private const int NUMBER_OF_SEQUENCE_CODEWORDS = 2; internal static DecoderResult decode(int[] codewords, String ecLevel) { var result = new StringBuilder(codewords.Length * 2); // Get compaction mode int codeIndex = 1; int code = codewords[codeIndex++]; var resultMetadata = new PDF417ResultMetadata(); Encoding encoding = null; while (codeIndex < codewords[0]) { switch (code) { case TEXT_COMPACTION_MODE_LATCH: codeIndex = textCompaction(codewords, codeIndex, result); break; case BYTE_COMPACTION_MODE_LATCH: case BYTE_COMPACTION_MODE_LATCH_6: codeIndex = byteCompaction(code, codewords, encoding ?? (encoding = getEncoding(PDF417HighLevelEncoder.DEFAULT_ENCODING_NAME)), codeIndex, result); break; case MODE_SHIFT_TO_BYTE_COMPACTION_MODE: result.Append((char)codewords[codeIndex++]); break; case NUMERIC_COMPACTION_MODE_LATCH: codeIndex = numericCompaction(codewords, codeIndex, result); break; case ECI_CHARSET: var charsetECI = CharacterSetECI.getCharacterSetECIByValue(codewords[codeIndex++]); encoding = getEncoding(charsetECI.EncodingName); break; case ECI_GENERAL_PURPOSE: // Can't do anything with generic ECI; skip its 2 characters codeIndex += 2; break; case ECI_USER_DEFINED: // Can't do anything with user ECI; skip its 1 character codeIndex++; break; case BEGIN_MACRO_PDF417_CONTROL_BLOCK: codeIndex = decodeMacroBlock(codewords, codeIndex, resultMetadata); break; case BEGIN_MACRO_PDF417_OPTIONAL_FIELD: case MACRO_PDF417_TERMINATOR: // Should not see these outside a macro block return null; default: // Default to text compaction. During testing numerous barcodes // appeared to be missing the starting mode. In these cases defaulting // to text compaction seems to work. codeIndex--; codeIndex = textCompaction(codewords, codeIndex, result); break; } if (codeIndex < 0) return null; if (codeIndex < codewords.Length) { code = codewords[codeIndex++]; } else { return null; } } if (result.Length == 0) { return null; } var decoderResult = new DecoderResult(null, result.ToString(), null, ecLevel); decoderResult.Other = resultMetadata; return decoderResult; } private static Encoding getEncoding(string encodingName) { Encoding encoding = null; try { encoding = Encoding.GetEncoding(encodingName); } #if (WINDOWS_PHONE70 || WINDOWS_PHONE71 || SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE || NETSTANDARD || MONOANDROID || MONOTOUCH) catch (ArgumentException) { try { // Silverlight only supports a limited number of character sets, trying fallback to UTF-8 encoding = Encoding.GetEncoding("UTF-8"); } catch (Exception) { } } #endif #if WindowsCE catch (PlatformNotSupportedException) { try { // WindowsCE doesn't support all encodings. But it is device depended. // So we try here the some different ones if (encodingName == "ISO-8859-1") { encoding = Encoding.GetEncoding(1252); } else { encoding = Encoding.GetEncoding("UTF-8"); } } catch (Exception) { } } #endif catch (Exception) { return null; } return encoding; } private static int decodeMacroBlock(int[] codewords, int codeIndex, PDF417ResultMetadata resultMetadata) { if (codeIndex + NUMBER_OF_SEQUENCE_CODEWORDS > codewords[0]) { // we must have at least two bytes left for the segment index return -1; } var segmentIndexArray = new int[NUMBER_OF_SEQUENCE_CODEWORDS]; for (var i = 0; i < NUMBER_OF_SEQUENCE_CODEWORDS; i++, codeIndex++) { segmentIndexArray[i] = codewords[codeIndex]; } var s = decodeBase900toBase10(segmentIndexArray, NUMBER_OF_SEQUENCE_CODEWORDS); if (s == null) return -1; resultMetadata.SegmentIndex = Int32.Parse(s); var fileId = new StringBuilder(); codeIndex = textCompaction(codewords, codeIndex, fileId); resultMetadata.FileId = fileId.ToString(); switch (codewords[codeIndex]) { case BEGIN_MACRO_PDF417_OPTIONAL_FIELD: codeIndex++; var additionalOptionCodeWords = new int[codewords[0] - codeIndex]; var additionalOptionCodeWordsIndex = 0; var end = false; while ((codeIndex < codewords[0]) && !end) { var code = codewords[codeIndex++]; if (code < TEXT_COMPACTION_MODE_LATCH) { additionalOptionCodeWords[additionalOptionCodeWordsIndex++] = code; } else { switch (code) { case MACRO_PDF417_TERMINATOR: resultMetadata.IsLastSegment = true; codeIndex++; end = true; break; default: return -1; } } } resultMetadata.OptionalData = new int[additionalOptionCodeWordsIndex]; Array.Copy(additionalOptionCodeWords, resultMetadata.OptionalData, additionalOptionCodeWordsIndex); break; case MACRO_PDF417_TERMINATOR: resultMetadata.IsLastSegment = true; codeIndex++; break; } return codeIndex; } /// <summary> /// Text Compaction mode (see 5.4.1.5) permits all printable ASCII characters to be /// encoded, i.e. values 32 - 126 inclusive in accordance with ISO/IEC 646 (IRV), as /// well as selected control characters. /// /// <param name="codewords">The array of codewords (data + error)</param> /// <param name="codeIndex">The current index into the codeword array.</param> /// <param name="result">The decoded data is appended to the result.</param> /// <returns>The next index into the codeword array.</returns> /// </summary> private static int textCompaction(int[] codewords, int codeIndex, StringBuilder result) { // 2 character per codeword int[] textCompactionData = new int[(codewords[0] - codeIndex) << 1]; // Used to hold the byte compaction value if there is a mode shift int[] byteCompactionData = new int[(codewords[0] - codeIndex) << 1]; int index = 0; bool end = false; while ((codeIndex < codewords[0]) && !end) { int code = codewords[codeIndex++]; if (code < TEXT_COMPACTION_MODE_LATCH) { textCompactionData[index] = code / 30; textCompactionData[index + 1] = code % 30; index += 2; } else { switch (code) { case TEXT_COMPACTION_MODE_LATCH: // reinitialize text compaction mode to alpha sub mode textCompactionData[index++] = TEXT_COMPACTION_MODE_LATCH; break; case BYTE_COMPACTION_MODE_LATCH: case BYTE_COMPACTION_MODE_LATCH_6: case NUMERIC_COMPACTION_MODE_LATCH: case BEGIN_MACRO_PDF417_CONTROL_BLOCK: case BEGIN_MACRO_PDF417_OPTIONAL_FIELD: case MACRO_PDF417_TERMINATOR: codeIndex--; end = true; break; case MODE_SHIFT_TO_BYTE_COMPACTION_MODE: // The Mode Shift codeword 913 shall cause a temporary // switch from Text Compaction mode to Byte Compaction mode. // This switch shall be in effect for only the next codeword, // after which the mode shall revert to the prevailing sub-mode // of the Text Compaction mode. Codeword 913 is only available // in Text Compaction mode; its use is described in 5.4.2.4. textCompactionData[index] = MODE_SHIFT_TO_BYTE_COMPACTION_MODE; code = codewords[codeIndex++]; byteCompactionData[index] = code; index++; break; } } } decodeTextCompaction(textCompactionData, byteCompactionData, index, result); return codeIndex; } /// <summary> /// The Text Compaction mode includes all the printable ASCII characters /// (i.e. values from 32 to 126) and three ASCII control characters: HT or tab /// (ASCII value 9), LF or line feed (ASCII value 10), and CR or carriage /// return (ASCII value 13). The Text Compaction mode also includes various latch /// and shift characters which are used exclusively within the mode. The Text /// Compaction mode encodes up to 2 characters per codeword. The compaction rules /// for converting data into PDF417 codewords are defined in 5.4.2.2. The sub-mode /// switches are defined in 5.4.2.3. /// /// <param name="textCompactionData">The text compaction data.</param> /// <param name="byteCompactionData">The byte compaction data if there</param> /// was a mode shift. /// <param name="length">The size of the text compaction and byte compaction data.</param> /// <param name="result">The decoded data is appended to the result.</param> /// </summary> private static void decodeTextCompaction(int[] textCompactionData, int[] byteCompactionData, int length, StringBuilder result) { // Beginning from an initial state of the Alpha sub-mode // The default compaction mode for PDF417 in effect at the start of each symbol shall always be Text // Compaction mode Alpha sub-mode (uppercase alphabetic). A latch codeword from another mode to the Text // Compaction mode shall always switch to the Text Compaction Alpha sub-mode. Mode subMode = Mode.ALPHA; Mode priorToShiftMode = Mode.ALPHA; int i = 0; while (i < length) { int subModeCh = textCompactionData[i]; char? ch = null; switch (subMode) { case Mode.ALPHA: // Alpha (uppercase alphabetic) if (subModeCh < 26) { // Upper case Alpha Character ch = (char)('A' + subModeCh); } else { switch (subModeCh) { case 26: ch = ' '; break; case LL: subMode = Mode.LOWER; break; case ML: subMode = Mode.MIXED; break; case PS: // Shift to punctuation priorToShiftMode = subMode; subMode = Mode.PUNCT_SHIFT; break; case MODE_SHIFT_TO_BYTE_COMPACTION_MODE: // TODO Does this need to use the current character encoding? See other occurrences below result.Append((char) byteCompactionData[i]); break; case TEXT_COMPACTION_MODE_LATCH: subMode = Mode.ALPHA; break; } } break; case Mode.LOWER: // Lower (lowercase alphabetic) if (subModeCh < 26) { ch = (char) ('a' + subModeCh); } else { switch (subModeCh) { case 26: ch = ' '; break; case AS: // Shift to alpha priorToShiftMode = subMode; subMode = Mode.ALPHA_SHIFT; break; case ML: subMode = Mode.MIXED; break; case PS: // Shift to punctuation priorToShiftMode = subMode; subMode = Mode.PUNCT_SHIFT; break; case MODE_SHIFT_TO_BYTE_COMPACTION_MODE: // TODO Does this need to use the current character encoding? See other occurrences below result.Append((char) byteCompactionData[i]); break; case TEXT_COMPACTION_MODE_LATCH: subMode = Mode.ALPHA; break; } } break; case Mode.MIXED: // Mixed (numeric and some punctuation) if (subModeCh < PL) { ch = MIXED_CHARS[subModeCh]; } else { switch (subModeCh) { case PL: subMode = Mode.PUNCT; break; case 26: ch = ' '; break; case LL: subMode = Mode.LOWER; break; case AL: subMode = Mode.ALPHA; break; case PS: // Shift to punctuation priorToShiftMode = subMode; subMode = Mode.PUNCT_SHIFT; break; case MODE_SHIFT_TO_BYTE_COMPACTION_MODE: result.Append((char) byteCompactionData[i]); break; case TEXT_COMPACTION_MODE_LATCH: subMode = Mode.ALPHA; break; } } break; case Mode.PUNCT: // Punctuation if (subModeCh < PAL) { ch = PUNCT_CHARS[subModeCh]; } else { switch (subModeCh) { case PAL: subMode = Mode.ALPHA; break; case MODE_SHIFT_TO_BYTE_COMPACTION_MODE: result.Append((char) byteCompactionData[i]); break; case TEXT_COMPACTION_MODE_LATCH: subMode = Mode.ALPHA; break; } } break; case Mode.ALPHA_SHIFT: // Restore sub-mode subMode = priorToShiftMode; if (subModeCh < 26) { ch = (char) ('A' + subModeCh); } else { switch (subModeCh) { case 26: ch = ' '; break; case TEXT_COMPACTION_MODE_LATCH: subMode = Mode.ALPHA; break; } } break; case Mode.PUNCT_SHIFT: // Restore sub-mode subMode = priorToShiftMode; if (subModeCh < PAL) { ch = PUNCT_CHARS[subModeCh]; } else { switch (subModeCh) { case PAL: subMode = Mode.ALPHA; break; case MODE_SHIFT_TO_BYTE_COMPACTION_MODE: // PS before Shift-to-Byte is used as a padding character, // see 5.4.2.4 of the specification result.Append((char) byteCompactionData[i]); break; case TEXT_COMPACTION_MODE_LATCH: subMode = Mode.ALPHA; break; } } break; } if (ch != null) { // Append decoded character to result result.Append(ch.Value); } i++; } } /// <summary> /// Byte Compaction mode (see 5.4.3) permits all 256 possible 8-bit byte values to be encoded. /// This includes all ASCII characters value 0 to 127 inclusive and provides for international /// character set support. /// /// <param name="mode">The byte compaction mode i.e. 901 or 924</param> /// <param name="codewords">The array of codewords (data + error)</param> /// <param name="encoding">Currently active character encoding</param> /// <param name="codeIndex">The current index into the codeword array.</param> /// <param name="result">The decoded data is appended to the result.</param> /// <returns>The next index into the codeword array.</returns> /// </summary> private static int byteCompaction(int mode, int[] codewords, Encoding encoding, int codeIndex, StringBuilder result) { var count = 0; var value = 0L; var end = false; using (var decodedBytes = new System.IO.MemoryStream()) { switch (mode) { case BYTE_COMPACTION_MODE_LATCH: // Total number of Byte Compaction characters to be encoded // is not a multiple of 6 int[] byteCompactedCodewords = new int[6]; int nextCode = codewords[codeIndex++]; while ((codeIndex < codewords[0]) && !end) { byteCompactedCodewords[count++] = nextCode; // Base 900 value = 900*value + nextCode; nextCode = codewords[codeIndex++]; // perhaps it should be ok to check only nextCode >= TEXT_COMPACTION_MODE_LATCH switch (nextCode) { case TEXT_COMPACTION_MODE_LATCH: case BYTE_COMPACTION_MODE_LATCH: case NUMERIC_COMPACTION_MODE_LATCH: case BYTE_COMPACTION_MODE_LATCH_6: case BEGIN_MACRO_PDF417_CONTROL_BLOCK: case BEGIN_MACRO_PDF417_OPTIONAL_FIELD: case MACRO_PDF417_TERMINATOR: codeIndex--; end = true; break; default: if ((count%5 == 0) && (count > 0)) { // Decode every 5 codewords // Convert to Base 256 for (int j = 0; j < 6; ++j) { decodedBytes.WriteByte((byte) (value >> (8*(5 - j)))); } value = 0; count = 0; } break; } } // if the end of all codewords is reached the last codeword needs to be added if (codeIndex == codewords[0] && nextCode < TEXT_COMPACTION_MODE_LATCH) { byteCompactedCodewords[count++] = nextCode; } // If Byte Compaction mode is invoked with codeword 901, // the last group of codewords is interpreted directly // as one byte per codeword, without compaction. for (int i = 0; i < count; i++) { decodedBytes.WriteByte((byte) byteCompactedCodewords[i]); } break; case BYTE_COMPACTION_MODE_LATCH_6: // Total number of Byte Compaction characters to be encoded // is an integer multiple of 6 while (codeIndex < codewords[0] && !end) { int code = codewords[codeIndex++]; if (code < TEXT_COMPACTION_MODE_LATCH) { count++; // Base 900 value = 900*value + code; } else { switch (code) { case TEXT_COMPACTION_MODE_LATCH: case BYTE_COMPACTION_MODE_LATCH: case NUMERIC_COMPACTION_MODE_LATCH: case BYTE_COMPACTION_MODE_LATCH_6: case BEGIN_MACRO_PDF417_CONTROL_BLOCK: case BEGIN_MACRO_PDF417_OPTIONAL_FIELD: case MACRO_PDF417_TERMINATOR: codeIndex--; end = true; break; } } if ((count%5 == 0) && (count > 0)) { // Decode every 5 codewords // Convert to Base 256 for (int j = 0; j < 6; ++j) { decodedBytes.WriteByte((byte) (value >> (8*(5 - j)))); } value = 0; count = 0; } } break; } var bytes = decodedBytes.ToArray(); result.Append(encoding.GetString(bytes, 0, bytes.Length)); } return codeIndex; } /// <summary> /// Numeric Compaction mode (see 5.4.4) permits efficient encoding of numeric data strings. /// /// <param name="codewords">The array of codewords (data + error)</param> /// <param name="codeIndex">The current index into the codeword array.</param> /// <param name="result">The decoded data is appended to the result.</param> /// <returns>The next index into the codeword array.</returns> /// </summary> private static int numericCompaction(int[] codewords, int codeIndex, StringBuilder result) { int count = 0; bool end = false; int[] numericCodewords = new int[MAX_NUMERIC_CODEWORDS]; while (codeIndex < codewords[0] && !end) { int code = codewords[codeIndex++]; if (codeIndex == codewords[0]) { end = true; } if (code < TEXT_COMPACTION_MODE_LATCH) { numericCodewords[count] = code; count++; } else { switch (code) { case TEXT_COMPACTION_MODE_LATCH: case BYTE_COMPACTION_MODE_LATCH: case BYTE_COMPACTION_MODE_LATCH_6: case BEGIN_MACRO_PDF417_CONTROL_BLOCK: case BEGIN_MACRO_PDF417_OPTIONAL_FIELD: case MACRO_PDF417_TERMINATOR: codeIndex--; end = true; break; } } if (count % MAX_NUMERIC_CODEWORDS == 0 || code == NUMERIC_COMPACTION_MODE_LATCH || end) { // Re-invoking Numeric Compaction mode (by using codeword 902 // while in Numeric Compaction mode) serves to terminate the // current Numeric Compaction mode grouping as described in 5.4.4.2, // and then to start a new one grouping. if (count > 0) { String s = decodeBase900toBase10(numericCodewords, count); if (s == null) return -1; result.Append(s); count = 0; } } } return codeIndex; } /// <summary> /// Convert a list of Numeric Compacted codewords from Base 900 to Base 10. /// EXAMPLE /// Encode the fifteen digit numeric string 000213298174000 /// Prefix the numeric string with a 1 and set the initial value of /// t = 1 000 213 298 174 000 /// Calculate codeword 0 /// d0 = 1 000 213 298 174 000 mod 900 = 200 /// /// t = 1 000 213 298 174 000 div 900 = 1 111 348 109 082 /// Calculate codeword 1 /// d1 = 1 111 348 109 082 mod 900 = 282 /// /// t = 1 111 348 109 082 div 900 = 1 234 831 232 /// Calculate codeword 2 /// d2 = 1 234 831 232 mod 900 = 632 /// /// t = 1 234 831 232 div 900 = 1 372 034 /// Calculate codeword 3 /// d3 = 1 372 034 mod 900 = 434 /// /// t = 1 372 034 div 900 = 1 524 /// Calculate codeword 4 /// d4 = 1 524 mod 900 = 624 /// /// t = 1 524 div 900 = 1 /// Calculate codeword 5 /// d5 = 1 mod 900 = 1 /// t = 1 div 900 = 0 /// Codeword sequence is: 1, 624, 434, 632, 282, 200 /// /// Decode the above codewords involves /// 1 x 900 power of 5 + 624 x 900 power of 4 + 434 x 900 power of 3 + /// 632 x 900 power of 2 + 282 x 900 power of 1 + 200 x 900 power of 0 = 1000213298174000 /// /// Remove leading 1 => Result is 000213298174000 /// <param name="codewords">The array of codewords</param> /// <param name="count">The number of codewords</param> /// <returns>The decoded string representing the Numeric data.</returns> /// </summary> private static String decodeBase900toBase10(int[] codewords, int count) { #if (SILVERLIGHT4 || SILVERLIGHT5 || NET40 || NET45 || NET46 || NET47 || NETFX_CORE || NETSTANDARD) && !NETSTANDARD1_0 BigInteger result = BigInteger.Zero; for (int i = 0; i < count; i++) { result = BigInteger.Add(result, BigInteger.Multiply(EXP900[count - i - 1], new BigInteger(codewords[i]))); } String resultString = result.ToString(); if (resultString[0] != '1') { return null; } return resultString.Substring(1); #else BigInteger result = BigInteger.Zero; for (int i = 0; i < count; i++) { result = BigInteger.Addition(result, BigInteger.Multiplication(EXP900[count - i - 1], new BigInteger(codewords[i]))); } String resultString = result.ToString(); if (resultString[0] != '1') { return null; } return resultString.Substring(1); #endif } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using System.Net.Test.Common; using System.Security.Principal; using System.Text; using System.Threading.Tasks; using Xunit; namespace System.Net.Security.Tests { [PlatformSpecific(TestPlatforms.Windows)] // NegotiateStream only supports client-side functionality on Unix public abstract class NegotiateStreamStreamToStreamTest { private readonly byte[] _sampleMsg = Encoding.UTF8.GetBytes("Sample Test Message"); protected abstract Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName); protected abstract Task AuthenticateAsServerAsync(NegotiateStream server); [Fact] public void NegotiateStream_StreamToStream_Authentication_Success() { VirtualNetwork network = new VirtualNetwork(); using (var clientStream = new VirtualNetworkStream(network, isServer: false)) using (var serverStream = new VirtualNetworkStream(network, isServer: true)) using (var client = new NegotiateStream(clientStream)) using (var server = new NegotiateStream(serverStream)) { Assert.False(client.IsAuthenticated); Assert.False(server.IsAuthenticated); Task[] auth = new Task[2]; auth[0] = AuthenticateAsClientAsync(client, CredentialCache.DefaultNetworkCredentials, string.Empty); auth[1] = AuthenticateAsServerAsync(server); bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds); Assert.True(finished, "Handshake completed in the allotted time"); // Expected Client property values: Assert.True(client.IsAuthenticated); Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel); Assert.Equal(true, client.IsEncrypted); Assert.Equal(false, client.IsMutuallyAuthenticated); Assert.Equal(false, client.IsServer); Assert.Equal(true, client.IsSigned); Assert.Equal(false, client.LeaveInnerStreamOpen); IIdentity serverIdentity = client.RemoteIdentity; Assert.Equal("NTLM", serverIdentity.AuthenticationType); Assert.Equal(false, serverIdentity.IsAuthenticated); Assert.Equal("", serverIdentity.Name); // Expected Server property values: Assert.True(server.IsAuthenticated); Assert.Equal(TokenImpersonationLevel.Identification, server.ImpersonationLevel); Assert.Equal(true, server.IsEncrypted); Assert.Equal(false, server.IsMutuallyAuthenticated); Assert.Equal(true, server.IsServer); Assert.Equal(true, server.IsSigned); Assert.Equal(false, server.LeaveInnerStreamOpen); IIdentity clientIdentity = server.RemoteIdentity; Assert.Equal("NTLM", clientIdentity.AuthenticationType); Assert.Equal(true, clientIdentity.IsAuthenticated); IdentityValidator.AssertIsCurrentIdentity(clientIdentity); } } [Fact] public void NegotiateStream_StreamToStream_Authentication_TargetName_Success() { string targetName = "testTargetName"; VirtualNetwork network = new VirtualNetwork(); using (var clientStream = new VirtualNetworkStream(network, isServer: false)) using (var serverStream = new VirtualNetworkStream(network, isServer: true)) using (var client = new NegotiateStream(clientStream)) using (var server = new NegotiateStream(serverStream)) { Assert.False(client.IsAuthenticated); Assert.False(server.IsAuthenticated); Task[] auth = new Task[2]; auth[0] = AuthenticateAsClientAsync(client, CredentialCache.DefaultNetworkCredentials, targetName); auth[1] = AuthenticateAsServerAsync(server); bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds); Assert.True(finished, "Handshake completed in the allotted time"); // Expected Client property values: Assert.True(client.IsAuthenticated); Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel); Assert.Equal(true, client.IsEncrypted); Assert.Equal(false, client.IsMutuallyAuthenticated); Assert.Equal(false, client.IsServer); Assert.Equal(true, client.IsSigned); Assert.Equal(false, client.LeaveInnerStreamOpen); IIdentity serverIdentity = client.RemoteIdentity; Assert.Equal("NTLM", serverIdentity.AuthenticationType); Assert.Equal(true, serverIdentity.IsAuthenticated); Assert.Equal(targetName, serverIdentity.Name); // Expected Server property values: Assert.True(server.IsAuthenticated); Assert.Equal(TokenImpersonationLevel.Identification, server.ImpersonationLevel); Assert.Equal(true, server.IsEncrypted); Assert.Equal(false, server.IsMutuallyAuthenticated); Assert.Equal(true, server.IsServer); Assert.Equal(true, server.IsSigned); Assert.Equal(false, server.LeaveInnerStreamOpen); IIdentity clientIdentity = server.RemoteIdentity; Assert.Equal("NTLM", clientIdentity.AuthenticationType); Assert.Equal(true, clientIdentity.IsAuthenticated); IdentityValidator.AssertIsCurrentIdentity(clientIdentity); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Core difference in behavior: https://github.com/dotnet/corefx/issues/5241")] public void NegotiateStream_StreamToStream_Authentication_EmptyCredentials_Fails() { string targetName = "testTargetName"; // Ensure there is no confusion between DefaultCredentials / DefaultNetworkCredentials and a // NetworkCredential object with empty user, password and domain. NetworkCredential emptyNetworkCredential = new NetworkCredential("", "", ""); Assert.NotEqual(emptyNetworkCredential, CredentialCache.DefaultCredentials); Assert.NotEqual(emptyNetworkCredential, CredentialCache.DefaultNetworkCredentials); VirtualNetwork network = new VirtualNetwork(); using (var clientStream = new VirtualNetworkStream(network, isServer: false)) using (var serverStream = new VirtualNetworkStream(network, isServer: true)) using (var client = new NegotiateStream(clientStream)) using (var server = new NegotiateStream(serverStream)) { Assert.False(client.IsAuthenticated); Assert.False(server.IsAuthenticated); Task[] auth = new Task[2]; auth[0] = AuthenticateAsClientAsync(client, emptyNetworkCredential, targetName); auth[1] = AuthenticateAsServerAsync(server); bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds); Assert.True(finished, "Handshake completed in the allotted time"); // Expected Client property values: Assert.True(client.IsAuthenticated); Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel); Assert.Equal(true, client.IsEncrypted); Assert.Equal(false, client.IsMutuallyAuthenticated); Assert.Equal(false, client.IsServer); Assert.Equal(true, client.IsSigned); Assert.Equal(false, client.LeaveInnerStreamOpen); IIdentity serverIdentity = client.RemoteIdentity; Assert.Equal("NTLM", serverIdentity.AuthenticationType); Assert.Equal(true, serverIdentity.IsAuthenticated); Assert.Equal(targetName, serverIdentity.Name); // Expected Server property values: Assert.True(server.IsAuthenticated); Assert.Equal(TokenImpersonationLevel.Identification, server.ImpersonationLevel); Assert.Equal(true, server.IsEncrypted); Assert.Equal(false, server.IsMutuallyAuthenticated); Assert.Equal(true, server.IsServer); Assert.Equal(true, server.IsSigned); Assert.Equal(false, server.LeaveInnerStreamOpen); IIdentity clientIdentity = server.RemoteIdentity; Assert.Equal("NTLM", clientIdentity.AuthenticationType); // TODO #5241: Behavior difference: Assert.Equal(false, clientIdentity.IsAuthenticated); // On .Net Desktop: Assert.Equal(true, clientIdentity.IsAuthenticated); IdentityValidator.AssertHasName(clientIdentity, @"NT AUTHORITY\ANONYMOUS LOGON"); } } [Fact] public void NegotiateStream_StreamToStream_Successive_ClientWrite_Sync_Success() { byte[] recvBuf = new byte[_sampleMsg.Length]; VirtualNetwork network = new VirtualNetwork(); using (var clientStream = new VirtualNetworkStream(network, isServer: false)) using (var serverStream = new VirtualNetworkStream(network, isServer: true)) using (var client = new NegotiateStream(clientStream)) using (var server = new NegotiateStream(serverStream)) { Assert.False(client.IsAuthenticated); Assert.False(server.IsAuthenticated); Task[] auth = new Task[2]; auth[0] = AuthenticateAsClientAsync(client, CredentialCache.DefaultNetworkCredentials, string.Empty); auth[1] = AuthenticateAsServerAsync(server); bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds); Assert.True(finished, "Handshake completed in the allotted time"); client.Write(_sampleMsg, 0, _sampleMsg.Length); server.Read(recvBuf, 0, _sampleMsg.Length); Assert.True(_sampleMsg.SequenceEqual(recvBuf)); client.Write(_sampleMsg, 0, _sampleMsg.Length); server.Read(recvBuf, 0, _sampleMsg.Length); Assert.True(_sampleMsg.SequenceEqual(recvBuf)); } } [Fact] public void NegotiateStream_StreamToStream_Successive_ClientWrite_Async_Success() { byte[] recvBuf = new byte[_sampleMsg.Length]; VirtualNetwork network = new VirtualNetwork(); using (var clientStream = new VirtualNetworkStream(network, isServer: false)) using (var serverStream = new VirtualNetworkStream(network, isServer: true)) using (var client = new NegotiateStream(clientStream)) using (var server = new NegotiateStream(serverStream)) { Assert.False(client.IsAuthenticated); Assert.False(server.IsAuthenticated); Task[] auth = new Task[2]; auth[0] = AuthenticateAsClientAsync(client, CredentialCache.DefaultNetworkCredentials, string.Empty); auth[1] = AuthenticateAsServerAsync(server); bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds); Assert.True(finished, "Handshake completed in the allotted time"); auth[0] = client.WriteAsync(_sampleMsg, 0, _sampleMsg.Length); auth[1] = server.ReadAsync(recvBuf, 0, _sampleMsg.Length); finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds); Assert.True(finished, "Send/receive completed in the allotted time"); Assert.True(_sampleMsg.SequenceEqual(recvBuf)); auth[0] = client.WriteAsync(_sampleMsg, 0, _sampleMsg.Length); auth[1] = server.ReadAsync(recvBuf, 0, _sampleMsg.Length); finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds); Assert.True(finished, "Send/receive completed in the allotted time"); Assert.True(_sampleMsg.SequenceEqual(recvBuf)); } } [Fact] public void NegotiateStream_StreamToStream_Flush_Propagated() { VirtualNetwork network = new VirtualNetwork(); using (var stream = new VirtualNetworkStream(network, isServer: false)) using (var negotiateStream = new NegotiateStream(stream)) { Assert.False(stream.HasBeenSyncFlushed); negotiateStream.Flush(); Assert.True(stream.HasBeenSyncFlushed); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Relies on FlushAsync override not available in desktop")] public void NegotiateStream_StreamToStream_FlushAsync_Propagated() { VirtualNetwork network = new VirtualNetwork(); using (var stream = new VirtualNetworkStream(network, isServer: false)) using (var negotiateStream = new NegotiateStream(stream)) { Task task = negotiateStream.FlushAsync(); Assert.False(task.IsCompleted); stream.CompleteAsyncFlush(); Assert.True(task.IsCompleted); } } } public sealed class NegotiateStreamStreamToStreamTest_Async : NegotiateStreamStreamToStreamTest { protected override Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName) => client.AuthenticateAsClientAsync(credential, targetName); protected override Task AuthenticateAsServerAsync(NegotiateStream server) => server.AuthenticateAsServerAsync(); } public sealed class NegotiateStreamStreamToStreamTest_BeginEnd : NegotiateStreamStreamToStreamTest { protected override Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName) => Task.Factory.FromAsync(client.BeginAuthenticateAsClient, client.EndAuthenticateAsClient, credential, targetName, null); protected override Task AuthenticateAsServerAsync(NegotiateStream server) => Task.Factory.FromAsync(server.BeginAuthenticateAsServer, server.EndAuthenticateAsServer, null); } public sealed class NegotiateStreamStreamToStreamTest_Sync : NegotiateStreamStreamToStreamTest { protected override Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName) => Task.Run(() => client.AuthenticateAsClient(credential, targetName)); protected override Task AuthenticateAsServerAsync(NegotiateStream server) => Task.Run(() => server.AuthenticateAsServer()); } }
/* * This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson, * the work of Kim Sheffield and the fyiReporting project. * * Prior Copyrights: * _________________________________________________________ * |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others| * | (http://reportfu.org) | * ========================================================= * _________________________________________________________ * |Copyright (C) 2004-2008 fyiReporting Software, LLC | * |For additional information, email info@fyireporting.com | * |or visit the website www.fyiReporting.com. | * ========================================================= * * License: * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Drawing; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Windows.Forms; using System.Xml; namespace Reporting.RdlDesign { internal enum PropertyTypeEnum { Report, DataSets, ReportItems, Grouping, ChartLegend, CategoryAxis, ValueAxis, ChartTitle, CategoryAxisTitle, ValueAxisTitle, TableGroup, ValueAxis2Title// 20022008 AJM GJL } /// <summary> /// Summary description for PropertyDialog. /// </summary> internal class PropertyDialog : System.Windows.Forms.Form { private DesignXmlDraw _Draw; // design draw private List<XmlNode> _Nodes; // selected nodes private PropertyTypeEnum _Type; private bool _Changed=false; private bool _Delete=false; private XmlNode _TableColumn=null; // when table this is the current table column private XmlNode _TableRow=null; // when table this is the current table row private List<UserControl> _TabPanels = new List<UserControl>(); // list of IProperty controls private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Button bCancel; private System.Windows.Forms.Button bOK; private System.Windows.Forms.Button bApply; private System.Windows.Forms.TabControl tcProps; private System.Windows.Forms.Button bDelete; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; internal PropertyDialog(DesignXmlDraw dxDraw, List<XmlNode> sNodes, PropertyTypeEnum type) : this(dxDraw, sNodes, type, null, null) {} internal PropertyDialog(DesignXmlDraw dxDraw, List<XmlNode> sNodes, PropertyTypeEnum type, XmlNode tcNode, XmlNode trNode) { this._Draw = dxDraw; this._Nodes = sNodes; this._Type = type; _TableColumn = tcNode; _TableRow = trNode; // // Required for Windows Form Designer support // InitializeComponent(); // Add the controls for the selected ReportItems switch (_Type) { case PropertyTypeEnum.Report: BuildReportTabs(); break; case PropertyTypeEnum.DataSets: BuildDataSetsTabs(); break; case PropertyTypeEnum.Grouping: BuildGroupingTabs(); break; case PropertyTypeEnum.ChartLegend: BuildChartLegendTabs(); break; case PropertyTypeEnum.CategoryAxis: case PropertyTypeEnum.ValueAxis: BuildChartAxisTabs(type); break; case PropertyTypeEnum.ChartTitle: case PropertyTypeEnum.CategoryAxisTitle: case PropertyTypeEnum.ValueAxisTitle: case PropertyTypeEnum.ValueAxis2Title:// 20022008 AJM GJL BuildTitle(type); break; case PropertyTypeEnum.ReportItems: default: BuildReportItemTabs(); break; } } internal bool Changed { get {return _Changed; } } internal bool Delete { get {return _Delete; } } private void BuildReportTabs() { this.Text = "Report Properties"; ReportCtl rc = new ReportCtl(_Draw); AddTab("Report", rc); ReportParameterCtl pc = new ReportParameterCtl(_Draw); AddTab("Parameters", pc); ReportXmlCtl xc = new ReportXmlCtl(_Draw); AddTab("XML Rendering", xc); BodyCtl bc = new BodyCtl(_Draw); AddTab("Body", bc); CodeCtl cc = new CodeCtl(_Draw); AddTab("Code", cc); ModulesClassesCtl mc = new ModulesClassesCtl(_Draw); AddTab("Modules/Classes", mc); return; } private void BuildDataSetsTabs() { bDelete.Visible = true; this.Text = "DataSet"; XmlNode aNode; if (_Nodes != null && _Nodes.Count > 0) aNode = _Nodes[0]; else aNode = null; DataSetsCtl dsc = new DataSetsCtl(_Draw, aNode); AddTab("DataSet", dsc); QueryParametersCtl qp = new QueryParametersCtl(_Draw, dsc.DSV); AddTab("Query Parameters", qp); FiltersCtl fc = new FiltersCtl(_Draw, aNode); AddTab("Filters", fc); DataSetRowsCtl dsrc = new DataSetRowsCtl(_Draw, aNode, dsc.DSV); AddTab("Data", dsrc); return; } private void BuildGroupingTabs() { XmlNode aNode = _Nodes[0]; if (aNode.Name == "DynamicSeries") { this.Text = "Series Grouping"; } else if (aNode.Name == "DynamicCategories") { this.Text = "Category Grouping"; } else { this.Text = "Grouping and Sorting"; } GroupingCtl gc = new GroupingCtl(_Draw, aNode); AddTab("Grouping", gc); SortingCtl sc = new SortingCtl(_Draw, aNode); AddTab("Sorting", sc); // We have to create a grouping here but will need to kill it if no definition follows it XmlNode gNode = _Draw.GetCreateNamedChildNode(aNode, "Grouping"); FiltersCtl fc = new FiltersCtl(_Draw, gNode); AddTab("Filters", fc); return; } private void BuildReportItemTabs() { XmlNode aNode = _Nodes[0]; // Determine if all nodes are the same type string type = aNode.Name; if (type == "CustomReportItem") { // For customReportItems we use the type that is a parameter string t = _Draw.GetElementValue(aNode, "Type", ""); if (t.Length > 0) type = t; } foreach (XmlNode pNode in this._Nodes) { // For customReportItems we use the type that is a parameter string t = pNode.Name; if (t == "CustomReportItem") { t = _Draw.GetElementValue(aNode, "Type", ""); if (t.Length == 0) // Shouldn't happen t = pNode.Name; } if (t != type) type = ""; // Not all nodes have the same type } EnsureStyle(); // Make sure we have Style nodes for all the report items if (_Nodes.Count > 1) this.Text = "Group Selection Properties"; else { string name = _Draw.GetElementAttribute(aNode, "Name", ""); this.Text = string.Format("{0} {1} Properties", type.Replace("fyi:",""), name); } // Create all the tabs if (type == "Textbox") { StyleTextCtl stc = new StyleTextCtl(_Draw, this._Nodes); AddTab("Text", stc); } else if (type == "List") { ListCtl lc = new ListCtl(_Draw, this._Nodes); AddTab("List", lc); if (_Nodes.Count == 1) { XmlNode l = _Nodes[0]; FiltersCtl fc = new FiltersCtl(_Draw, l); AddTab("Filters", fc); SortingCtl srtc = new SortingCtl(_Draw, l); AddTab("Sorting", srtc); } } else if (type == "Chart") { ChartCtl cc = new ChartCtl(_Draw, this._Nodes); AddTab("Chart", cc); // 05122007 AJM & GJL Create a new StaticSeriesCtl tab StaticSeriesCtl ssc = new StaticSeriesCtl(_Draw, this._Nodes); if (ssc.ShowMe) { //If the chart has static series, then show the StaticSeriesCtl GJL AddTab("Static Series", ssc); } if (_Nodes.Count == 1) { FiltersCtl fc = new FiltersCtl(_Draw, _Nodes[0]); AddTab("Filters", fc); } } else if (type == "Image") { ImageCtl imgc = new ImageCtl(_Draw, this._Nodes); AddTab("Image", imgc); } else if (type == "Table") { XmlNode table = _Nodes[0]; TableCtl tc = new TableCtl(_Draw, this._Nodes); AddTab("Table", tc); FiltersCtl fc = new FiltersCtl(_Draw, table); AddTab("Filters", fc); XmlNode details = _Draw.GetNamedChildNode(table, "Details"); if (details != null) { // if no details then we don't need details sorting GroupingCtl grpc = new GroupingCtl(_Draw, details); AddTab("Grouping", grpc); SortingCtl srtc = new SortingCtl(_Draw, details); AddTab("Sorting", srtc); } if (_TableColumn != null) { TableColumnCtl tcc = new TableColumnCtl(_Draw, _TableColumn); AddTab("Table Column", tcc); } if (_TableRow != null) { TableRowCtl trc = new TableRowCtl(_Draw, _TableRow); AddTab("Table Row", trc); } } else if (type == "fyi:Grid") { GridCtl gc = new GridCtl(_Draw, this._Nodes); AddTab("Grid", gc); } else if (type == "Matrix") { XmlNode matrix = _Nodes[0]; MatrixCtl mc = new MatrixCtl(_Draw, this._Nodes); AddTab("Matrix", mc); FiltersCtl fc = new FiltersCtl(_Draw, matrix); AddTab("Filters", fc); } else if (type == "Subreport" && _Nodes.Count == 1) { XmlNode subreport = _Nodes[0]; SubreportCtl src = new SubreportCtl(_Draw, subreport); AddTab("Subreport", src); } else if (aNode.Name == "CustomReportItem") { XmlNode cri = _Nodes[0]; CustomReportItemCtl cric = new CustomReportItemCtl(_Draw, _Nodes); AddTab(type, cric); } // Position tab PositionCtl pc = new PositionCtl(_Draw, this._Nodes); AddTab("Name/Position", pc); // Border tab StyleBorderCtl bc = new StyleBorderCtl(_Draw, null, this._Nodes); AddTab("Border", bc); if (! (type == "Line" || type == "Subreport")) { // Style tab StyleCtl sc = new StyleCtl(_Draw, this._Nodes); AddTab("Style", sc); // Interactivity tab InteractivityCtl ic = new InteractivityCtl(_Draw, this._Nodes); AddTab("Interactivity", ic); } } private void BuildChartAxisTabs(PropertyTypeEnum type) { string propName; if (type == PropertyTypeEnum.CategoryAxis) { this.Text = "Chart Category (X) Axis"; propName = "CategoryAxis"; } else { this.Text = "Chart Value (Y) Axis"; propName = "ValueAxis"; } XmlNode cNode = _Nodes[0]; XmlNode aNode = _Draw.GetCreateNamedChildNode(cNode, propName); XmlNode axNode = _Draw.GetCreateNamedChildNode(aNode, "Axis"); // Now we replace the node array with a new one containing only the legend _Nodes = new List<XmlNode>(); _Nodes.Add(axNode); EnsureStyle(); // Make sure we have Style nodes // Chart Axis ChartAxisCtl cac = new ChartAxisCtl(_Draw, this._Nodes); AddTab("Axis", cac); // Style Text StyleTextCtl stc = new StyleTextCtl(_Draw, this._Nodes); AddTab("Text", stc); // Border tab StyleBorderCtl bc = new StyleBorderCtl(_Draw, null, this._Nodes); AddTab("Border", bc); // Style tab StyleCtl sc = new StyleCtl(_Draw, this._Nodes); AddTab("Style", sc); } private void BuildChartLegendTabs() { this.Text = "Chart Legend Properties"; XmlNode cNode = _Nodes[0]; XmlNode lNode = _Draw.GetCreateNamedChildNode(cNode, "Legend"); // Now we replace the node array with a new one containing only the legend _Nodes = new List<XmlNode>(); _Nodes.Add(lNode); EnsureStyle(); // Make sure we have Style nodes // Chart Legend ChartLegendCtl clc = new ChartLegendCtl(_Draw, this._Nodes); AddTab("Legend", clc); // Style Text StyleTextCtl stc = new StyleTextCtl(_Draw, this._Nodes); AddTab("Text", stc); // Border tab StyleBorderCtl bc = new StyleBorderCtl(_Draw, null, this._Nodes); AddTab("Border", bc); // Style tab StyleCtl sc = new StyleCtl(_Draw, this._Nodes); AddTab("Style", sc); } private void BuildTitle(PropertyTypeEnum type) { XmlNode cNode = _Nodes[0]; _Nodes = new List<XmlNode>(); // replace with a new one if (type == PropertyTypeEnum.ChartTitle) { this.Text = "Chart Title"; XmlNode lNode = _Draw.GetCreateNamedChildNode(cNode, "Title"); _Nodes.Add(lNode); // Working on the title } else if (type == PropertyTypeEnum.CategoryAxisTitle) { this.Text = "Category (X) Axis Title"; XmlNode caNode = _Draw.GetCreateNamedChildNode(cNode, "CategoryAxis"); XmlNode aNode = _Draw.GetCreateNamedChildNode(caNode, "Axis"); XmlNode tNode = _Draw.GetCreateNamedChildNode(aNode, "Title"); _Nodes.Add(tNode); // Working on the title } // 20022008 AJM GJL else if (type == PropertyTypeEnum.ValueAxis2Title) { this.Text = "Value (Y) Axis (Right) Title"; XmlNode caNode = _Draw.GetCreateNamedChildNode(cNode, "ValueAxis"); XmlNode aNode = _Draw.GetCreateNamedChildNode(caNode, "Axis"); XmlNode tNode = _Draw.GetCreateNamedChildNode(aNode, "fyi:Title2"); _Nodes.Add(tNode); // Working on the title } else { this.Text = "Value (Y) Axis Title"; XmlNode caNode = _Draw.GetCreateNamedChildNode(cNode, "ValueAxis"); XmlNode aNode = _Draw.GetCreateNamedChildNode(caNode, "Axis"); XmlNode tNode = _Draw.GetCreateNamedChildNode(aNode, "Title"); _Nodes.Add(tNode); // Working on the title } EnsureStyle(); // Make sure we have Style nodes // Style Text StyleTextCtl stc = new StyleTextCtl(_Draw, this._Nodes); AddTab("Text", stc); // Border tab StyleBorderCtl bc = new StyleBorderCtl(_Draw, null, this._Nodes); AddTab("Border", bc); // Style tab StyleCtl sc = new StyleCtl(_Draw, this._Nodes); AddTab("Style", sc); } private void EnsureStyle() { // Make sure we have Style nodes for all the nodes foreach (XmlNode pNode in this._Nodes) { XmlNode stNode = _Draw.GetCreateNamedChildNode(pNode, "Style"); } return; } private void AddTab(string name, UserControl uc) { // Style tab TabPage tp = new TabPage(); tp.Location = new System.Drawing.Point(4, 22); tp.Name = name + "1"; tp.Size = new System.Drawing.Size(552, 284); tp.TabIndex = 1; tp.Text = name; _TabPanels.Add(uc); tp.Controls.Add(uc); uc.Dock = System.Windows.Forms.DockStyle.Fill; uc.Location = new System.Drawing.Point(0, 0); uc.Name = name + "1"; uc.Size = new System.Drawing.Size(552, 284); uc.TabIndex = 0; tcProps.Controls.Add(tp); } /// <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.panel1 = new System.Windows.Forms.Panel(); this.bDelete = new System.Windows.Forms.Button(); this.bApply = new System.Windows.Forms.Button(); this.bOK = new System.Windows.Forms.Button(); this.bCancel = new System.Windows.Forms.Button(); this.tcProps = new System.Windows.Forms.TabControl(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // panel1 // this.panel1.CausesValidation = false; this.panel1.Controls.Add(this.bDelete); this.panel1.Controls.Add(this.bApply); this.panel1.Controls.Add(this.bOK); this.panel1.Controls.Add(this.bCancel); this.panel1.Dock = System.Windows.Forms.DockStyle.Bottom; this.panel1.Location = new System.Drawing.Point(0, 326); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(458, 40); this.panel1.TabIndex = 1; // // bDelete // this.bDelete.Location = new System.Drawing.Point(8, 8); this.bDelete.Name = "bDelete"; this.bDelete.Size = new System.Drawing.Size(75, 23); this.bDelete.TabIndex = 3; this.bDelete.Text = "Delete"; this.bDelete.Visible = false; this.bDelete.Click += new System.EventHandler(this.bDelete_Click); // // bApply // this.bApply.Location = new System.Drawing.Point(376, 8); this.bApply.Name = "bApply"; this.bApply.Size = new System.Drawing.Size(75, 23); this.bApply.TabIndex = 2; this.bApply.Text = "Apply"; this.bApply.Click += new System.EventHandler(this.bApply_Click); // // bOK // this.bOK.Location = new System.Drawing.Point(216, 8); this.bOK.Name = "bOK"; this.bOK.Size = new System.Drawing.Size(75, 23); this.bOK.TabIndex = 0; this.bOK.Text = "OK"; this.bOK.Click += new System.EventHandler(this.bOK_Click); // // bCancel // this.bCancel.CausesValidation = false; this.bCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.bCancel.Location = new System.Drawing.Point(296, 8); this.bCancel.Name = "bCancel"; this.bCancel.Size = new System.Drawing.Size(75, 23); this.bCancel.TabIndex = 1; this.bCancel.Text = "Cancel"; // // tcProps // this.tcProps.Dock = System.Windows.Forms.DockStyle.Fill; this.tcProps.Location = new System.Drawing.Point(0, 0); this.tcProps.Multiline = true; this.tcProps.Name = "tcProps"; this.tcProps.SelectedIndex = 0; this.tcProps.Size = new System.Drawing.Size(458, 326); this.tcProps.TabIndex = 0; // // PropertyDialog // this.AcceptButton = this.bOK; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.CancelButton = this.bCancel; this.ClientSize = new System.Drawing.Size(458, 366); this.Controls.Add(this.tcProps); this.Controls.Add(this.panel1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "PropertyDialog"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Properties"; this.Closing += new System.ComponentModel.CancelEventHandler(this.PropertyDialog_Closing); this.panel1.ResumeLayout(false); this.ResumeLayout(false); } #endregion private void bApply_Click(object sender, System.EventArgs e) { if (!IsValid()) return; this._Changed = true; foreach (IProperty ip in _TabPanels) { ip.Apply(); } this._Draw.Invalidate(); // Force screen to redraw } private void bOK_Click(object sender, System.EventArgs e) { if (!IsValid()) return; bApply_Click(sender, e); // Apply does all the work this.DialogResult = DialogResult.OK; } private bool IsValid() { int index=0; foreach (IProperty ip in _TabPanels) { if (!ip.IsValid()) { tcProps.SelectedIndex = index; return false; } index++; } return true; } private void PropertyDialog_Closing(object sender, System.ComponentModel.CancelEventArgs e) { if (_Type == PropertyTypeEnum.Grouping) { // Need to check if grouping value is still required XmlNode aNode = _Nodes[0]; // We have to create a grouping here but will need to kill it if no definition follows it XmlNode gNode = _Draw.GetNamedChildNode(aNode, "Grouping"); if (gNode != null && _Draw.GetNamedChildNode(gNode, "GroupExpressions") == null) { // Not a valid group if no GroupExpressions aNode.RemoveChild(gNode); } } } private void bDelete_Click(object sender, System.EventArgs e) { if (MessageBox.Show(this, "Are you sure you want to delete this dataset?", "DataSet", MessageBoxButtons.YesNo) == DialogResult.Yes) { _Delete = true; this.DialogResult = DialogResult.OK; } } } internal interface IProperty { void Apply(); bool IsValid(); } }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Roslyn.Diagnostics.Analyzers.DoNotMixAttributesFromDifferentVersionsOfMEFAnalyzer, Roslyn.Diagnostics.CSharp.Analyzers.CSharpDoNotMixAttributesFromDifferentVersionsOfMEFFixer>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Roslyn.Diagnostics.Analyzers.DoNotMixAttributesFromDifferentVersionsOfMEFAnalyzer, Roslyn.Diagnostics.VisualBasic.Analyzers.BasicDoNotMixAttributesFromDifferentVersionsOfMEFFixer>; namespace Roslyn.Diagnostics.Analyzers.UnitTests { public class DoNotMixAttributesFromDifferentVersionsOfMEFTests { private const string CSharpWellKnownAttributesDefinition = @" namespace System.Composition { public class ExportAttribute : System.Attribute { public ExportAttribute(System.Type contractType){ } } public class MetadataAttributeAttribute : System.Attribute { public MetadataAttributeAttribute() { } } public class ImportAttribute : System.Attribute { public ImportAttribute() { } } public class ImportingConstructorAttribute : System.Attribute { public ImportingConstructorAttribute() { } } } [System.Composition.MetadataAttribute] public class SystemCompositionMetadataAttribute : System.Attribute { public class ExportAttribute : System.Attribute { public ExportAttribute(System.Type contractType){ } } public class MetadataAttributeAttribute : System.Attribute { public MetadataAttributeAttribute() { } } public class ImportAttribute : System.Attribute { public ImportAttribute() { } } public class ImportingConstructorAttribute : System.Attribute { public ImportingConstructorAttribute() { } } } namespace System.ComponentModel.Composition { public class ExportAttribute : System.Attribute { public ExportAttribute(System.Type contractType){ } } public class MetadataAttributeAttribute : System.Attribute { public MetadataAttributeAttribute() { } } public class ImportAttribute : System.Attribute { public ImportAttribute() { } } public class ImportingConstructorAttribute : System.Attribute { public ImportingConstructorAttribute() { } } } [System.ComponentModel.Composition.MetadataAttribute] public class SystemComponentModelCompositionMetadataAttribute : System.Attribute { } "; private const string BasicWellKnownAttributesDefinition = @" Namespace System.Composition Public Class ExportAttribute Inherits System.Attribute Public Sub New(contractType As System.Type) End Sub End Class Public Class MetadataAttributeAttribute Inherits System.Attribute Public Sub New() End Sub End Class Public Class ImportAttribute Inherits System.Attribute Public Sub New() End Sub End Class Public Class ImportingConstructorAttribute Inherits System.Attribute Public Sub New() End Sub End Class End Namespace <System.Composition.MetadataAttribute> _ Public Class SystemCompositionMetadataAttribute Inherits System.Attribute End Class Namespace System.ComponentModel.Composition Public Class ExportAttribute Inherits System.Attribute Public Sub New(contractType As System.Type) End Sub End Class Public Class MetadataAttributeAttribute Inherits System.Attribute Public Sub New() End Sub End Class Public Class ImportAttribute Inherits System.Attribute Public Sub New() End Sub End Class Public Class ImportingConstructorAttribute Inherits System.Attribute Public Sub New() End Sub End Class End Namespace <System.ComponentModel.Composition.MetadataAttribute> _ Public Class SystemComponentModelCompositionMetadataAttribute Inherits System.Attribute End Class "; #region No Diagnostic Tests [Fact] public async Task NoDiagnosticCases_SingleMefAttribute() { await VerifyCS.VerifyAnalyzerAsync(@" using System; [System.Composition.Export(typeof(C))] public class C { } [System.ComponentModel.Composition.Export(typeof(C2))] public class C2 { } " + CSharpWellKnownAttributesDefinition); await VerifyVB.VerifyAnalyzerAsync(@" Imports System <System.Composition.Export(GetType(C))> _ Public Class C End Class <System.ComponentModel.Composition.Export(GetType(C2))> _ Public Class C2 End Class " + BasicWellKnownAttributesDefinition); } [Fact] public async Task NoDiagnosticCases_SingleMefAttributeAndValidMetadataAttribute() { await VerifyCS.VerifyAnalyzerAsync(@" using System; [System.Composition.Export(typeof(C))] [SystemCompositionMetadataAttribute] public class C { } [System.ComponentModel.Composition.Export(typeof(C2))] [SystemComponentModelCompositionMetadataAttribute] public class C2 { } " + CSharpWellKnownAttributesDefinition); await VerifyVB.VerifyAnalyzerAsync(@" Imports System <System.Composition.Export(GetType(C))> _ <SystemCompositionMetadataAttribute> _ Public Class C End Class <System.ComponentModel.Composition.Export(GetType(C2))> _ <SystemComponentModelCompositionMetadataAttribute> _ Public Class C2 End Class " + BasicWellKnownAttributesDefinition); } [Fact] public async Task NoDiagnosticCases_SingleMefAttributeAndAnotherExportAttribute() { await VerifyCS.VerifyAnalyzerAsync(@" using System; [System.Composition.Export(typeof(C)), MyNamespace.Export(typeof(C))] public class C { } [System.ComponentModel.Composition.Export(typeof(C2)), MyNamespace.Export(typeof(C2))] public class C2 { } namespace MyNamespace { public class ExportAttribute : System.Attribute { public ExportAttribute(System.Type contractType){ } } } " + CSharpWellKnownAttributesDefinition); await VerifyVB.VerifyAnalyzerAsync(@" Imports System <System.Composition.Export(GetType(C)), MyNamespace.Export(GetType(C))> _ Public Class C End Class <System.ComponentModel.Composition.Export(GetType(C2)), MyNamespace.Export(GetType(C2))> _ Public Class C2 End Class Namespace MyNamespace Public Class ExportAttribute Inherits System.Attribute Public Sub New(contractType As System.Type) End Sub End Class End Namespace " + BasicWellKnownAttributesDefinition); } [Fact] public async Task NoDiagnosticCases_SingleMefAttributeOnTypeAndValidMefAttributeOnMember() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class B { } [System.Composition.Export(typeof(C))] public class C { [System.Composition.ImportingConstructor] public C([System.Composition.Import]B b) { } [System.Composition.Import] public B PropertyB { get; } } [System.ComponentModel.Composition.Export(typeof(C2))] public class C2 { [System.ComponentModel.Composition.ImportingConstructor] public C2([System.ComponentModel.Composition.Import]B b) { } [System.ComponentModel.Composition.Import] public B PropertyB { get; } } " + CSharpWellKnownAttributesDefinition); await VerifyVB.VerifyAnalyzerAsync(@" Public Class B End Class <System.Composition.Export(GetType(C))> _ Public Class C <System.Composition.ImportingConstructor> _ Public Sub New(<System.Composition.Import> b As B) End Sub <System.Composition.Import> _ Public ReadOnly Property PropertyB() As B End Class <System.ComponentModel.Composition.Export(GetType(C2))> _ Public Class C2 <System.ComponentModel.Composition.ImportingConstructor> _ Public Sub New(<System.ComponentModel.Composition.Import> b As B) End Sub <System.ComponentModel.Composition.Import> _ Public ReadOnly Property PropertyB() As B End Class " + BasicWellKnownAttributesDefinition); } [Fact] public async Task NoDiagnosticCases_UnresolvedTypes() { await new VerifyCS.Test { TestState = { Sources = { @" using System; public class B { } [System.{|CS0234:Composition|}.Export(typeof(C))] public class C { [System.ComponentModel.{|CS0234:Composition|}.Import] public B PropertyB { get; } } " }, }, ReferenceAssemblies = ReferenceAssemblies.Default, }.RunAsync(); await new VerifyVB.Test { TestState = { Sources = { @" Public Class B End Class <{|BC30002:System.Composition.Export|}(GetType(C))> _ Public Class C <{|BC30002:System.ComponentModel.Composition.Import|}> _ Public ReadOnly Property PropertyB() As B End Class " }, }, ReferenceAssemblies = ReferenceAssemblies.Default, }.RunAsync(); } [Fact] public async Task NoDiagnosticCases_MultiMefMetadataAttribute() { await VerifyCS.VerifyAnalyzerAsync(@" using System; [System.ComponentModel.Composition.Export(typeof(C)), MyNamespace.MultiMefMetadataAttribute] public class C { } namespace MyNamespace { [System.ComponentModel.Composition.MetadataAttribute, System.Composition.MetadataAttribute] public class MultiMefMetadataAttribute : System.Attribute { } } " + CSharpWellKnownAttributesDefinition); await VerifyVB.VerifyAnalyzerAsync(@" Imports System <System.ComponentModel.Composition.Export(GetType(C)), MyNamespace.MultiMefMetadataAttribute> _ Public Class C End Class Namespace MyNamespace <System.ComponentModel.Composition.MetadataAttribute, System.Composition.MetadataAttribute> _ Public Class MultiMefMetadataAttribute Inherits System.Attribute End Class End Namespace " + BasicWellKnownAttributesDefinition); } #endregion #region Diagnostic Tests [Fact] public async Task DiagnosticCases_BadMetadataAttribute() { await VerifyCS.VerifyAnalyzerAsync(@" using System; [System.Composition.Export(typeof(C))] [SystemComponentModelCompositionMetadataAttribute] public class C { } [System.ComponentModel.Composition.Export(typeof(C2))] [SystemCompositionMetadataAttribute] public class C2 { } " + CSharpWellKnownAttributesDefinition, // Test0.cs(5,2): warning RS0006: Attribute 'SystemComponentModelCompositionMetadataAttribute' comes from a different version of MEF than the export attribute on 'C' GetCSharpResultAt(5, 2, "SystemComponentModelCompositionMetadataAttribute", "C"), // Test0.cs(11,2): warning RS0006: Attribute 'SystemCompositionMetadataAttribute' comes from a different version of MEF than the export attribute on 'C2' GetCSharpResultAt(11, 2, "SystemCompositionMetadataAttribute", "C2")); await VerifyVB.VerifyAnalyzerAsync(@" Imports System <System.Composition.Export(GetType(C))> _ <SystemComponentModelCompositionMetadataAttribute> _ Public Class C End Class <System.ComponentModel.Composition.Export(GetType(C2))> _ <SystemCompositionMetadataAttribute> _ Public Class C2 End Class " + BasicWellKnownAttributesDefinition, // Test0.vb(5,2): warning RS0006: Attribute 'SystemComponentModelCompositionMetadataAttribute' comes from a different version of MEF than the export attribute on 'C' GetBasicResultAt(5, 2, "SystemComponentModelCompositionMetadataAttribute", "C"), // Test0.vb(10,2): warning RS0006: Attribute 'SystemCompositionMetadataAttribute' comes from a different version of MEF than the export attribute on 'C2' GetBasicResultAt(10, 2, "SystemCompositionMetadataAttribute", "C2")); } [Fact] public async Task DiagnosticCases_BadMefAttributeOnMember() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class B { } [System.Composition.Export(typeof(C))] public class C { [System.ComponentModel.Composition.ImportingConstructor] public C([System.Composition.Import]B b) { } [System.ComponentModel.Composition.Import] public B PropertyB { get; } } [System.ComponentModel.Composition.Export(typeof(C2))] public class C2 { [System.Composition.ImportingConstructor] public C2([System.ComponentModel.Composition.Import]B b) { } [System.Composition.Import] public B PropertyB { get; } } " + CSharpWellKnownAttributesDefinition, // Test0.cs(9,6): warning RS0006: Attribute 'ImportingConstructorAttribute' comes from a different version of MEF than the export attribute on 'C' GetCSharpResultAt(9, 6, "ImportingConstructorAttribute", "C"), // Test0.cs(12,6): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C' GetCSharpResultAt(12, 6, "ImportAttribute", "C"), // Test0.cs(19,6): warning RS0006: Attribute 'ImportingConstructorAttribute' comes from a different version of MEF than the export attribute on 'C2' GetCSharpResultAt(19, 6, "ImportingConstructorAttribute", "C2"), // Test0.cs(22,6): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C2' GetCSharpResultAt(22, 6, "ImportAttribute", "C2") ); await VerifyVB.VerifyAnalyzerAsync(@" Public Class B End Class <System.Composition.Export(GetType(C))> _ Public Class C <System.ComponentModel.Composition.ImportingConstructor> _ Public Sub New(<System.Composition.Import> b As B) End Sub <System.ComponentModel.Composition.Import> _ Public ReadOnly Property PropertyB() As B End Class <System.ComponentModel.Composition.Export(GetType(C2))> _ Public Class C2 <System.Composition.ImportingConstructor> _ Public Sub New(<System.ComponentModel.Composition.Import> b As B) End Sub <System.Composition.Import> _ Public ReadOnly Property PropertyB() As B End Class " + BasicWellKnownAttributesDefinition, // Test0.vb(7,3): warning RS0006: Attribute 'ImportingConstructorAttribute' comes from a different version of MEF than the export attribute on 'C' GetBasicResultAt(7, 3, "ImportingConstructorAttribute", "C"), // Test0.vb(11,3): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C' GetBasicResultAt(11, 3, "ImportAttribute", "C"), // Test0.vb(17,3): warning RS0006: Attribute 'ImportingConstructorAttribute' comes from a different version of MEF than the export attribute on 'C2' GetBasicResultAt(17, 3, "ImportingConstructorAttribute", "C2"), // Test0.vb(21,3): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C2' GetBasicResultAt(21, 3, "ImportAttribute", "C2") ); } [Fact] public async Task DiagnosticCases_BadMefAttributeOnParameter() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class B { } [System.Composition.Export(typeof(C))] public class C { [System.Composition.ImportingConstructor] public C([System.ComponentModel.Composition.Import]B b) { } [System.Composition.Import] public B PropertyB { get; } } [System.ComponentModel.Composition.Export(typeof(C2))] public class C2 { [System.ComponentModel.Composition.ImportingConstructor] public C2([System.Composition.Import]B b) { } [System.ComponentModel.Composition.Import] public B PropertyB { get; } } " + CSharpWellKnownAttributesDefinition, // Test0.cs(10,15): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C' GetCSharpResultAt(10, 15, "ImportAttribute", "C"), // Test0.cs(20,16): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C2' GetCSharpResultAt(20, 16, "ImportAttribute", "C2")); await VerifyVB.VerifyAnalyzerAsync(@" Public Class B End Class <System.Composition.Export(GetType(C))> _ Public Class C <System.Composition.ImportingConstructor> _ Public Sub New(<System.ComponentModel.Composition.Import> b As B) End Sub <System.Composition.Import> _ Public ReadOnly Property PropertyB() As B End Class <System.ComponentModel.Composition.Export(GetType(C2))> _ Public Class C2 <System.ComponentModel.Composition.ImportingConstructor> _ Public Sub New(<System.Composition.Import> b As B) End Sub <System.ComponentModel.Composition.Import> _ Public ReadOnly Property PropertyB() As B End Class " + BasicWellKnownAttributesDefinition, // Test0.vb(8,18): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C' GetBasicResultAt(8, 18, "ImportAttribute", "C"), // Test0.vb(18,18): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C2' GetBasicResultAt(18, 18, "ImportAttribute", "C2")); } #endregion private static DiagnosticResult GetCSharpResultAt(int line, int column, string attributeName, string typeName) => #pragma warning disable RS0030 // Do not used banned APIs VerifyCS.Diagnostic() .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(attributeName, typeName); private static DiagnosticResult GetBasicResultAt(int line, int column, string attributeName, string typeName) => #pragma warning disable RS0030 // Do not used banned APIs VerifyVB.Diagnostic() .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(attributeName, typeName); } }
using System; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media.Animation; using System.Windows.Threading; using Microsoft.Surface.Presentation.Controls; namespace csShared.Controls.TwoWaySliding { /// <summary> /// Interaction logic for TwoWaySlidingView.xaml /// </summary> public partial class TwoWaySlidingView : UserControl { DispatcherTimer timer; //DispatcherTimer animateTimer; bool scrollChanged = false; //bool autoScroll = false; double vertScrolled = 0; double horScrolled = 0; double scrollFrom = 0; //double scrollCurrent = 0; double scrollTo = 0; bool scrollAnimating = false; //double scrollStep = 50; bool mouseButtonDown = false; bool touchDown = false; Point mouseMoveFrom; Point mouseMoveTo; Point mouseMoveOriginal; double horScrollMargin = 25; public double listboxsize; double lastHorScrolled = -1; double lastVerScrolled = 0; bool doScrollToVert = false; public TwoWaySlidingView() { InitializeComponent(); this.Collection.ScrollChanged += Collection_ScrollChanged; // Mouse events voor scrollen this.CollectionList.PreviewMouseLeftButtonDown += CollectionList_MouseLeftButtonDown; this.CollectionList.PreviewMouseLeftButtonUp += CollectionList_MouseLeftButtonUp; this.CollectionList.MouseLeave += CollectionList_MouseLeave; this.CollectionList.PreviewMouseMove += CollectionList_PreviewMouseMove; // Touch events voor scrollen this.CollectionList.PreviewTouchDown += CollectionList_PreviewTouchDown; this.CollectionList.PreviewTouchUp += CollectionList_PreviewTouchUp; this.CollectionList.PreviewTouchMove += CollectionList_PreviewTouchMove; this.CollectionList.TouchLeave += CollectionList_TouchLeave; this.Collection.HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden; this.Collection.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden; timer = new DispatcherTimer(); timer.Tick += DispatchWorker; timer.Interval = new TimeSpan(0, 0, 0, 0, 100); timer.Start(); this.SizeChanged += TwoWaySlidingView_SizeChanged; } void CollectionList_TouchLeave(object sender, TouchEventArgs e) { touchDown = false; } void CollectionList_PreviewTouchMove(object sender, TouchEventArgs e) { if (touchDown) { mouseMoveTo = e.TouchDevice.GetTouchPoint(this.Collection).Position; double difX = mouseMoveFrom.X - mouseMoveTo.X; if (difX != 0) this.Collection.ScrollToHorizontalOffset(this.Collection.HorizontalOffset + difX); mouseMoveFrom = mouseMoveTo; } } void CollectionList_PreviewTouchUp(object sender, TouchEventArgs e) { touchDown = false; mouseMoveTo = e.TouchDevice.GetTouchPoint(this.Collection).Position; double difX = mouseMoveOriginal.X - mouseMoveTo.X; double difY = mouseMoveOriginal.Y - mouseMoveTo.Y; if (Math.Abs(difX) > horScrollMargin) // || Math.Abs(difY) > horScrollMargin) e.Handled = true; } void CollectionList_PreviewTouchDown(object sender, TouchEventArgs e) { touchDown = true; mouseMoveFrom = e.TouchDevice.GetTouchPoint(this.Collection).Position; } void CollectionList_MouseLeave(object sender, MouseEventArgs e) { mouseButtonDown = false; } void CollectionList_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { mouseButtonDown = false; mouseMoveTo = e.MouseDevice.GetPosition(this.Collection); double difX = mouseMoveOriginal.X - mouseMoveTo.X; double difY = mouseMoveOriginal.Y - mouseMoveTo.Y; //e.Handled = true; if (Math.Abs(difX) > horScrollMargin) // || Math.Abs(difY) > horScrollMargin) { //do generate mouseclick or select item which is undereath the mouse e.Handled = true; e.MouseDevice.DirectlyOver.ReleaseMouseCapture(); } // e.Handled = true; } void CollectionList_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { mouseButtonDown = true; mouseMoveOriginal = e.MouseDevice.GetPosition(this.Collection); mouseMoveFrom = e.MouseDevice.GetPosition(this.Collection); //e.Handled = true; } void CollectionList_PreviewMouseMove(object sender, MouseEventArgs e) { // Prefer touch over mouse moves if (mouseButtonDown && !touchDown) { mouseMoveTo = e.MouseDevice.GetPosition(this.Collection); double difX = mouseMoveFrom.X - mouseMoveTo.X; if (difX != 0) this.Collection.ScrollToHorizontalOffset(this.Collection.HorizontalOffset + difX); double difY = mouseMoveFrom.Y - mouseMoveTo.Y; if (difY != 0) { //this.Collection.ScrollToVerticalOffset(this.Collection.VerticalOffset + difY); } mouseMoveFrom = mouseMoveTo; //e.Handled = true; } } void TwoWaySlidingView_SizeChanged(object sender, SizeChangedEventArgs e) { if (e.WidthChanged) { double newWidth = this.Collection.ActualWidth; int itemNr = 1; int maxNr = this.HeaderList.Items.Count; foreach (singleSlide ss in this.HeaderList.Items) { if (itemNr == 1 || itemNr == maxNr) { ss.ColWidth = newWidth * 0.5; ss.ColWidthHeader = newWidth * 0.25; } else { ss.ColWidth = newWidth; ss.ColWidthHeader = newWidth * 0.5; } itemNr++; } } if (e.HeightChanged) { foreach (singleSlide ss in this.HeaderList.Items) { if (this.ActualHeight > 40) ss.ColHeight = this.ActualHeight - 40; else { ss.ColHeight = 0; } } } } void DispatchWorker(object sender, EventArgs e) { if (doScrollToVert) { doScrollToVert = false; this.Collection.ScrollToVerticalOffset(lastVerScrolled); } if (!this.Collection.IsScrolling && scrollChanged && !mouseButtonDown && !touchDown) { // Scroll has ended, check position to scroll further to an item int scrollRemVert; if (this.CollectionList.Items.Count == 0) return; int verWidth = Convert.ToInt32(this.CollectionList.ActualHeight) / (((singleSlide)this.CollectionList.Items[0]).Items.Count); int scrollToVert = Math.DivRem(Convert.ToInt32(vertScrolled), verWidth, out scrollRemVert); // For now no vertical scrolling if (scrollRemVert != 0) { //autoScroll = true; //this.Collection.ScrollToVerticalOffset(Convert.ToDouble((scrollToVert + 1) * verWidth)); } //int scrollToHor = Convert.ToInt32(vertScrolled) / 100; double scrollDif = horScrolled - scrollTo; int direction = 1; if (scrollDif < 0) direction = 0; int nrItems = this.CollectionList.Items.Count; int horWidth = Convert.ToInt32(this.CollectionList.ActualWidth) / nrItems; int scrollRemHor; int scrollToHor = Math.DivRem(Convert.ToInt32(horScrolled), horWidth, out scrollRemHor); if (scrollRemHor != 0 && Math.Abs(scrollDif) > horScrollMargin) { //autoScroll = true; scrollFrom = horScrolled; if (scrollToHor == (nrItems - 1)) direction = 0; scrollTo = Convert.ToDouble((scrollToHor + direction) * horWidth); if (scrollTo < 0) scrollTo = 0; scrollAnimating = true; int tmAnim = Convert.ToInt32(Convert.ToDouble(Math.Abs(scrollFrom - scrollTo)) * 600d / Convert.ToDouble(horWidth)); Duration animDur = new Duration(new TimeSpan(0, 0, 0, 0, tmAnim)); DoubleAnimation danim = new DoubleAnimation(scrollFrom, scrollTo, animDur); danim.EasingFunction = new ExponentialEase() { EasingMode = System.Windows.Media.Animation.EasingMode.EaseInOut, Exponent = 6 }; Storyboard myStoryboard = new Storyboard(); myStoryboard.Completed += myStoryboard_Completed; myStoryboard.Children.Add(danim); Storyboard.SetTarget(danim, this.Collection); Storyboard.SetTargetProperty(danim, new PropertyPath(SurfaceScrollViewerUtilities.HorizontalOffsetProperty)); myStoryboard.Begin(); } else if (Math.Abs(scrollDif) <= horScrollMargin) { this.Collection.ScrollToHorizontalOffset(this.Collection.HorizontalOffset - scrollDif); } scrollChanged = false; } } void myStoryboard_Completed(object sender, EventArgs e) { scrollAnimating = false; } void Collection_ScrollChanged(object sender, ScrollChangedEventArgs e) { // Makes sure the header will also scroll vertScrolled = e.VerticalOffset; if (Math.Abs(e.HorizontalChange) != 0) { horScrolled = e.HorizontalOffset; } if ((Math.Abs(e.VerticalChange) != 0) && (touchDown || mouseButtonDown)) lastVerScrolled = e.VerticalOffset; if (lastHorScrolled == -1) lastHorScrolled = horScrolled; if (!scrollAnimating) scrollChanged = true; if (Math.Abs(e.HorizontalChange) == 0) return; int nrItems = this.CollectionList.Items.Count; if (nrItems == 0) return; double dScr = horScrolled / 2.0d; //((((singleSlide)this.CollectionList.Items[0]).ColWidth / 3.0d) * horScrolled / this.CollectionList.ActualWidth) + (horScrolled / 2.0d); int horWidth = Convert.ToInt32(this.CollectionList.ActualWidth) / nrItems; Header.ScrollToHorizontalOffset(dScr); lastHorScrolled = horScrolled; } public void ScrollToLastVerPos() { //Collection.ScrollToVerticalOffset(lastVerScrolled); doScrollToVert = true; } private SurfaceListBox selectedListBox = null; private object selectedItem = null; public string selectedItemString = ""; // void lbSelectionChanged(object sender, SelectionChangedEventArgs args) // { // if (args.AddedItems.Count > 0) // { // foreach (object selIt in args.AddedItems) // { // TwoWaySliding.SelectableItem sit = selIt as TwoWaySliding.SelectableItem; // var slb = sender as SurfaceListBox; // var rem = new List<SelectableItem>(); // foreach (SelectableItem si in slb.SelectedItems) // { // if (si.Name != sit.Name) // rem.Add(si); // } // foreach (var r in rem) // slb.SelectedItems.Remove(r); // if ((sit != null) && ( sit.Name == selectedItemString)) // { // selectedListBox = sender as SurfaceListBox; // selectedItem = args.AddedItems[0]; // //selectedListBox.ScrollIntoView(selectedItem); // } // } // } // //if (args.RemovedItems.Count >0) // //{ // // foreach (object desIt in args.RemovedItems) // // { // // SelectableItem rem = desIt as SelectableItem; // // selectedItem = rem; // // if ((rem != null) && rem.Name == selectedItemString) // // { // // var slb = sender as SurfaceListBox; // // if (rem.Selected == true) // // rem.Selected = false; // // } // // } // //} // } void lbItemsScrollChanged(object sender, ScrollChangedEventArgs e) { SurfaceListBox slb = sender as SurfaceListBox; foreach (object slbIt in slb.Items) { TwoWaySliding.SelectableItem sit = slbIt as TwoWaySliding.SelectableItem; if ((sit != null) && (sit.Name == selectedItemString.Split('.').Last())) { slb.ScrollIntoView(sit); selectedItemString = "_"; } } if (selectedListBox != null && selectedItem != null) { //selectedListBox.ScrollIntoView(selectedItem); } /*if (slb != null && selectedListBox == slb) { slb.ScrollIntoView(slb.SelectedItem); }*/ //((SurfaceListBox)sender).ScrollIntoView(((SurfaceListBox)sender).SelectedItem); //e.Handled = false; //e.VerticalOffset = lastVerScrolled; //selectedListBox = (SurfaceListBox)sender; //selectedListBox. } } public class SurfaceScrollViewerUtilities { public static readonly DependencyProperty HorizontalOffsetProperty = DependencyProperty.RegisterAttached("HorizontalOffset", typeof(double), typeof(SurfaceScrollViewerUtilities), new FrameworkPropertyMetadata((double)0.0, OnHorizontalOffsetChanged)); /// <summary> /// Gets the HorizontalOffset property. This dependency property /// indicates .... /// </summary> public static double GetHorizontalOffset(DependencyObject d) { return (double)d.GetValue(HorizontalOffsetProperty); } /// <summary> /// Sets the HorizontalOffset property. This dependency property /// indicates .... /// </summary> public static void SetHorizontalOffset(DependencyObject d, double value) { d.SetValue(HorizontalOffsetProperty, value); } /// <summary> /// Handles changes to the HorizontalOffset property. /// </summary> private static void OnHorizontalOffsetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { SurfaceScrollViewer viewer = (SurfaceScrollViewer)d; viewer.ScrollToHorizontalOffset((double)e.NewValue); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // EncoderReplacementFallback.cs // namespace System.Text { using System; [Serializable] public sealed class EncoderReplacementFallback : EncoderFallback { // Our variables private String strDefault; // Construction. Default replacement fallback uses no best fit and ? replacement string public EncoderReplacementFallback() : this( "?" ) { } public EncoderReplacementFallback( String replacement ) { // Must not be null if(replacement == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "replacement" ); #else throw new ArgumentNullException(); #endif } // Make sure it doesn't have bad surrogate pairs bool bFoundHigh = false; for(int i = 0; i < replacement.Length; i++) { // Found a surrogate? if(Char.IsSurrogate( replacement, i )) { // High or Low? if(Char.IsHighSurrogate( replacement, i )) { // if already had a high one, stop if(bFoundHigh) { break; // break & throw at the bFoundHIgh below } bFoundHigh = true; } else { // Low, did we have a high? if(!bFoundHigh) { // Didn't have one, make if fail when we stop bFoundHigh = true; break; } // Clear flag bFoundHigh = false; } } // If last was high we're in trouble (not surrogate so not low surrogate, so break) else if(bFoundHigh) { break; } } if(bFoundHigh) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidCharSequenceNoIndex", "replacement" ) ); #else throw new ArgumentException(); #endif } strDefault = replacement; } public String DefaultString { get { return strDefault; } } public override EncoderFallbackBuffer CreateFallbackBuffer() { return new EncoderReplacementFallbackBuffer( this ); } // Maximum number of characters that this instance of this fallback could return public override int MaxCharCount { get { return strDefault.Length; } } public override bool Equals( Object value ) { EncoderReplacementFallback that = value as EncoderReplacementFallback; if(that != null) { return (this.strDefault == that.strDefault); } return (false); } public override int GetHashCode() { return strDefault.GetHashCode(); } } public sealed class EncoderReplacementFallbackBuffer : EncoderFallbackBuffer { // Store our default string private String strDefault; int fallbackCount = -1; int fallbackIndex = -1; // Construction public EncoderReplacementFallbackBuffer( EncoderReplacementFallback fallback ) { // 2X in case we're a surrogate pair this.strDefault = fallback.DefaultString + fallback.DefaultString; } // Fallback Methods public override bool Fallback( char charUnknown, int index ) { // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. if(fallbackCount >= 1) { // If we're recursive we may still have something in our buffer that makes this a surrogate if(char.IsHighSurrogate( charUnknown ) && fallbackCount >= 0 && char.IsLowSurrogate( strDefault[fallbackIndex + 1] )) { ThrowLastCharRecursive( Char.ConvertToUtf32( charUnknown, strDefault[fallbackIndex + 1] ) ); } // Nope, just one character ThrowLastCharRecursive( unchecked( (int)charUnknown ) ); } // Go ahead and get our fallback // Divide by 2 because we aren't a surrogate pair fallbackCount = strDefault.Length / 2; fallbackIndex = -1; return fallbackCount != 0; } public override bool Fallback( char charUnknownHigh, char charUnknownLow, int index ) { // Double check input surrogate pair if(!Char.IsHighSurrogate( charUnknownHigh )) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "charUnknownHigh", Environment.GetResourceString( "ArgumentOutOfRange_Range", 0xD800, 0xDBFF ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(!Char.IsLowSurrogate( charUnknownLow )) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "CharUnknownLow", Environment.GetResourceString( "ArgumentOutOfRange_Range", 0xDC00, 0xDFFF ) ); #else throw new ArgumentOutOfRangeException(); #endif } // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. if(fallbackCount >= 1) { ThrowLastCharRecursive( Char.ConvertToUtf32( charUnknownHigh, charUnknownLow ) ); } // Go ahead and get our fallback fallbackCount = strDefault.Length; fallbackIndex = -1; return fallbackCount != 0; } public override char GetNextChar() { // We want it to get < 0 because == 0 means that the current/last character is a fallback // and we need to detect recursion. We could have a flag but we already have this counter. fallbackCount--; fallbackIndex++; // Do we have anything left? 0 is now last fallback char, negative is nothing left if(fallbackCount < 0) { return (char)0; } // Need to get it out of the buffer. BCLDebug.Assert( fallbackIndex < strDefault.Length && fallbackIndex >= 0, "Index exceeds buffer range" ); return strDefault[fallbackIndex]; } public override bool MovePrevious() { // Back up one, only if we just processed the last character (or earlier) if(fallbackCount >= -1 && fallbackIndex >= 0) { fallbackIndex--; fallbackCount++; return true; } // Return false 'cause we couldn't do it. return false; } // How many characters left to output? public override int Remaining { get { // Our count is 0 for 1 character left. return (fallbackCount < 0) ? 0 : fallbackCount; } } // Clear the buffer public override unsafe void Reset() { fallbackCount = -1; fallbackIndex = 0; charStart = null; bFallingBack = false; } } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.Collections; using System.Collections.Generic; using System.Text; using Autodesk.Revit; using Autodesk.Revit.DB; using Autodesk.Revit.DB.Structure; namespace Revit.SDK.Samples.Reinforcement.CS { /// <summary> /// The geometry support for reinforcement creation on conlumn. /// It can prepare the geometry information for transverse and vertical rebar creation /// </summary> class ColumnGeometrySupport : GeometrySupport { // Private members double m_columnLength; //the length of the column double m_columnWidth; //the width of the column double m_columnHeight; //the height of the column /// <summary> /// constructor for the ColumnGeometrySupport /// </summary> /// <param name="element">the column which the rebars are placed on</param> /// <param name="geoOptions">the geometry option</param> public ColumnGeometrySupport(FamilyInstance element, Options geoOptions) : base(element, geoOptions) { // assert the host element is a column if (!element.StructuralType.Equals(StructuralType.Column)) { throw new Exception("ColumnGeometrySupport can only work for column instance."); } // Get the length, width and height of the column. m_columnHeight = GetDrivingLineLength(); m_columnLength = GetColumnLength(); m_columnWidth = GetColumnWidth(); } /// <summary> /// Get the geometry information of the transverse rebar /// </summary> /// <param name="location">the location of transverse rebar</param> /// <param name="spacing">the spacing value of the rebar</param> /// <returns>the gotted geometry information</returns> public RebarGeometry GetTransverseRebar(TransverseRebarLocation location, double spacing) { // sort the points of the swept profile XYZHeightComparer comparer = new XYZHeightComparer(); m_points.Sort(comparer); // the offset from the column surface to the rebar double offset = ColumnRebarData.TransverseOffset; //the length of the transverse rebar double rebarLength = 0; // get the origin and normal parameter for rebar creation Autodesk.Revit.DB.XYZ normal = m_drivingVector; double curveOffset = 0; //set rebar length and origin according to the location of rebar switch (location) { case TransverseRebarLocation.Start: // start transverse rebar rebarLength = m_columnHeight / 4; break; case TransverseRebarLocation.Center: // center transverse rebar rebarLength = m_columnHeight / 2; curveOffset = m_columnHeight / 4 + (rebarLength % spacing) / 2; break; case TransverseRebarLocation.End: // end transverse rebar rebarLength = m_columnHeight / 4; curveOffset = m_columnHeight - rebarLength + (rebarLength % spacing); break; default: throw new Exception("The program should never go here."); } // the number of the transverse rebar int rebarNumber = (int)(rebarLength / spacing) + 1; // get the profile of the transverse rebar List<Autodesk.Revit.DB.XYZ > movedPoints = OffsetPoints(offset); List<Autodesk.Revit.DB.XYZ > translatedPoints = new List<Autodesk.Revit.DB.XYZ >(); foreach (Autodesk.Revit.DB.XYZ point in movedPoints) { translatedPoints.Add(GeomUtil.OffsetPoint(point, m_drivingVector, curveOffset)); } IList<Curve> curves = new List<Curve>(); //the profile of the transverse rebar Autodesk.Revit.DB.XYZ first = translatedPoints[0]; Autodesk.Revit.DB.XYZ second = translatedPoints[1]; Autodesk.Revit.DB.XYZ third = translatedPoints[2]; Autodesk.Revit.DB.XYZ fourth = translatedPoints[3]; curves.Add(Line.get_Bound(first, second)); curves.Add(Line.get_Bound(second, fourth)); curves.Add(Line.get_Bound(fourth, third)); curves.Add(Line.get_Bound(third, first)); // return the rebar geometry information return new RebarGeometry(normal, curves, rebarNumber, spacing); } /// <summary> /// Get the geometry information of vertical rebar /// </summary> /// <param name="location">the location of vertical rebar</param> /// <param name="rebarNumber">the spacing value of the rebar</param> /// <returns>the gotted geometry information</returns> public RebarGeometry GetVerticalRebar(VerticalRebarLocation location, int rebarNumber) { // sort the points of the swept profile XYZHeightComparer comparer = new XYZHeightComparer(); m_points.Sort(comparer); // Get the offset and rebar length of rebar double offset = ColumnRebarData.VerticalOffset; double rebarLength = m_columnHeight + 3; //the length of rebar // Get the start point of the vertical rebar curve Autodesk.Revit.DB.XYZ startPoint = m_drivingLine.get_EndPoint(0); List<Autodesk.Revit.DB.XYZ > movedPoints = OffsetPoints(offset); movedPoints.Sort(comparer); Autodesk.Revit.DB.XYZ normal = new Autodesk.Revit.DB.XYZ (); // the normal parameter double rebarOffset = 0; // rebar offset, equal to rebarNumber* spacing // get the normal, start point and rebar offset of vertical rebar switch (location) { case VerticalRebarLocation.East: //vertical rebar in east normal = new Autodesk.Revit.DB.XYZ (0, 1, 0); rebarOffset = m_columnWidth - 2 * offset; startPoint = movedPoints[1]; break; case VerticalRebarLocation.North: //vertical rebar in north normal = new Autodesk.Revit.DB.XYZ (-1, 0, 0); rebarOffset = m_columnLength - 2 * offset; startPoint = movedPoints[3]; break; case VerticalRebarLocation.West: //vertical rebar in west normal = new Autodesk.Revit.DB.XYZ (0, -1, 0); rebarOffset = m_columnWidth - 2 * offset; startPoint = movedPoints[2]; break; case VerticalRebarLocation.South: //vertical rebar in south normal = new Autodesk.Revit.DB.XYZ (1, 0, 0); rebarOffset = m_columnLength - 2 * offset; startPoint = movedPoints[0]; break; default: break; } double spacing = rebarOffset / rebarNumber; //spacing value of the rebar Autodesk.Revit.DB.XYZ endPoint = GeomUtil.OffsetPoint(startPoint, m_drivingVector, rebarLength); IList<Curve> curves = new List<Curve>(); //profile of the rebar curves.Add(Line.get_Bound(startPoint, endPoint)); // return the rebar geometry information return new RebarGeometry(normal, curves, rebarNumber, spacing); } /// <summary> /// Get the length of the column /// </summary> /// <returns>the length data</returns> private double GetColumnLength() { XYZHeightComparer comparer = new XYZHeightComparer(); m_points.Sort(comparer); Autodesk.Revit.DB.XYZ refPoint = m_points[0]; List<Autodesk.Revit.DB.XYZ > directions = GetRelatedVectors(refPoint); directions.Sort(comparer); return GeomUtil.GetLength(directions[0]); } /// <summary> /// Get the width of the column /// </summary> /// <returns>the width data</returns> private double GetColumnWidth() { XYZHeightComparer comparer = new XYZHeightComparer(); m_points.Sort(comparer); Autodesk.Revit.DB.XYZ refPoint = m_points[0]; List<Autodesk.Revit.DB.XYZ > directions = GetRelatedVectors(refPoint); directions.Sort(comparer); return GeomUtil.GetLength(directions[1]); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Versioning; using EnvDTE; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using NuGet.VisualStudio.Resources; using MsBuildProject = Microsoft.Build.Evaluation.Project; using MsBuildProjectItem = Microsoft.Build.Evaluation.ProjectItem; using Project = EnvDTE.Project; namespace NuGet.VisualStudio { public class VsProjectSystem : PhysicalFileSystem, IVsProjectSystem, IComparer<IPackageFile> { private const string BinDir = "bin"; private FrameworkName _targetFramework; private readonly IFileSystem _baseFileSystem; public VsProjectSystem(Project project, IFileSystemProvider fileSystemProvider) : base(project.GetFullPath()) { Project = project; _baseFileSystem = fileSystemProvider.GetFileSystem(project.GetFullPath()); Debug.Assert(_baseFileSystem != null); } protected Project Project { get; private set; } protected IFileSystem BaseFileSystem { get { return _baseFileSystem; } } public virtual string ProjectName { get { return Project.Name; } } public string UniqueName { get { return Project.GetUniqueName(); } } public FrameworkName TargetFramework { get { if (_targetFramework == null) { _targetFramework = Project.GetTargetFrameworkName() ?? VersionUtility.DefaultTargetFramework; } return _targetFramework; } } public virtual bool IsBindingRedirectSupported { get { // Silverlight projects and Windows Phone projects do not support binding redirect. // They both share the same identifier as "Silverlight" return !"Silverlight".Equals(TargetFramework.Identifier, StringComparison.OrdinalIgnoreCase); } } public override void AddFile(string path, Stream stream) { AddFileCore(path, () => base.AddFile(path, stream)); } public override void AddFile(string path, Action<Stream> writeToStream) { AddFileCore(path, () => base.AddFile(path, writeToStream)); } private void AddFileCore(string path, Action addFile) { bool fileExistsInProject = FileExistsInProject(path); // If the file exists on disk but not in the project then skip it. // One exception is the 'packages.config' file, in which case we want to include // it into the project. if (base.FileExists(path) && !fileExistsInProject && !path.Equals(Constants.PackageReferenceFile)) { Logger.Log(MessageLevel.Warning, VsResources.Warning_FileAlreadyExists, path); } else { EnsureCheckedOutIfExists(path); addFile(); if (!fileExistsInProject) { AddFileToProject(path); } } } public override Stream CreateFile(string path) { EnsureCheckedOutIfExists(path); return base.CreateFile(path); } public override void DeleteDirectory(string path, bool recursive = false) { // Only delete this folder if it is empty and we didn't specify that we want to recurse if (!recursive && (base.GetFiles(path, "*.*", recursive).Any() || base.GetDirectories(path).Any())) { Logger.Log(MessageLevel.Warning, VsResources.Warning_DirectoryNotEmpty, path); return; } // Workaround for TFS update issue. If we're bound to TFS, do not try and delete directories. if (!(_baseFileSystem is ISourceControlFileSystem) && Project.DeleteProjectItem(path)) { Logger.Log(MessageLevel.Debug, VsResources.Debug_RemovedFolder, path); } } public override void DeleteFile(string path) { if (Project.DeleteProjectItem(path)) { string folderPath = Path.GetDirectoryName(path); if (!String.IsNullOrEmpty(folderPath)) { Logger.Log(MessageLevel.Debug, VsResources.Debug_RemovedFileFromFolder, Path.GetFileName(path), folderPath); } else { Logger.Log(MessageLevel.Debug, VsResources.Debug_RemovedFile, Path.GetFileName(path)); } } } public void AddFrameworkReference(string name) { try { // Add a reference to the project AddGacReference(name); Logger.Log(MessageLevel.Debug, VsResources.Debug_AddReference, name, ProjectName); } catch (Exception e) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, VsResources.FailedToAddGacReference, name), e); } } protected virtual void AddGacReference(string name) { Project.GetReferences().Add(name); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want to catch all exceptions")] public virtual void AddReference(string referencePath, Stream stream) { string name = Path.GetFileNameWithoutExtension(referencePath); try { // Get the full path to the reference string fullPath = PathUtility.GetAbsolutePath(Root, referencePath); string assemblyPath = fullPath; bool usedTempFile = false; // There is a bug in Visual Studio whereby if the fullPath contains a comma, // then calling Project.Object.References.Add() on it will throw a COM exception. // To work around it, we copy the assembly into temp folder and add reference to the copied assembly if (fullPath.Contains(",")) { string tempFile = Path.Combine(Path.GetTempPath(), Path.GetFileName(fullPath)); File.Copy(fullPath, tempFile, true); assemblyPath = tempFile; usedTempFile = true; } // Add a reference to the project dynamic reference = Project.GetReferences().Add(assemblyPath); // if we copied the assembly to temp folder earlier, delete it now since we no longer need it. if (usedTempFile) { try { File.Delete(assemblyPath); } catch { // don't care if we fail to delete a temp file } } if (reference != null) { TrySetCopyLocal(reference); // This happens if the assembly appears in any of the search paths that VS uses to locate assembly references. // Most commonly, it happens if this assembly is in the GAC or in the output path. if (reference.Path != null && !reference.Path.Equals(fullPath, StringComparison.OrdinalIgnoreCase)) { // Get the msbuild project for this project MsBuildProject buildProject = Project.AsMSBuildProject(); if (buildProject != null) { // Get the assembly name of the reference we are trying to add AssemblyName assemblyName = AssemblyName.GetAssemblyName(fullPath); // Try to find the item for the assembly name MsBuildProjectItem item = (from assemblyReferenceNode in buildProject.GetAssemblyReferences() where AssemblyNamesMatch(assemblyName, assemblyReferenceNode.Item2) select assemblyReferenceNode.Item1).FirstOrDefault(); if (item != null) { // Add the <HintPath> metadata item as a relative path item.SetMetadataValue("HintPath", referencePath); // Save the project after we've modified it. Project.Save(this); } } } } Logger.Log(MessageLevel.Debug, VsResources.Debug_AddReference, name, ProjectName); } catch (Exception e) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, VsResources.FailedToAddReference, name), e); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want to catch all exceptions")] public virtual void RemoveReference(string name) { try { // Get the reference name without extension string referenceName = Path.GetFileNameWithoutExtension(name); // Remove the reference from the project // NOTE:- Project.Object.References.Item requires Reference.Identity // which is, the Assembly name without path or extension // But, we pass in the assembly file name. And, this works for // almost all the assemblies since Assembly Name is the same as the assembly file name // In case of F#, the input parameter is case-sensitive as well // Hence, an override to THIS function is added to take care of that var reference = Project.GetReferences().Item(referenceName); if (reference != null) { reference.Remove(); Logger.Log(MessageLevel.Debug, VsResources.Debug_RemoveReference, name, ProjectName); } } catch (Exception e) { Logger.Log(MessageLevel.Warning, e.Message); } } public virtual bool FileExistsInProject(string path) { return Project.ContainsFile(path); } protected virtual bool ExcludeFile(string path) { // Exclude files from the bin directory. return Path.GetDirectoryName(path).Equals(BinDir, StringComparison.OrdinalIgnoreCase); } protected virtual void AddFileToProject(string path) { if (ExcludeFile(path)) { return; } // Get the project items for the folder path string folderPath = Path.GetDirectoryName(path); string fullPath = GetFullPath(path); ThreadHelper.Generic.Invoke(() => { ProjectItems container = Project.GetProjectItems(folderPath, createIfNotExists: true); // Add the file to project or folder AddFileToContainer(fullPath, folderPath, container); }); Logger.Log(MessageLevel.Debug, VsResources.Debug_AddedFileToProject, path, ProjectName); } protected virtual void AddFileToContainer(string fullPath, string folderPath, ProjectItems container) { container.AddFromFileCopy(fullPath); } public virtual string ResolvePath(string path) { return path; } public override IEnumerable<string> GetFiles(string path, string filter, bool recursive) { if (recursive) { throw new NotSupportedException(); } else { // Get all physical files return from p in Project.GetChildItems(path, filter, VsConstants.VsProjectItemKindPhysicalFile) select p.Name; } } public override IEnumerable<string> GetDirectories(string path) { // Get all physical folders return from p in Project.GetChildItems(path, "*.*", VsConstants.VsProjectItemKindPhysicalFolder) select p.Name; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We never want to fail when checking for existance")] public virtual bool ReferenceExists(string name) { try { string referenceName = name; if (Constants.AssemblyReferencesExtensions.Contains(Path.GetExtension(name), StringComparer.OrdinalIgnoreCase)) { // Get the reference name without extension referenceName = Path.GetFileNameWithoutExtension(name); } return Project.GetReferences().Item(referenceName) != null; } catch { } return false; } public virtual dynamic GetPropertyValue(string propertyName) { try { Property property = Project.Properties.Item(propertyName); if (property != null) { return property.Value; } } catch (ArgumentException) { // If the property doesn't exist this will throw an argument exception } return null; } public virtual void AddImport(string targetPath, ProjectImportLocation location) { if (String.IsNullOrEmpty(targetPath)) { throw new ArgumentNullException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "targetPath"); } string relativeTargetPath = PathUtility.GetRelativePath(PathUtility.EnsureTrailingSlash(Root), targetPath); Project.AddImportStatement(relativeTargetPath, location); Project.Save(this); // notify the project system of the change UpdateImportStamp(Project); } public virtual void RemoveImport(string targetPath) { if (String.IsNullOrEmpty(targetPath)) { throw new ArgumentNullException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "targetPath"); } string relativeTargetPath = PathUtility.GetRelativePath(PathUtility.EnsureTrailingSlash(Root), targetPath); Project.RemoveImportStatement(relativeTargetPath); Project.Save(this); // notify the project system of the change UpdateImportStamp(Project); } public virtual bool IsSupportedFile(string path) { string fileName = Path.GetFileName(path); // exclude all file names with the pattern as "web.*.config", // e.g. web.config, web.release.config, web.debug.config return !(fileName.StartsWith("web.", StringComparison.OrdinalIgnoreCase) && fileName.EndsWith(".config", StringComparison.OrdinalIgnoreCase)); } private void EnsureCheckedOutIfExists(string path) { Project.EnsureCheckedOutIfExists(this, path); } private static bool AssemblyNamesMatch(AssemblyName name1, AssemblyName name2) { return name1.Name.Equals(name2.Name, StringComparison.OrdinalIgnoreCase) && EqualsIfNotNull(name1.Version, name2.Version) && EqualsIfNotNull(name1.CultureInfo, name2.CultureInfo) && EqualsIfNotNull(name1.GetPublicKeyToken(), name2.GetPublicKeyToken(), Enumerable.SequenceEqual); } private static bool EqualsIfNotNull<T>(T obj1, T obj2) { return EqualsIfNotNull(obj1, obj2, (a, b) => a.Equals(b)); } private static bool EqualsIfNotNull<T>(T obj1, T obj2, Func<T, T, bool> equals) { // If both objects are non null do the equals if (obj1 != null && obj2 != null) { return equals(obj1, obj2); } // Otherwise consider them equal if either of the values are null return true; } public int Compare(IPackageFile x, IPackageFile y) { // BUG 636: We sort files so that they are added in the correct order // e.g aspx before aspx.cs if (x.Path.Equals(y.Path, StringComparison.OrdinalIgnoreCase)) { return 0; } // Add files that are prefixes of other files first if (x.Path.StartsWith(y.Path, StringComparison.OrdinalIgnoreCase)) { return -1; } if (y.Path.StartsWith(x.Path, StringComparison.OrdinalIgnoreCase)) { return 1; } return y.Path.CompareTo(x.Path); } /// <summary> /// Sets NuGetPackageImportStamp to a new random guid. This is a hack to let the project system know it is out of date. /// The value does not matter, it just needs to change. /// </summary> protected static void UpdateImportStamp(Project project) { // There is no reason to call this for pre-Dev12 project systems. if (VsVersionHelper.IsVisualStudio2013) { IVsBuildPropertyStorage propStore = project.ToVsHierarchy() as IVsBuildPropertyStorage; if (propStore != null) { // <NuGetPackageImportStamp>af617720</NuGetPackageImportStamp> string stamp = Guid.NewGuid().ToString().Split('-')[0]; ErrorHandler.ThrowOnFailure(propStore.SetPropertyValue("NuGetPackageImportStamp", string.Empty, (uint)_PersistStorageType.PST_PROJECT_FILE, stamp)); } } } private static void TrySetCopyLocal(dynamic reference) { // Always set copy local to true for references that we add try { reference.CopyLocal = true; } catch (NotSupportedException) { } catch (NotImplementedException) { } } } }
using System; using System.Collections.Generic; using Texture2D = Microsoft.Xna.Framework.Graphics.Texture2D; using FlatRedBall.Utilities; namespace FlatRedBall.Graphics.Animation { /// <summary> /// Represents a collection of AnimationFrames which can be used to perform /// texture flipping animation on IAnimationChainAnimatables such as Sprites. /// </summary> public partial class AnimationChain : List<AnimationFrame>, INameable, IEquatable<AnimationChain> { #region Fields private string mName; //private string mParentFileName; internal int mIndexInLoadedAchx = -1; #endregion #region Properties /// <summary> /// Sets the frame time to every frame in the animation to the value. For example, assigning a FrameTime of .2 will make every frame in the animation last .2 seconds. /// </summary> public float FrameTime { set { foreach (AnimationFrame frame in this) frame.FrameLength = value; } } public int IndexInLoadedAchx { get { return mIndexInLoadedAchx; } } #region XML Docs /// <summary> /// Gets the last AnimationFrame of the AnimationChain or null if /// there are no AnimationFrames. /// </summary> #endregion public AnimationFrame LastFrame { get { if (this.Count == 0) { return null; } else { return this[this.Count - 1]; } } } #region XML Docs /// <summary> /// The name of the AnimationChain. /// </summary> #endregion public string Name { get { return mName; } set { mName = value; } } private string mParentAchxFileName; public string ParentAchxFileName { get { return mParentAchxFileName; } set { mParentAchxFileName = value; } } private string mParentGifFileName; public string ParentGifFileName { get { return mParentGifFileName; } set { mParentGifFileName = value; } } /// <summary> /// The total duration of the animation in seconds. This is obtained by adding the FrameTime of all contained frames. /// </summary> public float TotalLength { get { float sum = 0; for (int i = 0; i < this.Count; i++) { AnimationFrame af = this[i]; sum += af.FrameLength; } return sum; } } #endregion #region Methods #region Constructors #region XML Docs /// <summary> /// Creates an empty AnimationChain. /// </summary> #endregion public AnimationChain() : base() { } #region XML Docs /// <summary> /// Creates a new AnimationChain with the argument capacity. /// </summary> /// <param name="capacity">Sets the initial capacity. Used to reduce memory allocation.</param> #endregion public AnimationChain(int capacity) : base(capacity) { } #endregion #region Public Methods public AnimationChain Clone() { AnimationChain animationChain = new AnimationChain(); foreach (AnimationFrame animationFrame in this) { animationChain.Add(animationFrame.Clone()); } animationChain.ParentGifFileName = ParentGifFileName; animationChain.ParentAchxFileName = ParentAchxFileName; animationChain.mIndexInLoadedAchx = mIndexInLoadedAchx; animationChain.mName = this.mName; return animationChain; } #region XML Docs /// <summary> /// Searches for and returns the AnimationFrame with its Name matching /// the nameToSearchFor argument, or null if none are found. /// </summary> /// <param name="nameToSearchFor">The name of the AnimationFrame to search for.</param> /// <returns>The AnimationFrame with matching name, or null if none exists.</returns> #endregion public AnimationFrame FindByName(string nameToSearchFor) { for (int i = 0; i < this.Count; i++) { AnimationFrame af = this[i]; if (af.Texture.Name == nameToSearchFor) return af; } return null; } #region XML Docs /// <summary> /// Returns the shortest absolute number of frames between the two argument frame numbers. This /// method moves forward and backward and considers looping. /// </summary> /// <param name="frame1">The index of the first frame.</param> /// <param name="frame2">The index of the second frame.</param> /// <returns>The positive or negative number of frames between the two arguments.</returns> #endregion public int FrameToFrame(int frame1, int frame2) { int difference = frame2 - frame1; if (difference > this.Count / 2.0) difference -= this.Count; else if (difference < -this.Count / 2.0) difference += this.Count; return difference; } public void ReplaceTexture(Texture2D oldTexture, Texture2D newTexture) { for (int i = 0; i < this.Count; i++) { if (this[i].Texture == oldTexture) { this[i].Texture = newTexture; this[i].TextureName = newTexture.Name; } } } public override string ToString() { return Name + " (" + Count + ")"; } #endregion #endregion #region IEquatable<AnimationChain> Members bool IEquatable<AnimationChain>.Equals(AnimationChain other) { return this == other; } #endregion } }
using Bridge.Contract; using Bridge.Contract.Constants; using ICSharpCode.NRefactory.CSharp; using System.Collections.Generic; using System.Linq; namespace Bridge.Translator { public class ForBlock : AbstractEmitterBlock { public ForBlock(IEmitter emitter, ForStatement forStatement) : base(emitter, forStatement) { this.Emitter = emitter; this.ForStatement = forStatement; } public ForStatement ForStatement { get; set; } public List<IAsyncStep> EmittedAsyncSteps { get; set; } protected override void DoEmit() { var awaiters = this.Emitter.IsAsync ? this.GetAwaiters(this.ForStatement) : null; if (awaiters != null && awaiters.Length > 0) { this.VisitAsyncForStatement(); } else { this.VisitForStatement(); } } protected void VisitAsyncForStatement() { ForStatement forStatement = this.ForStatement; var oldValue = this.Emitter.ReplaceAwaiterByVar; var jumpStatements = this.Emitter.JumpStatements; this.Emitter.JumpStatements = new List<IJumpInfo>(); this.PushLocals(); bool newLine = false; foreach (var item in forStatement.Initializers) { if (newLine) { this.WriteNewLine(); } item.AcceptVisitor(this.Emitter); newLine = true; } this.RemovePenultimateEmptyLines(true); this.WriteNewLine(); this.Write(JS.Vars.ASYNC_STEP + " = " + this.Emitter.AsyncBlock.Step + ";"); this.WriteNewLine(); this.Write("continue;"); IAsyncStep conditionStep = this.Emitter.AsyncBlock.AddAsyncStep(); this.WriteAwaiters(forStatement.Condition); this.Emitter.ReplaceAwaiterByVar = true; var lastConditionStep = this.Emitter.AsyncBlock.Steps.Last(); this.WriteIf(); this.WriteOpenParentheses(true); if (!forStatement.Condition.IsNull) { forStatement.Condition.AcceptVisitor(this.Emitter); } else { this.Write("true"); } this.WriteCloseParentheses(true); this.Emitter.ReplaceAwaiterByVar = oldValue; this.WriteSpace(); this.BeginBlock(); this.Write(JS.Vars.ASYNC_STEP + " = " + this.Emitter.AsyncBlock.Step + ";"); this.WriteNewLine(); this.Write("continue;"); this.EmittedAsyncSteps = this.Emitter.AsyncBlock.EmittedAsyncSteps; this.Emitter.AsyncBlock.EmittedAsyncSteps = new List<IAsyncStep>(); var writer = this.SaveWriter(); this.Emitter.AsyncBlock.AddAsyncStep(); this.Emitter.IgnoreBlock = forStatement.EmbeddedStatement; var startCount = this.Emitter.AsyncBlock.Steps.Count; forStatement.EmbeddedStatement.AcceptVisitor(this.Emitter); IAsyncStep loopStep = null; if (this.Emitter.AsyncBlock.Steps.Count > startCount) { loopStep = this.Emitter.AsyncBlock.Steps.Last(); } this.RestoreWriter(writer); if (!AbstractEmitterBlock.IsJumpStatementLast(this.Emitter.Output.ToString())) { this.WriteNewLine(); this.Write(JS.Vars.ASYNC_STEP + " = " + this.Emitter.AsyncBlock.Step + ";"); this.WriteNewLine(); this.Write("continue;"); this.WriteNewLine(); this.EndBlock(); this.WriteSpace(); } else { this.WriteNewLine(); this.EndBlock(); this.WriteSpace(); } if (this.Emitter.IsAsync) { this.Emitter.AsyncBlock.EmittedAsyncSteps = this.EmittedAsyncSteps; } IAsyncStep iteratorsStep = this.Emitter.AsyncBlock.AddAsyncStep(); /*foreach (var item in forStatement.Iterators) { this.WriteAwaiters(item); }*/ var lastIteratorStep = this.Emitter.AsyncBlock.Steps.Last(); if (loopStep != null) { loopStep.JumpToStep = iteratorsStep.Step; } lastIteratorStep.JumpToStep = conditionStep.Step; this.Emitter.ReplaceAwaiterByVar = true; var beforeStepsCount = this.Emitter.AsyncBlock.Steps.Count; foreach (var item in forStatement.Iterators) { item.AcceptVisitor(this.Emitter); if (this.Emitter.Output.ToString().TrimEnd().Last() != ';') { this.WriteSemiColon(); } this.WriteNewLine(); } if (beforeStepsCount < this.Emitter.AsyncBlock.Steps.Count) { this.Emitter.AsyncBlock.Steps.Last().JumpToStep = conditionStep.Step; } this.Emitter.ReplaceAwaiterByVar = oldValue; this.PopLocals(); var nextStep = this.Emitter.AsyncBlock.AddAsyncStep(); lastConditionStep.JumpToStep = nextStep.Step; if (this.Emitter.JumpStatements.Count > 0) { this.Emitter.JumpStatements.Sort((j1, j2) => -j1.Position.CompareTo(j2.Position)); foreach (var jump in this.Emitter.JumpStatements) { jump.Output.Insert(jump.Position, jump.Break ? nextStep.Step : iteratorsStep.Step); } } this.Emitter.JumpStatements = jumpStatements; } protected void VisitForStatement() { ForStatement forStatement = this.ForStatement; var jumpStatements = this.Emitter.JumpStatements; this.Emitter.JumpStatements = null; this.PushLocals(); this.Emitter.EnableSemicolon = false; this.WriteFor(); this.WriteOpenParentheses(); var old = this.Emitter.IsAsync; this.Emitter.IsAsync = false; foreach (var item in forStatement.Initializers) { if (item != forStatement.Initializers.First()) { this.WriteComma(); } item.AcceptVisitor(this.Emitter); } this.Emitter.IsAsync = old; this.WriteSemiColon(); this.WriteSpace(); if (!forStatement.Condition.IsNull) { forStatement.Condition.AcceptVisitor(this.Emitter); } this.WriteSemiColon(); this.WriteSpace(); foreach (var item in forStatement.Iterators) { if (item != forStatement.Iterators.First()) { this.WriteComma(); } item.AcceptVisitor(this.Emitter); } this.WriteCloseParentheses(); this.Emitter.EnableSemicolon = true; this.EmitBlockOrIndentedLine(forStatement.EmbeddedStatement); this.PopLocals(); this.Emitter.JumpStatements = jumpStatements; } } }
// <copyright file="DriverService.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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. // </copyright> using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net; using System.Security.Permissions; using OpenQA.Selenium.Internal; using OpenQA.Selenium.Remote; namespace OpenQA.Selenium { /// <summary> /// Exposes the service provided by a native WebDriver server executable. /// </summary> public abstract class DriverService : ICommandServer { private string driverServicePath; private string driverServiceExecutableName; private string driverServiceHostName = "localhost"; private int driverServicePort; private bool silent; private bool hideCommandPromptWindow; private Process driverServiceProcess; /// <summary> /// Initializes a new instance of the <see cref="DriverService"/> class. /// </summary> /// <param name="servicePath">The full path to the directory containing the executable providing the service to drive the browser.</param> /// <param name="port">The port on which the driver executable should listen.</param> /// <param name="driverServiceExecutableName">The file name of the driver service executable.</param> /// <param name="driverServiceDownloadUrl">A URL at which the driver service executable may be downloaded.</param> /// <exception cref="ArgumentException"> /// If the path specified is <see langword="null"/> or an empty string. /// </exception> /// <exception cref="DriverServiceNotFoundException"> /// If the specified driver service executable does not exist in the specified directory. /// </exception> protected DriverService(string servicePath, int port, string driverServiceExecutableName, Uri driverServiceDownloadUrl) { if (string.IsNullOrEmpty(servicePath)) { throw new ArgumentException("Path to locate driver executable cannot be null or empty.", "servicePath"); } string executablePath = Path.Combine(servicePath, driverServiceExecutableName); if (!File.Exists(executablePath)) { throw new DriverServiceNotFoundException(string.Format(CultureInfo.InvariantCulture, "The file {0} does not exist. The driver can be downloaded at {1}", executablePath, driverServiceDownloadUrl)); } this.driverServicePath = servicePath; this.driverServiceExecutableName = driverServiceExecutableName; this.driverServicePort = port; } /// <summary> /// Gets the Uri of the service. /// </summary> public Uri ServiceUrl { get { return new Uri(string.Format(CultureInfo.InvariantCulture, "http://{0}:{1}", this.driverServiceHostName, this.driverServicePort)); } } /// <summary> /// Gets or sets the host name of the service. Defaults to "localhost." /// </summary> /// <remarks> /// Most driver service executables do not allow connections from remote /// (non-local) machines. This property can be used as a workaround so /// that an IP address (like "127.0.0.1" or "::1") can be used instead. /// </remarks> public string HostName { get { return this.driverServiceHostName; } set { this.driverServiceHostName = value; } } /// <summary> /// Gets or sets the port of the service. /// </summary> public int Port { get { return this.driverServicePort; } set { this.driverServicePort = value; } } /// <summary> /// Gets or sets a value indicating whether the initial diagnostic information is suppressed /// when starting the driver server executable. Defaults to <see langword="false"/>, meaning /// diagnostic information should be shown by the driver server executable. /// </summary> public bool SuppressInitialDiagnosticInformation { get { return this.silent; } set { this.silent = value; } } /// <summary> /// Gets a value indicating whether the service is running. /// </summary> public bool IsRunning { [SecurityPermission(SecurityAction.Demand)] get { return this.driverServiceProcess != null && !this.driverServiceProcess.HasExited; } } /// <summary> /// Gets or sets a value indicating whether the command prompt window of the service should be hidden. /// </summary> public bool HideCommandPromptWindow { get { return this.hideCommandPromptWindow; } set { this.hideCommandPromptWindow = value; } } /// <summary> /// Gets the process ID of the running driver service executable. Returns 0 if the process is not running. /// </summary> public int ProcessId { get { if (this.IsRunning) { // There's a slight chance that the Process object is running, // but does not have an ID set. This should be rare, but we // definitely don't want to throw an exception. try { return this.driverServiceProcess.Id; } catch (InvalidOperationException) { } } return 0; } } /// <summary> /// Gets the executable file name of the driver service. /// </summary> protected string DriverServiceExecutableName { get { return this.driverServiceExecutableName; } } /// <summary> /// Gets the command-line arguments for the driver service. /// </summary> protected virtual string CommandLineArguments { get { return string.Format(CultureInfo.InvariantCulture, "--port={0}", this.driverServicePort); } } /// <summary> /// Gets a value indicating the time to wait for an initial connection before timing out. /// </summary> protected virtual TimeSpan InitializationTimeout { get { return TimeSpan.FromSeconds(20); } } /// <summary> /// Gets a value indicating the time to wait for the service to terminate before forcing it to terminate. /// </summary> protected virtual TimeSpan TerminationTimeout { get { return TimeSpan.FromSeconds(10); } } /// <summary> /// Gets a value indicating whether the service has a shutdown API that can be called to terminate /// it gracefully before forcing a termination. /// </summary> protected virtual bool HasShutdown { get { return true; } } /// <summary> /// Gets a value indicating whether the service is responding to HTTP requests. /// </summary> protected virtual bool IsInitialized { get { bool isInitialized = false; try { Uri serviceHealthUri = new Uri(this.ServiceUrl, new Uri(DriverCommand.Status, UriKind.Relative)); HttpWebRequest request = HttpWebRequest.Create(serviceHealthUri) as HttpWebRequest; request.KeepAlive = false; request.Timeout = 5000; HttpWebResponse response = request.GetResponse() as HttpWebResponse; // Checking the response from the 'status' end point. Note that we are simply checking // that the HTTP status returned is a 200 status, and that the resposne has the correct // Content-Type header. A more sophisticated check would parse the JSON response and // validate its values. At the moment we do not do this more sophisticated check. isInitialized = response.StatusCode == HttpStatusCode.OK && response.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase); response.Close(); } catch (WebException ex) { Console.WriteLine(ex.Message); } return isInitialized; } } /// <summary> /// Releases all resources associated with this <see cref="DriverService"/>. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Starts the DriverService. /// </summary> [SecurityPermission(SecurityAction.Demand)] public void Start() { this.driverServiceProcess = new Process(); this.driverServiceProcess.StartInfo.FileName = Path.Combine(this.driverServicePath, this.driverServiceExecutableName); this.driverServiceProcess.StartInfo.Arguments = this.CommandLineArguments; this.driverServiceProcess.StartInfo.UseShellExecute = false; this.driverServiceProcess.StartInfo.CreateNoWindow = this.hideCommandPromptWindow; this.driverServiceProcess.Start(); bool serviceAvailable = this.WaitForServiceInitialization(); if (!serviceAvailable) { string msg = "Cannot start the driver service on " + this.ServiceUrl; throw new WebDriverException(msg); } } /// <summary> /// Finds the specified driver service executable. /// </summary> /// <param name="executableName">The file name of the executable to find.</param> /// <param name="downloadUrl">A URL at which the driver service executable may be downloaded.</param> /// <returns>The directory containing the driver service executable.</returns> /// <exception cref="DriverServiceNotFoundException"> /// If the specified driver service executable does not exist in the current directory or in a directory on the system path. /// </exception> protected static string FindDriverServiceExecutable(string executableName, Uri downloadUrl) { string serviceDirectory = FileUtilities.FindFile(executableName); if (string.IsNullOrEmpty(serviceDirectory)) { throw new DriverServiceNotFoundException(string.Format(CultureInfo.InvariantCulture, "The {0} file does not exist in the current directory or in a directory on the PATH environment variable. The driver can be downloaded at {1}.", executableName, downloadUrl)); } return serviceDirectory; } /// <summary> /// Releases all resources associated with this <see cref="DriverService"/>. /// </summary> /// <param name="disposing"><see langword="true"/> if the Dispose method was explicitly called; otherwise, <see langword="false"/>.</param> protected virtual void Dispose(bool disposing) { if (disposing) { this.Stop(); } } /// <summary> /// Stops the DriverService. /// </summary> [SecurityPermission(SecurityAction.Demand)] private void Stop() { if (this.IsRunning) { if (this.HasShutdown) { Uri shutdownUrl = new Uri(this.ServiceUrl, "/shutdown"); DateTime timeout = DateTime.Now.Add(this.TerminationTimeout); while (this.IsRunning && DateTime.Now < timeout) { try { // Issue the shutdown HTTP request, then wait a short while for // the process to have exited. If the process hasn't yet exited, // we'll retry. We wait for exit here, since catching the exception // for a failed HTTP request due to a closed socket is particularly // expensive. HttpWebRequest request = HttpWebRequest.Create(shutdownUrl) as HttpWebRequest; request.KeepAlive = false; HttpWebResponse response = request.GetResponse() as HttpWebResponse; response.Close(); this.driverServiceProcess.WaitForExit(3000); } catch (WebException) { } } } // If at this point, the process still hasn't exited, wait for one // last-ditch time, then, if it still hasn't exited, kill it. Note // that falling into this branch of code should be exceedingly rare. if (this.IsRunning) { this.driverServiceProcess.WaitForExit(Convert.ToInt32(this.TerminationTimeout.TotalMilliseconds)); if (!this.driverServiceProcess.HasExited) { this.driverServiceProcess.Kill(); } } this.driverServiceProcess.Dispose(); this.driverServiceProcess = null; } } /// <summary> /// Waits until a the service is initialized, or the timeout set /// by the <see cref="InitializationTimeout"/> property is reached. /// </summary> /// <returns><see langword="true"/> if the service is properly started and receiving HTTP requests; /// otherwise; <see langword="false"/>.</returns> private bool WaitForServiceInitialization() { bool isInitialized = false; DateTime timeout = DateTime.Now.Add(this.InitializationTimeout); while (!isInitialized && DateTime.Now < timeout) { // If the driver service process has exited, we can exit early. if (!this.IsRunning) { break; } isInitialized = this.IsInitialized; } return isInitialized; } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections; using System.Collections.Concurrent; using System.Linq.Expressions; using System.Collections.ObjectModel; using System.Diagnostics; using System.Management.Automation.Internal; using Microsoft.PowerShell.Commands; using Dbg = System.Management.Automation.Diagnostics; #if CORECLR using System.Reflection; #endif namespace System.Management.Automation { /// <summary> /// Class definition of CommandProcessor - This class provides interface to create /// and execute commands written in CLS compliant languages. /// </summary> internal class CommandProcessor : CommandProcessorBase { #region ctor static CommandProcessor() { s_constructInstanceCache = new ConcurrentDictionary<Type, Func<Cmdlet>>(); // Avoid jitting constructors some of the more commonly used cmdlets in SMA.dll - not meant to be // exhaustive b/c many cmdlets aren't called at all, so we'd never even need an entry in the cache. s_constructInstanceCache.GetOrAdd(typeof(ForEachObjectCommand), () => new ForEachObjectCommand()); s_constructInstanceCache.GetOrAdd(typeof(WhereObjectCommand), () => new WhereObjectCommand()); s_constructInstanceCache.GetOrAdd(typeof(ImportModuleCommand), () => new ImportModuleCommand()); s_constructInstanceCache.GetOrAdd(typeof(GetModuleCommand), () => new GetModuleCommand()); s_constructInstanceCache.GetOrAdd(typeof(GetHelpCommand), () => new GetHelpCommand()); s_constructInstanceCache.GetOrAdd(typeof(InvokeCommandCommand), () => new InvokeCommandCommand()); s_constructInstanceCache.GetOrAdd(typeof(GetCommandCommand), () => new GetCommandCommand()); s_constructInstanceCache.GetOrAdd(typeof(OutDefaultCommand), () => new OutDefaultCommand()); s_constructInstanceCache.GetOrAdd(typeof(OutHostCommand), () => new OutHostCommand()); s_constructInstanceCache.GetOrAdd(typeof(OutNullCommand), () => new OutNullCommand()); s_constructInstanceCache.GetOrAdd(typeof(SetStrictModeCommand), () => new SetStrictModeCommand()); s_constructInstanceCache.GetOrAdd(typeof(FormatDefaultCommand), () => new FormatDefaultCommand()); s_constructInstanceCache.GetOrAdd(typeof(OutLineOutputCommand), () => new OutLineOutputCommand()); } /// <summary> /// Initializes the new instance of CommandProcessor class. /// </summary> /// /// <param name="cmdletInfo"> /// The information about the cmdlet. /// </param> /// /// <param name="context"> /// PowerShell engine execution context for this command. /// </param> /// /// <exception cref="CommandNotFoundException"> /// If there was a failure creating an instance of the cmdlet type. /// </exception> /// internal CommandProcessor(CmdletInfo cmdletInfo, ExecutionContext context) : base(cmdletInfo) { this._context = context; Init(cmdletInfo); } /// <summary> /// This is the constructor for script as cmdlet. /// </summary> /// <param name="scriptCommandInfo"> /// The information about the cmdlet. /// </param> /// <param name="context"> /// PowerShell engine execution context for this command. /// </param> /// <param name="useLocalScope"></param> /// <param name="sessionState"></param> /// <param name="fromScriptFile">True when the script to be executed came from a file (as opposed to a function, or interactive input)</param> internal CommandProcessor(IScriptCommandInfo scriptCommandInfo, ExecutionContext context, bool useLocalScope, bool fromScriptFile, SessionStateInternal sessionState) : base(scriptCommandInfo as CommandInfo) { this._context = context; this._useLocalScope = useLocalScope; this._fromScriptFile = fromScriptFile; this.CommandSessionState = sessionState; Init(scriptCommandInfo); } // CommandProcessor #endregion ctor #region internal members /// <summary> /// Returns a CmdletParameterBinderController for the specified command /// </summary> /// /// <param name="command"> /// The cmdlet to bind parameters to. /// </param> /// /// <returns> /// A new instance of a CmdletParameterBinderController. /// </returns> /// /// <exception cref="ArgumentException"> /// if <paramref name="command"/> is not a Cmdlet. /// </exception> /// internal ParameterBinderController NewParameterBinderController(InternalCommand command) { Cmdlet cmdlet = command as Cmdlet; if (cmdlet == null) { throw PSTraceSource.NewArgumentException("command"); } ParameterBinderBase parameterBinder; IScriptCommandInfo scriptCommandInfo = CommandInfo as IScriptCommandInfo; if (scriptCommandInfo != null) { parameterBinder = new ScriptParameterBinder(scriptCommandInfo.ScriptBlock, cmdlet.MyInvocation, this._context, cmdlet, CommandScope); } else { parameterBinder = new ReflectionParameterBinder(cmdlet, cmdlet); } _cmdletParameterBinderController = new CmdletParameterBinderController(cmdlet, CommandInfo.CommandMetadata, parameterBinder); return _cmdletParameterBinderController; } internal CmdletParameterBinderController CmdletParameterBinderController { get { if (_cmdletParameterBinderController == null) { NewParameterBinderController(this.Command); } return _cmdletParameterBinderController; } } private CmdletParameterBinderController _cmdletParameterBinderController; /// <summary> /// Get the ObsoleteAttribute of the current command /// </summary> internal override ObsoleteAttribute ObsoleteAttribute { get { return _obsoleteAttribute; } } private ObsoleteAttribute _obsoleteAttribute; /// <summary> /// Binds the specified command-line parameters to the target /// </summary> /// /// <returns> /// true if encode succeeds otherwise false. /// </returns> /// /// <exception cref="ParameterBindingException"> /// If any parameters fail to bind, /// or /// If any mandatory parameters are missing. /// </exception> /// /// <exception cref="MetadataException"> /// If there is an error generating the metadata for dynamic parameters. /// </exception> internal void BindCommandLineParameters() { using (commandRuntime.AllowThisCommandToWrite(false)) { Diagnostics.Assert( this.CmdletParameterBinderController != null, "A parameter binder controller should always be available"); // Always set the hash table on MyInvocation so it's available for both interpreted cmdlets // as well as compiled ones. this.CmdletParameterBinderController.CommandLineParameters.UpdateInvocationInfo(this.Command.MyInvocation); this.Command.MyInvocation.UnboundArguments = new Collections.Generic.List<object>(); this.CmdletParameterBinderController.BindCommandLineParameters(arguments); } } /// <summary> /// Prepares the command. Encodes the command-line parameters /// JonN 2003-04-02 Split from Execute() /// </summary> /// <exception cref="ParameterBindingException"> /// If any parameters fail to bind, /// or /// If any mandatory parameters are missing. /// </exception> /// <exception cref="MetadataException"> /// If there is an error generating the metadata for dynamic parameters. /// </exception> internal override void Prepare(IDictionary psDefaultParameterValues) { // Note that Prepare() and DoBegin() should NOT be combined. // Reason: Encoding of commandline parameters happen as part of // Prepare(). If they are combined, the first command's // DoBegin() will be called before the next command's Prepare(). // Since BeginProcessing() can write objects to the downstream // commandlet, it will end up calling DoExecute() (from Pipe.Add()) // before Prepare. // Steps involved: // (1) Backup the default parameter values // (2) Handle input objects - add them to the input pipe. // (3) Bind the parameters to properties (encoding) // (4) Execute the command method using DoExecute() (repeatedly) this.CmdletParameterBinderController.DefaultParameterValues = psDefaultParameterValues; Diagnostics.Assert( this.Command != null, "CommandProcessor did not initialize Command\n" + this.CommandInfo.Name); BindCommandLineParameters(); } /// <summary> /// Execute BeginProcessing part of command /// </summary> internal override void DoBegin() { if (!RanBeginAlready && CmdletParameterBinderController.ObsoleteParameterWarningList != null) { using (CommandRuntime.AllowThisCommandToWrite(false)) { // Write out warning messages for the bound obsolete parameters. // The warning message are generated during parameter binding, but we delay writing // them out until now so that the -WarningAction will be respected as expected. foreach (WarningRecord warningRecord in CmdletParameterBinderController.ObsoleteParameterWarningList) { CommandRuntime.WriteWarning(warningRecord); } } // Clear up the warning message list CmdletParameterBinderController.ObsoleteParameterWarningList.Clear(); } base.DoBegin(); } /// <summary> /// This calls the command. It assumes that Prepare() has already been called. /// JonN 2003-04-02 Split from Execute() /// </summary> /// <exception cref="PipelineStoppedException"> /// a terminating error occurred, or the pipeline was otherwise stopped /// </exception> internal override void ProcessRecord() { // Invoke the Command method with the request object if (!this.RanBeginAlready) { RanBeginAlready = true; try { // NOTICE-2004/06/08-JonN 959638 using (commandRuntime.AllowThisCommandToWrite(true)) { if (Context._debuggingMode > 0 && !(Command is PSScriptCmdlet)) { Context.Debugger.CheckCommand(this.Command.MyInvocation); } Command.DoBeginProcessing(); } } // 2004/03/18-JonN This is understood to be // an FXCOP violation, cleared by KCwalina. catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); // This cmdlet threw an exception, so // wrap it and bubble it up. throw ManageInvocationException(e); } } Debug.Assert(this.Command.MyInvocation.PipelineIterationInfo != null); // this should have been allocated when the pipeline was started while (Read()) { Pipe oldErrorOutputPipe = _context.ShellFunctionErrorOutputPipe; Exception exceptionToThrow = null; try { // // On V1 the output pipe was redirected to the command's output pipe only when it // was already redirected. This is the original comment explaining this behaviour: // // NTRAID#Windows Out of Band Releases-926183-2005-12-15 // MonadTestHarness has a bad dependency on an artifact of the current implementation // The following code only redirects the output pipe if it's already redirected // to preserve the artifact. The test suites need to be fixed and then this // the check can be removed and the assignment always done. // // However, this makes the hosting APIs behave differently than commands executed // from the command-line host (for example, see bugs Win7:415915 and Win7:108670). // The RedirectShellErrorOutputPipe flag is used by the V2 hosting API to force the // redirection. // if (this.RedirectShellErrorOutputPipe || _context.ShellFunctionErrorOutputPipe != null) { _context.ShellFunctionErrorOutputPipe = this.commandRuntime.ErrorOutputPipe; } // NOTICE-2004/06/08-JonN 959638 using (commandRuntime.AllowThisCommandToWrite(true)) { if (CmdletParameterBinderController.ObsoleteParameterWarningList != null && CmdletParameterBinderController.ObsoleteParameterWarningList.Count > 0) { // Write out warning messages for the pipeline-value-bound obsolete parameters. // The warning message are generated during parameter binding, but we delay writing // them out until now so that the -WarningAction will be respected as expected. foreach (WarningRecord warningRecord in CmdletParameterBinderController.ObsoleteParameterWarningList) { CommandRuntime.WriteWarning(warningRecord); } // Clear up the warning message list CmdletParameterBinderController.ObsoleteParameterWarningList.Clear(); } this.Command.MyInvocation.PipelineIterationInfo[this.Command.MyInvocation.PipelinePosition]++; Command.DoProcessRecord(); } } catch (RuntimeException rte) { // Most exceptions get wrapped here, but an exception that originated from // a throw statement should not get wrapped, so it is just rethrown. if (rte.WasThrownFromThrowStatement) { throw; } exceptionToThrow = rte; } catch (LoopFlowException) { // Win8:84066 - Don't wrap LoopFlowException, we incorrectly raise a PipelineStoppedException // which gets caught by a script try/catch if we wrap here. throw; } // 2004/03/18-JonN This is understood to be // an FXCOP violation, cleared by KCwalina. catch (Exception e) // Catch-all OK, 3rd party callout. { exceptionToThrow = e; } finally { _context.ShellFunctionErrorOutputPipe = oldErrorOutputPipe; } if (exceptionToThrow != null) { CommandProcessorBase.CheckForSevereException(exceptionToThrow); // This cmdlet threw an exception, so // wrap it and bubble it up. throw ManageInvocationException(exceptionToThrow); } } } #endregion public_methods #region helper_methods /// <summary> /// Tells whether it is the first call to Read /// </summary> private bool _firstCallToRead = true; /// <summary> /// Tells whether to bail out in the next call to Read /// </summary> private bool _bailInNextCall; /// <summary> /// Populates the parameters specified from the pipeline. /// </summary> /// /// <returns> /// A bool indicating whether read succeeded. /// </returns> /// /// <exception cref="ParameterBindingException"> /// If a parameter fails to bind. /// or /// If a mandatory parameter is missing. /// </exception> /// <exception cref="PipelineStoppedException"> /// The pipeline was already stopped. /// </exception> /// // 2003/10/07-JonN was public, now internal internal sealed override bool Read() { // (1) If Read() is called for the first time and with pipe closed and // no object in the input pipe and // (typically for the first cmdlet in the pipe & during programmatic // execution of a command), Read() will succeed (return true) for // only one time (so that the // (2) If Read() is called with some input objects in the pipeline, it // processes the input // object one at a time and adds parameters from the input object // to the list of parameters. If // added to the error pipe and Read() will continue to read the // next object in the pipe. // (3) Read() will return false if there are no objects in the pipe // for processing. // (4) Read() will return true if the parameters are encoded in the // request - signals ready for execution. // (5) Read() will refresh the properties that are encoded via pipeline // parameters in the next // call to Read() [To their default values, so that the // next execution of the command will // not work on previously specified parameter]. // If the flag 'bail in next call' is true, then bail out returning false. if (_bailInNextCall) return false; // ProcessRecord() will loop on Command.Read(), and continue calling // ProcessRecord() until the incoming pipe is empty. We need to // stop this loop if a downstream cmdlet broke guidelines and // "swallowed" a PipelineStoppedException. Command.ThrowIfStopping(); // Prepare the default value parameter list if this is the first call to Read if (_firstCallToRead) { _firstCallToRead = false; if (!IsPipelineInputExpected()) { // Cmdlet should operate only with command-line parameters // Let the command Execute with the specified command line parameters // And Read should return false in the next call. _bailInNextCall = true; return true; } } // If this cmdlet has any members that could be bound // from the pipeline, do that now. In fact, we always try and // do it once anyway because this BindPipelineParameters() does // the final binding stage in before executing the cmdlet. bool mandatoryParametersSpecified = false; while (!mandatoryParametersSpecified) { // Retrieve the object from the input pipeline object inputObject = this.commandRuntime.InputPipe.Retrieve(); if (inputObject == AutomationNull.Value) { // no object in the pipeline, stop reading Command.CurrentPipelineObject = null; return false; } // If we are reading input for the first command in the pipeline increment PipelineIterationInfo[0], which is the number of items read from the input if (this.Command.MyInvocation.PipelinePosition == 1) { this.Command.MyInvocation.PipelineIterationInfo[0]++; } try { // Process the input pipeline object if (false == ProcessInputPipelineObject(inputObject)) { // The input object was not bound to any parameters of the cmdlet. // Write a non-terminating error and continue with the next input // object. WriteInputObjectError( inputObject, ParameterBinderStrings.InputObjectNotBound, "InputObjectNotBound"); continue; } } catch (ParameterBindingException bindingError) { // Set the target and write the error bindingError.ErrorRecord.SetTargetObject(inputObject); ErrorRecord errorRecord = new ErrorRecord( bindingError.ErrorRecord, bindingError); this.commandRuntime._WriteErrorSkipAllowCheck(errorRecord); continue; } Collection<MergedCompiledCommandParameter> missingMandatoryParameters; using (ParameterBinderBase.bindingTracer.TraceScope( "MANDATORY PARAMETER CHECK on cmdlet [{0}]", this.CommandInfo.Name)) { // Check for unbound mandatory parameters but don't prompt mandatoryParametersSpecified = this.CmdletParameterBinderController.HandleUnboundMandatoryParameters(out missingMandatoryParameters); } if (!mandatoryParametersSpecified) { string missingParameters = CmdletParameterBinderController.BuildMissingParamsString(missingMandatoryParameters); // Since the input object did not satisfy all mandatory parameters // for the command, write an ErrorRecord to the error pipe with // the target as the input object. WriteInputObjectError( inputObject, ParameterBinderStrings.InputObjectMissingMandatory, "InputObjectMissingMandatory", missingParameters); } } return true; } /// <summary> /// Writes an ErrorRecord to the commands error pipe because the specified /// input object was not bound to the command. /// </summary> /// /// <param name="inputObject"> /// The pipeline input object that was not bound. /// </param> /// /// <param name="resourceString"> /// The error message. /// </param> /// /// <param name="errorId"> /// The resource ID of the error message is also used as error ID /// of the ErrorRecord. /// </param> /// /// <param name="args"> /// Additional arguments to be formatted into the error message that represented in <paramref name="resourceString"/>. /// </param> /// private void WriteInputObjectError( object inputObject, string resourceString, string errorId, params object[] args) { Type inputObjectType = (inputObject == null) ? null : inputObject.GetType(); ParameterBindingException bindingException = new ParameterBindingException( ErrorCategory.InvalidArgument, this.Command.MyInvocation, null, null, null, inputObjectType, resourceString, errorId, args); ErrorRecord errorRecord = new ErrorRecord( bindingException, errorId, ErrorCategory.InvalidArgument, inputObject); errorRecord.SetInvocationInfo(this.Command.MyInvocation); this.commandRuntime._WriteErrorSkipAllowCheck(errorRecord); } // WriteIgnoredInputObjectError /// <summary> /// Reads an object from an input pipeline and attempts to bind the parameters /// </summary> /// /// <param name="inputObject"> /// The pipeline input object to be processed. /// </param> /// /// <returns> /// False the pipeline input object was not bound in any way to the command. /// </returns> /// /// <exception cref="ParameterBindingException"> /// If a ShouldProcess parameter is specified but the cmdlet does not support /// ShouldProcess. /// or /// If an error occurred trying to bind a parameter from the pipeline object. /// </exception> /// private bool ProcessInputPipelineObject(object inputObject) { PSObject inputToOperateOn = null; // Use ETS to retrieve properties from the input object // turn it into a shell object if it isn't one already... // we depend on PSObject.AsPSObject() being idempotent - if // it's already a shell object, don't encapsulate it again. if (inputObject != null) { inputToOperateOn = PSObject.AsPSObject(inputObject); } Command.CurrentPipelineObject = inputToOperateOn; return this.CmdletParameterBinderController.BindPipelineParameters(inputToOperateOn); } private static readonly ConcurrentDictionary<Type, Func<Cmdlet>> s_constructInstanceCache; private static Cmdlet ConstructInstance(Type type) { // Call the default constructor if type derives from Cmdlet. // Return null (and the caller will generate an appropriate error) if // type does not derive from Cmdlet. We do it this way so the expensive type check // is performed just once per type. return s_constructInstanceCache.GetOrAdd(type, t => Expression.Lambda<Func<Cmdlet>>( typeof(Cmdlet).IsAssignableFrom(t) ? (Expression)Expression.New(t) : Expression.Constant(null, typeof(Cmdlet))).Compile())(); } /// <summary> /// Initializes the command's request object /// </summary> /// /// <param name="cmdletInformation"> /// The information about the cmdlet. /// </param> /// /// <exception cref="CmdletInvocationException"> /// If the constructor for the cmdlet threw an exception. /// </exception> /// /// <exception cref="MemberAccessException"> /// The type referenced by <paramref name="cmdletInformation"/> refered to an /// abstract type or them member was invoked via a late-binding mechanism. /// </exception> /// /// <exception cref="TypeLoadException"> /// If <paramref name="cmdletInformation"/> refers to a type that is invalid. /// </exception> /// private void Init(CmdletInfo cmdletInformation) { Diagnostics.Assert(cmdletInformation != null, "Constructor should throw exception if LookupCommand returned null."); Cmdlet newCmdlet = null; Exception initError = null; string errorIdAndResourceId = null; string resourceStr = null; try { // Create the request object newCmdlet = ConstructInstance(cmdletInformation.ImplementingType); if (newCmdlet == null) { // We could test the inheritance before constructing, but that's // expensive. Much cheaper to just check for null. initError = new InvalidCastException(); errorIdAndResourceId = "CmdletDoesNotDeriveFromCmdletType"; resourceStr = DiscoveryExceptions.CmdletDoesNotDeriveFromCmdletType; } } catch (MemberAccessException memberAccessException) { initError = memberAccessException; } catch (TypeLoadException typeLoadException) { initError = typeLoadException; } catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); // We don't have a Command or InvocationInfo at this point, // since the command failed to initialize. var commandException = new CmdletInvocationException(e, null); // Log a command health event MshLog.LogCommandHealthEvent( this._context, commandException, Severity.Warning); throw commandException; } if (null != initError) { // Log a command health event MshLog.LogCommandHealthEvent( this._context, initError, Severity.Warning); CommandNotFoundException exception = new CommandNotFoundException( cmdletInformation.Name, initError, errorIdAndResourceId ?? "CmdletNotFoundException", resourceStr ?? DiscoveryExceptions.CmdletNotFoundException, initError.Message); throw exception; } this.Command = newCmdlet; this.CommandScope = Context.EngineSessionState.CurrentScope; InitCommon(); } private void Init(IScriptCommandInfo scriptCommandInfo) { InternalCommand scriptCmdlet = new PSScriptCmdlet(scriptCommandInfo.ScriptBlock, _useLocalScope, FromScriptFile, _context); this.Command = scriptCmdlet; this.CommandScope = _useLocalScope ? this.CommandSessionState.NewScope(_fromScriptFile) : this.CommandSessionState.CurrentScope; InitCommon(); // If the script has been dotted, throw an error if it's from a different language mode. if (!this.UseLocalScope) { ValidateCompatibleLanguageMode(scriptCommandInfo.ScriptBlock, _context.LanguageMode, Command.MyInvocation); } } private void InitCommon() { // set the metadata this.Command.CommandInfo = this.CommandInfo; // set the ObsoleteAttribute of the current command _obsoleteAttribute = this.CommandInfo.CommandMetadata.Obsolete; // set the execution context this.Command.Context = this._context; // Now set up the command runtime for this command. try { this.commandRuntime = new MshCommandRuntime(_context, this.CommandInfo, this.Command); this.Command.commandRuntime = this.commandRuntime; } catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); // Log a command health event MshLog.LogCommandHealthEvent( this._context, e, Severity.Warning); throw; } } /// <summary> /// Checks if user has requested help (for example passing "-?" parameter for a cmdlet) /// and if yes, then returns the help target to display. /// </summary> /// <param name="helpTarget">help target to request</param> /// <param name="helpCategory">help category to request</param> /// <returns><c>true</c> if user requested help; <c>false</c> otherwise</returns> internal override bool IsHelpRequested(out string helpTarget, out HelpCategory helpCategory) { if (this.arguments != null) { foreach (CommandParameterInternal parameter in this.arguments) { Dbg.Assert(parameter != null, "CommandProcessor.arguments shouldn't have any null arguments"); if (parameter.IsDashQuestion()) { helpCategory = HelpCategory.All; // using InvocationName mainly to avoid bogus this.CommandInfo.Name // (when CmdletInfo.Name is initialized from "cmdlet" declaration // of a scriptblock and when "cmdlet" declaration doesn't specify any name) if ((this.Command != null) && (this.Command.MyInvocation != null) && (!string.IsNullOrEmpty(this.Command.MyInvocation.InvocationName))) { helpTarget = this.Command.MyInvocation.InvocationName; // Win8: 391035 get-help does not work properly for aliased cmdlets // For aliased cmdlets/functions,example Initialize-Volume -> Format-Volume, // MyInvocation.InvocationName is different from CommandInfo.Name // - CommandInfo.Name points to Format-Volume // - MyInvocation.InvocationName points to Initialize-Volume if (string.Equals(this.Command.MyInvocation.InvocationName, this.CommandInfo.Name, StringComparison.OrdinalIgnoreCase)) { helpCategory = this.CommandInfo.HelpCategory; } } else { helpTarget = this.CommandInfo.Name; helpCategory = this.CommandInfo.HelpCategory; } return true; } } } return base.IsHelpRequested(out helpTarget, out helpCategory); } #endregion helper_methods } }
using Line.Messaging; using Line.Messaging.Webhooks; using Microsoft.Azure.WebJobs.Host; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Threading.Tasks; namespace FunctionAppSample { class RichMenuSampleApp : WebhookApplication { private LineMessagingClient MessagingClient { get; } private TraceWriter Log { get; } #region RichMenu definitions private static readonly ImagemapSize _richMenuSize = ImagemapSize.RichMenuShort; private static readonly int _buttonWidth = _richMenuSize.Width / 4; private static readonly int _buttonHeight = _richMenuSize.Height; private static readonly string MenuNameA = "RichMenuA"; private static readonly string MenuNameB = "RichMenuB"; private static readonly string MenuNameC = "RichMenuC"; private static readonly string MenuNameD = "RichMenuD"; private static readonly IList<ActionArea> _menuActionAreas = new[] { new ActionArea() { Bounds = new ImagemapArea(_buttonWidth * 0, 0, _buttonWidth, _buttonHeight), Action = new PostbackTemplateAction("ButtonA", MenuNameA, "Menu A") }, new ActionArea() { Bounds = new ImagemapArea(_buttonWidth * 1, 0, _buttonWidth, _buttonHeight), Action = new PostbackTemplateAction("ButtonB", MenuNameB, "Menu B") }, new ActionArea() { Bounds = new ImagemapArea(_buttonWidth * 2, 0, _buttonWidth, _buttonHeight), Action = new PostbackTemplateAction("ButtonC", MenuNameC, "Menu C") }, new ActionArea() { Bounds = new ImagemapArea(_buttonWidth * 3, 0, _buttonWidth, _buttonHeight), Action = new PostbackTemplateAction("ButtonD", MenuNameD, "Menu D") }, }; private static readonly RichMenu RichMenuA = new RichMenu { Name = MenuNameA, Size = _richMenuSize, Selected = true, ChatBarText = "Menu A", Areas = _menuActionAreas }; private static readonly RichMenu RichMenuB = new RichMenu { Name = MenuNameB, Size = _richMenuSize, Selected = true, ChatBarText = "Menu B", Areas = _menuActionAreas }; private static readonly RichMenu RichMenuC = new RichMenu { Name = MenuNameC, Size = _richMenuSize, Selected = true, ChatBarText = "Menu C", Areas = _menuActionAreas }; private static readonly RichMenu RichMenuD = new RichMenu { Name = MenuNameD, Size = _richMenuSize, Selected = true, ChatBarText = "Menu D", Areas = _menuActionAreas }; #endregion public RichMenuSampleApp(LineMessagingClient lineMessagingClient, TraceWriter log) { MessagingClient = lineMessagingClient; Log = log; } public async Task<IList<ResponseRichMenu>> CreateRichMenuAsync(bool isRefresh) { var menuList = await MessagingClient.GetRichMenuListAsync(); if (isRefresh) { await DeleteRichMenusAsync(menuList); } var newMenuList = new List<ResponseRichMenu>(); newMenuList.Add(await RegisterRichMenuAsync(RichMenuA)); newMenuList.Add(await RegisterRichMenuAsync(RichMenuB)); newMenuList.Add(await RegisterRichMenuAsync(RichMenuC)); newMenuList.Add(await RegisterRichMenuAsync(RichMenuD)); return newMenuList; async Task<ResponseRichMenu> RegisterRichMenuAsync(RichMenu newItem) { var item = menuList.FirstOrDefault(menu => menu.Name == newItem.Name); if (item == null) { var id = await MessagingClient.CreateRichMenuAsync(newItem); var image = CreateRichMenuImage(newItem); await UploadRichMenuImageAsync(image, id); item = newItem.ToResponseRichMenu(id); } return item; } } private async Task DeleteRichMenusAsync(IList<ResponseRichMenu> menuList) { foreach (var menu in menuList) { await MessagingClient.DeleteRichMenuAsync(menu.RichMenuId); } menuList.Clear(); } private async Task UploadRichMenuImageAsync(System.Drawing.Image image, string richMenuId) { using (var stream = new MemoryStream()) { image.Save(stream, ImageFormat.Jpeg); stream.Position = 0; await MessagingClient.UploadRichMenuJpegImageAsync(stream, richMenuId); } } private System.Drawing.Image CreateRichMenuImage(RichMenu menu) { var bitmap = new Bitmap(menu.Size.Width, menu.Size.Height); var g = Graphics.FromImage(bitmap); var bkBrush = Brushes.White; if (menu.Name == RichMenuA.Name) { bkBrush = Brushes.Red; } else if (menu.Name == RichMenuB.Name) { bkBrush = Brushes.Blue; } else if (menu.Name == RichMenuC.Name) { bkBrush = Brushes.Green; } else if (menu.Name == RichMenuD.Name) { bkBrush = Brushes.Yellow; } g.FillRectangle(bkBrush, new Rectangle(0, 0, menu.Size.Width, menu.Size.Height)); using (var pen = new Pen(Color.DarkGray, 10.0f)) using (var font = new Font(FontFamily.GenericSansSerif, 80)) { foreach (var area in menu.Areas) { var action = (PostbackTemplateAction)area.Action; g.DrawRectangle(pen, area.Bounds.X, area.Bounds.Y, area.Bounds.Width, area.Bounds.Height); g.DrawString(action.Label, font, Brushes.Black, new RectangleF(area.Bounds.X, area.Bounds.Y, area.Bounds.Width, area.Bounds.Height), new StringFormat() { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center }); } } return bitmap; } protected override async Task OnMessageAsync(MessageEvent ev) { Log.WriteInfo($"SourceType:{ev.Source.Type}, SourceId:{ev.Source.Id}, MessageType:{ev.Message.Type}"); var textMessage = ev.Message as TextEventMessage; bool isRefresh = (textMessage?.Text?.Trim()?.ToLower() == "refresh"); var memuList = await CreateRichMenuAsync(isRefresh); var menuA = memuList.FirstOrDefault(m => m.Name == MenuNameA); if (menuA == null) { return; } await MessagingClient.LinkRichMenuToUserAsync(ev.Source.UserId, menuA.RichMenuId); await MessagingClient.ReplyMessageAsync(ev.ReplyToken, "Hello Rich Menu!"); } protected override async Task OnPostbackAsync(PostbackEvent ev) { var menuList = await MessagingClient.GetRichMenuListAsync(); var nextMenu = menuList.FirstOrDefault(menu => menu.Name == ev.Postback.Data); if (nextMenu == null) { await MessagingClient.ReplyMessageAsync(ev.ReplyToken, $"Error!! {ev.Postback.Data} not found."); } await MessagingClient.LinkRichMenuToUserAsync(ev.Source.UserId, nextMenu.RichMenuId); await MessagingClient.ReplyMessageAsync(ev.ReplyToken, $"I changed a rich menu to {nextMenu.ChatBarText}"); } } }
// Copyright (c) 2013-2018 SIL International // This software is licensed under the MIT license (http://opensource.org/licenses/MIT) using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Text.RegularExpressions; #if !NET40 using Microsoft.Extensions.DependencyModel; #endif namespace Icu { /// <summary> /// Helper class to try and get path to icu native binaries when running on /// Windows or .NET Core. /// </summary> internal static class NativeMethodsHelper { private const string Icu4c = nameof(Icu4c); private const string IcuRegexLinux = @"libicu\w+.so\.(?<version>[0-9]{2,})(\.[0-9])*"; private const string IcuRegexWindows = @"icu\w+(?<version>[0-9]{2,})(\.[0-9])*\.dll"; private static readonly Regex IcuBinaryRegex = new Regex($"{IcuRegexWindows}|{IcuRegexLinux}$", RegexOptions.Compiled); private static readonly string IcuSearchPattern = Platform.OperatingSystem == OperatingSystemType.Windows ? "icu*.dll" : "libicu*.so.*"; private static readonly string NugetPackageDirectory = GetDefaultPackageDirectory(Platform.OperatingSystem); private static IcuVersionInfo IcuVersion; /// <summary> /// Reset the member variables /// </summary> public static void Reset() { IcuVersion = null; } /// <summary> /// Tries to get path and version to Icu when running on .NET Core or Windows. /// </summary> /// <returns>The path and version of icu binaries if found. Check /// <see cref="IcuVersionInfo.Success"/> to see if the values were set.</returns> public static IcuVersionInfo GetIcuVersionInfoForNetCoreOrWindows() { // We've already tried to set the path to native assets. Don't try again. if (IcuVersion != null) { return IcuVersion; } // Set the default to IcuVersion with an empty path and no version set. IcuVersion = new IcuVersionInfo(); if (TryGetPathFromAssemblyDirectory()) { return IcuVersion; } // That's odd.. I guess we use normal search paths from %PATH% then. // One possibility is that it is not a dev machine and the application // is a published app... but then it should have returned true in // TryGetPathFromAssemblyDirectory. if (string.IsNullOrEmpty(NugetPackageDirectory)) { Trace.TraceWarning($"{nameof(NugetPackageDirectory)} is empty and application was unable to set path from current assembly directory."); return IcuVersion; } #if !NET40 var context = DependencyContext.Default; // If this is false, something went wrong. These files should have // either been found above or we should have been able to locate the // asset paths (for .NET Core and NuGet v3+ projects). if (!TryGetNativeAssetPaths(context, out string[] nativeAssetPaths)) { Trace.WriteLine("Could not locate icu native assets from DependencyModel."); return IcuVersion; } var icuLib = context.CompileLibraries .Where(x => x.Name.StartsWith(Icu4c, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault(); if (icuLib == default(CompilationLibrary)) { Trace.TraceWarning("Could not find Icu4c compilation library. Possible that the library writer did not include the Icu4c.Win.Full.Lib or Icu4c.Win.Full.Lib NuGet package."); return IcuVersion; } if (!TryResolvePackagePath(icuLib, NugetPackageDirectory, out string packagePath)) { Trace.WriteLine("Could not resolve nuget package directory...."); return IcuVersion; } TrySetIcuPathFromDirectory(new DirectoryInfo(packagePath), nativeAssetPaths); #endif return IcuVersion; } /// <summary> /// Tries to set the native library using the <see cref="NativeMethods.DirectoryOfThisAssembly"/> /// as the root directory. The following scenarios could happen: /// 1. {directoryOfAssembly}/icu*.dll /// Occurs when the project is published using the .NET Core CLI /// against the full .NET framework. /// 2. {directoryOfAssembly}/lib/{arch}/icu*.dll /// Occurs when the project is using NuGet v2, the traditional /// .NET Framework csproj or the new VS2017 projects. /// 3. {directoryOfAssembly}/runtimes/{runtimeId}/native/icu*.dll /// Occurs when the project is published using the .NET Core CLI. /// If one of the scenarios match, sets the <see cref="IcuVersion"/>. /// </summary> /// <returns>True if it was able to find the icu binaries within /// <see cref="NativeMethods.DirectoryOfThisAssembly"/>, false otherwise. /// </returns> private static bool TryGetPathFromAssemblyDirectory() { var assemblyDirectory = new DirectoryInfo(NativeMethods.DirectoryOfThisAssembly); // 1. Check in {assemblyDirectory}/ if (TryGetIcuVersionNumber(assemblyDirectory, out var version)) { IcuVersion = new IcuVersionInfo(assemblyDirectory, version); return true; } // 2. Check in {assemblyDirectory}/lib/*{architecture}*/ var libDirectory = Path.Combine(assemblyDirectory.FullName, "lib"); if (Directory.Exists(libDirectory)) { var candidateDirectories = Directory .EnumerateDirectories(libDirectory, $"*{Platform.ProcessArchitecture}*") .Select(x => new DirectoryInfo(x)); foreach (var directory in candidateDirectories) { if (TryGetIcuVersionNumber(directory, out version)) { IcuVersion = new IcuVersionInfo(directory, version); return true; } } } string[] nativeAssetPaths = null; #if !NET40 // 3. Check in {directoryOfAssembly}/runtimes/{runtimeId}/native/ if (!TryGetNativeAssetPaths(DependencyContext.Default, out nativeAssetPaths)) { Trace.WriteLine("Could not locate icu native assets from DependencyModel."); return false; } #endif // If we found the icu*.dll files under {directoryOfAssembly}/runtimes/{rid}/native/, // they should ALL be there... or else something went wrong in publishing the app or // restoring the files, or packaging the NuGet package. return TrySetIcuPathFromDirectory(assemblyDirectory, nativeAssetPaths); } /// <summary> /// Iterates through the directory for files with the path icu*.dll and /// tries to fetch the icu version number from them. /// </summary> /// <returns>Returns the version number if the search was successful and /// null, otherwise.</returns> private static bool TryGetIcuVersionNumber(DirectoryInfo directory, out int icuVersion) { icuVersion = int.MinValue; if (directory == null || !directory.Exists) return false; var version = directory.GetFiles(IcuSearchPattern) .Select(x => { var match = IcuBinaryRegex.Match(x.Name); if (match.Success && int.TryParse(match.Groups["version"].Value, out var retVal) && retVal >= NativeMethods.MinIcuVersion && retVal <= NativeMethods.MaxIcuVersion) { return retVal; } return new int?(); }) .OrderByDescending(x => x) .FirstOrDefault(); if (version.HasValue) icuVersion = version.Value; return version.HasValue; } /// <summary> /// Given a root path and a set of native asset paths, tries to see if /// the files exist and if they do, sets <see cref="IcuVersion"/>. /// </summary> /// <param name="baseDirectory">Root path to append asset paths to.</param> /// <param name="nativeAssetPaths">Set of native asset paths to check.</param> /// <returns>true if it was able to find the directory for all the asset /// paths given; false otherwise.</returns> private static bool TrySetIcuPathFromDirectory(DirectoryInfo baseDirectory, string[] nativeAssetPaths) { if (nativeAssetPaths == null || nativeAssetPaths.Length == 0) return false; Trace.WriteLine("Assets: " + Environment.NewLine + string.Join(Environment.NewLine + "\t-", nativeAssetPaths)); var assetPaths = nativeAssetPaths .Select(asset => new FileInfo(Path.Combine(baseDirectory.FullName, asset))); var doAllAssetsExistInDirectory = assetPaths.All(x => x.Exists); if (doAllAssetsExistInDirectory) { var directories = assetPaths.Select(file => file.Directory).ToArray(); if (directories.Length > 1) Trace.TraceWarning($"There are multiple directories for these runtime assets: {string.Join(Path.PathSeparator.ToString(), directories.Select(x => x.FullName))}. There should only be one... Using first directory."); var icuDirectory = directories.First(); if (TryGetIcuVersionNumber(icuDirectory, out int version)) { IcuVersion = new IcuVersionInfo(icuDirectory, version); } } return doAllAssetsExistInDirectory; } #if !NET40 /// <summary> /// Tries to get the icu native binaries by searching the Runtime /// ID graph to find the first set of paths that have those binaries. /// </summary> /// <returns>Unique relative paths to the native assets; empty if none /// could be found.</returns> private static bool TryGetNativeAssetPaths(DependencyContext context, out string[] nativeAssetPaths) { var assetPaths = Enumerable.Empty<string>(); if (context == null) { nativeAssetPaths = assetPaths.ToArray(); return false; } var defaultNativeAssets = context.GetDefaultNativeAssets().ToArray(); // This goes through the runtime graph and tries to find icu native // asset paths matching that runtime. foreach (var runtime in context.RuntimeGraph) { var nativeAssets = context.GetRuntimeNativeAssets(runtime.Runtime); assetPaths = nativeAssets.Except(defaultNativeAssets).Where(assetPath => IcuBinaryRegex.IsMatch(assetPath)); if (assetPaths.Any()) break; } nativeAssetPaths = assetPaths.ToArray(); return nativeAssetPaths.Length > 0; } /// <summary> /// Given a CompilationLibrary and a base path, tries to construct the /// nuget package location and returns true if it exists. /// /// Taken from: https://github.com/dotnet/core-setup/blob/master/src/Microsoft.Extensions.DependencyModel/Resolution/ResolverUtils.cs#L12 /// </summary> /// <param name="library">Compilation library to try to get the rooted /// path from.</param> /// <param name="basePath">Rooted base path to try and get library from.</param> /// <param name="packagePath">The path for the library if it exists; /// null otherwise.</param> /// <returns></returns> private static bool TryResolvePackagePath(CompilationLibrary library, string basePath, out string packagePath) { var path = library.Path; if (string.IsNullOrEmpty(path)) { path = Path.Combine(library.Name, library.Version); } packagePath = Path.Combine(basePath, path); return Directory.Exists(packagePath); } #endif /// <summary> /// Tries to fetch the default package directory for NuGet packages. /// Taken from: /// https://github.com/dotnet/core-setup/blob/master/src/Microsoft.Extensions.DependencyModel/Resolution/PackageCompilationAssemblyResolver.cs#L41-L64 /// </summary> /// <param name="osPlatform">OS Platform to fetch default package /// directory for.</param> /// <returns>The path to the default package directory; null if none /// could be set.</returns> private static string GetDefaultPackageDirectory(OperatingSystemType osPlatform) { var packageDirectory = Environment.GetEnvironmentVariable("NUGET_PACKAGES"); if (!string.IsNullOrEmpty(packageDirectory)) { return packageDirectory; } string basePath; if (osPlatform == OperatingSystemType.Windows) { basePath = Environment.GetEnvironmentVariable("USERPROFILE"); } else { basePath = Environment.GetEnvironmentVariable("HOME"); } if (string.IsNullOrEmpty(basePath)) { return null; } return Path.Combine(basePath, ".nuget", "packages"); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Data; using OpenMetaverse; using OpenSim.Framework; using MySql.Data.MySqlClient; namespace OpenSim.Data.MySQL { public class MySqlRegionData : MySqlFramework, IRegionData { private string m_Realm; private List<string> m_ColumnNames = null; // private int m_LastExpire = 0; public MySqlRegionData(string connectionString, string realm) : base(connectionString) { m_Realm = realm; Migration m = new Migration(m_Connection, GetType().Assembly, "GridStore"); m.Update(); } public List<RegionData> Get(string regionName, UUID scopeID) { string command = "select * from `"+m_Realm+"` where regionName like ?regionName"; if (scopeID != UUID.Zero) command += " and ScopeID = ?scopeID"; using (MySqlCommand cmd = new MySqlCommand(command)) { cmd.Parameters.AddWithValue("?regionName", regionName); cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString()); return RunCommand(cmd); } } public RegionData Get(int posX, int posY, UUID scopeID) { string command = "select * from `"+m_Realm+"` where locX = ?posX and locY = ?posY"; if (scopeID != UUID.Zero) command += " and ScopeID = ?scopeID"; using (MySqlCommand cmd = new MySqlCommand(command)) { cmd.Parameters.AddWithValue("?posX", posX.ToString()); cmd.Parameters.AddWithValue("?posY", posY.ToString()); cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString()); List<RegionData> ret = RunCommand(cmd); if (ret.Count == 0) return null; return ret[0]; } } public RegionData Get(UUID regionID, UUID scopeID) { string command = "select * from `"+m_Realm+"` where uuid = ?regionID"; if (scopeID != UUID.Zero) command += " and ScopeID = ?scopeID"; using (MySqlCommand cmd = new MySqlCommand(command)) { cmd.Parameters.AddWithValue("?regionID", regionID.ToString()); cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString()); List<RegionData> ret = RunCommand(cmd); if (ret.Count == 0) return null; return ret[0]; } } public List<RegionData> Get(int startX, int startY, int endX, int endY, UUID scopeID) { string command = "select * from `"+m_Realm+"` where locX between ?startX and ?endX and locY between ?startY and ?endY"; if (scopeID != UUID.Zero) command += " and ScopeID = ?scopeID"; using (MySqlCommand cmd = new MySqlCommand(command)) { cmd.Parameters.AddWithValue("?startX", startX.ToString()); cmd.Parameters.AddWithValue("?startY", startY.ToString()); cmd.Parameters.AddWithValue("?endX", endX.ToString()); cmd.Parameters.AddWithValue("?endY", endY.ToString()); cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString()); return RunCommand(cmd); } } public List<RegionData> RunCommand(MySqlCommand cmd) { List<RegionData> retList = new List<RegionData>(); using (IDataReader result = ExecuteReader(cmd)) { while (result.Read()) { RegionData ret = new RegionData(); ret.Data = new Dictionary<string, object>(); UUID regionID; UUID.TryParse(result["uuid"].ToString(), out regionID); ret.RegionID = regionID; UUID scope; UUID.TryParse(result["ScopeID"].ToString(), out scope); ret.ScopeID = scope; ret.RegionName = result["regionName"].ToString(); ret.posX = Convert.ToInt32(result["locX"]); ret.posY = Convert.ToInt32(result["locY"]); ret.sizeX = Convert.ToInt32(result["sizeX"]); ret.sizeY = Convert.ToInt32(result["sizeY"]); if (m_ColumnNames == null) { m_ColumnNames = new List<string>(); DataTable schemaTable = result.GetSchemaTable(); foreach (DataRow row in schemaTable.Rows) { if (row["ColumnName"] != null) m_ColumnNames.Add(row["ColumnName"].ToString()); } } foreach (string s in m_ColumnNames) { if (s == "uuid") continue; if (s == "ScopeID") continue; if (s == "regionName") continue; if (s == "locX") continue; if (s == "locY") continue; ret.Data[s] = result[s].ToString(); } retList.Add(ret); } CloseDBConnection(result, cmd); } return retList; } public bool Store(RegionData data) { if (data.Data.ContainsKey("uuid")) data.Data.Remove("uuid"); if (data.Data.ContainsKey("ScopeID")) data.Data.Remove("ScopeID"); if (data.Data.ContainsKey("regionName")) data.Data.Remove("regionName"); if (data.Data.ContainsKey("posX")) data.Data.Remove("posX"); if (data.Data.ContainsKey("posY")) data.Data.Remove("posY"); if (data.Data.ContainsKey("sizeX")) data.Data.Remove("sizeX"); if (data.Data.ContainsKey("sizeY")) data.Data.Remove("sizeY"); if (data.Data.ContainsKey("locX")) data.Data.Remove("locX"); if (data.Data.ContainsKey("locY")) data.Data.Remove("locY"); string[] fields = new List<string>(data.Data.Keys).ToArray(); using (MySqlCommand cmd = new MySqlCommand()) { string update = "update `" + m_Realm + "` set locX=?posX, locY=?posY, sizeX=?sizeX, sizeY=?sizeY"; foreach (string field in fields) { update += ", "; update += "`" + field + "` = ?" + field; cmd.Parameters.AddWithValue("?" + field, data.Data[field]); } update += " where uuid = ?regionID"; if (data.ScopeID != UUID.Zero) update += " and ScopeID = ?scopeID"; cmd.CommandText = update; cmd.Parameters.AddWithValue("?regionID", data.RegionID.ToString()); cmd.Parameters.AddWithValue("?regionName", data.RegionName); cmd.Parameters.AddWithValue("?scopeID", data.ScopeID.ToString()); cmd.Parameters.AddWithValue("?posX", data.posX.ToString()); cmd.Parameters.AddWithValue("?posY", data.posY.ToString()); cmd.Parameters.AddWithValue("?sizeX", data.sizeX.ToString()); cmd.Parameters.AddWithValue("?sizeY", data.sizeY.ToString()); if (ExecuteNonQuery(cmd) < 1) { string insert = "insert into `" + m_Realm + "` (`uuid`, `ScopeID`, `locX`, `locY`, `sizeX`, `sizeY`, `regionName`, `" + String.Join("`, `", fields) + "`) values ( ?regionID, ?scopeID, ?posX, ?posY, ?sizeX, ?sizeY, ?regionName, ?" + String.Join(", ?", fields) + ")"; cmd.CommandText = insert; if (ExecuteNonQuery(cmd) < 1) { return false; } } } return true; } public bool SetDataItem(UUID regionID, string item, string value) { using (MySqlCommand cmd = new MySqlCommand("update `" + m_Realm + "` set `" + item + "` = ?" + item + " where uuid = ?UUID")) { cmd.Parameters.AddWithValue("?" + item, value); cmd.Parameters.AddWithValue("?UUID", regionID.ToString()); if (ExecuteNonQuery(cmd) > 0) return true; } return false; } public bool Delete(UUID regionID) { using (MySqlCommand cmd = new MySqlCommand("delete from `" + m_Realm + "` where uuid = ?UUID")) { cmd.Parameters.AddWithValue("?UUID", regionID.ToString()); if (ExecuteNonQuery(cmd) > 0) return true; } return false; } } }
// (c) Copyright HutongGames, LLC 2010-2013. All rights reserved. using HutongGames.PlayMakerEditor; using UnityEditor; using UnityEngine; // You can't open an EditorWindow class in a C# Dll (as far as I can tell) // So we use a wrapper script to create the window and hook the editor up // TODO: move this to dll when Unity supports it... namespace HutongGames.PlayMakerEditor { [System.Serializable] class FsmEditorWindow : HutongGames.PlayMakerEditor.BaseEditorWindow { /// <summary> /// Open the Fsm Editor and optionally show the Welcome Screen /// </summary> public static void OpenWindow() { GetWindow<FsmEditorWindow>(); if (EditorPrefs.GetBool(EditorPrefStrings.ShowWelcomeScreen, true)) { GetWindow<PlayMakerWelcomeWindow>(true); } } /// <summary> /// Open the Fsm Editor and select an Fsm Component /// </summary> public static void OpenWindow(PlayMakerFSM fsmComponent) { OpenWindow(); FsmEditor.SelectFsm(fsmComponent.Fsm); } /// <summary> /// Open the Fsm Editor and select an Fsm Component /// </summary> public static void OpenWindow(FsmTemplate fsmTemplate) { OpenWindow(); FsmEditor.SelectFsm(fsmTemplate.fsm); } /// <summary> /// Is the Fsm Editor open? /// </summary> public static bool IsOpen() { return instance != null; } private static FsmEditorWindow instance; [SerializeField] private FsmEditor fsmEditor; // tool windows (can't open them inside dll) [SerializeField] private FsmSelectorWindow fsmSelectorWindow; [SerializeField] private FsmTemplateWindow fsmTemplateWindow; [SerializeField] private FsmStateWindow stateSelectorWindow; [SerializeField] private FsmActionWindow actionWindow; [SerializeField] private FsmErrorWindow errorWindow; [SerializeField] private FsmLogWindow logWindow; [SerializeField] private ContextToolWindow toolWindow; [SerializeField] private GlobalEventsWindow globalEventsWindow; [SerializeField] private GlobalVariablesWindow globalVariablesWindow; [SerializeField] private ReportWindow reportWindow; [SerializeField] private AboutWindow aboutWindow; // ReSharper disable UnusedMember.Local /// <summary> /// Delay initialization until first OnGUI to avoid interfering with runtime system intialization. /// </summary> public override void Initialize() { instance = this; if (fsmEditor == null) { fsmEditor = new FsmEditor(); } fsmEditor.InitWindow(this); fsmEditor.OnEnable(); } public override void DoGUI() { fsmEditor.OnGUI(); /* Debug Repaint events if (Event.current.type == EventType.repaint) { Debug.Log("Repaint"); }*/ if (Event.current.type == EventType.ValidateCommand) { switch (Event.current.commandName) { case "UndoRedoPerformed": case "Cut": case "Copy": case "Paste": case "SelectAll": Event.current.Use(); break; } } if (Event.current.type == EventType.ExecuteCommand) { switch (Event.current.commandName) { case "UndoRedoPerformed": FsmEditor.UndoRedoPerformed(); break; case "Cut": FsmEditor.Cut(); break; case "Copy": FsmEditor.Copy(); break; case "Paste": FsmEditor.Paste(); break; case "SelectAll": FsmEditor.SelectAll(); break; case "OpenWelcomeWindow": GetWindow<PlayMakerWelcomeWindow>(); break; case "OpenToolWindow": toolWindow = GetWindow<ContextToolWindow>(); break; case "OpenFsmSelectorWindow": fsmSelectorWindow = GetWindow<FsmSelectorWindow>(); fsmSelectorWindow.ShowUtility(); break; case "OpenFsmTemplateWindow": fsmTemplateWindow = GetWindow<FsmTemplateWindow>(); break; case "OpenStateSelectorWindow": stateSelectorWindow = GetWindow<FsmStateWindow>(); break; case "OpenActionWindow": actionWindow = GetWindow<FsmActionWindow>(); break; case "OpenGlobalEventsWindow": globalEventsWindow = GetWindow<FsmEventsWindow>(); break; case "OpenGlobalVariablesWindow": globalVariablesWindow = GetWindow<FsmGlobalsWindow>(); break; case "OpenErrorWindow": errorWindow = GetWindow<FsmErrorWindow>(); break; case "OpenFsmLogWindow": logWindow = GetWindow<FsmLogWindow>(); break; case "OpenAboutWindow": aboutWindow = GetWindow<AboutWindow>(); break; case "OpenReportWindow": reportWindow = GetWindow<ReportWindow>(); break; case "AddFsmComponent": PlayMakerMainMenu.AddFsmToSelected(); break; case "RepaintAll": RepaintAllWindows(); break; case "ChangeLanguage": ResetWindowTitles(); break; } GUIUtility.ExitGUI(); } } // called when you change editor language public void ResetWindowTitles() { if (toolWindow != null) { toolWindow.InitWindowTitle(); } if (fsmSelectorWindow != null) { fsmSelectorWindow.InitWindowTitle(); } if (stateSelectorWindow != null) { stateSelectorWindow.InitWindowTitle(); } if (actionWindow != null) { actionWindow.InitWindowTitle(); } if (globalEventsWindow != null) { globalEventsWindow.InitWindowTitle(); } if (globalVariablesWindow != null) { globalVariablesWindow.InitWindowTitle(); } if (errorWindow != null) { errorWindow.InitWindowTitle(); } if (logWindow != null) { logWindow.InitWindowTitle(); } if (reportWindow != null) { reportWindow.InitWindowTitle(); } if (fsmTemplateWindow != null) { fsmTemplateWindow.InitWindowTitle(); } } public void RepaintAllWindows() { if (toolWindow != null) { toolWindow.Repaint(); } if (fsmSelectorWindow != null) { fsmSelectorWindow.Repaint(); } if (stateSelectorWindow != null) { stateSelectorWindow.Repaint(); } if (actionWindow != null) { actionWindow.Repaint(); } if (globalEventsWindow != null) { globalEventsWindow.Repaint(); } if (globalVariablesWindow != null) { globalVariablesWindow.Repaint(); } if (errorWindow != null) { errorWindow.Repaint(); } if (logWindow != null) { logWindow.Repaint(); } if (reportWindow != null) { reportWindow.Repaint(); } if (fsmTemplateWindow != null) { fsmTemplateWindow.Repaint(); } Repaint(); } private void Update() { if (Initialized && fsmEditor != null) { fsmEditor.Update(); } } private void OnInspectorUpdate() { if (Initialized && fsmEditor != null) { fsmEditor.OnInspectorUpdate(); } } private void OnFocus() { if (Initialized && fsmEditor != null) { fsmEditor.OnFocus(); } } private void OnSelectionChange() { if (Initialized && fsmEditor != null) { fsmEditor.OnSelectionChange(); } } private void OnHierarchyChange() { if (Initialized && fsmEditor != null) { fsmEditor.OnHierarchyChange(); } } private void OnProjectChange() { if (Initialized && fsmEditor != null) { fsmEditor.OnProjectChange(); } } private void OnDisable() { if (Initialized && fsmEditor != null) { fsmEditor.OnDisable(); } instance = null; } private void OnDestroy() { if (toolWindow != null) { toolWindow.SafeClose(); } if (fsmSelectorWindow != null) { fsmSelectorWindow.SafeClose(); } if (fsmTemplateWindow != null) { fsmTemplateWindow.SafeClose(); } if (stateSelectorWindow != null) { stateSelectorWindow.SafeClose(); } if (actionWindow != null) { actionWindow.SafeClose(); } if (globalVariablesWindow != null) { globalVariablesWindow.SafeClose(); } if (globalEventsWindow != null) { globalEventsWindow.SafeClose(); } if (errorWindow != null) { errorWindow.SafeClose(); } if (logWindow != null) { logWindow.SafeClose(); } if (reportWindow != null) { reportWindow.SafeClose(); } if (aboutWindow != null) { aboutWindow.SafeClose(); } if (Initialized && fsmEditor != null) { fsmEditor.OnDestroy(); } } // ReSharper restore UnusedMember.Local } }
/*--------------------------------------------------------------------- * SocketExceptionsTests.cs - file description * Version: 1.0 * Author: REDMOND\a-grchat * Created: 9/12/2007 4:51:10 PM * ---------------------------------------------------------------------*/ using System.Net; using System.Net.Sockets; using System.Threading; using System; namespace Microsoft.Zelig.Test { public class SocketExceptionTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { /// <summary> /// This file tests all of the SocketExceptions except: /// /// The following ErrorCodes are not supported by the MF due to /// the lack of non-blocking (Begin-End)Send and (Begin-End)Receive methods: /// AlreadyInProgress, ConnectionAborted, Disconnecting /// /// The following ErrorCodes are not tested because they represent occurances /// that the TestHarness cannot duplicate: /// NetworkDown, NetworkUnreachable, NetworkReset, ConnectionReset , HostDown /// ProcessLimit, SystemNotReady, VersionNotSupported, TryAgain, NoRecovery, NoData /// /// The following ErrorCodes are not supported by the MF for other reasons: /// NotSocket, TypeNotFound -- VS returns typing errors instead /// DestinationAddressRequired -- VS throws AddressNotAvailable instead /// Shutdown -- MF does not implement Shutdown() /// NotInitialized -- C# doesn't use WSAStartup /// </summary> //Wait for GC try { // Check networking - we need to make sure we can reach our proxy server System.Net.Dns.GetHostEntry("itgproxy.dns.microsoft.com"); } catch (Exception ex) { Log.Exception("Unable to get address for itgproxy.dns.microsoft.com", ex); return InitializeResult.Skip; } Log.Comment("The following tests are located in SocketExceptionTests.cs"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); } public override TestResult Run( string[] args ) { return TestResult.Pass; } //--// //--// //--// [TestMethod] public TestResult SocketExceptionTest2_AddressAlreadyInUse() { /// <summary> /// 1. Causes an AddressAlreadyInUse error /// </summary> /// bool isCorrectCatch = false; bool isAnyCatch = false; try { Socket socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Socket socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { socketClient.Bind(new IPEndPoint(IPAddress.Loopback, 10)); socketServer.Bind(new IPEndPoint(IPAddress.Loopback, 10)); } catch (SocketException e) { if (e.ErrorCode.ToString() != SocketError.AddressAlreadyInUse.ToString()) throw new System.Exception("Incorrect ErrorCode in SocketException " + e.ErrorCode, e); isCorrectCatch = true; isAnyCatch = true; } finally { socketClient.Close(); socketServer.Close(); } } catch (System.Exception e) { isAnyCatch = true; Log.Comment("Incorrect exception caught: " + e.Message); } if (!isAnyCatch) { Log.Comment("No exception caught"); } return (isCorrectCatch ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketExceptionTest3_Protocol_Address_FamilyNotSupported() { /// <summary> /// 1. Causes an Address or ProtocolFamilyNotSupported error /// According to MSDN these Exceptions are "interchangeable in most cases" /// </summary> /// bool isAnyCatch = false; try { try { Socket socketTest = new Socket(AddressFamily.AppleTalk, SocketType.Stream, ProtocolType.Udp); } catch (SocketException e) { if (e.ErrorCode != (int)SocketError.ProtocolFamilyNotSupported && e.ErrorCode != (int)SocketError.AddressFamilyNotSupported) throw new System.Exception("Incorrect ErrorCode in SocketException " + e.ErrorCode, e); isAnyCatch = true; } } catch (System.Exception e) { isAnyCatch = true; Log.Comment("Incorrect exception caught: " + e.Message); } if (!isAnyCatch) { Log.Comment("No exception caught"); } return (isAnyCatch ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketExceptionTest4_ProtocolNotSupported() { /// <summary> /// 1. Causes a ProtocolNotSupported error /// This test currently fails see 17577 /// </summary> /// bool isAnyCatch = false; try { try { Socket socketTest = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Udp); } catch (SocketException e) { if (e.ErrorCode != (int)SocketError.ProtocolNotSupported) throw new System.Exception("Incorrect ErrorCode in SocketException " + e.ErrorCode, e); isAnyCatch = true; } } catch (System.Exception e) { isAnyCatch = true; Log.Comment("Incorrect exception caught: " + e.Message); } if (!isAnyCatch) { Log.Comment("No exception caught"); } return (isAnyCatch ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketExceptionTest6_IsConnected() { /// <summary> /// 1. Causes a IsConnected error /// </summary> /// bool isCorrectCatch = false; bool isAnyCatch = false; SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); try { try { testSockets.Startup(0, 0); testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); testSockets.socketClient.Connect(testSockets.epServer); } catch (SocketException) { isCorrectCatch = true; isAnyCatch = true; } } catch (System.Exception e) { isAnyCatch = true; Log.Comment("Incorrect exception caught: " + e.Message); } finally { testSockets.TearDown(); } if (!isAnyCatch) { Log.Comment("No exception caught"); } return (isCorrectCatch ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketExceptionTest11_AccessDenied() { /// <summary> /// 1. Causes a AccessDenied error /// </summary> /// bool isCorrectCatch = false; bool isAnyCatch = false; SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Dgram); try { try { int clientPort = SocketTools.nextPort; int serverPort = SocketTools.nextPort; int tempPort = serverPort; testSockets.socketClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, false); testSockets.Startup(clientPort, serverPort); IPEndPoint epBroadcast = new IPEndPoint(SocketTools.DottedDecimalToIp((byte)255, (byte)255, (byte)255, (byte)255), tempPort); EndPoint serverEndPoint = epBroadcast.Create(epBroadcast.Serialize()); testSockets.socketClient.SendTo(testSockets.bufSend, serverEndPoint); } catch (SocketException) { isCorrectCatch = true; isAnyCatch = true; } } catch (System.Exception e) { isAnyCatch = true; Log.Comment("Incorrect exception caught: " + e.Message); } finally { testSockets.TearDown(); } if (!isAnyCatch) { Log.Comment("No exception caught"); } return (isCorrectCatch ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketExceptionTest12_NotConnected() { /// <summary> /// 1. Causes a NotConnected error /// </summary> /// bool isCorrectCatch = false; bool isAnyCatch = false; SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); try { try { testSockets.Startup(0, 0); Socket socketTemp = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socketTemp.Bind(testSockets.socketServer.RemoteEndPoint); socketTemp.Send(new byte[2]); } catch (SocketException) { isCorrectCatch = true; isAnyCatch = true; } } catch (System.Exception e) { isAnyCatch = true; Log.Comment("Incorrect exception caught: " + e.Message); } finally { testSockets.TearDown(); } if (!isAnyCatch) { Log.Comment("No exception caught"); } return (isCorrectCatch ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketExceptionTest13_InvalidArgument() { /// <summary> /// 1. Causes a InvalidArgument error /// </summary> /// bool isCorrectCatch = false; bool isAnyCatch = false; SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); try { try { int clientPort = SocketTools.nextPort; int serverPort = SocketTools.nextPort; int tempPort = clientPort; testSockets.Startup(clientPort, serverPort); testSockets.socketServer.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.Broadcast, true); } catch (SocketException) { isCorrectCatch = true; isAnyCatch = true; } } catch (System.Exception e) { isAnyCatch = true; Log.Comment("Incorrect exception caught: " + e.Message); } finally { testSockets.TearDown(); } if (!isAnyCatch) { Log.Comment("No exception caught"); } return (isCorrectCatch ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketExceptionTest14_AddressNotAvailable() { /// <summary> /// 1. Causes a AddressNotAvailable error /// Due to loopback this method causes an InvalidArgument /// SocketException erroneously /// </summary> /// bool isCorrectCatch = false; bool isAnyCatch = false; SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); try { try { int clientPort = SocketTools.nextPort; int serverPort = SocketTools.nextPort; int tempPort = clientPort; testSockets.Startup(clientPort, serverPort); testSockets.socketClient.Bind(new IPEndPoint(new IPAddress(SocketTools.DottedDecimalToIp((byte)192, (byte)168, (byte)192, (byte)168)), tempPort)); } catch (SocketException) { isCorrectCatch = true; isAnyCatch = true; } } catch (System.Exception e) { isAnyCatch = true; Log.Comment("Incorrect exception caught: " + e.Message); } finally { testSockets.TearDown(); } if (!isAnyCatch) { Log.Comment("No exception caught"); } return (isCorrectCatch ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketExceptionTest16_HostNotFound() { /// <summary> /// 1. Causes a HostNotFound error /// </summary> /// bool isCorrectCatch = false; bool isAnyCatch = false; try { try { IPHostEntry ipHostEntry = Dns.GetHostEntry("fakeHostName"); } catch (SocketException) { isCorrectCatch = true; isAnyCatch = true; } } catch (System.Exception e) { isAnyCatch = true; Log.Comment("Incorrect exception caught: " + e.Message); } if (!isAnyCatch) { Log.Comment("No exception caught"); } return (isCorrectCatch ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketExceptionTest17_SocketError() { /// <summary> /// 1. Causes a SocketError error /// This currently succeeds but will need re-writing if 17577 is addressed /// </summary> /// bool isCorrectCatch = false; try { SocketPair testSockets = new SocketPair(ProtocolType.Udp, SocketType.Stream); } catch (SocketException) { isCorrectCatch = true; } return (isCorrectCatch ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketExceptionTest18_Fault() { /// <summary> /// 1. Causes a Fault error /// </summary> /// bool isCorrectCatch = false; bool isAnyCatch = false; SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); try { try { testSockets.socketClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new byte[] { (byte)0 }); testSockets.Startup(0, 0); } catch (SocketException) { isCorrectCatch = true; isAnyCatch = true; } } catch (System.Exception e) { isAnyCatch = true; Log.Comment("Incorrect exception caught: " + e.Message); } finally { testSockets.TearDown(); } if (!isAnyCatch) { Log.Comment("No exception caught"); } return (isCorrectCatch ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketExceptionTest19_ProtocolOption() { /// <summary> /// 1. Causes a ProtocolOption error /// </summary> /// bool isCorrectCatch = false; bool isAnyCatch = false; SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); try { try { testSockets.Startup(0, 0); testSockets.socketClient.GetSocketOption(SocketOptionLevel.IP, SocketOptionName.Linger); } catch (SocketException) { isCorrectCatch = true; isAnyCatch = true; } } catch (System.Exception e) { isAnyCatch = true; Log.Comment("Incorrect exception caught: " + e.Message); } if (!isAnyCatch) { Log.Comment("No exception caught"); } testSockets.TearDown(); testSockets = null; return (isCorrectCatch ? TestResult.Pass : TestResult.Fail); } [TestMethod] public TestResult SocketExceptionTest20_OperationNotSupported() { /// <summary> /// 1. Causes a OperationNotSupported error /// </summary> /// bool isCorrectCatch = false; bool isAnyCatch = false; SocketPair testSockets = new SocketPair(ProtocolType.Tcp, SocketType.Stream); try { try { testSockets.Startup(0, 0); testSockets.socketServer.Listen(1); testSockets.socketClient.Connect(testSockets.epServer); testSockets.socketClient.Send(testSockets.bufSend); using (Socket sock = testSockets.socketServer.Accept()) { sock.Receive(testSockets.bufReceive, SocketFlags.DontRoute); } isCorrectCatch = true; } catch (SocketException) { isCorrectCatch = true; isAnyCatch = true; } } catch (System.Exception e) { isAnyCatch = true; Log.Comment("Incorrect exception caught: " + e.Message); } if (!isAnyCatch) { Log.Comment("No exception caught"); } testSockets.TearDown(); testSockets = null; return (isCorrectCatch ? TestResult.Pass : TestResult.Fail); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Html; using System.Web.Routing; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Dynamics; using Umbraco.Core.IO; using Umbraco.Core.Models; using Umbraco.Core.Profiling; using Umbraco.Web.Models; using Umbraco.Web.Mvc; using Constants = Umbraco.Core.Constants; using Member = umbraco.cms.businesslogic.member.Member; namespace Umbraco.Web { /// <summary> /// HtmlHelper extensions for use in templates /// </summary> public static class HtmlHelperRenderExtensions { /// <summary> /// Renders the markup for the profiler /// </summary> /// <param name="helper"></param> /// <returns></returns> public static IHtmlString RenderProfiler(this HtmlHelper helper) { return new HtmlString(ProfilerResolver.Current.Profiler.Render()); } /// <summary> /// Renders a partial view that is found in the specified area /// </summary> /// <param name="helper"></param> /// <param name="partial"></param> /// <param name="area"></param> /// <param name="model"></param> /// <param name="viewData"></param> /// <returns></returns> public static MvcHtmlString AreaPartial(this HtmlHelper helper, string partial, string area, object model = null, ViewDataDictionary viewData = null) { var originalArea = helper.ViewContext.RouteData.DataTokens["area"]; helper.ViewContext.RouteData.DataTokens["area"] = area; var result = helper.Partial(partial, model, viewData); helper.ViewContext.RouteData.DataTokens["area"] = originalArea; return result; } /// <summary> /// Will render the preview badge when in preview mode which is not required ever unless the MVC page you are /// using does not inherit from UmbracoTemplatePage /// </summary> /// <param name="helper"></param> /// <returns></returns> /// <remarks> /// See: http://issues.umbraco.org/issue/U4-1614 /// </remarks> public static MvcHtmlString PreviewBadge(this HtmlHelper helper) { if (UmbracoContext.Current.InPreviewMode) { var htmlBadge = String.Format(UmbracoConfig.For.UmbracoSettings().Content.PreviewBadge, IOHelper.ResolveUrl(SystemDirectories.Umbraco), IOHelper.ResolveUrl(SystemDirectories.UmbracoClient), UmbracoContext.Current.HttpContext.Server.UrlEncode(UmbracoContext.Current.HttpContext.Request.Path)); return new MvcHtmlString(htmlBadge); } return new MvcHtmlString(""); } public static IHtmlString CachedPartial( this HtmlHelper htmlHelper, string partialViewName, object model, int cachedSeconds, bool cacheByPage = false, bool cacheByMember = false, ViewDataDictionary viewData = null, Func<object, ViewDataDictionary, string> contextualKeyBuilder = null) { var cacheKey = new StringBuilder(partialViewName); if (cacheByPage) { if (UmbracoContext.Current == null) { throw new InvalidOperationException("Cannot cache by page if the UmbracoContext has not been initialized, this parameter can only be used in the context of an Umbraco request"); } cacheKey.AppendFormat("{0}-", UmbracoContext.Current.PageId); } if (cacheByMember) { var currentMember = Member.GetCurrentMember(); cacheKey.AppendFormat("m{0}-", currentMember == null ? 0 : currentMember.Id); } if (contextualKeyBuilder != null) { var contextualKey = contextualKeyBuilder(model, viewData); cacheKey.AppendFormat("c{0}-", contextualKey); } return ApplicationContext.Current.ApplicationCache.CachedPartialView(htmlHelper, partialViewName, model, cachedSeconds, cacheKey.ToString(), viewData); } public static MvcHtmlString EditorFor<T>(this HtmlHelper htmlHelper, string templateName = "", string htmlFieldName = "", object additionalViewData = null) where T : new() { var model = new T(); var typedHelper = new HtmlHelper<T>( htmlHelper.ViewContext.CopyWithModel(model), htmlHelper.ViewDataContainer.CopyWithModel(model)); return typedHelper.EditorFor(x => model, templateName, htmlFieldName, additionalViewData); } /// <summary> /// A validation summary that lets you pass in a prefix so that the summary only displays for elements /// containing the prefix. This allows you to have more than on validation summary on a page. /// </summary> /// <param name="htmlHelper"></param> /// <param name="prefix"></param> /// <param name="excludePropertyErrors"></param> /// <param name="message"></param> /// <param name="htmlAttributes"></param> /// <returns></returns> public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, string prefix = "", bool excludePropertyErrors = false, string message = "", IDictionary<string, object> htmlAttributes = null) { if (prefix.IsNullOrWhiteSpace()) { return htmlHelper.ValidationSummary(excludePropertyErrors, message, htmlAttributes); } //if there's a prefix applied, we need to create a new html helper with a filtered ModelState collection so that it only looks for //specific model state with the prefix. var filteredHtmlHelper = new HtmlHelper(htmlHelper.ViewContext, htmlHelper.ViewDataContainer.FilterContainer(prefix)); return filteredHtmlHelper.ValidationSummary(excludePropertyErrors, message, htmlAttributes); } /// <summary> /// Returns the result of a child action of a strongly typed SurfaceController /// </summary> /// <typeparam name="T"></typeparam> /// <param name="htmlHelper"></param> /// <param name="actionName"></param> /// <returns></returns> public static IHtmlString Action<T>(this HtmlHelper htmlHelper, string actionName) where T : SurfaceController { return htmlHelper.Action(actionName, typeof(T)); } /// <summary> /// Returns the result of a child action of a SurfaceController /// </summary> /// <typeparam name="T"></typeparam> /// <param name="htmlHelper"></param> /// <param name="actionName"></param> /// <param name="surfaceType"></param> /// <returns></returns> public static IHtmlString Action(this HtmlHelper htmlHelper, string actionName, Type surfaceType) { Mandate.ParameterNotNull(surfaceType, "surfaceType"); Mandate.ParameterNotNullOrEmpty(actionName, "actionName"); var routeVals = new RouteValueDictionary(new {area = ""}); var surfaceController = SurfaceControllerResolver.Current.RegisteredSurfaceControllers .SingleOrDefault(x => x == surfaceType); if (surfaceController == null) throw new InvalidOperationException("Could not find the surface controller of type " + surfaceType.FullName); var metaData = PluginController.GetMetadata(surfaceController); if (!metaData.AreaName.IsNullOrWhiteSpace()) { //set the area to the plugin area if (routeVals.ContainsKey("area")) { routeVals["area"] = metaData.AreaName; } else { routeVals.Add("area", metaData.AreaName); } } return htmlHelper.Action(actionName, metaData.ControllerName, routeVals); } #region GetCropUrl [Obsolete("Use the UrlHelper.GetCropUrl extension instead")] [EditorBrowsable(EditorBrowsableState.Never)] public static IHtmlString GetCropUrl(this HtmlHelper htmlHelper, IPublishedContent mediaItem, string cropAlias) { return new HtmlString(mediaItem.GetCropUrl(cropAlias: cropAlias, useCropDimensions: true)); } [Obsolete("Use the UrlHelper.GetCropUrl extension instead")] [EditorBrowsable(EditorBrowsableState.Never)] public static IHtmlString GetCropUrl(this HtmlHelper htmlHelper, IPublishedContent mediaItem, string propertyAlias, string cropAlias) { return new HtmlString(mediaItem.GetCropUrl(propertyAlias: propertyAlias, cropAlias: cropAlias, useCropDimensions: true)); } [Obsolete("Use the UrlHelper.GetCropUrl extension instead")] [EditorBrowsable(EditorBrowsableState.Never)] public static IHtmlString GetCropUrl(this HtmlHelper htmlHelper, IPublishedContent mediaItem, int? width = null, int? height = null, string propertyAlias = Constants.Conventions.Media.File, string cropAlias = null, int? quality = null, ImageCropMode? imageCropMode = null, ImageCropAnchor? imageCropAnchor = null, bool preferFocalPoint = false, bool useCropDimensions = false, bool cacheBuster = true, string furtherOptions = null, ImageCropRatioMode? ratioMode = null, bool upScale = true) { return new HtmlString(mediaItem.GetCropUrl(width, height, propertyAlias, cropAlias, quality, imageCropMode, imageCropAnchor, preferFocalPoint, useCropDimensions, cacheBuster, furtherOptions, ratioMode, upScale)); } [Obsolete("Use the UrlHelper.GetCropUrl extension instead")] [EditorBrowsable(EditorBrowsableState.Never)] public static IHtmlString GetCropUrl(this HtmlHelper htmlHelper, string imageUrl, int? width = null, int? height = null, string imageCropperValue = null, string cropAlias = null, int? quality = null, ImageCropMode? imageCropMode = null, ImageCropAnchor? imageCropAnchor = null, bool preferFocalPoint = false, bool useCropDimensions = false, string cacheBusterValue = null, string furtherOptions = null, ImageCropRatioMode? ratioMode = null, bool upScale = true) { return new HtmlString(imageUrl.GetCropUrl(width, height, imageCropperValue, cropAlias, quality, imageCropMode, imageCropAnchor, preferFocalPoint, useCropDimensions, cacheBusterValue, furtherOptions, ratioMode, upScale)); } #endregion #region BeginUmbracoForm /// <summary> /// Used for rendering out the Form for BeginUmbracoForm /// </summary> internal class UmbracoForm : MvcForm { /// <summary> /// Creates an UmbracoForm /// </summary> /// <param name="viewContext"></param> /// <param name="controllerName"></param> /// <param name="controllerAction"></param> /// <param name="area"></param> /// <param name="method"></param> /// <param name="additionalRouteVals"></param> public UmbracoForm( ViewContext viewContext, string controllerName, string controllerAction, string area, FormMethod method, object additionalRouteVals = null) : base(viewContext) { _viewContext = viewContext; _method = method; _encryptedString = UmbracoHelper.CreateEncryptedRouteString(controllerName, controllerAction, area, additionalRouteVals); } private readonly ViewContext _viewContext; private readonly FormMethod _method; private bool _disposed; private readonly string _encryptedString; protected override void Dispose(bool disposing) { if (this._disposed) return; this._disposed = true; //write out the hidden surface form routes _viewContext.Writer.Write("<input name='ufprt' type='hidden' value='" + _encryptedString + "' />"); base.Dispose(disposing); } } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, FormMethod method) { return html.BeginUmbracoForm(action, controllerName, null, new Dictionary<string, object>(), method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName) { return html.BeginUmbracoForm(action, controllerName, null, new Dictionary<string, object>()); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="additionalRouteVals"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, object additionalRouteVals, FormMethod method) { return html.BeginUmbracoForm(action, controllerName, additionalRouteVals, new Dictionary<string, object>(), method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="additionalRouteVals"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, object additionalRouteVals) { return html.BeginUmbracoForm(action, controllerName, additionalRouteVals, new Dictionary<string, object>()); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, object additionalRouteVals, object htmlAttributes, FormMethod method) { return html.BeginUmbracoForm(action, controllerName, additionalRouteVals, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes), method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, object additionalRouteVals, object htmlAttributes) { return html.BeginUmbracoForm(action, controllerName, additionalRouteVals, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, object additionalRouteVals, IDictionary<string, object> htmlAttributes, FormMethod method) { Mandate.ParameterNotNullOrEmpty(action, "action"); Mandate.ParameterNotNullOrEmpty(controllerName, "controllerName"); return html.BeginUmbracoForm(action, controllerName, "", additionalRouteVals, htmlAttributes, method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline against a locally declared controller /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, object additionalRouteVals, IDictionary<string, object> htmlAttributes) { Mandate.ParameterNotNullOrEmpty(action, "action"); Mandate.ParameterNotNullOrEmpty(controllerName, "controllerName"); return html.BeginUmbracoForm(action, controllerName, "", additionalRouteVals, htmlAttributes); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="surfaceType">The surface controller to route to</param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType, FormMethod method) { return html.BeginUmbracoForm(action, surfaceType, null, new Dictionary<string, object>(), method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="surfaceType">The surface controller to route to</param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType) { return html.BeginUmbracoForm(action, surfaceType, null, new Dictionary<string, object>()); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <typeparam name="T"></typeparam> /// <param name="html"></param> /// <param name="action"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action, FormMethod method) where T : SurfaceController { return html.BeginUmbracoForm(action, typeof(T), method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <typeparam name="T"></typeparam> /// <param name="html"></param> /// <param name="action"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action) where T : SurfaceController { return html.BeginUmbracoForm(action, typeof(T)); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="surfaceType">The surface controller to route to</param> /// <param name="additionalRouteVals"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType, object additionalRouteVals, FormMethod method) { return html.BeginUmbracoForm(action, surfaceType, additionalRouteVals, new Dictionary<string, object>(), method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="surfaceType">The surface controller to route to</param> /// <param name="additionalRouteVals"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType, object additionalRouteVals) { return html.BeginUmbracoForm(action, surfaceType, additionalRouteVals, new Dictionary<string, object>()); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <typeparam name="T"></typeparam> /// <param name="html"></param> /// <param name="action"></param> /// <param name="additionalRouteVals"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action, object additionalRouteVals, FormMethod method) where T : SurfaceController { return html.BeginUmbracoForm(action, typeof(T), additionalRouteVals, method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <typeparam name="T"></typeparam> /// <param name="html"></param> /// <param name="action"></param> /// <param name="additionalRouteVals"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action, object additionalRouteVals) where T : SurfaceController { return html.BeginUmbracoForm(action, typeof(T), additionalRouteVals); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="surfaceType">The surface controller to route to</param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType, object additionalRouteVals, object htmlAttributes, FormMethod method) { return html.BeginUmbracoForm(action, surfaceType, additionalRouteVals, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes), method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="surfaceType">The surface controller to route to</param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType, object additionalRouteVals, object htmlAttributes) { return html.BeginUmbracoForm(action, surfaceType, additionalRouteVals, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <typeparam name="T"></typeparam> /// <param name="html"></param> /// <param name="action"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action, object additionalRouteVals, object htmlAttributes, FormMethod method) where T : SurfaceController { return html.BeginUmbracoForm(action, typeof(T), additionalRouteVals, htmlAttributes, method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <typeparam name="T"></typeparam> /// <param name="html"></param> /// <param name="action"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action, object additionalRouteVals, object htmlAttributes) where T : SurfaceController { return html.BeginUmbracoForm(action, typeof(T), additionalRouteVals, htmlAttributes); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="surfaceType">The surface controller to route to</param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType, object additionalRouteVals, IDictionary<string, object> htmlAttributes, FormMethod method) { Mandate.ParameterNotNullOrEmpty(action, "action"); Mandate.ParameterNotNull(surfaceType, "surfaceType"); var area = ""; var surfaceController = SurfaceControllerResolver.Current.RegisteredSurfaceControllers .SingleOrDefault(x => x == surfaceType); if (surfaceController == null) throw new InvalidOperationException("Could not find the surface controller of type " + surfaceType.FullName); var metaData = PluginController.GetMetadata(surfaceController); if (metaData.AreaName.IsNullOrWhiteSpace() == false) { //set the area to the plugin area area = metaData.AreaName; } return html.BeginUmbracoForm(action, metaData.ControllerName, area, additionalRouteVals, htmlAttributes, method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="surfaceType">The surface controller to route to</param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType, object additionalRouteVals, IDictionary<string, object> htmlAttributes) { return html.BeginUmbracoForm(action, surfaceType, additionalRouteVals, htmlAttributes, FormMethod.Post); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <typeparam name="T"></typeparam> /// <param name="html"></param> /// <param name="action"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action, object additionalRouteVals, IDictionary<string, object> htmlAttributes, FormMethod method) where T : SurfaceController { return html.BeginUmbracoForm(action, typeof(T), additionalRouteVals, htmlAttributes, method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <typeparam name="T"></typeparam> /// <param name="html"></param> /// <param name="action"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm<T>(this HtmlHelper html, string action, object additionalRouteVals, IDictionary<string, object> htmlAttributes) where T : SurfaceController { return html.BeginUmbracoForm(action, typeof(T), additionalRouteVals, htmlAttributes); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="area"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, string area, FormMethod method) { return html.BeginUmbracoForm(action, controllerName, area, null, new Dictionary<string, object>(), method); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="area"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, string area) { return html.BeginUmbracoForm(action, controllerName, area, null, new Dictionary<string, object>()); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="area"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <param name="method"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, string area, object additionalRouteVals, IDictionary<string, object> htmlAttributes, FormMethod method) { Mandate.ParameterNotNullOrEmpty(action, "action"); Mandate.ParameterNotNullOrEmpty(controllerName, "controllerName"); var formAction = UmbracoContext.Current.OriginalRequestUrl.PathAndQuery; return html.RenderForm(formAction, method, htmlAttributes, controllerName, action, area, additionalRouteVals); } /// <summary> /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin /// </summary> /// <param name="html"></param> /// <param name="action"></param> /// <param name="controllerName"></param> /// <param name="area"></param> /// <param name="additionalRouteVals"></param> /// <param name="htmlAttributes"></param> /// <returns></returns> public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, string controllerName, string area, object additionalRouteVals, IDictionary<string, object> htmlAttributes) { return html.BeginUmbracoForm(action, controllerName, area, additionalRouteVals, htmlAttributes, FormMethod.Post); } /// <summary> /// This renders out the form for us /// </summary> /// <param name="htmlHelper"></param> /// <param name="formAction"></param> /// <param name="method"></param> /// <param name="htmlAttributes"></param> /// <param name="surfaceController"></param> /// <param name="surfaceAction"></param> /// <param name="area"></param> /// <param name="additionalRouteVals"></param> /// <returns></returns> /// <remarks> /// This code is pretty much the same as the underlying MVC code that writes out the form /// </remarks> private static MvcForm RenderForm(this HtmlHelper htmlHelper, string formAction, FormMethod method, IDictionary<string, object> htmlAttributes, string surfaceController, string surfaceAction, string area, object additionalRouteVals = null) { //ensure that the multipart/form-data is added to the html attributes if (htmlAttributes.ContainsKey("enctype") == false) { htmlAttributes.Add("enctype", "multipart/form-data"); } var tagBuilder = new TagBuilder("form"); tagBuilder.MergeAttributes(htmlAttributes); // action is implicitly generated, so htmlAttributes take precedence. tagBuilder.MergeAttribute("action", formAction); // method is an explicit parameter, so it takes precedence over the htmlAttributes. tagBuilder.MergeAttribute("method", HtmlHelper.GetFormMethodString(method), true); var traditionalJavascriptEnabled = htmlHelper.ViewContext.ClientValidationEnabled && htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled == false; if (traditionalJavascriptEnabled) { // forms must have an ID for client validation tagBuilder.GenerateId("form" + Guid.NewGuid().ToString("N")); } htmlHelper.ViewContext.Writer.Write(tagBuilder.ToString(TagRenderMode.StartTag)); //new UmbracoForm: var theForm = new UmbracoForm(htmlHelper.ViewContext, surfaceController, surfaceAction, area, method, additionalRouteVals); if (traditionalJavascriptEnabled) { htmlHelper.ViewContext.FormContext.FormId = tagBuilder.Attributes["id"]; } return theForm; } #endregion #region Wrap public static HtmlTagWrapper Wrap(this HtmlHelper html, string tag, string innerText, params IHtmlTagWrapper[] children) { var item = html.Wrap(tag, innerText, (object)null); foreach (var child in children) { item.AddChild(child); } return item; } public static HtmlTagWrapper Wrap(this HtmlHelper html, string tag, object inner, object anonymousAttributes, params IHtmlTagWrapper[] children) { string innerText = null; if (inner != null && inner.GetType() != typeof(DynamicNull)) { innerText = string.Format("{0}", inner); } var item = html.Wrap(tag, innerText, anonymousAttributes); foreach (var child in children) { item.AddChild(child); } return item; } public static HtmlTagWrapper Wrap(this HtmlHelper html, string tag, object inner) { string innerText = null; if (inner != null && inner.GetType() != typeof(DynamicNull)) { innerText = string.Format("{0}", inner); } return html.Wrap(tag, innerText, (object)null); } public static HtmlTagWrapper Wrap(this HtmlHelper html, string tag, string innerText, object anonymousAttributes, params IHtmlTagWrapper[] children) { var wrap = new HtmlTagWrapper(tag); if (anonymousAttributes != null) { wrap.ReflectAttributesFromAnonymousType(anonymousAttributes); } if (!string.IsNullOrWhiteSpace(innerText)) { wrap.AddChild(new HtmlTagWrapperTextNode(innerText)); } foreach (var child in children) { wrap.AddChild(child); } return wrap; } public static HtmlTagWrapper Wrap(this HtmlHelper html, bool visible, string tag, string innerText, object anonymousAttributes, params IHtmlTagWrapper[] children) { var item = html.Wrap(tag, innerText, anonymousAttributes, children); item.Visible = visible; return item; } #endregion #region canvasdesigner public static IHtmlString EnableCanvasDesigner(this HtmlHelper html, UrlHelper url, UmbracoContext umbCtx) { return html.EnableCanvasDesigner(url, umbCtx, string.Empty, string.Empty); } public static IHtmlString EnableCanvasDesigner(this HtmlHelper html, UrlHelper url, UmbracoContext umbCtx, string canvasdesignerConfigPath) { return html.EnableCanvasDesigner(url, umbCtx, canvasdesignerConfigPath, string.Empty); } public static IHtmlString EnableCanvasDesigner(this HtmlHelper html, UrlHelper url, UmbracoContext umbCtx, string canvasdesignerConfigPath, string canvasdesignerPalettesPath) { var umbracoPath = url.Content(SystemDirectories.Umbraco); string previewLink = @"<script src=""{0}/lib/jquery/jquery.min.js"" type=""text/javascript""></script>" + @"<script src=""{1}"" type=""text/javascript""></script>" + @"<script src=""{2}"" type=""text/javascript""></script>" + @"<script type=""text/javascript"">var pageId = '{3}'</script>" + @"<script src=""{0}/js/canvasdesigner.front.js"" type=""text/javascript""></script>"; string noPreviewLinks = @"<link href=""{1}"" type=""text/css"" rel=""stylesheet"" data-title=""canvasdesignerCss"" />"; // Get page value int pageId = umbCtx.PublishedContentRequest.UmbracoPage.PageID; string[] path = umbCtx.PublishedContentRequest.UmbracoPage.SplitPath; string result = string.Empty; string cssPath = CanvasDesignerUtility.GetStylesheetPath(path, false); if (umbCtx.InPreviewMode) { canvasdesignerConfigPath = string.IsNullOrEmpty(canvasdesignerConfigPath) == false ? canvasdesignerConfigPath : string.Format("{0}/js/canvasdesigner.config.js", umbracoPath); canvasdesignerPalettesPath = string.IsNullOrEmpty(canvasdesignerPalettesPath) == false ? canvasdesignerPalettesPath : string.Format("{0}/js/canvasdesigner.palettes.js", umbracoPath); if (string.IsNullOrEmpty(cssPath) == false) result = string.Format(noPreviewLinks, cssPath) + Environment.NewLine; result = result + string.Format(previewLink, umbracoPath, canvasdesignerConfigPath, canvasdesignerPalettesPath, pageId); } else { // Get css path for current page if (string.IsNullOrEmpty(cssPath) == false) result = string.Format(noPreviewLinks, cssPath); } return new HtmlString(result); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Signum.Engine.Basics; using Signum.Engine.DynamicQuery; using Signum.Engine.Maps; using Signum.Engine.Operations; using Signum.Entities; using Signum.Entities.DynamicQuery; using Signum.Entities.Mailing; using Signum.Utilities; using Signum.Utilities.ExpressionTrees; using Signum.Entities.Isolation; using Signum.Entities.Templating; using Signum.Engine.UserAssets; using Signum.Engine.Authorization; namespace Signum.Engine.Mailing { public interface IEmailModel { ModifiableEntity UntypedEntity { get; } List<EmailOwnerRecipientData> GetRecipients(); List<Filter> GetFilters(QueryDescription qd); Pagination GetPagination(); List<Order> GetOrders(QueryDescription queryDescription); } public class EmailOwnerRecipientData { public EmailOwnerRecipientData(EmailOwnerData ownerData) { this.OwnerData = ownerData; } public readonly EmailOwnerData OwnerData; public EmailRecipientKind Kind; } public abstract class EmailModel<T> : IEmailModel where T : ModifiableEntity { public EmailModel(T entity) { this.Entity = entity; } public T Entity { get; set; } ModifiableEntity IEmailModel.UntypedEntity { get { return Entity; } } public virtual List<EmailOwnerRecipientData> GetRecipients() { return new List<EmailOwnerRecipientData>(); } protected static List<EmailOwnerRecipientData> SendTo(EmailOwnerData ownerData) { return new List<EmailOwnerRecipientData> { new EmailOwnerRecipientData(ownerData) }; } public virtual List<Filter> GetFilters(QueryDescription qd) { var imp = qd.Columns.SingleEx(a => a.IsEntity).Implementations!.Value; if (imp.IsByAll && typeof(Entity).IsAssignableFrom(typeof(T)) || imp.Types.Contains(typeof(T))) return new List<Filter> { new FilterCondition(QueryUtils.Parse("Entity", qd, 0), FilterOperation.EqualTo, ((Entity)(ModifiableEntity)Entity).ToLite()) }; throw new InvalidOperationException($"Since {typeof(T).Name} is not in {imp}, it's necessary to override ${nameof(GetFilters)} in ${this.GetType().Name}"); } public virtual List<Order> GetOrders(QueryDescription queryDescription) { return new List<Order>(); } public virtual Pagination GetPagination() { return new Pagination.All(); } } public class MultiEntityEmail : EmailModel<MultiEntityModel> { public MultiEntityEmail(MultiEntityModel entity) : base(entity) { } public override List<Filter> GetFilters(QueryDescription qd) { return new List<Filter> { new FilterCondition(QueryUtils.Parse("Entity", qd, 0), FilterOperation.IsIn, this.Entity.Entities.ToList()) }; } } public class QueryEmail : EmailModel<QueryModel> { public QueryEmail(QueryModel entity) : base(entity) { } public override List<Filter> GetFilters(QueryDescription qd) { return this.Entity.Filters; } public override Pagination GetPagination() { return this.Entity.Pagination; } public override List<Order> GetOrders(QueryDescription queryDescription) { return this.Entity.Orders; } } public static class EmailModelLogic { class EmailModelInfo { public object QueryName; public Func<EmailTemplateEntity>? DefaultTemplateConstructor; public EmailModelInfo(object queryName) { QueryName = queryName; } } static ResetLazy<Dictionary<Lite<EmailModelEntity>, List<EmailTemplateEntity>>> EmailModelToTemplates = null!; static Dictionary<Type, EmailModelInfo> registeredModels = new Dictionary<Type, EmailModelInfo>(); static ResetLazy<Dictionary<Type, EmailModelEntity>> typeToEntity = null!; static ResetLazy<Dictionary<EmailModelEntity, Type>> entityToType = null!; public static void Start(SchemaBuilder sb) { if (sb.NotDefined(MethodInfo.GetCurrentMethod())) { sb.Schema.Generating += Schema_Generating; sb.Schema.Synchronizing += Schema_Synchronizing; sb.Include<EmailModelEntity>() .WithQuery(() => se => new { Entity = se, se.Id, se.FullClassName, }); UserAssetsImporter.Register<EmailTemplateEntity>("EmailTemplate", EmailTemplateOperation.Save); new Graph<EmailTemplateEntity>.ConstructFrom<EmailModelEntity>(EmailTemplateOperation.CreateEmailTemplateFromModel) { Construct = (se, _) => CreateDefaultTemplateInternal(se) }.Register(); EmailModelToTemplates = sb.GlobalLazy(() => ( from et in Database.Query<EmailTemplateEntity>() where et.Model != null select new { se = et.Model, et }) .GroupToDictionary(pair => pair.se!.ToLite(), pair => pair.et!), /*CSBUG*/ new InvalidateWith(typeof(EmailModelEntity), typeof(EmailTemplateEntity))); typeToEntity = sb.GlobalLazy(() => { var dbModels = Database.RetrieveAll<EmailModelEntity>(); return EnumerableExtensions.JoinRelaxed( dbModels, registeredModels.Keys, entity => entity.FullClassName, type => type.FullName!, (entity, type) => KeyValuePair.Create(type, entity), "caching " + nameof(EmailModelEntity)) .ToDictionary(); }, new InvalidateWith(typeof(EmailModelEntity))); sb.Schema.Initializing += () => typeToEntity.Load(); entityToType = sb.GlobalLazy(() => typeToEntity.Value.Inverse(), new InvalidateWith(typeof(EmailModelEntity))); } } static readonly string EmailModelReplacementKey = "EmailModel"; static SqlPreCommand? Schema_Synchronizing(Replacements replacements) { Table table = Schema.Current.Table<EmailModelEntity>(); Dictionary<string, EmailModelEntity> should = GenerateEmailModelEntities().ToDictionary(s => s.FullClassName); Dictionary<string, EmailModelEntity> old = Administrator.TryRetrieveAll<EmailModelEntity>(replacements).ToDictionary(c => c.FullClassName); replacements.AskForReplacements( old.Keys.ToHashSet(), should.Keys.ToHashSet(), EmailModelReplacementKey); Dictionary<string, EmailModelEntity> current = replacements.ApplyReplacementsToOld(old, EmailModelReplacementKey); using (replacements.WithReplacedDatabaseName()) return Synchronizer.SynchronizeScript(Spacing.Double, should, current, createNew: (tn, s) => table.InsertSqlSync(s), removeOld: (tn, c) => table.DeleteSqlSync(c, se => se.FullClassName == c.FullClassName), mergeBoth: (tn, s, c) => { var oldClassName = c.FullClassName; c.FullClassName = s.FullClassName; return table.UpdateSqlSync(c, se => se.FullClassName == oldClassName); }); } public static void RegisterEmailModel<T>(Func<EmailTemplateEntity>? defaultTemplateConstructor, object? queryName = null) where T : IEmailModel { RegisterEmailModel(typeof(T), defaultTemplateConstructor, queryName); } public static void RegisterEmailModel(Type model, Func<EmailTemplateEntity>? defaultTemplateConstructor, object? queryName = null) { registeredModels[model] = new EmailModelInfo(queryName ?? GetEntityType(model)) { DefaultTemplateConstructor = defaultTemplateConstructor, }; } public static Type GetEntityType(Type model) { var baseType = model.Follow(a => a.BaseType).FirstOrDefault(b => b.IsInstantiationOf(typeof(EmailModel<>))); if (baseType != null) { return baseType.GetGenericArguments()[0]; } throw new InvalidOperationException("Unknown queryName from {0}, set the argument queryName in RegisterEmailModel".FormatWith(model.TypeName())); } internal static List<EmailModelEntity> GenerateEmailModelEntities() { var list = (from type in registeredModels.Keys select new EmailModelEntity { FullClassName = type.FullName! }).ToList(); return list; } static SqlPreCommand? Schema_Generating() { Table table = Schema.Current.Table<EmailModelEntity>(); return (from ei in GenerateEmailModelEntities() select table.InsertSqlSync(ei)).Combine(Spacing.Simple); } public static EmailModelEntity GetEmailModelEntity<T>() where T : IEmailModel { return ToEmailModelEntity(typeof(T)); } public static EmailModelEntity GetEmailModelEntity(string fullClassName) { return typeToEntity.Value.Where(x => x.Key.FullName == fullClassName).FirstOrDefault().Value; } public static EmailModelEntity ToEmailModelEntity(Type emailModelType) { return typeToEntity.Value.GetOrThrow(emailModelType, "The EmailModel {0} was not registered"); } public static Type ToType(this EmailModelEntity modelEntity) { return entityToType.Value.GetOrThrow(modelEntity, "The EmailModel {0} was not registered"); } public static IEnumerable<EmailMessageEntity> CreateEmailMessage(this IEmailModel emailModel) { if (emailModel.UntypedEntity == null) throw new InvalidOperationException("Entity property not set on EmailModel"); using (IsolationEntity.Override((emailModel.UntypedEntity as Entity)?.TryIsolation())) { var emailModelEntity = ToEmailModelEntity(emailModel.GetType()); var template = GetCurrentTemplate(emailModelEntity, emailModel.UntypedEntity as Entity); return EmailTemplateLogic.CreateEmailMessage(template.ToLite(), model: emailModel); } } public static EmailTemplateEntity GetCurrentTemplate<M>() where M : IEmailModel { var emailModelEntity = ToEmailModelEntity(typeof(M)); return GetCurrentTemplate(emailModelEntity, null); } private static EmailTemplateEntity GetCurrentTemplate(EmailModelEntity emailModelEntity, Entity? entity) { var isAllowed = Schema.Current.GetInMemoryFilter<EmailTemplateEntity>(userInterface: false); var templates = EmailModelToTemplates.Value.TryGetC(emailModelEntity.ToLite()).EmptyIfNull(); templates = templates.Where(isAllowed); if (templates.IsNullOrEmpty()) return CreateDefaultEmailTemplate(emailModelEntity); return templates.Where(t => t.IsApplicable(entity)).SingleEx(() => "Active EmailTemplates for EmailModel {0}".FormatWith(emailModelEntity)); } public static EmailTemplateEntity CreateDefaultEmailTemplate(EmailModelEntity emailModelEntity) { using (AuthLogic.Disable()) using (OperationLogic.AllowSave<EmailTemplateEntity>()) using (Transaction tr = Transaction.ForceNew()) { var template = CreateDefaultTemplateInternal(emailModelEntity); template.Save(); return tr.Commit(template); } } internal static EmailTemplateEntity CreateDefaultTemplateInternal(EmailModelEntity emailModel) { EmailModelInfo info = registeredModels.GetOrThrow(entityToType.Value.GetOrThrow(emailModel)); if (info.DefaultTemplateConstructor == null) throw new InvalidOperationException($"No EmailTemplate for {emailModel} found and DefaultTemplateConstructor = null"); EmailTemplateEntity template = info.DefaultTemplateConstructor.Invoke(); if (template.MasterTemplate == null) template.MasterTemplate = EmailMasterTemplateLogic.GetDefaultMasterTemplate(); if (template.Name == null) template.Name = emailModel.FullClassName; template.Model = emailModel; template.Query = QueryLogic.GetQueryEntity(info.QueryName); template.ParseData(QueryLogic.Queries.QueryDescription(info.QueryName)); return template; } public static void GenerateAllTemplates() { foreach (var emailModelType in registeredModels.Keys) { var emailModelEntity = ToEmailModelEntity(emailModelType); var template = Database.Query<EmailTemplateEntity>().SingleOrDefaultEx(t => t.Model == emailModelEntity); if (template == null) { template = CreateDefaultTemplateInternal(emailModelEntity); using (ExecutionMode.Global()) using (OperationLogic.AllowSave<EmailTemplateEntity>()) template.Save(); } } } public static bool RequiresExtraParameters(EmailModelEntity emailModelEntity) { return GetEntityConstructor(entityToType.Value.GetOrThrow(emailModelEntity)) == null; } internal static bool HasDefaultTemplateConstructor(EmailModelEntity emailModelEntity) { EmailModelInfo info = registeredModels.GetOrThrow(emailModelEntity.ToType()); return info.DefaultTemplateConstructor != null; } public static IEmailModel CreateModel(EmailModelEntity model, ModifiableEntity? entity) { return (IEmailModel)EmailModelLogic.GetEntityConstructor(model.ToType())!.Invoke(new[] { entity }); } public static ConstructorInfo? GetEntityConstructor(Type emailModel) { var entityType = GetEntityType(emailModel); return (from ci in emailModel.GetConstructors() let pi = ci.GetParameters().Only() where pi != null && pi.ParameterType == entityType select ci).SingleOrDefaultEx(); } } }
// Bareplan (c) 2015-17 MIT License <baltasarq@gmail.com> namespace Bareplan.Gui { using System; using System.Drawing; using System.Windows.Forms; using System.Globalization; using System.Diagnostics; using Bareplan.Core; public partial class MainWindow: Form { /// <summary>Fonts are incremented by 2 units each time.</summary> public const int FontStep = 2; /// <summary>Represents the order of columns in the gridview.</summary> public enum ColsIndex { Num, DoW, Date, Kind, Contents }; /// <summary>Tag in the configuration file for the width of the window.</summary> public const string EtqWidth = "width"; /// <summary>Tag in the configuration file for the height of the window.</summary> public const string EtqHeight = "height"; /// <summary>Tag in the configuration file for the locale of the app.</summary> public const string EtqLocale = "locale"; /// <summary>The name of the confif file.</summary> public const string CfgFileName = ".bareplan.cfg"; /// <summary>Strings for the context menu.</summary> public static readonly Func<string>[] GetContextItemCaptions = { () => L10n.Get( L10n.Id.OpAdd ), () => L10n.Get( L10n.Id.OpInsert ), () => L10n.Get( L10n.Id.OpInsertDate ), () => L10n.Get( L10n.Id.OpInsertTask ), () => "-", () => L10n.Get( L10n.Id.OpRemove ), () => L10n.Get( L10n.Id.OpRemoveDate ), () => L10n.Get( L10n.Id.OpRemoveTask ) }; /// <summary>Actions for the context menu.</summary> public static readonly Func<MainWindow, EventHandler>[] GetContextItemActions = { (MainWindow mw) => (sender, e) => mw.OnAdd(), (MainWindow mw) => (sender, e) => mw.OnInsertRow(), (MainWindow mw) => (sender, e) => mw.OnInsertDate(), (MainWindow mw) => (sender, e) => mw.OnInsertTask(), (MainWindow mw) => (sender, e) => {}, (MainWindow mw) => (sender, e) => mw.OnRemove(), (MainWindow mw) => (sender, e) => mw.OnRemoveDate(), (MainWindow mw) => (sender, e) => mw.OnRemoveTask() }; private void BuildContextMenu() { // Menu item's captions if ( this.cntxtMenu == null ) { this.cntxtMenu = new ContextMenu(); this.grdPlanning.ContextMenu = this.cntxtMenu; foreach(Func<string> getContextItemCaption in GetContextItemCaptions) { this.cntxtMenu.MenuItems.Add( getContextItemCaption() ); } } else { for(int i = 0; i < GetContextItemCaptions.Length; ++i) { this.cntxtMenu.MenuItems[ i ].Text = GetContextItemCaptions[ i ](); } } // Menu Item's actions for(int i = 0; i < GetContextItemActions.Length; ++i) { this.cntxtMenu.MenuItems[ i ].Click += GetContextItemActions[ i ]( this ); } } private void BuildCalendarTab(Panel panel) { this.calendar = new MonthCalendar() { Dock = DockStyle.Top, ShowToday = false, ShowTodayCircle = false, MaxSelectionCount = 1, ScrollChange = 1 }; this.calendar.DateSelected += (sender, e) => this.OnCalendarDateChanged(); this.txtDesc = new TextBox() { Dock = DockStyle.Fill, ReadOnly = true, Multiline = true }; panel.Dock = DockStyle.Fill; panel.Controls.Add( this.txtDesc ); panel.Controls.Add( this.calendar ); } private void BuildPlanning() { // Prepare the list of events this.grdPlanning = new DataGridView { AllowUserToResizeRows = false, RowHeadersVisible = false, AutoGenerateColumns = false, MultiSelect = false, AllowUserToAddRows = false, }; this.grdPlanning.RowHeadersDefaultCellStyle.BackColor = Color.LightGray; this.grdPlanning.RowHeadersDefaultCellStyle.ForeColor = Color.Black; this.grdPlanning.ColumnHeadersDefaultCellStyle.BackColor = Color.LightGray; this.grdPlanning.ColumnHeadersDefaultCellStyle.ForeColor = Color.Black; this.planningFont = new Font( this.grdPlanning.Font, FontStyle.Regular ); var textCellTemplate0 = new DataGridViewTextBoxCell(); var textCellTemplate1 = new DataGridViewTextBoxCell(); var textCellTemplate2 = new DataGridViewTextBoxCell(); var textCellTemplate3 = new DataGridViewTextBoxCell(); var textCellTemplate4 = new DataGridViewTextBoxCell(); textCellTemplate0.Style.BackColor = this.grdPlanning.RowHeadersDefaultCellStyle.BackColor; textCellTemplate0.Style.ForeColor = this.grdPlanning.RowHeadersDefaultCellStyle.ForeColor; textCellTemplate0.Style.Font = new Font( this.planningFont, FontStyle.Bold ); textCellTemplate1.Style.BackColor = this.grdPlanning.RowHeadersDefaultCellStyle.BackColor; textCellTemplate1.Style.ForeColor = this.grdPlanning.RowHeadersDefaultCellStyle.ForeColor; textCellTemplate1.Style.Font = new Font( this.planningFont, FontStyle.Bold ); textCellTemplate2.Style.BackColor = Color.Wheat; textCellTemplate2.Style.ForeColor = Color.Black; textCellTemplate3.Style.BackColor = Color.White; textCellTemplate3.Style.ForeColor = Color.Navy; textCellTemplate4.Style.BackColor = Color.White; textCellTemplate4.Style.ForeColor = Color.Navy; var column0 = new DataGridViewTextBoxColumn { HeaderText = "#", Width = 25, ReadOnly = true, CellTemplate = textCellTemplate0, SortMode = DataGridViewColumnSortMode.NotSortable }; var column1 = new DataGridViewTextBoxColumn { HeaderText = "{*}", Width = 25, ReadOnly = true, CellTemplate = textCellTemplate1, SortMode = DataGridViewColumnSortMode.NotSortable }; var column2 = new DataGridViewTextBoxColumn { HeaderText = "Fecha", Width = 75, CellTemplate = textCellTemplate2, SortMode = DataGridViewColumnSortMode.NotSortable }; var column3 = new DataGridViewTextBoxColumn { HeaderText = "Tipo", Width = 250, CellTemplate = textCellTemplate3, SortMode = DataGridViewColumnSortMode.NotSortable }; var column4 = new DataGridViewTextBoxColumn { HeaderText = "Tarea", Width = 250, CellTemplate = textCellTemplate4, SortMode = DataGridViewColumnSortMode.NotSortable }; this.grdPlanning.Columns.AddRange( new DataGridViewColumn[] { column0, column1, column2, column3, column4 } ); this.grdPlanning.CellEndEdit += (object dest, DataGridViewCellEventArgs args) => this.OnRowEdited( args.RowIndex ); this.grdPlanning.Dock = DockStyle.Fill; this.grdPlanning.TabIndex = 3; this.grdPlanning.AllowUserToOrderColumns = false; // Create tabbed control this.tabbed = new TabControl { Dock = DockStyle.Fill, Alignment = TabAlignment.Top }; this.tabbed.ImageList = new ImageList(); this.tabbed.ImageList.Images.AddRange( new Image[]{ this.listIcon, this.calendarViewIcon } ); this.tabbed.ImageList.ImageSize = new Size( 16, 16 ); var tabPlanning = new TabPage { Text = L10n.Get( L10n.Id.HdSession ), ImageIndex = 0 }; var tabCalendar = new TabPage { Text = L10n.Get (L10n.Id.HdDate), ImageIndex = 1 }; tabPlanning.Controls.Add( this.grdPlanning ); var pnlCalendar = new Panel(); this.BuildCalendarTab( pnlCalendar ); tabCalendar.Controls.Add( pnlCalendar ); this.tabbed.TabPages.Add( tabPlanning ); this.tabbed.TabPages.Add( tabCalendar ); this.tabbed.SelectedIndex = 0; this.tabbed.SelectedIndexChanged += (obj, evt) => { this.OnTabChanged(); }; // Layout this.pnlPlanning = new Panel { Dock = DockStyle.Fill }; this.pnlPlanning.SuspendLayout(); this.pnlPlanning.Controls.Add( this.tabbed ); } private void BuildPropertiesContainer() { // Sizes Graphics grf = this.CreateGraphics(); SizeF fontSize = grf.MeasureString( "M", this.defaultFont ); int charSize = (int) fontSize.Width + 5; // Panel this.pnlConfigContainer = new Panel { Dock = DockStyle.Bottom, BackColor = Color.FloralWhite, ForeColor = Color.Black }; this.pnlConfigContainer.SuspendLayout(); // Inner panel var pnlInner = new Panel { Dock = DockStyle.Fill }; pnlInner.SuspendLayout(); var somePadding = new Padding { All = 10 }; pnlInner.Padding = somePadding; // Steps editing var pnlSteps = new Panel { Dock = DockStyle.Left }; pnlSteps.SuspendLayout(); var btBuilder = new Button { Text = "...", Dock = DockStyle.Right, FlatStyle = FlatStyle.Flat }; btBuilder.FlatAppearance.BorderSize = 0; this.lblSteps = new Label { Text = "Pasos:", Dock = DockStyle.Left} ; this.edSteps = new TextBox { Dock = DockStyle.Fill, ReadOnly = true }; // End when pressing enter this.edSteps.KeyDown += (object obj, KeyEventArgs args) => { if ( args.KeyCode == Keys.Enter ) { this.OnPropertiesPanelClosed(); } }; // Opens a GUI helper btBuilder.Click += (sender, e) => { var dlg = new StepsBuilder( this, this.edSteps.Text ); if ( dlg.ShowDialog() == DialogResult.OK ) { this.edSteps.Text = dlg.Result; } }; pnlSteps.Controls.Add( this.edSteps ); pnlSteps.Controls.Add( this.lblSteps ); pnlSteps.Controls.Add( btBuilder ); pnlSteps.ResumeLayout( true ); // Initial date var pnlDate = new Panel { Dock = DockStyle.Right }; pnlDate.SuspendLayout(); this.lblInitialDate = new Label { Text = "Fecha inicial:", Dock = DockStyle.Left }; this.edInitialDate = new DateTimePicker { Dock = DockStyle.Fill, Format = DateTimePickerFormat.Custom, CustomFormat = Locale.CurrentLocale.DateTimeFormat.ShortDatePattern }; pnlDate.Controls.Add( this.edInitialDate ); pnlDate.Controls.Add( this.lblInitialDate ); pnlDate.ResumeLayout( false ); // Button for hiding the panel var btCloseConfigContainer = new Button { Text = "X", Dock = DockStyle.Right, Font = new Font( this.defaultFont, FontStyle.Bold ), Width = charSize * 5, FlatStyle = FlatStyle.Flat }; btCloseConfigContainer.FlatAppearance.BorderSize = 0; btCloseConfigContainer.Click += (object obj, EventArgs args) => { this.OnPropertiesPanelClosed(); }; // Adding controls pnlInner.Controls.Add( pnlSteps ); pnlInner.Controls.Add( pnlDate ); pnlInner.ResumeLayout( true ); this.pnlConfigContainer.Controls.Add( pnlInner ); this.pnlConfigContainer.Controls.Add( btCloseConfigContainer ); this.pnlConfigContainer.ResumeLayout( true ); // Finishing this.pnlPlanning.Controls.Add( this.pnlConfigContainer ); this.pnlConfigContainer.MaximumSize = new Size( int.MaxValue, (int) fontSize.Height * 2 ); btBuilder.Size = btBuilder.MaximumSize = new Size( (int) fontSize.Width * btBuilder.Text.Length, this.edSteps.Height ); lblSteps.Size = new Size( (int) fontSize.Width * this.lblSteps.Text.Length, (int) fontSize.Height * 2 ); this.pnlConfigContainer.Hide(); } private void BuildMainMenu() { // Menu options this.mMain = new MainMenu(); this.mFile = new MenuItem( "Archivo" ); this.mHelp = new MenuItem( "Ayuda" ); this.mEdit = new MenuItem( "Editar" ); this.opQuit = new MenuItem( "Salir" ); this.opAbout = new MenuItem( "Acerca de..." ); this.mView = new MenuItem( "Ver" ); this.opExport = new MenuItem( "Exportar" ); this.opOpen = new MenuItem( "Abrir" ); this.opNew = new MenuItem( "Nuevo" ); this.opSave = new MenuItem( "Guardar" ); this.opSaveAs = new MenuItem( "Guardar como..." ); this.opClose = new MenuItem( "Cerrar" ); this.opAdd = new MenuItem( "Agregar fila" ); this.opProperties = new MenuItem( "Propiedades" ); this.opInsertTask = new MenuItem( "Insertar tarea" ); this.opInsert = new MenuItem( "Insertar fila" ); this.opInsertDate = new MenuItem( "Insertar fecha" ); this.opRemove = new MenuItem( "Eliminar fila" ); this.opRemoveTask = new MenuItem( "Eliminar tarea" ); this.opRemoveDate = new MenuItem( "Eliminar fecha" ); this.opIncFont = new MenuItem( "Incrementar fuente" ); this.opDecFont = new MenuItem( "Decrementar fuente" ); this.opViewCalendar = new MenuItem( "Ver calendario" ); this.opViewSessions = new MenuItem( "Ver sesiones" ); this.opSettings = new MenuItem( "Preferencias" ); // Build the menu this.mMain.MenuItems.Add( this.mFile ); this.mMain.MenuItems.Add( this.mView ); this.mMain.MenuItems.Add( this.mEdit ); this.mMain.MenuItems.Add( this.mHelp ); this.mFile.MenuItems.Add ( this.opNew ); this.mFile.MenuItems.Add ( this.opOpen ); this.mFile.MenuItems.Add ( this.opSave ); this.mFile.MenuItems.Add ( this.opSaveAs ); this.mFile.MenuItems.Add ( this.opExport ); this.mFile.MenuItems.Add ( this.opClose ); this.mFile.MenuItems.Add( this.opQuit ); this.mView.MenuItems.Add( this.opViewSessions ); this.mView.MenuItems.Add( this.opViewCalendar ); this.mView.MenuItems.Add( "-" ); this.mView.MenuItems.Add( this.opDecFont ); this.mView.MenuItems.Add( this.opIncFont ); this.mEdit.MenuItems.Add( this.opAdd ); this.mEdit.MenuItems.Add( "-" ); this.mEdit.MenuItems.Add( this.opInsert ); this.mEdit.MenuItems.Add( this.opInsertTask ); this.mEdit.MenuItems.Add( this.opInsertDate ); this.mEdit.MenuItems.Add( "-" ); this.mEdit.MenuItems.Add( this.opRemove ); this.mEdit.MenuItems.Add( this.opRemoveTask ); this.mEdit.MenuItems.Add( this.opRemoveDate ); this.mEdit.MenuItems.Add( "-" ); this.mEdit.MenuItems.Add( this.opProperties ); this.mEdit.MenuItems.Add( this.opSettings ); this.mHelp.MenuItems.Add( this.opAbout ); // Shortcuts this.opQuit.Shortcut = Shortcut.CtrlQ; this.opNew.Shortcut = Shortcut.CtrlN; this.opOpen.Shortcut = Shortcut.CtrlO; this.opSave.Shortcut = Shortcut.CtrlS; this.opAdd.Shortcut = Shortcut.CtrlIns; this.opProperties.Shortcut = Shortcut.F2; // Events this.opQuit.Click += ( obj, evt ) => this.OnQuit(); this.opAbout.Click += ( obj, evt ) => this.OnAbout(); this.opExport.Click += ( obj, evt ) => this.OnExport(); this.opNew.Click += ( obj, evt ) => this.OnNew(); this.opOpen.Click += ( obj, evt ) => this.OnOpen(); this.opSave.Click += ( obj, evt ) => this.OnSave(); this.opSaveAs.Click += ( obj, evt ) => this.OnSaveAs(); this.opClose.Click += ( obj, evt ) => this.OnClose(); this.opAdd.Click += ( obj, evt ) => this.OnAdd(); this.opProperties.Click += ( obj, evt ) => this.OnProperties(); this.opInsert.Click += (sender, e) => this.OnInsertRow(); this.opInsertTask.Click += ( obj, evt ) => this.OnInsertTask(); this.opInsertDate.Click += (sender, e) => this.OnInsertDate(); this.opRemove.Click += ( obj, evt ) => this.OnRemove(); this.opRemoveTask.Click += ( obj, evt ) => this.OnRemoveTask(); this.opRemoveDate.Click += ( obj, evt ) => this.OnRemoveDate(); this.opIncFont.Click += ( obj, evt ) => this.OnIncFont(); this.opDecFont.Click += ( obj, evt ) => this.OnDecFont(); this.opViewSessions.Click += ( obj, evt ) => this.ChangeToSessionsTab(); this.opViewCalendar.Click += ( obj, evt ) => this.ChangeToCalendarTab(); this.opSettings.Click += ( obj, evt ) => this.OnSettings(); this.Menu = this.mMain; } private void BuildAboutPanel() { // Sizes Graphics grf = this.CreateGraphics(); SizeF fontSize = grf.MeasureString( "M", this.defaultFont ); int charSize = (int) fontSize.Width + 5; // Panel for about info this.pnlAbout = new Panel() { Dock = DockStyle.Bottom, BackColor = Color.LightYellow, ForeColor = Color.Black }; this.pnlAbout.SuspendLayout(); this.lblAbout = new Label { Text = AppInfo.Name + " v" + AppInfo.Version + ", " + AppInfo.Author, Dock = DockStyle.Left, TextAlign = ContentAlignment.MiddleCenter, AutoSize = true, Font = new Font( this.defaultFont, FontStyle.Bold ) }; var btCloseAboutPanel = new Button() { Text = "X", Dock = DockStyle.Right, Width = charSize * 5, FlatStyle = FlatStyle.Flat, Font = new Font( this.defaultFont, FontStyle.Bold ) }; btCloseAboutPanel.FlatAppearance.BorderSize = 0; btCloseAboutPanel.Click += (o, evt) => this.pnlAbout.Hide(); this.pnlAbout.Controls.Add( lblAbout ); this.pnlAbout.Controls.Add( btCloseAboutPanel ); this.pnlAbout.Hide(); this.pnlAbout.MinimumSize = new Size( this.Width, this.lblAbout.Height + 5 ); this.pnlAbout.MaximumSize = new Size( Int32.MaxValue, this.lblAbout.Height + 5 ); this.pnlAbout.ResumeLayout( false ); } private void BuildSettingsPanel() { this.pnlSettings = new TableLayoutPanel { BackColor = Color.White, ForeColor = Color.Black, Dock = DockStyle.Bottom, ColumnCount = 1, GrowStyle = TableLayoutPanelGrowStyle.AddRows }; this.pnlSettings.SuspendLayout(); // Button var btClose = new Button { BackColor = Color.White, Text = "X", Anchor = AnchorStyles.Right, Font = new Font( Font, FontStyle.Bold ), FlatStyle = FlatStyle.Flat }; btClose.FlatAppearance.BorderSize = 0; btClose.Click += (sender, e) => this.ChangeSettings(); this.pnlSettings.Controls.Add( btClose ); // Locale var pnlLocales = new Panel { Margin = new Padding( 5 ), Dock = DockStyle.Top }; this.lblLocales = new Label { Text = L10n.Get( L10n.Id.LblLanguage ), Dock = DockStyle.Left }; this.cbLocales = new ComboBox() { ForeColor = Color.Black, BackColor = Color.White, Dock = DockStyle.Fill, DropDownStyle = ComboBoxStyle.DropDownList, Text = Locale.CurrentLocale.ToString() }; CultureInfo[] locales = CultureInfo.GetCultures( CultureTypes.SpecificCultures ); Array.Sort( locales, ((CultureInfo x, CultureInfo y) => String.Compare( x.ToString(), y.ToString(), false, CultureInfo.InvariantCulture ) ) ); this.cbLocales.Items.Add( "<local>" ); foreach(CultureInfo locale in locales ) { this.cbLocales.Items.Add( locale.NativeName + ": " + locale.ToString() ); } pnlLocales.Controls.Add( this.cbLocales ); pnlLocales.Controls.Add( this.lblLocales ); pnlLocales.MaximumSize = new Size( Int32.MaxValue, cbLocales.Height ); this.pnlSettings.Controls.Add( pnlLocales ); this.pnlSettings.ResumeLayout( false ); this.pnlSettings.Hide(); return; } private void BuildIcons() { try { this.bmpAppIcon = new Bitmap( System.Reflection.Assembly.GetEntryAssembly( ). GetManifestResourceStream( "Bareplan.Res.appIcon.png" ) ); this.addRowIcon = new Bitmap( System.Reflection.Assembly.GetEntryAssembly( ). GetManifestResourceStream( "Bareplan.Res.addIcon.png" ) ); this.calendarViewIcon = new Bitmap( System.Reflection.Assembly.GetEntryAssembly( ). GetManifestResourceStream( "Bareplan.Res.calendarViewIcon.png" ) ); this.exportIcon = new Bitmap( System.Reflection.Assembly.GetEntryAssembly( ). GetManifestResourceStream( "Bareplan.Res.exportIcon.png" ) ); this.listIcon = new Bitmap( System.Reflection.Assembly.GetEntryAssembly( ). GetManifestResourceStream( "Bareplan.Res.listIcon.png" ) ); this.newIcon = new Bitmap( System.Reflection.Assembly.GetEntryAssembly( ). GetManifestResourceStream( "Bareplan.Res.newIcon.png" ) ); this.openIcon = new Bitmap( System.Reflection.Assembly.GetEntryAssembly( ). GetManifestResourceStream( "Bareplan.Res.openIcon.png" ) ); this.propertiesIcon = new Bitmap( System.Reflection.Assembly.GetEntryAssembly( ). GetManifestResourceStream( "Bareplan.Res.propertiesIcon.png" ) ); this.saveIcon = new Bitmap( System.Reflection.Assembly.GetEntryAssembly( ). GetManifestResourceStream( "Bareplan.Res.saveIcon.png" ) ); this.settingsIcon = new Bitmap( System.Reflection.Assembly.GetEntryAssembly( ). GetManifestResourceStream( "Bareplan.Res.settingsIcon.png" ) ); } catch(Exception e) { Debug.WriteLine( "ERROR loading icons: " + e.Message); } return; } private void BuildToolbar() { this.tbBar = new ToolBar(); // Create image list var imgList = new ImageList{ ImageSize = new Size( 24, 24 ) }; imgList.Images.AddRange( new Image[]{ this.newIcon, this.openIcon, this.saveIcon, this.exportIcon, this.addRowIcon, this.propertiesIcon, this.settingsIcon, }); // Buttons this.tbbNew = new ToolBarButton { ImageIndex = 0 }; this.tbbOpen = new ToolBarButton { ImageIndex = 1 }; this.tbbSave = new ToolBarButton { ImageIndex = 2 }; this.tbbExport = new ToolBarButton { ImageIndex = 3 }; this.tbbAddRow = new ToolBarButton { ImageIndex = 4 }; this.tbbProperties = new ToolBarButton { ImageIndex = 5 }; this.tbbSettings = new ToolBarButton { ImageIndex = 6 }; // Triggers this.tbBar.ButtonClick += (object sender, ToolBarButtonClickEventArgs e) => this.OnToolbarButton( e.Button ); // Polishing this.tbBar.ShowToolTips = true; this.tbBar.ImageList = imgList; this.tbBar.Dock = DockStyle.Top; this.tbBar.BorderStyle = BorderStyle.None; this.tbBar.Appearance = ToolBarAppearance.Flat; this.tbBar.Buttons.AddRange( new ToolBarButton[] { this.tbbNew, this.tbbOpen, this.tbbSave, this.tbbExport, this.tbbAddRow, this.tbbProperties, this.tbbSettings }); } private void Build() { this.defaultFont = new Font( System.Drawing.SystemFonts.DefaultFont.FontFamily, 12, FontStyle.Regular ); // Start this.StartPosition = FormStartPosition.CenterScreen; this.SuspendLayout(); // Status bar this.stbStatus = new StatusBar(); this.BuildIcons(); this.BuildToolbar(); this.BuildPlanning(); this.BuildMainMenu(); this.BuildAboutPanel(); this.BuildPropertiesContainer(); this.BuildSettingsPanel(); // Add all to the UI this.Controls.Add( this.pnlPlanning ); this.Controls.Add( this.tbBar ); this.Controls.Add( this.pnlSettings ); this.Controls.Add( this.pnlAbout ); this.Controls.Add( this.stbStatus ); // Apply configuration this.Width = this.CfgWidth; this.Height = this.CfgHeight; this.ChangeUILanguage( Locale.CurrentLocale ); // Polish UI this.Text = AppInfo.Name; this.Icon = Icon.FromHandle( this.bmpAppIcon.GetHicon() ); this.Cursor = Cursors.Arrow; this.MinimumSize = new Size( 620, 460 ); this.Resize += ( obj, args) => this.ResizeWindow(); this.Closed += ( obj, e) => this.OnQuit(); // End this.pnlPlanning.ResumeLayout( false ); this.ResumeLayout( true ); this.ResizeWindow(); return; } /// <summary> /// Resizes the window, also the planning. /// The width of the columns of the planning /// is calculated by using percentages. /// </summary> private void ResizeWindow() { // Get the new measures int width = this.pnlPlanning.ClientRectangle.Width; // Resize the table of events this.grdPlanning.Width = width; this.grdPlanning.Columns[ (int) ColsIndex.Num ].Width = (int) Math.Floor( width *.07 ); // Num this.grdPlanning.Columns[ (int) ColsIndex.DoW ].Width = (int) Math.Floor( width *.07 ); // DoW this.grdPlanning.Columns[ (int) ColsIndex.Date ].Width = (int) Math.Floor( width *.16 ); // Date this.grdPlanning.Columns[ (int) ColsIndex.Kind ].Width = (int) Math.Floor( width *.16 ); // Kind this.grdPlanning.Columns[ (int) ColsIndex.Contents ].Width = (int) Math.Floor( width *.54 ); // Contents } private Bitmap bmpAppIcon; private Bitmap addRowIcon; private Bitmap calendarViewIcon; private Bitmap exportIcon; private Bitmap listIcon; private Bitmap newIcon; private Bitmap openIcon; private Bitmap propertiesIcon; private Bitmap saveIcon; private Bitmap settingsIcon; private ToolBarButton tbbAddRow; private ToolBarButton tbbExport; private ToolBarButton tbbNew; private ToolBarButton tbbOpen; private ToolBarButton tbbProperties; private ToolBarButton tbbSave; private ToolBarButton tbbSettings; private DataGridView grdPlanning; private Panel pnlConfigContainer; private TableLayoutPanel pnlSettings; private StatusBar stbStatus; private Panel pnlAbout; private Panel pnlPlanning; private Label lblLocales; private ComboBox cbLocales; private MonthCalendar calendar; private Label lblAbout; private Label lblInitialDate; private Label lblSteps; private TextBox edSteps; private DateTimePicker edInitialDate; private Font defaultFont; private Font planningFont; private MenuItem opInsertTask; private MenuItem opInsertDate; private MenuItem opInsert; private MenuItem opRemove; private MenuItem opRemoveTask; private MenuItem opRemoveDate; private MenuItem opIncFont; private MenuItem opDecFont; private MenuItem opViewSessions; private MenuItem opViewCalendar; private ToolBar tbBar; private TabControl tabbed; private TextBox txtDesc; private MainMenu mMain; private MenuItem mFile; private MenuItem mEdit; private MenuItem mView; private MenuItem mHelp; private MenuItem opExport; private MenuItem opProperties; private MenuItem opNew; private MenuItem opOpen; private MenuItem opSave; private MenuItem opSaveAs; private MenuItem opClose; private MenuItem opQuit; private MenuItem opAdd; private MenuItem opAbout; private MenuItem opSettings; private ContextMenu cntxtMenu; } }
/* * Created by SharpDevelop. * User: Mejov Andrei <andrei.mejov@gmail.com> * Date: 01.01.2009 * Time: 15:34 * */ using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Messaging; using System.Text; using System.Threading; using System.Runtime.InteropServices; namespace MSMQAdapter { [ComVisible(true)] [ComSourceInterfacesAttribute(typeof(IAdapter))] [ClassInterface(ClassInterfaceType.AutoDual)] [ProgId("MSMQAdapter")] [Guid("0339E962-6744-4844-9408-1A795828CCBE")] public class MSMQAdapter : IAdapter { public static readonly string ReceiveQueueName = "ReceiveQueueName"; public static readonly string SendQueueName = "SendQueueName"; public static readonly string UserName = "UserName"; public static readonly string Password = "Password"; public static readonly string UseZip = "UseZip"; private MessageQueue receiveQueue = null; private MessageQueue sendQueue = null; private MessageQueueTransaction transaction = null; private bool transactionStarted = false; private bool useZipFlag = false; private Dictionary<string, string> parameters = new Dictionary<string, string>(); [ComVisible(false)] public Dictionary<string, string> Parameters { get {return parameters;} } public void SetParameter(string _name, string _value) { parameters.Add(_name, _value); } public void ClearParameters() { parameters.Clear(); } public void SendFile(string _fileName) { using (FileStream fs = new FileStream(_fileName, FileMode.Open)) { using (StreamReader sr = new StreamReader(fs, System.Text.UTF8Encoding.UTF8, true)) { string buf = ""; while (!sr.EndOfStream) { buf += sr.ReadLine(); } Send(buf); } } } public void Send(string _text) { if (sendQueue == null) { throw new Exception("This connector not configured for sending"); } if (!transactionStarted) { Begin(); } if (useZipFlag) { sendQueue.Send(CompressString(_text), transaction); } else { sendQueue.Send(_text, transaction); } } public bool HasMessage() { if (receiveQueue == null) { throw new Exception("This connector not configured for receiving"); } IAsyncResult r = receiveQueue.BeginPeek(); Thread.Sleep(20); return r.IsCompleted; } public string Receive() { if (receiveQueue == null) { throw new Exception("This connector not configured for receiving"); } if (!transactionStarted) { Begin(); } Message message = receiveQueue.Receive(transaction); if (useZipFlag) { return DecompressString((byte[])(message.Body)); } else { return message.Body.ToString(); } } private void ValidateParameters() { if (!((Parameters.ContainsKey(SendQueueName)) || (Parameters.ContainsKey(ReceiveQueueName)))) { throw new Exception("SendQueueName and/or ReceiveQueueName must be set"); } if ((Parameters.ContainsKey(UserName)) && (!Parameters.ContainsKey(Password))) { throw new Exception("Password must not be empty"); } } public void Start() { ValidateParameters(); transaction = new MessageQueueTransaction(); if (MessageQueue.Exists(this.Parameters[ReceiveQueueName])) { receiveQueue = new MessageQueue(this.Parameters[ReceiveQueueName], true); } else { receiveQueue = MessageQueue.Create(this.Parameters[ReceiveQueueName], true); } if (MessageQueue.Exists(this.Parameters[SendQueueName])) { sendQueue = new MessageQueue(this.Parameters[SendQueueName], true); } else { sendQueue = MessageQueue.Create(this.Parameters[SendQueueName], true); } if (Parameters.ContainsKey(UseZip)) { if ( (Parameters[UseZip].Equals("true")) || (Parameters[UseZip].Equals("True")) || (Parameters[UseZip].Equals("1")) ) { useZipFlag = true; sendQueue.Formatter = new BinaryMessageFormatter(); receiveQueue.Formatter = new BinaryMessageFormatter(); } } if (!useZipFlag) { sendQueue.Formatter = new XmlMessageFormatter(new Type[]{typeof(string)}); receiveQueue.Formatter = new XmlMessageFormatter(new Type[]{typeof(string)}); } } public void Stop() { if (transactionStarted) { transaction.Abort(); } receiveQueue.Dispose(); sendQueue.Dispose(); receiveQueue = null; sendQueue = null; useZipFlag = false; } public void Begin() { transaction.Begin(); transactionStarted = true; } public void Commit() { if (transactionStarted) { transaction.Commit(); transactionStarted = false; } } public void Rollback() { if (transactionStarted) { transaction.Abort(); transactionStarted = false; } } public static byte[] CompressString(string _s) { byte[] buf = UTF8Encoding.UTF8.GetBytes(_s); using (MemoryStream ms = new MemoryStream()) { using (DeflateStream ds = new DeflateStream(ms, CompressionMode.Compress)) { ds.Write(buf,0, buf.Length); ds.Close(); return ms.GetBuffer(); } } } public static string DecompressString(byte[] _bytes) { using (MemoryStream ms = new MemoryStream(_bytes)) { using (DeflateStream ds = new DeflateStream(ms, CompressionMode.Decompress)) { using (MemoryStream resStream = new MemoryStream()) { int b = ds.ReadByte(); while (b>0) { resStream.WriteByte((byte)b); b = ds.ReadByte(); } byte[] buf = new byte[resStream.Position]; resStream.Seek(0L, SeekOrigin.Begin); resStream.Read(buf, 0, buf.Length); return new string(UTF8Encoding.UTF8.GetChars(buf)); }//using resStream }//using ds }//using ms } public void Dispose() { Stop(); } } }
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 frmStockList { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmStockList() : base() { FormClosed += frmStockList_FormClosed; KeyPress += frmStockList_KeyPress; KeyDown += frmStockList_KeyDown; //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; private System.Windows.Forms.Button withEventsField_cmdBOM; public System.Windows.Forms.Button cmdBOM { get { return withEventsField_cmdBOM; } set { if (withEventsField_cmdBOM != null) { withEventsField_cmdBOM.Click -= cmdBOM_Click; } withEventsField_cmdBOM = value; if (withEventsField_cmdBOM != null) { withEventsField_cmdBOM.Click += cmdBOM_Click; } } } private System.Windows.Forms.TextBox withEventsField_txtSearch; public System.Windows.Forms.TextBox txtSearch { get { return withEventsField_txtSearch; } set { if (withEventsField_txtSearch != null) { withEventsField_txtSearch.Enter -= txtSearch_Enter; withEventsField_txtSearch.KeyDown -= txtSearch_KeyDown; withEventsField_txtSearch.KeyPress -= txtSearch_KeyPress; } withEventsField_txtSearch = value; if (withEventsField_txtSearch != null) { withEventsField_txtSearch.Enter += txtSearch_Enter; withEventsField_txtSearch.KeyDown += txtSearch_KeyDown; withEventsField_txtSearch.KeyPress += txtSearch_KeyPress; } } } private System.Windows.Forms.Button withEventsField_cmdExit; public System.Windows.Forms.Button cmdExit { get { return withEventsField_cmdExit; } set { if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click -= cmdExit_Click; } withEventsField_cmdExit = value; if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click += cmdExit_Click; } } } private System.Windows.Forms.Button withEventsField_cmdNamespace; public System.Windows.Forms.Button cmdNamespace { get { return withEventsField_cmdNamespace; } set { if (withEventsField_cmdNamespace != null) { withEventsField_cmdNamespace.Click -= cmdNamespace_Click; } withEventsField_cmdNamespace = value; if (withEventsField_cmdNamespace != null) { withEventsField_cmdNamespace.Click += cmdNamespace_Click; } } } private myDataGridView withEventsField_DataList1; public myDataGridView DataList1 { get { return withEventsField_DataList1; } set { if (withEventsField_DataList1 != null) { withEventsField_DataList1.DoubleClick -= DataList1_DblClick; withEventsField_DataList1.KeyPress -= DataList1_KeyPress; } withEventsField_DataList1 = value; if (withEventsField_DataList1 != null) { withEventsField_DataList1.DoubleClick += DataList1_DblClick; withEventsField_DataList1.KeyPress += DataList1_KeyPress; } } } private System.Windows.Forms.TextBox withEventsField_txtBCode; public System.Windows.Forms.TextBox txtBCode { get { return withEventsField_txtBCode; } set { if (withEventsField_txtBCode != null) { withEventsField_txtBCode.Enter -= txtBCode_Enter; withEventsField_txtBCode.KeyDown -= txtBCode_KeyDown; withEventsField_txtBCode.KeyPress -= txtBCode_KeyPress; } withEventsField_txtBCode = value; if (withEventsField_txtBCode != null) { withEventsField_txtBCode.Enter += txtBCode_Enter; withEventsField_txtBCode.KeyDown += txtBCode_KeyDown; withEventsField_txtBCode.KeyPress += txtBCode_KeyPress; } } } public System.Windows.Forms.Label Label1; public System.Windows.Forms.GroupBox Frame1; public System.Windows.Forms.Label lblRecords; public System.Windows.Forms.Label lbl; public System.Windows.Forms.Label lblHeading; //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() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmStockList)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.cmdBOM = new System.Windows.Forms.Button(); this.txtSearch = new System.Windows.Forms.TextBox(); this.cmdExit = new System.Windows.Forms.Button(); this.cmdNamespace = new System.Windows.Forms.Button(); this.DataList1 = new myDataGridView(); this.Frame1 = new System.Windows.Forms.GroupBox(); this.txtBCode = new System.Windows.Forms.TextBox(); this.Label1 = new System.Windows.Forms.Label(); this.lblRecords = new System.Windows.Forms.Label(); this.lbl = new System.Windows.Forms.Label(); this.lblHeading = new System.Windows.Forms.Label(); this.Frame1.SuspendLayout(); this.SuspendLayout(); this.ToolTip1.Active = true; ((System.ComponentModel.ISupportInitialize)this.DataList1).BeginInit(); this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Text = "Select a Stock Item"; this.ClientSize = new System.Drawing.Size(352, 449); this.Location = new System.Drawing.Point(3, 22); this.ControlBox = false; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Enabled = true; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.HelpButton = false; this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Name = "frmStockList"; this.cmdBOM.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdBOM.Text = "&Show Items with Bill of Materials"; this.cmdBOM.Size = new System.Drawing.Size(97, 52); this.cmdBOM.Location = new System.Drawing.Point(250, 96); this.cmdBOM.TabIndex = 10; this.cmdBOM.TabStop = false; this.cmdBOM.BackColor = System.Drawing.SystemColors.Control; this.cmdBOM.CausesValidation = true; this.cmdBOM.Enabled = true; this.cmdBOM.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdBOM.Cursor = System.Windows.Forms.Cursors.Default; this.cmdBOM.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdBOM.Name = "cmdBOM"; this.txtSearch.AutoSize = false; this.txtSearch.Size = new System.Drawing.Size(294, 19); this.txtSearch.Location = new System.Drawing.Point(53, 8); this.txtSearch.TabIndex = 0; this.txtSearch.AcceptsReturn = true; this.txtSearch.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtSearch.BackColor = System.Drawing.SystemColors.Window; this.txtSearch.CausesValidation = true; this.txtSearch.Enabled = true; this.txtSearch.ForeColor = System.Drawing.SystemColors.WindowText; this.txtSearch.HideSelection = true; this.txtSearch.ReadOnly = false; this.txtSearch.MaxLength = 0; this.txtSearch.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtSearch.Multiline = false; this.txtSearch.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtSearch.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtSearch.TabStop = true; this.txtSearch.Visible = true; this.txtSearch.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtSearch.Name = "txtSearch"; this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdExit.Text = "E&xit"; this.cmdExit.Size = new System.Drawing.Size(97, 52); this.cmdExit.Location = new System.Drawing.Point(252, 318); this.cmdExit.TabIndex = 6; this.cmdExit.TabStop = false; this.cmdExit.BackColor = System.Drawing.SystemColors.Control; this.cmdExit.CausesValidation = true; this.cmdExit.Enabled = true; this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default; this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdExit.Name = "cmdExit"; this.cmdNamespace.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdNamespace.Text = "&Filter"; this.cmdNamespace.Size = new System.Drawing.Size(97, 52); this.cmdNamespace.Location = new System.Drawing.Point(250, 32); this.cmdNamespace.TabIndex = 5; this.cmdNamespace.TabStop = false; this.cmdNamespace.BackColor = System.Drawing.SystemColors.Control; this.cmdNamespace.CausesValidation = true; this.cmdNamespace.Enabled = true; this.cmdNamespace.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdNamespace.Cursor = System.Windows.Forms.Cursors.Default; this.cmdNamespace.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdNamespace.Name = "cmdNamespace"; //'DataList1.OcxState = CType(resources.GetObject("'DataList1.OcxState"), System.Windows.Forms.AxHost.State) this.DataList1.Size = new System.Drawing.Size(244, 342); this.DataList1.Location = new System.Drawing.Point(2, 32); this.DataList1.TabIndex = 4; this.DataList1.Name = "DataList1"; this.Frame1.Text = "Search . . ."; this.Frame1.Size = new System.Drawing.Size(345, 73); this.Frame1.Location = new System.Drawing.Point(2, 32); this.Frame1.TabIndex = 1; this.Frame1.Visible = false; this.Frame1.BackColor = System.Drawing.SystemColors.Control; this.Frame1.Enabled = true; this.Frame1.ForeColor = System.Drawing.SystemColors.ControlText; this.Frame1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Frame1.Padding = new System.Windows.Forms.Padding(0); this.Frame1.Name = "Frame1"; this.txtBCode.AutoSize = false; this.txtBCode.Size = new System.Drawing.Size(182, 19); this.txtBCode.Location = new System.Drawing.Point(59, 16); this.txtBCode.TabIndex = 2; this.txtBCode.AcceptsReturn = true; this.txtBCode.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtBCode.BackColor = System.Drawing.SystemColors.Window; this.txtBCode.CausesValidation = true; this.txtBCode.Enabled = true; this.txtBCode.ForeColor = System.Drawing.SystemColors.WindowText; this.txtBCode.HideSelection = true; this.txtBCode.ReadOnly = false; this.txtBCode.MaxLength = 0; this.txtBCode.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtBCode.Multiline = false; this.txtBCode.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtBCode.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtBCode.TabStop = true; this.txtBCode.Visible = true; this.txtBCode.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtBCode.Name = "txtBCode"; this.Label1.TextAlign = System.Drawing.ContentAlignment.TopRight; this.Label1.Text = "&Barcode :"; this.Label1.Size = new System.Drawing.Size(46, 13); this.Label1.Location = new System.Drawing.Point(10, 21); this.Label1.TabIndex = 3; this.Label1.BackColor = System.Drawing.Color.Transparent; this.Label1.Enabled = true; this.Label1.ForeColor = System.Drawing.SystemColors.ControlText; this.Label1.Cursor = System.Windows.Forms.Cursors.Default; this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label1.UseMnemonic = true; this.Label1.Visible = true; this.Label1.AutoSize = true; this.Label1.BorderStyle = System.Windows.Forms.BorderStyle.None; this.Label1.Name = "Label1"; this.lblRecords.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lblRecords.Font = new System.Drawing.Font("Verdana", 9.75f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(0)); this.lblRecords.Size = new System.Drawing.Size(337, 15); this.lblRecords.Location = new System.Drawing.Point(8, 426); this.lblRecords.TabIndex = 9; this.lblRecords.BackColor = System.Drawing.SystemColors.Control; this.lblRecords.Enabled = true; this.lblRecords.ForeColor = System.Drawing.SystemColors.ControlText; this.lblRecords.Cursor = System.Windows.Forms.Cursors.Default; this.lblRecords.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblRecords.UseMnemonic = true; this.lblRecords.Visible = true; this.lblRecords.AutoSize = false; this.lblRecords.BorderStyle = System.Windows.Forms.BorderStyle.None; this.lblRecords.Name = "lblRecords"; this.lbl.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lbl.Text = "&Search :"; this.lbl.Size = new System.Drawing.Size(40, 13); this.lbl.Location = new System.Drawing.Point(8, 8); this.lbl.TabIndex = 8; this.lbl.BackColor = System.Drawing.Color.Transparent; this.lbl.Enabled = true; this.lbl.ForeColor = System.Drawing.SystemColors.ControlText; this.lbl.Cursor = System.Windows.Forms.Cursors.Default; this.lbl.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lbl.UseMnemonic = true; this.lbl.Visible = true; this.lbl.AutoSize = true; this.lbl.BorderStyle = System.Windows.Forms.BorderStyle.None; this.lbl.Name = "lbl"; this.lblHeading.Text = "Using the \"Stock Item Selector\" ....."; this.lblHeading.Size = new System.Drawing.Size(349, 70); this.lblHeading.Location = new System.Drawing.Point(0, 376); this.lblHeading.TabIndex = 7; this.lblHeading.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.lblHeading.BackColor = System.Drawing.SystemColors.Control; this.lblHeading.Enabled = true; this.lblHeading.ForeColor = System.Drawing.SystemColors.ControlText; this.lblHeading.Cursor = System.Windows.Forms.Cursors.Default; this.lblHeading.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblHeading.UseMnemonic = true; this.lblHeading.Visible = true; this.lblHeading.AutoSize = false; this.lblHeading.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblHeading.Name = "lblHeading"; this.Controls.Add(cmdBOM); this.Controls.Add(txtSearch); this.Controls.Add(cmdExit); this.Controls.Add(cmdNamespace); this.Controls.Add(DataList1); this.Controls.Add(Frame1); this.Controls.Add(lblRecords); this.Controls.Add(lbl); this.Controls.Add(lblHeading); this.Frame1.Controls.Add(txtBCode); this.Frame1.Controls.Add(Label1); ((System.ComponentModel.ISupportInitialize)this.DataList1).EndInit(); this.Frame1.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
//////////////////////////////////////////////////////////////////////////////// // The MIT License (MIT) // // Copyright (c) 2021 Tim Stair // // 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.Drawing; using System.Globalization; using System.Reflection; using System.Windows.Forms; namespace Support.UI { public class QueryPanel { // Critical Note: It is important that the user of a QueryPanel set the auto scroll option after all controls are added! protected const int X_CONTROL_BUFFER = 8; protected const int X_BUTTON_WIDTH = 24; protected const int Y_CONTROL_BUFFER = 4; protected const int Y_CONTROL_HEIGHT = 20; // default textbox height protected const int X_NUMERIC_WIDTH = 100; protected int X_LABEL_SIZE = 80; // this one varies based on the overall width private readonly Dictionary<object, QueryItem> m_dictionaryItems; private Control m_zCurrentLayoutControl; // the current panel / tab page to add controls to private bool m_bTabbed; private int m_nTabIndex; // the tab index value of a control protected Dictionary<Control, List<Control>> m_dictionaryLayoutControlControls = new Dictionary<Control, List<Control>>(); protected int m_nButtonHeight; protected TabControl m_zTabControl; protected Panel m_zPanel; public enum ControlType { TextBox, ComboBox, PullDownBox, CheckBox, NumBox, NumBoxSlider, BrowseBox, Label, Button, ListBox, DateTimePicker, None } /// <summary> /// /// </summary> /// <param name="zPanel">Empty Panel to add controls to</param> /// <param name="bTabbed">Flag indicating whether to use a tab control</param> public QueryPanel(Panel zPanel, bool bTabbed) { m_dictionaryItems = new Dictionary<object,QueryItem>(); InitPanel(zPanel, bTabbed); X_LABEL_SIZE = (int)((float)m_zPanel.Width * 0.25); } /// <summary> /// /// </summary> /// <param name="zPanel">Empty Panel to add controls to</param> /// <param name="nLabelWidth">Desired with of labels</param> /// <param name="bTabbed">Flag indicating whether to use a tab control</param> public QueryPanel(Panel zPanel, int nLabelWidth, bool bTabbed) { m_dictionaryItems = new Dictionary<object, QueryItem>(); InitPanel(zPanel, bTabbed); if(0 < nLabelWidth && nLabelWidth < m_zPanel.Width) { X_LABEL_SIZE = nLabelWidth; } } /// <summary> /// /// </summary> /// <param name="zPanel">Panel to setup and configure</param> /// <param name="bTabbed">Flag indicating whether to use a tab control</param> private void InitPanel(Panel zPanel, bool bTabbed) { m_nButtonHeight = new Button().Height; // setup the panel to contain the controls m_zPanel = zPanel ?? new Panel(); m_zPanel.AutoScroll = false; m_zCurrentLayoutControl = m_zPanel; // default to this as the main item if (bTabbed) { m_bTabbed = true; m_zTabControl = new TabControl { Dock = DockStyle.Fill, ClientSize = new Size(0, 0) }; m_zPanel.Controls.Add(m_zTabControl); // The SwitchToTab method is used to add items } // initialize m_zCurrentLayoutControl.Tag = Y_CONTROL_BUFFER; } /// <summary> /// Performs any finalization process related to the controls (intended for use before showing!) /// </summary> public void FinalizeControls() { // add the panel controls after the client size has been set (adding them before displayed an odd issue with control anchor/size) foreach (var zLayoutControl in m_dictionaryLayoutControlControls.Keys) { m_dictionaryLayoutControlControls[zLayoutControl].ForEach(zControl => zLayoutControl.Controls.Add(zControl)); } } /// <summary> /// Adds the control in a pending state to be placed on the panel by FinalizeControls /// </summary> /// <param name="zControl">The control to add</param> private void AddPendingControl(Control zControl) { List<Control> listControls; if (!m_dictionaryLayoutControlControls.TryGetValue(m_zCurrentLayoutControl, out listControls)) { listControls = new List<Control>(); m_dictionaryLayoutControlControls.Add(m_zCurrentLayoutControl, listControls); } listControls.Add(zControl); } /// <summary> /// Adds a label /// </summary> /// <param name="sLabel">Label string</param> /// <param name="nHeight">Label height</param> public Label AddLabel(string sLabel, int nHeight) { Label zLabel = CreateLabel(sLabel); zLabel.Anchor = AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top; zLabel.TextAlign = ContentAlignment.MiddleLeft; zLabel.Size = new Size(m_zCurrentLayoutControl.ClientSize.Width - (X_CONTROL_BUFFER * 2), nHeight); AddToYPosition(zLabel.Height + Y_CONTROL_BUFFER); AddPendingControl(zLabel); return zLabel; } /// <summary> /// Adds vertical spacing /// </summary> /// <param name="nHeight">The amount of space to add.</param> public void AddVerticalSpace(int nHeight) { AddToYPosition(nHeight); } /// <summary> /// Adds a check box with an associated label. /// </summary> /// <param name="sLabel">Label seting</param> /// <param name="bCheckDefault">Default check box state</param> /// <param name="zQueryKey">The query key for requesting the value</param> public CheckBox AddCheckBox(string sLabel, bool bCheckDefault, object zQueryKey) { var zLabel = CreateLabel(sLabel); var zCheck = new CheckBox { Checked = bCheckDefault }; SetupControl(zCheck, zLabel, ControlType.CheckBox, true, zQueryKey); return zCheck; } /// <summary> /// Adds a button /// </summary> /// <param name="sLabel">Text label of the button</param> /// <param name="nDesiredWidth">The desired width of the button</param> /// <param name="eHandler">The event handler to associated with the button</param> /// <param name="zQueryKey">The query key for requesting the value</param> public Button AddButton(string sLabel, int nDesiredWidth, EventHandler eHandler, object zQueryKey) { var zButton = new Button { Text = sLabel }; zButton.Size = new Size(nDesiredWidth, zButton.Height); if (null != eHandler) { zButton.Click += eHandler; } SetupControl(zButton, null, ControlType.Button, false, zQueryKey); return zButton; } /// <summary> /// Adds a NumericUpDown /// </summary> /// <param name="sLabel">Label string</param> /// <param name="dDefault">Default value</param> /// <param name="dMin">Minimum value</param> /// <param name="dMax">Maximum value</param> /// <param name="dIncrement">Increment amout</param> /// <param name="nDecimalPlaces">decimal places</param> /// <param name="zQueryKey">The query key for requesting the value</param> public NumericUpDown AddNumericBox(string sLabel, decimal dDefault, decimal dMin, decimal dMax, decimal dIncrement, int nDecimalPlaces, object zQueryKey) { var zLabel = CreateLabel(sLabel); var zNumeric = new NumericUpDown { Minimum = dMin, Maximum = dMax, Increment = dIncrement, DecimalPlaces = nDecimalPlaces }; if (dMin <= dDefault && dMax >= dDefault) { zNumeric.Value = dDefault; } SetupControl(zNumeric, zLabel, ControlType.NumBox, true, zQueryKey); return zNumeric; } /// <summary> /// Adds a NumericUpDown /// </summary> /// <param name="sLabel">Label string</param> /// <param name="dDefault">Default value</param> /// <param name="dMin">Minimum value</param> /// <param name="dMax">Maximum value</param> /// <param name="zQueryKey">The query key for requesting the value</param> public NumericUpDown AddNumericBox(string sLabel, decimal dDefault, decimal dMin, decimal dMax, object zQueryKey) { return AddNumericBox(sLabel, dDefault, dMin, dMax, 1, 0, zQueryKey); } /// <summary> /// Adds a NumericUpDown with associated slider /// </summary> /// <param name="sLabel">Label string</param> /// <param name="bFloat">Flag indicating whether the values associated are floating point</param> /// <param name="dDefault">Default value</param> /// <param name="dMin">Minimum value</param> /// <param name="dMax">Maximum value</param> /// <param name="zQueryKey">The query key for requesting the value</param> public NumericUpDown AddNumericBoxSlider(string sLabel, bool bFloat, decimal dDefault, decimal dMin, decimal dMax, object zQueryKey) { var zLabel = CreateLabel(sLabel); var zNumeric = new NumericUpDown(); var zTrackBar = new TrackBar(); zNumeric.Minimum = dMin; zNumeric.Maximum = dMax; zNumeric.Increment = 1; zNumeric.Value = dMin; // default this to a valid number... if (bFloat) { int nZeroDecimalPlaces = 3 - (int)Math.Log10(Math.Max(Math.Abs((double)dMin), Math.Abs((double)dMax))); // note the trackbar value is set below using the numeric change event if (0 <= nZeroDecimalPlaces) { zNumeric.Increment = new Decimal( float.Parse("0." + "1".PadLeft(1 + nZeroDecimalPlaces, '0'), NumberStyles.Any, CultureInfo.InvariantCulture)); zNumeric.DecimalPlaces = nZeroDecimalPlaces + 1; } else { zNumeric.Increment = 1; zNumeric.DecimalPlaces = 0; } zTrackBar.Minimum = 0; zTrackBar.Maximum = ((int)(dMax / zNumeric.Increment)) - ((int)(dMin / zNumeric.Increment)); } else { zTrackBar.Minimum = (int)dMin; zTrackBar.Maximum = (int)dMax; zTrackBar.Value = (int)dDefault; } if (dDefault >= dMin && dDefault <= dMax) { zNumeric.Value = dDefault; } zNumeric.Location = new Point(GetLabelWidth(zLabel) + (X_CONTROL_BUFFER), GetYPosition()); zNumeric.Size = new Size(X_NUMERIC_WIDTH, Y_CONTROL_HEIGHT); zNumeric.Tag = zTrackBar; // the tag of the numeric is the trackbar zNumeric.Anchor = AnchorStyles.Left | AnchorStyles.Top; zNumeric.ValueChanged += numeric_ValueChanged; zLabel.Height = zNumeric.Height; // adjust the height of the label to match the control to its right zTrackBar.Location = new Point(zNumeric.Width + zNumeric.Location.X + X_CONTROL_BUFFER, GetYPosition()); zTrackBar.Size = new Size(m_zPanel.ClientSize.Width - (zTrackBar.Location.X + X_CONTROL_BUFFER), Y_CONTROL_HEIGHT); zTrackBar.Tag = zNumeric; // the tag of the trackbar is the numeric (value changes will affect the numeric) zTrackBar.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top; zTrackBar.ValueChanged += numericSlider_ValueChanged; if (bFloat) { // set the trackbar value using the change event numeric_ValueChanged(zNumeric, new EventArgs()); } AddPendingControl(zLabel); AddPendingControl(zNumeric); AddPendingControl(zTrackBar); AddToYPosition(zTrackBar.Size.Height + Y_CONTROL_BUFFER); var qItem = new QueryItem(ControlType.NumBoxSlider, zNumeric, zTrackBar, ref m_nTabIndex); // the tag of the QueryItem is the trackbar (used when disabling the QueryItem) m_dictionaryItems.Add(zQueryKey, qItem); return zNumeric; } /// <summary> /// Adds a TextBox /// </summary> /// <param name="sLabel">Label string</param> /// <param name="sDefaultValue">Default text</param> /// <param name="bPassword">Flag indicating that this is a password textbox</param> /// <param name="zQueryKey">The query key for requesting the value</param> public TextBox AddTextBox(string sLabel, string sDefaultValue, bool bPassword, object zQueryKey) { return AddTextBox(sLabel, sDefaultValue, false, bPassword, 0, zQueryKey); } /// <summary> /// Adds a multiline TextBox /// </summary> /// <param name="sLabel">Label string</param> /// <param name="sDefaultValue">Default text</param> /// <param name="nHeight">Height of the TextBox</param> /// <param name="zQueryKey">The query key for requesting the value</param> public TextBox AddMultiLineTextBox(string sLabel, string sDefaultValue, int nHeight, object zQueryKey) { return AddTextBox(sLabel, sDefaultValue, true, false, nHeight, zQueryKey); } /// <summary> /// Adds a TextBox /// </summary> /// <param name="sLabel">Label string</param> /// <param name="sDefaultValue">Default text</param> /// <param name="bMultiLine">Flag indicating whether this is a multi line textbox</param> /// <param name="bPassword">Flag indicating that this is a password textbox</param> /// <param name="nHeight">Height of the text box. This only applies to those with bMultiLine set to true</param> /// <param name="zQueryKey">The query key for requesting the value</param> private TextBox AddTextBox(string sLabel, string sDefaultValue, bool bMultiLine, bool bPassword, int nHeight, object zQueryKey) { var zLabel = CreateLabel(sLabel); var zText = new TextBox(); if (bPassword) { zText.PasswordChar = 'x'; } zText.Multiline = bMultiLine; zText.Text = sDefaultValue; if(bMultiLine) { zText.AcceptsReturn = true; zText.Size = new Size(m_zCurrentLayoutControl.ClientSize.Width - ((X_CONTROL_BUFFER * 2) + GetLabelWidth(zLabel)), nHeight); zText.ScrollBars = ScrollBars.Both; zText.WordWrap = false; } else { zText.Size = new Size(m_zCurrentLayoutControl.ClientSize.Width - ((X_CONTROL_BUFFER * 2) + GetLabelWidth(zLabel)), Y_CONTROL_HEIGHT); } SetupControl(zText, zLabel, ControlType.TextBox, false, zQueryKey); return zText; } /// <summary> /// Adds a ComboBox /// </summary> /// <param name="sLabel">Label string</param> /// <param name="arrayEntries">Array of strings to be used in the combo box</param> /// <param name="nDefaultIndex">Default index of the combo box</param> /// <param name="zQueryKey">The query key for requesting the value</param> public ComboBox AddComboBox(string sLabel, string[] arrayEntries, int nDefaultIndex, object zQueryKey) { return AddComboBox(sLabel, arrayEntries, nDefaultIndex, false, zQueryKey); } /// <summary> /// Adds a ComboBox with the pulldownlist style. /// </summary> /// <param name="sLabel">Label string</param> /// <param name="arrayEntries">Array of strings to be used in the combo box</param> /// <param name="nDefaultIndex">Default index of the combo box</param> /// <param name="zQueryKey">The query key for requesting the value</param> public ComboBox AddPullDownBox(string sLabel, string[] arrayEntries, int nDefaultIndex, object zQueryKey) { return AddComboBox(sLabel, arrayEntries, nDefaultIndex, true, zQueryKey); } /// <summary> /// Adds a combo box with the items specified (based on the type specified) /// </summary> /// <param name="sLabel">Label string</param> /// <param name="arrayEntries">Array of strings to be used in the combo box</param> /// <param name="nDefaultIndex">Default index of the combo box</param> /// <param name="bPulldown">Flag indicating whether this is a pulldownlist or not</param> /// <param name="zQueryKey">The query key for requesting the value</param> private ComboBox AddComboBox(string sLabel, string[] arrayEntries, int nDefaultIndex, bool bPulldown, object zQueryKey) { var zLabel = CreateLabel(sLabel); var zCombo = new ComboBox(); if (null != arrayEntries) { foreach (var entry in arrayEntries) { zCombo.Items.Add(entry); } if (zCombo.Items.Count > nDefaultIndex) { zCombo.SelectedIndex = nDefaultIndex; } else if (0 < zCombo.Items.Count) { zCombo.SelectedIndex = 0; } } if(bPulldown) { zCombo.DropDownStyle = ComboBoxStyle.DropDownList; SetupControl(zCombo, zLabel, ControlType.PullDownBox, true, zQueryKey); } else { zCombo.DropDownStyle = ComboBoxStyle.DropDown; SetupControl(zCombo, zLabel, ControlType.ComboBox, true, zQueryKey); } return zCombo; } /// <summary> /// Adds a ListBox with the specified items and selected items /// </summary> /// <param name="sLabel">Label string</param> /// <param name="arrayEntries">Array of strings as entries</param> /// <param name="arraySelected">Array of indicies to select</param> /// <param name="bMultiSelect">Flag indicating whether multiple items can be selected</param> /// <param name="nHeight">The desired height of the ListBox</param> /// <param name="zQueryKey">The query key for requesting the value</param> public ListBox AddListBox(string sLabel, string[] arrayEntries, int[] arraySelected, bool bMultiSelect, int nHeight, object zQueryKey) { var zLabel = CreateLabel(sLabel); var zListBox = new ListBox { SelectionMode = bMultiSelect ? SelectionMode.MultiSimple : SelectionMode.One }; if (null != arrayEntries) { foreach (var sEntry in arrayEntries) { zListBox.Items.Add(sEntry); } if (null != arraySelected) { foreach (var nIndex in arraySelected) { if ((-1 < nIndex) && (nIndex < zListBox.Items.Count)) { zListBox.SelectedIndex = nIndex; } } } } zListBox.Height = nHeight; SetupControl(zListBox, zLabel, ControlType.ListBox, true, zQueryKey); return zListBox; } /// <summary> /// Adds a DateTime picker field /// </summary> /// <param name="sLabel">Label string</param> /// <param name="eFormat">DateTimePickerFormat to control the visual component</param> /// <param name="dtValue">The default date time value</param> /// <param name="zQueryKey">The query key for requesting the value</param> /// <returns></returns> public DateTimePicker AddDateTimePicker(string sLabel, DateTimePickerFormat eFormat, DateTime dtValue, object zQueryKey) { var zLabel = CreateLabel(sLabel); var zPicker = new DateTimePicker { Format = eFormat, Value = dtValue }; switch (eFormat) { case DateTimePickerFormat.Time: zPicker.ShowUpDown = true; break; } SetupControl(zPicker, zLabel, ControlType.DateTimePicker, true, zQueryKey); return zPicker; } /// <summary> /// Support method to setup the control location/size. This method also adds the control to the form. /// </summary> /// <param name="zControl">Control to configure</param> /// <param name="zLabel">Label Control associated with the Control</param> /// <param name="eType">ControlType</param> /// <param name="bApplySize">Apply size based on form flag</param> /// <param name="zQueryKey">The query key for requesting the value</param> private void SetupControl(Control zControl, Label zLabel, ControlType eType, bool bApplySize, object zQueryKey) { if (null != zLabel) { if (bApplySize) { zControl.Size = new Size((m_zCurrentLayoutControl.ClientSize.Width - GetLabelWidth(zLabel)) - (X_CONTROL_BUFFER * 2), zControl.Size.Height); } zControl.Location = new Point(zLabel.Location.X + GetLabelWidth(zLabel), GetYPosition()); zLabel.Height = zControl.Height; AddPendingControl(zLabel); AddToYPosition(Math.Max(zLabel.Height, zControl.Height) + Y_CONTROL_BUFFER); } else { zControl.Location = new Point((m_zCurrentLayoutControl.ClientSize.Width - zControl.Width) - X_CONTROL_BUFFER, GetYPosition()); AddToYPosition(zControl.Height + Y_CONTROL_BUFFER); } zControl.Anchor = AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top; AddPendingControl(zControl); var qItem = new QueryItem(eType, zControl, ref m_nTabIndex); m_dictionaryItems.Add(zQueryKey, qItem); } /// <summary> /// Adds a folder browser component /// </summary> /// <param name="sLabel">Label string</param> /// <param name="sDefault">Default string</param> /// <param name="zQueryKey">The query key for requesting the value</param> public TextBox AddFolderBrowseBox(string sLabel, string sDefault, object zQueryKey) { return AddBrowseBox(sLabel, sDefault, null, zQueryKey); } /// <summary> /// Adds a file browser component. /// </summary> /// <param name="sLabel">Label string</param> /// <param name="sDefault">Default string</param> /// <param name="sFilter">File filter (standard format for OpenFileDialog), string.empty for default *.*</param> /// <param name="zQueryKey">The query key for requesting the value</param> public TextBox AddFileBrowseBox(string sLabel, string sDefault, string sFilter, object zQueryKey) { return AddBrowseBox(sLabel, sDefault, sFilter, zQueryKey); } /// <summary> /// Adds a browse component (button/textbox/label) /// </summary> /// <param name="sLabel">Label for the component</param> /// <param name="sDefault">Default value</param> /// <param name="sFilter">File filter (applies to file browsing only)</param> /// <param name="zQueryKey">The query key for requesting the value</param> private TextBox AddBrowseBox(string sLabel, string sDefault, string sFilter, object zQueryKey) { var zLabel = CreateLabel(sLabel); var zButton = new Button(); var zTextLocation = new Point(GetLabelWidth(zLabel) + (X_CONTROL_BUFFER), GetYPosition()); var zText = new TextBox { Text = sDefault, Location = zTextLocation, Size = new Size( m_zCurrentLayoutControl.ClientSize.Width - (zTextLocation.X + X_BUTTON_WIDTH + (X_CONTROL_BUFFER * 2)), Y_CONTROL_HEIGHT), Anchor = AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top }; if (null != sFilter) { zText.Tag = 0 != sFilter.Length ? sFilter : "All files (*.*)|*.*"; } zLabel.Height = zText.Height; // adjust the height of the label to match the control to its right zButton.Text = "..."; zButton.Size = new Size(X_BUTTON_WIDTH, Y_CONTROL_HEIGHT); zButton.Location = new Point(m_zCurrentLayoutControl.ClientSize.Width - (zButton.Size.Width + X_CONTROL_BUFFER), GetYPosition()); zButton.Tag = zText; // the tag of the button is the textbox zButton.Anchor = AnchorStyles.Right | AnchorStyles.Top; zButton.Click += zButton_Click; AddPendingControl(zLabel); AddPendingControl(zText); AddPendingControl(zButton); AddToYPosition(zText.Size.Height + Y_CONTROL_BUFFER); var qItem = new QueryItem(ControlType.BrowseBox, zText, zButton, ref m_nTabIndex); // the tag of the QueryItem is the button (used when disabling the QueryItem) m_dictionaryItems.Add(zQueryKey, qItem); return zText; } /// <summary> /// Adds a browse component (button/textbox/label) /// </summary> /// <param name="sLabel">Label for the component</param> /// <param name="sDefault">Default value</param> /// <param name="actionBrowseClicked">Function that returns the form to show (or null if it should not)</param> /// <param name="actionSelect">Action to take with the dialog and TextBox (if the result is OK)</param> /// <param name="zQueryKey">The query key for requesting the value</param> public TextBox AddSelectorBox<T>(string sLabel, string sDefault, Func<T> actionBrowseClicked, Action<T, TextBox> actionSelect, object zQueryKey) where T : Form { var zLabel = CreateLabel(sLabel); var zButton = new Button(); var zTextLocation = new Point(GetLabelWidth(zLabel) + (X_CONTROL_BUFFER), GetYPosition()); var zText = new TextBox { Text = sDefault, Location = zTextLocation, Size = new Size( m_zCurrentLayoutControl.ClientSize.Width - (zTextLocation.X + X_BUTTON_WIDTH + (X_CONTROL_BUFFER * 2)), Y_CONTROL_HEIGHT), Anchor = AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top }; zLabel.Height = zText.Height; // adjust the height of the label to match the control to its right zButton.Text = "..."; zButton.Size = new Size(X_BUTTON_WIDTH, Y_CONTROL_HEIGHT); zButton.Location = new Point(m_zCurrentLayoutControl.ClientSize.Width - (zButton.Size.Width + X_CONTROL_BUFFER), GetYPosition()); zButton.Tag = zText; // the tag of the button is the textbox zButton.Anchor = AnchorStyles.Right | AnchorStyles.Top; zButton.Click += (sender, args) => { var zDialog = actionBrowseClicked(); if (null == zDialog) { return; } if (DialogResult.OK == zDialog.ShowDialog(this.m_zPanel)) { actionSelect(zDialog, zText); } }; AddPendingControl(zLabel); AddPendingControl(zText); AddPendingControl(zButton); AddToYPosition(zText.Size.Height + Y_CONTROL_BUFFER); var qItem = new QueryItem(ControlType.BrowseBox, zText, zButton, ref m_nTabIndex); // the tag of the QueryItem is the button (used when disabling the QueryItem) m_dictionaryItems.Add(zQueryKey, qItem); return zText; } /// <summary> /// Created a label based on the current y position /// </summary> /// <param name="sLabel">The Label string</param> /// <returns></returns> private Label CreateLabel(string sLabel) { var zLabel = new Label(); if(null != sLabel) { zLabel.Text = sLabel; zLabel.TextAlign = ContentAlignment.MiddleRight; zLabel.Location = new Point(X_CONTROL_BUFFER, GetYPosition()); zLabel.Size = new Size(X_LABEL_SIZE, Y_CONTROL_HEIGHT); } else { zLabel.Location = new Point(X_CONTROL_BUFFER, GetYPosition()); zLabel.Size = new Size(0, Y_CONTROL_HEIGHT); } return zLabel; } /// <summary> /// Changes to the tab specified and creates it if necessary /// </summary> /// <param name="sTabName">Name of the tab to change to</param> public void ChangeToTab(string sTabName) { AddTab(sTabName); } /// <summary> /// Creates a Tab /// </summary> /// <param name="sTabName">Name of the tab to create</param> /// <returns></returns> public TabPage AddTab(string sTabName) { if (!m_bTabbed) { throw new Exception("QueryPanel: Attempted to add tab on non-tabbed QueryPanel."); } if (m_zTabControl.TabPages.ContainsKey(sTabName)) { TabPage zPage = m_zTabControl.TabPages[sTabName]; m_zCurrentLayoutControl = zPage; return zPage; } else { m_zTabControl.TabPages.Add(sTabName, sTabName); var zPage = m_zTabControl.TabPages[sTabName]; zPage.Tag = Y_CONTROL_BUFFER; // stores the current Y Position zPage.AutoScroll = true; zPage.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top; zPage.Dock = DockStyle.Fill; m_zCurrentLayoutControl = zPage; return zPage; } } /// <summary> /// Adds the specified control to be enabled when the given control is enabled. /// </summary> /// <param name="zQueryKey">The parent control to base the enable state on</param> /// <param name="zQueryKeyEnable">The control to enable/disable based on the parent control state</param> /// <returns>true on success, false otherwise</returns> public bool AddEnableControl(object zQueryKey, object zQueryKeyEnable) { QueryItem zQueryItem, zQueryItemEnable; if (m_dictionaryItems.TryGetValue(zQueryKey, out zQueryItem) && m_dictionaryItems.TryGetValue(zQueryKeyEnable, out zQueryItemEnable)) { (zQueryItem).AddEnableControl(zQueryItemEnable); return true; } return false; } /// <summary> /// Adds the specified controls to be enabled when the given control is enabled. /// </summary> /// <param name="zQueryKey">The parent control to base the enable state on</param> /// <param name="arrayQueryKeyEnable">string[] of controls to enable/disable based on the parent control state</param> /// <returns>true on success, false otherwise</returns> public bool AddEnableControls(object zQueryKey, object[] arrayQueryKeyEnable) { var bRet = true; foreach(var zKey in arrayQueryKeyEnable) { bRet &= AddEnableControl(zQueryKey, zKey); } return bRet; } /// <summary> /// This gets the width of the label + the control buffer (or 0 if the label is empty) /// </summary> /// <param name="zLabel"></param> /// <returns></returns> private int GetLabelWidth(Label zLabel) { return (zLabel.Width == 0) ? 0 : zLabel.Width + X_CONTROL_BUFFER; } public static void SetupScrollState(ScrollableControl scrollableControl) { Type scrollableControlType = typeof(ScrollableControl); MethodInfo setScrollStateMethod = scrollableControlType.GetMethod("SetScrollState", BindingFlags.NonPublic | BindingFlags.Instance); setScrollStateMethod.Invoke(scrollableControl, new object[] { 0x10 /*ScrollableControl.ScrollStateFullDrag*/, true }); } #region Value Getters /// <summary> /// Gets the control associated with the query key /// </summary> /// <param name="zQueryKey">The query key for requesting the value</param> /// <returns>The control associated with the query key</returns> public Control GetControl(object zQueryKey) { var zItem = GetQueryItem(zQueryKey); if(null != zItem) { return zItem.QueryControl; } ThrowBadQueryException(); return null; } /// <summary> /// Gets the state of the specified check box /// </summary> /// <param name="zQueryKey">The query key for requesting the value</param> /// <returns></returns> public bool GetBool(object zQueryKey) { var zItem = GetQueryItem(zQueryKey); if(null != zItem) { if(ControlType.CheckBox == zItem.Type) { return ((CheckBox)zItem.QueryControl).Checked; } ThrowWrongTypeException(); } return false; } /// <summary> /// Gets the index of the specified combo box /// </summary> /// <param name="zQueryKey">The query key for requesting the value</param> /// <returns></returns> public int GetIndex(object zQueryKey) { var zItem = GetQueryItem(zQueryKey); if(null != zItem) { switch(zItem.Type) { case ControlType.PullDownBox: case ControlType.ComboBox: return ((ComboBox)zItem.QueryControl).SelectedIndex; case ControlType.ListBox: return ((ListBox)zItem.QueryControl).SelectedIndex; } ThrowWrongTypeException(); } return 0; } /// <summary> /// Gets the selected indices of the given control /// </summary> /// <param name="zQueryKey">The query key for requesting the value</param> /// <returns>Array of selected indices, NULL if none are selected</returns> public int[] GetIndices(object zQueryKey) { var zItem = GetQueryItem(zQueryKey); if (null != zItem) { switch (zItem.Type) { case ControlType.ListBox: var zListBox = (ListBox)zItem.QueryControl; var arrayItems = new int[zListBox.SelectedIndices.Count]; for (var nIdx = 0; nIdx < arrayItems.Length; nIdx++) { arrayItems[nIdx] = zListBox.SelectedIndices[nIdx]; } return arrayItems; } ThrowWrongTypeException(); } return null; } /// <summary> /// Gets the string value of the specified control /// </summary> /// <param name="zQueryKey">The query key for requesting the value</param> /// <returns></returns> public string GetString(object zQueryKey) { var zItem = GetQueryItem(zQueryKey); if(null != zItem) { switch(zItem.Type) { case ControlType.BrowseBox: case ControlType.PullDownBox: case ControlType.ComboBox: case ControlType.TextBox: return zItem.QueryControl.Text; case ControlType.ListBox: return (string)((ListBox)zItem.QueryControl).SelectedItem; case ControlType.NumBox: return ((NumericUpDown)zItem.QueryControl).Value.ToString(CultureInfo.CurrentCulture); } ThrowWrongTypeException(); } return string.Empty; } /// <summary> /// Gets the selected strings of the control /// </summary> /// <param name="zQueryKey">The query key for requesting the value</param> /// <returns>Array of selected strings, or NULL if none are selected</returns> public string[] GetStrings(object zQueryKey) { var zItem = GetQueryItem(zQueryKey); if (null != zItem) { switch (zItem.Type) { case ControlType.ListBox: var zListBox = (ListBox)zItem.QueryControl; var arrayItems = new string[zListBox.SelectedItems.Count]; for (var nIdx = 0; nIdx < arrayItems.Length; nIdx++) { arrayItems[nIdx] = (string)zListBox.SelectedItems[nIdx]; } return arrayItems; } ThrowWrongTypeException(); } return null; } /// <summary> /// /// </summary> /// <param name="zQueryKey">The query key for requesting the value</param> /// <returns></returns> public decimal GetDecimal(object zQueryKey) { var zItem = GetQueryItem(zQueryKey); if(null != zItem) { switch(zItem.Type) { case ControlType.NumBox: case ControlType.NumBoxSlider: return ((NumericUpDown)zItem.QueryControl).Value; } ThrowWrongTypeException(); } return 0; } /// <summary> /// Returns the DateTime of the specified control. /// </summary> /// <param name="zQueryKey">The query key for requesting the value</param> /// <returns></returns> public DateTime GetDateTime(object zQueryKey) { var zItem = GetQueryItem(zQueryKey); if (null != zItem) { switch (zItem.Type) { case ControlType.DateTimePicker: return ((DateTimePicker)zItem.QueryControl).Value; } ThrowWrongTypeException(); } return DateTime.Now; } /// <summary> /// /// </summary> /// <param name="zQueryKey">The query key for requesting the value</param> /// <returns></returns> private QueryItem GetQueryItem(object zQueryKey) { QueryItem zQueryItem; if (!m_dictionaryItems.TryGetValue(zQueryKey, out zQueryItem)) { ThrowBadQueryException(); } return zQueryItem; } /// <summary> /// Used to throw a general exception when the wrong type is queried /// </summary> private void ThrowWrongTypeException() { throw new Exception("QueryDialog: Incorrect type for specified return."); } /// <summary> /// Used to throw a general exception when the query key specified is wrong /// </summary> private void ThrowBadQueryException() { throw new Exception("QueryDialog: Invalid Query Key."); } /// <summary> /// Class representing an entry/item on the dialog /// </summary> protected class QueryItem { private ControlType m_eControlType = ControlType.None; private Control m_zControl; private readonly List<QueryItem> m_listEnableControls = new List<QueryItem>(); public object Tag; // always good to have an extra object reference just in case... public ControlType Type => m_eControlType; public Control QueryControl => m_zControl; /// <summary> /// Constructor /// </summary> /// <param name="eControlType">The ControlType to create</param> /// <param name="zControl">The associated control</param> /// <param name="nTabIndex"></param> public QueryItem(ControlType eControlType, Control zControl, ref int nTabIndex) { ConfigureQueryItem(eControlType, zControl, null, ref nTabIndex); } /// <summary> /// Constructor /// </summary> /// <param name="eControlType">The ControlType to create</param> /// <param name="zControl">The associated control</param> /// <param name="zTagControl">The Tag control of the query item</param> /// <param name="nTabIndex"></param> public QueryItem(ControlType eControlType, Control zControl, Control zTagControl, ref int nTabIndex) { ConfigureQueryItem(eControlType, zControl, zTagControl, ref nTabIndex); } private void ConfigureQueryItem(ControlType eControlType, Control zControl, Control zTagControl, ref int nTabIndex) { Tag = zTagControl; m_eControlType = eControlType; m_zControl = zControl; m_zControl.TabIndex = nTabIndex++; switch (eControlType) { case ControlType.TextBox: case ControlType.ComboBox: zControl.TextChanged += QueryItem_TextChanged; break; case ControlType.CheckBox: ((CheckBox)zControl).CheckedChanged += QueryItem_CheckedChanged; break; case ControlType.BrowseBox: zControl.TextChanged += QueryItem_TextChanged; zTagControl.TabIndex = nTabIndex++; break; case ControlType.NumBoxSlider: zTagControl.TabIndex = nTabIndex++; break; } } /// <summary> /// Adds an enable control state for the specified item /// </summary> /// <param name="zItem"></param> public void AddEnableControl(QueryItem zItem) { if (!m_listEnableControls.Contains(zItem)) { m_listEnableControls.Add(zItem); } } private void QueryItem_TextChanged(object sender, EventArgs e) { UpdateEnableStates(); } private void QueryItem_CheckedChanged(object sender, EventArgs e) { UpdateEnableStates(); } /// <summary> /// Updates all of the enable states for the controls (based on the current state of this control) /// </summary> public void UpdateEnableStates() { bool bEnabled; switch(m_eControlType) { case ControlType.TextBox: case ControlType.BrowseBox: case ControlType.ComboBox: bEnabled = 0 < m_zControl.Text.Length; break; case ControlType.CheckBox: bEnabled = ((CheckBox)m_zControl).Checked; break; default: return; } foreach (QueryItem zItem in m_listEnableControls) { zItem.m_zControl.Enabled = bEnabled; switch (zItem.m_eControlType) { case ControlType.BrowseBox: case ControlType.NumBoxSlider: ((Control)zItem.Tag).Enabled = bEnabled; break; } } } } #endregion #region Events /// <summary> /// Generic button press (used for the browse file/folder box) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void zButton_Click(object sender, EventArgs e) { var zButton = (Button)sender; var zText = (TextBox)zButton.Tag; var sFilter = (string)zText.Tag; if(!string.IsNullOrEmpty(sFilter)) // file browse { var ofn = new OpenFileDialog { Filter = sFilter, CheckFileExists = false, FileName = zText.Text }; if(DialogResult.OK == ofn.ShowDialog()) { zText.Text = ofn.FileName; } } else // folder browse { var fbd = new FolderBrowserDialog { ShowNewFolderButton = true, SelectedPath = zText.Text }; if(DialogResult.OK == fbd.ShowDialog()) { zText.Text = fbd.SelectedPath; } } } /// <summary> /// Handles generic numeric slider change /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void numericSlider_ValueChanged(object sender, EventArgs e) { var zTrackBar = (TrackBar)sender; var zNumeric = (NumericUpDown)zTrackBar.Tag; if (1 > zNumeric.Increment) { zNumeric.Value = zNumeric.Minimum + ((decimal)zTrackBar.Value * zNumeric.Increment); } else { zNumeric.Value = zTrackBar.Value; } } /// <summary> /// Handles generic numeric change /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void numeric_ValueChanged(object sender, EventArgs e) { var zNumeric = (NumericUpDown)sender; var zTrackBar = (TrackBar)zNumeric.Tag; if (1 > zNumeric.Increment) { zTrackBar.Value = (int)((zNumeric.Value - zNumeric.Minimum) * ((decimal)1 / zNumeric.Increment)); } else { zTrackBar.Value = (int)zNumeric.Value; } } /// <summary> /// Sets the Y position for the current layout control (panel, tab etc.) /// </summary> /// <param name="nYAmount">Amount to add</param> private void AddToYPosition(int nYAmount) { var nCurrentY = (int)m_zCurrentLayoutControl.Tag; nCurrentY += nYAmount; m_zCurrentLayoutControl.Tag = nCurrentY; } /// <summary> /// Gets the current y position (based on the current layout control) /// </summary> /// <returns></returns> protected int GetYPosition() { return (int)m_zCurrentLayoutControl.Tag; } public void UpdateEnableStates() { // Update enable states foreach (var zItem in m_dictionaryItems.Values) { zItem.UpdateEnableStates(); } } #endregion } }
/* * 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: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace XenAPI { /// <summary> /// A physical USB device /// First published in XenServer 7.3. /// </summary> public partial class PUSB : XenObject<PUSB> { public PUSB() { } public PUSB(string uuid, XenRef<USB_group> USB_group, XenRef<Host> host, string path, string vendor_id, string vendor_desc, string product_id, string product_desc, string serial, string version, string description, bool passthrough_enabled, Dictionary<string, string> other_config) { this.uuid = uuid; this.USB_group = USB_group; this.host = host; this.path = path; this.vendor_id = vendor_id; this.vendor_desc = vendor_desc; this.product_id = product_id; this.product_desc = product_desc; this.serial = serial; this.version = version; this.description = description; this.passthrough_enabled = passthrough_enabled; this.other_config = other_config; } /// <summary> /// Creates a new PUSB from a Proxy_PUSB. /// </summary> /// <param name="proxy"></param> public PUSB(Proxy_PUSB proxy) { this.UpdateFromProxy(proxy); } /// <summary> /// Updates each field of this instance with the value of /// the corresponding field of a given PUSB. /// </summary> public override void UpdateFrom(PUSB update) { uuid = update.uuid; USB_group = update.USB_group; host = update.host; path = update.path; vendor_id = update.vendor_id; vendor_desc = update.vendor_desc; product_id = update.product_id; product_desc = update.product_desc; serial = update.serial; version = update.version; description = update.description; passthrough_enabled = update.passthrough_enabled; other_config = update.other_config; } internal void UpdateFromProxy(Proxy_PUSB proxy) { uuid = proxy.uuid == null ? null : (string)proxy.uuid; USB_group = proxy.USB_group == null ? null : XenRef<USB_group>.Create(proxy.USB_group); host = proxy.host == null ? null : XenRef<Host>.Create(proxy.host); path = proxy.path == null ? null : (string)proxy.path; vendor_id = proxy.vendor_id == null ? null : (string)proxy.vendor_id; vendor_desc = proxy.vendor_desc == null ? null : (string)proxy.vendor_desc; product_id = proxy.product_id == null ? null : (string)proxy.product_id; product_desc = proxy.product_desc == null ? null : (string)proxy.product_desc; serial = proxy.serial == null ? null : (string)proxy.serial; version = proxy.version == null ? null : (string)proxy.version; description = proxy.description == null ? null : (string)proxy.description; passthrough_enabled = (bool)proxy.passthrough_enabled; other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); } public Proxy_PUSB ToProxy() { Proxy_PUSB result_ = new Proxy_PUSB(); result_.uuid = uuid ?? ""; result_.USB_group = USB_group ?? ""; result_.host = host ?? ""; result_.path = path ?? ""; result_.vendor_id = vendor_id ?? ""; result_.vendor_desc = vendor_desc ?? ""; result_.product_id = product_id ?? ""; result_.product_desc = product_desc ?? ""; result_.serial = serial ?? ""; result_.version = version ?? ""; result_.description = description ?? ""; result_.passthrough_enabled = passthrough_enabled; result_.other_config = Maps.convert_to_proxy_string_string(other_config); return result_; } /// <summary> /// Creates a new PUSB from a Hashtable. /// Note that the fields not contained in the Hashtable /// will be created with their default values. /// </summary> /// <param name="table"></param> public PUSB(Hashtable table) : this() { UpdateFrom(table); } /// <summary> /// Given a Hashtable with field-value pairs, it updates the fields of this PUSB /// with the values listed in the Hashtable. Note that only the fields contained /// in the Hashtable will be updated and the rest will remain the same. /// </summary> /// <param name="table"></param> public void UpdateFrom(Hashtable table) { if (table.ContainsKey("uuid")) uuid = Marshalling.ParseString(table, "uuid"); if (table.ContainsKey("USB_group")) USB_group = Marshalling.ParseRef<USB_group>(table, "USB_group"); if (table.ContainsKey("host")) host = Marshalling.ParseRef<Host>(table, "host"); if (table.ContainsKey("path")) path = Marshalling.ParseString(table, "path"); if (table.ContainsKey("vendor_id")) vendor_id = Marshalling.ParseString(table, "vendor_id"); if (table.ContainsKey("vendor_desc")) vendor_desc = Marshalling.ParseString(table, "vendor_desc"); if (table.ContainsKey("product_id")) product_id = Marshalling.ParseString(table, "product_id"); if (table.ContainsKey("product_desc")) product_desc = Marshalling.ParseString(table, "product_desc"); if (table.ContainsKey("serial")) serial = Marshalling.ParseString(table, "serial"); if (table.ContainsKey("version")) version = Marshalling.ParseString(table, "version"); if (table.ContainsKey("description")) description = Marshalling.ParseString(table, "description"); if (table.ContainsKey("passthrough_enabled")) passthrough_enabled = Marshalling.ParseBool(table, "passthrough_enabled"); if (table.ContainsKey("other_config")) other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(PUSB other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._USB_group, other._USB_group) && Helper.AreEqual2(this._host, other._host) && Helper.AreEqual2(this._path, other._path) && Helper.AreEqual2(this._vendor_id, other._vendor_id) && Helper.AreEqual2(this._vendor_desc, other._vendor_desc) && Helper.AreEqual2(this._product_id, other._product_id) && Helper.AreEqual2(this._product_desc, other._product_desc) && Helper.AreEqual2(this._serial, other._serial) && Helper.AreEqual2(this._version, other._version) && Helper.AreEqual2(this._description, other._description) && Helper.AreEqual2(this._passthrough_enabled, other._passthrough_enabled) && Helper.AreEqual2(this._other_config, other._other_config); } internal static List<PUSB> ProxyArrayToObjectList(Proxy_PUSB[] input) { var result = new List<PUSB>(); foreach (var item in input) result.Add(new PUSB(item)); return result; } public override string SaveChanges(Session session, string opaqueRef, PUSB server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { if (!Helper.AreEqual2(_other_config, server._other_config)) { PUSB.set_other_config(session, opaqueRef, _other_config); } return null; } } /// <summary> /// Get a record containing the current state of the given PUSB. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_pusb">The opaque_ref of the given pusb</param> public static PUSB get_record(Session session, string _pusb) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pusb_get_record(session.opaque_ref, _pusb); else return new PUSB((Proxy_PUSB)session.proxy.pusb_get_record(session.opaque_ref, _pusb ?? "").parse()); } /// <summary> /// Get a reference to the PUSB instance with the specified UUID. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<PUSB> get_by_uuid(Session session, string _uuid) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pusb_get_by_uuid(session.opaque_ref, _uuid); else return XenRef<PUSB>.Create(session.proxy.pusb_get_by_uuid(session.opaque_ref, _uuid ?? "").parse()); } /// <summary> /// Get the uuid field of the given PUSB. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_pusb">The opaque_ref of the given pusb</param> public static string get_uuid(Session session, string _pusb) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pusb_get_uuid(session.opaque_ref, _pusb); else return (string)session.proxy.pusb_get_uuid(session.opaque_ref, _pusb ?? "").parse(); } /// <summary> /// Get the USB_group field of the given PUSB. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_pusb">The opaque_ref of the given pusb</param> public static XenRef<USB_group> get_USB_group(Session session, string _pusb) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pusb_get_usb_group(session.opaque_ref, _pusb); else return XenRef<USB_group>.Create(session.proxy.pusb_get_usb_group(session.opaque_ref, _pusb ?? "").parse()); } /// <summary> /// Get the host field of the given PUSB. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_pusb">The opaque_ref of the given pusb</param> public static XenRef<Host> get_host(Session session, string _pusb) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pusb_get_host(session.opaque_ref, _pusb); else return XenRef<Host>.Create(session.proxy.pusb_get_host(session.opaque_ref, _pusb ?? "").parse()); } /// <summary> /// Get the path field of the given PUSB. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_pusb">The opaque_ref of the given pusb</param> public static string get_path(Session session, string _pusb) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pusb_get_path(session.opaque_ref, _pusb); else return (string)session.proxy.pusb_get_path(session.opaque_ref, _pusb ?? "").parse(); } /// <summary> /// Get the vendor_id field of the given PUSB. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_pusb">The opaque_ref of the given pusb</param> public static string get_vendor_id(Session session, string _pusb) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pusb_get_vendor_id(session.opaque_ref, _pusb); else return (string)session.proxy.pusb_get_vendor_id(session.opaque_ref, _pusb ?? "").parse(); } /// <summary> /// Get the vendor_desc field of the given PUSB. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_pusb">The opaque_ref of the given pusb</param> public static string get_vendor_desc(Session session, string _pusb) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pusb_get_vendor_desc(session.opaque_ref, _pusb); else return (string)session.proxy.pusb_get_vendor_desc(session.opaque_ref, _pusb ?? "").parse(); } /// <summary> /// Get the product_id field of the given PUSB. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_pusb">The opaque_ref of the given pusb</param> public static string get_product_id(Session session, string _pusb) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pusb_get_product_id(session.opaque_ref, _pusb); else return (string)session.proxy.pusb_get_product_id(session.opaque_ref, _pusb ?? "").parse(); } /// <summary> /// Get the product_desc field of the given PUSB. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_pusb">The opaque_ref of the given pusb</param> public static string get_product_desc(Session session, string _pusb) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pusb_get_product_desc(session.opaque_ref, _pusb); else return (string)session.proxy.pusb_get_product_desc(session.opaque_ref, _pusb ?? "").parse(); } /// <summary> /// Get the serial field of the given PUSB. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_pusb">The opaque_ref of the given pusb</param> public static string get_serial(Session session, string _pusb) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pusb_get_serial(session.opaque_ref, _pusb); else return (string)session.proxy.pusb_get_serial(session.opaque_ref, _pusb ?? "").parse(); } /// <summary> /// Get the version field of the given PUSB. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_pusb">The opaque_ref of the given pusb</param> public static string get_version(Session session, string _pusb) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pusb_get_version(session.opaque_ref, _pusb); else return (string)session.proxy.pusb_get_version(session.opaque_ref, _pusb ?? "").parse(); } /// <summary> /// Get the description field of the given PUSB. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_pusb">The opaque_ref of the given pusb</param> public static string get_description(Session session, string _pusb) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pusb_get_description(session.opaque_ref, _pusb); else return (string)session.proxy.pusb_get_description(session.opaque_ref, _pusb ?? "").parse(); } /// <summary> /// Get the passthrough_enabled field of the given PUSB. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_pusb">The opaque_ref of the given pusb</param> public static bool get_passthrough_enabled(Session session, string _pusb) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pusb_get_passthrough_enabled(session.opaque_ref, _pusb); else return (bool)session.proxy.pusb_get_passthrough_enabled(session.opaque_ref, _pusb ?? "").parse(); } /// <summary> /// Get the other_config field of the given PUSB. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_pusb">The opaque_ref of the given pusb</param> public static Dictionary<string, string> get_other_config(Session session, string _pusb) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pusb_get_other_config(session.opaque_ref, _pusb); else return Maps.convert_from_proxy_string_string(session.proxy.pusb_get_other_config(session.opaque_ref, _pusb ?? "").parse()); } /// <summary> /// Set the other_config field of the given PUSB. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_pusb">The opaque_ref of the given pusb</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _pusb, Dictionary<string, string> _other_config) { if (session.JsonRpcClient != null) session.JsonRpcClient.pusb_set_other_config(session.opaque_ref, _pusb, _other_config); else session.proxy.pusb_set_other_config(session.opaque_ref, _pusb ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given PUSB. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_pusb">The opaque_ref of the given pusb</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _pusb, string _key, string _value) { if (session.JsonRpcClient != null) session.JsonRpcClient.pusb_add_to_other_config(session.opaque_ref, _pusb, _key, _value); else session.proxy.pusb_add_to_other_config(session.opaque_ref, _pusb ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given PUSB. If the key is not in that Map, then do nothing. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_pusb">The opaque_ref of the given pusb</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _pusb, string _key) { if (session.JsonRpcClient != null) session.JsonRpcClient.pusb_remove_from_other_config(session.opaque_ref, _pusb, _key); else session.proxy.pusb_remove_from_other_config(session.opaque_ref, _pusb ?? "", _key ?? "").parse(); } /// <summary> /// /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_host">The host</param> public static void scan(Session session, string _host) { if (session.JsonRpcClient != null) session.JsonRpcClient.pusb_scan(session.opaque_ref, _host); else session.proxy.pusb_scan(session.opaque_ref, _host ?? "").parse(); } /// <summary> /// /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_host">The host</param> public static XenRef<Task> async_scan(Session session, string _host) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_pusb_scan(session.opaque_ref, _host); else return XenRef<Task>.Create(session.proxy.async_pusb_scan(session.opaque_ref, _host ?? "").parse()); } /// <summary> /// /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_pusb">The opaque_ref of the given pusb</param> /// <param name="_value">passthrough is enabled when true and disabled with false</param> public static void set_passthrough_enabled(Session session, string _pusb, bool _value) { if (session.JsonRpcClient != null) session.JsonRpcClient.pusb_set_passthrough_enabled(session.opaque_ref, _pusb, _value); else session.proxy.pusb_set_passthrough_enabled(session.opaque_ref, _pusb ?? "", _value).parse(); } /// <summary> /// /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_pusb">The opaque_ref of the given pusb</param> /// <param name="_value">passthrough is enabled when true and disabled with false</param> public static XenRef<Task> async_set_passthrough_enabled(Session session, string _pusb, bool _value) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_pusb_set_passthrough_enabled(session.opaque_ref, _pusb, _value); else return XenRef<Task>.Create(session.proxy.async_pusb_set_passthrough_enabled(session.opaque_ref, _pusb ?? "", _value).parse()); } /// <summary> /// Return a list of all the PUSBs known to the system. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> public static List<XenRef<PUSB>> get_all(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pusb_get_all(session.opaque_ref); else return XenRef<PUSB>.Create(session.proxy.pusb_get_all(session.opaque_ref).parse()); } /// <summary> /// Get all the PUSB Records at once, in a single XML RPC call /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<PUSB>, PUSB> get_all_records(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pusb_get_all_records(session.opaque_ref); else return XenRef<PUSB>.Create<Proxy_PUSB>(session.proxy.pusb_get_all_records(session.opaque_ref).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid = ""; /// <summary> /// USB group the PUSB is contained in /// </summary> [JsonConverter(typeof(XenRefConverter<USB_group>))] public virtual XenRef<USB_group> USB_group { get { return _USB_group; } set { if (!Helper.AreEqual(value, _USB_group)) { _USB_group = value; Changed = true; NotifyPropertyChanged("USB_group"); } } } private XenRef<USB_group> _USB_group = new XenRef<USB_group>("OpaqueRef:NULL"); /// <summary> /// Physical machine that owns the USB device /// </summary> [JsonConverter(typeof(XenRefConverter<Host>))] public virtual XenRef<Host> host { get { return _host; } set { if (!Helper.AreEqual(value, _host)) { _host = value; Changed = true; NotifyPropertyChanged("host"); } } } private XenRef<Host> _host = new XenRef<Host>("OpaqueRef:NULL"); /// <summary> /// port path of USB device /// </summary> public virtual string path { get { return _path; } set { if (!Helper.AreEqual(value, _path)) { _path = value; Changed = true; NotifyPropertyChanged("path"); } } } private string _path = ""; /// <summary> /// vendor id of the USB device /// </summary> public virtual string vendor_id { get { return _vendor_id; } set { if (!Helper.AreEqual(value, _vendor_id)) { _vendor_id = value; Changed = true; NotifyPropertyChanged("vendor_id"); } } } private string _vendor_id = ""; /// <summary> /// vendor description of the USB device /// </summary> public virtual string vendor_desc { get { return _vendor_desc; } set { if (!Helper.AreEqual(value, _vendor_desc)) { _vendor_desc = value; Changed = true; NotifyPropertyChanged("vendor_desc"); } } } private string _vendor_desc = ""; /// <summary> /// product id of the USB device /// </summary> public virtual string product_id { get { return _product_id; } set { if (!Helper.AreEqual(value, _product_id)) { _product_id = value; Changed = true; NotifyPropertyChanged("product_id"); } } } private string _product_id = ""; /// <summary> /// product description of the USB device /// </summary> public virtual string product_desc { get { return _product_desc; } set { if (!Helper.AreEqual(value, _product_desc)) { _product_desc = value; Changed = true; NotifyPropertyChanged("product_desc"); } } } private string _product_desc = ""; /// <summary> /// serial of the USB device /// </summary> public virtual string serial { get { return _serial; } set { if (!Helper.AreEqual(value, _serial)) { _serial = value; Changed = true; NotifyPropertyChanged("serial"); } } } private string _serial = ""; /// <summary> /// USB device version /// </summary> public virtual string version { get { return _version; } set { if (!Helper.AreEqual(value, _version)) { _version = value; Changed = true; NotifyPropertyChanged("version"); } } } private string _version = ""; /// <summary> /// USB device description /// </summary> public virtual string description { get { return _description; } set { if (!Helper.AreEqual(value, _description)) { _description = value; Changed = true; NotifyPropertyChanged("description"); } } } private string _description = ""; /// <summary> /// enabled for passthrough /// </summary> public virtual bool passthrough_enabled { get { return _passthrough_enabled; } set { if (!Helper.AreEqual(value, _passthrough_enabled)) { _passthrough_enabled = value; Changed = true; NotifyPropertyChanged("passthrough_enabled"); } } } private bool _passthrough_enabled = false; /// <summary> /// additional configuration /// </summary> [JsonConverter(typeof(StringStringMapConverter))] public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; Changed = true; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config = new Dictionary<string, string>() {}; } }
using System; using System.Net.Sockets; using System.Net.Security; using System.Text; using System.Threading; using System.IO; using System.Security.Cryptography.X509Certificates; using System.Collections.Generic; using System.Diagnostics; using System.Data; using MySql.Data.MySqlClient; namespace GraystoneIRC { public class IRC { private string version = "0.1"; private bool Verbose = false; public string Nick = "Graystone"; public string User = "Graystone Graystone 8 * :Graystone IRC Bot"; public string Server = ""; public string Channel = "#channel"; public int Port = 6667; public bool Ssl = false; public static bool AllowBadSsl = false; public bool AllowInChannel = true; public string ServerPassword = ""; public string NickPassword = ""; public string OperPassword = ""; public string ChannelPassword = ""; public TcpClient tcpSocket; public NetworkStream tcpStream; public SslStream sslStream; public StreamReader streamInput; public StreamWriter streamOutput; public bool Connected = false; public string buffer; public bool Running = true; public bool isLinux = IsLinux(); public int ConnectionAttempt = 0; public static List<string> AllowedUsers = new List<string> (); public static List<Action> Actions = new List<Action> (); public bool UseMysql = false; public bool MySQLRunning = false; public int MySQLSleep = 100; public MySqlConnection MySQLConn; public string MySQLConnectionString = "Server=localhost; Database=graystone; Uid=root; Pwd=toor;"; public string MySQLTable = "messages"; public string MySQLFieldId = "message_id"; public string MySQLFieldType = "message_type"; public string MySQLFieldData = "message_data"; public enum ActionType { CommandLine, Http } public enum ResponseType { Message, Raw } public class Action { public string Name; public ActionType Type; public ResponseType ResponseType; public string Command; public Action(string Name, ActionType Type, ResponseType ResponseType, string Command) { this.Name = Name; this.Type = Type; this.ResponseType = ResponseType; this.Command = Command; } } public IRC () { } public void Main (string[] args) { ConsoleMessage ("Graystone v" + version); ConsoleMessage ("Copyright (c) 2015 Geoff Woollams"); ConsoleMessage (""); LoadSettings (); if (Nick.Length < 1 || User.Split (' ').Length < 4 || Server.Length < 1 || Port < 1) { ConsoleMessage ("You must configure Graystone.conf before starting!"); Running = false; } if (UseMysql) { ThreadPool.QueueUserWorkItem(o => SQLLoop()); } while (Running) { if(!Connected) { ConsoleMessage ("Connecting to irc" + (Ssl ? "s" : "") + "://" + Server + ":" + Port + "/" + Channel); if(!Connect()) { int secondsToWait = 1; if(ConnectionAttempt <= 3) secondsToWait = 1; else if(ConnectionAttempt <= 10) secondsToWait = 10; else if(ConnectionAttempt <= 20) secondsToWait = 30; else if(ConnectionAttempt <= 50) secondsToWait = 60; else if(ConnectionAttempt > 50) secondsToWait = 120; ConsoleMessage ("Connect Failed. Trying again in " + secondsToWait + " seconds."); Thread.Sleep (1000 * secondsToWait); } else { ConnectionAttempt = 0; ConsoleMessage ("Connected!"); } } if(Connected) { while ((buffer = streamInput.ReadLine()) != null) { if(Verbose) ConsoleMessage("[INPUT]: " + buffer); if (buffer.StartsWith("ERROR ")) { Connected = false; } else if (buffer.StartsWith("PING ")) { SendLine(buffer.Replace("PING", "PONG")); } else if (buffer.StartsWith(":")) { var buf = buffer.Split(new char[] { ' ' }, 5); string username = buf[2]; if(buf[1] == "PRIVMSG" && (buf[2] == Channel || buf[2] == Nick) && buf[3].StartsWith(":!")) { bool isPrivate = (buf[2] == Nick); if(isPrivate) username = buf[0].Substring(1).Split('!')[0]; if(!AllowInChannel && isPrivate) continue; if(AllowedUsers.Count > 0) { bool allowed = false; var thisUser = buf[0].Split('!'); foreach(var user in AllowedUsers) { if(thisUser[0] == user) allowed = true; } if(!allowed) continue; } if(buf[3].Substring(2) == "help") { SendMessage("Available Commands:", username); SendMessage(" !save - Saves settings", username); SendMessage(" !load - Loads settings", username); SendMessage(" !exit - Exits", username); SendMessage(" !reconnect - Reonnects", username); SendMessage(" !help - Shows this message", username); SendMessage(" !users - Shows users allowed to use these commands", username); foreach(var action in Actions) { if(action.Type == ActionType.CommandLine) { if(isLinux) { SendMessage(" !" + action.Name + " -> bash -c " + action.Command, username); } else { SendMessage(" !" + action.Name + " -> cmd.exe /c " + action.Command, username); } } else if(action.Type == ActionType.CommandLine) { SendMessage(" !" + action.Name + " -> " + action.Command, username); } } } else if(buf[3].Substring(2) == "users") { foreach(var user in AllowedUsers) { SendMessage(user, username); } } else if(buf[3].Substring(2) == "load") { SendMessage("Loading Settings...", username); LoadSettings(); } else if(buf[3].Substring(2) == "save") { SendMessage("Saving Settings...", username); SaveSettings(); } else if(buf[3].Substring(2) == "exit") { Running = false; } else if(buf[3].Substring(2) == "reconnect") { SendLine("QUIT"); Connected = false; } else { foreach(var action in Actions) { string actionCommand = action.Command; if(buf.Length >= 5 && buf[4].Length > 0) actionCommand = ReplaceArgs(actionCommand, buf[4]); else actionCommand = ReplaceArgs(actionCommand, ""); if(buf[3].Substring(2) == action.Name) { if(action.Type == ActionType.CommandLine) { Process p = new Process(); if(isLinux) { p.StartInfo = new ProcessStartInfo("bash", "-c " + actionCommand); } else { p.StartInfo = new ProcessStartInfo("cmd.exe", "/c " + actionCommand); } p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.UseShellExecute = false; p.Start(); using (StreamReader reader = p.StandardOutput) { string result = reader.ReadToEnd(); if(action.ResponseType == ResponseType.Message) SendMessage(result, username); else if(action.ResponseType == ResponseType.Raw) SendLine(result); } } else if(action.Type == ActionType.Http) { string contents; using (var wc = new System.Net.WebClient()) contents = wc.DownloadString(actionCommand); if(action.ResponseType == ResponseType.Message) SendMessage(contents, username); else if(action.ResponseType == ResponseType.Raw) SendLine(contents); } } } } } } if(!Running || !Connected || !tcpSocket.Connected) break; } SendLine("QUIT"); if(!tcpSocket.Connected) Connected = false; } } ConsoleMessage ("Quiting..."); SaveSettings (); if (MySQLRunning) { ConsoleMessage ("Closing SQL Connection..."); while (MySQLRunning) { // waiting... } } ConsoleMessage ("Goodbye!"); try { streamInput.Close (); streamOutput.Close (); if (Ssl) sslStream.Close (); else tcpStream.Close (); tcpSocket.Close (); } catch(Exception e) { if(Verbose) ConsoleMessage("[ERROR] " + e.ToString()); } } public bool Connect() { ConnectionAttempt++; Connected = false; if (tcpSocket != null && tcpSocket.Connected) tcpSocket.Close(); tcpSocket = new TcpClient(); tcpSocket.Connect(Server, Port); if (Ssl) { try { sslStream = new SslStream (tcpSocket.GetStream(), false, new RemoteCertificateValidationCallback(CertificateValidationCallback)); sslStream.AuthenticateAsClient(Server); streamInput = new StreamReader(sslStream); streamOutput = new StreamWriter(sslStream); Connected = true; } catch(Exception e) { return false; } } else { tcpStream = tcpSocket.GetStream(); streamInput = new StreamReader(tcpStream); streamOutput = new StreamWriter(tcpStream); Connected = true; } streamOutput.AutoFlush = true; if(ServerPassword.Length > 0) SendLine("PASS " + ServerPassword); SendLine("NICK " + Nick); SendLine("USER " + User); if(NickPassword.Length > 0) SendLine("PRIVMSG NickServ :identify " + NickPassword); while ((buffer = streamInput.ReadLine()) != null) { if(Verbose) ConsoleMessage("[INPUT]: " + buffer); if (buffer.StartsWith("ERROR ")) { Connected = false; } else if (buffer.StartsWith("PING ")) { SendLine(buffer.Replace("PING", "PONG")); } else if (buffer[0] != ':') continue; else { var buf = buffer.Split(' '); if (buf[1] == "001") { //SendLine("MODE " + Nick + " +B"); if(ChannelPassword.Length > 0) SendLine("JOIN " + Channel + " " + ChannelPassword); else SendLine("JOIN " + Channel); } else if (buf[0].StartsWith(":" + Nick + "!") && buf[1] == "JOIN" && buf[2] == ":" + Channel) { //ConsoleMessage("Joined Channel!"); if (OperPassword.Length > 0) { SendLine("OPER " + Nick + " " + OperPassword); } break; } } } return Connected; } public void SQLLoop() { MySqlDataReader reader; MySqlCommand cmd; List<int> deleteIds = new List<int>(); try { MySQLConn = new MySqlConnection(MySQLConnectionString); MySQLConn.Open(); MySQLRunning = true; string query = "SELECT `" + MySQLFieldId + "`,`" + MySQLFieldType + "`,`" + MySQLFieldData + "` FROM `" + MySQLTable + "` ORDER BY `" + MySQLFieldId + "`"; while (Running) { if(Connected) { cmd = new MySqlCommand(query,MySQLConn); reader = cmd.ExecuteReader(); while(reader.Read()) { if(reader.GetInt32(1) == 1) { // Message SendMessage(reader.GetString(2)); } else if(reader.GetInt32(1) == 2) { // Raw SendLine(reader.GetString(2)); } deleteIds.Add(reader.GetInt32(0)); } reader.Close(); foreach(int deleteId in deleteIds) { string queryDelete = "DELETE FROM `" + MySQLTable + "` WHERE `" + MySQLFieldId + "`='" + deleteId + "'"; var cmdDelete = new MySqlCommand(queryDelete,MySQLConn); var readerDelete = cmdDelete.ExecuteNonQuery(); //readerDelete.Close(); } deleteIds.Clear(); } Thread.Sleep(MySQLSleep); } MySQLConn.Close (); } catch(Exception e) { ConsoleMessage("[SQL] " + e.Message); } MySQLRunning = false; } public void LoadSettings() { if (!System.IO.File.Exists ("Graystone.conf")) { SaveSettings(); return; } AllowedUsers.Clear(); Actions.Clear(); System.IO.StreamReader file = new System.IO.StreamReader("Graystone.conf"); string line; while((line = file.ReadLine()) != null) { if(line.StartsWith(";") || line.StartsWith("#")) continue; if(line.StartsWith("setting ")) { var item = line.Split(new char[] { ' ' }, 3); if(item[1] == "Verbose") { Verbose = item[2] == "true" ? true : false; } else if(item[1] == "Nick") { Nick = item[2]; } else if(item[1] == "User") { User = item[2]; } else if(item[1] == "Server") { Server = item[2]; } else if(item[1] == "Channel") { Channel = item[2]; } else if(item[1] == "Port") { Port = Convert.ToInt32(item[2]); } else if(item[1] == "Ssl") { Ssl = item[2] == "true" ? true : false; } else if(item[1] == "AllowBadSsl") { AllowBadSsl = item[2] == "true" ? true : false; } else if(item[1] == "AllowInChannel") { AllowInChannel = item[2] == "true" ? true : false; } else if(item[1] == "ServerPassword") { ServerPassword = item[2]; } else if(item[1] == "NickPassword") { NickPassword = item[2]; } else if(item[1] == "ChannelPassword") { ChannelPassword = item[2]; } else if(item[1] == "OperPassword") { OperPassword = item[2]; } else if(item[1] == "UseMysql") { UseMysql = item[2] == "true" ? true : false; } else if(item[1] == "MySQLSleep") { MySQLSleep = Convert.ToInt32(item[2]); } else if(item[1] == "MySQLConnectionString") { MySQLConnectionString = item[2]; } else if(item[1] == "MySQLTable") { MySQLTable = item[2]; } else if(item[1] == "MySQLFieldId") { MySQLFieldId = item[2]; } else if(item[1] == "MySQLFieldType") { MySQLFieldType = item[2]; } else if(item[1] == "MySQLFieldData") { MySQLFieldData = item[2]; } } else if(line.StartsWith("action ")) { var item = line.Split(new char[] { ' ' }, 5); try { Actions.Add(new Action(item[1], (ActionType) Enum.Parse(typeof(ActionType), item[2]), (ResponseType) Enum.Parse(typeof(ResponseType), item[3]), item[4])); } catch(Exception e) { if(Verbose) { ConsoleMessage("[ERROR 1/2] " + line); ConsoleMessage("[ERROR 2/2] " + e.Message); } } } else if(line.StartsWith("alloweduser ")) { var item = line.Split(new char[] { ' ' }, 2); AllowedUsers.Add(item[1]); } } file.Close (); } public void SaveSettings() { StreamWriter writer = new StreamWriter ("Graystone.conf", false); writer.WriteLine("#setting <var> <val>"); writer.WriteLine("setting Verbose " + (Verbose == true ? "true" : "false")); writer.WriteLine("setting Nick " + Nick); writer.WriteLine("setting User " + User); writer.WriteLine("setting Server " + Server); writer.WriteLine("setting Channel " + Channel); writer.WriteLine("setting Port " + Port); writer.WriteLine("setting Ssl " + (Ssl == true ? "true" : "false")); writer.WriteLine("setting AllowBadSsl " + (AllowBadSsl == true ? "true" : "false")); writer.WriteLine("setting AllowInChannel " + (AllowInChannel == true ? "true" : "false")); writer.WriteLine("setting ServerPassword " + ServerPassword); writer.WriteLine("setting NickPassword " + NickPassword); writer.WriteLine("setting ChannelPassword " + ChannelPassword); writer.WriteLine("setting OperPassword " + OperPassword); writer.WriteLine(""); writer.WriteLine("#MySQL - id & type fields must be int's, data field should be text."); writer.WriteLine("setting UseMysql " + (UseMysql == true ? "true" : "false")); writer.WriteLine("setting MySQLSleep " + MySQLSleep); writer.WriteLine("setting MySQLConnectionString " + MySQLConnectionString); writer.WriteLine("setting MySQLTable " + MySQLTable); writer.WriteLine("setting MySQLFieldId " + MySQLFieldId); writer.WriteLine("setting MySQLFieldType " + MySQLFieldType); writer.WriteLine("setting MySQLFieldData " + MySQLFieldData); writer.WriteLine(""); writer.WriteLine("#Execute the command by typing the name into IRC prefixed with a !"); writer.WriteLine("#Name and types must contain no spaces. Command can contain spaces."); writer.WriteLine("#Reserved names: save, load, help, users, exit, reconnect."); writer.WriteLine("#Types: CommandLine, Http."); writer.WriteLine("#Response Types: Message, Raw."); writer.WriteLine("#action <name> <type> <responeType> <command>"); writer.WriteLine("#action ls CommandLine Message ls -al"); writer.WriteLine("#action myip Http Message http://what-is-my-ip.net/?text"); foreach(var action in Actions) { writer.WriteLine("action " + action.Name + " " + action.Type + " " + action.ResponseType + " " + action.Command); } writer.WriteLine(""); writer.WriteLine("#If you dont list any names, everyone will be able to use the commands"); writer.WriteLine("#alloweduser <nick>"); foreach(var users in AllowedUsers) { writer.WriteLine("alloweduser " + users); } writer.Close (); } public void SendMessage(string data, string name) { if (name == Channel) SendMessage (data); else SendPM (data, name); } public void SendPM(string data, string user) { if(data.Contains("\n")) { string[] lines = data.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None); foreach(var line in lines) { SendPM(line, user); } } else { SendLine("PRIVMSG " + user + " :" + data); } } public void SendMessage(string data) { if(data.Contains("\n")) { string[] lines = data.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None); foreach(var line in lines) { SendMessage(line); } } else { SendLine("PRIVMSG " + Channel + " :" + data); } } public void SendLine(string data) { if(data.Contains("\n")) { string[] lines = data.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None); foreach(var line in lines) { SendLine(line); } } else { if(Verbose) ConsoleMessage("[OUTPUT]: " + data); streamOutput.Write(data + "\r\n"); } } public void ConsoleMessage(string message) { Console.WriteLine (message); } static bool CertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (AllowBadSsl) return true; if (sslPolicyErrors != SslPolicyErrors.None) { Console.WriteLine("[SSL ERROR] " + sslPolicyErrors.ToString()); return false; } else return true; } public static bool IsLinux() { int p = (int) Environment.OSVersion.Platform; return (p == 4) || (p == 6) || (p == 128); } public string ReplaceArgs(string command, string args) { return command.Replace("{{args}}", args); } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Collections; using System.Text; using gov.va.medora.mdo.dao; using gov.va.medora.mdo.dao.sql.npt; namespace gov.va.medora.mdo.api { public class PatientApi { string DAO_NAME = "IPatientDao"; public PatientApi() {} public Patient[] match(AbstractConnection cxn, string target) { return ((IPatientDao)cxn.getDao(DAO_NAME)).match(target); } public IndexedHashtable match(ConnectionSet cxns, string target) { return cxns.query(DAO_NAME, "match", new object[] { target }); } public Patient[] matchByNameCityState(AbstractConnection cxn, string name, string city, string state) { return ((IPatientDao)cxn.getDao(DAO_NAME)).matchByNameCityState(name,city,state); } public IndexedHashtable matchByNameCityState(ConnectionSet cxns, string name, string city, string state) { return cxns.query(DAO_NAME, "matchByNameCityState", new object[] { name,city,state }); } public Patient[] getPatientsByWard(AbstractConnection cxn, string wardId) { return ((IPatientDao)cxn.getDao(DAO_NAME)).getPatientsByWard(wardId); } public Patient[] getPatientsByClinic(AbstractConnection cxn, string clinicId) { return ((IPatientDao)cxn.getDao(DAO_NAME)).getPatientsByClinic(clinicId); } public Patient[] getPatientsByClinic(AbstractConnection cxn, string clinicId, string fromDate, string toDate) { return ((IPatientDao)cxn.getDao(DAO_NAME)).getPatientsByClinic(clinicId, fromDate, toDate); } public Patient[] getPatientsBySpecialty(AbstractConnection cxn, string specialtyId) { return ((IPatientDao)cxn.getDao(DAO_NAME)).getPatientsBySpecialty(specialtyId); } public Patient[] getPatientsByTeam(AbstractConnection cxn, string teamId) { return ((IPatientDao)cxn.getDao(DAO_NAME)).getPatientsByTeam(teamId); } public Patient[] getPatientsByProvider(AbstractConnection cxn, string duz) { return ((IPatientDao)cxn.getDao(DAO_NAME)).getPatientsByProvider(duz); } public Patient select(AbstractConnection cxn, string pid) { return ((IPatientDao)cxn.getDao(DAO_NAME)).select(pid); } public IndexedHashtable select(ConnectionSet cxns) { return cxns.query(DAO_NAME, "select", new object[] { }); } public string getLocalPid(AbstractConnection cxn, string mpiPID) { return ((IPatientDao)cxn.getDao(DAO_NAME)).getLocalPid(mpiPID); } public IndexedHashtable getLocalPids(ConnectionSet cxns, string mpiPID) { return cxns.query(DAO_NAME, "getLocalPid", new Object[] { mpiPID }); } public IndexedHashtable setLocalPids(ConnectionSet cxns, string mpiPid) { IndexedHashtable result = cxns.query(DAO_NAME, "getLocalPid", new object[] { mpiPid }); for (int i = 0; i < result.Count; i++) { if (result.GetValue(i).GetType().Name.EndsWith("Exception")) { continue; } string siteId = (string)result.GetKey(i); AbstractConnection cxn = cxns.getConnection(siteId); cxn.Pid = (string)result.GetValue(i); } return result; } public bool isTestPatient(AbstractConnection cxn) { return ((IPatientDao)cxn.getDao(DAO_NAME)).isTestPatient(); } public IndexedHashtable isTestPatient(ConnectionSet cxns) { return cxns.query(DAO_NAME, "isTestPatient", new object[] { }); } public KeyValuePair<int, string> getConfidentiality(AbstractConnection cxn) { return ((IPatientDao)cxn.getDao(DAO_NAME)).getConfidentiality(); } public IndexedHashtable getConfidentiality(ConnectionSet cxns) { return cxns.query(DAO_NAME, "getConfidentiality", new object[] { }); } public StringDictionary getRemoteSiteIds(AbstractConnection cxn, string pid) { return ((IPatientDao)cxn.getDao(DAO_NAME)).getRemoteSiteIds(pid); } public string issueConfidentialityBulletin(AbstractConnection cxn) { return ((IPatientDao)cxn.getDao(DAO_NAME)).issueConfidentialityBulletin(); } public IndexedHashtable issueConfidentialityBulletin(ConnectionSet cxns) { return cxns.query(DAO_NAME, "issueConfidentialityBulletin", new object[] { }); } public Site[] getRemoteSites(AbstractConnection cxn, string pid) { return ((IPatientDao)cxn.getDao(DAO_NAME)).getRemoteSites(pid); } public IndexedHashtable getPatientSelectionData(ConnectionSet cxns) { return cxns.query(DAO_NAME, "getPatientSelectionData", new Object[] { }); } public OEF_OIF[] getOefOif(AbstractConnection cxn) { return ((IPatientDao)cxn.getDao(DAO_NAME)).getOefOif(); } public IndexedHashtable getOefOif(ConnectionSet cxns) { return cxns.query(DAO_NAME, "getOefOif", new object[] { }); } public void addHomeDate(AbstractConnection cxn, Patient patient) { ((IPatientDao)cxn.getDao(DAO_NAME)).addHomeData(patient); } public Patient[] mpiMatch(DataSource src, string ssn) { gov.va.medora.mdo.dao.hl7.mpi.MpiConnection cxn = new gov.va.medora.mdo.dao.hl7.mpi.MpiConnection(src); gov.va.medora.mdo.dao.hl7.mpi.MpiPatientDao dao = new gov.va.medora.mdo.dao.hl7.mpi.MpiPatientDao(cxn); return dao.match(ssn); } public PatientAssociate[] getPatientAssociates(AbstractConnection cxn, string pid) { return ((IPatientDao)cxn.getDao(DAO_NAME)).getPatientAssociates(pid); } public IndexedHashtable getPatientAssociates(ConnectionSet cxns) { return cxns.query(DAO_NAME, "getPatientAssociates", new Object[] { }); } public string patientInquiry(AbstractConnection cxn, string pid) { return ((IPatientDao)cxn.getDao(DAO_NAME)).patientInquiry(pid); } public StringDictionary getPatientTypes(AbstractConnection cxn) { return ((IPatientDao)cxn.getDao(DAO_NAME)).getPatientTypes(); } public IndexedHashtable getPatientTypes(ConnectionSet cxns) { return cxns.query(DAO_NAME, "getPatientTypes", new Object[] { }); } public IndexedHashtable patientInquiry(ConnectionSet cxns, string pid) { return cxns.query(DAO_NAME, "patientInquiry", new Object[] { pid }); } public Patient[] nptMatch(string ssn) { NptPatientDao dao = new NptPatientDao(new NptConnection(new DataSource())); return dao.getPatient(ssn); } /// <summary> /// Match on Patient.Name, Patient.DOB, and Patient.SSN /// </summary> /// <param name="patient">The patient to match</param> /// <param name="connectionString">The SQL connection string</param> /// <returns>An array of matching patients</returns> public Patient[] nptLookup(Patient patient) { NptPatientDao dao = new NptPatientDao(new NptConnection(new DataSource())); return dao.getPatient(patient); } public RatedDisability[] getRatedDisabiliities(AbstractConnection cxn) { return ((IPatientDao)cxn.getDao(DAO_NAME)).getRatedDisabilities(); } public RatedDisability[] getRatedDisabiliities(AbstractConnection cxn, string pid) { return ((IPatientDao)cxn.getDao(DAO_NAME)).getRatedDisabilities(pid); } public IndexedHashtable getRatedDisabiliities(ConnectionSet cxns) { return cxns.query(DAO_NAME, "getRatedDisabiliities", new Object[] { }); } public TextReport getMOSReport(AbstractConnection cxn, Patient patient) { gov.va.medora.mdo.dao.oracle.vadir.VadirPatientDao vadirPatientDao = new dao.oracle.vadir.VadirPatientDao(cxn); return vadirPatientDao.getMOSReport(patient); } /// <summary> /// Get patient identifiers from the treating facility file at a single Vista (typically the base connection) /// </summary> /// <param name="cxn">Typically a VistaConnection</param> /// <param name="pid">Patient ID - typically a DFN</param> /// <returns>Dictionary of patient identifiers where key is the site ID and value is the patient ID at that site</returns> public Dictionary<string, string> getTreatingFacilityIds(AbstractConnection cxn, string pid) { return ((IPatientDao)cxn.getDao(DAO_NAME)).getTreatingFacilityIds(pid); } public IndexedHashtable getIdProofingStatus(ConnectionSet cxns, Patient patient) { return cxns.query(DAO_NAME, "isIdentityProofed", new object[] { patient }); } } }
// // Copyright (C) 2012-2014 DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Threading; using System.Net.Sockets; using System.Threading.Tasks; using Cassandra.Tasks; namespace Cassandra { internal class ControlConnection : IDisposable { private const string SelectPeers = "SELECT peer, data_center, rack, tokens, rpc_address FROM system.peers"; private const string SelectLocal = "SELECT * FROM system.local WHERE key='local'"; private const CassandraEventType CassandraEventTypes = CassandraEventType.TopologyChange | CassandraEventType.StatusChange | CassandraEventType.SchemaChange; private static readonly IPAddress BindAllAddress = new IPAddress(new byte[4]); /// <summary> /// Protocol version used by the control connection /// </summary> private int _controlConnectionProtocolVersion = 2; private volatile Host _host; private volatile Connection _connection; private static readonly Logger _logger = new Logger(typeof (ControlConnection)); private readonly Configuration _config; private readonly IReconnectionPolicy _reconnectionPolicy = new ExponentialReconnectionPolicy(2*1000, 5*60*1000); private IReconnectionSchedule _reconnectionSchedule; private readonly Timer _reconnectionTimer; private int _isShutdown = 0; private readonly object _refreshLock = new Object(); private int _protocolVersion; /// <summary> /// Gets the recommended binary protocol version to be used for this cluster. /// </summary> internal int ProtocolVersion { get { if (_protocolVersion != 0) { return _protocolVersion; } return _controlConnectionProtocolVersion; } } private Metadata Metadata { get; set; } internal Host Host { get { return _host; } set { _host = value; } } /// <summary> /// The address of the endpoint used by the ControlConnection /// </summary> internal IPEndPoint BindAddress { get { if (_connection == null) { return null; } return _connection.Address; } } internal ControlConnection(ICluster cluster, Metadata metadata) { Metadata = metadata; _reconnectionSchedule = _reconnectionPolicy.NewSchedule(); _reconnectionTimer = new Timer(_ => Refresh(true), null, Timeout.Infinite, Timeout.Infinite); _config = cluster.Configuration; } public void Dispose() { Shutdown(); } /// <summary> /// Tries to create a connection to any of the contact points and retrieve cluster metadata for the first time. Not thread-safe. /// </summary> /// <exception cref="NoHostAvailableException" /> /// <exception cref="DriverInternalError" /> internal void Init() { _logger.Info("Trying to connect the ControlConnection"); Connect(true); try { SubscribeEventHandlers(); RefreshNodeList(); Metadata.RefreshKeyspaces(false); } catch (SocketException ex) { //There was a problem using the connection obtained //It is not usual but can happen _logger.Error("An error occurred when trying to retrieve the cluster metadata, retrying.", ex); //Retry one more time and throw if there is problem Refresh(true, true); } } /// <summary> /// Tries to create the a connection to the cluster /// </summary> /// <exception cref="NoHostAvailableException" /> /// <exception cref="DriverInternalError" /> private void Connect(bool firstTime) { var triedHosts = new Dictionary<IPEndPoint, Exception>(); IEnumerable<Host> hostIterator = Metadata.Hosts; if (!firstTime) { _logger.Info("Trying to reconnect the ControlConnection"); //Use the load balancing policy to determine which host to use hostIterator = _config.Policies.LoadBalancingPolicy.NewQueryPlan(null, null); } foreach (var host in hostIterator) { var address = host.Address; var c = new Connection((byte)_controlConnectionProtocolVersion, address, _config); try { c.Init(); _connection = c; _host = host; return; } catch (UnsupportedProtocolVersionException) { _logger.Info(String.Format("Unsupported protocol version {0}, trying with a lower version", _controlConnectionProtocolVersion)); _controlConnectionProtocolVersion--; c.Dispose(); if (_controlConnectionProtocolVersion < 1) { throw new DriverInternalError("Invalid protocol version"); } //Retry using the new protocol version Connect(firstTime); return; } catch (Exception ex) { //There was a socket exception or an authentication exception triedHosts.Add(host.Address, ex); c.Dispose(); } } throw new NoHostAvailableException(triedHosts); } internal void Refresh(bool reconnect = false, bool throwExceptions = false) { lock (_refreshLock) { try { if (reconnect) { Unsubscribe(); Connect(false); SubscribeEventHandlers(); } RefreshNodeList(); Metadata.RefreshKeyspaces(false); _reconnectionSchedule = _reconnectionPolicy.NewSchedule(); } catch (Exception ex) { _logger.Error("There was an error when trying to refresh the ControlConnection", ex); _reconnectionTimer.Change(_reconnectionSchedule.NextDelayMs(), Timeout.Infinite); if (throwExceptions) { throw; } } } } public void Shutdown() { if (Interlocked.Increment(ref _isShutdown) != 1) { //Only shutdown once return; } var c = _connection; if (c != null) { c.Dispose(); } _reconnectionTimer.Change(Timeout.Infinite, Timeout.Infinite); _reconnectionTimer.Dispose(); } /// <summary> /// Gets the next connection and setup the event listener for the host and connection. /// Not thread-safe. /// </summary> private void SubscribeEventHandlers() { _host.Down += OnHostDown; _connection.CassandraEventResponse += OnConnectionCassandraEvent; //Register to events on the connection var registerTask = _connection.Send(new RegisterForEventRequest(_controlConnectionProtocolVersion, CassandraEventTypes)); TaskHelper.WaitToComplete(registerTask, 10000); if (!(registerTask.Result is ReadyResponse)) { throw new DriverInternalError("Expected ReadyResponse, obtained " + registerTask.Result.GetType().Name); } } private void Unsubscribe() { var c = _connection; var h = _host; if (c != null) { c.CassandraEventResponse -= OnConnectionCassandraEvent; } if (h != null) { h.Down -= OnHostDown; } } private void OnHostDown(Host h, DateTimeOffset nextUpTime) { h.Down -= OnHostDown; _logger.Warning("Host " + h.Address + " used by the ControlConnection DOWN"); Task.Factory.StartNew(() => Refresh(true), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); } private void OnConnectionCassandraEvent(object sender, CassandraEventArgs e) { Task.Factory.StartNew(() => { if (e is TopologyChangeEventArgs) { var tce = (TopologyChangeEventArgs) e; if (tce.What == TopologyChangeEventArgs.Reason.NewNode) { Refresh(false); return; } if (tce.What == TopologyChangeEventArgs.Reason.RemovedNode) { Refresh(false); return; } } if (e is StatusChangeEventArgs) { var sce = (StatusChangeEventArgs) e; //The address in the Cassandra event message needs to be translated var address = TranslateAddress(sce.Address); if (sce.What == StatusChangeEventArgs.Reason.Up) { Metadata.BringUpHost(address, this); return; } if (sce.What == StatusChangeEventArgs.Reason.Down) { Metadata.SetDownHost(address, this); return; } } if (e is SchemaChangeEventArgs) { var ssc = (SchemaChangeEventArgs) e; if (!String.IsNullOrEmpty(ssc.Table)) { Metadata.RefreshTable(ssc.Keyspace, ssc.Table); return; } if (ssc.What == SchemaChangeEventArgs.Reason.Dropped) { Metadata.RemoveKeyspace(ssc.Keyspace); return; } Metadata.RefreshSingleKeyspace(ssc.What == SchemaChangeEventArgs.Reason.Created, ssc.Keyspace); } }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); } private IPEndPoint TranslateAddress(IPEndPoint value) { return _config.AddressTranslator.Translate(value); } private void RefreshNodeList() { _logger.Info("Refreshing node list"); var localRow = Query(SelectLocal).FirstOrDefault(); var rsPeers = Query(SelectPeers); if (localRow == null) { _logger.Error("Local host metadata could not be retrieved"); return; } Metadata.Partitioner = localRow.GetValue<string>("partitioner"); int protocolVersion; if (localRow.GetColumn("native_protocol_version") != null && Int32.TryParse(localRow.GetValue<string>("native_protocol_version"), out protocolVersion)) { //In Cassandra < 2 // there is no native protocol version column, it will get the default value _protocolVersion = protocolVersion; } UpdateLocalInfo(localRow); UpdatePeersInfo(rsPeers); _logger.Info("Node list retrieved successfully"); } internal void UpdateLocalInfo(Row row) { var localhost = _host; // Update cluster name, DC and rack for the one node we are connected to var clusterName = row.GetValue<string>("cluster_name"); if (clusterName != null) { Metadata.ClusterName = clusterName; } localhost.SetLocationInfo(row.GetValue<string>("data_center"), row.GetValue<string>("rack")); localhost.Tokens = row.GetValue<IEnumerable<string>>("tokens") ?? new string[0]; } internal void UpdatePeersInfo(IEnumerable<Row> rs) { var foundPeers = new HashSet<IPEndPoint>(); foreach (var row in rs) { var address = GetAddressForPeerHost(row, _config.AddressTranslator, _config.ProtocolOptions.Port); if (address == null) { _logger.Error("No address found for host, ignoring it."); continue; } foundPeers.Add(address); var host = Metadata.GetHost(address); if (host == null) { host = Metadata.AddHost(address); } host.SetLocationInfo(row.GetValue<string>("data_center"), row.GetValue<string>("rack")); host.Tokens = row.GetValue<IEnumerable<string>>("tokens") ?? new string[0]; } // Removes all those that seems to have been removed (since we lost the control connection or not valid contact point) foreach (var address in Metadata.AllReplicas()) { if (!address.Equals(_host.Address) && !foundPeers.Contains(address)) { Metadata.RemoveHost(address); } } } /// <summary> /// Uses system.peers values to build the Address translator /// </summary> internal static IPEndPoint GetAddressForPeerHost(Row row, IAddressTranslator translator, int port) { var address = row.GetValue<IPAddress>("rpc_address"); if (address == null) { return null; } if (BindAllAddress.Equals(address) && !row.IsNull("peer")) { address = row.GetValue<IPAddress>("peer"); _logger.Warning(String.Format("Found host with 0.0.0.0 as rpc_address, using listen_address ({0}) to contact it instead. If this is incorrect you should avoid the use of 0.0.0.0 server side.", address)); } return translator.Translate(new IPEndPoint(address, port)); } /// <summary> /// Uses the active connection to execute a query /// </summary> public RowSet Query(string cqlQuery, bool retry = false) { var request = new QueryRequest(_controlConnectionProtocolVersion, cqlQuery, false, QueryProtocolOptions.Default); var task = _connection.Send(request); try { TaskHelper.WaitToComplete(task, 10000); } catch (SocketException ex) { const string message = "There was an error while executing on the host {0} the query '{1}'"; _logger.Error(String.Format(message, cqlQuery, _connection.Address), ex); if (retry) { //Try to connect to another host Refresh(reconnect:true, throwExceptions:true); //Try to execute again without retry return Query(cqlQuery, false); } throw; } return GetRowSet(task.Result); } /// <summary> /// Validates that the result contains a RowSet and returns it. /// </summary> /// <exception cref="NullReferenceException" /> /// <exception cref="DriverInternalError" /> public static RowSet GetRowSet(AbstractResponse response) { if (response == null) { throw new NullReferenceException("Response can not be null"); } if (!(response is ResultResponse)) { throw new DriverInternalError("Expected rows, obtained " + response.GetType().FullName); } var result = (ResultResponse) response; if (!(result.Output is OutputRows)) { throw new DriverInternalError("Expected rows output, obtained " + result.Output.GetType().FullName); } return ((OutputRows) result.Output).RowSet; } } }
// // enum.cs: Enum handling. // // Author: Miguel de Icaza (miguel@gnu.org) // Ravi Pratap (ravi@ximian.com) // Marek Safar (marek.safar@seznam.cz) // // Dual licensed under the terms of the MIT X11 or GNU GPL // // Copyright 2001 Ximian, Inc (http://www.ximian.com) // Copyright 2003-2003 Novell, Inc (http://www.novell.com) // using System; #if STATIC using MetaType = IKVM.Reflection.Type; using IKVM.Reflection; #else using MetaType = System.Type; using System.Reflection; #endif namespace Mono.CSharp { public class EnumMember : Const { class EnumTypeExpr : TypeExpr { protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec) { type = ec.CurrentType; return this; } public override TypeExpr ResolveAsTypeTerminal (IMemberContext ec, bool silent) { return DoResolveAsTypeStep (ec); } } public EnumMember (Enum parent, MemberName name, Attributes attrs) : base (parent, new EnumTypeExpr (), Modifiers.PUBLIC, name, attrs) { } static bool IsValidEnumType (TypeSpec t) { return (t == TypeManager.int32_type || t == TypeManager.uint32_type || t == TypeManager.int64_type || t == TypeManager.byte_type || t == TypeManager.sbyte_type || t == TypeManager.short_type || t == TypeManager.ushort_type || t == TypeManager.uint64_type || t == TypeManager.char_type || TypeManager.IsEnumType (t)); } public override Constant ConvertInitializer (ResolveContext rc, Constant expr) { if (expr is EnumConstant) expr = ((EnumConstant) expr).Child; var underlying = ((Enum) Parent).UnderlyingType; if (expr != null) { expr = expr.ImplicitConversionRequired (rc, underlying, Location); if (expr != null && !IsValidEnumType (expr.Type)) { Enum.Error_1008 (Location, Report); expr = null; } } if (expr == null) expr = New.Constantify (underlying, Location); return new EnumConstant (expr, MemberType).Resolve (rc); } public override bool Define () { if (!ResolveMemberType ()) return false; const FieldAttributes attr = FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal; FieldBuilder = Parent.TypeBuilder.DefineField (Name, MemberType.GetMetaInfo (), attr); spec = new ConstSpec (Parent.Definition, this, MemberType, FieldBuilder, ModFlags, initializer); Parent.MemberCache.AddMember (spec); return true; } } /// <summary> /// Enumeration container /// </summary> public class Enum : TypeContainer { // // Implicit enum member initializer, used when no constant value is provided // class ImplicitInitializer : Expression { readonly EnumMember prev; readonly EnumMember current; public ImplicitInitializer (EnumMember current, EnumMember prev) { this.current = current; this.prev = prev; } public override Expression CreateExpressionTree (ResolveContext ec) { throw new NotSupportedException ("Missing Resolve call"); } protected override Expression DoResolve (ResolveContext rc) { // We are the first member if (prev == null) { return New.Constantify (current.Parent.Definition, Location).Resolve (rc); } var c = ((ConstSpec) prev.Spec).GetConstant (rc) as EnumConstant; try { return c.Increment ().Resolve (rc); } catch (OverflowException) { rc.Report.Error (543, current.Location, "The enumerator value `{0}' is outside the range of enumerator underlying type `{1}'", current.GetSignatureForError (), ((Enum) current.Parent).UnderlyingType.GetSignatureForError ()); return New.Constantify (current.Parent.Definition, current.Location).Resolve (rc); } } public override void Emit (EmitContext ec) { throw new NotSupportedException ("Missing Resolve call"); } } public static readonly string UnderlyingValueField = "value__"; const Modifiers AllowedModifiers = Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE; public Enum (NamespaceEntry ns, DeclSpace parent, TypeExpression type, Modifiers mod_flags, MemberName name, Attributes attrs) : base (ns, parent, name, attrs, MemberKind.Enum) { base_type_expr = type; var accmods = IsTopLevel ? Modifiers.INTERNAL : Modifiers.PRIVATE; ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod_flags, accmods, Location, Report); spec = new EnumSpec (null, this, null, null, ModFlags); } #region Properties public override AttributeTargets AttributeTargets { get { return AttributeTargets.Enum; } } public TypeExpr BaseTypeExpression { get { return base_type_expr; } } protected override TypeAttributes TypeAttr { get { return ModifiersExtensions.TypeAttr (ModFlags, IsTopLevel) | TypeAttributes.Class | TypeAttributes.Sealed | base.TypeAttr; } } public TypeSpec UnderlyingType { get { return ((EnumSpec) spec).UnderlyingType; } } #endregion public override void Accept (StructuralVisitor visitor) { visitor.Visit (this); } public void AddEnumMember (EnumMember em) { if (em.Name == UnderlyingValueField) { Report.Error (76, em.Location, "An item in an enumeration cannot have an identifier `{0}'", UnderlyingValueField); return; } AddConstant (em); } public static void Error_1008 (Location loc, Report Report) { Report.Error (1008, loc, "Type byte, sbyte, short, ushort, int, uint, long or ulong expected"); } protected override bool DefineNestedTypes () { ((EnumSpec) spec).UnderlyingType = base_type_expr == null ? TypeManager.int32_type : base_type_expr.Type; TypeBuilder.DefineField (UnderlyingValueField, UnderlyingType.GetMetaInfo (), FieldAttributes.Public | FieldAttributes.SpecialName | FieldAttributes.RTSpecialName); return true; } protected override bool DoDefineMembers () { if (constants != null) { for (int i = 0; i < constants.Count; ++i) { EnumMember em = (EnumMember) constants [i]; if (em.Initializer == null) { em.Initializer = new ImplicitInitializer (em, i == 0 ? null : (EnumMember) constants[i - 1]); } em.Define (); } } return true; } public override bool IsUnmanagedType () { return true; } protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class) { base_type = TypeManager.enum_type; base_class = base_type_expr; return null; } protected override bool VerifyClsCompliance () { if (!base.VerifyClsCompliance ()) return false; if (UnderlyingType == TypeManager.uint32_type || UnderlyingType == TypeManager.uint64_type || UnderlyingType == TypeManager.ushort_type) { Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (UnderlyingType)); } return true; } } class EnumSpec : TypeSpec { TypeSpec underlying; public EnumSpec (TypeSpec declaringType, ITypeDefinition definition, TypeSpec underlyingType, MetaType info, Modifiers modifiers) : base (MemberKind.Enum, declaringType, definition, info, modifiers | Modifiers.SEALED) { this.underlying = underlyingType; } public TypeSpec UnderlyingType { get { return underlying; } set { if (underlying != null) throw new InternalErrorException ("UnderlyingType reset"); underlying = value; } } public static TypeSpec GetUnderlyingType (TypeSpec t) { return ((EnumSpec) t.GetDefinition ()).UnderlyingType; } } }
using System; namespace SharpVectors.Dom.Svg { public class SvgMarkerElement : SvgStyleableElement, ISvgMarkerElement, ISharpDoNotPaint, IContainerElement { internal SvgMarkerElement(string prefix, string localname, string ns, SvgDocument doc) : base(prefix, localname, ns, doc) { svgExternalResourcesRequired = new SvgExternalResourcesRequired(this); svgFitToViewBox = new SvgFitToViewBox(this); } #region Implementation of ISvgMarkerElement /// <summary> /// Sets the value of attribute orient to 'auto'. /// </summary> public void SetOrientToAuto() { orientType = null; SetAttribute("orient", "auto"); } /// <summary> /// Sets the value of attribute orient to the given angle. /// </summary> /// <param name="angle"> The angle value to use for attribute orient.</param> public void SetOrientToAngle(ISvgAngle angle) { orientType = null; SetAttribute("orient", angle.ValueAsString); orientAngle = new SvgAnimatedAngle(angle); } private ISvgAnimatedLength refX; /// <summary> /// Corresponds to attribute refX on the given 'marker' element. /// </summary> public ISvgAnimatedLength RefX { get { if(refX == null) { refX = new SvgAnimatedLength(this, "refX", SvgLengthDirection.Horizontal, "0"); } return refX; } } private ISvgAnimatedLength refY; /// <summary> /// Corresponds to attribute refY on the given 'marker' element. /// </summary> public ISvgAnimatedLength RefY { get { if(refY == null) { refY = new SvgAnimatedLength(this, "refY", SvgLengthDirection.Vertical, "0"); } return refY; } } private ISvgAnimatedEnumeration markerUnits; /// <summary> /// Corresponds to attribute markerUnits on the given 'marker' element. /// </summary> public ISvgAnimatedEnumeration MarkerUnits { get { if(markerUnits == null) { SvgMarkerUnit type = SvgMarkerUnit.Unknown; switch(GetAttribute("markerUnits")) { case "userSpaceOnUse": type = SvgMarkerUnit.UserSpaceOnUse; break; case "": case "strokeWidth": type = SvgMarkerUnit.StrokeWidth; break; } markerUnits = new SvgAnimatedEnumeration((ushort)type); } return markerUnits; } } private ISvgAnimatedLength markerWidth; /// <summary> /// Corresponds to attribute markerWidth on the given 'marker' element /// </summary> public ISvgAnimatedLength MarkerWidth { get { if(markerWidth == null) { markerWidth = new SvgAnimatedLength(this, "markerWidth", SvgLengthDirection.Horizontal, "3"); } return markerWidth; } } private ISvgAnimatedLength markerHeight; /// <summary> /// Corresponds to attribute markerHeight on the given 'marker' element. /// </summary> public ISvgAnimatedLength MarkerHeight { get { if(markerHeight == null) { markerHeight = new SvgAnimatedLength(this, "markerHeight", SvgLengthDirection.Vertical, "3"); } return markerHeight; } } private ISvgAnimatedEnumeration orientType; /// <summary> /// Corresponds to attribute orient on the given 'marker' element. One of the Marker Orientation Types defined above. /// </summary> public ISvgAnimatedEnumeration OrientType { get { if(orientType == null) { if(GetAttribute("orient") == "auto") { orientType = new SvgAnimatedEnumeration((ushort)SvgMarkerOrient.Auto); } else { orientType = new SvgAnimatedEnumeration((ushort)SvgMarkerOrient.Angle); } } return orientType; } } public ISvgAnimatedAngle orientAngle; /// <summary> /// Corresponds to attribute orient on the given 'marker' element. If markerUnits is SVG_MARKER_ORIENT_ANGLE, the angle value for attribute orient; otherwise, it will be set to zero. /// </summary> public ISvgAnimatedAngle OrientAngle { get { if(orientAngle == null) { if(OrientType.AnimVal.Equals(SvgMarkerOrient.Angle)) { orientAngle = new SvgAnimatedAngle(GetAttribute("orient"), "0"); } else { orientAngle = new SvgAnimatedAngle("0", "0"); } } return orientAngle; } } #endregion #region Implementation of ISvgFitToViewBox private SvgFitToViewBox svgFitToViewBox; public ISvgAnimatedRect ViewBox { get { return svgFitToViewBox.ViewBox; } } public ISvgAnimatedPreserveAspectRatio PreserveAspectRatio { get { return svgFitToViewBox.PreserveAspectRatio; } } #endregion #region Implementation of ISvgExternalResourcesRequired private SvgExternalResourcesRequired svgExternalResourcesRequired; public ISvgAnimatedBoolean ExternalResourcesRequired { get { return svgExternalResourcesRequired.ExternalResourcesRequired; } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32.SafeHandles; using System.Text; using System.Runtime.InteropServices; using System.ComponentModel; using System.Diagnostics; using System; using System.Collections.Generic; using System.Threading; using System.Globalization; using System.Security; namespace System.ServiceProcess { /// This class represents an NT service. It allows you to connect to a running or stopped service /// and manipulate it or get information about it. public class ServiceController : IDisposable { private readonly string _machineName; private readonly ManualResetEvent _waitForStatusSignal = new ManualResetEvent(false); private const string DefaultMachineName = "."; private string _name; private string _eitherName; private string _displayName; private int _commandsAccepted; private bool _statusGenerated; private bool _startTypeInitialized; private int _type; private bool _disposed; private SafeServiceHandle _serviceManagerHandle; private ServiceControllerStatus _status; private ServiceController[] _dependentServices; private ServiceController[] _servicesDependedOn; private ServiceStartMode _startType; private const int SERVICENAMEMAXLENGTH = 80; private const int DISPLAYNAMEBUFFERSIZE = 256; /// Creates a ServiceController object, based on service name. public ServiceController(string name) : this(name, DefaultMachineName) { } /// Creates a ServiceController object, based on machine and service name. public ServiceController(string name, string machineName) { if (!CheckMachineName(machineName)) throw new ArgumentException(SR.Format(SR.BadMachineName, machineName)); if (string.IsNullOrEmpty(name)) throw new ArgumentException(SR.Format(SR.InvalidParameter, "name", name)); _machineName = machineName; _eitherName = name; _type = Interop.mincore.ServiceTypeOptions.SERVICE_TYPE_ALL; } /// Used by the GetServices and GetDevices methods. Avoids duplicating work by the static /// methods and our own GenerateInfo(). private ServiceController(string machineName, Interop.mincore.ENUM_SERVICE_STATUS status) { if (!CheckMachineName(machineName)) throw new ArgumentException(SR.Format(SR.BadMachineName, machineName)); _machineName = machineName; _name = status.serviceName; _displayName = status.displayName; _commandsAccepted = status.controlsAccepted; _status = (ServiceControllerStatus)status.currentState; _type = status.serviceType; _statusGenerated = true; } /// Used by the GetServicesInGroup method. private ServiceController(string machineName, Interop.mincore.ENUM_SERVICE_STATUS_PROCESS status) { if (!CheckMachineName(machineName)) throw new ArgumentException(SR.Format(SR.BadMachineName, machineName)); _machineName = machineName; _name = status.serviceName; _displayName = status.displayName; _commandsAccepted = status.controlsAccepted; _status = (ServiceControllerStatus)status.currentState; _type = status.serviceType; _statusGenerated = true; } /// Tells if the service referenced by this object can be paused. public bool CanPauseAndContinue { get { GenerateStatus(); return (_commandsAccepted & Interop.mincore.AcceptOptions.ACCEPT_PAUSE_CONTINUE) != 0; } } /// Tells if the service is notified when system shutdown occurs. public bool CanShutdown { get { GenerateStatus(); return (_commandsAccepted & Interop.mincore.AcceptOptions.ACCEPT_SHUTDOWN) != 0; } } /// Tells if the service referenced by this object can be stopped. public bool CanStop { get { GenerateStatus(); return (_commandsAccepted & Interop.mincore.AcceptOptions.ACCEPT_STOP) != 0; } } /// The descriptive name shown for this service in the Service applet. public string DisplayName { get { if (_displayName == null) GenerateNames(); return _displayName; } } /// The set of services that depend on this service. These are the services that will be stopped if /// this service is stopped. public ServiceController[] DependentServices { get { if (_dependentServices == null) { IntPtr serviceHandle = GetServiceHandle(Interop.mincore.ServiceOptions.SERVICE_ENUMERATE_DEPENDENTS); try { // figure out how big a buffer we need to get the info int bytesNeeded = 0; int numEnumerated = 0; bool result = Interop.mincore.EnumDependentServices(serviceHandle, Interop.mincore.ServiceState.SERVICE_STATE_ALL, IntPtr.Zero, 0, ref bytesNeeded, ref numEnumerated); if (result) { _dependentServices = Array.Empty<ServiceController>(); return _dependentServices; } int lastError = Marshal.GetLastWin32Error(); if (lastError != Interop.mincore.Errors.ERROR_MORE_DATA) throw new Win32Exception(lastError); // allocate the buffer IntPtr enumBuffer = Marshal.AllocHGlobal((IntPtr)bytesNeeded); try { // get all the info result = Interop.mincore.EnumDependentServices(serviceHandle, Interop.mincore.ServiceState.SERVICE_STATE_ALL, enumBuffer, bytesNeeded, ref bytesNeeded, ref numEnumerated); if (!result) throw new Win32Exception(); // for each of the entries in the buffer, create a new ServiceController object. _dependentServices = new ServiceController[numEnumerated]; for (int i = 0; i < numEnumerated; i++) { Interop.mincore.ENUM_SERVICE_STATUS status = new Interop.mincore.ENUM_SERVICE_STATUS(); IntPtr structPtr = (IntPtr)((long)enumBuffer + (i * Marshal.SizeOf<Interop.mincore.ENUM_SERVICE_STATUS>())); Marshal.PtrToStructure(structPtr, status); _dependentServices[i] = new ServiceController(_machineName, status); } } finally { Marshal.FreeHGlobal(enumBuffer); } } finally { Interop.mincore.CloseServiceHandle(serviceHandle); } } return _dependentServices; } } /// The name of the machine on which this service resides. public string MachineName { get { return _machineName; } } /// Returns the short name of the service referenced by this object. public string ServiceName { get { if (_name == null) GenerateNames(); return _name; } } public unsafe ServiceController[] ServicesDependedOn { get { if (_servicesDependedOn != null) return _servicesDependedOn; IntPtr serviceHandle = GetServiceHandle(Interop.mincore.ServiceOptions.SERVICE_QUERY_CONFIG); try { int bytesNeeded = 0; bool success = Interop.mincore.QueryServiceConfig(serviceHandle, IntPtr.Zero, 0, out bytesNeeded); if (success) { _servicesDependedOn = Array.Empty<ServiceController>(); return _servicesDependedOn; } int lastError = Marshal.GetLastWin32Error(); if (lastError != Interop.mincore.Errors.ERROR_INSUFFICIENT_BUFFER) throw new Win32Exception(lastError); // get the info IntPtr bufPtr = Marshal.AllocHGlobal((IntPtr)bytesNeeded); try { success = Interop.mincore.QueryServiceConfig(serviceHandle, bufPtr, bytesNeeded, out bytesNeeded); if (!success) throw new Win32Exception(Marshal.GetLastWin32Error()); Interop.mincore.QUERY_SERVICE_CONFIG config = new Interop.mincore.QUERY_SERVICE_CONFIG(); Marshal.PtrToStructure(bufPtr, config); Dictionary<string, ServiceController> dependencyHash = null; char* dependencyChar = config.lpDependencies; if (dependencyChar != null) { // lpDependencies points to the start of multiple null-terminated strings. The list is // double-null terminated. int length = 0; dependencyHash = new Dictionary<string, ServiceController>(); while (*(dependencyChar + length) != '\0') { length++; if (*(dependencyChar + length) == '\0') { string dependencyNameStr = new string(dependencyChar, 0, length); dependencyChar = dependencyChar + length + 1; length = 0; if (dependencyNameStr.StartsWith("+", StringComparison.Ordinal)) { // this entry is actually a service load group Interop.mincore.ENUM_SERVICE_STATUS_PROCESS[] loadGroup = GetServicesInGroup(_machineName, dependencyNameStr.Substring(1)); foreach (Interop.mincore.ENUM_SERVICE_STATUS_PROCESS groupMember in loadGroup) { if (!dependencyHash.ContainsKey(groupMember.serviceName)) dependencyHash.Add(groupMember.serviceName, new ServiceController(MachineName, groupMember)); } } else { if (!dependencyHash.ContainsKey(dependencyNameStr)) dependencyHash.Add(dependencyNameStr, new ServiceController(dependencyNameStr, MachineName)); } } } } if (dependencyHash != null) { _servicesDependedOn = new ServiceController[dependencyHash.Count]; dependencyHash.Values.CopyTo(_servicesDependedOn, 0); } else { _servicesDependedOn = Array.Empty<ServiceController>(); } return _servicesDependedOn; } finally { Marshal.FreeHGlobal(bufPtr); } } finally { Interop.mincore.CloseServiceHandle(serviceHandle); } } } public ServiceStartMode StartType { get { if (_startTypeInitialized) return _startType; IntPtr serviceHandle = IntPtr.Zero; try { serviceHandle = GetServiceHandle(Interop.mincore.ServiceOptions.SERVICE_QUERY_CONFIG); int bytesNeeded = 0; bool success = Interop.mincore.QueryServiceConfig(serviceHandle, IntPtr.Zero, 0, out bytesNeeded); int lastError = Marshal.GetLastWin32Error(); if (lastError != Interop.mincore.Errors.ERROR_INSUFFICIENT_BUFFER) throw new Win32Exception(lastError); // get the info IntPtr bufPtr = IntPtr.Zero; try { bufPtr = Marshal.AllocHGlobal((IntPtr)bytesNeeded); success = Interop.mincore.QueryServiceConfig(serviceHandle, bufPtr, bytesNeeded, out bytesNeeded); if (!success) throw new Win32Exception(Marshal.GetLastWin32Error()); Interop.mincore.QUERY_SERVICE_CONFIG config = new Interop.mincore.QUERY_SERVICE_CONFIG(); Marshal.PtrToStructure(bufPtr, config); _startType = (ServiceStartMode)config.dwStartType; _startTypeInitialized = true; } finally { if (bufPtr != IntPtr.Zero) Marshal.FreeHGlobal(bufPtr); } } finally { if (serviceHandle != IntPtr.Zero) Interop.mincore.CloseServiceHandle(serviceHandle); } return _startType; } } public SafeHandle ServiceHandle { get { return new SafeServiceHandle(GetServiceHandle(Interop.mincore.ServiceOptions.SERVICE_ALL_ACCESS)); } } /// Gets the status of the service referenced by this object, e.g., Running, Stopped, etc. public ServiceControllerStatus Status { get { GenerateStatus(); return _status; } } /// Gets the type of service that this object references. public ServiceType ServiceType { get { GenerateStatus(); return (ServiceType)_type; } } private static bool CheckMachineName(string value) { return !string.IsNullOrWhiteSpace(value) && value.IndexOf('\\') == -1; } private void Close() { } public void Dispose() { Dispose(true); } /// Disconnects this object from the service and frees any allocated resources. protected virtual void Dispose(bool disposing) { if (_serviceManagerHandle != null) { _serviceManagerHandle.Dispose(); _serviceManagerHandle = null; } _statusGenerated = false; _startTypeInitialized = false; _type = Interop.mincore.ServiceTypeOptions.SERVICE_TYPE_ALL; _disposed = true; } private unsafe void GenerateStatus() { if (!_statusGenerated) { IntPtr serviceHandle = GetServiceHandle(Interop.mincore.ServiceOptions.SERVICE_QUERY_STATUS); try { Interop.mincore.SERVICE_STATUS svcStatus = new Interop.mincore.SERVICE_STATUS(); bool success = Interop.mincore.QueryServiceStatus(serviceHandle, &svcStatus); if (!success) throw new Win32Exception(Marshal.GetLastWin32Error()); _commandsAccepted = svcStatus.controlsAccepted; _status = (ServiceControllerStatus)svcStatus.currentState; _type = svcStatus.serviceType; _statusGenerated = true; } finally { Interop.mincore.CloseServiceHandle(serviceHandle); } } } private unsafe void GenerateNames() { if (_machineName.Length == 0) throw new ArgumentException(SR.NoMachineName); IntPtr databaseHandle = IntPtr.Zero; IntPtr memory = IntPtr.Zero; int bytesNeeded; int servicesReturned; int resumeHandle = 0; try { databaseHandle = GetDataBaseHandleWithEnumerateAccess(_machineName); Interop.mincore.EnumServicesStatusEx( databaseHandle, Interop.mincore.ServiceControllerOptions.SC_ENUM_PROCESS_INFO, Interop.mincore.ServiceTypeOptions.SERVICE_TYPE_WIN32, Interop.mincore.StatusOptions.STATUS_ALL, IntPtr.Zero, 0, out bytesNeeded, out servicesReturned, ref resumeHandle, null); memory = Marshal.AllocHGlobal(bytesNeeded); Interop.mincore.EnumServicesStatusEx( databaseHandle, Interop.mincore.ServiceControllerOptions.SC_ENUM_PROCESS_INFO, Interop.mincore.ServiceTypeOptions.SERVICE_TYPE_WIN32, Interop.mincore.StatusOptions.STATUS_ALL, memory, bytesNeeded, out bytesNeeded, out servicesReturned, ref resumeHandle, null); // Since the service name of one service cannot be equal to the // service or display name of another service, we can safely // loop through all services checking if either the service or // display name matches the user given name. If there is a // match, then we've found the service. for (int i = 0; i < servicesReturned; i++) { IntPtr structPtr = (IntPtr)((long)memory + (i * Marshal.SizeOf<Interop.mincore.ENUM_SERVICE_STATUS_PROCESS>())); Interop.mincore.ENUM_SERVICE_STATUS_PROCESS status = new Interop.mincore.ENUM_SERVICE_STATUS_PROCESS(); Marshal.PtrToStructure(structPtr, status); if (string.Equals(_eitherName, status.serviceName, StringComparison.OrdinalIgnoreCase) || string.Equals(_eitherName, status.displayName, StringComparison.OrdinalIgnoreCase)) { if (_name == null) { _name = status.serviceName; } if (_displayName == null) { _displayName = status.displayName; } _eitherName = string.Empty; return; } } throw new InvalidOperationException(SR.Format(SR.NoService, _eitherName, _machineName)); } finally { Marshal.FreeHGlobal(memory); if (databaseHandle != IntPtr.Zero) { Interop.mincore.CloseServiceHandle(databaseHandle); } } } private static IntPtr GetDataBaseHandleWithAccess(string machineName, int serviceControlManagerAccess) { IntPtr databaseHandle = IntPtr.Zero; if (machineName.Equals(DefaultMachineName) || machineName.Length == 0) { databaseHandle = Interop.mincore.OpenSCManager(null, null, serviceControlManagerAccess); } else { databaseHandle = Interop.mincore.OpenSCManager(machineName, null, serviceControlManagerAccess); } if (databaseHandle == IntPtr.Zero) { Exception inner = new Win32Exception(Marshal.GetLastWin32Error()); throw new InvalidOperationException(SR.Format(SR.OpenSC, machineName), inner); } return databaseHandle; } private void GetDataBaseHandleWithConnectAccess() { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } // get a handle to SCM with connect access and store it in serviceManagerHandle field. if (_serviceManagerHandle == null) { _serviceManagerHandle = new SafeServiceHandle(GetDataBaseHandleWithAccess(_machineName, Interop.mincore.ServiceControllerOptions.SC_MANAGER_CONNECT)); } } private static IntPtr GetDataBaseHandleWithEnumerateAccess(string machineName) { return GetDataBaseHandleWithAccess(machineName, Interop.mincore.ServiceControllerOptions.SC_MANAGER_ENUMERATE_SERVICE); } /// Gets all the device-driver services on the local machine. public static ServiceController[] GetDevices() { return GetDevices(DefaultMachineName); } /// Gets all the device-driver services in the machine specified. public static ServiceController[] GetDevices(string machineName) { return GetServicesOfType(machineName, Interop.mincore.ServiceTypeOptions.SERVICE_TYPE_DRIVER); } /// Opens a handle for the current service. The handle must be closed with /// a call to Interop.CloseServiceHandle(). private IntPtr GetServiceHandle(int desiredAccess) { GetDataBaseHandleWithConnectAccess(); IntPtr serviceHandle = Interop.mincore.OpenService(_serviceManagerHandle.DangerousGetHandle(), ServiceName, desiredAccess); if (serviceHandle == IntPtr.Zero) { Exception inner = new Win32Exception(Marshal.GetLastWin32Error()); throw new InvalidOperationException(SR.Format(SR.OpenService, ServiceName, _machineName), inner); } return serviceHandle; } /// Gets the services (not including device-driver services) on the local machine. public static ServiceController[] GetServices() { return GetServices(DefaultMachineName); } /// Gets the services (not including device-driver services) on the machine specified. public static ServiceController[] GetServices(string machineName) { return GetServicesOfType(machineName, Interop.mincore.ServiceTypeOptions.SERVICE_TYPE_WIN32); } /// Helper function for ServicesDependedOn. private static Interop.mincore.ENUM_SERVICE_STATUS_PROCESS[] GetServicesInGroup(string machineName, string group) { return GetServices<Interop.mincore.ENUM_SERVICE_STATUS_PROCESS>(machineName, Interop.mincore.ServiceTypeOptions.SERVICE_TYPE_WIN32, group, status => { return status; }); } /// Helper function for GetDevices and GetServices. private static ServiceController[] GetServicesOfType(string machineName, int serviceType) { if (!CheckMachineName(machineName)) throw new ArgumentException(SR.Format(SR.BadMachineName, machineName)); return GetServices<ServiceController>(machineName, serviceType, null, status => { return new ServiceController(machineName, status); }); } /// Helper for GetDevices, GetServices, and ServicesDependedOn private static T[] GetServices<T>(string machineName, int serviceType, string group, Func<Interop.mincore.ENUM_SERVICE_STATUS_PROCESS, T> selector) { IntPtr databaseHandle = IntPtr.Zero; IntPtr memory = IntPtr.Zero; int bytesNeeded; int servicesReturned; int resumeHandle = 0; T[] services; try { databaseHandle = GetDataBaseHandleWithEnumerateAccess(machineName); Interop.mincore.EnumServicesStatusEx( databaseHandle, Interop.mincore.ServiceControllerOptions.SC_ENUM_PROCESS_INFO, serviceType, Interop.mincore.StatusOptions.STATUS_ALL, IntPtr.Zero, 0, out bytesNeeded, out servicesReturned, ref resumeHandle, group); memory = Marshal.AllocHGlobal((IntPtr)bytesNeeded); // // Get the set of services // Interop.mincore.EnumServicesStatusEx( databaseHandle, Interop.mincore.ServiceControllerOptions.SC_ENUM_PROCESS_INFO, serviceType, Interop.mincore.StatusOptions.STATUS_ALL, memory, bytesNeeded, out bytesNeeded, out servicesReturned, ref resumeHandle, group); // // Go through the block of memory it returned to us and select the results // services = new T[servicesReturned]; for (int i = 0; i < servicesReturned; i++) { IntPtr structPtr = (IntPtr)((long)memory + (i * Marshal.SizeOf<Interop.mincore.ENUM_SERVICE_STATUS_PROCESS>())); Interop.mincore.ENUM_SERVICE_STATUS_PROCESS status = new Interop.mincore.ENUM_SERVICE_STATUS_PROCESS(); Marshal.PtrToStructure(structPtr, status); services[i] = selector(status); } } finally { Marshal.FreeHGlobal(memory); if (databaseHandle != IntPtr.Zero) { Interop.mincore.CloseServiceHandle(databaseHandle); } } return services; } /// Suspends a service's operation. public unsafe void Pause() { IntPtr serviceHandle = GetServiceHandle(Interop.mincore.ServiceOptions.SERVICE_PAUSE_CONTINUE); try { Interop.mincore.SERVICE_STATUS status = new Interop.mincore.SERVICE_STATUS(); bool result = Interop.mincore.ControlService(serviceHandle, Interop.mincore.ControlOptions.CONTROL_PAUSE, &status); if (!result) { Exception inner = new Win32Exception(Marshal.GetLastWin32Error()); throw new InvalidOperationException(SR.Format(SR.PauseService, ServiceName, _machineName), inner); } } finally { Interop.mincore.CloseServiceHandle(serviceHandle); } } /// Continues a service after it has been paused. public unsafe void Continue() { IntPtr serviceHandle = GetServiceHandle(Interop.mincore.ServiceOptions.SERVICE_PAUSE_CONTINUE); try { Interop.mincore.SERVICE_STATUS status = new Interop.mincore.SERVICE_STATUS(); bool result = Interop.mincore.ControlService(serviceHandle, Interop.mincore.ControlOptions.CONTROL_CONTINUE, &status); if (!result) { Exception inner = new Win32Exception(Marshal.GetLastWin32Error()); throw new InvalidOperationException(SR.Format(SR.ResumeService, ServiceName, _machineName), inner); } } finally { Interop.mincore.CloseServiceHandle(serviceHandle); } } /// Refreshes all property values. public void Refresh() { _statusGenerated = false; _startTypeInitialized = false; _dependentServices = null; _servicesDependedOn = null; } /// Starts the service. public void Start() { Start(Array.Empty<string>()); } /// Starts a service in the machine specified. public void Start(string[] args) { if (args == null) throw new ArgumentNullException("args"); IntPtr serviceHandle = GetServiceHandle(Interop.mincore.ServiceOptions.SERVICE_START); try { IntPtr[] argPtrs = new IntPtr[args.Length]; int i = 0; try { for (i = 0; i < args.Length; i++) { if (args[i] == null) throw new ArgumentNullException(SR.ArgsCantBeNull, "args"); argPtrs[i] = Marshal.StringToHGlobalUni(args[i]); } } catch { for (int j = 0; j < i; j++) Marshal.FreeHGlobal(argPtrs[i]); throw; } GCHandle argPtrsHandle = new GCHandle(); try { argPtrsHandle = GCHandle.Alloc(argPtrs, GCHandleType.Pinned); bool result = Interop.mincore.StartService(serviceHandle, args.Length, (IntPtr)argPtrsHandle.AddrOfPinnedObject()); if (!result) { Exception inner = new Win32Exception(Marshal.GetLastWin32Error()); throw new InvalidOperationException(SR.Format(SR.CannotStart, ServiceName, _machineName), inner); } } finally { for (i = 0; i < args.Length; i++) Marshal.FreeHGlobal(argPtrs[i]); if (argPtrsHandle.IsAllocated) argPtrsHandle.Free(); } } finally { Interop.mincore.CloseServiceHandle(serviceHandle); } } /// Stops the service. If any other services depend on this one for operation, /// they will be stopped first. The DependentServices property lists this set /// of services. public unsafe void Stop() { IntPtr serviceHandle = GetServiceHandle(Interop.mincore.ServiceOptions.SERVICE_STOP); try { // Before stopping this service, stop all the dependent services that are running. // (It's OK not to cache the result of getting the DependentServices property because it caches on its own.) for (int i = 0; i < DependentServices.Length; i++) { ServiceController currentDependent = DependentServices[i]; currentDependent.Refresh(); if (currentDependent.Status != ServiceControllerStatus.Stopped) { currentDependent.Stop(); currentDependent.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 30)); } } Interop.mincore.SERVICE_STATUS status = new Interop.mincore.SERVICE_STATUS(); bool result = Interop.mincore.ControlService(serviceHandle, Interop.mincore.ControlOptions.CONTROL_STOP, &status); if (!result) { Exception inner = new Win32Exception(Marshal.GetLastWin32Error()); throw new InvalidOperationException(SR.Format(SR.StopService, ServiceName, _machineName), inner); } } finally { Interop.mincore.CloseServiceHandle(serviceHandle); } } /// Waits infinitely until the service has reached the given status. public void WaitForStatus(ServiceControllerStatus desiredStatus) { WaitForStatus(desiredStatus, TimeSpan.MaxValue); } /// Waits until the service has reached the given status or until the specified time /// has expired public void WaitForStatus(ServiceControllerStatus desiredStatus, TimeSpan timeout) { if (!Enum.IsDefined(typeof(ServiceControllerStatus), desiredStatus)) throw new ArgumentException(SR.Format(SR.InvalidEnumArgument, "desiredStatus", (int)desiredStatus, typeof(ServiceControllerStatus))); DateTime start = DateTime.UtcNow; Refresh(); while (Status != desiredStatus) { if (DateTime.UtcNow - start > timeout) throw new System.ServiceProcess.TimeoutException(SR.Timeout); _waitForStatusSignal.WaitOne(250); Refresh(); } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System.Diagnostics.Contracts; using System; namespace System.Globalization { public class DateTimeFormatInfo { extern public string UniversalSortableDateTimePattern { get; } public CalendarWeekRule CalendarWeekRule { get { return default(CalendarWeekRule); } set { Contract.Requires((int)value >= 0); Contract.Requires((int)value <= 2); } } public string AMDesignator { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } set { Contract.Requires(value != null); } } public String[] DayNames { get { Contract.Ensures(Contract.Result<string[]>() != null); Contract.Ensures(Contract.Result<string[]>().Length == 7); return default(string[]); } set { Contract.Requires(value != null); Contract.Requires(value.Length == 7); } } public string ShortTimePattern { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } set { Contract.Requires(value != null); } } public string ShortDatePattern { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } set { Contract.Requires(value != null); } } public DayOfWeek FirstDayOfWeek { get { Contract.Ensures((int)Contract.Result<DayOfWeek>() >= 0); Contract.Ensures((int)Contract.Result<DayOfWeek>() <= 6); return default(DayOfWeek); } set { Contract.Requires((int)value >= 0); Contract.Requires((int)value <= 6); } } extern public static DateTimeFormatInfo CurrentInfo { get; } public String[] MonthNames { get { Contract.Ensures(Contract.Result<string[]>() != null); Contract.Ensures(Contract.Result<string[]>().Length == 13); return default(string[]); } set { Contract.Requires(value != null); Contract.Requires(value.Length == 13); } } public String[] AbbreviatedMonthNames { get { Contract.Ensures(Contract.Result<string[]>() != null); Contract.Ensures(Contract.Result<string[]>().Length == 13); return default(string[]); } set { Contract.Requires(value != null); Contract.Requires(value.Length == 13); } } public string PMDesignator { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } set { Contract.Requires(value != null); } } public String[] AbbreviatedDayNames { get { Contract.Ensures(Contract.Result<string[]>() != null); Contract.Ensures(Contract.Result<string[]>().Length == 7); return default(string[]); } set { Contract.Requires(value != null); Contract.Requires(value.Length == 7); } } #if !SILVERLIGHT public string DateSeparator { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } set { Contract.Requires(value != null); } } #endif public string FullDateTimePattern { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } set { Contract.Requires(value != null); } } #if !SILVERLIGHT public string TimeSeparator { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } set { Contract.Requires(value != null); } } #endif public Calendar Calendar { get { Contract.Ensures(Contract.Result<Calendar>() != null); return default(Calendar); } set { Contract.Requires(value != null); } } public string LongTimePattern { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } set { Contract.Requires(value != null); } } extern public static DateTimeFormatInfo InvariantInfo { get; } public string MonthDayPattern { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } set { Contract.Requires(value != null); } } public string YearMonthPattern { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } set { Contract.Requires(value != null); } } public string SortableDateTimePattern { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public string LongDatePattern { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } set { Contract.Requires(value != null); } } extern public string RFC1123Pattern { get; } extern public bool IsReadOnly { get; } public static DateTimeFormatInfo ReadOnly(DateTimeFormatInfo dtfi) { Contract.Requires(dtfi != null); Contract.Ensures(Contract.Result<DateTimeFormatInfo>() != null); Contract.Ensures(Contract.Result<DateTimeFormatInfo>().IsReadOnly); return default(DateTimeFormatInfo); } public string GetMonthName(int month) { Contract.Requires(month >= 1); Contract.Requires(month <= 13); return default(string); } public string GetAbbreviatedMonthName(int month) { Contract.Requires(month >= 1); Contract.Requires(month <= 13); return default(string); } public string GetDayName(DayOfWeek dayofweek) { Contract.Requires((int)dayofweek >= 0); Contract.Requires((int)dayofweek <= 6); return default(string); } #if !SILVERLIGHT public String[] GetAllDateTimePatterns(Char format) { Contract.Ensures(Contract.Result<String[]>() != null); return default(String[]); } public String[] GetAllDateTimePatterns() { Contract.Ensures(Contract.Result<String[]>() != null); return default(String[]); } #endif public string GetAbbreviatedDayName(DayOfWeek dayofweek) { Contract.Requires((int)dayofweek >= 0); Contract.Requires((int)dayofweek <= 6); return default(string); } public string GetAbbreviatedEraName(int era) { Contract.Requires(era >= 0); return default(string); } public string GetEraName(int era) { Contract.Requires(era >= 0); return default(string); } public int GetEra(string eraName) { Contract.Requires(eraName != null); return default(int); } public virtual object Clone() { return default(object); } public virtual object GetFormat(Type formatType) { return default(object); } public static DateTimeFormatInfo GetInstance(IFormatProvider provider) { Contract.Ensures(Contract.Result<DateTimeFormatInfo>() != null); return default(DateTimeFormatInfo); } } }
/* * Copyright (c) 2015, InWorldz Halcyon Developers * 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 halcyon nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using OpenMetaverse; namespace InWorldz.PhysxPhysics { internal class PhysUtil { public static PhysX.Math.Vector3[] OmvVectorArrayToPhysx(OpenMetaverse.Vector3[] omvArray) { PhysX.Math.Vector3[] physxArray = new PhysX.Math.Vector3[omvArray.Length]; for (int i = 0; i < omvArray.Length; ++i) { OpenMetaverse.Vector3 omvVec = omvArray[i]; physxArray[i] = new PhysX.Math.Vector3(omvVec.X, omvVec.Y, omvVec.Z); } return physxArray; } public static PhysX.Math.Vector3[] FloatArrayToVectorArray(float[] floatArray) { if (floatArray.Length % 3 != 0) throw new InvalidOperationException("Float array size must be a multiple of 3 (X,Y,Z)"); PhysX.Math.Vector3[] ret = new PhysX.Math.Vector3[floatArray.Length / 3]; for (int i = 0, j = 0; i < floatArray.Length; i += 3, ++j) { ret[j] = new PhysX.Math.Vector3(floatArray[i + 0], floatArray[i + 1], floatArray[i + 2]); } return ret; } public static PhysX.Math.Vector3 OmvVectorToPhysx(OpenMetaverse.Vector3 vec) { MakeFinite(ref vec); return new PhysX.Math.Vector3(vec.X, vec.Y, vec.Z); } public static OpenMetaverse.Vector3 PhysxVectorToOmv(PhysX.Math.Vector3 vec) { return new OpenMetaverse.Vector3(vec.X, vec.Y, vec.Z); } public static PhysX.Math.Matrix PositionToMatrix(OpenMetaverse.Vector3 position, OpenMetaverse.Quaternion rotation) { MakeFinite(ref position); MakeFinite(ref rotation); return PhysX.Math.Matrix.RotationQuaternion(new PhysX.Math.Quaternion(rotation.X, rotation.Y, rotation.Z, rotation.W)) * PhysX.Math.Matrix.Translation(position.X, position.Y, position.Z); } private static void MakeFinite(ref Quaternion rotation) { if (float.IsNaN(rotation.X) || float.IsInfinity(rotation.X)) { rotation = Quaternion.Identity; } if (float.IsNaN(rotation.Y) || float.IsInfinity(rotation.Y)) { rotation = Quaternion.Identity; } if (float.IsNaN(rotation.Z) || float.IsInfinity(rotation.Z)) { rotation = Quaternion.Identity; } if (float.IsNaN(rotation.W) || float.IsInfinity(rotation.W)) { rotation = Quaternion.Identity; } } private static void MakeFinite(ref Vector3 position) { if (float.IsNaN(position.X) || float.IsInfinity(position.X)) { position.X = 0.0f; } if (float.IsNaN(position.Y) || float.IsInfinity(position.Y)) { position.Y = 0.0f; } if (float.IsNaN(position.Z) || float.IsInfinity(position.Z)) { position.Z = 0.0f; } } public static OpenMetaverse.Vector3 DecomposeToPosition(PhysX.Math.Matrix matrix) { return new OpenMetaverse.Vector3(matrix.M41, matrix.M42, matrix.M43); } public static OpenMetaverse.Quaternion DecomposeToRotation(PhysX.Math.Matrix matrix) { PhysX.Math.Quaternion physxRot = PhysX.Math.Quaternion.RotationMatrix(matrix); return new OpenMetaverse.Quaternion(physxRot.X, physxRot.Y, physxRot.Z, physxRot.W); } public static OpenSim.Region.Physics.Manager.Pose MatrixToPose(PhysX.Math.Matrix matrix) { OpenSim.Region.Physics.Manager.Pose pose; pose.Position = DecomposeToPosition(matrix); pose.Rotation = DecomposeToRotation(matrix); return pose; } // This will make a 3rd version of the same algorithm (refactor later) public static float AngleBetween(OpenMetaverse.Quaternion a, OpenMetaverse.Quaternion b) { double aa = (a.X * a.X + a.Y * a.Y + a.Z * a.Z + a.W * a.W); double bb = (b.X * b.X + b.Y * b.Y + b.Z * b.Z + b.W * b.W); double aabb = aa * bb; if (aabb == 0) return 0.0f; double ab = (a.X * b.X + a.Y * b.Y + a.Z * b.Z + a.W * b.W); double quotient = (ab * ab) / aabb; if (quotient >= 1.0) return 0.0f; return (float)Math.Acos(2 * quotient - 1); } public static OpenMetaverse.Quaternion RotBetween(OpenMetaverse.Vector3 a, OpenMetaverse.Vector3 b) { //A and B should both be normalized double dotProduct = OpenMetaverse.Vector3.Dot(a, b); OpenMetaverse.Vector3 crossProduct = OpenMetaverse.Vector3.Cross(a, b); double magProduct = OpenMetaverse.Vector3.Mag(a) * OpenMetaverse.Vector3.Mag(b); double angle = Math.Acos(dotProduct / magProduct); OpenMetaverse.Vector3 axis = OpenMetaverse.Vector3.Normalize(crossProduct); double s = Math.Sin(angle / 2); double x = axis.X * s; double y = axis.Y * s; double z = axis.Z * s; double w = Math.Cos(angle / 2); if (Double.IsNaN(x) || Double.IsNaN(y) || Double.IsNaN(z) || Double.IsNaN(w)) return new OpenMetaverse.Quaternion(0.0f, 0.0f, 0.0f, 1.0f); return OpenMetaverse.Quaternion.Normalize(new OpenMetaverse.Quaternion((float)x, (float)y, (float)z, (float)w)); } // Returns the angle of a quaternion (see llRot2Axis for the axis) public static float Rot2Angle(OpenMetaverse.Quaternion rot) { if (rot.W > 1) // normalization needed { float length = (float)Math.Sqrt(rot.X * rot.X + rot.Y * rot.Y + rot.Z * rot.Z + rot.W * rot.W); rot.X /= length; rot.Y /= length; rot.Z /= length; rot.W /= length; } float angle = (float)(2 * Math.Acos(rot.W)); return angle; } public static OpenMetaverse.Quaternion AxisAngle2Rot(OpenMetaverse.Vector3 axis, float angle) { double x, y, z, s, t; s = Math.Cos(angle / 2); t = Math.Sin(angle / 2); // temp value to avoid 2 more sin() calcs x = axis.X * t; y = axis.Y * t; z = axis.Z * t; return new OpenMetaverse.Quaternion((float)x, (float)y, (float)z, (float)s); } public static OpenMetaverse.Vector3 Rot2Axis(OpenMetaverse.Quaternion rot) { double x, y, z; if (rot.W < 0f) { //negate to prevent NaN in sqrt after normalization is applied rot = Quaternion.Negate(rot); } if (rot.W > 1) // normalization needed { float length = (float)Math.Sqrt(rot.X * rot.X + rot.Y * rot.Y + rot.Z * rot.Z + rot.W * rot.W); rot.X /= length; rot.Y /= length; rot.Z /= length; rot.W /= length; } // double angle = 2 * Math.Acos(rot.s); double s = Math.Sqrt(1 - rot.W * rot.W); if (s < 0.001) { x = 1; y = z = 0; } else { x = rot.X / s; // normalize axis y = rot.Y / s; z = rot.Z / s; } return new OpenMetaverse.Vector3((float)x, (float)y, (float)z); } public static OpenMetaverse.Vector3 Rot2Euler(OpenMetaverse.Quaternion r) { OpenMetaverse.Vector3 v = new OpenMetaverse.Vector3(0.0f, 0.0f, 1.0f) * r; // Z axis unit vector unaffected by Z rotation component of r. double m = OpenMetaverse.Vector3.Mag(v); // Just in case v isn't normalized, need magnitude for Asin() operation later. if (m == 0.0) return new OpenMetaverse.Vector3(); double x = Math.Atan2(-v.Y, v.Z); double sin = v.X / m; if (sin < -0.999999 || sin > 0.999999) x = 0.0; // Force X rotation to 0 at the singularities. double y = Math.Asin(sin); // Rotate X axis unit vector by r and unwind the X and Y rotations leaving only the Z rotation v = new OpenMetaverse.Vector3(1.0f, 0.0f, 0.0f) * ((r * new OpenMetaverse.Quaternion((float)Math.Sin(-x / 2.0), 0.0f, 0.0f, (float)Math.Cos(-x / 2.0))) * new OpenMetaverse.Quaternion(0.0f, (float)Math.Sin(-y / 2.0), 0.0f, (float)Math.Cos(-y / 2.0))); double z = Math.Atan2(v.Y, v.X); return new OpenMetaverse.Vector3((float)x, (float)y, (float)z); } public static OpenMetaverse.Quaternion Euler2Rot(OpenMetaverse.Vector3 v) { float x, y, z, s; double c1 = Math.Cos(v.X / 2.0); double c2 = Math.Cos(v.Y / 2.0); double c3 = Math.Cos(v.Z / 2.0); double s1 = Math.Sin(v.X / 2.0); double s2 = Math.Sin(v.Y / 2.0); double s3 = Math.Sin(v.Z / 2.0); x = (float)(s1 * c2 * c3 + c1 * s2 * s3); y = (float)(c1 * s2 * c3 - s1 * c2 * s3); z = (float)(s1 * s2 * c3 + c1 * c2 * s3); s = (float)(c1 * c2 * c3 - s1 * s2 * s3); // Normalize the results to LL "lindle" precision format // (matching visual/viewer precision of 5 decimal places) OpenMetaverse.Quaternion rot = OpenMetaverse.Quaternion.Normalize(new OpenMetaverse.Quaternion(x, y, z, s)); return rot; } } }
// *********************************************************************** // Copyright (c) 2008 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** #if !PORTABLE && !NETSTANDARD1_6 using System; using System.Reflection; namespace NUnit.Framework.Internal { [TestFixture] public class RuntimeFrameworkTests { static RuntimeType currentRuntime = Type.GetType("Mono.Runtime", false) != null ? RuntimeType.Mono : RuntimeType.Net; [Test] public void CanGetCurrentFramework() { RuntimeFramework framework = RuntimeFramework.CurrentFramework; Assert.That(framework.Runtime, Is.EqualTo(currentRuntime), "#1"); Assert.That(framework.ClrVersion, Is.EqualTo(Environment.Version), "#2"); } #if NET_4_5 [Test] public void TargetFrameworkIsSetCorrectly() { // We use reflection so it will compile and pass on Mono, // including older versions that do not have the property. var prop = typeof(AppDomainSetup).GetProperty("FrameworkName"); Assume.That(prop, Is.Not.Null); Assert.That( prop.GetValue(AppDomain.CurrentDomain.SetupInformation), Is.EqualTo(".NETFramework,Version=v4.5")); } [Test] public void DoesNotRunIn40CompatibilityModeWhenCompiled45() { var uri = new Uri( "http://host.com/path./" ); var uriStr = uri.ToString(); Assert.AreEqual( "http://host.com/path./", uriStr ); } #elif NET_4_0 [Test] [Platform(Exclude = "Mono", Reason = "Mono does not run assemblies targeting 4.0 in compatibility mode")] public void RunsIn40CompatibilityModeWhenCompiled40() { var uri = new Uri("http://host.com/path./"); var uriStr = uri.ToString(); Assert.AreEqual("http://host.com/path/", uriStr); } #endif [Test] public void CurrentFrameworkHasBuildSpecified() { Assert.That(RuntimeFramework.CurrentFramework.ClrVersion.Build, Is.GreaterThan(0)); } [TestCaseSource("frameworkData")] public void CanCreateUsingFrameworkVersion(FrameworkData data) { RuntimeFramework framework = new RuntimeFramework(data.runtime, data.frameworkVersion); Assert.AreEqual(data.runtime, framework.Runtime, "#1"); Assert.AreEqual(data.frameworkVersion, framework.FrameworkVersion, "#2"); Assert.AreEqual(data.clrVersion, framework.ClrVersion, "#3"); } [TestCaseSource("frameworkData")] public void CanCreateUsingClrVersion(FrameworkData data) { Assume.That(data.frameworkVersion.Major != 3, "#0"); RuntimeFramework framework = new RuntimeFramework(data.runtime, data.clrVersion); Assert.AreEqual(data.runtime, framework.Runtime, "#1"); Assert.AreEqual(data.frameworkVersion, framework.FrameworkVersion, "#2"); Assert.AreEqual(data.clrVersion, framework.ClrVersion, "#3"); } [TestCaseSource("frameworkData")] public void CanParseRuntimeFramework(FrameworkData data) { RuntimeFramework framework = RuntimeFramework.Parse(data.representation); Assert.AreEqual(data.runtime, framework.Runtime, "#1"); Assert.AreEqual(data.clrVersion, framework.ClrVersion, "#2"); } [TestCaseSource("frameworkData")] public void CanDisplayFrameworkAsString(FrameworkData data) { RuntimeFramework framework = new RuntimeFramework(data.runtime, data.frameworkVersion); Assert.AreEqual(data.representation, framework.ToString(), "#1"); Assert.AreEqual(data.displayName, framework.DisplayName, "#2"); } [TestCaseSource("matchData")] public bool CanMatchRuntimes(RuntimeFramework f1, RuntimeFramework f2) { return f1.Supports(f2); } internal static TestCaseData[] matchData = new TestCaseData[] { new TestCaseData( new RuntimeFramework(RuntimeType.Net, new Version(3,5)), new RuntimeFramework(RuntimeType.Net, new Version(2,0))) .Returns(true), new TestCaseData( new RuntimeFramework(RuntimeType.Net, new Version(2,0)), new RuntimeFramework(RuntimeType.Net, new Version(3,5))) .Returns(false), new TestCaseData( new RuntimeFramework(RuntimeType.Net, new Version(3,5)), new RuntimeFramework(RuntimeType.Net, new Version(3,5))) .Returns(true), new TestCaseData( new RuntimeFramework(RuntimeType.Net, new Version(2,0)), new RuntimeFramework(RuntimeType.Net, new Version(2,0))) .Returns(true), new TestCaseData( new RuntimeFramework(RuntimeType.Net, new Version(2,0)), new RuntimeFramework(RuntimeType.Net, new Version(2,0,50727))) .Returns(true), new TestCaseData( new RuntimeFramework(RuntimeType.Net, new Version(2,0,50727)), new RuntimeFramework(RuntimeType.Net, new Version(2,0))) .Returns(true), new TestCaseData( new RuntimeFramework(RuntimeType.Net, new Version(2,0,50727)), new RuntimeFramework(RuntimeType.Net, new Version(2,0))) .Returns(true), new TestCaseData( new RuntimeFramework(RuntimeType.Net, new Version(2,0)), new RuntimeFramework(RuntimeType.Mono, new Version(2,0))) .Returns(false), new TestCaseData( new RuntimeFramework(RuntimeType.Net, new Version(2,0)), new RuntimeFramework(RuntimeType.Net, new Version(1,1))) .Returns(false), new TestCaseData( new RuntimeFramework(RuntimeType.Net, new Version(2,0,50727)), new RuntimeFramework(RuntimeType.Net, new Version(2,0,40607))) .Returns(false), new TestCaseData( new RuntimeFramework(RuntimeType.Mono, new Version(1,1)), // non-existent version but it works new RuntimeFramework(RuntimeType.Mono, new Version(1,0))) .Returns(true), new TestCaseData( new RuntimeFramework(RuntimeType.Mono, new Version(2,0)), new RuntimeFramework(RuntimeType.Any, new Version(2,0))) .Returns(true), new TestCaseData( new RuntimeFramework(RuntimeType.Any, new Version(2,0)), new RuntimeFramework(RuntimeType.Mono, new Version(2,0))) .Returns(true), new TestCaseData( new RuntimeFramework(RuntimeType.Any, new Version(2,0)), new RuntimeFramework(RuntimeType.Any, new Version(2,0))) .Returns(true), new TestCaseData( new RuntimeFramework(RuntimeType.Any, new Version(2,0)), new RuntimeFramework(RuntimeType.Any, new Version(4,0))) .Returns(false), new TestCaseData( new RuntimeFramework(RuntimeType.Net, RuntimeFramework.DefaultVersion), new RuntimeFramework(RuntimeType.Net, new Version(2,0))) .Returns(true), new TestCaseData( new RuntimeFramework(RuntimeType.Net, new Version(2,0)), new RuntimeFramework(RuntimeType.Net, RuntimeFramework.DefaultVersion)) .Returns(true), new TestCaseData( new RuntimeFramework(RuntimeType.Any, RuntimeFramework.DefaultVersion), new RuntimeFramework(RuntimeType.Net, new Version(2,0))) .Returns(true), new TestCaseData( new RuntimeFramework(RuntimeType.Net, new Version(2,0)), new RuntimeFramework(RuntimeType.Any, RuntimeFramework.DefaultVersion)) .Returns(true) }; public struct FrameworkData { public RuntimeType runtime; public Version frameworkVersion; public Version clrVersion; public string representation; public string displayName; public FrameworkData(RuntimeType runtime, Version frameworkVersion, Version clrVersion, string representation, string displayName) { this.runtime = runtime; this.frameworkVersion = frameworkVersion; this.clrVersion = clrVersion; this.representation = representation; this.displayName = displayName; } public override string ToString() { return string.Format("<{0},{1},{2}>", this.runtime, this.frameworkVersion, this.clrVersion); } } internal static FrameworkData[] frameworkData = new FrameworkData[] { new FrameworkData(RuntimeType.Net, new Version(1,0), new Version(1,0,3705), "net-1.0", "Net 1.0"), // new FrameworkData(RuntimeType.Net, new Version(1,0,3705), new Version(1,0,3705), "net-1.0.3705", "Net 1.0.3705"), // new FrameworkData(RuntimeType.Net, new Version(1,0), new Version(1,0,3705), "net-1.0.3705", "Net 1.0.3705"), new FrameworkData(RuntimeType.Net, new Version(1,1), new Version(1,1,4322), "net-1.1", "Net 1.1"), // new FrameworkData(RuntimeType.Net, new Version(1,1,4322), new Version(1,1,4322), "net-1.1.4322", "Net 1.1.4322"), new FrameworkData(RuntimeType.Net, new Version(2,0), new Version(2,0,50727), "net-2.0", "Net 2.0"), // new FrameworkData(RuntimeType.Net, new Version(2,0,40607), new Version(2,0,40607), "net-2.0.40607", "Net 2.0.40607"), // new FrameworkData(RuntimeType.Net, new Version(2,0,50727), new Version(2,0,50727), "net-2.0.50727", "Net 2.0.50727"), new FrameworkData(RuntimeType.Net, new Version(3,0), new Version(2,0,50727), "net-3.0", "Net 3.0"), new FrameworkData(RuntimeType.Net, new Version(3,5), new Version(2,0,50727), "net-3.5", "Net 3.5"), new FrameworkData(RuntimeType.Net, new Version(4,0), new Version(4,0,30319), "net-4.0", "Net 4.0"), new FrameworkData(RuntimeType.Net, RuntimeFramework.DefaultVersion, RuntimeFramework.DefaultVersion, "net", "Net"), new FrameworkData(RuntimeType.Mono, new Version(1,0), new Version(1,1,4322), "mono-1.0", "Mono 1.0"), new FrameworkData(RuntimeType.Mono, new Version(2,0), new Version(2,0,50727), "mono-2.0", "Mono 2.0"), // new FrameworkData(RuntimeType.Mono, new Version(2,0,50727), new Version(2,0,50727), "mono-2.0.50727", "Mono 2.0.50727"), new FrameworkData(RuntimeType.Mono, new Version(3,5), new Version(2,0,50727), "mono-3.5", "Mono 3.5"), new FrameworkData(RuntimeType.Mono, new Version(4,0), new Version(4,0,30319), "mono-4.0", "Mono 4.0"), new FrameworkData(RuntimeType.Mono, RuntimeFramework.DefaultVersion, RuntimeFramework.DefaultVersion, "mono", "Mono"), new FrameworkData(RuntimeType.Any, new Version(1,1), new Version(1,1,4322), "v1.1", "v1.1"), new FrameworkData(RuntimeType.Any, new Version(2,0), new Version(2,0,50727), "v2.0", "v2.0"), // new FrameworkData(RuntimeType.Any, new Version(2,0,50727), new Version(2,0,50727), "v2.0.50727", "v2.0.50727"), new FrameworkData(RuntimeType.Any, new Version(3,5), new Version(2,0,50727), "v3.5", "v3.5"), new FrameworkData(RuntimeType.Any, new Version(4,0), new Version(4,0,30319), "v4.0", "v4.0"), new FrameworkData(RuntimeType.Any, RuntimeFramework.DefaultVersion, RuntimeFramework.DefaultVersion, "any", "Any") }; } } #endif
#region License /* * Copyright 2002-2010 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. */ #endregion using System; using System.Collections.Specialized; using System.Reflection; using Common.Logging; using Spring.Objects.Factory; using Spring.Threading; using Spring.Util; namespace Spring.Transaction.Interceptor { /// <summary> /// Superclass for transaction aspects, such as the AOP Alliance-compatible /// <see cref="Spring.Transaction.Interceptor.TransactionInterceptor"/>. /// </summary> /// <remarks> /// <p> /// This enables the underlying Spring transaction infrastructure to be used /// to easily implement an aspect for any aspect system. /// </p> /// <p> /// Subclasses are responsible for calling methods in this class in the correct order. /// </p> /// <p> /// Uses the Strategy design pattern. A <see cref="Spring.Transaction.IPlatformTransactionManager"/> /// implementation will perform the actual transaction management /// </p> /// <p> /// A transaction aspect is serializable if its /// <see cref="Spring.Transaction.IPlatformTransactionManager"/> and /// <see cref="Spring.Transaction.Interceptor.ITransactionAttributeSource"/> are serializable. /// </p> /// </remarks> /// <author>Rod Johnson</author> /// <author>Juergen Hoeller</author> /// <author>Griffin Caprio (.NET)</author> /// <author>Mark Pollack (.NET)</author> [Serializable] public class TransactionAspectSupport : IInitializingObject { //TODO work on serialization support. #region TransactionInfo Class /// <summary> /// Opaque object used to hold transaction information. /// </summary> /// <remarks> /// <p> /// Subclasses must pass it back to method on this class, but not see its internals. /// </p> /// </remarks> internal protected class TransactionInfo { private ITransactionAttribute _transactionAttribute; private string _joinpointIdentification; private ITransactionStatus _transactionStatus; private TransactionInfo _oldTransactionInfo; /// <summary> /// Creates a new instance of the /// <see cref="Spring.Transaction.Interceptor.TransactionAspectSupport.TransactionInfo"/> /// class for the supplied <paramref name="transactionAttribute"/>. /// </summary> /// <param name="transactionAttribute">The transaction attributes to associate with any transaction.</param> /// <param name="joinpointIdentification">The info for diagnostic display of joinpoint</param> public TransactionInfo( ITransactionAttribute transactionAttribute, string joinpointIdentification) { _transactionAttribute = transactionAttribute; _joinpointIdentification = joinpointIdentification; } /// <summary> /// Does this instance currently have a transaction? /// </summary> /// <value><b>True</b> if this instance has a transaction.</value> public bool HasTransaction { get { return _transactionStatus != null; } } /// <summary> /// Gets and sets the <see cref="Spring.Transaction.ITransactionStatus"/> for this object. /// </summary> public ITransactionStatus TransactionStatus { set { _transactionStatus = value; } get { return _transactionStatus; } } /// <summary> /// Binds this /// <see cref="Spring.Transaction.Interceptor.TransactionAspectSupport.TransactionInfo"/> /// instance to the thread local storage variable for the current thread and /// backs up the existing /// <see cref="Spring.Transaction.Interceptor.TransactionAspectSupport.TransactionInfo"/> /// object for the current thread. /// </summary> public void BindToThread() { // Expose current TransactionStatus, preserving any existing TransactionStatus // for restoration after this transaction is complete. TransactionInfo currentTransactionInfo = LogicalThreadContext.GetData(CURRENT_TRANSACTIONINFO_SLOTNAME) as TransactionInfo; _oldTransactionInfo = currentTransactionInfo; LogicalThreadContext.SetData(CURRENT_TRANSACTIONINFO_SLOTNAME, this); } /// <summary> /// Restores the previous /// <see cref="Spring.Transaction.Interceptor.TransactionAspectSupport.TransactionInfo"/> /// object to the current thread. /// </summary> public void RestoreThreadLocalStatus() { // Use stack to restore old transaction TransactionInfo. // Will be null if none was set. LogicalThreadContext.SetData(CURRENT_TRANSACTIONINFO_SLOTNAME, _oldTransactionInfo); } /// <summary> /// Gets the current /// <see cref="Spring.Transaction.Interceptor.ITransactionAttribute"/> for this /// <see cref="Spring.Transaction.Interceptor.TransactionAspectSupport.TransactionInfo"/> /// object. /// </summary> public ITransactionAttribute TransactionAttribute { get { return _transactionAttribute; } } /// <summary> /// Gets the joinpoint identification. /// </summary> /// <value>The joinpoint identification.</value> public string JoinpointIdentification { get { return _joinpointIdentification; } } } #endregion #region Logging Definition [NonSerialized] protected ILog log = LogManager.GetLogger(typeof (TransactionAspectSupport)); #endregion /// <summary> /// The name in thread local storage where the TransactionInfo object is located /// </summary> public const string CURRENT_TRANSACTIONINFO_SLOTNAME = "TransactionAspectSupport.CurrentTransactionInfoSlotName"; /// <summary> /// The <see cref="Spring.Transaction.IPlatformTransactionManager"/> currently referenced by /// this aspect /// </summary> private IPlatformTransactionManager _transactionManager; /// <summary> /// The <see cref="Spring.Transaction.Interceptor.ITransactionAttributeSource"/> currently /// referenced by this aspect. /// </summary> private ITransactionAttributeSource _transactionAttributeSource; /// <summary> /// Creates a new instance of the /// <see cref="Spring.Transaction.Interceptor.TransactionAspectSupport"/> class. /// </summary> public TransactionAspectSupport() {} /// <summary> /// Gets and sets the <see cref="Spring.Transaction.IPlatformTransactionManager"/> for /// this aspect. /// </summary> public IPlatformTransactionManager TransactionManager { get { return _transactionManager; } set { _transactionManager = value; } } /// <summary> /// Gets and sets the /// <see cref="Spring.Transaction.Interceptor.ITransactionAttributeSource"/> for /// this aspect. /// </summary> public ITransactionAttributeSource TransactionAttributeSource { get { return _transactionAttributeSource; } set { _transactionAttributeSource = value; } } /// <summary> /// Returns the <see cref="Spring.Transaction.ITransactionStatus"/> /// of the current method invocation. /// </summary> /// <remarks> /// Mainly intended for code that wants to set the current transaction /// rollback-only but not throw an application exception. /// </remarks> /// <exception cref="Spring.Transaction.NoTransactionException"> /// If the transaction info cannot be found, because the method was invoked /// outside of an AOP invocation context. /// </exception> public static ITransactionStatus CurrentTransactionStatus { get { return CurrentTransactionInfo.TransactionStatus; } } /// <summary> /// Subclasses can use this to return the current /// <see cref="Spring.Transaction.Interceptor.TransactionAspectSupport.TransactionInfo"/>. /// </summary> /// <remarks> /// Only subclasses that cannot handle all operations in one method /// need to use this mechanism to get at the current /// <see cref="Spring.Transaction.Interceptor.TransactionAspectSupport.TransactionInfo"/>. /// An around advice such as an AOP Alliance /// <see cref="AopAlliance.Intercept.IMethodInterceptor"/> can hold a reference to the /// <see cref="Spring.Transaction.Interceptor.TransactionAspectSupport.TransactionInfo"/> /// throughout the aspect method. /// A <see cref="Spring.Transaction.Interceptor.TransactionAspectSupport.TransactionInfo"/> /// will be returned even if no transaction was created. The /// <see cref="Spring.Transaction.Interceptor.TransactionAspectSupport.TransactionInfo.HasTransaction"/> /// property can be used to query this. /// </remarks> /// <exception cref="Spring.Transaction.NoTransactionException"> /// If no transaction has been created by an aspect. /// </exception> protected static TransactionInfo CurrentTransactionInfo { get { TransactionInfo currentTransactionInfo = LogicalThreadContext.GetData(CURRENT_TRANSACTIONINFO_SLOTNAME) as TransactionInfo; if (currentTransactionInfo == null) { throw new NoTransactionException("No transaction aspect-managed ITransactionStatus in scope"); } return currentTransactionInfo; } } /// <summary> /// Set properties with method names as keys and transaction attribute /// descriptors (parsed via <see cref="Spring.Transaction.Interceptor.TransactionAttributeEditor"/>) as values: /// e.g. key = "MyMethod", value = "PROPAGATION_REQUIRED,readOnly". /// </summary> /// <remarks> /// <note> /// Method names are always applied to the target class, no matter if defined in an /// interface or the class itself. /// </note> /// <p> /// Internally, a /// <see cref="Spring.Transaction.Interceptor.NameMatchTransactionAttributeSource"/> /// will be created from the given properties. /// </p> /// </remarks> public NameValueCollection TransactionAttributes { set { NameMatchTransactionAttributeSource attributeSource = new NameMatchTransactionAttributeSource(); attributeSource.NameProperties = value; _transactionAttributeSource = attributeSource; } } /// <summary> /// Checks that the required properties are set. /// </summary> public void AfterPropertiesSet() { if ( null == _transactionManager) { throw new ArgumentException("IPlatformTransactionManager is required"); } if ( null == _transactionAttributeSource ) { throw new ArgumentException("Either 'TransactionAttributeSource' or 'TransactionAttribute' property is required: " + "If there are no transactional methods, don't use a TransactionInterceptor " + "or TransactionProxyFactoryObject." ); } } /// <summary> /// Create a transaction if necessary /// </summary> /// <param name="method">Method about to execute</param> /// <param name="targetType">Type that the method is on</param> /// <returns> /// A <see cref="Spring.Transaction.Interceptor.TransactionAspectSupport.TransactionInfo"/> object, /// whether or not a transaction was created. /// <p> /// The /// <see cref="Spring.Transaction.Interceptor.TransactionAspectSupport.TransactionInfo.HasTransaction"/> /// property on the /// <see cref="Spring.Transaction.Interceptor.TransactionAspectSupport.TransactionInfo"/> /// class can be used to tell if there was a transaction created. /// </p> /// </returns> protected TransactionInfo CreateTransactionIfNecessary( MethodInfo method, Type targetType ) { // If the transaction attribute is null, the method is non-transactional. ITransactionAttribute sourceAttr = _transactionAttributeSource.ReturnTransactionAttribute( method, targetType ); return CreateTransactionIfNecessary(sourceAttr, MethodIdentification(method)); } /// <summary> /// Creates the transaction if necessary. /// </summary> /// <param name="sourceAttr">The source transaction attribute.</param> /// <param name="joinpointIdentification">The joinpoint identification.</param> /// <returns>Transaction Info for declarative transaction management.</returns> protected TransactionInfo CreateTransactionIfNecessary(ITransactionAttribute sourceAttr, string joinpointIdentification) { ITransactionAttribute txAttr = sourceAttr; // If no name specified, apply method identification as transaction name. if (txAttr != null && txAttr.Name == null) { txAttr = new DelegatingTransactionAttributeWithName(txAttr, joinpointIdentification); } TransactionInfo transactionInfo = new TransactionInfo(txAttr, joinpointIdentification); if ( txAttr != null ) { // We need a transaction for this method #region Instrumentation if (log.IsDebugEnabled) { log.Debug("Getting transaction for " + transactionInfo.JoinpointIdentification); } #endregion // The transaction manager will flag an error if an incompatible tx already exists transactionInfo.TransactionStatus = _transactionManager.GetTransaction(txAttr); } else { // The TransactionInfo.HasTransaction property will return // false. We created it only to preserve the integrity of // the ThreadLocal stack maintained in this class. if (log.IsDebugEnabled) { log.Debug("Skipping transactional joinpoint [" + joinpointIdentification + "] because no transaction manager has been configured"); } } // We always bind the TransactionInfo to the thread, even if we didn't create // a new transaction here. This guarantees that the TransactionInfo stack // will be managed correctly even if no transaction was created by this aspect. transactionInfo.BindToThread( ); return transactionInfo; } /// <summary> /// Identifies the method by providing the qualfied method name. /// </summary> /// <param name="methodInfo">The method info.</param> /// <returns>qualified mehtod name.</returns> protected string MethodIdentification(MethodInfo methodInfo) { return ObjectUtils.GetQualifiedMethodName(methodInfo); } /// <summary> /// Execute after the successful completion of call, but not after an exception was handled. /// </summary> /// <remarks> /// <p> /// Do nothing if we didn't create a transaction. /// </p> /// </remarks> /// <param name="transactionInfo"> /// The /// <see cref="Spring.Transaction.Interceptor.TransactionAspectSupport.TransactionInfo"/> /// about the current transaction. /// </param> protected void CommitTransactionAfterReturning( TransactionInfo transactionInfo ) { if ( transactionInfo != null && transactionInfo.HasTransaction ) { #region Instrumentation if (log.IsDebugEnabled) { log.Debug("Completing transaction for [" + transactionInfo.JoinpointIdentification + "]"); } #endregion _transactionManager.Commit( transactionInfo.TransactionStatus ); } } /// <summary> /// Handle a exception, closing out the transaction. /// </summary> /// <remarks> /// <p> /// We may commit or roll back, depending on our configuration. /// </p> /// </remarks> /// <param name="transactionInfo"> /// The /// <see cref="Spring.Transaction.Interceptor.TransactionAspectSupport.TransactionInfo"/> /// about the current transaction. /// </param> /// <param name="exception">The <see cref="System.Exception"/> encountered.</param> protected void CompleteTransactionAfterThrowing( TransactionInfo transactionInfo, Exception exception ) { if ( transactionInfo != null && transactionInfo.HasTransaction ) { if (log.IsDebugEnabled) { log.Debug("Completing transaction for [" + transactionInfo.JoinpointIdentification + "] after exception: " + exception); } if ( transactionInfo.TransactionAttribute.RollbackOn( exception )) { try { _transactionManager.Rollback( transactionInfo.TransactionStatus ); } catch (Exception e) { log.Error("Application exception overridden by rollback exception", e); throw; } } else { // We don't roll back on this exception. // Will still roll back if TransactionStatus.RollbackOnly is true. try { _transactionManager.Commit(transactionInfo.TransactionStatus); } catch (Exception e) { log.Error("Application exception overriden by commit exception", e); throw; } } } } /// <summary> /// Resets the /// <see cref="Spring.Transaction.Interceptor.TransactionAspectSupport.TransactionInfo"/> /// for this thread. /// </summary> /// <remarks> /// <note> /// Call this in all cases: exceptions or normal return. /// </note> /// </remarks> /// <param name="transactionInfo"> /// The /// <see cref="Spring.Transaction.Interceptor.TransactionAspectSupport.TransactionInfo"/> /// about the current transaction. May be null. /// </param> protected void CleanupTransactionInfo( TransactionInfo transactionInfo ) { if ( transactionInfo != null ) { transactionInfo.RestoreThreadLocalStatus( ); } } } }
// // 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 VariableOperationsExtensions { /// <summary> /// Create a variable. (see /// http://aka.ms/azureautomationsdk/variableoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IVariableOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the create variable operation. /// </param> /// <returns> /// The response model for the create variable operation. /// </returns> public static VariableCreateResponse Create(this IVariableOperations operations, string automationAccount, VariableCreateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IVariableOperations)s).CreateAsync(automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create a variable. (see /// http://aka.ms/azureautomationsdk/variableoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IVariableOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the create variable operation. /// </param> /// <returns> /// The response model for the create variable operation. /// </returns> public static Task<VariableCreateResponse> CreateAsync(this IVariableOperations operations, string automationAccount, VariableCreateParameters parameters) { return operations.CreateAsync(automationAccount, parameters, CancellationToken.None); } /// <summary> /// Delete the variable. (see /// http://aka.ms/azureautomationsdk/variableoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IVariableOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='variableName'> /// Required. The name of variable. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IVariableOperations operations, string automationAccount, string variableName) { return Task.Factory.StartNew((object s) => { return ((IVariableOperations)s).DeleteAsync(automationAccount, variableName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete the variable. (see /// http://aka.ms/azureautomationsdk/variableoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IVariableOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='variableName'> /// Required. The name of variable. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IVariableOperations operations, string automationAccount, string variableName) { return operations.DeleteAsync(automationAccount, variableName, CancellationToken.None); } /// <summary> /// Retrieve the variable identified by variable name. (see /// http://aka.ms/azureautomationsdk/variableoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IVariableOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='variableName'> /// Required. The name of variable. /// </param> /// <returns> /// The response model for the get variable operation. /// </returns> public static VariableGetResponse Get(this IVariableOperations operations, string automationAccount, string variableName) { return Task.Factory.StartNew((object s) => { return ((IVariableOperations)s).GetAsync(automationAccount, variableName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve the variable identified by variable name. (see /// http://aka.ms/azureautomationsdk/variableoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IVariableOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='variableName'> /// Required. The name of variable. /// </param> /// <returns> /// The response model for the get variable operation. /// </returns> public static Task<VariableGetResponse> GetAsync(this IVariableOperations operations, string automationAccount, string variableName) { return operations.GetAsync(automationAccount, variableName, CancellationToken.None); } /// <summary> /// Retrieve a list of variables. (see /// http://aka.ms/azureautomationsdk/variableoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IVariableOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <returns> /// The response model for the list variables operation. /// </returns> public static VariableListResponse List(this IVariableOperations operations, string automationAccount) { return Task.Factory.StartNew((object s) => { return ((IVariableOperations)s).ListAsync(automationAccount); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of variables. (see /// http://aka.ms/azureautomationsdk/variableoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IVariableOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <returns> /// The response model for the list variables operation. /// </returns> public static Task<VariableListResponse> ListAsync(this IVariableOperations operations, string automationAccount) { return operations.ListAsync(automationAccount, CancellationToken.None); } /// <summary> /// Retrieve next list of variables. (see /// http://aka.ms/azureautomationsdk/variableoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IVariableOperations. /// </param> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <returns> /// The response model for the list variables operation. /// </returns> public static VariableListResponse ListNext(this IVariableOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IVariableOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve next list of variables. (see /// http://aka.ms/azureautomationsdk/variableoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IVariableOperations. /// </param> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <returns> /// The response model for the list variables operation. /// </returns> public static Task<VariableListResponse> ListNextAsync(this IVariableOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } /// <summary> /// Update a variable. (see /// http://aka.ms/azureautomationsdk/variableoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IVariableOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the update variable operation. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Update(this IVariableOperations operations, string automationAccount, VariableUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IVariableOperations)s).UpdateAsync(automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Update a variable. (see /// http://aka.ms/azureautomationsdk/variableoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Automation.IVariableOperations. /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the update variable operation. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> UpdateAsync(this IVariableOperations operations, string automationAccount, VariableUpdateParameters parameters) { return operations.UpdateAsync(automationAccount, parameters, CancellationToken.None); } } }
// Copyright 2009 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using NodaTime.TimeZones; using NodaTime.TzdbCompiler.Tzdb; using NUnit.Framework; using System; using System.Globalization; using System.IO; using System.Linq; namespace NodaTime.TzdbCompiler.Test.Tzdb { /// <summary> /// Tests for TzdbZoneInfoParser. /// </summary> public class TzdbZoneInfoParserTest { private static Offset ToOffset(int hours, int minutes) { return Offset.FromHoursAndMinutes(hours, minutes); } private static void ValidateCounts(TzdbDatabase database, int ruleSets, int zoneLists, int links) { Assert.AreEqual(ruleSets, database.Rules.Count, "Rules"); Assert.AreEqual(zoneLists, database.Zones.Count, "Zones"); Assert.AreEqual(links, database.Aliases.Count, "Links"); } [Test] public void ParseDateTimeOfYear_emptyString() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize(""); Assert.Throws(typeof(InvalidDataException), () => parser.ParseDateTimeOfYear(tokens, true)); } [Test] public void ParseDateTimeOfYear_missingAt_invalidForRule() { var parser = new TzdbZoneInfoParser(); const string text = "Mar lastSun"; var tokens = Tokens.Tokenize(text); Assert.Throws(typeof(InvalidDataException), () => parser.ParseDateTimeOfYear(tokens, true)); } [Test] public void ParseDateTimeOfYear_missingOn_invalidForRule() { var parser = new TzdbZoneInfoParser(); const string text = "Mar"; var tokens = Tokens.Tokenize(text); Assert.Throws(typeof(InvalidDataException), () => parser.ParseDateTimeOfYear(tokens, true)); } [Test] public void ParseDateTimeOfYear_missingAt_validForZone() { var parser = new TzdbZoneInfoParser(); const string text = "Mar lastSun"; var tokens = Tokens.Tokenize(text); var actual = parser.ParseDateTimeOfYear(tokens, false); var expected = new ZoneYearOffset(TransitionMode.Wall, 3, -1, (int) IsoDayOfWeek.Sunday, false, LocalTime.Midnight); Assert.AreEqual(expected, actual); } [Test] public void ParseDateTimeOfYear_missingOn_validForZone() { var parser = new TzdbZoneInfoParser(); const string text = "Mar"; var tokens = Tokens.Tokenize(text); var actual = parser.ParseDateTimeOfYear(tokens, false); var expected = new ZoneYearOffset(TransitionMode.Wall, 3, 1, 0, false, LocalTime.Midnight); Assert.AreEqual(expected, actual); } [Test] public void ParseDateTimeOfYear_onAfter() { var parser = new TzdbZoneInfoParser(); const string text = "Mar Tue>=14 2:00"; var tokens = Tokens.Tokenize(text); var actual = parser.ParseDateTimeOfYear(tokens, true); var expected = new ZoneYearOffset(TransitionMode.Wall, 3, 14, (int)IsoDayOfWeek.Tuesday, true, new LocalTime(2, 0)); Assert.AreEqual(expected, actual); } [Test] public void ParseDateTimeOfYear_onBefore() { var parser = new TzdbZoneInfoParser(); const string text = "Mar Tue<=14 2:00"; var tokens = Tokens.Tokenize(text); var actual = parser.ParseDateTimeOfYear(tokens, true); var expected = new ZoneYearOffset(TransitionMode.Wall, 3, 14, (int)IsoDayOfWeek.Tuesday, false, new LocalTime(2, 0)); Assert.AreEqual(expected, actual); } [Test] public void ParseDateTimeOfYear_onLast() { var parser = new TzdbZoneInfoParser(); const string text = "Mar lastTue 2:00"; var tokens = Tokens.Tokenize(text); var actual = parser.ParseDateTimeOfYear(tokens, true); var expected = new ZoneYearOffset(TransitionMode.Wall, 3, -1, (int)IsoDayOfWeek.Tuesday, false, new LocalTime(2, 0)); Assert.AreEqual(expected, actual); } [Test] public void ParseLine_comment() { const string line = "# Comment"; var database = ParseText(line); ValidateCounts(database, 0, 0, 0); } [Test] public void ParseLine_commentWithLeadingWhitespace() { const string line = " # Comment"; var database = ParseText(line); ValidateCounts(database, 0, 0, 0); } [Test] public void ParseLine_emptyString() { var database = ParseText(""); ValidateCounts(database, 0, 0, 0); } // Assume that all lines work the same way - it's comment handling // that's important here. [Test] public void ParseLine_commentAtEndOfLine() { string line = "Link from to#Comment"; var database = ParseText(line); ValidateCounts(database, 0, 0, 1); Assert.AreEqual("from", database.Aliases["to"]); } [Test] public void ParseLine_link() { const string line = "Link from to"; var database = ParseText(line); ValidateCounts(database, 0, 0, 1); } [Test] public void ParseLine_whiteSpace() { const string line = " \t\t\n"; var database = ParseText(line); ValidateCounts(database, 0, 0, 0); } [Test] public void ParseLine_zone() { const string line = "Zone PST 2:00 US P%sT"; var database = ParseText(line); ValidateCounts(database, 0, 1, 0); Assert.AreEqual(1, database.Zones.Values.Single().Count); } [Test] public void ParseLine_zonePlus() { string lines = "Zone PST 2:00 US P%sT\n" + " 3:00 US P%sT"; var database = ParseText(lines); ValidateCounts(database, 0, 1, 0); Assert.AreEqual(2, database.Zones["PST"].Count); } [Test] public void ParseLink_emptyString_exception() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize(""); Assert.Throws(typeof(InvalidDataException), () => parser.ParseLink(tokens)); } [Test] public void ParseLink_simple() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize("from to"); var actual = parser.ParseLink(tokens); var expected = Tuple.Create("from", "to"); Assert.AreEqual(expected, actual); } [Test] public void ParseLink_tooFewWords_exception() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize("from"); Assert.Throws<InvalidDataException>(() => parser.ParseLink(tokens)); } [Test] public void ParseMonth_nullOrEmpty() { Assert.Throws<ArgumentException>(() => TzdbZoneInfoParser.ParseMonth("")); Assert.Throws<ArgumentException>(() => TzdbZoneInfoParser.ParseMonth(null!)); } [Test] public void ParseMonth_invalidMonth_default() { Assert.Throws<InvalidDataException>(() => TzdbZoneInfoParser.ParseMonth("Able")); } [Test] public void ParseMonth_shortMonthNames() { for (int i = 1; i < 12; i++) { var month = new DateTime(2000, i, 1).ToString("MMM", CultureInfo.InvariantCulture); Assert.AreEqual(i, TzdbZoneInfoParser.ParseMonth(month)); } } [Test] public void ParseMonth_longMonthNames() { for (int i = 1; i < 12; i++) { var month = new DateTime(2000, i, 1).ToString("MMMM", CultureInfo.InvariantCulture); Assert.AreEqual(i, TzdbZoneInfoParser.ParseMonth(month)); } } [Test] public void ParseZone_badOffset_exception() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize("asd US P%sT 1969 Mar 23 14:53:27.856s"); Assert.Throws(typeof(FormatException), () => parser.ParseZone("", tokens)); } [Test] public void ParseZone_emptyString_exception() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize(""); Assert.Throws(typeof(InvalidDataException), () => parser.ParseZone("", tokens)); } [Test] public void ParseZone_optionalRule() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize("2:00 - P%sT"); var expected = new ZoneLine("", ToOffset(2, 0), null, "P%sT", int.MaxValue, TzdbZoneInfoParser.StartOfYearZoneOffset); Assert.AreEqual(expected, parser.ParseZone("", tokens)); } [Test] public void ParseZone_simple() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize("2:00 US P%sT"); var expected = new ZoneLine("", ToOffset(2, 0), "US", "P%sT", int.MaxValue, TzdbZoneInfoParser.StartOfYearZoneOffset); Assert.AreEqual(expected, parser.ParseZone("", tokens)); } [Test] public void ParseZone_tooFewWords1_exception() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize("2:00 US"); Assert.Throws(typeof(InvalidDataException), () => parser.ParseZone("", tokens)); } [Test] public void ParseZone_tooFewWords2_exception() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize("2:00"); Assert.Throws(typeof(InvalidDataException), () => parser.ParseZone("", tokens)); } [Test] public void ParseZone_withYear() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize("2:00 US P%sT 1969"); var expected = new ZoneLine("", ToOffset(2, 0), "US", "P%sT", 1969, new ZoneYearOffset(TransitionMode.Wall, 1, 1, 0, false, LocalTime.Midnight)); Assert.AreEqual(expected, parser.ParseZone("", tokens)); } [Test] public void ParseZone_withYearMonthDay() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize("2:00 US P%sT 1969 Mar 23"); var expected = new ZoneLine("", ToOffset(2, 0), "US", "P%sT", 1969, new ZoneYearOffset(TransitionMode.Wall, 3, 23, 0, false, LocalTime.Midnight)); Assert.AreEqual(expected, parser.ParseZone("", tokens)); } [Test] public void ParseZone_withYearMonthDayTime() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize("2:00 US P%sT 1969 Mar 23 14:53:27.856"); var expected = new ZoneLine("", ToOffset(2, 0), "US", "P%sT", 1969, new ZoneYearOffset(TransitionMode.Wall, 3, 23, 0, false, new LocalTime(14, 53, 27, 856))); Assert.AreEqual(expected, parser.ParseZone("", tokens)); } [Test] public void ParseZone_withYearMonthDayTimeZone() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize("2:00 US P%sT 1969 Mar 23 14:53:27.856s"); var expected = new ZoneLine("", ToOffset(2, 0), "US", "P%sT", 1969, new ZoneYearOffset(TransitionMode.Standard, 3, 23, 0, false, new LocalTime(14, 53, 27, 856))); Assert.AreEqual(expected, parser.ParseZone("", tokens)); } [Test] public void ParseZone_withDayOfWeek() { var parser = new TzdbZoneInfoParser(); var tokens = Tokens.Tokenize("2:00 US P%sT 1969 Mar lastSun"); var expected = new ZoneLine("", ToOffset(2, 0), "US", "P%sT", 1969, new ZoneYearOffset(TransitionMode.Wall, 3, -1, (int) IsoDayOfWeek.Sunday, false, LocalTime.Midnight)); Assert.AreEqual(expected, parser.ParseZone("", tokens)); } [Test] public void Parse_threeLines() { const string text = "# A comment\n" + "Zone PST 2:00 US P%sT\n" + " 3:00 - P%sT\n"; var database = ParseText(text); ValidateCounts(database, 0, 1, 0); Assert.AreEqual(2, database.Zones.Values.Single().Count); } [Test] public void Parse_threeLinesWithComment() { const string text = "# A comment\n" + "Zone PST 2:00 US P%sT # An end of line comment\n" + " 3:00 - P%sT\n"; var database = ParseText(text); ValidateCounts(database, 0, 1, 0); Assert.AreEqual(2, database.Zones.Values.Single().Count); } [Test] public void Parse_twoLines() { const string text = "# A comment\n" + "Zone PST 2:00 US P%sT\n"; var database = ParseText(text); ValidateCounts(database, 0, 1, 0); Assert.AreEqual(1, database.Zones.Values.Single().Count); } [Test] public void Parse_twoLinks() { const string text = "# First line must be a comment\n" + "Link from to\n" + "Link target source\n"; var database = ParseText(text); ValidateCounts(database, 0, 0, 2); } [Test] public void Parse_twoZones() { const string text = "# A comment\n" + "Zone PST 2:00 US P%sT # An end of line comment\n" + " 3:00 - P%sT\n" + " 4:00 - P%sT\n" + "Zone EST 2:00 US E%sT # An end of line comment\n" + " 3:00 - E%sT\n"; var database = ParseText(text); ValidateCounts(database, 0, 2, 0); Assert.AreEqual(3, database.Zones["PST"].Count); Assert.AreEqual(2, database.Zones["EST"].Count); } [Test] public void Parse_twoZonesTwoRule() { const string text = "# A comment\n" + "Rule US 1987 2006 - Apr Sun>=1 2:00 1:00 D\n" + "Rule US 2007 max - Mar Sun>=8 2:00 1:00 D\n" + "Zone PST 2:00 US P%sT # An end of line comment\n" + " 3:00 - P%sT\n" + " 4:00 - P%sT\n" + "Zone EST 2:00 US E%sT # An end of line comment\n" + " 3:00 - E%sT\n"; var database = ParseText(text); ValidateCounts(database, 1, 2, 0); Assert.AreEqual(3, database.Zones["PST"].Count); Assert.AreEqual(2, database.Zones["EST"].Count); } // 2018f uses 25:00 for Japan's fallback transitions 1948-1951 [Test] public void Parse_2500_FromDay_AtLeast_Sunday() { var parser = new TzdbZoneInfoParser(); const string text = "Apr Sun>=1 25:00"; var tokens = Tokens.Tokenize(text); var rule = parser.ParseDateTimeOfYear(tokens, true); var actual = rule.GetOccurrenceForYear(2012); var expected = new LocalDateTime(2012, 4, 2, 1, 0).ToLocalInstant(); Assert.AreEqual(expected, actual); } [Test] public void Parse_2400_FromDay_AtLeast_Sunday() { var parser = new TzdbZoneInfoParser(); const string text = "Apr Sun>=1 24:00"; var tokens = Tokens.Tokenize(text); var rule = parser.ParseDateTimeOfYear(tokens, true); var actual = rule.GetOccurrenceForYear(2012); var expected = new LocalDateTime(2012, 4, 2, 0, 0).ToLocalInstant(); Assert.AreEqual(expected, actual); } [Test] public void Parse_2400_FromDay_AtMost_Sunday() { var parser = new TzdbZoneInfoParser(); const string text = "Apr Sun<=7 24:00"; var tokens = Tokens.Tokenize(text); var rule = parser.ParseDateTimeOfYear(tokens, true); var actual = rule.GetOccurrenceForYear(2012); var expected = new LocalDateTime(2012, 4, 2, 0, 0).ToLocalInstant(); Assert.AreEqual(expected, actual); } [Test] public void Parse_2400_FromDay_AtLeast_Wednesday() { var parser = new TzdbZoneInfoParser(); const string text = "Apr Wed>=1 24:00"; var tokens = Tokens.Tokenize(text); var rule = parser.ParseDateTimeOfYear(tokens, true); var actual = rule.GetOccurrenceForYear(2012); var expected = new LocalDateTime(2012, 4, 5, 0, 0).ToLocalInstant(); Assert.AreEqual(expected, actual); } [Test] public void Parse_2400_FromDay_AtMost_Wednesday() { var parser = new TzdbZoneInfoParser(); const string text = "Apr Wed<=14 24:00"; var tokens = Tokens.Tokenize(text); var rule = parser.ParseDateTimeOfYear(tokens, true); var actual = rule.GetOccurrenceForYear(2012); var expected = new LocalDateTime(2012, 4, 12, 0, 0).ToLocalInstant(); Assert.AreEqual(expected, actual); } [Test] public void Parse_2400_FromDay() { var parser = new TzdbZoneInfoParser(); const string text = "Apr Sun>=1 24:00"; var tokens = Tokens.Tokenize(text); var actual = parser.ParseDateTimeOfYear(tokens, true); var expected = new ZoneYearOffset(TransitionMode.Wall, 4, 1, (int)IsoDayOfWeek.Sunday, true, LocalTime.Midnight, true); Assert.AreEqual(expected, actual); } [Test] public void Parse_2400_Last() { var parser = new TzdbZoneInfoParser(); const string text = "Mar lastSun 24:00"; var tokens = Tokens.Tokenize(text); var actual = parser.ParseDateTimeOfYear(tokens, true); var expected = new ZoneYearOffset(TransitionMode.Wall, 3, -1, (int)IsoDayOfWeek.Sunday, false, LocalTime.Midnight, true); Assert.AreEqual(expected, actual); } [Test] public void Parse_Fixed_Eastern() { const string text = "# A comment\n" + "Zone\tEtc/GMT-9\t9\t-\tGMT-9\n"; var database = ParseText(text); ValidateCounts(database, 0, 1, 0); var zone = database.Zones["Etc/GMT-9"].Single(); Assert.AreEqual(Offset.FromHours(9), zone.StandardOffset); Assert.IsNull(zone.Rules); Assert.AreEqual(int.MaxValue, zone.UntilYear); } [Test] public void Parse_Fixed_Western() { const string text = "# A comment\n" + "Zone\tEtc/GMT+9\t-9\t-\tGMT+9\n"; var database = ParseText(text); ValidateCounts(database, 0, 1, 0); var zone = database.Zones["Etc/GMT+9"].Single(); Assert.AreEqual(Offset.FromHours(-9), zone.StandardOffset); Assert.IsNull(zone.Rules); Assert.AreEqual(int.MaxValue, zone.UntilYear); } [Test] public void Parse_RuleWithType() { string line = "Rule BrokenRule 2010 2020 odd Apr Sun>=1 2:00 1:00 D\n"; var exception = Assert.Throws<NotImplementedException>(() => ParseText(line)); StringAssert.Contains("'BrokenRule'", exception.Message); StringAssert.Contains("'odd'", exception.Message); } /// <summary> /// Helper method to create a database and call Parse with the given text. /// </summary> private TzdbDatabase ParseText(string line) { var parser = new TzdbZoneInfoParser(); var database = new TzdbDatabase("version"); parser.Parse(new StringReader(line), database); return database; } } }
using System; using System.IO; namespace DataTool.ConvertLogic { public class CodebookLibrary { public string m_file; public byte[] m_codebookData; public long[] m_codebookOffsets; private readonly long m_codebookCount; public CodebookLibrary(string file) { m_file = file; using (Stream codebookStream = System.IO.File.OpenRead(file)) { using (BinaryReader reader = new BinaryReader(codebookStream)) { long fileSize = codebookStream.Length; codebookStream.Seek(fileSize - 4, SeekOrigin.Begin); long offsetOffset = reader.ReadInt32(); m_codebookCount = (fileSize - offsetOffset) / 4; m_codebookData = new byte[offsetOffset]; m_codebookOffsets = new long[m_codebookCount]; codebookStream.Position = 0; for (int i = 0; i < offsetOffset; i++) { m_codebookData[i] = reader.ReadByte(); } for (int i = 0; i < m_codebookCount; i++) { m_codebookOffsets[i] = reader.ReadInt32(); } } } } public void Rebuild(int codebookID, BitOggstream os) { long? cbIndexStart = GetCodebook(codebookID); ulong cbSize; { long signedCbSize = GetCodebookSize(codebookID); if (cbIndexStart == null || -1 == signedCbSize) throw new InvalidID(); cbSize = (ulong) signedCbSize; } long cbStartIndex = (long) cbIndexStart; long unsignedSize = (long) cbSize; Stream codebookStream = new MemoryStream(); for (long i = cbStartIndex; i < unsignedSize + cbStartIndex; i++) { codebookStream.WriteByte(m_codebookData[i]); } BinaryReader reader = new BinaryReader(codebookStream); BitStream bitStream = new BitStream(reader); reader.BaseStream.Position = 0; // todo: the rest of the stuff Rebuild(bitStream, cbSize, os); } public void Rebuild(BitStream bis, ulong cbSize, BitOggstream bos) { /* IN: 4 bit dimensions, 14 bit entry count */ BitUint dimensions = new BitUint(4); BitUint entries = new BitUint(14); bis.Read(dimensions); bis.Read(entries); /* OUT: 24 bit identifier, 16 bit dimensions, 24 bit entry count */ bos.Write(new BitUint(24, 0x564342)); bos.Write(new BitUint(16, dimensions)); bos.Write(new BitUint(24, entries)); /* IN/OUT: 1 bit ordered flag */ BitUint ordered = new BitUint(1); bis.Read(ordered); bos.Write(ordered); if (ordered == 1) { /* IN/OUT: 5 bit initial length */ BitUint initialLength = new BitUint(5); bis.Read(initialLength); bos.Write(initialLength); int currentEntry = 0; while (currentEntry < entries) { /* IN/OUT: ilog(entries-current_entry) bit count w/ given length */ BitUint number = new BitUint((uint) Sound.WwiseRIFFVorbis.Ilog((uint) (entries - currentEntry))); bis.Read(number); bos.Write(number); currentEntry = (int) (currentEntry + number); } if (currentEntry > entries) throw new Exception("current_entry out of range"); } else { /* IN: 3 bit codeword length length, 1 bit sparse flag */ BitUint codewordLengthLength = new BitUint(3); BitUint sparse = new BitUint(1); bis.Read(codewordLengthLength); bis.Read(sparse); if (0 == codewordLengthLength || 5 < codewordLengthLength) { throw new Exception("nonsense codeword length"); } /* OUT: 1 bit sparse flag */ bos.Write(sparse); //if (sparse) //{ // cout << "Sparse" << endl; //} //else //{ // cout << "Nonsparse" << endl; //} for (int i = 0; i < entries; i++) { bool presentBool = true; if (sparse == 1) { /* IN/OUT 1 bit sparse presence flag */ BitUint present = new BitUint(1); bis.Read(present); bos.Write(present); presentBool = 0 != present; } if (presentBool) { /* IN: n bit codeword length-1 */ BitUint codewordLength = new BitUint(codewordLengthLength); bis.Read(codewordLength); /* OUT: 5 bit codeword length-1 */ bos.Write(new BitUint(5, codewordLength)); } } } // done with lengths // lookup table /* IN: 1 bit lookup type */ BitUint lookupType = new BitUint(1); bis.Read(lookupType); /* OUT: 4 bit lookup type */ bos.Write(new BitUint(4, lookupType)); if (lookupType == 0) { //cout << "no lookup table" << endl; } else if (lookupType == 1) { //cout << "lookup type 1" << endl; /* IN/OUT: 32 bit minimum length, 32 bit maximum length, 4 bit value length-1, 1 bit sequence flag */ BitUint min = new BitUint(32); BitUint max = new BitUint(32); BitUint valueLength = new BitUint(4); BitUint sequenceFlag = new BitUint(1); bis.Read(min); bis.Read(max); bis.Read(valueLength); bis.Read(sequenceFlag); bos.Write(min); bos.Write(max); bos.Write(valueLength); bos.Write(sequenceFlag); uint quantvals = _bookMaptype1Quantvals(entries, dimensions); for (uint i = 0; i < quantvals; i++) { /* IN/OUT: n bit value */ BitUint val = new BitUint(valueLength + 1); bis.Read(val); bos.Write(val); } } /* check that we used exactly all bytes */ /* note: if all bits are used in the last byte there will be one extra 0 byte */ if (0 != cbSize && bis.TotalBitsRead / 8 + 1 != (int) cbSize) { throw new Exception($"{cbSize}, {bis.TotalBitsRead / 8 + 1}"); } } private uint _bookMaptype1Quantvals(uint entries, uint dimensions) { /* get us a starting hint, we'll polish it below */ int bits = Sound.WwiseRIFFVorbis.Ilog(entries); int vals = (int) (entries >> (int) ((bits - 1) * (dimensions - 1) / dimensions)); while (true) { uint acc = 1; uint acc1 = 1; uint i; for (i = 0; i < dimensions; i++) { acc = (uint) (acc * vals); acc1 = (uint) (acc * vals + 1); } if (acc <= entries && acc1 > entries) { return (uint) vals; } else { if (acc > entries) vals--; else vals++; } } } public long? GetCodebook(int i) { if (i >= m_codebookCount - 1 || i < 0) return null; return m_codebookOffsets[i]; // return the offset // CodebookData[CodebookOffsets[i]] } public long GetCodebookSize(int i) { if (i >= m_codebookCount - 1 || i < 0) return -1; return m_codebookOffsets[i + 1] - m_codebookOffsets[i]; } public class InvalidID : Exception { } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using Should; using Xunit; namespace AutoMapper.UnitTests { namespace InterfaceMapping { public class When_mapping_an_interface_to_an_abstract_type : AutoMapperSpecBase { private DtoObject _result; public class ModelObject { public IChildModelObject Child { get; set; } } public interface IChildModelObject { string ChildProperty { get; set; } } public class SubChildModelObject : IChildModelObject { public string ChildProperty { get; set; } } public class DtoObject { public DtoChildObject Child { get; set; } } public abstract class DtoChildObject { public virtual string ChildProperty { get; set; } } public class SubDtoChildObject : DtoChildObject { } protected override void Establish_context() { Mapper.Reset(); var model = new ModelObject { Child = new SubChildModelObject {ChildProperty = "child property value"} }; Mapper.Initialize(cfg => { cfg.CreateMap<ModelObject, DtoObject>(); cfg.CreateMap<IChildModelObject, DtoChildObject>() .Include<SubChildModelObject, SubDtoChildObject>(); cfg.CreateMap<SubChildModelObject, SubDtoChildObject>(); }); Mapper.AssertConfigurationIsValid(); _result = Mapper.Map<ModelObject, DtoObject>(model); } [Fact] public void Should_map_Child_to_SubDtoChildObject_type() { _result.Child.ShouldBeType(typeof (SubDtoChildObject)); } [Fact] public void Should_map_ChildProperty_to_child_property_value() { _result.Child.ChildProperty.ShouldEqual("child property value"); } } #if !SILVERLIGHT && !NETFX_CORE public class When_mapping_a_concrete_type_to_an_interface_type : AutoMapperSpecBase { private IDestination _result; public class Source { public int Value { get; set; } } public interface IDestination { int Value { get; set; } } protected override void Establish_context() { Mapper.CreateMap<Source, IDestination>(); } protected override void Because_of() { _result = Mapper.Map<Source, IDestination>(new Source {Value = 5}); } [Fact] public void Should_create_an_implementation_of_the_interface() { _result.Value.ShouldEqual(5); } [Fact] public void Should_not_derive_from_INotifyPropertyChanged() { _result.ShouldNotBeInstanceOf<INotifyPropertyChanged>(); } } public class When_mapping_a_concrete_type_to_an_interface_type_that_derives_from_INotifyPropertyChanged : AutoMapperSpecBase { private IDestination _result; private int _count; public class Source { public int Value { get; set; } } public interface IDestination : INotifyPropertyChanged { int Value { get; set; } } protected override void Establish_context() { Mapper.CreateMap<Source, IDestination>(); } protected override void Because_of() { _result = Mapper.Map<Source, IDestination>(new Source {Value = 5}); } [Fact] public void Should_create_an_implementation_of_the_interface() { _result.Value.ShouldEqual(5); } [Fact] public void Should_derive_from_INotifyPropertyChanged() { var q = _result as INotifyPropertyChanged; q.ShouldNotBeNull(); } [Fact] public void Should_notify_property_changes() { var count = 0; _result.PropertyChanged += (o, e) => { count++; o.ShouldBeSameAs(_result); e.PropertyName.ShouldEqual("Value"); }; _result.Value = 42; count.ShouldEqual(1); _result.Value.ShouldEqual(42); } [Fact] public void Should_detach_event_handler() { _result.PropertyChanged += MyHandler; _count.ShouldEqual(0); _result.Value = 56; _count.ShouldEqual(1); _result.PropertyChanged -= MyHandler; _count.ShouldEqual(1); _result.Value = 75; _count.ShouldEqual(1); } private void MyHandler(object sender, PropertyChangedEventArgs e) { _count++; } } #endif public class When_mapping_a_derived_interface_to_an_derived_concrete_type : AutoMapperSpecBase { private Destination _result = null; public interface ISourceBase { int Id { get; } } public interface ISource : ISourceBase { int SecondId { get; } } public class Source : ISource { public int Id { get; set; } public int SecondId { get; set; } } public abstract class DestinationBase { public int Id { get; set; } } public class Destination : DestinationBase { public int SecondId { get; set; } } protected override void Establish_context() { Mapper.CreateMap<ISource, Destination>(); } protected override void Because_of() { _result = Mapper.Map<ISource, Destination>(new Source {Id = 7, SecondId = 42}); } [Fact] public void Should_map_base_interface_property() { _result.Id.ShouldEqual(7); } [Fact] public void Should_map_derived_interface_property() { _result.SecondId.ShouldEqual(42); } [Fact] public void Should_pass_configuration_testing() { Mapper.AssertConfigurationIsValid(); } } public class When_mapping_a_derived_interface_to_an_derived_concrete_type_with_readonly_interface_members : AutoMapperSpecBase { private Destination _result = null; public interface ISourceBase { int Id { get; } } public interface ISource : ISourceBase { int SecondId { get; } } public class Source : ISource { public int Id { get; set; } public int SecondId { get; set; } } public interface IDestinationBase { int Id { get; } } public interface IDestination : IDestinationBase { int SecondId { get; } } public abstract class DestinationBase : IDestinationBase { public int Id { get; set; } } public class Destination : DestinationBase, IDestination { public int SecondId { get; set; } } protected override void Establish_context() { Mapper.CreateMap<ISource, Destination>(); } protected override void Because_of() { _result = Mapper.Map<ISource, Destination>(new Source {Id = 7, SecondId = 42}); } [Fact] public void Should_map_base_interface_property() { _result.Id.ShouldEqual(7); } [Fact] public void Should_map_derived_interface_property() { _result.SecondId.ShouldEqual(42); } [Fact] public void Should_pass_configuration_testing() { Mapper.AssertConfigurationIsValid(); } } public class When_mapping_to_a_type_with_explicitly_implemented_interface_members : AutoMapperSpecBase { private Destination _destination; public class Source { public int Value { get; set; } } public interface IOtherDestination { int OtherValue { get; set; } } public class Destination : IOtherDestination { public int Value { get; set; } int IOtherDestination.OtherValue { get; set; } } protected override void Establish_context() { Mapper.CreateMap<Source, Destination>(); } protected override void Because_of() { _destination = Mapper.Map<Source, Destination>(new Source {Value = 10}); } [Fact] public void Should_ignore_interface_members_for_mapping() { _destination.Value.ShouldEqual(10); } [Fact] public void Should_ignore_interface_members_for_validation() { Mapper.AssertConfigurationIsValid(); } } public class MappingToInterfacesWithPolymorphism : AutoMapperSpecBase { private BaseDto[] _baseDtos; public interface IBase { } public interface IDerived : IBase { } public class Base : IBase { } public class Derived : Base, IDerived { } public class BaseDto { } public class DerivedDto : BaseDto { } //and following mappings: protected override void Establish_context() { Mapper.Initialize(cfg => { cfg.CreateMap<Base, BaseDto>().Include<Derived, DerivedDto>(); cfg.CreateMap<Derived, DerivedDto>(); cfg.CreateMap<IBase, BaseDto>().Include<IDerived, DerivedDto>(); cfg.CreateMap<IDerived, DerivedDto>(); }); } protected override void Because_of() { List<Base> list = new List<Base>() { new Derived() }; _baseDtos = Mapper.Map<IEnumerable<Base>, BaseDto[]>(list); } [Fact] public void Should_use_the_derived_type_map() { _baseDtos.First().ShouldBeType<DerivedDto>(); } } //[TestFixture, Explicit] //public class MappingToInterfacesPolymorphic //{ // [SetUp] // public void SetUp() // { // Mapper.Reset(); // } // public interface DomainInterface // { // Guid Id { get; set; } // NestedType Nested { get; set; } // } // public class NestedType // { // public virtual string Name { get; set; } // public virtual decimal DecimalValue { get; set; } // } // public class DomainImplA : DomainInterface // { // public virtual Guid Id { get; set; } // private NestedType nested; // public virtual NestedType Nested // { // get // { // if (nested == null) nested = new NestedType(); // return nested; // } // set { nested = value; } // } // } // public class DomainImplB : DomainInterface // { // public virtual Guid Id { get; set; } // private NestedType nested; // public virtual NestedType Nested // { // get // { // if (nested == null) nested = new NestedType(); // return nested; // } // set { nested = value; } // } // } // public class Dto // { // public Guid Id { get; set; } // public string Name { get; set; } // public decimal DecimalValue { get; set; } // } // [Fact] // public void CanMapToDomainInterface() // { // Mapper.CreateMap<DomainInterface, Dto>() // .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Nested.Name)) // .ForMember(dest => dest.DecimalValue, opt => opt.MapFrom(src => src.Nested.DecimalValue)); // Mapper.CreateMap<Dto, DomainInterface>() // .ForMember(dest => dest.Nested.Name, opt => opt.MapFrom(src => src.Name)) // .ForMember(dest => dest.Nested.DecimalValue, opt => opt.MapFrom(src => src.DecimalValue)); // var domainInstance1 = new DomainImplA(); // var domainInstance2 = new DomainImplB(); // var domainInstance3 = new DomainImplA(); // var dtoCollection = new List<Dto> // { // Mapper.Map<DomainInterface, Dto>(domainInstance1), // Mapper.Map<DomainInterface, Dto>(domainInstance2), // Mapper.Map<DomainInterface, Dto>(domainInstance3) // }; // dtoCollection[0].Id = Guid.NewGuid(); // dtoCollection[0].DecimalValue = 1M; // dtoCollection[0].Name = "Bob"; // dtoCollection[1].Id = Guid.NewGuid(); // dtoCollection[1].DecimalValue = 0.1M; // dtoCollection[1].Name = "Frank"; // dtoCollection[2].Id = Guid.NewGuid(); // dtoCollection[2].DecimalValue = 2.1M; // dtoCollection[2].Name = "Sam"; // Mapper.Map<Dto, DomainInterface>(dtoCollection[0], domainInstance1); // Mapper.Map<Dto, DomainInterface>(dtoCollection[1], domainInstance2); // Mapper.Map<Dto, DomainInterface>(dtoCollection[2], domainInstance3); // dtoCollection[0].Id.ShouldEqual(domainInstance1.Id); // dtoCollection[1].Id.ShouldEqual(domainInstance2.Id); // dtoCollection[2].Id.ShouldEqual(domainInstance3.Id); // dtoCollection[0].DecimalValue.ShouldEqual(domainInstance1.Nested.DecimalValue); // dtoCollection[1].DecimalValue.ShouldEqual(domainInstance2.Nested.DecimalValue); // dtoCollection[2].DecimalValue.ShouldEqual(domainInstance3.Nested.DecimalValue); // dtoCollection[0].DecimalValue.ShouldEqual(domainInstance1.Nested.Name); // dtoCollection[1].DecimalValue.ShouldEqual(domainInstance2.Nested.Name); // dtoCollection[2].DecimalValue.ShouldEqual(domainInstance3.Nested.Name); // } //} } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Text { [Serializable] public sealed class DecoderReplacementFallback : DecoderFallback { // Our variables private String strDefault; // Construction. Default replacement fallback uses no best fit and ? replacement string public DecoderReplacementFallback() : this("?") { } public DecoderReplacementFallback(String replacement) { if (replacement == null) throw new ArgumentNullException(nameof(replacement)); Contract.EndContractBlock(); // Make sure it doesn't have bad surrogate pairs bool bFoundHigh = false; for (int i = 0; i < replacement.Length; i++) { // Found a surrogate? if (Char.IsSurrogate(replacement, i)) { // High or Low? if (Char.IsHighSurrogate(replacement, i)) { // if already had a high one, stop if (bFoundHigh) break; // break & throw at the bFoundHIgh below bFoundHigh = true; } else { // Low, did we have a high? if (!bFoundHigh) { // Didn't have one, make if fail when we stop bFoundHigh = true; break; } // Clear flag bFoundHigh = false; } } // If last was high we're in trouble (not surrogate so not low surrogate, so break) else if (bFoundHigh) break; } if (bFoundHigh) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex", nameof(replacement))); strDefault = replacement; } public String DefaultString { get { return strDefault; } } public override DecoderFallbackBuffer CreateFallbackBuffer() { return new DecoderReplacementFallbackBuffer(this); } // Maximum number of characters that this instance of this fallback could return public override int MaxCharCount { get { return strDefault.Length; } } public override bool Equals(Object value) { DecoderReplacementFallback that = value as DecoderReplacementFallback; if (that != null) { return (strDefault == that.strDefault); } return (false); } public override int GetHashCode() { return strDefault.GetHashCode(); } } public sealed class DecoderReplacementFallbackBuffer : DecoderFallbackBuffer { // Store our default string private String strDefault; private int fallbackCount = -1; private int fallbackIndex = -1; // Construction public DecoderReplacementFallbackBuffer(DecoderReplacementFallback fallback) { strDefault = fallback.DefaultString; } // Fallback Methods public override bool Fallback(byte[] bytesUnknown, int index) { // We expect no previous fallback in our buffer // We can't call recursively but others might (note, we don't test on last char!!!) if (fallbackCount >= 1) { ThrowLastBytesRecursive(bytesUnknown); } // Go ahead and get our fallback if (strDefault.Length == 0) return false; fallbackCount = strDefault.Length; fallbackIndex = -1; return true; } public override char GetNextChar() { // We want it to get < 0 because == 0 means that the current/last character is a fallback // and we need to detect recursion. We could have a flag but we already have this counter. fallbackCount--; fallbackIndex++; // Do we have anything left? 0 is now last fallback char, negative is nothing left if (fallbackCount < 0) return '\0'; // Need to get it out of the buffer. // Make sure it didn't wrap from the fast count-- path if (fallbackCount == int.MaxValue) { fallbackCount = -1; return '\0'; } // Now make sure its in the expected range Debug.Assert(fallbackIndex < strDefault.Length && fallbackIndex >= 0, "Index exceeds buffer range"); return strDefault[fallbackIndex]; } public override bool MovePrevious() { // Back up one, only if we just processed the last character (or earlier) if (fallbackCount >= -1 && fallbackIndex >= 0) { fallbackIndex--; fallbackCount++; return true; } // Return false 'cause we couldn't do it. return false; } // How many characters left to output? public override int Remaining { get { // Our count is 0 for 1 character left. return (fallbackCount < 0) ? 0 : fallbackCount; } } // Clear the buffer public override unsafe void Reset() { fallbackCount = -1; fallbackIndex = -1; byteStart = null; } // This version just counts the fallback and doesn't actually copy anything. internal unsafe override int InternalFallback(byte[] bytes, byte* pBytes) // Right now this has both bytes and bytes[], since we might have extra bytes, hence the // array, and we might need the index, hence the byte* { // return our replacement string Length return strDefault.Length; } } }
// 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.Serialization { using System.Configuration; using System.Reflection; using System.Reflection.Emit; using System.Collections; using System.IO; using System; using System.Text; using System.Xml; using System.Threading; using System.Security; using System.Security.Policy; using System.Xml.Serialization.Configuration; using System.Diagnostics; using System.CodeDom.Compiler; using System.Globalization; using System.Runtime.Versioning; using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; using System.Xml.Extensions; using System.Linq; internal class TempAssembly { internal const string GeneratedAssemblyNamespace = "Microsoft.Xml.Serialization.GeneratedAssembly"; private Assembly _assembly; private XmlSerializerImplementation _contract = null; private IDictionary _writerMethods; private IDictionary _readerMethods; private TempMethodDictionary _methods; private Hashtable _assemblies = new Hashtable(); internal class TempMethod { internal MethodInfo writeMethod; internal MethodInfo readMethod; internal string name; internal string ns; internal bool isSoap; internal string methodKey; } private TempAssembly() { } internal TempAssembly(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace, string location, Evidence evidence) { #if !NET_NATIVE bool containsSoapMapping = false; for (int i = 0; i < xmlMappings.Length; i++) { xmlMappings[i].CheckShallow(); if (xmlMappings[i].IsSoap) { containsSoapMapping = true; } } // We will make best effort to use RefEmit for assembly generation bool fallbackToCSharpAssemblyGeneration = false; if (!containsSoapMapping && !TempAssembly.UseLegacySerializerGeneration) { try { _assembly = GenerateRefEmitAssembly(xmlMappings, types, defaultNamespace, evidence); } // Only catch and handle known failures with RefEmit catch (CodeGeneratorConversionException) { fallbackToCSharpAssemblyGeneration = true; } // Add other known exceptions here... // } else { fallbackToCSharpAssemblyGeneration = true; } if (fallbackToCSharpAssemblyGeneration) { _assembly = GenerateAssembly(xmlMappings, types, defaultNamespace, evidence, XmlSerializerCompilerParameters.Create(location), null, _assemblies); } #endif #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (_assembly == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "Failed to generate XmlSerializer assembly, but did not throw")); #endif InitAssemblyMethods(xmlMappings); } internal TempAssembly(XmlMapping[] xmlMappings, Assembly assembly, XmlSerializerImplementation contract) { _assembly = assembly; InitAssemblyMethods(xmlMappings); _contract = contract; } internal static bool UseLegacySerializerGeneration { get { return false; } } internal TempAssembly(XmlSerializerImplementation contract) { _contract = contract; } internal XmlSerializerImplementation Contract { get { if (_contract == null) { _contract = (XmlSerializerImplementation)Activator.CreateInstance(GetTypeFromAssembly(_assembly, "XmlSerializerContract")); } return _contract; } } internal void InitAssemblyMethods(XmlMapping[] xmlMappings) { _methods = new TempMethodDictionary(); for (int i = 0; i < xmlMappings.Length; i++) { TempMethod method = new TempMethod(); method.isSoap = xmlMappings[i].IsSoap; method.methodKey = xmlMappings[i].Key; XmlTypeMapping xmlTypeMapping = xmlMappings[i] as XmlTypeMapping; if (xmlTypeMapping != null) { method.name = xmlTypeMapping.ElementName; method.ns = xmlTypeMapping.Namespace; } _methods.Add(xmlMappings[i].Key, method); } } /// <devdoc> /// <para> /// Attempts to load pre-generated serialization assembly. /// First check for the [XmlSerializerAssembly] attribute /// </para> /// </devdoc> // SxS: This method does not take any resource name and does not expose any resources to the caller. // It's OK to suppress the SxS warning. internal static Assembly LoadGeneratedAssembly(Type type, string defaultNamespace, out XmlSerializerImplementation contract) { Assembly serializer = null; contract = null; string serializerName = null; //BinCompat TODO: Check if this needs to come back // Packaged apps do not support loading generated serializers. /*if (Microsoft.Win32.UnsafeNativeMethods.IsPackagedProcess.Value) { return null; }*/ // check to see if we loading explicit pre-generated assembly IEnumerable<Attribute> attrs = type.GetTypeInfo().GetCustomAttributes(typeof(XmlSerializerAssemblyAttribute), false); if (attrs.Count() == 0) { // Guess serializer name: if parent assembly signed use strong name AssemblyName name = type.GetTypeInfo().Assembly.GetName(); serializerName = Compiler.GetTempAssemblyName(name, defaultNamespace); // use strong name name.Name = serializerName; //BinCompat TODO: Check if this was actually needed //name.CodeBase = null; //name.CultureInfo = CultureInfo.InvariantCulture; try { serializer = Assembly.Load(name); } catch (Exception e) { if (e is OutOfMemoryException) { throw; } byte[] token = name.GetPublicKeyToken(); if (token != null && token.Length > 0) { // the parent assembly was signed, so do not try to LoadWithPartialName return null; } //BinCompat TODO: Test this throw new NotImplementedException(string.Format("Could not load assembly ", name)); /*#pragma warning disable 618 serializer = Assembly.LoadWithPartialName(serializerName, null); #pragma warning restore 618*/ } if (serializer == null) { return null; } } else { XmlSerializerAssemblyAttribute assemblyAttribute = (XmlSerializerAssemblyAttribute)attrs.First(); if (assemblyAttribute.AssemblyName != null && assemblyAttribute.CodeBase != null) throw new InvalidOperationException(SR.Format(SR.XmlPregenInvalidXmlSerializerAssemblyAttribute, "AssemblyName", "CodeBase")); // found XmlSerializerAssemblyAttribute attribute, it should have all needed information to load the pre-generated serializer if (assemblyAttribute.AssemblyName != null) { serializerName = assemblyAttribute.AssemblyName; //BinCompat TODO: Test this throw new NotImplementedException(string.Format("Could not load assembly ", serializerName)); /*#pragma warning disable 618 serializer = Assembly.LoadWithPartialName(serializerName, null); #pragma warning restore 618*/ } else if (assemblyAttribute.CodeBase != null && assemblyAttribute.CodeBase.Length > 0) { serializerName = assemblyAttribute.CodeBase; //BinCompat TODO: Test this throw new NotImplementedException(string.Format("Could not load assembly ", serializerName)); //serializer = Assembly.LoadFrom(serializerName); } else { serializerName = type.GetTypeInfo().Assembly.FullName; serializer = type.GetTypeInfo().Assembly; } if (serializer == null) { throw new FileNotFoundException(null, serializerName); } } Type contractType = GetTypeFromAssembly(serializer, "XmlSerializerContract"); contract = (XmlSerializerImplementation)Activator.CreateInstance(contractType); if (contract.CanSerialize(type)) return serializer; return null; } // SxS: This method does not take any resource name and does not expose any resources to the caller. // It's OK to suppress the SxS warning. private static string GenerateAssemblyId(Type type) { //BinCompat TODO throw new NotImplementedException(); /*Module[] modules = type.GetTypeInfo().Assembly.GetModules(); ArrayList list = new ArrayList(); for (int i = 0; i < modules.Length; i++) { list.Add(modules[i].ModuleVersionId.ToString()); } list.Sort(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < list.Count; i++) { sb.Append(list[i].ToString()); sb.Append(","); } return sb.ToString();*/ } internal static Assembly GenerateAssembly(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace, Evidence evidence, XmlSerializerCompilerParameters parameters, Assembly assembly, Hashtable assemblies) { Compiler compiler = new Compiler(); try { Hashtable scopeTable = new Hashtable(); foreach (XmlMapping mapping in xmlMappings) scopeTable[mapping.Scope] = mapping; TypeScope[] scopes = new TypeScope[scopeTable.Keys.Count]; scopeTable.Keys.CopyTo(scopes, 0); assemblies.Clear(); Hashtable importedTypes = new Hashtable(); foreach (TypeScope scope in scopes) { foreach (Type t in scope.Types) { compiler.AddImport(t, importedTypes); Assembly a = t.GetTypeInfo().Assembly; string name = a.FullName; if (assemblies[name] != null) continue; } } for (int i = 0; i < types.Length; i++) { compiler.AddImport(types[i], importedTypes); } compiler.AddImport(typeof(object).GetTypeInfo().Assembly); compiler.AddImport(typeof(XmlSerializer).GetTypeInfo().Assembly); IndentedWriter writer = new IndentedWriter(compiler.Source, false); writer.WriteLine("#if _DYNAMIC_XMLSERIALIZER_COMPILATION"); writer.WriteLine("[assembly:System.Security.AllowPartiallyTrustedCallers()]"); writer.WriteLine("[assembly:System.Security.SecurityTransparent()]"); writer.WriteLine("[assembly:System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)]"); writer.WriteLine("#endif"); // Add AssemblyVersion attribute to match parent accembly version if (types != null && types.Length > 0 && types[0] != null) { writer.WriteLine("[assembly:System.Reflection.AssemblyVersionAttribute(\"" + types[0].GetTypeInfo().Assembly.GetName().Version.ToString() + "\")]"); } if (assembly != null && types.Length > 0) { for (int i = 0; i < types.Length; i++) { Type type = types[i]; if (type == null) continue; if (DynamicAssemblies.IsTypeDynamic(type)) { throw new InvalidOperationException(SR.Format(SR.XmlPregenTypeDynamic, types[i].FullName)); } } writer.Write("[assembly:"); writer.Write(typeof(XmlSerializerVersionAttribute).FullName); writer.Write("("); writer.Write("ParentAssemblyId="); ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, GenerateAssemblyId(types[0])); writer.Write(", Version="); ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, ThisAssembly.Version); if (defaultNamespace != null) { writer.Write(", Namespace="); ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, defaultNamespace); } writer.WriteLine(")]"); } CodeIdentifiers classes = new CodeIdentifiers(); classes.AddUnique("XmlSerializationWriter", "XmlSerializationWriter"); classes.AddUnique("XmlSerializationReader", "XmlSerializationReader"); string suffix = null; if (types != null && types.Length == 1 && types[0] != null) { suffix = CodeIdentifier.MakeValid(types[0].Name); if (types[0].IsArray) { suffix += "Array"; } } writer.WriteLine("namespace " + GeneratedAssemblyNamespace + " {"); writer.Indent++; writer.WriteLine(); string writerClass = "XmlSerializationWriter" + suffix; writerClass = classes.AddUnique(writerClass, writerClass); XmlSerializationWriterCodeGen writerCodeGen = new XmlSerializationWriterCodeGen(writer, scopes, "public", writerClass); writerCodeGen.GenerateBegin(); string[] writeMethodNames = new string[xmlMappings.Length]; for (int i = 0; i < xmlMappings.Length; i++) { writeMethodNames[i] = writerCodeGen.GenerateElement(xmlMappings[i]); } writerCodeGen.GenerateEnd(); writer.WriteLine(); string readerClass = "XmlSerializationReader" + suffix; readerClass = classes.AddUnique(readerClass, readerClass); XmlSerializationReaderCodeGen readerCodeGen = new XmlSerializationReaderCodeGen(writer, scopes, "public", readerClass); readerCodeGen.GenerateBegin(); string[] readMethodNames = new string[xmlMappings.Length]; for (int i = 0; i < xmlMappings.Length; i++) { readMethodNames[i] = readerCodeGen.GenerateElement(xmlMappings[i]); } readerCodeGen.GenerateEnd(readMethodNames, xmlMappings, types); string baseSerializer = readerCodeGen.GenerateBaseSerializer("XmlSerializer1", readerClass, writerClass, classes); Hashtable serializers = new Hashtable(); for (int i = 0; i < xmlMappings.Length; i++) { if (serializers[xmlMappings[i].Key] == null) { serializers[xmlMappings[i].Key] = readerCodeGen.GenerateTypedSerializer(readMethodNames[i], writeMethodNames[i], xmlMappings[i], classes, baseSerializer, readerClass, writerClass); } } readerCodeGen.GenerateSerializerContract("XmlSerializerContract", xmlMappings, types, readerClass, readMethodNames, writerClass, writeMethodNames, serializers); writer.Indent--; writer.WriteLine("}"); return compiler.Compile(assembly, defaultNamespace, parameters, evidence); } finally { compiler.Close(); } } #if !NET_NATIVE [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2106:SecureAsserts", Justification = "It is safe because the serialization assembly is generated by the framework code, not by the user.")] internal static Assembly GenerateRefEmitAssembly(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace, Evidence evidence) { var scopeTable = new Dictionary<TypeScope, XmlMapping>(); foreach (XmlMapping mapping in xmlMappings) scopeTable[mapping.Scope] = mapping; TypeScope[] scopes = new TypeScope[scopeTable.Keys.Count]; scopeTable.Keys.CopyTo(scopes, 0); string assemblyName = "Microsoft.GeneratedCode"; AssemblyBuilder assemblyBuilder = CodeGenerator.CreateAssemblyBuilder(assemblyName); ConstructorInfo SecurityTransparentAttribute_ctor = typeof(SecurityTransparentAttribute).GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty<Type>() ); assemblyBuilder.SetCustomAttribute(new CustomAttributeBuilder(SecurityTransparentAttribute_ctor, Array.Empty<object>())); ConstructorInfo AllowPartiallyTrustedCallersAttribute_ctor = typeof(AllowPartiallyTrustedCallersAttribute).GetConstructor( CodeGenerator.EmptyTypeArray ); assemblyBuilder.SetCustomAttribute(new CustomAttributeBuilder(AllowPartiallyTrustedCallersAttribute_ctor, new Object[0])); ConstructorInfo SecurityRulesAttribute_ctor = typeof(SecurityRulesAttribute).GetConstructor( new Type[] { typeof(SecurityRuleSet) } ); assemblyBuilder.SetCustomAttribute(new CustomAttributeBuilder(SecurityRulesAttribute_ctor, new Object[] { SecurityRuleSet.Level1 })); // Add AssemblyVersion attribute to match parent accembly version if (types != null && types.Length > 0 && types[0] != null) { ConstructorInfo AssemblyVersionAttribute_ctor = typeof(AssemblyVersionAttribute).GetConstructor( new Type[] { typeof(String) } ); string assemblyVersion = types[0].GetTypeInfo().Assembly.GetName().Version.ToString(); assemblyBuilder.SetCustomAttribute(new CustomAttributeBuilder(AssemblyVersionAttribute_ctor, new Object[] { assemblyVersion })); } CodeIdentifiers classes = new CodeIdentifiers(); classes.AddUnique("XmlSerializationWriter", "XmlSerializationWriter"); classes.AddUnique("XmlSerializationReader", "XmlSerializationReader"); string suffix = null; if (types != null && types.Length == 1 && types[0] != null) { suffix = CodeIdentifier.MakeValid(types[0].Name); if (types[0].IsArray) { suffix += "Array"; } } ModuleBuilder moduleBuilder = CodeGenerator.CreateModuleBuilder(assemblyBuilder, assemblyName); string writerClass = "XmlSerializationWriter" + suffix; writerClass = classes.AddUnique(writerClass, writerClass); XmlSerializationWriterILGen writerCodeGen = new XmlSerializationWriterILGen(scopes, "public", writerClass); writerCodeGen.ModuleBuilder = moduleBuilder; writerCodeGen.GenerateBegin(); string[] writeMethodNames = new string[xmlMappings.Length]; for (int i = 0; i < xmlMappings.Length; i++) { writeMethodNames[i] = writerCodeGen.GenerateElement(xmlMappings[i]); } Type writerType = writerCodeGen.GenerateEnd(); string readerClass = "XmlSerializationReader" + suffix; readerClass = classes.AddUnique(readerClass, readerClass); XmlSerializationReaderILGen readerCodeGen = new XmlSerializationReaderILGen(scopes, "public", readerClass); readerCodeGen.ModuleBuilder = moduleBuilder; readerCodeGen.CreatedTypes.Add(writerType.Name, writerType); readerCodeGen.GenerateBegin(); string[] readMethodNames = new string[xmlMappings.Length]; for (int i = 0; i < xmlMappings.Length; i++) { readMethodNames[i] = readerCodeGen.GenerateElement(xmlMappings[i]); } readerCodeGen.GenerateEnd(readMethodNames, xmlMappings, types); string baseSerializer = readerCodeGen.GenerateBaseSerializer("XmlSerializer1", readerClass, writerClass, classes); var serializers = new Dictionary<string, string>(); for (int i = 0; i < xmlMappings.Length; i++) { if (!serializers.ContainsKey(xmlMappings[i].Key)) { serializers[xmlMappings[i].Key] = readerCodeGen.GenerateTypedSerializer(readMethodNames[i], writeMethodNames[i], xmlMappings[i], classes, baseSerializer, readerClass, writerClass); } } readerCodeGen.GenerateSerializerContract("XmlSerializerContract", xmlMappings, types, readerClass, readMethodNames, writerClass, writeMethodNames, serializers); return writerType.GetTypeInfo().Assembly; } #endif private static MethodInfo GetMethodFromType(Type type, string methodName) { MethodInfo method = type.GetMethod(methodName); if (method != null) return method; // Not support pregen. Workaround SecurityCritical required for assembly.CodeBase api. MissingMethodException missingMethod = new MissingMethodException(type.FullName + "::" + methodName); throw missingMethod; } internal static Type GetTypeFromAssembly(Assembly assembly, string typeName) { typeName = GeneratedAssemblyNamespace + "." + typeName; Type type = assembly.GetType(typeName); if (type == null) throw new InvalidOperationException(SR.Format(SR.XmlMissingType, typeName, assembly.FullName)); return type; } internal bool CanRead(XmlMapping mapping, XmlReader xmlReader) { if (mapping == null) return false; if (mapping.Accessor.Any) { return true; } TempMethod method = _methods[mapping.Key]; return xmlReader.IsStartElement(method.name, method.ns); } private string ValidateEncodingStyle(string encodingStyle, string methodKey) { if (encodingStyle != null && encodingStyle.Length > 0) { if (_methods[methodKey].isSoap) { if (encodingStyle != Soap.Encoding && encodingStyle != Soap12.Encoding) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidEncoding3, encodingStyle, Soap.Encoding, Soap12.Encoding)); } } else { throw new InvalidOperationException(SR.Format(SR.XmlInvalidEncodingNotEncoded1, encodingStyle)); } } else { if (_methods[methodKey].isSoap) { encodingStyle = Soap.Encoding; } } return encodingStyle; } internal object InvokeReader(XmlMapping mapping, XmlReader xmlReader, XmlDeserializationEvents events, string encodingStyle) { XmlSerializationReader reader = null; try { encodingStyle = ValidateEncodingStyle(encodingStyle, mapping.Key); reader = Contract.Reader; reader.Init(xmlReader, events, encodingStyle, this); if (_methods[mapping.Key].readMethod == null) { if (_readerMethods == null) { _readerMethods = Contract.ReadMethods; } string methodName = (string)_readerMethods[mapping.Key]; if (methodName == null) { throw new InvalidOperationException(SR.Format(SR.XmlNotSerializable, mapping.Accessor.Name)); } _methods[mapping.Key].readMethod = GetMethodFromType(reader.GetType(), methodName); } return _methods[mapping.Key].readMethod.Invoke(reader, Array.Empty<object>()); } catch (SecurityException e) { throw new InvalidOperationException(SR.XmlNoPartialTrust, e); } finally { if (reader != null) reader.Dispose(); } } internal void InvokeWriter(XmlMapping mapping, XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id) { XmlSerializationWriter writer = null; try { encodingStyle = ValidateEncodingStyle(encodingStyle, mapping.Key); writer = Contract.Writer; writer.Init(xmlWriter, namespaces, encodingStyle, id, this); if (_methods[mapping.Key].writeMethod == null) { if (_writerMethods == null) { _writerMethods = Contract.WriteMethods; } string methodName = (string)_writerMethods[mapping.Key]; if (methodName == null) { throw new InvalidOperationException(SR.Format(SR.XmlNotSerializable, mapping.Accessor.Name)); } _methods[mapping.Key].writeMethod = GetMethodFromType(writer.GetType(), methodName); } _methods[mapping.Key].writeMethod.Invoke(writer, new object[] { o }); } catch (SecurityException e) { throw new InvalidOperationException(SR.XmlNoPartialTrust, e); } finally { if (writer != null) writer.Dispose(); } } internal sealed class TempMethodDictionary : Dictionary<string, TempMethod> { } } internal sealed class XmlSerializerCompilerParameters { private bool _needTempDirAccess; private CompilerParameters _parameters; private XmlSerializerCompilerParameters(CompilerParameters parameters, bool needTempDirAccess) { _needTempDirAccess = needTempDirAccess; _parameters = parameters; } internal bool IsNeedTempDirAccess { get { return _needTempDirAccess; } } internal CompilerParameters CodeDomParameters { get { return _parameters; } } internal static XmlSerializerCompilerParameters Create(string location) { CompilerParameters parameters = new CompilerParameters(); parameters.GenerateInMemory = true; if (string.IsNullOrEmpty(location)) { // Trim leading and trailing white spaces (VSWhidbey 229873) if (!string.IsNullOrEmpty(location)) { location = location.Trim(); } } parameters.TempFiles = new TempFileCollection(location); return new XmlSerializerCompilerParameters(parameters, string.IsNullOrEmpty(location)); } internal static XmlSerializerCompilerParameters Create(CompilerParameters parameters, bool needTempDirAccess) { return new XmlSerializerCompilerParameters(parameters, needTempDirAccess); } } internal class TempAssemblyCacheKey { private string _ns; private object _type; internal TempAssemblyCacheKey(string ns, object type) { _type = type; _ns = ns; } public override bool Equals(object o) { TempAssemblyCacheKey key = o as TempAssemblyCacheKey; if (key == null) return false; return (key._type == _type && key._ns == _ns); } public override int GetHashCode() { return ((_ns != null ? _ns.GetHashCode() : 0) ^ (_type != null ? _type.GetHashCode() : 0)); } } internal class TempAssemblyCache { private Dictionary<TempAssemblyCacheKey, TempAssembly> _cache = new Dictionary<TempAssemblyCacheKey, TempAssembly>(); internal TempAssembly this[string ns, object o] { get { TempAssembly tempAssembly; _cache.TryGetValue(new TempAssemblyCacheKey(ns, o), out tempAssembly); return tempAssembly; } } internal void Add(string ns, object o, TempAssembly assembly) { TempAssemblyCacheKey key = new TempAssemblyCacheKey(ns, o); lock (this) { TempAssembly tempAssembly; if (_cache.TryGetValue(key, out tempAssembly) && tempAssembly == assembly) return; _cache = new Dictionary<TempAssemblyCacheKey, TempAssembly>(_cache); // clone _cache[key] = assembly; } } } }
/* * 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.Cache { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cache.Expiry; using Apache.Ignite.Core.Cache.Query; using Apache.Ignite.Core.Cache.Query.Continuous; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Cache.Query; using Apache.Ignite.Core.Impl.Cache.Query.Continuous; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Unmanaged; using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils; /// <summary> /// Native cache wrapper. /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")] internal class CacheImpl<TK, TV> : PlatformTarget, ICache<TK, TV> { /** Duration: unchanged. */ private const long DurUnchanged = -2; /** Duration: eternal. */ private const long DurEternal = -1; /** Duration: zero. */ private const long DurZero = 0; /** Ignite instance. */ private readonly Ignite _ignite; /** Flag: skip store. */ private readonly bool _flagSkipStore; /** Flag: keep binary. */ private readonly bool _flagKeepBinary; /** Flag: async mode.*/ private readonly bool _flagAsync; /** Flag: no-retries.*/ private readonly bool _flagNoRetries; /** Async instance. */ private readonly Lazy<CacheImpl<TK, TV>> _asyncInstance; /// <summary> /// Constructor. /// </summary> /// <param name="grid">Grid.</param> /// <param name="target">Target.</param> /// <param name="marsh">Marshaller.</param> /// <param name="flagSkipStore">Skip store flag.</param> /// <param name="flagKeepBinary">Keep binary flag.</param> /// <param name="flagAsync">Async mode flag.</param> /// <param name="flagNoRetries">No-retries mode flag.</param> public CacheImpl(Ignite grid, IUnmanagedTarget target, Marshaller marsh, bool flagSkipStore, bool flagKeepBinary, bool flagAsync, bool flagNoRetries) : base(target, marsh) { _ignite = grid; _flagSkipStore = flagSkipStore; _flagKeepBinary = flagKeepBinary; _flagAsync = flagAsync; _flagNoRetries = flagNoRetries; _asyncInstance = new Lazy<CacheImpl<TK, TV>>(() => new CacheImpl<TK, TV>(this)); } /// <summary> /// Initializes a new async instance. /// </summary> /// <param name="cache">The cache.</param> private CacheImpl(CacheImpl<TK, TV> cache) : base(UU.CacheWithAsync(cache.Target), cache.Marshaller) { _ignite = cache._ignite; _flagSkipStore = cache._flagSkipStore; _flagKeepBinary = cache._flagKeepBinary; _flagAsync = true; _flagNoRetries = cache._flagNoRetries; } /** <inheritDoc /> */ public IIgnite Ignite { get { return _ignite; } } /** <inheritDoc /> */ private bool IsAsync { get { return _flagAsync; } } /// <summary> /// Gets and resets task for previous asynchronous operation. /// </summary> /// <param name="lastAsyncOp">The last async op id.</param> /// <returns> /// Task for previous asynchronous operation. /// </returns> private Task GetTask(CacheOp lastAsyncOp) { return GetTask<object>(lastAsyncOp); } /// <summary> /// Gets and resets task for previous asynchronous operation. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="lastAsyncOp">The last async op id.</param> /// <param name="converter">The converter.</param> /// <returns> /// Task for previous asynchronous operation. /// </returns> private Task<TResult> GetTask<TResult>(CacheOp lastAsyncOp, Func<BinaryReader, TResult> converter = null) { Debug.Assert(_flagAsync); return GetFuture((futId, futTypeId) => UU.TargetListenFutureForOperation(Target, futId, futTypeId, (int) lastAsyncOp), _flagKeepBinary, converter).Task; } /** <inheritDoc /> */ public string Name { get { return DoInOp<string>((int)CacheOp.GetName); } } /** <inheritDoc /> */ public CacheConfiguration GetConfiguration() { return DoInOp((int) CacheOp.GetConfig, stream => new CacheConfiguration(Marshaller.StartUnmarshal(stream))); } /** <inheritDoc /> */ public bool IsEmpty() { return GetSize() == 0; } /** <inheritDoc /> */ public ICache<TK, TV> WithSkipStore() { if (_flagSkipStore) return this; return new CacheImpl<TK, TV>(_ignite, UU.CacheWithSkipStore(Target), Marshaller, true, _flagKeepBinary, _flagAsync, true); } /// <summary> /// Skip store flag getter. /// </summary> internal bool IsSkipStore { get { return _flagSkipStore; } } /** <inheritDoc /> */ public ICache<TK1, TV1> WithKeepBinary<TK1, TV1>() { if (_flagKeepBinary) { var result = this as ICache<TK1, TV1>; if (result == null) throw new InvalidOperationException( "Can't change type of binary cache. WithKeepBinary has been called on an instance of " + "binary cache with incompatible generic arguments."); return result; } return new CacheImpl<TK1, TV1>(_ignite, UU.CacheWithKeepBinary(Target), Marshaller, _flagSkipStore, true, _flagAsync, _flagNoRetries); } /** <inheritDoc /> */ public ICache<TK, TV> WithExpiryPolicy(IExpiryPolicy plc) { IgniteArgumentCheck.NotNull(plc, "plc"); long create = ConvertDuration(plc.GetExpiryForCreate()); long update = ConvertDuration(plc.GetExpiryForUpdate()); long access = ConvertDuration(plc.GetExpiryForAccess()); IUnmanagedTarget cache0 = UU.CacheWithExpiryPolicy(Target, create, update, access); return new CacheImpl<TK, TV>(_ignite, cache0, Marshaller, _flagSkipStore, _flagKeepBinary, _flagAsync, _flagNoRetries); } /// <summary> /// Convert TimeSpan to duration recognizable by Java. /// </summary> /// <param name="dur">.Net duration.</param> /// <returns>Java duration in milliseconds.</returns> private static long ConvertDuration(TimeSpan? dur) { if (dur.HasValue) { if (dur.Value == TimeSpan.MaxValue) return DurEternal; long dur0 = (long)dur.Value.TotalMilliseconds; return dur0 > 0 ? dur0 : DurZero; } return DurUnchanged; } /** <inheritDoc /> */ public bool IsKeepBinary { get { return _flagKeepBinary; } } /** <inheritDoc /> */ public void LoadCache(ICacheEntryFilter<TK, TV> p, params object[] args) { LoadCache0(p, args, (int)CacheOp.LoadCache); } /** <inheritDoc /> */ public Task LoadCacheAsync(ICacheEntryFilter<TK, TV> p, params object[] args) { AsyncInstance.LoadCache(p, args); return AsyncInstance.GetTask(CacheOp.LoadCache); } /** <inheritDoc /> */ public void LocalLoadCache(ICacheEntryFilter<TK, TV> p, params object[] args) { LoadCache0(p, args, (int)CacheOp.LocLoadCache); } /** <inheritDoc /> */ public Task LocalLoadCacheAsync(ICacheEntryFilter<TK, TV> p, params object[] args) { AsyncInstance.LocalLoadCache(p, args); return AsyncInstance.GetTask(CacheOp.LocLoadCache); } /// <summary> /// Loads the cache. /// </summary> private void LoadCache0(ICacheEntryFilter<TK, TV> p, object[] args, int opId) { DoOutOp(opId, writer => { if (p != null) { var p0 = new CacheEntryFilterHolder(p, (k, v) => p.Invoke(new CacheEntry<TK, TV>((TK) k, (TV) v)), Marshaller, IsKeepBinary); writer.WriteObject(p0); } else writer.WriteObject<CacheEntryFilterHolder>(null); writer.WriteArray(args); }); } /** <inheritDoc /> */ public bool ContainsKey(TK key) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutOp((int)CacheOp.ContainsKey, key) == True; } /** <inheritDoc /> */ public Task<bool> ContainsKeyAsync(TK key) { AsyncInstance.ContainsKey(key); return AsyncInstance.GetTask<bool>(CacheOp.ContainsKey); } /** <inheritDoc /> */ public bool ContainsKeys(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); return DoOutOp((int)CacheOp.ContainsKeys, writer => WriteEnumerable(writer, keys)) == True; } /** <inheritDoc /> */ public Task<bool> ContainsKeysAsync(IEnumerable<TK> keys) { AsyncInstance.ContainsKeys(keys); return AsyncInstance.GetTask<bool>(CacheOp.ContainsKeys); } /** <inheritDoc /> */ public TV LocalPeek(TK key, params CachePeekMode[] modes) { IgniteArgumentCheck.NotNull(key, "key"); TV res; if (TryLocalPeek(key, out res)) return res; throw GetKeyNotFoundException(); } /** <inheritDoc /> */ public bool TryLocalPeek(TK key, out TV value, params CachePeekMode[] modes) { IgniteArgumentCheck.NotNull(key, "key"); var res = DoOutInOpNullable<TV>((int)CacheOp.Peek, writer => { writer.Write(key); writer.WriteInt(EncodePeekModes(modes)); }); value = res.Success ? res.Value : default(TV); return res.Success; } /** <inheritDoc /> */ public TV this[TK key] { get { if (IsAsync) throw new InvalidOperationException("Indexer can't be used in async mode."); return Get(key); } set { if (IsAsync) throw new InvalidOperationException("Indexer can't be used in async mode."); Put(key, value); } } /** <inheritDoc /> */ public TV Get(TK key) { IgniteArgumentCheck.NotNull(key, "key"); var result = DoOutInOpNullable<TK, TV>((int) CacheOp.Get, key); if (!IsAsync) { if (!result.Success) throw GetKeyNotFoundException(); return result.Value; } Debug.Assert(!result.Success); return default(TV); } /** <inheritDoc /> */ public Task<TV> GetAsync(TK key) { AsyncInstance.Get(key); return AsyncInstance.GetTask(CacheOp.Get, reader => { if (reader != null) return reader.ReadObject<TV>(); throw GetKeyNotFoundException(); }); } /** <inheritDoc /> */ public bool TryGet(TK key, out TV value) { IgniteArgumentCheck.NotNull(key, "key"); if (IsAsync) throw new InvalidOperationException("TryGet can't be used in async mode."); var res = DoOutInOpNullable<TK, TV>((int) CacheOp.Get, key); value = res.Value; return res.Success; } /** <inheritDoc /> */ public Task<CacheResult<TV>> TryGetAsync(TK key) { IgniteArgumentCheck.NotNull(key, "key"); AsyncInstance.Get(key); return AsyncInstance.GetTask(CacheOp.Get, GetCacheResult); } /** <inheritDoc /> */ public IDictionary<TK, TV> GetAll(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); return DoOutInOp((int)CacheOp.GetAll, writer => WriteEnumerable(writer, keys), input => { var reader = Marshaller.StartUnmarshal(input, _flagKeepBinary); return ReadGetAllDictionary(reader); }); } /** <inheritDoc /> */ public Task<IDictionary<TK, TV>> GetAllAsync(IEnumerable<TK> keys) { AsyncInstance.GetAll(keys); return AsyncInstance.GetTask(CacheOp.GetAll, r => r == null ? null : ReadGetAllDictionary(r)); } /** <inheritdoc /> */ public void Put(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); DoOutOp((int)CacheOp.Put, key, val); } /** <inheritDoc /> */ public Task PutAsync(TK key, TV val) { AsyncInstance.Put(key, val); return AsyncInstance.GetTask(CacheOp.Put); } /** <inheritDoc /> */ public CacheResult<TV> GetAndPut(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); return DoOutInOpNullable<TK, TV, TV>((int)CacheOp.GetAndPut, key, val); } /** <inheritDoc /> */ public Task<CacheResult<TV>> GetAndPutAsync(TK key, TV val) { AsyncInstance.GetAndPut(key, val); return AsyncInstance.GetTask(CacheOp.GetAndPut, GetCacheResult); } /** <inheritDoc /> */ public CacheResult<TV> GetAndReplace(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); return DoOutInOpNullable<TK, TV, TV>((int) CacheOp.GetAndReplace, key, val); } /** <inheritDoc /> */ public Task<CacheResult<TV>> GetAndReplaceAsync(TK key, TV val) { AsyncInstance.GetAndReplace(key, val); return AsyncInstance.GetTask(CacheOp.GetAndReplace, GetCacheResult); } /** <inheritDoc /> */ public CacheResult<TV> GetAndRemove(TK key) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutInOpNullable<TK, TV>((int)CacheOp.GetAndRemove, key); } /** <inheritDoc /> */ public Task<CacheResult<TV>> GetAndRemoveAsync(TK key) { AsyncInstance.GetAndRemove(key); return AsyncInstance.GetTask(CacheOp.GetAndRemove, GetCacheResult); } /** <inheritdoc /> */ public bool PutIfAbsent(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); return DoOutOp((int) CacheOp.PutIfAbsent, key, val) == True; } /** <inheritDoc /> */ public Task<bool> PutIfAbsentAsync(TK key, TV val) { AsyncInstance.PutIfAbsent(key, val); return AsyncInstance.GetTask<bool>(CacheOp.PutIfAbsent); } /** <inheritdoc /> */ public CacheResult<TV> GetAndPutIfAbsent(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); return DoOutInOpNullable<TK, TV, TV>((int)CacheOp.GetAndPutIfAbsent, key, val); } /** <inheritDoc /> */ public Task<CacheResult<TV>> GetAndPutIfAbsentAsync(TK key, TV val) { AsyncInstance.GetAndPutIfAbsent(key, val); return AsyncInstance.GetTask(CacheOp.GetAndPutIfAbsent, GetCacheResult); } /** <inheritdoc /> */ public bool Replace(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); return DoOutOp((int) CacheOp.Replace2, key, val) == True; } /** <inheritDoc /> */ public Task<bool> ReplaceAsync(TK key, TV val) { AsyncInstance.Replace(key, val); return AsyncInstance.GetTask<bool>(CacheOp.Replace2); } /** <inheritdoc /> */ public bool Replace(TK key, TV oldVal, TV newVal) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(oldVal, "oldVal"); IgniteArgumentCheck.NotNull(newVal, "newVal"); return DoOutOp((int)CacheOp.Replace3, key, oldVal, newVal) == True; } /** <inheritDoc /> */ public Task<bool> ReplaceAsync(TK key, TV oldVal, TV newVal) { AsyncInstance.Replace(key, oldVal, newVal); return AsyncInstance.GetTask<bool>(CacheOp.Replace3); } /** <inheritdoc /> */ public void PutAll(IDictionary<TK, TV> vals) { IgniteArgumentCheck.NotNull(vals, "vals"); DoOutOp((int) CacheOp.PutAll, writer => WriteDictionary(writer, vals)); } /** <inheritDoc /> */ public Task PutAllAsync(IDictionary<TK, TV> vals) { AsyncInstance.PutAll(vals); return AsyncInstance.GetTask(CacheOp.PutAll); } /** <inheritdoc /> */ public void LocalEvict(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); DoOutOp((int) CacheOp.LocEvict, writer => WriteEnumerable(writer, keys)); } /** <inheritdoc /> */ public void Clear() { UU.CacheClear(Target); } /** <inheritDoc /> */ public Task ClearAsync() { AsyncInstance.Clear(); return AsyncInstance.GetTask(); } /** <inheritdoc /> */ public void Clear(TK key) { IgniteArgumentCheck.NotNull(key, "key"); DoOutOp((int) CacheOp.Clear, key); } /** <inheritDoc /> */ public Task ClearAsync(TK key) { AsyncInstance.Clear(key); return AsyncInstance.GetTask(CacheOp.Clear); } /** <inheritdoc /> */ public void ClearAll(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); DoOutOp((int)CacheOp.ClearAll, writer => WriteEnumerable(writer, keys)); } /** <inheritDoc /> */ public Task ClearAllAsync(IEnumerable<TK> keys) { AsyncInstance.ClearAll(keys); return AsyncInstance.GetTask(CacheOp.ClearAll); } /** <inheritdoc /> */ public void LocalClear(TK key) { IgniteArgumentCheck.NotNull(key, "key"); DoOutOp((int) CacheOp.LocalClear, key); } /** <inheritdoc /> */ public void LocalClearAll(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); DoOutOp((int)CacheOp.LocalClearAll, writer => WriteEnumerable(writer, keys)); } /** <inheritdoc /> */ public bool Remove(TK key) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutOp((int) CacheOp.RemoveObj, key) == True; } /** <inheritDoc /> */ public Task<bool> RemoveAsync(TK key) { AsyncInstance.Remove(key); return AsyncInstance.GetTask<bool>(CacheOp.RemoveObj); } /** <inheritDoc /> */ public bool Remove(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); return DoOutOp((int)CacheOp.RemoveBool, key, val) == True; } /** <inheritDoc /> */ public Task<bool> RemoveAsync(TK key, TV val) { AsyncInstance.Remove(key, val); return AsyncInstance.GetTask<bool>(CacheOp.RemoveBool); } /** <inheritDoc /> */ public void RemoveAll(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); DoOutOp((int)CacheOp.RemoveAll, writer => WriteEnumerable(writer, keys)); } /** <inheritDoc /> */ public Task RemoveAllAsync(IEnumerable<TK> keys) { AsyncInstance.RemoveAll(keys); return AsyncInstance.GetTask(CacheOp.RemoveAll); } /** <inheritDoc /> */ public void RemoveAll() { UU.CacheRemoveAll(Target); } /** <inheritDoc /> */ public Task RemoveAllAsync() { AsyncInstance.RemoveAll(); return AsyncInstance.GetTask(); } /** <inheritDoc /> */ public int GetLocalSize(params CachePeekMode[] modes) { return Size0(true, modes); } /** <inheritDoc /> */ public int GetSize(params CachePeekMode[] modes) { return Size0(false, modes); } /** <inheritDoc /> */ public Task<int> GetSizeAsync(params CachePeekMode[] modes) { AsyncInstance.GetSize(modes); return AsyncInstance.GetTask<int>(); } /// <summary> /// Internal size routine. /// </summary> /// <param name="loc">Local flag.</param> /// <param name="modes">peek modes</param> /// <returns>Size.</returns> private int Size0(bool loc, params CachePeekMode[] modes) { int modes0 = EncodePeekModes(modes); return UU.CacheSize(Target, modes0, loc); } /** <inheritDoc /> */ public void LocalPromote(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); DoOutOp((int)CacheOp.LocPromote, writer => WriteEnumerable(writer, keys)); } /** <inheritdoc /> */ public TRes Invoke<TArg, TRes>(TK key, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(processor, "processor"); var holder = new CacheEntryProcessorHolder(processor, arg, (e, a) => processor.Process((IMutableCacheEntry<TK, TV>)e, (TArg)a), typeof(TK), typeof(TV)); return DoOutInOp((int)CacheOp.Invoke, writer => { writer.Write(key); writer.Write(holder); }, input => GetResultOrThrow<TRes>(Unmarshal<object>(input))); } /** <inheritDoc /> */ public Task<TRes> InvokeAsync<TArg, TRes>(TK key, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg) { AsyncInstance.Invoke(key, processor, arg); return AsyncInstance.GetTask(CacheOp.Invoke, r => { if (r == null) return default(TRes); var hasError = r.ReadBoolean(); if (hasError) throw ReadException(r.Stream); return r.ReadObject<TRes>(); }); } /** <inheritdoc /> */ public IDictionary<TK, ICacheEntryProcessorResult<TRes>> InvokeAll<TArg, TRes>(IEnumerable<TK> keys, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg) { IgniteArgumentCheck.NotNull(keys, "keys"); IgniteArgumentCheck.NotNull(processor, "processor"); var holder = new CacheEntryProcessorHolder(processor, arg, (e, a) => processor.Process((IMutableCacheEntry<TK, TV>)e, (TArg)a), typeof(TK), typeof(TV)); return DoOutInOp((int) CacheOp.InvokeAll, writer => { WriteEnumerable(writer, keys); writer.Write(holder); }, input => ReadInvokeAllResults<TRes>(input)); } /** <inheritDoc /> */ public Task<IDictionary<TK, ICacheEntryProcessorResult<TRes>>> InvokeAllAsync<TArg, TRes>(IEnumerable<TK> keys, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg) { AsyncInstance.InvokeAll(keys, processor, arg); return AsyncInstance.GetTask(CacheOp.InvokeAll, reader => ReadInvokeAllResults<TRes>(reader.Stream)); } /** <inheritdoc /> */ public ICacheLock Lock(TK key) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutInOp((int)CacheOp.Lock, writer => { writer.Write(key); }, input => new CacheLock(input.ReadInt(), Target)); } /** <inheritdoc /> */ public ICacheLock LockAll(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); return DoOutInOp((int)CacheOp.LockAll, writer => { WriteEnumerable(writer, keys); }, input => new CacheLock(input.ReadInt(), Target)); } /** <inheritdoc /> */ public bool IsLocalLocked(TK key, bool byCurrentThread) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutOp((int)CacheOp.IsLocalLocked, writer => { writer.Write(key); writer.WriteBoolean(byCurrentThread); }) == True; } /** <inheritDoc /> */ public ICacheMetrics GetMetrics() { return DoInOp((int)CacheOp.Metrics, stream => { IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false); return new CacheMetricsImpl(reader); }); } /** <inheritDoc /> */ public Task Rebalance() { return GetFuture<object>((futId, futTyp) => UU.CacheRebalance(Target, futId)).Task; } /** <inheritDoc /> */ public ICache<TK, TV> WithNoRetries() { if (_flagNoRetries) return this; return new CacheImpl<TK, TV>(_ignite, UU.CacheWithNoRetries(Target), Marshaller, _flagSkipStore, _flagKeepBinary, _flagAsync, true); } /// <summary> /// Gets the asynchronous instance. /// </summary> private CacheImpl<TK, TV> AsyncInstance { get { return _asyncInstance.Value; } } #region Queries /** <inheritDoc /> */ public IQueryCursor<IList> QueryFields(SqlFieldsQuery qry) { IgniteArgumentCheck.NotNull(qry, "qry"); if (string.IsNullOrEmpty(qry.Sql)) throw new ArgumentException("Sql cannot be null or empty"); IUnmanagedTarget cursor; using (var stream = IgniteManager.Memory.Allocate().GetStream()) { var writer = Marshaller.StartMarshal(stream); writer.WriteBoolean(qry.Local); writer.WriteString(qry.Sql); writer.WriteInt(qry.PageSize); WriteQueryArgs(writer, qry.Arguments); FinishMarshal(writer); cursor = UU.CacheOutOpQueryCursor(Target, (int) CacheOp.QrySqlFields, stream.SynchronizeOutput()); } return new FieldsQueryCursor(cursor, Marshaller, _flagKeepBinary); } /** <inheritDoc /> */ public IQueryCursor<ICacheEntry<TK, TV>> Query(QueryBase qry) { IgniteArgumentCheck.NotNull(qry, "qry"); IUnmanagedTarget cursor; using (var stream = IgniteManager.Memory.Allocate().GetStream()) { var writer = Marshaller.StartMarshal(stream); qry.Write(writer, IsKeepBinary); FinishMarshal(writer); cursor = UU.CacheOutOpQueryCursor(Target, (int)qry.OpId, stream.SynchronizeOutput()); } return new QueryCursor<TK, TV>(cursor, Marshaller, _flagKeepBinary); } /// <summary> /// Write query arguments. /// </summary> /// <param name="writer">Writer.</param> /// <param name="args">Arguments.</param> private static void WriteQueryArgs(BinaryWriter writer, object[] args) { if (args == null) writer.WriteInt(0); else { writer.WriteInt(args.Length); foreach (var arg in args) writer.WriteObject(arg); } } /** <inheritdoc /> */ public IContinuousQueryHandle QueryContinuous(ContinuousQuery<TK, TV> qry) { IgniteArgumentCheck.NotNull(qry, "qry"); return QueryContinuousImpl(qry, null); } /** <inheritdoc /> */ public IContinuousQueryHandle<ICacheEntry<TK, TV>> QueryContinuous(ContinuousQuery<TK, TV> qry, QueryBase initialQry) { IgniteArgumentCheck.NotNull(qry, "qry"); IgniteArgumentCheck.NotNull(initialQry, "initialQry"); return QueryContinuousImpl(qry, initialQry); } /// <summary> /// QueryContinuous implementation. /// </summary> private IContinuousQueryHandle<ICacheEntry<TK, TV>> QueryContinuousImpl(ContinuousQuery<TK, TV> qry, QueryBase initialQry) { qry.Validate(); var hnd = new ContinuousQueryHandleImpl<TK, TV>(qry, Marshaller, _flagKeepBinary); try { using (var stream = IgniteManager.Memory.Allocate().GetStream()) { var writer = Marshaller.StartMarshal(stream); hnd.Start(_ignite, writer, () => { if (initialQry != null) { writer.WriteInt((int) initialQry.OpId); initialQry.Write(writer, IsKeepBinary); } else writer.WriteInt(-1); // no initial query FinishMarshal(writer); // ReSharper disable once AccessToDisposedClosure return UU.CacheOutOpContinuousQuery(Target, (int) CacheOp.QryContinuous, stream.SynchronizeOutput()); }, qry); } return hnd; } catch (Exception) { hnd.Dispose(); throw; } } #endregion #region Enumerable support /** <inheritdoc /> */ public IEnumerable<ICacheEntry<TK, TV>> GetLocalEntries(CachePeekMode[] peekModes) { return new CacheEnumerable<TK, TV>(this, EncodePeekModes(peekModes)); } /** <inheritdoc /> */ public IEnumerator<ICacheEntry<TK, TV>> GetEnumerator() { return new CacheEnumeratorProxy<TK, TV>(this, false, 0); } /** <inheritdoc /> */ IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Create real cache enumerator. /// </summary> /// <param name="loc">Local flag.</param> /// <param name="peekModes">Peek modes for local enumerator.</param> /// <returns>Cache enumerator.</returns> internal CacheEnumerator<TK, TV> CreateEnumerator(bool loc, int peekModes) { if (loc) return new CacheEnumerator<TK, TV>(UU.CacheLocalIterator(Target, peekModes), Marshaller, _flagKeepBinary); return new CacheEnumerator<TK, TV>(UU.CacheIterator(Target), Marshaller, _flagKeepBinary); } #endregion /** <inheritDoc /> */ protected override T Unmarshal<T>(IBinaryStream stream) { return Marshaller.Unmarshal<T>(stream, _flagKeepBinary); } /// <summary> /// Encodes the peek modes into a single int value. /// </summary> private static int EncodePeekModes(CachePeekMode[] modes) { int modesEncoded = 0; if (modes != null) { foreach (var mode in modes) modesEncoded |= (int) mode; } return modesEncoded; } /// <summary> /// Unwraps an exception. /// </summary> /// <typeparam name="T">Result type.</typeparam> /// <param name="obj">Object.</param> /// <returns>Result.</returns> private static T GetResultOrThrow<T>(object obj) { var err = obj as Exception; if (err != null) throw err as CacheEntryProcessorException ?? new CacheEntryProcessorException(err); return obj == null ? default(T) : (T) obj; } /// <summary> /// Reads results of InvokeAll operation. /// </summary> /// <typeparam name="T">The type of the result.</typeparam> /// <param name="inStream">Stream.</param> /// <returns>Results of InvokeAll operation.</returns> private IDictionary<TK, ICacheEntryProcessorResult<T>> ReadInvokeAllResults<T>(IBinaryStream inStream) { var count = inStream.ReadInt(); if (count == -1) return null; var results = new Dictionary<TK, ICacheEntryProcessorResult<T>>(count); for (var i = 0; i < count; i++) { var key = Unmarshal<TK>(inStream); var hasError = inStream.ReadBool(); results[key] = hasError ? new CacheEntryProcessorResult<T>(ReadException(inStream)) : new CacheEntryProcessorResult<T>(Unmarshal<T>(inStream)); } return results; } /// <summary> /// Reads the exception, either in binary wrapper form, or as a pair of strings. /// </summary> /// <param name="inStream">The stream.</param> /// <returns>Exception.</returns> private CacheEntryProcessorException ReadException(IBinaryStream inStream) { var item = Unmarshal<object>(inStream); var clsName = item as string; if (clsName == null) return new CacheEntryProcessorException((Exception) item); var msg = Unmarshal<string>(inStream); return new CacheEntryProcessorException(ExceptionUtils.GetException(_ignite, clsName, msg)); } /// <summary> /// Read dictionary returned by GET_ALL operation. /// </summary> /// <param name="reader">Reader.</param> /// <returns>Dictionary.</returns> private static IDictionary<TK, TV> ReadGetAllDictionary(BinaryReader reader) { IBinaryStream stream = reader.Stream; if (stream.ReadBool()) { int size = stream.ReadInt(); IDictionary<TK, TV> res = new Dictionary<TK, TV>(size); for (int i = 0; i < size; i++) { TK key = reader.ReadObject<TK>(); TV val = reader.ReadObject<TV>(); res[key] = val; } return res; } return null; } /// <summary> /// Gets the cache result. /// </summary> private static CacheResult<TV> GetCacheResult(BinaryReader reader) { var res = reader == null ? new CacheResult<TV>() : new CacheResult<TV>(reader.ReadObject<TV>()); return res; } /// <summary> /// Throws the key not found exception. /// </summary> private static KeyNotFoundException GetKeyNotFoundException() { return new KeyNotFoundException("The given key was not present in the cache."); } /// <summary> /// Perform simple out-in operation accepting single argument. /// </summary> /// <param name="type">Operation type.</param> /// <param name="val">Value.</param> /// <returns>Result.</returns> private CacheResult<TR> DoOutInOpNullable<T1, TR>(int type, T1 val) { var res = DoOutInOp<T1, object>(type, val); return res == null ? new CacheResult<TR>() : new CacheResult<TR>((TR)res); } /// <summary> /// Perform out-in operation. /// </summary> /// <param name="type">Operation type.</param> /// <param name="outAction">Out action.</param> /// <returns>Result.</returns> private CacheResult<TR> DoOutInOpNullable<TR>(int type, Action<BinaryWriter> outAction) { var res = DoOutInOp<object>(type, outAction); return res == null ? new CacheResult<TR>() : new CacheResult<TR>((TR)res); } /// <summary> /// Perform simple out-in operation accepting single argument. /// </summary> /// <param name="type">Operation type.</param> /// <param name="val1">Value.</param> /// <param name="val2">Value.</param> /// <returns>Result.</returns> private CacheResult<TR> DoOutInOpNullable<T1, T2, TR>(int type, T1 val1, T2 val2) { var res = DoOutInOp<T1, T2, object>(type, val1, val2); return res == null ? new CacheResult<TR>() : new CacheResult<TR>((TR)res); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Microsoft.Xunit.Performance; using Xunit; namespace System.Collections.Tests { public class Perf_Dictionary { /// <summary> /// Creates a Dictionary of int-int with the specified number of pairs /// </summary> public static Dictionary<int, int> CreateDictionary(int size) { Random rand = new Random(837322); Dictionary<int, int> dict = new Dictionary<int, int>(); while (dict.Count < size) { int key = rand.Next(500000, int.MaxValue); dict.TryAdd(key, 0); } return dict; } [Benchmark] [InlineData(1000)] [InlineData(10000)] [InlineData(100000)] public void Add(int size) { Dictionary<int, int> dict = CreateDictionary(size); foreach (var iteration in Benchmark.Iterations) { Dictionary<int, int> copyDict = new Dictionary<int, int>(dict); using (iteration.StartMeasurement()) for (int i = 0; i <= 20000; i++) { copyDict.Add(i * 10 + 1, 0); copyDict.Add(i * 10 + 2, 0); copyDict.Add(i * 10 + 3, 0); copyDict.Add(i * 10 + 4, 0); copyDict.Add(i * 10 + 5, 0); copyDict.Add(i * 10 + 6, 0); copyDict.Add(i * 10 + 7, 0); copyDict.Add(i * 10 + 8, 0); copyDict.Add(i * 10 + 9, 0); } } } [Benchmark] public void ctor() { foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int i = 0; i <= 20000; i++) { new Dictionary<int, string>(); new Dictionary<int, string>(); new Dictionary<int, string>(); new Dictionary<int, string>(); new Dictionary<int, string>(); new Dictionary<int, string>(); new Dictionary<int, string>(); new Dictionary<int, string>(); new Dictionary<int, string>(); } } [Benchmark] [InlineData(0)] [InlineData(1024)] [InlineData(4096)] [InlineData(16384)] public void ctor_int(int size) { foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int i = 0; i <= 500; i++) { new Dictionary<int, string>(size); new Dictionary<int, string>(size); new Dictionary<int, string>(size); new Dictionary<int, string>(size); new Dictionary<int, string>(size); new Dictionary<int, string>(size); new Dictionary<int, string>(size); new Dictionary<int, string>(size); new Dictionary<int, string>(size); } } [Benchmark] [InlineData(1000)] [InlineData(10000)] [InlineData(100000)] public void GetItem(int size) { Dictionary<int, int> dict = CreateDictionary(size); // Setup int retrieved; for (int i = 1; i <= 9; i++) dict.Add(i, 0); // Actual perf testing foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) for (int i = 0; i <= 10000; i++) { retrieved = dict[1]; retrieved = dict[2]; retrieved = dict[3]; retrieved = dict[4]; retrieved = dict[5]; retrieved = dict[6]; retrieved = dict[7]; retrieved = dict[8]; retrieved = dict[9]; } } } [Benchmark] [InlineData(1000)] [InlineData(10000)] [InlineData(100000)] public void SetItem(int size) { Dictionary<int, int> dict = CreateDictionary(size); // Setup for (int i = 1; i <= 9; i++) dict.Add(i, 0); // Actual perf testing foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) for (int i = 0; i <= 10000; i++) { dict[1] = 0; dict[2] = 0; dict[3] = 0; dict[4] = 0; dict[5] = 0; dict[6] = 0; dict[7] = 0; dict[8] = 0; dict[9] = 0; } } } [Benchmark] [InlineData(1000)] [InlineData(10000)] [InlineData(100000)] public void GetKeys(int size) { Dictionary<int, int> dict = CreateDictionary(size); IEnumerable<int> result; foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int i = 0; i <= 20000; i++) { result = dict.Keys; result = dict.Keys; result = dict.Keys; result = dict.Keys; result = dict.Keys; result = dict.Keys; result = dict.Keys; result = dict.Keys; result = dict.Keys; } } [Benchmark] [InlineData(1000)] [InlineData(10000)] [InlineData(100000)] public void TryGetValue(int size) { Dictionary<int, int> dict = CreateDictionary(size); // Setup - utils needs a specific seed to prevent key collision with TestData int retrieved; Random rand = new Random(837322); int key = rand.Next(0, 400000); dict.Add(key, 12); // Actual perf testing foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int i = 0; i <= 1000; i++) { dict.TryGetValue(key, out retrieved); dict.TryGetValue(key, out retrieved); dict.TryGetValue(key, out retrieved); dict.TryGetValue(key, out retrieved); dict.TryGetValue(key, out retrieved); dict.TryGetValue(key, out retrieved); dict.TryGetValue(key, out retrieved); dict.TryGetValue(key, out retrieved); } } [Benchmark] [InlineData(1)] [InlineData(10)] [InlineData(1000)] public static void Remove_ValueType(long size) { Dictionary<long?, long?> collection = new Dictionary<long?, long?>(); long?[] items; items = new long?[size * 10]; for (long i = 0; i < size * 10; ++i) { items[i] = i; collection.Add(items[i], items[i]); } foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (long i = 1; i < size; ++i) collection.Remove(items[i]); } [Benchmark] public static void Indexer_get_ValueType() { int size = 1024; int? item; Dictionary<int?, int?> collection = new Dictionary<int?, int?>(); for (int i = 0; i < size; ++i) { collection.Add(i, i); } foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int j = 0; j < size; ++j) { item = (int)collection[j]; item = (int)collection[j]; item = (int)collection[j]; item = (int)collection[j]; item = (int)collection[j]; item = (int)collection[j]; item = (int)collection[j]; item = (int)collection[j]; item = (int)collection[j]; item = (int)collection[j]; } } } } [Benchmark] public static void Enumeration_ValueType() { int size = 1024; int? key; int? value; Dictionary<int?, int?> collection = new Dictionary<int?, int?>(); for (int i = 0; i < size; ++i) { collection.Add(i, i); } foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { foreach (KeyValuePair<int?, int?> tempItem in collection) { key = tempItem.Key; value = tempItem.Value; } } } } [Benchmark] [InlineData(1000)] [InlineData(10000)] [InlineData(100000)] public static void Dictionary_ContainsValue_Int_True(int sampleLength) { Dictionary<int, int> dictionary = new Dictionary<int, int>(); for (int i = 0; i < sampleLength; i++) { dictionary.Add(i, i); } bool result = false; foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int j = 0; j < sampleLength; j++) result = dictionary.ContainsValue(j); //Every value searched for is present in the dictionary. } [Benchmark] [InlineData(1000)] [InlineData(10000)] [InlineData(100000)] public static void Dictionary_ContainsValue_Int_False(int sampleLength) { Dictionary<int, int> dictionary = new Dictionary<int, int>(); for (int i = 0; i < sampleLength; i++) { dictionary.Add(i, i); } bool result = false; int missingValue = sampleLength; //The value sampleLength is not present in the dictionary. foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int j = 0; j < sampleLength; j++) result = dictionary.ContainsValue(missingValue); } [Benchmark] [InlineData(1000)] [InlineData(10000)] [InlineData(100000)] public static void Dictionary_ContainsValue_String_True(int sampleLength) { string[] sampleValues = new string[sampleLength]; Dictionary<string, string> dictionary = new Dictionary<string, string>(); for (int i = 0; i < sampleLength; i++) { sampleValues[i] = i.ToString(); dictionary.Add(sampleValues[i], sampleValues[i]); } bool result = false; foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int j = 0; j < sampleLength; j++) result = dictionary.ContainsValue(sampleValues[j]); //Every value searched for is present in the dictionary. } [Benchmark] [InlineData(1000)] [InlineData(10000)] [InlineData(100000)] public static void Dictionary_ContainsValue_String_False(int sampleLength) { string sampleValue; Dictionary<string, string> dictionary = new Dictionary<string, string>(); for (int i = 0; i < sampleLength; i++) { sampleValue = i.ToString(); dictionary.Add(sampleValue, sampleValue); } bool result = false; string missingValue = sampleLength.ToString(); //The string representation of sampleLength is not present in the dictionary. foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int j = 0; j < sampleLength; j++) result = dictionary.ContainsValue(missingValue); } [Benchmark] [InlineData(1000)] [InlineData(10000)] [InlineData(100000)] public static void Dictionary_ContainsKey_Int_True(int sampleLength) { Dictionary<int, int> dictionary = new Dictionary<int, int>(); for (int i = 0; i < sampleLength; i++) { dictionary.Add(i, i); } bool result = false; foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int j = 0; j < sampleLength; j++) result = dictionary.ContainsKey(j); } [Benchmark] [InlineData(1000)] [InlineData(10000)] [InlineData(100000)] public static void Dictionary_ContainsKey_Int_False(int sampleLength) { Dictionary<int, int> dictionary = new Dictionary<int, int>(); for (int i = 0; i < sampleLength; i++) { dictionary.Add(i, i); } bool result = false; int missingKey = sampleLength; //The key sampleLength is not present in the dictionary. foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int j = 0; j < sampleLength; j++) result = dictionary.ContainsKey(missingKey); } [Benchmark] [InlineData(1000)] [InlineData(10000)] [InlineData(100000)] public static void Dictionary_ContainsKey_String_True(int sampleLength) { string[] sampleKeys = new string[sampleLength]; Dictionary<string, string> dictionary = new Dictionary<string, string>(); for (int i = 0; i < sampleLength; i++) { sampleKeys[i] = i.ToString(); dictionary.Add(sampleKeys[i], sampleKeys[i]); } bool result = false; foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int j = 0; j < sampleLength; j++) result = dictionary.ContainsKey(sampleKeys[j]); //Every key searched for is present in the dictionary. } [Benchmark] [InlineData(1000)] [InlineData(10000)] [InlineData(100000)] public static void Dictionary_ContainsKey_String_False(int sampleLength) { string sampleKey; Dictionary<string, string> dictionary = new Dictionary<string, string>(); for (int i = 0; i < sampleLength; i++) { sampleKey = i.ToString(); dictionary.Add(sampleKey, sampleKey); } bool result = false; string missingKey = sampleLength.ToString(); //The string representation of sampleLength is not present in the dictionary. foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int j = 0; j < sampleLength; j++) result = dictionary.ContainsKey(missingKey); } [Benchmark] [InlineData(1000)] [InlineData(10000)] [InlineData(100000)] public static void Dictionary_ContainsKey_String_False_IgnoreCase(int sampleLength) { string sampleKey; Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); for (int i = 0; i < sampleLength; i++) { sampleKey = i.ToString(); dictionary.Add(sampleKey, sampleKey); } bool result = false; string missingKey = sampleLength.ToString(); //The string representation of sampleLength is not present in the dictionary. foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) for (int j = 0; j < sampleLength; j++) result = dictionary.ContainsKey(missingKey); } } }
// 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.Diagnostics; using System.Collections.Generic; using ReflectionEventSource = System.Reflection.Runtime.Tracing.ReflectionEventSource; namespace Internal.Reflection.Tracing { // // The individual event methods. These are in a separate file to allow them to be tool-generated. // public static partial class ReflectionTrace { public static void Type_MakeGenericType(Type type, Type[] typeArguments) { String typeName = type.NameString(); if (typeName == null) return; String typeArgumentStrings = typeArguments.GenericTypeArgumentStrings(); if (typeArgumentStrings == null) return; ReflectionEventSource.Log.TypeInfo_MakeGenericType(typeName, typeArgumentStrings); } public static void Type_MakeArrayType(Type type) { String typeName = type.NameString(); if (typeName == null) return; ReflectionEventSource.Log.TypeInfo_MakeArrayType(typeName); } public static void Type_FullName(Type type) { String typeName = type.NameString(); if (typeName == null) return; ReflectionEventSource.Log.TypeInfo_FullName(typeName); } public static void Type_Namespace(Type type) { String typeName = type.NameString(); if (typeName == null) return; ReflectionEventSource.Log.TypeInfo_Namespace(typeName); } public static void Type_AssemblyQualifiedName(Type type) { String typeName = type.NameString(); if (typeName == null) return; ReflectionEventSource.Log.TypeInfo_AssemblyQualifiedName(typeName); } public static void Type_Name(Type type) { String typeName = type.NameString(); if (typeName == null) return; ReflectionEventSource.Log.TypeInfo_Name(typeName); } public static void TypeInfo_CustomAttributes(TypeInfo typeInfo) { String typeName = typeInfo.NameString(); if (typeName == null) return; ReflectionEventSource.Log.TypeInfo_CustomAttributes(typeName); } public static void TypeInfo_Name(TypeInfo typeInfo) { String typeName = typeInfo.NameString(); if (typeName == null) return; ReflectionEventSource.Log.TypeInfo_Name(typeName); } public static void TypeInfo_BaseType(TypeInfo typeInfo) { String typeName = typeInfo.NameString(); if (typeName == null) return; ReflectionEventSource.Log.TypeInfo_BaseType(typeName); } public static void TypeInfo_DeclaredConstructors(TypeInfo typeInfo) { String typeName = typeInfo.NameString(); if (typeName == null) return; ReflectionEventSource.Log.TypeInfo_DeclaredConstructors(typeName); } public static void TypeInfo_DeclaredEvents(TypeInfo typeInfo) { String typeName = typeInfo.NameString(); if (typeName == null) return; ReflectionEventSource.Log.TypeInfo_DeclaredEvents(typeName); } public static void TypeInfo_DeclaredFields(TypeInfo typeInfo) { String typeName = typeInfo.NameString(); if (typeName == null) return; ReflectionEventSource.Log.TypeInfo_DeclaredFields(typeName); } public static void TypeInfo_DeclaredMembers(TypeInfo typeInfo) { String typeName = typeInfo.NameString(); if (typeName == null) return; ReflectionEventSource.Log.TypeInfo_DeclaredMembers(typeName); } public static void TypeInfo_DeclaredMethods(TypeInfo typeInfo) { String typeName = typeInfo.NameString(); if (typeName == null) return; ReflectionEventSource.Log.TypeInfo_DeclaredMethods(typeName); } public static void TypeInfo_DeclaredNestedTypes(TypeInfo typeInfo) { String typeName = typeInfo.NameString(); if (typeName == null) return; ReflectionEventSource.Log.TypeInfo_DeclaredNestedTypes(typeName); } public static void TypeInfo_DeclaredProperties(TypeInfo typeInfo) { String typeName = typeInfo.NameString(); if (typeName == null) return; ReflectionEventSource.Log.TypeInfo_DeclaredProperties(typeName); } public static void TypeInfo_DeclaringMethod(TypeInfo typeInfo) { String typeName = typeInfo.NameString(); if (typeName == null) return; ReflectionEventSource.Log.TypeInfo_DeclaringMethod(typeName); } public static void TypeInfo_FullName(TypeInfo typeInfo) { String typeName = typeInfo.NameString(); if (typeName == null) return; ReflectionEventSource.Log.TypeInfo_FullName(typeName); } public static void TypeInfo_AssemblyQualifiedName(TypeInfo typeInfo) { String typeName = typeInfo.NameString(); if (typeName == null) return; ReflectionEventSource.Log.TypeInfo_AssemblyQualifiedName(typeName); } public static void TypeInfo_Namespace(TypeInfo typeInfo) { String typeName = typeInfo.NameString(); if (typeName == null) return; ReflectionEventSource.Log.TypeInfo_Namespace(typeName); } public static void TypeInfo_GetDeclaredEvent(TypeInfo typeInfo, String eventName) { String typeName = typeInfo.NameString(); if (typeName == null) return; if (eventName == null) return; ReflectionEventSource.Log.TypeInfo_GetDeclaredEvent(typeName, eventName); } public static void TypeInfo_GetDeclaredField(TypeInfo typeInfo, String fieldName) { String typeName = typeInfo.NameString(); if (typeName == null) return; if (fieldName == null) return; ReflectionEventSource.Log.TypeInfo_GetDeclaredField(typeName, fieldName); } public static void TypeInfo_GetDeclaredMethod(TypeInfo typeInfo, String methodName) { String typeName = typeInfo.NameString(); if (typeName == null) return; if (methodName == null) return; ReflectionEventSource.Log.TypeInfo_GetDeclaredMethod(typeName, methodName); } public static void TypeInfo_GetDeclaredProperty(TypeInfo typeInfo, String propertyName) { String typeName = typeInfo.NameString(); if (typeName == null) return; if (propertyName == null) return; ReflectionEventSource.Log.TypeInfo_GetDeclaredProperty(typeName, propertyName); } public static void TypeInfo_MakeArrayType(TypeInfo typeInfo) { String typeName = typeInfo.NameString(); if (typeName == null) return; ReflectionEventSource.Log.TypeInfo_MakeArrayType(typeName); } public static void TypeInfo_MakeArrayType(TypeInfo typeInfo, int rank) { String typeName = typeInfo.NameString(); if (typeName == null) return; ReflectionEventSource.Log.TypeInfo_MakeArrayType(typeName); } public static void TypeInfo_MakeByRefType(TypeInfo typeInfo) { String typeName = typeInfo.NameString(); if (typeName == null) return; ReflectionEventSource.Log.TypeInfo_MakeByRefType(typeName); } public static void TypeInfo_MakeGenericType(TypeInfo typeInfo, Type[] typeArguments) { String typeName = typeInfo.NameString(); if (typeName == null) return; String typeArgumentStrings = typeArguments.GenericTypeArgumentStrings(); if (typeArgumentStrings == null) return; ReflectionEventSource.Log.TypeInfo_MakeGenericType(typeName, typeArgumentStrings); } public static void TypeInfo_MakePointerType(TypeInfo typeInfo) { String typeName = typeInfo.NameString(); if (typeName == null) return; ReflectionEventSource.Log.TypeInfo_MakePointerType(typeName); } public static void Assembly_DefinedTypes(Assembly assembly) { String assemblyName = assembly.NameString(); if (assemblyName == null) return; ReflectionEventSource.Log.Assembly_DefinedTypes(assemblyName); } public static void Assembly_GetType(Assembly assembly, String typeName) { String assemblyName = assembly.NameString(); if (assemblyName == null) return; if (typeName == null) return; ReflectionEventSource.Log.Assembly_GetType(assemblyName, typeName); } public static void Assembly_CustomAttributes(Assembly assembly) { String assemblyName = assembly.NameString(); if (assemblyName == null) return; ReflectionEventSource.Log.Assembly_CustomAttributes(assemblyName); } public static void Assembly_FullName(Assembly assembly) { String assemblyName = assembly.NameString(); if (assemblyName == null) return; ReflectionEventSource.Log.Assembly_FullName(assemblyName); } public static void Assembly_GetName(Assembly assembly) { String assemblyName = assembly.NameString(); if (assemblyName == null) return; ReflectionEventSource.Log.Assembly_GetName(assemblyName); } public static void CustomAttributeData_ConstructorArguments(CustomAttributeData customAttributeData) { String attributeTypeName = customAttributeData.AttributeTypeNameString(); if (attributeTypeName == null) return; ReflectionEventSource.Log.CustomAttributeData_ConstructorArguments(attributeTypeName); } public static void CustomAttributeData_NamedArguments(CustomAttributeData customAttributeData) { String attributeTypeName = customAttributeData.AttributeTypeNameString(); if (attributeTypeName == null) return; ReflectionEventSource.Log.CustomAttributeData_NamedArguments(attributeTypeName); } public static void EventInfo_AddMethod(EventInfo eventInfo) { String declaringTypeName = eventInfo.DeclaringTypeNameString(); if (declaringTypeName == null) return; String eventName = eventInfo.NameString(); if (eventName == null) return; ReflectionEventSource.Log.EventInfo_AddMethod(declaringTypeName, eventName); } public static void EventInfo_RaiseMethod(EventInfo eventInfo) { String declaringTypeName = eventInfo.DeclaringTypeNameString(); if (declaringTypeName == null) return; String eventName = eventInfo.NameString(); if (eventName == null) return; ReflectionEventSource.Log.EventInfo_RaiseMethod(declaringTypeName, eventName); } public static void EventInfo_RemoveMethod(EventInfo eventInfo) { String declaringTypeName = eventInfo.DeclaringTypeNameString(); if (declaringTypeName == null) return; String eventName = eventInfo.NameString(); if (eventName == null) return; ReflectionEventSource.Log.EventInfo_RemoveMethod(declaringTypeName, eventName); } public static void EventInfo_CustomAttributes(EventInfo eventInfo) { String declaringTypeName = eventInfo.DeclaringTypeNameString(); if (declaringTypeName == null) return; String eventName = eventInfo.NameString(); if (eventName == null) return; ReflectionEventSource.Log.EventInfo_CustomAttributes(declaringTypeName, eventName); } public static void EventInfo_Name(EventInfo eventInfo) { String declaringTypeName = eventInfo.DeclaringTypeNameString(); if (declaringTypeName == null) return; String eventName = eventInfo.NameString(); if (eventName == null) return; ReflectionEventSource.Log.EventInfo_Name(declaringTypeName, eventName); } public static void EventInfo_DeclaringType(EventInfo eventInfo) { String declaringTypeName = eventInfo.DeclaringTypeNameString(); if (declaringTypeName == null) return; String eventName = eventInfo.NameString(); if (eventName == null) return; ReflectionEventSource.Log.EventInfo_DeclaringType(declaringTypeName, eventName); } public static void FieldInfo_SetValue(FieldInfo fieldInfo, Object obj, Object value) { String declaringTypeName = fieldInfo.DeclaringTypeNameString(); if (declaringTypeName == null) return; String fieldName = fieldInfo.NameString(); if (fieldName == null) return; ReflectionEventSource.Log.FieldInfo_SetValue(declaringTypeName, fieldName); } public static void FieldInfo_GetValue(FieldInfo fieldInfo, Object obj) { String declaringTypeName = fieldInfo.DeclaringTypeNameString(); if (declaringTypeName == null) return; String fieldName = fieldInfo.NameString(); if (fieldName == null) return; ReflectionEventSource.Log.FieldInfo_GetValue(declaringTypeName, fieldName); } public static void FieldInfo_CustomAttributes(FieldInfo fieldInfo) { String declaringTypeName = fieldInfo.DeclaringTypeNameString(); if (declaringTypeName == null) return; String fieldName = fieldInfo.NameString(); if (fieldName == null) return; ReflectionEventSource.Log.FieldInfo_CustomAttributes(declaringTypeName, fieldName); } public static void FieldInfo_Name(FieldInfo fieldInfo) { String declaringTypeName = fieldInfo.DeclaringTypeNameString(); if (declaringTypeName == null) return; String fieldName = fieldInfo.NameString(); if (fieldName == null) return; ReflectionEventSource.Log.FieldInfo_Name(declaringTypeName, fieldName); } public static void FieldInfo_DeclaringType(FieldInfo fieldInfo) { String declaringTypeName = fieldInfo.DeclaringTypeNameString(); if (declaringTypeName == null) return; String fieldName = fieldInfo.NameString(); if (fieldName == null) return; ReflectionEventSource.Log.FieldInfo_DeclaringType(declaringTypeName, fieldName); } public static void MethodBase_CustomAttributes(MethodBase methodBase) { String declaringTypeName = methodBase.DeclaringTypeNameString(); if (declaringTypeName == null) return; String methodName = methodBase.NameString(); if (methodName == null) return; ReflectionEventSource.Log.MethodBase_CustomAttributes(declaringTypeName, methodName); } public static void MethodBase_Name(MethodBase methodBase) { String declaringTypeName = methodBase.DeclaringTypeNameString(); if (declaringTypeName == null) return; String methodName = methodBase.NameString(); if (methodName == null) return; ReflectionEventSource.Log.MethodBase_Name(declaringTypeName, methodName); } public static void MethodBase_DeclaringType(MethodBase methodBase) { String declaringTypeName = methodBase.DeclaringTypeNameString(); if (declaringTypeName == null) return; String methodName = methodBase.NameString(); if (methodName == null) return; ReflectionEventSource.Log.MethodBase_DeclaringType(declaringTypeName, methodName); } public static void MethodBase_GetParameters(MethodBase methodBase) { String declaringTypeName = methodBase.DeclaringTypeNameString(); if (declaringTypeName == null) return; String methodName = methodBase.NameString(); if (methodName == null) return; ReflectionEventSource.Log.MethodBase_GetParameters(declaringTypeName, methodName); } public static void ConstructorInfo_Invoke(ConstructorInfo constructor, Object[] parameters) { String declaringTypeName = constructor.DeclaringTypeNameString(); if (declaringTypeName == null) return; String methodName = constructor.NameString(); if (methodName == null) return; ReflectionEventSource.Log.MethodBase_Invoke(declaringTypeName, methodName); } public static void MethodBase_Invoke(MethodBase methodBase, Object obj, Object[] parameters) { String declaringTypeName = methodBase.DeclaringTypeNameString(); if (declaringTypeName == null) return; String methodName = methodBase.NameString(); if (methodName == null) return; ReflectionEventSource.Log.MethodBase_Invoke(declaringTypeName, methodName); } public static void MethodInfo_ReturnParameter(MethodInfo methodInfo) { String declaringTypeName = methodInfo.DeclaringTypeNameString(); if (declaringTypeName == null) return; String methodName = methodInfo.NameString(); if (methodName == null) return; ReflectionEventSource.Log.MethodInfo_ReturnParameter(declaringTypeName, methodName); } public static void MethodInfo_ReturnType(MethodInfo methodInfo) { String declaringTypeName = methodInfo.DeclaringTypeNameString(); if (declaringTypeName == null) return; String methodName = methodInfo.NameString(); if (methodName == null) return; ReflectionEventSource.Log.MethodInfo_ReturnType(declaringTypeName, methodName); } public static void MethodInfo_MakeGenericMethod(MethodInfo methodInfo, Type[] typeArguments) { String declaringTypeName = methodInfo.DeclaringTypeNameString(); if (declaringTypeName == null) return; String methodName = methodInfo.NameString(); if (methodName == null) return; String typeArgumentStrings = typeArguments.GenericTypeArgumentStrings(); if (typeArgumentStrings == null) return; ReflectionEventSource.Log.MethodInfo_MakeGenericMethod(declaringTypeName, methodName, typeArgumentStrings); } public static void MethodInfo_CreateDelegate(MethodInfo methodInfo, Type delegateType) { String declaringTypeName = methodInfo.DeclaringTypeNameString(); if (declaringTypeName == null) return; String methodName = methodInfo.NameString(); if (methodName == null) return; String delegateTypeName = delegateType.NameString(); if (delegateType == null) return; ReflectionEventSource.Log.MethodInfo_CreateDelegate(declaringTypeName, methodName, delegateTypeName); } public static void MethodInfo_CreateDelegate(MethodInfo methodInfo, Type delegateType, Object target) { String declaringTypeName = methodInfo.DeclaringTypeNameString(); if (declaringTypeName == null) return; String methodName = methodInfo.NameString(); if (methodName == null) return; String delegateTypeName = delegateType.NameString(); if (delegateType == null) return; ReflectionEventSource.Log.MethodInfo_CreateDelegate(declaringTypeName, methodName, delegateTypeName); } public static void PropertyInfo_GetValue(PropertyInfo propertyInfo, Object obj, Object[] index) { String declaringTypeName = propertyInfo.DeclaringTypeNameString(); if (declaringTypeName == null) return; String propertyName = propertyInfo.NameString(); if (propertyName == null) return; ReflectionEventSource.Log.PropertyInfo_GetValue(declaringTypeName, propertyName); } public static void PropertyInfo_SetValue(PropertyInfo propertyInfo, Object obj, Object value, Object[] index) { String declaringTypeName = propertyInfo.DeclaringTypeNameString(); if (declaringTypeName == null) return; String propertyName = propertyInfo.NameString(); if (propertyName == null) return; ReflectionEventSource.Log.PropertyInfo_SetValue(declaringTypeName, propertyName); } public static void PropertyInfo_GetMethod(PropertyInfo propertyInfo) { String declaringTypeName = propertyInfo.DeclaringTypeNameString(); if (declaringTypeName == null) return; String propertyName = propertyInfo.NameString(); if (propertyName == null) return; ReflectionEventSource.Log.PropertyInfo_GetMethod(declaringTypeName, propertyName); } public static void PropertyInfo_SetMethod(PropertyInfo propertyInfo) { String declaringTypeName = propertyInfo.DeclaringTypeNameString(); if (declaringTypeName == null) return; String propertyName = propertyInfo.NameString(); if (propertyName == null) return; ReflectionEventSource.Log.PropertyInfo_SetMethod(declaringTypeName, propertyName); } public static void PropertyInfo_GetConstantValue(PropertyInfo propertyInfo) { String declaringTypeName = propertyInfo.DeclaringTypeNameString(); if (declaringTypeName == null) return; String propertyName = propertyInfo.NameString(); if (propertyName == null) return; ReflectionEventSource.Log.PropertyInfo_GetConstantValue(declaringTypeName, propertyName); } public static void PropertyInfo_PropertyType(PropertyInfo propertyInfo) { String declaringTypeName = propertyInfo.DeclaringTypeNameString(); if (declaringTypeName == null) return; String propertyName = propertyInfo.NameString(); if (propertyName == null) return; ReflectionEventSource.Log.PropertyInfo_PropertyType(declaringTypeName, propertyName); } public static void PropertyInfo_CustomAttributes(PropertyInfo propertyInfo) { String declaringTypeName = propertyInfo.DeclaringTypeNameString(); if (declaringTypeName == null) return; String propertyName = propertyInfo.NameString(); if (propertyName == null) return; ReflectionEventSource.Log.PropertyInfo_CustomAttributes(declaringTypeName, propertyName); } public static void PropertyInfo_Name(PropertyInfo propertyInfo) { String declaringTypeName = propertyInfo.DeclaringTypeNameString(); if (declaringTypeName == null) return; String propertyName = propertyInfo.NameString(); if (propertyName == null) return; ReflectionEventSource.Log.PropertyInfo_Name(declaringTypeName, propertyName); } public static void PropertyInfo_DeclaringType(PropertyInfo propertyInfo) { String declaringTypeName = propertyInfo.DeclaringTypeNameString(); if (declaringTypeName == null) return; String propertyName = propertyInfo.NameString(); if (propertyName == null) return; ReflectionEventSource.Log.PropertyInfo_DeclaringType(declaringTypeName, propertyName); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq.Expressions; using FluentNHibernate.Mapping.Providers; using FluentNHibernate.MappingModel; using FluentNHibernate.MappingModel.Collections; using FluentNHibernate.Utils; namespace FluentNHibernate.Mapping { public class ManyToManyPart<TChild> : ToManyBase<ManyToManyPart<TChild>, TChild> { private readonly IList<IFilterMappingProvider> childFilters = new List<IFilterMappingProvider>(); private readonly FetchTypeExpression<ManyToManyPart<TChild>> fetch; private readonly NotFoundExpression<ManyToManyPart<TChild>> notFound; private IndexManyToManyPart manyToManyIndex; private IndexPart index; private readonly ColumnMappingCollection<ManyToManyPart<TChild>> childKeyColumns; private readonly ColumnMappingCollection<ManyToManyPart<TChild>> parentKeyColumns; private readonly Type childType; private Type valueType; private bool isTernary; public ManyToManyPart(Type entity, Member property) : this(entity, property, property.PropertyType) { } protected ManyToManyPart(Type entity, Member member, Type collectionType) : base(entity, member, collectionType) { childType = collectionType; fetch = new FetchTypeExpression<ManyToManyPart<TChild>>(this, value => collectionAttributes.Set("Fetch", Layer.UserSupplied, value)); notFound = new NotFoundExpression<ManyToManyPart<TChild>>(this, value => relationshipAttributes.Set("NotFound", Layer.UserSupplied, value)); childKeyColumns = new ColumnMappingCollection<ManyToManyPart<TChild>>(this); parentKeyColumns = new ColumnMappingCollection<ManyToManyPart<TChild>>(this); } /// <summary> /// Sets a single child key column. If there are multiple columns, use ChildKeyColumns.Add /// </summary> public ManyToManyPart<TChild> ChildKeyColumn(string childKeyColumn) { childKeyColumns.Clear(); childKeyColumns.Add(childKeyColumn); return this; } /// <summary> /// Sets a single parent key column. If there are multiple columns, use ParentKeyColumns.Add /// </summary> public ManyToManyPart<TChild> ParentKeyColumn(string parentKeyColumn) { parentKeyColumns.Clear(); parentKeyColumns.Add(parentKeyColumn); return this; } public ColumnMappingCollection<ManyToManyPart<TChild>> ChildKeyColumns { get { return childKeyColumns; } } public ColumnMappingCollection<ManyToManyPart<TChild>> ParentKeyColumns { get { return parentKeyColumns; } } public ManyToManyPart<TChild> ForeignKeyConstraintNames(string parentForeignKeyName, string childForeignKeyName) { keyMapping.Set(x => x.ForeignKey, Layer.UserSupplied, parentForeignKeyName); relationshipAttributes.Set("ForeignKey", Layer.UserSupplied, childForeignKeyName); return this; } public ManyToManyPart<TChild> ChildPropertyRef(string childPropertyRef) { relationshipAttributes.Set("ChildPropertyRef", Layer.UserSupplied, childPropertyRef); return this; } public FetchTypeExpression<ManyToManyPart<TChild>> FetchType { get { return fetch; } } private void EnsureDictionary() { if (!typeof(IDictionary).IsAssignableFrom(childType)) throw new ArgumentException(member.Name + " must be of type IDictionary to be used in a non-generic ternary association. Type was: " + childType); } private void EnsureGenericDictionary() { if (!(childType.IsGenericType && childType.GetGenericTypeDefinition() == typeof(IDictionary<,>))) throw new ArgumentException(member.Name + " must be of type IDictionary<> to be used in a ternary assocation. Type was: " + childType); } public ManyToManyPart<TChild> AsTernaryAssociation() { EnsureGenericDictionary(); var indexType = typeof(TChild).GetGenericArguments()[0]; var typeOfValue = typeof(TChild).GetGenericArguments()[1]; return AsTernaryAssociation(indexType.Name + "_id", typeOfValue.Name + "_id"); } public ManyToManyPart<TChild> AsTernaryAssociation(string indexColumn, string valueColumn) { return AsTernaryAssociation(indexColumn, valueColumn, x => {}); } public ManyToManyPart<TChild> AsTernaryAssociation(string indexColumn, string valueColumn, Action<IndexManyToManyPart> indexAction) { EnsureGenericDictionary(); var indexType = typeof(TChild).GetGenericArguments()[0]; var typeOfValue = typeof(TChild).GetGenericArguments()[1]; manyToManyIndex = new IndexManyToManyPart(typeof(ManyToManyPart<TChild>)); manyToManyIndex.Column(indexColumn); manyToManyIndex.Type(indexType); if (indexAction != null) indexAction(manyToManyIndex); ChildKeyColumn(valueColumn); valueType = typeOfValue; isTernary = true; return this; } public ManyToManyPart<TChild> AsTernaryAssociation(Type indexType, Type typeOfValue) { return AsTernaryAssociation(indexType, indexType.Name + "_id", typeOfValue, typeOfValue.Name + "_id"); } public ManyToManyPart<TChild> AsTernaryAssociation(Type indexType, string indexColumn, Type typeOfValue, string valueColumn) { return AsTernaryAssociation(indexType, indexColumn, typeOfValue, valueColumn, x => {}); } public ManyToManyPart<TChild> AsTernaryAssociation(Type indexType, string indexColumn, Type typeOfValue, string valueColumn, Action<IndexManyToManyPart> indexAction) { EnsureDictionary(); manyToManyIndex = new IndexManyToManyPart(typeof(ManyToManyPart<TChild>)); manyToManyIndex.Column(indexColumn); manyToManyIndex.Type(indexType); if (indexAction != null) indexAction(manyToManyIndex); ChildKeyColumn(valueColumn); valueType = typeOfValue; isTernary = true; return this; } public ManyToManyPart<TChild> AsSimpleAssociation() { EnsureGenericDictionary(); var indexType = typeof(TChild).GetGenericArguments()[0]; var typeOfValue = typeof(TChild).GetGenericArguments()[1]; return AsSimpleAssociation(indexType.Name + "_id", typeOfValue.Name + "_id"); } public ManyToManyPart<TChild> AsSimpleAssociation(string indexColumn, string valueColumn) { EnsureGenericDictionary(); var indexType = typeof(TChild).GetGenericArguments()[0]; var typeOfValue = typeof(TChild).GetGenericArguments()[1]; index = new IndexPart(indexType); index.Column(indexColumn); index.Type(indexType); ChildKeyColumn(valueColumn); valueType = typeOfValue; isTernary = true; return this; } public ManyToManyPart<TChild> AsEntityMap() { // The argument to AsMap will be ignored as the ternary association will overwrite the index mapping for the map. // Therefore just pass null. return AsMap(null).AsTernaryAssociation(); } public ManyToManyPart<TChild> AsEntityMap(string indexColumn, string valueColumn) { return AsMap(null).AsTernaryAssociation(indexColumn, valueColumn); } public Type ChildType { get { return typeof(TChild); } } public NotFoundExpression<ManyToManyPart<TChild>> NotFound { get { return notFound; } } protected override ICollectionRelationshipMapping GetRelationship() { var mapping = new ManyToManyMapping(relationshipAttributes.Clone()) { ContainingEntityType = EntityType, }; if (isTernary && valueType != null) mapping.Set(x => x.Class, Layer.Defaults, new TypeReference(valueType)); foreach (var filterPart in childFilters) mapping.ChildFilters.Add(filterPart.GetFilterMapping()); return mapping; } /// <summary> /// Sets the order-by clause on the collection element. /// </summary> public ManyToManyPart<TChild> OrderBy(string orderBy) { collectionAttributes.Set("OrderBy", Layer.UserSupplied, orderBy); return this; } /// <summary> /// Sets the order-by clause on the many-to-many element. /// </summary> public ManyToManyPart<TChild> ChildOrderBy(string orderBy) { relationshipAttributes.Set("OrderBy", Layer.UserSupplied, orderBy); return this; } public ManyToManyPart<TChild> ReadOnly() { collectionAttributes.Set("Mutable", Layer.UserSupplied, !nextBool); nextBool = true; return this; } public ManyToManyPart<TChild> Subselect(string subselect) { collectionAttributes.Set("Subselect", Layer.UserSupplied, subselect); return this; } /// <overloads> /// Applies a filter to the child element of this entity given it's name. /// </overloads> /// <summary> /// Applies a filter to the child element of this entity given it's name. /// </summary> /// <param name="name">The filter's name</param> /// <param name="condition">The condition to apply</param> public ManyToManyPart<TChild> ApplyChildFilter(string name, string condition) { var part = new FilterPart(name, condition); childFilters.Add(part); return this; } /// <overloads> /// Applies a filter to the child element of this entity given it's name. /// </overloads> /// <summary> /// Applies a filter to the child element of this entity given it's name. /// </summary> /// <param name="name">The filter's name</param> public ManyToManyPart<TChild> ApplyChildFilter(string name) { return ApplyChildFilter(name, null); } /// <overloads> /// Applies a named filter to the child element of this many-to-many. /// </overloads> /// <summary> /// Applies a named filter to the child element of this many-to-many. /// </summary> /// <param name="condition">The condition to apply</param> /// <typeparam name="TFilter"> /// The type of a <see cref="FilterDefinition"/> implementation /// defining the filter to apply. /// </typeparam> public ManyToManyPart<TChild> ApplyChildFilter<TFilter>(string condition) where TFilter : FilterDefinition, new() { var part = new FilterPart(new TFilter().Name, condition); childFilters.Add(part); return this; } /// <summary> /// Applies a named filter to the child element of this many-to-many. /// </summary> /// <typeparam name="TFilter"> /// The type of a <see cref="FilterDefinition"/> implementation /// defining the filter to apply. /// </typeparam> public ManyToManyPart<TChild> ApplyChildFilter<TFilter>() where TFilter : FilterDefinition, new() { return ApplyChildFilter<TFilter>(null); } /// <summary> /// Sets the where clause for this relationship, on the many-to-many element. /// </summary> public ManyToManyPart<TChild> ChildWhere(string where) { relationshipAttributes.Set("Where", Layer.UserSupplied, where); return this; } /// <summary> /// Sets the where clause for this relationship, on the many-to-many element. /// Note: This only supports simple cases, use the string overload for more complex clauses. /// </summary> public ManyToManyPart<TChild> ChildWhere(Expression<Func<TChild, bool>> where) { var sql = ExpressionToSql.Convert(where); return ChildWhere(sql); } protected override CollectionMapping GetCollectionMapping() { var collection = base.GetCollectionMapping(); // key columns if (parentKeyColumns.Count == 0) collection.Key.AddColumn(Layer.Defaults, new ColumnMapping(EntityType.Name + "_id")); foreach (var column in parentKeyColumns) collection.Key.AddColumn(Layer.UserSupplied, column); if (collection.Relationship != null) { // child columns if (childKeyColumns.Count == 0) ((ManyToManyMapping)collection.Relationship).AddColumn(Layer.Defaults, new ColumnMapping(typeof(TChild).Name + "_id")); foreach (var column in childKeyColumns) ((ManyToManyMapping)collection.Relationship).AddColumn(Layer.UserSupplied, column); } // HACK: Index only on list and map - shouldn't have to do this! if (index != null) { #pragma warning disable 612,618 collection.Set(x => x.Index, Layer.Defaults, index.GetIndexMapping()); #pragma warning restore 612,618 } // HACK: shouldn't have to do this! if (manyToManyIndex != null && collection.Collection == Collection.Map) #pragma warning disable 612,618 collection.Set(x => x.Index, Layer.Defaults, manyToManyIndex.GetIndexMapping()); #pragma warning restore 612,618 return collection; } } }
// Copyright 2016 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 Android.App; using Android.OS; using Android.Views; using Android.Widget; using Esri.ArcGISRuntime.Data; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.Tasks; using Esri.ArcGISRuntime.Tasks.Geoprocessing; using Esri.ArcGISRuntime.UI; using Esri.ArcGISRuntime.UI.Controls; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace ArcGISRuntimeXamarin.Samples.AnalyzeViewshed { [Activity] public class AnalyzeViewshed : Activity { // Create and hold reference to the used MapView private MapView _myMapView = new MapView(); // Progress bar to show when the geoprocessing task is working ProgressBar _myProgressBar; // Url for the geoprocessing service private const string _viewshedUrl = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Elevation/ESRI_Elevation_World/GPServer/Viewshed"; // The graphics overlay to show where the user clicked in the map private GraphicsOverlay _inputOverlay; // The graphics overlay to display the result of the viewshed analysis private GraphicsOverlay _resultOverlay; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); Title = "Analyze Viewshed"; // Create the UI, setup the control references and execute initialization CreateLayout(); Initialize(); } private void Initialize() { // Create a map with topographic basemap and an initial location Map myMap = new Map(BasemapType.Topographic, 45.3790902612337, 6.84905317262762, 13); // Hook into the MapView tapped event _myMapView.GeoViewTapped += MyMapView_GeoViewTapped; // Create empty overlays for the user clicked location and the results of the viewshed analysis CreateOverlays(); // Assign the map to the MapView _myMapView.Map = myMap; } private async void MyMapView_GeoViewTapped(object sender, GeoViewInputEventArgs e) { // Indicate that the geoprocessing is running SetBusy(); // Clear previous user click location and the viewshed geoprocessing task results _inputOverlay.Graphics.Clear(); _resultOverlay.Graphics.Clear(); // Create a marker graphic where the user clicked on the map and add it to the existing graphics overlay Graphic myInputGraphic = new Graphic(e.Location); _inputOverlay.Graphics.Add(myInputGraphic); // Execute the geoprocessing task using the user click location await CalculateViewshed(e.Location); } private async Task CalculateViewshed(MapPoint location) { // This function will define a new geoprocessing task that performs a custom viewshed analysis based upon a // user click on the map and then display the results back as a polygon fill graphics overlay. If there // is a problem with the execution of the geoprocessing task an error message will be displayed // Create new geoprocessing task using the url defined in the member variables section var myViewshedTask = new GeoprocessingTask(new Uri(_viewshedUrl)); // Create a new feature collection table based upon point geometries using the current map view spatial reference var myInputFeatures = new FeatureCollectionTable(new List<Field>(), GeometryType.Point, _myMapView.SpatialReference); // Create a new feature from the feature collection table. It will not have a coordinate location (x,y) yet Feature myInputFeature = myInputFeatures.CreateFeature(); // Assign a physical location to the new point feature based upon where the user clicked in the map view myInputFeature.Geometry = location; // Add the new feature with (x,y) location to the feature collection table await myInputFeatures.AddFeatureAsync(myInputFeature); // Create the parameters that are passed to the used geoprocessing task GeoprocessingParameters myViewshedParameters = new GeoprocessingParameters(GeoprocessingExecutionType.SynchronousExecute); // Request the output features to use the same SpatialReference as the map view myViewshedParameters.OutputSpatialReference = _myMapView.SpatialReference; // Add an input location to the geoprocessing parameters myViewshedParameters.Inputs.Add("Input_Observation_Point", new GeoprocessingFeatures(myInputFeatures)); // Create the job that handles the communication between the application and the geoprocessing task var myViewshedJob = myViewshedTask.CreateJob(myViewshedParameters); try { // Execute analysis and wait for the results GeoprocessingResult myAnalysisResult = await myViewshedJob.GetResultAsync(); // Get the results from the outputs GeoprocessingFeatures myViewshedResultFeatures = myAnalysisResult.Outputs["Viewshed_Result"] as GeoprocessingFeatures; // Add all the results as a graphics to the map IFeatureSet myViewshedAreas = myViewshedResultFeatures.Features; foreach (var myFeature in myViewshedAreas) { _resultOverlay.Graphics.Add(new Graphic(myFeature.Geometry)); } } catch (Exception ex) { // Display an error message if there is a problem if (myViewshedJob.Status == JobStatus.Failed && myViewshedJob.Error != null) { var alertBuilder = new AlertDialog.Builder(this); alertBuilder.SetTitle("Geoprocessing error"); alertBuilder.SetMessage("Executing geoprocessing failed. " + myViewshedJob.Error.Message); alertBuilder.Show(); } else { var alertBuilder = new AlertDialog.Builder(this); alertBuilder.SetTitle("Sample error"); alertBuilder.SetMessage("An error occurred. " + ex.ToString()); alertBuilder.Show(); } } finally { // Indicate that the geoprocessing is not running SetBusy(false); } } private void CreateOverlays() { // This function will create the overlays that show the user clicked location and the results of the // viewshed analysis. Note: the overlays will not be populated with any graphics at this point // Create renderer for input graphic. Set the size and color properties for the simple renderer SimpleRenderer myInputRenderer = new SimpleRenderer() { Symbol = new SimpleMarkerSymbol() { Size = 15, // Account for the Color differences supported by the various platforms Color = System.Drawing.Color.Red } }; // Create overlay to where input graphic is shown _inputOverlay = new GraphicsOverlay() { Renderer = myInputRenderer }; // Create fill renderer for output of the viewshed analysis. Set the color property of the simple renderer SimpleRenderer myResultRenderer = new SimpleRenderer() { Symbol = new SimpleFillSymbol() { Color = System.Drawing.Color.FromArgb(100, 226, 119, 40) } }; // Create overlay to where viewshed analysis graphic is shown _resultOverlay = new GraphicsOverlay() { Renderer = myResultRenderer }; // Add the created overlays to the MapView _myMapView.GraphicsOverlays.Add(_inputOverlay); _myMapView.GraphicsOverlays.Add(_resultOverlay); } private void SetBusy(bool isBusy = true) { // This function toggles running of the 'progress' control feedback status to denote if // the viewshed analysis is executing as a result of the user click on the map if (isBusy) { // Show busy activity indication _myProgressBar.Visibility = ViewStates.Visible; } else { // Remove the busy activity indication _myProgressBar.Visibility = ViewStates.Invisible; } } private void CreateLayout() { // Create a new vertical layout for the app var layout = new LinearLayout(this) { Orientation = Orientation.Vertical }; // Label for the user instructions var textview_Label1 = new TextView(this); textview_Label1.Text = "Click a location on the map to perform the viewshed analysis."; layout.AddView(textview_Label1); // Add the progress bar to indicate the geoprocessing task is running; make invisible by default _myProgressBar = new ProgressBar(this); _myProgressBar.Indeterminate = true; _myProgressBar.Visibility = ViewStates.Invisible; layout.AddView(_myProgressBar); // Add the map view to the layout layout.AddView(_myMapView); // Show the layout in the app SetContentView(layout); } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine; namespace PlayFab.PfEditor { public class PlayFabEditor : UnityEditor.EditorWindow { #if !UNITY_5_3_OR_NEWER public GUIContent titleContent; #endif #region EdEx Variables // vars for the plugin-wide event system public enum EdExStates { OnLogin, OnLogout, OnMenuItemClicked, OnSubmenuItemClicked, OnHttpReq, OnHttpRes, OnError, OnSuccess, OnWarning } public delegate void PlayFabEdExStateHandler(EdExStates state, string status, string misc); public static event PlayFabEdExStateHandler EdExStateUpdate; public static Dictionary<string, float> blockingRequests = new Dictionary<string, float>(); // key and blockingRequest start time private static float blockingRequestTimeOut = 10f; // abandon the block after this many seconds. public static string latestEdExVersion = string.Empty; internal static PlayFabEditor window; #endregion #region unity lopps & methods void OnEnable() { if (window == null) { window = this; window.minSize = new Vector2(320, 0); } if (!IsEventHandlerRegistered(StateUpdateHandler)) { EdExStateUpdate += StateUpdateHandler; } PlayFabEditorDataService.RefreshStudiosList(true); GetLatestEdExVersion(); } void OnDisable() { // clean up objects: PlayFabEditorPrefsSO.Instance.PanelIsShown = false; if (IsEventHandlerRegistered(StateUpdateHandler)) { EdExStateUpdate -= StateUpdateHandler; } } void OnFocus() { OnEnable(); } [MenuItem("Window/PlayFab/Editor Extensions")] static void PlayFabServices() { var editorAsm = typeof(UnityEditor.Editor).Assembly; var inspWndType = editorAsm.GetType("UnityEditor.SceneHierarchyWindow"); if (inspWndType == null) { inspWndType = editorAsm.GetType("UnityEditor.InspectorWindow"); } window = GetWindow<PlayFabEditor>(inspWndType); window.titleContent = new GUIContent("PlayFab EdEx"); PlayFabEditorPrefsSO.Instance.PanelIsShown = true; } [InitializeOnLoad] public class Startup { static Startup() { if (PlayFabEditorPrefsSO.Instance.PanelIsShown || !PlayFabEditorSDKTools.IsInstalled) { EditorCoroutine.Start(OpenPlayServices()); } } } static IEnumerator OpenPlayServices() { yield return new WaitForSeconds(1f); if (!Application.isPlaying) { PlayFabServices(); } } private void OnGUI() { HideRepaintErrors(OnGuiInternal); } private void OnGuiInternal() { GUI.skin = PlayFabEditorHelper.uiStyle; using (new UnityVertical()) { //Run all updaters prior to drawing; PlayFabEditorHeader.DrawHeader(); GUI.enabled = blockingRequests.Count == 0 && !EditorApplication.isCompiling; if (PlayFabEditorAuthenticate.IsAuthenticated()) { PlayFabEditorMenu.DrawMenu(); switch (PlayFabEditorMenu._menuState) { case PlayFabEditorMenu.MenuStates.Sdks: PlayFabEditorSDKTools.DrawSdkPanel(); break; case PlayFabEditorMenu.MenuStates.Settings: PlayFabEditorSettings.DrawSettingsPanel(); break; case PlayFabEditorMenu.MenuStates.Help: PlayFabEditorHelpMenu.DrawHelpPanel(); break; case PlayFabEditorMenu.MenuStates.Data: PlayFabEditorDataMenu.DrawDataPanel(); break; case PlayFabEditorMenu.MenuStates.Tools: PlayFabEditorToolsMenu.DrawToolsPanel(); break; case PlayFabEditorMenu.MenuStates.Packages: PlayFabEditorPackages.DrawPackagesMenu(); break; default: break; } } else { PlayFabEditorAuthenticate.DrawAuthPanels(); } using (new UnityVertical(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1"), GUILayout.ExpandHeight(true), GUILayout.ExpandWidth(true))) { GUILayout.FlexibleSpace(); } // help tag at the bottom of the help menu. if (PlayFabEditorMenu._menuState == PlayFabEditorMenu.MenuStates.Help) { DisplayHelpMenu(); } } PruneBlockingRequests(); Repaint(); } private static void HideRepaintErrors(Action action) { try { action(); } catch (Exception e) { if (!e.Message.ToLower().Contains("repaint")) throw; // Hide any repaint issues when recompiling } } private static void DisplayHelpMenu() { using (new UnityVertical(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1"))) { using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear"))) { GUILayout.FlexibleSpace(); EditorGUILayout.LabelField("PlayFab Editor Extensions: " + PlayFabEditorHelper.EDEX_VERSION, PlayFabEditorHelper.uiStyle.GetStyle("versionText")); GUILayout.FlexibleSpace(); } //TODO Add plugin upgrade option here (if available); if (ShowEdExUpgrade()) { using (new UnityHorizontal()) { GUILayout.FlexibleSpace(); if (GUILayout.Button("UPGRADE EDEX", PlayFabEditorHelper.uiStyle.GetStyle("textButtonOr"))) { UpgradeEdEx(); } GUILayout.FlexibleSpace(); } } using (new UnityHorizontal()) { GUILayout.FlexibleSpace(); if (GUILayout.Button("VIEW DOCUMENTATION", PlayFabEditorHelper.uiStyle.GetStyle("textButton"))) { Application.OpenURL("https://github.com/PlayFab/UnityEditorExtensions"); } GUILayout.FlexibleSpace(); } using (new UnityHorizontal()) { GUILayout.FlexibleSpace(); if (GUILayout.Button("REPORT ISSUES", PlayFabEditorHelper.uiStyle.GetStyle("textButton"))) { Application.OpenURL("https://github.com/PlayFab/UnityEditorExtensions/issues"); } GUILayout.FlexibleSpace(); } if (!string.IsNullOrEmpty(PlayFabEditorHelper.EDEX_ROOT)) { using (new UnityHorizontal()) { GUILayout.FlexibleSpace(); if (GUILayout.Button("UNINSTALL ", PlayFabEditorHelper.uiStyle.GetStyle("textButton"))) { RemoveEdEx(); } GUILayout.FlexibleSpace(); } } } } #endregion #region menu and helper methods public static void RaiseStateUpdate(EdExStates state, string status = null, string json = null) { if (EdExStateUpdate != null) EdExStateUpdate(state, status, json); } private static void PruneBlockingRequests() { List<string> itemsToRemove = new List<string>(); foreach (var req in blockingRequests) if (req.Value + blockingRequestTimeOut < (float)EditorApplication.timeSinceStartup) itemsToRemove.Add(req.Key); foreach (var item in itemsToRemove) { ClearBlockingRequest(item); RaiseStateUpdate(EdExStates.OnWarning, string.Format(" Request {0} has timed out after {1} seconds.", item, blockingRequestTimeOut)); } } private static void AddBlockingRequest(string state) { blockingRequests[state] = (float)EditorApplication.timeSinceStartup; } private static void ClearBlockingRequest(string state = null) { if (state == null) { blockingRequests.Clear(); } else if (blockingRequests.ContainsKey(state)) { blockingRequests.Remove(state); } } /// <summary> /// Handles state updates within the editor extension. /// </summary> /// <param name="state">the state that triggered this event.</param> /// <param name="status">a generic message about the status.</param> /// <param name="json">a generic container for additional JSON encoded info.</param> private void StateUpdateHandler(EdExStates state, string status, string json) { switch (state) { case EdExStates.OnMenuItemClicked: PlayFabEditorPrefsSO.Instance.curSubMenuIdx = 0; break; case EdExStates.OnSubmenuItemClicked: int parsed; if (int.TryParse(json, out parsed)) PlayFabEditorPrefsSO.Instance.curSubMenuIdx = parsed; break; case EdExStates.OnHttpReq: object temp; if (string.IsNullOrEmpty(json) || Json.PlayFabSimpleJson.TryDeserializeObject(json, out temp)) break; var deserialized = temp as Json.JsonObject; object useSpinner = false; object blockUi = false; if (deserialized.TryGetValue("useSpinner", out useSpinner) && bool.Parse(useSpinner.ToString())) { ProgressBar.UpdateState(ProgressBar.ProgressBarStates.spin); } if (deserialized.TryGetValue("blockUi", out blockUi) && bool.Parse(blockUi.ToString())) { AddBlockingRequest(status); } break; case EdExStates.OnHttpRes: ProgressBar.UpdateState(ProgressBar.ProgressBarStates.off); ProgressBar.UpdateState(ProgressBar.ProgressBarStates.success); ClearBlockingRequest(status); break; case EdExStates.OnError: // deserialize and add json details // clear blocking requests ProgressBar.UpdateState(ProgressBar.ProgressBarStates.error); ClearBlockingRequest(); Debug.LogError(string.Format("PlayFab EditorExtensions: Caught an error:{0}", status)); break; case EdExStates.OnWarning: ProgressBar.UpdateState(ProgressBar.ProgressBarStates.warning); ClearBlockingRequest(); Debug.LogWarning(string.Format("PlayFab EditorExtensions: {0}", status)); break; case EdExStates.OnSuccess: ClearBlockingRequest(); ProgressBar.UpdateState(ProgressBar.ProgressBarStates.success); break; } } public static bool IsEventHandlerRegistered(PlayFabEdExStateHandler prospectiveHandler) { if (EdExStateUpdate == null) return false; foreach (PlayFabEdExStateHandler existingHandler in EdExStateUpdate.GetInvocationList()) if (existingHandler == prospectiveHandler) return true; return false; } private static void GetLatestEdExVersion() { var threshold = PlayFabEditorPrefsSO.Instance.EdSet_lastEdExVersionCheck != DateTime.MinValue ? PlayFabEditorPrefsSO.Instance.EdSet_lastEdExVersionCheck.AddHours(1) : DateTime.MinValue; if (DateTime.Today > threshold) { PlayFabEditorHttp.MakeGitHubApiCall("https://api.github.com/repos/PlayFab/UnityEditorExtensions/git/refs/tags", (version) => { latestEdExVersion = version ?? "Unknown"; PlayFabEditorPrefsSO.Instance.EdSet_latestEdExVersion = latestEdExVersion; }); } else { latestEdExVersion = PlayFabEditorPrefsSO.Instance.EdSet_latestEdExVersion; } } private static bool ShowEdExUpgrade() { if (string.IsNullOrEmpty(latestEdExVersion) || latestEdExVersion == "Unknown") return false; if (string.IsNullOrEmpty(PlayFabEditorHelper.EDEX_VERSION) || PlayFabEditorHelper.EDEX_VERSION == "Unknown") return true; string[] currrent = PlayFabEditorHelper.EDEX_VERSION.Split('.'); if (currrent.Length != 3) return true; string[] latest = latestEdExVersion.Split('.'); return latest.Length != 3 || int.Parse(latest[0]) > int.Parse(currrent[0]) || int.Parse(latest[1]) > int.Parse(currrent[1]) || int.Parse(latest[2]) > int.Parse(currrent[2]); } private static void RemoveEdEx(bool prompt = true) { if (prompt && !EditorUtility.DisplayDialog("Confirm Editor Extensions Removal", "This action will remove PlayFab Editor Extensions from the current project.", "Confirm", "Cancel")) return; try { window.Close(); var edExRoot = new DirectoryInfo(PlayFabEditorHelper.EDEX_ROOT); FileUtil.DeleteFileOrDirectory(edExRoot.Parent.FullName); AssetDatabase.Refresh(); } catch (Exception ex) { RaiseStateUpdate(EdExStates.OnError, ex.Message); } } private static void UpgradeEdEx() { if (EditorUtility.DisplayDialog("Confirm EdEx Upgrade", "This action will remove the current PlayFab Editor Extensions and install the lastet version.", "Confirm", "Cancel")) { window.Close(); ImportLatestEdEx(); } } private static void ImportLatestEdEx() { PlayFabEditorHttp.MakeDownloadCall("https://api.playfab.com/sdks/download/unity-edex-upgrade", (fileName) => { AssetDatabase.ImportPackage(fileName, false); Debug.Log("PlayFab EdEx Upgrade: Complete"); }); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void CompareNotLessThanDouble() { var test = new SimpleBinaryOpTest__CompareNotLessThanDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareNotLessThanDouble { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Double); private const int Op2ElementCount = VectorSize / sizeof(Double); private const int RetElementCount = VectorSize / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar2; private Vector128<Double> _fld1; private Vector128<Double> _fld2; private SimpleBinaryOpTest__DataTable<Double, Double, Double> _dataTable; static SimpleBinaryOpTest__CompareNotLessThanDouble() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__CompareNotLessThanDouble() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); } _dataTable = new SimpleBinaryOpTest__DataTable<Double, Double, Double>(_data1, _data2, new Double[RetElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.CompareNotLessThan( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.CompareNotLessThan( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.CompareNotLessThan( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareNotLessThan), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareNotLessThan), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareNotLessThan), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.CompareNotLessThan( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var result = Sse2.CompareNotLessThan(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareNotLessThan(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareNotLessThan(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__CompareNotLessThanDouble(); var result = Sse2.CompareNotLessThan(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.CompareNotLessThan(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Double> left, Vector128<Double> right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { if (BitConverter.DoubleToInt64Bits(result[0]) != (!(left[0] < right[0]) ? -1 : 0)) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(result[i]) != (!(left[i] < right[i]) ? -1 : 0)) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.CompareNotLessThan)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using UnityEngine; using UnityEngine.UI; using System.Collections.Generic; using System.Collections; public class AtomizeOnClick : MonoBehaviour { private static readonly int MaxEffects = 10; [SerializeField] private Vector2 uiBasePoint; void Start() { canAtomize = true; } void OnFinish() { StartCoroutine(SetVisible(true)); canAtomize = true; } private AtomizerEffectGroup GetRandomEffect() { AtomizerEffectGroup effectGroup = Atomizer.CreateEffectGroup(); bool combine = (Random.value > 0.5f); int numberOfEffects = Random.Range(1, 4); uiText = numberOfEffects + " Effect(s):\n"; for (int i = 0; i < numberOfEffects; ++i) { int selection = Random.Range(0, MaxEffects); switch (selection) { case 0: { Disintegrate effect = new Disintegrate(); effect.Duration = Random.Range(1.0f, 5.0f); effect.FadeColour = new Color(Random.value, Random.value, Random.value, Random.value); if (combine) { uiText += "\n\nCombined Effect: Disintegrate\nDuration: " + effect.Duration + "\nFadeColour: " + effect.FadeColour; effectGroup.Combine(effect); } else { uiText += "\n\nChained Effect: Disintegrate\nDuration: " + effect.Duration + "\nFadeColour: " + effect.FadeColour; effectGroup.Chain(effect); } } break; case 1: { Percolate effect = new Percolate(); effect.PercolationTime = Random.Range(1.0f, 4.0f); effect.PercolationSpeed = Random.Range(0.5f, 6.0f); effect.Duration = 2.0f * effect.PercolationTime; int directionIndex = Random.Range(0, System.Enum.GetValues(typeof(PercolationDirection)).Length); effect.Direction = (PercolationDirection)directionIndex; if (combine) { uiText += "\n\nCombined Effect: ParticlePercolator\nPercTime: " + effect.PercolationTime + "\nPercSpeed: " + effect.PercolationSpeed + "\nDuration: " + effect.Duration + "\nDirection: " + effect.Direction; effectGroup.Combine(effect); } else { uiText += "\n\nChained Effect: ParticlePercolator\nPercTime: " + effect.PercolationTime + "\nPercSpeed: " + effect.PercolationSpeed + "\nDuration: " + effect.Duration + "\nDirection: " + effect.Direction; effectGroup.Chain(effect); } } break; case 2: { BreakAndReform effect = new BreakAndReform(); effect.BreakApartSpeed = Random.Range(1.0f, 8.0f); effect.BreakPhaseDuration = Random.Range(1.0f, 3.0f); effect.ReformPhaseDuration = Random.Range(1.0f, 3.0f); if (combine) { uiText += "\n\nCombined Effect: BreakAndReform\nBreak Speed: " + effect.BreakApartSpeed + "\nBreak Phase Duration: " + effect.BreakPhaseDuration + "\nReform Phase Duration: " + effect.ReformPhaseDuration; effectGroup.Combine(effect); } else { uiText += "\n\nChained Effect: BreakAndReform\nBreak Speed: " + effect.BreakApartSpeed + "\nBreak Phase Duration: " + effect.BreakPhaseDuration + "\nReform Phase Duration: " + effect.ReformPhaseDuration; effectGroup.Chain(effect); } } break; case 3: { SwapColours effect = new SwapColours(); int modeIndex = Random.Range(0, System.Enum.GetValues(typeof(ColourSwapMode)).Length); effect.ColourSwapMode = (ColourSwapMode)modeIndex; effect.Duration = Random.Range(1.0f, 4.0f); if (combine) { uiText += "\n\nCombined Effect: SwapColours\nColour Swap Mode: " + effect.ColourSwapMode + "\nDuration: " + effect.Duration; effectGroup.Combine(effect); } else { uiText += "\n\nChained Effect: SwapColours\nColour Swap Mode: " + effect.ColourSwapMode + "\nDuration: " + effect.Duration; effectGroup.Chain(effect); } } break; case 4: { Pulse effect = new Pulse(); effect.PulseLength = Random.Range(0.1f, 0.6f); effect.PulseStrength = Random.Range(0.2f, 0.8f); effect.Duration = 4.0f * effect.PulseLength; if (combine) { uiText += "\n\nCombined Effect: Pulse\nPulse Length: " + effect.PulseLength + "\nStrength: " + effect.PulseStrength + "\nDuration: " + effect.Duration; effectGroup.Combine(effect); } else { uiText += "\n\nChained Effect: Pulse\nPulse Length: " + effect.PulseLength + "\nStrength: " + effect.PulseStrength + "\nDuration: " + effect.Duration; effectGroup.Chain(effect); } } break; case 5: { Vacuum effect = new Vacuum(); effect.VacuumPoint = new Vector3( transform.position.x + Random.Range(-1.0f, 1.0f), transform.position.y + Random.Range(-1.0f, 1.0f), transform.position.z + Random.Range(-1.0f, 1.0f)); effect.MoveSpeed = Random.Range(0.1f, 3.0f); effect.Duration = 5.0f; if (combine) { uiText += "\n\nCombined Effect: Vacuum\nPoint: " + effect.VacuumPoint + "\nMove Speed: " + effect.MoveSpeed + "\nDuration: " + effect.Duration; effectGroup.Combine(effect); } else { uiText += "\n\nChained Effect: Vacuum\nPoint: " + effect.VacuumPoint + "\nMove Speed: " + effect.MoveSpeed + "\nDuration: " + effect.Duration; effectGroup.Chain(effect); } } break; case 6: { Warp effect = new Warp(); effect.WarpTime = Random.Range(1.0f, 2.0f); effect.TargetPoint = new Vector3( transform.position.x + Random.Range(-1.0f, 1.0f), transform.position.y + Random.Range(-1.0f, 1.0f), transform.position.z + Random.Range(-1.0f, 1.0f)); effect.StartScale = Random.Range(0.5f, 3.0f); if (combine) { uiText += "\n\nCombined Effect: Warp\nTime: " + effect.WarpTime + "\nTarget: " + effect.TargetPoint + "\nStart Scale: " + effect.StartScale; effectGroup.Combine(effect); } else { uiText += "\n\nChained Effect: Warp\nTime: " + effect.WarpTime + "\nTarget: " + effect.TargetPoint + "\nStart Scale: " + effect.StartScale; effectGroup.Chain(effect); } } break; case 7: { Smolder effect = new Smolder(); effect.SmolderColour = new Color(Random.value, Random.value, Random.value, Random.value); effect.BurntColour = new Color(Random.value, Random.value, Random.value, Random.value); effect.EndColour = Color.clear; effect.SmolderDuration = Random.Range(0.5f, 2.5f); effect.BurntDuration = Random.Range(0.5f, 2.5f); effect.Smoothness = Random.Range(0.1f, 0.9f); effect.DispersionForce = Random.Range(0.0f, 4.0f); effect.SmolderSpeed = Random.Range(0.1f, 2.0f); effect.Source = Input.mousePosition; if (combine) { uiText += "\n\nCombined Effect: Smolder" + "\nSmolderColour : " + effect.SmolderColour + "\nBurntColour : " + effect.BurntColour + "\nEndColour : " + effect.EndColour + "\nSmolderDuration : " + effect.SmolderDuration + "\nBurntDuration : " + effect.BurntDuration + "\nSmoothness : " + effect.Smoothness + "\nDispersionForce : " + effect.DispersionForce + "\nSmolderSpeed : " + effect.SmolderSpeed; effectGroup.Combine(effect); } else { uiText += "\n\nChained Effect: Smolder" + "\nSmolderColour : " + effect.SmolderColour + "\nBurntColour : " + effect.BurntColour + "\nEndColour : " + effect.EndColour + "\nSmolderDuration : " + effect.SmolderDuration + "\nBurntDuration : " + effect.BurntDuration + "\nSmoothness : " + effect.Smoothness + "\nDispersionForce : " + effect.DispersionForce + "\nSmolderSpeed : " + effect.SmolderSpeed; effectGroup.Chain(effect); } } break; case 8: { Jiggle effect = new Jiggle(); effect.Noise = Random.Range(0.1f, 1.0f); effect.Duration = Random.Range(0.5f, 3.0f); if (combine) { uiText += "\n\nCombined Effect: Jiggle\nNoise: " + effect.Noise + "\nDuration: " + effect.Duration; effectGroup.Combine(effect); } else { uiText += "\n\nChained Effect: Jiggle\nNoise: " + effect.Noise + "\nDuration: " + effect.Duration; effectGroup.Chain(effect); } } break; case 9: { Pop effect = new Pop(); effect.Duration = Random.Range(1.0f, 3.0f); effect.Force = Random.Range(0.1f, 4.0f); if (combine) { uiText += "\n\nCombined Effect: Pop\nForce: " + effect.Force + "\nDuration: " + effect.Duration; effectGroup.Combine(effect); } else { uiText += "\n\nChained Effect: Pop\nForce: " + effect.Force + "\nDuration: " + effect.Duration; effectGroup.Chain(effect); } } break; } } return effectGroup; } public void Play() { uiText = ""; AtomizerEffectGroup effectGroup = GetRandomEffect(); Atomizer.Atomize(gameObject, effectGroup, OnFinish); StartCoroutine(SetVisible(false)); } private IEnumerator SetVisible(bool visible) { yield return new WaitForEndOfFrame(); List<Renderer> renderers = gameObject.GetAllComponents<Renderer>(); if (renderers != null) { renderers.ForEach(item => item.enabled = visible); } Image img = GetComponentInChildren<Image>(); if (img != null) { GetComponentInChildren<Image>().enabled = visible; } } void OnGUI() { GUI.Label(new Rect(uiBasePoint.x, uiBasePoint.y, 200, 600), uiText); } void OnMouseUpAsButton() { if (canAtomize) { canAtomize = false; Play(); } } private string uiText; private bool canAtomize; }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcdcv = Google.Cloud.Dialogflow.Cx.V3; using sys = System; namespace Google.Cloud.Dialogflow.Cx.V3 { /// <summary>Resource name for the <c>Version</c> resource.</summary> public sealed partial class VersionName : gax::IResourceName, sys::IEquatable<VersionName> { /// <summary>The possible contents of <see cref="VersionName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}</c>. /// </summary> ProjectLocationAgentFlowVersion = 1, } private static gax::PathTemplate s_projectLocationAgentFlowVersion = new gax::PathTemplate("projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}"); /// <summary>Creates a <see cref="VersionName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="VersionName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static VersionName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new VersionName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="VersionName"/> with the pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="flowId">The <c>Flow</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="versionId">The <c>Version</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="VersionName"/> constructed from the provided ids.</returns> public static VersionName FromProjectLocationAgentFlowVersion(string projectId, string locationId, string agentId, string flowId, string versionId) => new VersionName(ResourceNameType.ProjectLocationAgentFlowVersion, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), agentId: gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), flowId: gax::GaxPreconditions.CheckNotNullOrEmpty(flowId, nameof(flowId)), versionId: gax::GaxPreconditions.CheckNotNullOrEmpty(versionId, nameof(versionId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="VersionName"/> with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="flowId">The <c>Flow</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="versionId">The <c>Version</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="VersionName"/> with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}</c>. /// </returns> public static string Format(string projectId, string locationId, string agentId, string flowId, string versionId) => FormatProjectLocationAgentFlowVersion(projectId, locationId, agentId, flowId, versionId); /// <summary> /// Formats the IDs into the string representation of this <see cref="VersionName"/> with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="flowId">The <c>Flow</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="versionId">The <c>Version</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="VersionName"/> with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}</c>. /// </returns> public static string FormatProjectLocationAgentFlowVersion(string projectId, string locationId, string agentId, string flowId, string versionId) => s_projectLocationAgentFlowVersion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), gax::GaxPreconditions.CheckNotNullOrEmpty(flowId, nameof(flowId)), gax::GaxPreconditions.CheckNotNullOrEmpty(versionId, nameof(versionId))); /// <summary>Parses the given resource name string into a new <see cref="VersionName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="versionName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="VersionName"/> if successful.</returns> public static VersionName Parse(string versionName) => Parse(versionName, false); /// <summary> /// Parses the given resource name string into a new <see cref="VersionName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="versionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="VersionName"/> if successful.</returns> public static VersionName Parse(string versionName, bool allowUnparsed) => TryParse(versionName, allowUnparsed, out VersionName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="VersionName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="versionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="VersionName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string versionName, out VersionName result) => TryParse(versionName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="VersionName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="versionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="VersionName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string versionName, bool allowUnparsed, out VersionName result) { gax::GaxPreconditions.CheckNotNull(versionName, nameof(versionName)); gax::TemplatedResourceName resourceName; if (s_projectLocationAgentFlowVersion.TryParseName(versionName, out resourceName)) { result = FromProjectLocationAgentFlowVersion(resourceName[0], resourceName[1], resourceName[2], resourceName[3], resourceName[4]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(versionName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private VersionName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string agentId = null, string flowId = null, string locationId = null, string projectId = null, string versionId = null) { Type = type; UnparsedResource = unparsedResourceName; AgentId = agentId; FlowId = flowId; LocationId = locationId; ProjectId = projectId; VersionId = versionId; } /// <summary> /// Constructs a new instance of a <see cref="VersionName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="flowId">The <c>Flow</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="versionId">The <c>Version</c> ID. Must not be <c>null</c> or empty.</param> public VersionName(string projectId, string locationId, string agentId, string flowId, string versionId) : this(ResourceNameType.ProjectLocationAgentFlowVersion, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), agentId: gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), flowId: gax::GaxPreconditions.CheckNotNullOrEmpty(flowId, nameof(flowId)), versionId: gax::GaxPreconditions.CheckNotNullOrEmpty(versionId, nameof(versionId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Agent</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AgentId { get; } /// <summary> /// The <c>Flow</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string FlowId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Version</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string VersionId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationAgentFlowVersion: return s_projectLocationAgentFlowVersion.Expand(ProjectId, LocationId, AgentId, FlowId, VersionId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as VersionName); /// <inheritdoc/> public bool Equals(VersionName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(VersionName a, VersionName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(VersionName a, VersionName b) => !(a == b); } public partial class CreateVersionOperationMetadata { /// <summary> /// <see cref="VersionName"/>-typed view over the <see cref="Version"/> resource name property. /// </summary> public VersionName VersionAsVersionName { get => string.IsNullOrEmpty(Version) ? null : VersionName.Parse(Version, allowUnparsed: true); set => Version = value?.ToString() ?? ""; } } public partial class Version { /// <summary> /// <see cref="gcdcv::VersionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdcv::VersionName VersionName { get => string.IsNullOrEmpty(Name) ? null : gcdcv::VersionName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListVersionsRequest { /// <summary><see cref="FlowName"/>-typed view over the <see cref="Parent"/> resource name property.</summary> public FlowName ParentAsFlowName { get => string.IsNullOrEmpty(Parent) ? null : FlowName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetVersionRequest { /// <summary> /// <see cref="gcdcv::VersionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdcv::VersionName VersionName { get => string.IsNullOrEmpty(Name) ? null : gcdcv::VersionName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class CreateVersionRequest { /// <summary><see cref="FlowName"/>-typed view over the <see cref="Parent"/> resource name property.</summary> public FlowName ParentAsFlowName { get => string.IsNullOrEmpty(Parent) ? null : FlowName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class DeleteVersionRequest { /// <summary> /// <see cref="gcdcv::VersionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdcv::VersionName VersionName { get => string.IsNullOrEmpty(Name) ? null : gcdcv::VersionName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class LoadVersionRequest { /// <summary> /// <see cref="gcdcv::VersionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdcv::VersionName VersionName { get => string.IsNullOrEmpty(Name) ? null : gcdcv::VersionName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
using System; using System.Collections.Generic; using CamBam.Geom; using CamBam.CAD; namespace Geom { public struct Vector2d { public double X; public double Y; public double Mag { get { return Math.Sqrt(X * X + Y * Y); } } public double Angle { get { return Math.Atan2(Y, X); } } public double Ccw_angle { get { double angle = this.Angle; return angle >= 0 ? angle : angle + 2.0 * Math.PI; } } public Point2F Point { get { return (Point2F)this; } } public Vector2d(double x, double y) { X = x; Y = y; } public Vector2d(Point2F pt) { X = pt.X; Y = pt.Y; } public Vector2d(Point2F start, Point2F end) { X = end.X - start.X; Y = end.Y - start.Y; } public Vector2d(Vector2d v) { X = v.X; Y = v.Y; } public Vector2d Normal() { return new Vector2d(-Y, X); } public Vector2d Inverted() { return new Vector2d(-X, -Y); } public Vector2d Unit() { double mag = Mag; return new Vector2d(X / mag, Y / mag); } public Vector2d Rotated(double theta) { double x = X * Math.Cos(theta) - Y * Math.Sin(theta); double y = X * Math.Sin(theta) + Y * Math.Cos(theta); return new Vector2d(x, y); } public double Det(Vector2d b) { return X * b.Y - Y * b.X; } public double Angle_to(Vector2d b) { return Math.Atan2(this.Det(b), this * b); } public double Ccw_angle_to(Vector2d b) { double angle = this.Angle_to(b); return angle >= 0 ? angle : angle + 2.0 * Math.PI; } public static explicit operator Point2F(Vector2d v) { return new Point2F(v.X, v.Y); } public static double operator *(Vector2d a, Vector2d b) { return a.X * b.X + a.Y * b.Y; } public static Vector2d operator *(Vector2d a, double d) { return new Vector2d(a.X * d, a.Y * d); } public static Vector2d operator *(double d, Vector2d a) { return a * d; } public static Vector2d operator +(Vector2d a, Vector2d b) { return new Vector2d(a.X + b.X, a.Y + b.Y); } public static Vector2d operator -(Vector2d a, Vector2d b) { return new Vector2d(a.X - b.X, a.Y - b.Y); } } public struct Biarc2d { public object Seg1; public object Seg2; public Point2F P1 { get { return this.Seg1 is Arc2F ? ((Arc2F)this.Seg1).P1 : ((Line2F)this.Seg1).p1; } } public Point2F Pm { get { return this.Seg1 is Arc2F ? ((Arc2F)this.Seg1).P2 : ((Line2F)this.Seg1).p2; } } public Point2F P2 { get { return this.Seg2 is Arc2F ? ((Arc2F)this.Seg2).P2 : ((Line2F)this.Seg2).p2; } } /* Adapted from http://www.ryanjuckett.com/programming/biarc-interpolation */ private static Point2F calc_pm(Point2F p1, Vector2d t1, Point2F p2, Vector2d t2) { Vector2d v = new Vector2d(p2 - p1); Vector2d t = t1 + t2; double v_dot_t = v * t; double t1_dot_t2 = t1 * t2; double d2; double d2_denom = 2 * (1 - t1_dot_t2); if (d2_denom == 0) // equal tangents { d2_denom = 4.0 * (v * t2); d2 = v * v / d2_denom; if (d2_denom == 0) // v perpendicular to tangents return p1 + (v * 0.5).Point; } else // normal case { double d2_num = -v_dot_t + Math.Sqrt(v_dot_t * v_dot_t + 2 * (1 - t1_dot_t2) * (v * v)); d2 = d2_num / d2_denom; } return (p1 + p2 + (d2 * (t1 - t2)).Point) * 0.5; } private static object[] calc_arcs(Point2F p1, Vector2d t1, Point2F p2, Vector2d t2, Point2F pm) { object[] segs = new object[2]; Vector2d n1 = t1.Normal(); Vector2d pm_minus_p1 = new Vector2d(pm - p1); double c1_denom = 2 * (n1 * pm_minus_p1); if (c1_denom == 0) // c1 is at infinity, replace arc with line { segs[0] = new Line2F(p1, pm); } else { Point2F c1 = p1 + (pm_minus_p1 * pm_minus_p1 / c1_denom * n1).Point; RotationDirection dir1 = new Vector2d(p1 - c1) * n1 > 0 ? RotationDirection.CW : RotationDirection.CCW; segs[0] = new Arc2F(c1, p1, pm, dir1); } Vector2d n2 = t2.Normal(); Vector2d pm_minus_p2 = new Vector2d(pm - p2); double c2_denom = 2 * (n2 * pm_minus_p2); if (c2_denom == 0) // c2 is at infinity, replace arc with line { segs[1] = new Line2F(pm, p2); } else { Point2F c2 = p2 + (pm_minus_p2 * pm_minus_p2 / c2_denom * n2).Point; RotationDirection dir2 = new Vector2d(p2 - c2) * n2 > 0 ? RotationDirection.CW : RotationDirection.CCW; segs[1] = new Arc2F(c2, pm, p2, dir2); } return segs; } public Polyline To_polyline(double tolerance) { Polyline p = new Polyline(); if (Seg1 is Arc2F) p.Add((Arc2F)Seg1, tolerance); else p.Add((Line2F)Seg1, tolerance); if (Seg2 is Arc2F) p.Add((Arc2F)Seg2, tolerance); else p.Add((Line2F)Seg2, tolerance); return p; } public Biarc2d(Point2F p1, Vector2d t1, Point2F p2, Vector2d t2) { Point2F pm = calc_pm(p1, t1, p2, t2); object[] segs = calc_arcs(p1, t1, p2, t2, pm); this.Seg1 = segs[0]; this.Seg2 = segs[1]; } } public class Curve2d { // XXX: empty curve shouldn't be accessed private List<Point2F> _points = new List<Point2F>(); private List<double> _seg_offsets = new List<double>(); private double _len = 0; public List<Point2F> Points { get { return _points; } } public Point2F Start { get { return _points[0]; } } public Point2F End { get { return _points[_points.Count - 1]; } } public double Length { get { return _len; } } public void Add(Point2F pt) { if (_points.Count != 0) { double seg_len = End.DistanceTo(pt); _seg_offsets.Add(_len); _len += seg_len; } _points.Add(pt); } public Point2F Get_parametric_pt(double u) { if (_points.Count < 2) return _points[0]; double offset = u * _len; int seg = _seg_offsets.BinarySearch(offset); // if there is no exact element found, binary search returns 1's complemented index of the // first larger element, so we use it to find last smaller element if (seg < 0) seg = ~seg - 1; offset -= _seg_offsets[seg]; Point2F p1 = _points[seg]; Point2F p2 = _points[seg + 1]; double dist = p2.DistanceTo(p1); double x = p1.X + offset / dist * (p2.X - p1.X); double y = p1.Y + offset / dist * (p2.Y - p1.Y); return new Point2F(x, y); } public Polyline To_polyline() { Polyline p = new Polyline(); foreach (Point2F pt in Points) p.Add((Point3F)pt); return p; } } }
/* * CP28597.cs - Greek (ISO) code page. * * Copyright (c) 2002 Southern Storm Software, Pty Ltd * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Generated from "ibm-4909.ucm". namespace I18N.West { using System; using I18N.Common; public class CP28597 : ByteEncoding { public CP28597() : base(28597, ToChars, "Greek (ISO)", "iso-8859-7", "iso-8859-7", "iso-8859-7", true, true, true, true, 1253) {} private static readonly char[] ToChars = { '\u0000', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\u0007', '\u0008', '\u0009', '\u000A', '\u000B', '\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001A', '\u001B', '\u001C', '\u001D', '\u001E', '\u001F', '\u0020', '\u0021', '\u0022', '\u0023', '\u0024', '\u0025', '\u0026', '\u0027', '\u0028', '\u0029', '\u002A', '\u002B', '\u002C', '\u002D', '\u002E', '\u002F', '\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035', '\u0036', '\u0037', '\u0038', '\u0039', '\u003A', '\u003B', '\u003C', '\u003D', '\u003E', '\u003F', '\u0040', '\u0041', '\u0042', '\u0043', '\u0044', '\u0045', '\u0046', '\u0047', '\u0048', '\u0049', '\u004A', '\u004B', '\u004C', '\u004D', '\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u0053', '\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059', '\u005A', '\u005B', '\u005C', '\u005D', '\u005E', '\u005F', '\u0060', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065', '\u0066', '\u0067', '\u0068', '\u0069', '\u006A', '\u006B', '\u006C', '\u006D', '\u006E', '\u006F', '\u0070', '\u0071', '\u0072', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077', '\u0078', '\u0079', '\u007A', '\u007B', '\u007C', '\u007D', '\u007E', '\u007F', '\u0080', '\u0081', '\u0082', '\u0083', '\u0084', '\u0085', '\u0086', '\u0087', '\u0088', '\u0089', '\u008A', '\u008B', '\u008C', '\u008D', '\u008E', '\u008F', '\u0090', '\u0091', '\u0092', '\u0093', '\u0094', '\u0095', '\u0096', '\u0097', '\u0098', '\u0099', '\u009A', '\u009B', '\u009C', '\u009D', '\u009E', '\u009F', '\u00A0', '\u2018', '\u2019', '\u00A3', '\u20AC', '\u003F', '\u00A6', '\u00A7', '\u00A8', '\u00A9', '\u003F', '\u00AB', '\u00AC', '\u00AD', '\u003F', '\u2015', '\u00B0', '\u00B1', '\u00B2', '\u00B3', '\u00B4', '\u0385', '\u0386', '\u0387', '\u0388', '\u0389', '\u038A', '\u00BB', '\u038C', '\u00BD', '\u038E', '\u038F', '\u0390', '\u0391', '\u0392', '\u0393', '\u0394', '\u0395', '\u0396', '\u0397', '\u0398', '\u0399', '\u039A', '\u039B', '\u039C', '\u039D', '\u039E', '\u039F', '\u03A0', '\u03A1', '\u003F', '\u03A3', '\u03A4', '\u03A5', '\u03A6', '\u03A7', '\u03A8', '\u03A9', '\u03AA', '\u03AB', '\u03AC', '\u03AD', '\u03AE', '\u03AF', '\u03B0', '\u03B1', '\u03B2', '\u03B3', '\u03B4', '\u03B5', '\u03B6', '\u03B7', '\u03B8', '\u03B9', '\u03BA', '\u03BB', '\u03BC', '\u03BD', '\u03BE', '\u03BF', '\u03C0', '\u03C1', '\u03C2', '\u03C3', '\u03C4', '\u03C5', '\u03C6', '\u03C7', '\u03C8', '\u03C9', '\u03CA', '\u03CB', '\u03CC', '\u03CD', '\u03CE', '\u003F', }; protected override void ToBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(chars[charIndex++]); if(ch >= 161) switch(ch) { case 0x00A3: case 0x00A6: case 0x00A7: case 0x00A8: case 0x00A9: case 0x00AB: case 0x00AC: case 0x00AD: case 0x00B0: case 0x00B1: case 0x00B2: case 0x00B3: case 0x00B4: case 0x00B7: case 0x00BB: case 0x00BD: break; case 0x0385: case 0x0386: case 0x0387: case 0x0388: case 0x0389: case 0x038A: ch -= 0x02D0; break; case 0x038C: ch = 0xBC; break; case 0x038E: case 0x038F: case 0x0390: case 0x0391: case 0x0392: case 0x0393: case 0x0394: case 0x0395: case 0x0396: case 0x0397: case 0x0398: case 0x0399: case 0x039A: case 0x039B: case 0x039C: case 0x039D: case 0x039E: case 0x039F: case 0x03A0: case 0x03A1: ch -= 0x02D0; break; case 0x03A3: case 0x03A4: case 0x03A5: case 0x03A6: case 0x03A7: case 0x03A8: case 0x03A9: case 0x03AA: case 0x03AB: case 0x03AC: case 0x03AD: case 0x03AE: case 0x03AF: case 0x03B0: case 0x03B1: case 0x03B2: case 0x03B3: case 0x03B4: case 0x03B5: case 0x03B6: case 0x03B7: case 0x03B8: case 0x03B9: case 0x03BA: case 0x03BB: case 0x03BC: case 0x03BD: case 0x03BE: case 0x03BF: case 0x03C0: case 0x03C1: case 0x03C2: case 0x03C3: case 0x03C4: case 0x03C5: case 0x03C6: case 0x03C7: case 0x03C8: case 0x03C9: case 0x03CA: case 0x03CB: case 0x03CC: case 0x03CD: case 0x03CE: ch -= 0x02D0; break; case 0x03D5: ch = 0xF6; break; case 0x2015: ch = 0xAF; break; case 0x2018: ch = 0xA1; break; case 0x2019: ch = 0xA2; break; case 0x20AC: ch = 0xA4; break; default: { if(ch >= 0xFF01 && ch <= 0xFF5E) ch -= 0xFEE0; else ch = 0x3F; } break; } bytes[byteIndex++] = (byte)ch; --charCount; } } protected override void ToBytes(String s, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(s[charIndex++]); if(ch >= 161) switch(ch) { case 0x00A3: case 0x00A6: case 0x00A7: case 0x00A8: case 0x00A9: case 0x00AB: case 0x00AC: case 0x00AD: case 0x00B0: case 0x00B1: case 0x00B2: case 0x00B3: case 0x00B4: case 0x00B7: case 0x00BB: case 0x00BD: break; case 0x0385: case 0x0386: case 0x0387: case 0x0388: case 0x0389: case 0x038A: ch -= 0x02D0; break; case 0x038C: ch = 0xBC; break; case 0x038E: case 0x038F: case 0x0390: case 0x0391: case 0x0392: case 0x0393: case 0x0394: case 0x0395: case 0x0396: case 0x0397: case 0x0398: case 0x0399: case 0x039A: case 0x039B: case 0x039C: case 0x039D: case 0x039E: case 0x039F: case 0x03A0: case 0x03A1: ch -= 0x02D0; break; case 0x03A3: case 0x03A4: case 0x03A5: case 0x03A6: case 0x03A7: case 0x03A8: case 0x03A9: case 0x03AA: case 0x03AB: case 0x03AC: case 0x03AD: case 0x03AE: case 0x03AF: case 0x03B0: case 0x03B1: case 0x03B2: case 0x03B3: case 0x03B4: case 0x03B5: case 0x03B6: case 0x03B7: case 0x03B8: case 0x03B9: case 0x03BA: case 0x03BB: case 0x03BC: case 0x03BD: case 0x03BE: case 0x03BF: case 0x03C0: case 0x03C1: case 0x03C2: case 0x03C3: case 0x03C4: case 0x03C5: case 0x03C6: case 0x03C7: case 0x03C8: case 0x03C9: case 0x03CA: case 0x03CB: case 0x03CC: case 0x03CD: case 0x03CE: ch -= 0x02D0; break; case 0x03D5: ch = 0xF6; break; case 0x2015: ch = 0xAF; break; case 0x2018: ch = 0xA1; break; case 0x2019: ch = 0xA2; break; case 0x20AC: ch = 0xA4; break; default: { if(ch >= 0xFF01 && ch <= 0xFF5E) ch -= 0xFEE0; else ch = 0x3F; } break; } bytes[byteIndex++] = (byte)ch; --charCount; } } }; // class CP28597 public class ENCiso_8859_7 : CP28597 { public ENCiso_8859_7() : base() {} }; // class ENCiso_8859_7 }; // namespace I18N.West
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // using System.IO; using NUnit.Framework; using DiscUtils.Vdi; namespace DiscUtils.Partitions { [TestFixture] public class GuidPartitionTableTest { [Test] public void Initialize() { MemoryStream ms = new MemoryStream(); using (Disk disk = Disk.InitializeDynamic(ms, Ownership.Dispose, 3 * 1024 * 1024)) { GuidPartitionTable table = GuidPartitionTable.Initialize(disk); Assert.AreEqual(0, table.Count); } } [Test] public void CreateSmallWholeDisk() { MemoryStream ms = new MemoryStream(); using (Disk disk = Disk.InitializeDynamic(ms, Ownership.Dispose, 3 * 1024 * 1024)) { GuidPartitionTable table = GuidPartitionTable.Initialize(disk); int idx = table.Create(WellKnownPartitionType.WindowsFat, true); // Make sure the partition fills from first to last usable. Assert.AreEqual(table.FirstUsableSector, table[idx].FirstSector); Assert.AreEqual(table.LastUsableSector, table[idx].LastSector); } } [Test] public void CreateMediumWholeDisk() { MemoryStream ms = new MemoryStream(); using (Disk disk = Disk.InitializeDynamic(ms, Ownership.Dispose, 2 * 1024L * 1024 * 1024)) { GuidPartitionTable table = GuidPartitionTable.Initialize(disk); int idx = table.Create(WellKnownPartitionType.WindowsFat, true); Assert.AreEqual(2, table.Partitions.Count); Assert.AreEqual(GuidPartitionTypes.MicrosoftReserved, table[0].GuidType); Assert.AreEqual(32 * 1024 * 1024, table[0].SectorCount * 512); // Make sure the partition fills from first to last usable, allowing for MicrosoftReserved sector. Assert.AreEqual(table[0].LastSector + 1, table[idx].FirstSector); Assert.AreEqual(table.LastUsableSector, table[idx].LastSector); } } [Test] public void CreateLargeWholeDisk() { MemoryStream ms = new MemoryStream(); using (Disk disk = Disk.InitializeDynamic(ms, Ownership.Dispose, 200 * 1024L * 1024 * 1024)) { GuidPartitionTable table = GuidPartitionTable.Initialize(disk); int idx = table.Create(WellKnownPartitionType.WindowsFat, true); Assert.AreEqual(2, table.Partitions.Count); Assert.AreEqual(GuidPartitionTypes.MicrosoftReserved, table[0].GuidType); Assert.AreEqual(128 * 1024 * 1024, table[0].SectorCount * 512); // Make sure the partition fills from first to last usable, allowing for MicrosoftReserved sector. Assert.AreEqual(table[0].LastSector + 1, table[idx].FirstSector); Assert.AreEqual(table.LastUsableSector, table[idx].LastSector); } } [Test] public void CreateAlignedWholeDisk() { MemoryStream ms = new MemoryStream(); using (Disk disk = Disk.InitializeDynamic(ms, Ownership.Dispose, 200 * 1024L * 1024 * 1024)) { GuidPartitionTable table = GuidPartitionTable.Initialize(disk); int idx = table.CreateAligned(WellKnownPartitionType.WindowsFat, true, 1024 * 1024); Assert.AreEqual(2, table.Partitions.Count); Assert.AreEqual(GuidPartitionTypes.MicrosoftReserved, table[0].GuidType); Assert.AreEqual(128 * 1024 * 1024, table[0].SectorCount * 512); // Make sure the partition is aligned Assert.AreEqual(0, table[idx].FirstSector % 2048); Assert.AreEqual(0, (table[idx].LastSector + 1) % 2048); // Ensure partition fills most of the disk Assert.Greater((table[idx].SectorCount * 512), disk.Capacity * 0.9); } } [Test] public void CreateBySize() { MemoryStream ms = new MemoryStream(); using (Disk disk = Disk.InitializeDynamic(ms, Ownership.Dispose, 3 * 1024 * 1024)) { GuidPartitionTable table = GuidPartitionTable.Initialize(disk); int idx = table.Create(2 * 1024 * 1024, WellKnownPartitionType.WindowsFat, false); // Make sure the partition is within 10% of the size requested. Assert.That((2 * 1024 * 2) * 0.9 < table[idx].SectorCount); Assert.AreEqual(table.FirstUsableSector, table[idx].FirstSector); } } [Test] public void CreateBySizeInGap() { MemoryStream ms = new MemoryStream(); using (Disk disk = Disk.InitializeDynamic(ms, Ownership.Dispose, 300 * 1024 * 1024)) { GuidPartitionTable table = GuidPartitionTable.Initialize(disk); table.Create(10 * 1024 * 1024, WellKnownPartitionType.WindowsFat, false); table.Create((20 * 1024 * 1024) / 512, ((30 * 1024 * 1024) / 512) - 1, GuidPartitionTypes.WindowsBasicData, 0, "Data Partition"); table.Create((60 * 1024 * 1024) / 512, ((70 * 1024 * 1024) / 512) - 1, GuidPartitionTypes.WindowsBasicData, 0, "Data Partition"); int idx = table.Create(20 * 1024 * 1024, WellKnownPartitionType.WindowsFat, false); Assert.AreEqual(((30 * 1024 * 1024) / 512), table[idx].FirstSector); Assert.AreEqual(((50 * 1024 * 1024) / 512) - 1, table[idx].LastSector); } } [Test] public void CreateBySizeInGapAligned() { MemoryStream ms = new MemoryStream(); using (Disk disk = Disk.InitializeDynamic(ms, Ownership.Dispose, 300 * 1024 * 1024)) { GuidPartitionTable table = GuidPartitionTable.Initialize(disk); table.Create(10 * 1024 * 1024, WellKnownPartitionType.WindowsFat, false); // Note: end is unaligned table.Create((20 * 1024 * 1024) / 512, ((30 * 1024 * 1024) / 512) - 5, GuidPartitionTypes.WindowsBasicData, 0, "Data Partition"); table.Create((60 * 1024 * 1024) / 512, ((70 * 1024 * 1024) / 512) - 1, GuidPartitionTypes.WindowsBasicData, 0, "Data Partition"); int idx = table.CreateAligned(20 * 1024 * 1024, WellKnownPartitionType.WindowsFat, false, 64 * 1024); Assert.AreEqual(((30 * 1024 * 1024) / 512), table[idx].FirstSector); Assert.AreEqual(((50 * 1024 * 1024) / 512) - 1, table[idx].LastSector); } } [Test] public void Delete() { MemoryStream ms = new MemoryStream(); using (Disk disk = Disk.InitializeDynamic(ms, Ownership.Dispose, 10 * 1024 * 1024)) { GuidPartitionTable table = GuidPartitionTable.Initialize(disk); Assert.AreEqual(0, table.Create(1 * 1024 * 1024, WellKnownPartitionType.WindowsFat, false)); Assert.AreEqual(1, table.Create(2 * 1024 * 1024, WellKnownPartitionType.WindowsFat, false)); Assert.AreEqual(2, table.Create(3 * 1024 * 1024, WellKnownPartitionType.WindowsFat, false)); long[] sectorCount = new long[] { table[0].SectorCount, table[1].SectorCount, table[2].SectorCount }; table.Delete(1); Assert.AreEqual(2, table.Count); Assert.AreEqual(sectorCount[2], table[1].SectorCount); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using Xunit; namespace System.Linq.Expressions.Tests { public static class InvocationTests { public delegate void X(X a); [Theory] [ClassData(typeof(CompilationTypes))] public static void SelfApplication(bool useInterpreter) { // Expression<X> f = x => {}; Expression<X> f = Expression.Lambda<X>(Expression.Empty(), Expression.Parameter(typeof(X))); LambdaExpression a = Expression.Lambda(Expression.Invoke(f, f)); a.Compile(useInterpreter).DynamicInvoke(); ParameterExpression it = Expression.Parameter(f.Type); LambdaExpression b = Expression.Lambda(Expression.Invoke(Expression.Lambda(Expression.Invoke(it, it), it), f)); b.Compile(useInterpreter).DynamicInvoke(); } [Fact] public static void NoWriteBackToInstance() { new NoThread(false).DoTest(); new NoThread(true).DoTest(); // This case fails } public class NoThread { private readonly bool _preferInterpretation; public NoThread(bool preferInterpretation) { _preferInterpretation = preferInterpretation; } public Func<NoThread, int> DoItA = (nt) => { nt.DoItA = (nt0) => 1; return 0; }; public Action Compile() { ConstantExpression ind0 = Expression.Constant(this); MemberExpression fld = Expression.PropertyOrField(ind0, "DoItA"); BlockExpression block = Expression.Block(typeof(void), Expression.Invoke(fld, ind0)); return Expression.Lambda<Action>(block).Compile(_preferInterpretation); } public void DoTest() { Action act = Compile(); act(); Assert.Equal(1, DoItA(this)); } } private class FuncHolder { public Func<int> Function; public FuncHolder() { Function = () => { Function = () => 1; return 0; }; } } [Theory] [ClassData(typeof(CompilationTypes))] public static void InvocationDoesNotChangeFunctionInvoked(bool useInterpreter) { FuncHolder holder = new FuncHolder(); MemberExpression fld = Expression.Field(Expression.Constant(holder), "Function"); InvocationExpression inv = Expression.Invoke(fld); Func<int> act = (Func<int>)Expression.Lambda(inv).Compile(useInterpreter); act(); Assert.Equal(1, holder.Function()); } [Fact] public static void ToStringTest() { InvocationExpression e1 = Expression.Invoke(Expression.Parameter(typeof(Action), "f")); Assert.Equal("Invoke(f)", e1.ToString()); InvocationExpression e2 = Expression.Invoke(Expression.Parameter(typeof(Action<int>), "f"), Expression.Parameter(typeof(int), "x")); Assert.Equal("Invoke(f, x)", e2.ToString()); } [Fact] public static void GetArguments() { VerifyGetArguments(Expression.Invoke(Expression.Default(typeof(Action)))); VerifyGetArguments(Expression.Invoke(Expression.Default(typeof(Action<int>)), Expression.Constant(0))); VerifyGetArguments( Expression.Invoke( Expression.Default(typeof(Action<int, int>)), Enumerable.Range(0, 2).Select(i => Expression.Constant(i)))); VerifyGetArguments( Expression.Invoke( Expression.Default(typeof(Action<int, int, int>)), Enumerable.Range(0, 3).Select(i => Expression.Constant(i)))); VerifyGetArguments( Expression.Invoke( Expression.Default(typeof(Action<int, int, int, int>)), Enumerable.Range(0, 4).Select(i => Expression.Constant(i)))); VerifyGetArguments( Expression.Invoke( Expression.Default(typeof(Action<int, int, int, int, int>)), Enumerable.Range(0, 5).Select(i => Expression.Constant(i)))); VerifyGetArguments( Expression.Invoke( Expression.Default(typeof(Action<int, int, int, int, int, int>)), Enumerable.Range(0, 6).Select(i => Expression.Constant(i)))); VerifyGetArguments( Expression.Invoke( Expression.Default(typeof(Action<int, int, int, int, int, int, int>)), Enumerable.Range(0, 7).Select(i => Expression.Constant(i)))); } private static void VerifyGetArguments(InvocationExpression invoke) { var args = invoke.Arguments; Assert.Equal(args.Count, invoke.ArgumentCount); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => invoke.GetArgument(-1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => invoke.GetArgument(args.Count)); for (int i = 0; i != args.Count; ++i) { Assert.Same(args[i], invoke.GetArgument(i)); Assert.Equal(i, ((ConstantExpression)invoke.GetArgument(i)).Value); } } [Fact] public static void ArgumentCountMismatchLambda() { Expression<Func<int, int, int>> adder = (x, y) => x + y; Assert.Throws<InvalidOperationException>(() => Expression.Invoke(adder, Expression.Constant(1))); Assert.Throws<InvalidOperationException>(() => Expression.Invoke(adder, Expression.Constant(1), Expression.Constant(1), Expression.Constant(1))); } [Fact] public static void ArgumentTypeMismatchLambda() { Expression<Func<int, int, int>> adder = (x, y) => x + y; AssertExtensions.Throws<ArgumentException>("arg1", () => Expression.Invoke(adder, Expression.Constant(1), Expression.Constant(1L))); AssertExtensions.Throws<ArgumentException>("arg0", () => Expression.Invoke(adder, Expression.Constant(1L), Expression.Constant(1))); } [Fact] public static void ArgumentCountMismatchDelegate() { Func<int, int, int> adder = (x, y) => x + y; Assert.Throws<InvalidOperationException>(() => Expression.Invoke(Expression.Constant(adder), Expression.Constant(1))); Assert.Throws<InvalidOperationException>(() => Expression.Invoke(Expression.Constant(adder), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1))); } [Fact] public static void ArgumentTypeMismatchDelegate() { Func<int, int, int> adder = (x, y) => x + y; AssertExtensions.Throws<ArgumentException>("arg1", () => Expression.Invoke(Expression.Constant(adder), Expression.Constant(1), Expression.Constant(1L))); AssertExtensions.Throws<ArgumentException>("arg0", () => Expression.Invoke(Expression.Constant(adder), Expression.Constant(1L), Expression.Constant(1))); } [Fact] public static void UpdateSameReturnsSame() { Expression<Func<int, int, int>> adder = (x, y) => x + y; Expression lhs = Expression.Constant(1); Expression rhs = Expression.Constant(2); var invoke = Expression.Invoke(adder, lhs, rhs); Assert.Same(invoke, invoke.Update(adder, new[] {lhs, rhs})); } [Fact] public static void UpdateDifferentLambdaReturnsDifferent() { Expression<Func<int, int, int>> adder = (x, y) => x + y; Expression lhs = Expression.Constant(1); Expression rhs = Expression.Constant(2); var invoke = Expression.Invoke(adder, lhs, rhs); adder = (x, y) => y + x; Assert.NotSame(invoke, invoke.Update(adder, new[] { lhs, rhs })); } [Fact] public static void UpdateDifferentArgReturnsDifferent() { Expression<Func<int, int, int>> adder = (x, y) => x + y; Expression lhs = Expression.Constant(1); Expression rhs = Expression.Constant(2); var invoke = Expression.Invoke(adder, lhs, rhs); Assert.NotSame(invoke, invoke.Update(adder, new[] { lhs, Expression.Constant(2) })); } private static IEnumerable<object[]> InvocationExpressions() { for (int i = 0; i <= 6; ++i) { Type[] genArgs = Enumerable.Repeat(typeof(int), i + 1).ToArray(); Type delegateType = Expression.GetFuncType(genArgs); ParameterExpression instance = Expression.Parameter(delegateType); yield return new object[] {Expression.Invoke(instance, Enumerable.Repeat(Expression.Constant(0), i))}; } } private class ParameterChangingVisitor : ExpressionVisitor { protected override Expression VisitParameter(ParameterExpression node) => Expression.Parameter(node.Type); } private class ParameterAndConstantChangingVisitor : ParameterChangingVisitor { protected override Expression VisitConstant(ConstantExpression node) => Expression.Constant(node.Value, node.Type); } [Theory, MemberData(nameof(InvocationExpressions))] public static void LambdaChangeVisit(InvocationExpression invoke) { Assert.NotSame(invoke, new ParameterChangingVisitor().Visit(invoke)); } [Theory, MemberData(nameof(InvocationExpressions))] public static void LambdaAndArgChangeVisit(InvocationExpression invoke) { Assert.NotSame(invoke, new ParameterAndConstantChangingVisitor().Visit(invoke)); } #if FEATURE_COMPILE // When we don't have FEATURE_COMPILE we don't have the Reflection.Emit used in the tests. [Theory, ClassData(typeof(CompilationTypes))] public static void InvokePrivateDelegate(bool useInterpreter) { AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run); ModuleBuilder module = assembly.DefineDynamicModule("Name"); TypeBuilder builder = module.DefineType("Type", TypeAttributes.Class | TypeAttributes.NotPublic | TypeAttributes.Sealed | TypeAttributes.AnsiClass | TypeAttributes.AutoClass, typeof(MulticastDelegate)); builder.DefineConstructor(MethodAttributes.RTSpecialName | MethodAttributes.HideBySig | MethodAttributes.Public, CallingConventions.Standard, new[] { typeof(object), typeof(IntPtr) }).SetImplementationFlags(MethodImplAttributes.Runtime | MethodImplAttributes.Managed); builder.DefineMethod("Invoke", MethodAttributes.Private | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual, typeof(int), Type.EmptyTypes).SetImplementationFlags(MethodImplAttributes.Runtime | MethodImplAttributes.Managed); Type delType = builder.CreateTypeInfo(); LambdaExpression lambda = Expression.Lambda(delType, Expression.Constant(42)); Delegate del = lambda.Compile(useInterpreter); var invoke = Expression.Invoke(Expression.Constant(del)); var invLambda = Expression.Lambda<Func<int>>(invoke); var invFunc = invLambda.Compile(useInterpreter); Assert.Equal(42, invFunc()); } [Theory, ClassData(typeof(CompilationTypes))] public static void InvokePrivateDelegateTypeLambda(bool useInterpreter) { AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run); ModuleBuilder module = assembly.DefineDynamicModule("Name"); TypeBuilder builder = module.DefineType("Type", TypeAttributes.Class | TypeAttributes.NotPublic | TypeAttributes.Sealed | TypeAttributes.AnsiClass | TypeAttributes.AutoClass, typeof(MulticastDelegate)); builder.DefineConstructor(MethodAttributes.RTSpecialName | MethodAttributes.HideBySig | MethodAttributes.Public, CallingConventions.Standard, new[] { typeof(object), typeof(IntPtr) }).SetImplementationFlags(MethodImplAttributes.Runtime | MethodImplAttributes.Managed); builder.DefineMethod("Invoke", MethodAttributes.Private | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual, typeof(int), Type.EmptyTypes).SetImplementationFlags(MethodImplAttributes.Runtime | MethodImplAttributes.Managed); Type delType = builder.CreateTypeInfo(); LambdaExpression lambda = Expression.Lambda(delType, Expression.Constant(42)); var invoke = Expression.Invoke(lambda); var invLambda = Expression.Lambda<Func<int>>(invoke); var invFunc = invLambda.Compile(useInterpreter); Assert.Equal(42, invFunc()); } #endif } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using JetBrains.Annotations; using JetBrains.Application.Settings; using JetBrains.Application.UI.Options; using JetBrains.DataFlow; using JetBrains.Lifetimes; using JetBrains.ReSharper.Features.Intellisense.Options; using JetBrains.UI.Controls; using JetBrains.UI.Extensions; using JetBrains.UI.Options.OptionsDialog2.SimpleOptions; using JetBrains.UI.Wpf.Controls.NumericUpDown.Impl; using JetBrains.UI.Wpf.Converters; namespace GammaJul.ReSharper.EnhancedTooltip.Settings { [OptionsPage(Pid, "Enhanced Tooltip", typeof(ThemedIcons.Logo16), ParentId = IntelliSensePage.PID, Sequence = 100)] public partial class EnhancedTooltipOptionsPage : IOptionsPage, ISearchablePage { public const string Pid = "EnhancedTooltip.OptionsPage"; private readonly Lifetime _lifetime; private readonly OptionsSettingsSmartContext _context; private readonly List<OptionsPageKeyword> _keywords = new(); public event PropertyChangedEventHandler PropertyChanged { add { } remove { } } public string Id => Pid; public bool OnOk() => true; public IProperty<OptionsFilterResult> SearchFilter { get; } = new Property<OptionsFilterResult>(String.Format(CultureInfo.InvariantCulture, "Filter for {0}", typeof(EnhancedTooltipOptionsPage))); public OptionsPageKeywords GetKeywords() => new OptionsPageKeywords(_keywords); public void HighLightKeyword(OptionsFilterResult text) => SearchFilter.Value = text; public IEnumerable<string> GetTagKeywordsForPage() => new[] { "Tooltip" }; private static List<EnumValue> CreateEnumItemsSource(Type enumType) { var enumDescriptionConverter = new EnumDescriptionConverter(); return Enum.GetValues(enumType) .Cast<Enum>() .Select(e => new EnumValue(e, enumDescriptionConverter.Convert(e, typeof(string), null, CultureInfo.CurrentUICulture) as string ?? e.ToString())) .ToList(); } private void SetCheckBoxBinding<TSettings>( Expression<Func<TSettings, bool>> settingAccessor, CheckBoxDisabledNoCheck2 checkBox, CheckBoxDisabledNoCheck2? parentCheckBox, bool addColonToDescription = false) { SettingsScalarEntry entry = _context.Schema.GetScalarEntry(settingAccessor); string description = entry.Description; if (addColonToDescription) description += ":"; ConfigureCheckBox(checkBox, description, entry); parentCheckBox?.IsAppearingChecked.FlowInto(_lifetime, checkBox, IsEnabledProperty); } private void SetAttributesArgumentsCheckBoxBinding<TSettings>( Expression<Func<TSettings, bool>> settingAccessor, CheckBoxDisabledNoCheck2 checkBox, ComboBox parentComboBox) { SettingsScalarEntry entry = _context.Schema.GetScalarEntry(settingAccessor); ConfigureCheckBox(checkBox, "with arguments", entry); IProperty<object> selectedValueProperty = DependencyPropertyWrapper.Create<object>(_lifetime, parentComboBox, Selector.SelectedValueProperty, true); selectedValueProperty.FlowInto(_lifetime, checkBox, IsEnabledProperty, value => HasAttributesArguments((AttributesDisplayKind) value)); } private void ConfigureCheckBox(CheckBoxDisabledNoCheck2 checkBox, string content, SettingsScalarEntry entry) { checkBox.Content ??= content; _keywords.Add(new OptionsPageKeyword(content)); _context.SetBinding<bool>(_lifetime, entry, checkBox, CheckBoxDisabledNoCheck2.IsCheckedLogicallyDependencyProperty); SearchablePageBehavior.SetSearchFilter(checkBox, true); } [Pure] private static bool HasAttributesArguments(AttributesDisplayKind attributesDisplayKind) { switch (attributesDisplayKind) { case AttributesDisplayKind.AllAnnotations: case AttributesDisplayKind.Always: return true; default: return false; } } private void SetComboBoxBinding<TSettings, TEnum>( Expression<Func<TSettings, TEnum>> settingAccessor, ComboBox comboBox, CheckBoxDisabledNoCheck2? parentCheckBox) { comboBox.ItemsSource = CreateEnumItemsSource(typeof(TEnum)); comboBox.DisplayMemberPath = nameof(EnumValue.Description); comboBox.SelectedValuePath = nameof(EnumValue.Value); SettingsScalarEntry entry = _context.Schema.GetScalarEntry(settingAccessor); _context.SetBinding<object>(_lifetime, entry, comboBox, Selector.SelectedValueProperty); SetAssociatedLabel(comboBox, entry.Description); parentCheckBox?.IsAppearingChecked.FlowInto(_lifetime, comboBox, IsEnabledProperty); } private void SetNumericUpDownBinding<TSettings>( Expression<Func<TSettings, int>> settingAccessor, NumericUpDown numericUpDown, CheckBoxDisabledNoCheck2? parentCheckBox) { SettingsScalarEntry entry = _context.Schema.GetScalarEntry(settingAccessor); _context.SetBinding<int>(_lifetime, entry, numericUpDown, NumericUpDown.ValueProperty); SetAssociatedLabel(numericUpDown, entry.Description); parentCheckBox?.IsAppearingChecked.FlowInto(_lifetime, numericUpDown, IsEnabledProperty); } private void SetAssociatedLabel(FrameworkElement element, string description) { if (element.Parent?.FindDescendant<Label>() is not { } label) return; switch (label.Content) { case null: label.Content = description + ":"; _keywords.Add(new OptionsPageKeyword(description)); break; case string existingContentString: _keywords.Add(new OptionsPageKeyword(existingContentString)); break; } SearchablePageBehavior.SetSearchFilter(label, true); } private void SetIdentifierTooltipSettingsBindings() { CheckBoxDisabledNoCheck2 rootCheckBox = IdentifierTooltipEnabledCheckBox; SetCheckBoxBinding((IdentifierTooltipSettings s) => s.Enabled, rootCheckBox, null); SetCheckBoxBinding((IdentifierTooltipSettings s) => s.ShowIcon, IdentifierTooltipShowIconCheckBox, rootCheckBox); SetCheckBoxBinding((IdentifierTooltipSettings s) => s.ShowAccessRights, IdentifierTooltipShowAccessRightsCheckBox, rootCheckBox); SetCheckBoxBinding((IdentifierTooltipSettings s) => s.ShowAccessors, IdentifierTooltipShowAccessorsCheckBox, rootCheckBox); SetCheckBoxBinding((IdentifierTooltipSettings s) => s.ShowKind, IdentifierTooltipShowKindCheckBox, rootCheckBox); SetCheckBoxBinding((IdentifierTooltipSettings s) => s.UseExtensionMethodKind, IdentifierTooltipUseExtensionMethodKindCheckBox, IdentifierTooltipShowKindCheckBox); SetCheckBoxBinding((IdentifierTooltipSettings s) => s.UseAttributeClassKind, IdentifierTooltipUseAttributeClassKindCheckBox, IdentifierTooltipShowKindCheckBox); SetCheckBoxBinding((IdentifierTooltipSettings s) => s.UseMethodModifiersInKind, IdentifierTooltipUseMethodModifiersInKindCheckBox, IdentifierTooltipShowKindCheckBox); SetCheckBoxBinding((IdentifierTooltipSettings s) => s.UseClassModifiersInKind, IdentifierTooltipUseClassModifiersInKindCheckBox, IdentifierTooltipShowKindCheckBox); SetCheckBoxBinding((IdentifierTooltipSettings s) => s.UseStructModifiersInKind, IdentifierTooltipUseStructModifiersInKindCheckBox, IdentifierTooltipShowKindCheckBox); SetCheckBoxBinding((IdentifierTooltipSettings s) => s.ShowDocumentation, IdentifierTooltipShowDocumentationCheckBox, rootCheckBox); SetCheckBoxBinding((IdentifierTooltipSettings s) => s.ShowObsolete, IdentifierTooltipShowObsoleteCheckBox, IdentifierTooltipShowDocumentationCheckBox); SetCheckBoxBinding((IdentifierTooltipSettings s) => s.ShowReturn, IdentifierTooltipShowReturnCheckBox, IdentifierTooltipShowDocumentationCheckBox); SetCheckBoxBinding((IdentifierTooltipSettings s) => s.ShowValue, IdentifierTooltipShowValueCheckBox, IdentifierTooltipShowDocumentationCheckBox); SetCheckBoxBinding((IdentifierTooltipSettings s) => s.ShowRemarks, IdentifierTooltipShowRemarksCheckBox, IdentifierTooltipShowDocumentationCheckBox); SetCheckBoxBinding((IdentifierTooltipSettings s) => s.ShowExceptions, IdentifierTooltipShowExceptionsCheckBox, IdentifierTooltipShowDocumentationCheckBox); SetCheckBoxBinding((IdentifierTooltipSettings s) => s.ShowParams, IdentifierTooltipShowParametersCheckBox, IdentifierTooltipShowDocumentationCheckBox); SetCheckBoxBinding((IdentifierTooltipSettings s) => s.ShowOverloadCount, IdentifierTooltipShowOverloadCountCheckBox, rootCheckBox); SetCheckBoxBinding((IdentifierTooltipSettings s) => s.ShowArgumentsRole, IdentifierTooltipShowArgumentsRoleCheckBox, rootCheckBox); SetComboBoxBinding((IdentifierTooltipSettings s) => s.BaseTypeDisplayKind, IdentifierTooltipBaseTypeDisplayKindComboBox, rootCheckBox); SetComboBoxBinding((IdentifierTooltipSettings s) => s.ImplementedInterfacesDisplayKind, IdentifierTooltipImplementedInterfacesDisplayKindComboBox, rootCheckBox); SetCheckBoxBinding((IdentifierTooltipSettings s) => s.ShowAttributesUsage, IdentifierTooltipShowShowAttributesUsageCheckBox, rootCheckBox); SetCheckBoxBinding((IdentifierTooltipSettings s) => s.UseTypeKeywords, IdentifierTooltipUseTypeKeywordsCheckBox, rootCheckBox); SetCheckBoxBinding((IdentifierTooltipSettings s) => s.UseShortNullableForm, IdentifierTooltipUseShortNullableFormCheckBox, rootCheckBox); SetComboBoxBinding((IdentifierTooltipSettings s) => s.ShowIdentifierAttributes, IdentifierTooltipShowIdentifierAttributesComboBox, rootCheckBox); SetAttributesArgumentsCheckBoxBinding( (IdentifierTooltipSettings s) => s.ShowIdentifierAttributesArguments, IdentifierTooltipShowIdentifierAttributesArgumentsCheckBox, IdentifierTooltipShowIdentifierAttributesComboBox); SetComboBoxBinding((IdentifierTooltipSettings s) => s.ShowParametersAttributes, IdentifierTooltipShowParametersAttributesComboBox, rootCheckBox); SetAttributesArgumentsCheckBoxBinding( (IdentifierTooltipSettings s) => s.ShowParametersAttributesArguments, IdentifierTooltipShowParametersAttributesArgumentsCheckBox, IdentifierTooltipShowParametersAttributesComboBox); SetComboBoxBinding((IdentifierTooltipSettings s) => s.ConstructorReferenceDisplay, IdentifierTooltipConstructorReferenceDisplayComboBox, rootCheckBox); SetComboBoxBinding((IdentifierTooltipSettings s) => s.AttributeConstructorReferenceDisplay, IdentifierTooltipAttributeConstructorReferenceDisplayComboBox, rootCheckBox); SetComboBoxBinding((IdentifierTooltipSettings s) => s.SolutionCodeNamespaceDisplayKind, IdentifierTooltipSolutionCodeNamespaceDisplayKindComboBox, rootCheckBox); SetComboBoxBinding((IdentifierTooltipSettings s) => s.ExternalCodeNamespaceDisplayKind, IdentifierTooltipExternalCodeNamespaceDisplayKindComboBox, rootCheckBox); SetComboBoxBinding((IdentifierTooltipSettings s) => s.ParametersFormattingMode, IdentifierTooltipParametersFormattingModeComboBox, rootCheckBox); SetComboBoxBinding((IdentifierTooltipSettings s) => s.AttributesFormattingMode, IdentifierTooltipAttributesFormattingModeComboBox, rootCheckBox); } private void SetIssueTooltipSettingsBindings() { SetCheckBoxBinding((IssueTooltipSettings s) => s.ShowIcon, IssueTooltipShowIconCheckBox, null); SetCheckBoxBinding((IssueTooltipSettings s) => s.ColorizeElementsInErrors, IssueTooltipColorizeElementsInErrors, null); } private void SetParameterInfoSettingsBindings() { CheckBoxDisabledNoCheck2 rootCheckBox = ParameterInfoEnabledCheckBox; SetCheckBoxBinding((ParameterInfoSettings s) => s.Enabled, rootCheckBox, null); SetCheckBoxBinding((ParameterInfoSettings s) => s.ShowEmptyParametersText, ParameterInfoShowEmptyParametersTextCheckBox, rootCheckBox); SetCheckBoxBinding((ParameterInfoSettings s) => s.UseTypeKeywords, ParameterInfoUseTypeKeywordsCheckBox, rootCheckBox); } private void SetDisplaySettingsBindings() { CheckBoxDisabledNoCheck2 rootCheckBox = DisplayLimitTooltipWidth; SetCheckBoxBinding((DisplaySettings s) => s.LimitTooltipWidth, rootCheckBox, null, addColonToDescription: true); SetNumericUpDownBinding((DisplaySettings s) => s.ScreenWidthLimitPercent, DisplayScreenWidthLimitPercent, rootCheckBox); SetComboBoxBinding((DisplaySettings s) => s.TextFormattingMode, DisplayTextFormattingMode, null); SetComboBoxBinding((DisplaySettings s) => s.TooltipColorSource, DisplayTooltipColorSource, null); } public EnhancedTooltipOptionsPage(Lifetime lifetime, OptionsSettingsSmartContext context) { _lifetime = lifetime; _context = context; DataContext = this; InitializeComponent(); SetIdentifierTooltipSettingsBindings(); SetIssueTooltipSettingsBindings(); SetParameterInfoSettingsBindings(); SetDisplaySettingsBindings(); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.Serialization; namespace DDay.iCal { /// <summary> /// A class that represents an RFC 5545 VEVENT component. /// </summary> /// <note> /// TODO: Add support for the following properties: /// <list type="bullet"> /// <item>Add support for the Organizer and Attendee properties</item> /// <item>Add support for the Class property</item> /// <item>Add support for the Geo property</item> /// <item>Add support for the Priority property</item> /// <item>Add support for the Related property</item> /// <item>Create a TextCollection DataType for 'text' items separated by commas</item> /// </list> /// </note> #if !SILVERLIGHT [Serializable] #endif public class Event : RecurringComponent, IEvent { #region Public Properties /// <summary> /// The start date/time of the event. /// <note> /// If the duration has not been set, but /// the start/end time of the event is available, /// the duration is automatically determined. /// Likewise, if the end date/time has not been /// set, but a start and duration are available, /// the end date/time will be extrapolated. /// </note> /// </summary> public override IDateTime DTStart { get { return base.DTStart; } set { base.DTStart = value; ExtrapolateTimes(); } } /// <summary> /// The end date/time of the event. /// <note> /// If the duration has not been set, but /// the start/end time of the event is available, /// the duration is automatically determined. /// Likewise, if an end time and duration are available, /// but a start time has not been set, the start time /// will be extrapolated. /// </note> /// </summary> virtual public IDateTime DTEnd { get { return Properties.Get<IDateTime>("DTEND"); } set { if (!object.Equals(DTEnd, value)) { Properties.Set("DTEND", value); ExtrapolateTimes(); } } } /// <summary> /// The duration of the event. /// <note> /// If a start time and duration is available, /// the end time is automatically determined. /// Likewise, if the end time and duration is /// available, but a start time is not determined, /// the start time will be extrapolated from /// available information. /// </note> /// </summary> // NOTE: Duration is not supported by all systems, // (i.e. iPhone) and cannot co-exist with DTEnd. // RFC 5545 states: // // ; either 'dtend' or 'duration' may appear in // ; a 'eventprop', but 'dtend' and 'duration' // ; MUST NOT occur in the same 'eventprop' // // Therefore, Duration is not serialized, as DTEnd // should always be extrapolated from the duration. virtual public TimeSpan Duration { get { return Properties.Get<TimeSpan>("DURATION"); } set { if (!object.Equals(Duration, value)) { Properties.Set("DURATION", value); ExtrapolateTimes(); } } } /// <summary> /// An alias to the DTEnd field (i.e. end date/time). /// </summary> virtual public IDateTime End { get { return DTEnd; } set { DTEnd = value; } } /// <summary> /// Returns true if the event is an all-day event. /// </summary> virtual public bool IsAllDay { get { return !Start.HasTime; } set { // Set whether or not the start date/time // has a time value. if (Start != null) Start.HasTime = !value; if (End != null) End.HasTime = !value; if (value && Start != null && End != null && object.Equals(Start.Date, End.Date)) { Duration = default(TimeSpan); End = Start.AddDays(1); } } } /// <summary> /// The geographic location (lat/long) of the event. /// </summary> public IGeographicLocation GeographicLocation { get { return Properties.Get<IGeographicLocation>("GEO"); } set { Properties.Set("GEO", value); } } /// <summary> /// The location of the event. /// </summary> public string Location { get { return Properties.Get<string>("LOCATION"); } set { Properties.Set("LOCATION", value); } } /// <summary> /// Resources that will be used during the event. /// <example>Conference room #2</example> /// <example>Projector</example> /// </summary> public IList<string> Resources { get { return Properties.GetList<string>("RESOURCES"); } set { Properties.SetList("RESOURCES", value); } } /// <summary> /// The status of the event. /// </summary> public EventStatus Status { get { return Properties.Get<EventStatus>("STATUS"); } set { Properties.Set("STATUS", value); } } /// <summary> /// The transparency of the event. In other words, /// whether or not the period of time this event /// occupies can contain other events (transparent), /// or if the time cannot be scheduled for anything /// else (opaque). /// </summary> public TransparencyType Transparency { get { return Properties.Get<TransparencyType>("TRANSP"); } set { Properties.Set("TRANSP", value); } } #endregion #region Private Fields EventEvaluator m_Evaluator; #endregion #region Constructors /// <summary> /// Constructs an Event object, with an <see cref="iCalObject"/> /// (usually an iCalendar object) as its parent. /// </summary> /// <param name="parent">An <see cref="iCalObject"/>, usually an iCalendar object.</param> public Event() : base() { Initialize(); } private void Initialize() { this.Name = Components.EVENT; m_Evaluator = new EventEvaluator(this); SetService(m_Evaluator); } #endregion #region Public Methods /// <summary> /// Use this method to determine if an event occurs on a given date. /// <note type="caution"> /// This event should be called only after the <see cref="Evaluate"/> /// method has calculated the dates for which this event occurs. /// </note> /// </summary> /// <param name="DateTime">The date to test.</param> /// <returns>True if the event occurs on the <paramref name="DateTime"/> provided, False otherwise.</returns> virtual public bool OccursOn(IDateTime DateTime) { foreach (IPeriod p in m_Evaluator.Periods) // NOTE: removed UTC from date checks, since a date is a date. if (p.StartTime.Date == DateTime.Date || // It's the start date OR (p.StartTime.Date <= DateTime.Date && // It's after the start date AND (p.EndTime.HasTime && p.EndTime.Date >= DateTime.Date || // an end time was specified, and it's after the test date (!p.EndTime.HasTime && p.EndTime.Date > DateTime.Date)))) // an end time was not specified, and it's before the end date // NOTE: fixed bug as follows: // DTSTART;VALUE=DATE:20060704 // DTEND;VALUE=DATE:20060705 // Event.OccursOn(new iCalDateTime(2006, 7, 5)); // Evals to true; should be false return true; return false; } /// <summary> /// Use this method to determine if an event begins at a given date and time. /// </summary> /// <param name="DateTime">The date and time to test.</param> /// <returns>True if the event begins at the given date and time</returns> virtual public bool OccursAt(IDateTime DateTime) { foreach (IPeriod p in m_Evaluator.Periods) if (p.StartTime.Equals(DateTime)) return true; return false; } /// <summary> /// Determines whether or not the <see cref="Event"/> is actively displayed /// as an upcoming or occurred event. /// </summary> /// <returns>True if the event has not been cancelled, False otherwise.</returns> virtual public bool IsActive() { return (Status != EventStatus.Cancelled); } #endregion #region Overrides protected override bool EvaluationIncludesReferenceDate { get { return true; } } protected override void OnDeserializing(StreamingContext context) { base.OnDeserializing(context); Initialize(); } protected override void OnDeserialized(StreamingContext context) { base.OnDeserialized(context); ExtrapolateTimes(); } #endregion #region Private Methods private void ExtrapolateTimes() { if (DTEnd == null && DTStart != null && Duration != default(TimeSpan)) DTEnd = DTStart.Add(Duration); else if (Duration == default(TimeSpan) && DTStart != null && DTEnd != null) Duration = DTEnd.Subtract(DTStart); else if (DTStart == null && Duration != default(TimeSpan) && DTEnd != null) DTStart = DTEnd.Subtract(Duration); } #endregion } }
// <copyright file="CachedImageRenderer.cs" company="Anura Code"> // All rights reserved. // </copyright> // <author>Alberto Puyana</author> using Android.Runtime; using Android.Widget; using FFImageLoading.Views; using System; using System.ComponentModel; using System.IO; using System.Threading; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; namespace Anuracode.Forms.Controls.Renderers { /// <summary> /// CachedImage Implementation /// </summary> [Preserve(AllMembers = true)] public class ExtendedImageRenderer : ViewRenderer<ExtendedImage, ImageViewAsync> { /// <summary> /// Is disposed. /// </summary> private bool isDisposed; /// <summary> /// Last image source. /// </summary> private Xamarin.Forms.ImageSource lastImageSource = null; /// <summary> /// Default constructor. /// </summary> public ExtendedImageRenderer() : base(Android.App.Application.Context) { AutoPackage = false; } /// <summary> /// Allow down sample. /// </summary> public static bool AllowDownSample { get; set; } /// <summary> /// Token created when the view model is navigated and cancel when is navigated off. /// </summary> protected CancellationTokenSource UpdateSourceCancellationToken { get; set; } /// <summary> /// Get the number of cores. /// </summary> /// <returns>Number of cores of the device.</returns> public static int GetNumberOfCores() { if (((int)Android.OS.Build.VERSION.SdkInt) >= 17) { return Java.Lang.Runtime.GetRuntime().AvailableProcessors(); } else { return 1; } } /// <summary> /// Used for registration with dependency service /// </summary> public static void Init() { } /// <summary> /// Dispose control. /// </summary> /// <param name="disposing"></param> protected override void Dispose(bool disposing) { if (!isDisposed) { if (UpdateSourceCancellationToken != null) { UpdateSourceCancellationToken.Cancel(); UpdateSourceCancellationToken = null; } isDisposed = true; base.Dispose(disposing); } } /// <summary> /// On element changed. /// </summary> /// <param name="e">Arguments of the event.</param> protected override async void OnElementChanged(ElementChangedEventArgs<ExtendedImage> e) { try { base.OnElementChanged(e); if (e.OldElement != null || this.Element == null) return; if (e.OldElement == null) { ImageViewAsync nativeControl = new ImageViewAsync(Context); SetNativeControl(nativeControl); } await UpdateBitmap(e.OldElement); UpdateAspect(); } catch (Exception ex) { Anuracode.Forms.Controls.AC.TraceError("ManagedImageRenderer problem: {0}", ex); } } /// <summary> /// Property changed. /// </summary> /// <param name="sender">Sender of the event.</param> /// <param name="e">Arguments of the event.</param> protected override async void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { try { base.OnElementPropertyChanged(sender, e); if ((this.Element == null) || (this.Control == null)) { return; } if (e.PropertyName == ExtendedImage.SourceProperty.PropertyName) { await UpdateBitmap(null); } if (e.PropertyName == ExtendedImage.AspectProperty.PropertyName) { UpdateAspect(); } } catch (Exception ex) { Anuracode.Forms.Controls.AC.TraceError("ManagedImageRenderer problem: {0}", ex); } } /// <summary> /// Image loading. /// </summary> /// <param name="element">Element to use.</param> private void ImageLoadingFinished(ExtendedImage element) { if ((element != null) && !isDisposed && (Control != null)) { AC.ThreadManager.ScheduleManagedFull( async () => { await Task.FromResult(0); if ((element != null) && !isDisposed && (Control != null)) { ((IVisualElementController)element).NativeSizeChanged(); } }); } } /// <summary> /// Update aspect. /// </summary> private void UpdateAspect() { AC.ThreadManager.ScheduleManagedFull( async () => { await Task.FromResult(0); if ((Element != null) && (Control != null) && !isDisposed) { if (Element.Aspect == Aspect.AspectFill) { Control.SetScaleType(ImageView.ScaleType.CenterCrop); } else if (Element.Aspect == Aspect.Fill) { Control.SetScaleType(ImageView.ScaleType.FitXy); } else { Control.SetScaleType(ImageView.ScaleType.FitCenter); } } }); } /// <summary> /// Update bitmap. /// </summary> /// <param name="previous">Previous control.</param> private async Task UpdateBitmap(ExtendedImage previous = null) { if ((Element != null) && (Control != null) && !isDisposed) { Xamarin.Forms.ImageSource source = Element.Source; if (previous != null) { Xamarin.Forms.ImageSource source2 = previous.Source; if (object.Equals(source2, source)) { return; } if (source2 is FileImageSource && source is FileImageSource && ((FileImageSource)source2).File == ((FileImageSource)source).File) { return; } } try { if (UpdateSourceCancellationToken != null) { UpdateSourceCancellationToken.Cancel(); UpdateSourceCancellationToken = null; } if (UpdateSourceCancellationToken == null) { UpdateSourceCancellationToken = new CancellationTokenSource(); } if (previous == null || !object.Equals(previous.Source, Element.Source)) { ImageViewAsync formsImageView = Control as ImageViewAsync; if (formsImageView == null) { return; } var completed = await formsImageView.UpdateImageSource( source, lastImageSource: lastImageSource, allowDownSample: AllowDownSample, targetWidth: Element.WidthRequest, targetHeight: Element.HeightRequest, cancellationToken: UpdateSourceCancellationToken.Token); if (completed) { lastImageSource = source; } ImageLoadingFinished(Element); } } catch (TaskCanceledException taskCanceledException) { } catch (OperationCanceledException operationCanceledException) { } catch (IOException oException) { } catch (Exception ex) { AC.TraceError("Android Extended renderer", ex); } } } } }
//--------------------------------------------------------------------------- // // <copyright file="WindowsListViewGroup.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // // Description: Support for Windows ListView Group // // History: // alexsn - Created (in DotNet) // alexsn 2003/08/12 Updated for WCP // //--------------------------------------------------------------------------- using System; using System.Collections; using System.Globalization; using System.Runtime.InteropServices; using System.ComponentModel; using System.Windows.Automation; using System.Windows.Automation.Provider; using System.Windows; using MS.Win32; namespace MS.Internal.AutomationProxies { class WindowsListViewGroup : ProxyFragment, IGridProvider, IExpandCollapseProvider { // ------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructor internal WindowsListViewGroup (IntPtr hwnd, ProxyFragment parent, int groupID) : base (hwnd, parent, groupID) { _cControlType = ControlType.Group; _groupID = groupID; _sAutomationId = "Group " + (groupID + 1).ToString(CultureInfo.InvariantCulture); // This string is a non-localizable string _isComctrlV6OnOsVerV6orHigher = Misc.IsComctrlV6OnOsVerV6orHigher(hwnd); } #endregion Constructor //------------------------------------------------------ // // Patterns Implementation // //------------------------------------------------------ #region ProxySimple Interface // Returns a pattern interface if supported. internal override object GetPatternProvider(AutomationPattern iid) { if (iid == GridPattern.Pattern) { return this; } else if (iid == ExpandCollapsePattern.Pattern && WindowsListView.IsGroupViewEnabled(_hwnd)) { return this; } return null; } // Gets the bounding rectangle for this element internal override Rect BoundingRectangle { get { GroupManager manager = WindowsListView._groupsCollection [_hwnd]; NativeMethods.Win32Rect itemRectangle = manager.GetGroupRc(ID); // Don't need to normalize, GetGroupRc returns absolute coordinates. return itemRectangle.ToRect(false); } } // Process all the Logical and Raw Element Properties internal override object GetElementProperty (AutomationProperty idProp) { if (idProp == AutomationElement.ClassNameProperty) { return ""; } return base.GetElementProperty (idProp); } //Gets the localized name internal override string LocalizedName { get { if (_isComctrlV6OnOsVerV6orHigher) { NativeMethods.LVGROUP_V6 group = new NativeMethods.LVGROUP_V6(); group.Init(Marshal.SizeOf(typeof(NativeMethods.LVGROUP_V6))); group.iGroupID = ID; group.cchHeader = Misc.MaxLengthNameProperty; return XSendMessage.GetItemText(_hwnd, group, NativeMethods.LVGF_HEADER); } else { NativeMethods.LVGROUP group = new NativeMethods.LVGROUP(); group.Init(Marshal.SizeOf(typeof(NativeMethods.LVGROUP))); group.iGroupID = ID; group.mask = NativeMethods.LVGF_HEADER; group.cchHeader = Misc.MaxLengthNameProperty; return XSendMessage.GetItemText(_hwnd, group); } } } #endregion #region ProxyFragment // Returns the next sibling element in the raw hierarchy. // Peripheral controls have always negative values. // Returns null if no next child internal override ProxySimple GetNextSibling (ProxySimple child) { GroupManager.GroupInfo groupInfo = GetGroupInfo (_hwnd, ID); if (groupInfo) { int [] items = groupInfo._items; int current = child._item; // find the index of the current lvitem int nextLocation = groupInfo.IndexOf (current) + 1; //Array.IndexOf(items, current) + 1; if (nextLocation <= 0) { // No more siblings return null; } if (nextLocation < groupInfo._count) { return CreateListViewItem (items [nextLocation]); } // List view groups in vista can have an extra link at the end that says // somthing like "show all 11 items..." if (_isComctrlV6OnOsVerV6orHigher && nextLocation == groupInfo._count) { NativeMethods.LVGROUP_V6 group = new NativeMethods.LVGROUP_V6(); group.Init(Marshal.SizeOf(typeof(NativeMethods.LVGROUP_V6))); group.iGroupID = _groupID; group.mask = NativeMethods.LVGF_STATE; group.stateMask = NativeMethods.LVGS_SUBSETED; // Note: return code of GetGroupInfo() is not reliable. XSendMessage.GetGroupInfo(_hwnd, ref group); // ignore return code. // The items array holds the list items in this group. If we have a subset link we // don't store it with the list items because it isn't really a list item. Instead we just // create the subset link proxy with an item index one more than the last index. if ((group.state & NativeMethods.LVGS_SUBSETED) != 0) { return CreateGroupSubsetLink(items [groupInfo._count - 1] + 1); } } } return null; } // Returns the previous sibling element in the raw hierarchy. // Peripheral controls have always negative values. // Returns null is no previous internal override ProxySimple GetPreviousSibling (ProxySimple child) { GroupManager.GroupInfo groupInfo = GetGroupInfo (_hwnd, ID); if (groupInfo) { int [] items = groupInfo._items; int current = child._item; // The subset link has an index that is one past the list items // If we are on that then the previous is the last item in the items array. if (_isComctrlV6OnOsVerV6orHigher && current == groupInfo._count) { int index = items [groupInfo._count - 1]; return CreateListViewItem (index); } // find the index of the current lvitem int prevLocation = groupInfo.IndexOf (current) - 1; if (prevLocation <= -2) { throw new InvalidOperationException(SR.Get(SRID.OperationCannotBePerformed)); } if (prevLocation >= 0) { return CreateListViewItem (items [prevLocation]); } } return null; } // Returns the first child element in the raw hierarchy. internal override ProxySimple GetFirstChild () { // return first item in this group GroupManager.GroupInfo groupInfo = GetGroupInfo (_hwnd, ID); if (groupInfo) { int [] items = groupInfo._items; int index = items [0]; return CreateListViewItem (index); } return null; } // Returns the last child element in the raw hierarchy. internal override ProxySimple GetLastChild () { // return last item in this group GroupManager.GroupInfo groupInfo = GetGroupInfo (_hwnd, ID); // List view groups in vista can have an extra link at the end that says // something like "show all 11 items...". If one exists expose it as the last child. if (_isComctrlV6OnOsVerV6orHigher) { NativeMethods.LVGROUP_V6 group = new NativeMethods.LVGROUP_V6(); group.Init(Marshal.SizeOf(typeof(NativeMethods.LVGROUP_V6))); group.iGroupID = _groupID; group.mask = NativeMethods.LVGF_STATE; group.stateMask = NativeMethods.LVGS_SUBSETED; // Note: return code of GetGroupInfo() is not reliable. XSendMessage.GetGroupInfo(_hwnd, ref group); // ignore return code. // if we are not subseted then the last item is a regular listitem so // it is ok to fall through and let that be created. Otherwise we need to // create the subset link proxy. if ((group.state & NativeMethods.LVGS_SUBSETED) != 0) { int [] items = groupInfo._items; if (groupInfo._count <= 0 || groupInfo._count > items.Length) { return null; } int index = items [groupInfo._count - 1]; return CreateGroupSubsetLink(index + 1); } } if (groupInfo) { int [] items = groupInfo._items; if (groupInfo._count <= 0 || groupInfo._count > items.Length) { return null; } int index = items [groupInfo._count - 1]; return CreateListViewItem (index); } return null; } // Returns a Proxy element corresponding to the specified screen coordinates. internal override ProxySimple ElementProviderFromPoint (int x, int y) { NativeMethods.Win32Point pt = new NativeMethods.Win32Point (x, y); NativeMethods.LVHITTESTINFO_INTERNAL hitTest = WindowsListView.SubitemHitTest (_hwnd, pt); if ((hitTest.flags & NativeMethods.LVHT_EX_GROUP_HEADER) != 0) { return this; } if ((hitTest.flags & NativeMethods.LVHT_ONITEM) != 0 && hitTest.iItem >= 0) { // create the item return new ListViewItem (_hwnd, this, hitTest.iItem); } // If we did not land on an item we may be at a subset link these only exist // in v6 comctrl and vista or later. if (_isComctrlV6OnOsVerV6orHigher) { // Allocate a local LVHITTESTINFO struct. NativeMethods.LVHITTESTINFO_V6 hitTestNative = new NativeMethods.LVHITTESTINFO_V6(hitTest); unsafe { XSendMessage.XSendGetIndex(_hwnd, NativeMethods.LVM_HITTEST, new IntPtr(-1), new IntPtr(&hitTestNative), Marshal.SizeOf(hitTestNative.GetType())); } if ((hitTestNative.flags & NativeMethods.LVHT_EX_GROUP_SUBSETLINK) != 0) { GroupManager.GroupInfo groupInfo = GetGroupInfo (_hwnd, ID); int [] items = groupInfo._items; if (groupInfo._count <= 0 || groupInfo._count > items.Length) { return null; } int index = items [groupInfo._count - 1]; return CreateGroupSubsetLink(index + 1); } } return this; } protected override bool IsFocused () { int groupIndex = (int)Misc.ProxySendMessage(_hwnd, NativeMethods.LVM_GETFOCUSEDGROUP, IntPtr.Zero, IntPtr.Zero); // need to convert the item id to a group id NativeMethods.LVGROUP_V6 groupInfo = new NativeMethods.LVGROUP_V6(); groupInfo.Init(Marshal.SizeOf(typeof(NativeMethods.LVGROUP_V6))); groupInfo.mask = NativeMethods.LVGF_GROUPID; unsafe { bool lresult = XSendMessage.XSend(_hwnd, NativeMethods.LVM_GETGROUPINFOBYINDEX, new IntPtr(groupIndex), new IntPtr(&groupInfo), Marshal.SizeOf(typeof(NativeMethods.LVGROUP_V6))); if (!lresult) { // no group for this item should never happen. return false; } } if (groupInfo.iGroupID == _groupID) { return true; } return false; } #endregion Interface Methods #region Grid Pattern // Obtain the AutomationElement at an zero based absolute position in the grid. // Where 0,0 is top left IRawElementProviderSimple IGridProvider.GetItem(int row, int column) { int maxRow = GetRowCount (_hwnd, ID); int maxColumn = GetColumnCount(_hwnd, ID); if (row < 0 || row >= maxRow) { throw new ArgumentOutOfRangeException("row", row, SR.Get(SRID.GridRowOutOfRange)); } if (column < 0 || column >= maxColumn) { throw new ArgumentOutOfRangeException("column", column, SR.Get(SRID.GridColumnOutOfRange)); } if (WindowsListView.IsDetailMode (_hwnd)) { return GetCellInDetailMode (row, column); } return GetCellInOtherModes (row, column, maxColumn); } int IGridProvider.RowCount { get { return GetRowCount (_hwnd, ID); } } int IGridProvider.ColumnCount { get { return GetColumnCount (_hwnd, ID); } } #endregion Grid Pattern #region ExpandCollapse Pattern private void CheckControlEnabled() { if (!SafeNativeMethods.IsWindowEnabled(_hwnd)) { throw new ElementNotEnabledException(); } } void IExpandCollapseProvider.Expand() { ExpandOrCollapse(false); } private bool IsCollapsed() { return IsCollapsed(_hwnd, _groupID); } internal static bool IsCollapsed(IntPtr hwnd, int groupID) { bool isCollapsed = false; NativeMethods.LVGROUP group = new NativeMethods.LVGROUP(); group.Init(Marshal.SizeOf(typeof(NativeMethods.LVGROUP))); group.iGroupID = groupID; group.mask = NativeMethods.LVGF_STATE; group.stateMask = NativeMethods.LVGS_COLLAPSED; // Note: return code of GetGroupInfo() is not reliable. XSendMessage.GetGroupInfo(hwnd, ref group); // ignore return code. isCollapsed = (group.state & NativeMethods.LVGS_COLLAPSED) != 0; return isCollapsed; } // Hide all Children void IExpandCollapseProvider.Collapse() { ExpandOrCollapse(true); } // Indicates an elements current Collapsed or Expanded state ExpandCollapseState IExpandCollapseProvider.ExpandCollapseState { get { return IsCollapsed() ? ExpandCollapseState.Collapsed : ExpandCollapseState.Expanded; } } #endregion ExpandCollapse Pattern //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods // get focused element internal static ProxySimple GetFocusInGroup (IntPtr hwnd, ProxyFragment parent) { int index = WindowsListView.GetItemNext(hwnd, -1, NativeMethods.LVNI_FOCUSED); if (index != -1) { // get id of the group to which item belongs NativeMethods.LVITEM_V6 item = new NativeMethods.LVITEM_V6 (); item.mask = NativeMethods.LVIF_GROUPID; item.iItem = index; if (XSendMessage.GetItem(hwnd, ref item)) { WindowsListViewGroup group = new WindowsListViewGroup (hwnd, parent, item.iGroupID); return new ListViewItem (hwnd, group, index); } } else { // if none of the items have focus see if the focus is on the subset link // this only exists in v6 comctrl on vista or later. if (Misc.IsComctrlV6OnOsVerV6orHigher(hwnd)) { int groupIndex = (int)Misc.ProxySendMessage(hwnd, NativeMethods.LVM_GETFOCUSEDGROUP, IntPtr.Zero, IntPtr.Zero); // need to convert the item id to a group id NativeMethods.LVGROUP_V6 groupInfo = new NativeMethods.LVGROUP_V6(); groupInfo.Init(Marshal.SizeOf(typeof(NativeMethods.LVGROUP_V6))); groupInfo.mask = NativeMethods.LVGF_GROUPID; unsafe { bool lresult = XSendMessage.XSend(hwnd, NativeMethods.LVM_GETGROUPINFOBYINDEX, new IntPtr(groupIndex), new IntPtr(&groupInfo), Marshal.SizeOf(typeof(NativeMethods.LVGROUP_V6))); if (!lresult) { // no group for this item should never happen. return null; } } int groupId = groupInfo.iGroupID; groupInfo.Init(Marshal.SizeOf(typeof(NativeMethods.LVGROUP_V6))); groupInfo.iGroupID = groupId; groupInfo.mask = NativeMethods.LVGF_STATE; groupInfo.stateMask = NativeMethods.LVGS_SUBSETLINKFOCUSED; // Note: return code of GetGroupInfo() is not reliable. XSendMessage.GetGroupInfo(hwnd, ref groupInfo); // ignore return code. if ((groupInfo.state & NativeMethods.LVGS_SUBSETLINKFOCUSED) != 0) { GroupManager.GroupInfo groupManagerInfo = GetGroupInfo (hwnd, groupId); int [] items = groupManagerInfo._items; if (groupManagerInfo._count <= 0 || groupManagerInfo._count >= items.Length) { return null; } int sslIndex = items [groupManagerInfo._count - 1]; // The items array holds the list items in this group. If we have a subset link we // don't store it with the list items because it isn't really a list item. Instead we just // create the subset link proxy with an item index one more than the last index. WindowsListViewGroup group = new WindowsListViewGroup (hwnd, parent, groupId); return group.CreateGroupSubsetLink(sslIndex + 1); } else { return new WindowsListViewGroup (hwnd, parent, groupId); } } } return null; } internal int ID { get { return _groupID; } } // Expose the ability to retrieve count of columns in the Group's grid to the outside proxies // LVItem will be one of customer // Do not call when LV in the Detail mode static internal int GetColumnCountExternal (IntPtr hwnd, int groupID) { System.Diagnostics.Debug.Assert (!WindowsListView.IsDetailMode (hwnd), "GetColumnCountExternal: called when lv is in Detail mode"); return GetCountOfItemsInDimension (hwnd, groupID, new IsNewItemInDimension (IsNewColumn)); } // utility method returning object describing current group static internal GroupManager.GroupInfo GetGroupInfo (IntPtr hwnd, int groupID) { GroupManager.GroupInfo groupInfo = GroupManager.GroupInfo.Null; // if groupmanager is not available GetManager(hwnd) // will raise needed event GroupManager manager = WindowsListView._groupsCollection [hwnd]; groupInfo = manager.GetGroupInfo (groupID); if (!groupInfo) { // LV control did not raise the needed event // alexsn @ throw new InvalidOperationException(SR.Get(SRID.OperationCannotBePerformed)); } return groupInfo; } #endregion Internal Methods //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods // return the lvitem private ProxyFragment CreateListViewItem (int index) { return new ListViewItem (_hwnd, this, index); } private void ExpandOrCollapse(bool collapse) { CheckControlEnabled(); // Check if item can be expanded or collapsed. bool isCollapsed = IsCollapsed(); if ((!collapse && !isCollapsed) || (collapse && isCollapsed)) { throw new InvalidOperationException(SR.Get(SRID.OperationCannotBePerformed)); } NativeMethods.LVGROUP group = new NativeMethods.LVGROUP(); group.Init(Marshal.SizeOf(typeof(NativeMethods.LVGROUP))); // Note: If we set group.mask to LVGF_GROUPID | LVGF_STATE, // SetGroupInfo() will fail. Setting LVGF_STATE alone works, however. group.mask = NativeMethods.LVGF_STATE; group.iGroupID = _groupID; group.stateMask = NativeMethods.LVGS_COLLAPSED; group.state = collapse ? NativeMethods.LVGS_COLLAPSED : 0; if (!XSendMessage.SetGroupInfo(_hwnd, group)) { throw new InvalidOperationException(SR.Get(SRID.OperationCannotBePerformed)); } } // Grid.GetCell implementation for detail mode private IRawElementProviderSimple GetCellInDetailMode (int row, int column) { // Note: column can be used as it is // row corresponds to the index into the array of items that belong to current group GroupManager.GroupInfo groupInfo = GetGroupInfo (_hwnd, ID); if (groupInfo) { int lvitemIndex = groupInfo._items [row]; ProxyFragment lvItem = CreateListViewItem (lvitemIndex); return new ListViewSubItem (_hwnd, lvItem, column, lvitemIndex); } return null; } // Grid.GetCell implementation for lv that is not in detail mode private IRawElementProviderSimple GetCellInOtherModes(int row, int column, int maxColumn) { // Convert row, column into the index into the array of items that belong to // current group int indexIntoArray = row * maxColumn + column; GroupManager.GroupInfo groupInfo = GetGroupInfo (_hwnd, ID); if (!groupInfo) { return null; } if (indexIntoArray >= groupInfo._count) { // Return an empty cell return new EmptyGridItem (row, column, this); } // return cell return CreateListViewItem (groupInfo._items [indexIntoArray]); } static private bool IsGroupValid (IntPtr hwnd, int groupID) { GroupManager manager = WindowsListView._groupsCollection [hwnd]; // check group validity if (!manager.IsGroupIdValid (groupID)) { // Group was disabled but we did not get the needed event // since for some things events are not being sent // (e.g: Going from some LV modes to - List mode, List mode does not have Groups) // alexsn @ throw new InvalidOperationException(SR.Get(SRID.OperationCannotBePerformed)); } return true; } // Detect if 2 lvitems are located in the same column // desicion is based on item's rect coordinates static private NewItemInDimension IsNewColumn (NativeMethods.Win32Rect rc1, NativeMethods.Win32Rect rc2) { // NOTE: Array of lvitems has the following DIRECTION: // 0 1 2 // 3 4 5 // 6 7 // Due to the position of lvitems in the array (see above) // we may be looking at the item that is located in the column which is different from rc1's column but that we // have encountered already (e.g. Happens when we will compare rect of lvitem 3 with rect of lvitem 2, even though // lvitem 3 lives in the different column than lvitem 2, it nevertheless lives in the same column as lvitem 0) // The case when rc1.left would be > rc2.left will indicate the case above (we wrapped around) if (rc1.left < rc2.left) { return NewItemInDimension.New; } else if (rc1.left > rc2.left) { // we wrapped around (e.g. we on lvitem 3) // if we at the point were the column in which rc2 lives already been encountered // we want to stop the enumeration, since we will not discover any new columns return NewItemInDimension.Stop; } // left coordinates are equal, this can indicate that there is only 1 column if (rc1.top >= rc2.top) { // alexsn @ throw new InvalidOperationException(SR.Get(SRID.OperationCannotBePerformed)); } return NewItemInDimension.Stop; } // Detect if 2 lvitems are located in the same row // desicion is based on item's rect coordinates static private NewItemInDimension IsNewRow (NativeMethods.Win32Rect rc1, NativeMethods.Win32Rect rc2) { // NOTE: Array of lvitems has the following DIRECTION: // 0 1 2 // 3 4 5 // 6 7 // For row it should be enough to only check the top or bottom coordinate // due to location of items (see above) in the array return (rc1.top != rc2.top) ? NewItemInDimension.New : NewItemInDimension.Same; } // retrieve number of columns in the group static private int GetColumnCount (IntPtr hwnd, int groupID) { if (WindowsListView.IsDetailMode (hwnd)) { // check group for validity if (IsGroupValid (hwnd, groupID)) { // When lv in the detail mode, Group will have as many columns // as there header items int column = ListViewItem.GetSubItemCount (hwnd); return (column <= -1) ? 0 : column; } return -1; } return GetCountOfItemsInDimension (hwnd, groupID, new IsNewItemInDimension (IsNewColumn)); } // retrieve number of rows in the group static private int GetRowCount (IntPtr hwnd, int groupID) { if (WindowsListView.IsDetailMode (hwnd)) { // When lv in Detail mode (with items shown in groups) // each lvitem will live in their own row // we need to detect how many items belong to the group, // this would correspond to the number of rows GroupManager.GroupInfo groupInfo = GetGroupInfo (hwnd, groupID); if (groupInfo) { return groupInfo._count; } // Good place to send Grid Invalid event return -1; } return GetCountOfItemsInDimension (hwnd, groupID, new IsNewItemInDimension (IsNewRow)); } // This method returns the count of either columns or rows // in the Grid. static private int GetCountOfItemsInDimension (IntPtr hwnd, int groupID, IsNewItemInDimension comparer) { // Algorithm: // Get the rect of the item. // Compare it using provided "comparer" with the previously obtained rect of the previous item in the grid // if comparer returns New increase the count int itemsCount = 0; GroupManager.GroupInfo groupInfo = GetGroupInfo (hwnd, groupID); if (groupInfo) { int [] items = groupInfo._items; NativeMethods.Win32Rect rc; NativeMethods.Win32Rect rcNext; // get coordinates of the first item in the grid if (WindowsListView.GetItemRect(hwnd, items[0], NativeMethods.LVIR_BOUNDS, out rc)) { NewItemInDimension result = NewItemInDimension.New; itemsCount++; // at least one exist for (int i = 1; result != NewItemInDimension.Stop && i < groupInfo._count; i++) { if (!WindowsListView.GetItemRect(hwnd, items[i], NativeMethods.LVIR_BOUNDS, out rcNext)) { // Fail to get rc, makes no sense to continue System.Diagnostics.Debug.Assert (false, "GetCountOfItemsInDimension: failed to get item rect"); return 0; } result = comparer (rc, rcNext); if (result == NewItemInDimension.New) { // found a change in the rect // we either have a new column or new raw itemsCount++; // update the rc with the new coordinates rc = rcNext; } } } return itemsCount; } return -1; } private ProxySimple CreateGroupSubsetLink (int item) { return new ListViewGroupSubsetLink(_hwnd, this, item, _groupID); } #endregion Private Methods //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields private enum NewItemInDimension { New, // indicates that we found a new column or row Same, // indicates that we did not find a new column or row Stop // we should stop looking, since the rest of the items live in prev. seen col or row } // callback that compares 2 grid items based on their rect // return true - if item (rc2) either located in the new(never encountered before) row or column (depends on the call)) // else returns false private delegate NewItemInDimension IsNewItemInDimension (NativeMethods.Win32Rect rc1, NativeMethods.Win32Rect rc2); // same as _item, but to be clear use _groupID private int _groupID; private bool _isComctrlV6OnOsVerV6orHigher; #endregion Private Fields } }
// 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.Reflection.Emit; using Xunit; namespace System.Reflection.Emit.Tests { public class TypeBuilderNamespace { [Fact] public void TestWithoutNamespaceSpecifiedGeneric() { TypeBuilder myBuilder = CreateGenericTypeBuilderWithoutNamespace(); Assert.Equal("", myBuilder.Namespace); } [Fact] public void TestWithNameSpaceSpecifiedGeneric() { TypeBuilder myBuilder = CreateGenericTypeBuilderWithNamespace(); Assert.Equal("GenericTypeNamespace", myBuilder.Namespace); } [Fact] public void TestWithoutNamespaceSpecifiedNonGeneric() { TypeBuilder myBuilder = CreateNonGenericTypeBuilderWithoutNamespace(); Assert.Equal("", myBuilder.Namespace); } [Fact] public void TestWithNamespaceSpecifiedNonGeneric() { TypeBuilder myBuilder = CreateNonGenericTypeBuilderWithNamespace(); Assert.Equal("NonGenericTypeNamespace", myBuilder.Namespace); } public TypeBuilder CreateGenericTypeBuilderWithoutNamespace() { AssemblyName myAsmName = new AssemblyName("TypeBuilderGetFieldExample"); AssemblyBuilder myAssembly = AssemblyBuilder.DefineDynamicAssembly( myAsmName, AssemblyBuilderAccess.Run); ModuleBuilder myModule = TestLibrary.Utilities.GetModuleBuilder(myAssembly, "Module1"); TypeBuilder myType = myModule.DefineType("Sample", TypeAttributes.Class | TypeAttributes.Public); string[] typeParamNames = { "T" }; GenericTypeParameterBuilder[] typeParams = myType.DefineGenericParameters(typeParamNames); ConstructorBuilder ctor = myType.DefineDefaultConstructor( MethodAttributes.PrivateScope | MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName); FieldBuilder myField = myType.DefineField("Field", typeParams[0].AsType(), FieldAttributes.Public); MethodBuilder genMethod = myType.DefineMethod("GM", MethodAttributes.Public | MethodAttributes.Static); string[] methodParamNames = { "U" }; GenericTypeParameterBuilder[] methodParams = genMethod.DefineGenericParameters(methodParamNames); genMethod.SetSignature(null, null, null, new Type[] { methodParams[0].AsType() }, null, null); ILGenerator ilg = genMethod.GetILGenerator(); Type SampleOfU = myType.MakeGenericType(methodParams[0].AsType()); ilg.DeclareLocal(SampleOfU); ConstructorInfo ctorOfU = TypeBuilder.GetConstructor( SampleOfU, ctor); ilg.Emit(OpCodes.Newobj, ctorOfU); ilg.Emit(OpCodes.Stloc_0); ilg.Emit(OpCodes.Ldloc_0); ilg.Emit(OpCodes.Ldarg_0); FieldInfo FieldOfU = TypeBuilder.GetField( SampleOfU, myField); ilg.Emit(OpCodes.Stfld, FieldOfU); ilg.Emit(OpCodes.Ldloc_0); ilg.Emit(OpCodes.Ldfld, FieldOfU); ilg.Emit(OpCodes.Box, methodParams[0].AsType()); MethodInfo writeLineObj = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(object) }); ilg.EmitCall(OpCodes.Call, writeLineObj, null); ilg.Emit(OpCodes.Ret); TypeBuilder dummy = myModule.DefineType("Dummy", TypeAttributes.Class | TypeAttributes.NotPublic); MethodBuilder entryPoint = dummy.DefineMethod("Main", MethodAttributes.Public | MethodAttributes.Static, null, null); ilg = entryPoint.GetILGenerator(); Type SampleOfInt = myType.MakeGenericType(typeof(int)); MethodInfo SampleOfIntGM = TypeBuilder.GetMethod(SampleOfInt, genMethod); MethodInfo GMOfString = SampleOfIntGM.MakeGenericMethod(typeof(string)); ilg.Emit(OpCodes.Ldstr, "Hello, world!"); ilg.EmitCall(OpCodes.Call, GMOfString, null); ilg.Emit(OpCodes.Ret); myType.CreateTypeInfo().AsType(); return myType; } public TypeBuilder CreateGenericTypeBuilderWithNamespace() { AssemblyName myAsmName = new AssemblyName("TypeBuilderGetFieldExample"); AssemblyBuilder myAssembly = AssemblyBuilder.DefineDynamicAssembly( myAsmName, AssemblyBuilderAccess.Run); ModuleBuilder myModule = TestLibrary.Utilities.GetModuleBuilder(myAssembly, "Module1"); TypeBuilder myType = myModule.DefineType("GenericTypeNamespace.Sample", TypeAttributes.Class | TypeAttributes.Public); string[] typeParamNames = { "T" }; GenericTypeParameterBuilder[] typeParams = myType.DefineGenericParameters(typeParamNames); ConstructorBuilder ctor = myType.DefineDefaultConstructor( MethodAttributes.PrivateScope | MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName); FieldBuilder myField = myType.DefineField("Field", typeParams[0].AsType(), FieldAttributes.Public); MethodBuilder genMethod = myType.DefineMethod("GM", MethodAttributes.Public | MethodAttributes.Static); string[] methodParamNames = { "U" }; GenericTypeParameterBuilder[] methodParams = genMethod.DefineGenericParameters(methodParamNames); genMethod.SetSignature(null, null, null, new Type[] { methodParams[0].AsType() }, null, null); ILGenerator ilg = genMethod.GetILGenerator(); Type SampleOfU = myType.MakeGenericType(methodParams[0].AsType()); ilg.DeclareLocal(SampleOfU); ConstructorInfo ctorOfU = TypeBuilder.GetConstructor( SampleOfU, ctor); ilg.Emit(OpCodes.Newobj, ctorOfU); ilg.Emit(OpCodes.Stloc_0); ilg.Emit(OpCodes.Ldloc_0); ilg.Emit(OpCodes.Ldarg_0); FieldInfo FieldOfU = TypeBuilder.GetField( SampleOfU, myField); ilg.Emit(OpCodes.Stfld, FieldOfU); ilg.Emit(OpCodes.Ldloc_0); ilg.Emit(OpCodes.Ldfld, FieldOfU); ilg.Emit(OpCodes.Box, methodParams[0].AsType()); MethodInfo writeLineObj = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(object) }); ilg.EmitCall(OpCodes.Call, writeLineObj, null); ilg.Emit(OpCodes.Ret); TypeBuilder dummy = myModule.DefineType("Dummy", TypeAttributes.Class | TypeAttributes.NotPublic); MethodBuilder entryPoint = dummy.DefineMethod("Main", MethodAttributes.Public | MethodAttributes.Static, null, null); ilg = entryPoint.GetILGenerator(); Type SampleOfInt = myType.MakeGenericType(typeof(int)); MethodInfo SampleOfIntGM = TypeBuilder.GetMethod(SampleOfInt, genMethod); MethodInfo GMOfString = SampleOfIntGM.MakeGenericMethod(typeof(string)); ilg.Emit(OpCodes.Ldstr, "Hello, world!"); ilg.EmitCall(OpCodes.Call, GMOfString, null); ilg.Emit(OpCodes.Ret); myType.CreateTypeInfo().AsType(); return myType; } public TypeBuilder CreateNonGenericTypeBuilderWithoutNamespace() { AssemblyName myAsmName = new AssemblyName("TestTypeBuilder"); AssemblyBuilder myAssembly = AssemblyBuilder.DefineDynamicAssembly( myAsmName, AssemblyBuilderAccess.Run); ModuleBuilder myModule = TestLibrary.Utilities.GetModuleBuilder(myAssembly, "Module1"); TypeBuilder TestType = myModule.DefineType("Test", TypeAttributes.Class | TypeAttributes.Public); MethodBuilder entry = TestType.DefineMethod("Main", MethodAttributes.Public | MethodAttributes.Static, null, null); ILGenerator ilg = entry.GetILGenerator(); ilg.Emit(OpCodes.Ldstr, "Test string here."); MethodInfo writeObj = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }); ilg.EmitCall(OpCodes.Call, writeObj, null); ilg.Emit(OpCodes.Ret); TestType.CreateTypeInfo().AsType(); return TestType; } public TypeBuilder CreateNonGenericTypeBuilderWithNamespace() { AssemblyName myAsmName = new AssemblyName("TestTypeBuilder"); AssemblyBuilder myAssembly = AssemblyBuilder.DefineDynamicAssembly( myAsmName, AssemblyBuilderAccess.Run); ModuleBuilder myModule = TestLibrary.Utilities.GetModuleBuilder(myAssembly, "Module1"); TypeBuilder TestType = myModule.DefineType("NonGenericTypeNamespace.Test", TypeAttributes.Class | TypeAttributes.Public); MethodBuilder entry = TestType.DefineMethod("Main", MethodAttributes.Public | MethodAttributes.Static, null, null); ILGenerator ilg = entry.GetILGenerator(); ilg.Emit(OpCodes.Ldstr, "Test string here."); MethodInfo writeObj = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }); ilg.EmitCall(OpCodes.Call, writeObj, null); ilg.Emit(OpCodes.Ret); TestType.CreateTypeInfo().AsType(); return TestType; } } }
#region License // // Dasher // // Copyright 2015-2017 Drew Noakes // // 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. // // More information about this project is available at: // // https://github.com/drewnoakes/dasher // #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.Emit; #if NETSTANDARD1_3 using System.Runtime.CompilerServices; #endif namespace Dasher.TypeProviders { internal sealed class ComplexTypeProvider : ITypeProvider { public static bool TryValidateComplexType(Type type, ICollection<string> errors) { var constructors = type.GetConstructors(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance); switch (constructors.Length) { case 0: errors.Add("Complex type provider requires a public constructor."); return false; case 1: break; default: errors.Add($"Complex type provider requires a 1 public constructor, not {constructors.Length}."); return false; } if (constructors[0].GetParameters().Length == 0) { errors.Add($"Complex type provider requires constructor to have at least one parameter. Use \"{typeof(Empty).FullName}\" to model an empty type."); return false; } return true; } public bool CanProvide(Type type) { var constructors = type.GetConstructors(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance); return constructors.Length == 1 && constructors[0].GetParameters().Length != 0; } public bool UseDefaultNullHandling(Type valueType) => !valueType.GetTypeInfo().IsValueType; public bool TryEmitSerialiseCode(ILGenerator ilg, ThrowBlockGatherer throwBlocks, ICollection<string> errors, LocalBuilder value, LocalBuilder packer, LocalBuilder contextLocal, DasherContext context) { // treat as complex object and recur var props = value.LocalType .GetProperties(BindingFlags.Instance | BindingFlags.Public) .Where(p => p.CanRead) .ToList(); if (props.Count == 0) throw new SerialisationException($"Unable to serialise type \"{value.LocalType}\". It has no dedicated type provider, and has no properties for serialisation as a complex type.", value.LocalType); // write map header ilg.Emit(OpCodes.Ldloc, packer); ilg.Emit(OpCodes.Ldc_I4, props.Count); ilg.Emit(OpCodes.Call, Methods.Packer_PackMapHeader); var success = true; // write each property's value foreach (var prop in props) { var propValue = ilg.DeclareLocal(prop.PropertyType); // write property name ilg.Emit(OpCodes.Ldloc, packer); ilg.Emit(OpCodes.Ldstr, prop.Name); ilg.Emit(OpCodes.Call, Methods.Packer_Pack_String); // get property value ilg.Emit(value.LocalType.GetTypeInfo().IsValueType ? OpCodes.Ldloca : OpCodes.Ldloc, value); ilg.Emit(OpCodes.Call, prop.GetMethod); ilg.Emit(OpCodes.Stloc, propValue); success &= SerialiserEmitter.TryEmitSerialiseCode(ilg, throwBlocks, errors, propValue, packer, context, contextLocal); } return success; } public bool TryEmitDeserialiseCode(ILGenerator ilg, ThrowBlockGatherer throwBlocks, ICollection<string> errors, string name, Type targetType, LocalBuilder value, LocalBuilder unpacker, LocalBuilder contextLocal, DasherContext context, UnexpectedFieldBehaviour unexpectedFieldBehaviour) { if (!TryValidateComplexType(targetType, errors)) return false; var constructors = targetType.GetConstructors(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance); Debug.Assert(constructors.Length == 1, "Should have one constructor (validation should be performed before call)"); var constructor = constructors[0]; var parameters = constructor.GetParameters(); void ThrowException() { ilg.LoadType(targetType); ilg.Emit(OpCodes.Newobj, Methods.DeserialisationException_Ctor_String_Type); ilg.Emit(OpCodes.Throw); } #region Initialise locals for constructor args var valueLocals = new LocalBuilder[parameters.Length]; var valueSetLocals = new LocalBuilder[parameters.Length]; for (var i = 0; i < parameters.Length; i++) { var parameter = parameters[i]; valueLocals[i] = ilg.DeclareLocal(parameter.ParameterType); valueSetLocals[i] = ilg.DeclareLocal(typeof(int)); if (parameter.HasDefaultValue) { // set default values on params if (NullableValueProvider.IsNullableValueType(parameter.ParameterType)) { ilg.Emit(OpCodes.Ldloca, valueLocals[i]); if (parameter.DefaultValue == null) { ilg.Emit(OpCodes.Initobj, parameter.ParameterType); } else { ilg.LoadConstant(parameter.DefaultValue); ilg.Emit(OpCodes.Call, parameter.ParameterType.GetConstructor(new[] { parameter.ParameterType.GetGenericArguments().Single() })); } } else if (parameter.DefaultValue == null && parameter.ParameterType.GetTypeInfo().IsValueType) { // When DefaultValue is null for a parameter of value type, the programmer must have // stated default(T) as the default value. ilg.Emit(OpCodes.Ldloca, valueLocals[i]); ilg.Emit(OpCodes.Initobj, valueLocals[i].LocalType); } else { ilg.LoadConstant(parameter.DefaultValue); ilg.Emit(OpCodes.Stloc, valueLocals[i]); } // set 'valueSet' to true // note we use the second LSb to indicate a default value ilg.Emit(OpCodes.Ldc_I4_2); ilg.Emit(OpCodes.Stloc, valueSetLocals[i]); } else { // set 'valueSet' to false ilg.Emit(OpCodes.Ldc_I4_0); ilg.Emit(OpCodes.Stloc, valueSetLocals[i]); } } #endregion #region Read map length var mapSize = ilg.DeclareLocal(typeof(int)); { // MsgPack messages may be single values, arrays, maps, or any arbitrary // combination of these types. Our convention is to require messages to // be encoded as maps where the key is the property name. // // MsgPack maps begin with a header indicating the number of pairs // within the map. We read this here. ilg.Emit(OpCodes.Ldloc, unpacker); ilg.Emit(OpCodes.Ldloca, mapSize); ilg.Emit(OpCodes.Call, Methods.Unpacker_TryReadMapLength); // If false was returned, then the next MsgPack value is not a map throwBlocks.ThrowIfFalse(() => { // Check if it's a null ilg.Emit(OpCodes.Ldloc, unpacker); ilg.Emit(OpCodes.Call, Methods.Unpacker_TryReadNull); var lblNotNull = ilg.DefineLabel(); ilg.Emit(OpCodes.Brfalse_S, lblNotNull); { // value is null ilg.Emit(OpCodes.Ldnull); ilg.Emit(OpCodes.Ret); } ilg.MarkLabel(lblNotNull); ilg.Emit(OpCodes.Ldloc, unpacker); ilg.Emit(OpCodes.Call, Methods.Unpacker_HasStreamEnded_Get); var lblNotEmpty = ilg.DefineLabel(); ilg.Emit(OpCodes.Brfalse_S, lblNotEmpty); ilg.Emit(OpCodes.Ldstr, "Data stream empty"); ThrowException(); ilg.MarkLabel(lblNotEmpty); ilg.Emit(OpCodes.Ldstr, "Message must be encoded as a MsgPack map, not \"{0}\"."); ilg.PeekFormatString(unpacker); ilg.Emit(OpCodes.Call, Methods.String_Format_String_Object); ThrowException(); }); } #endregion #region Loop through each key/value pair in the map { #region Initialise loop // Create a loop counter, initialised to zero var loopIndex = ilg.DeclareLocal(typeof(long)); ilg.Emit(OpCodes.Ldc_I4_0); ilg.Emit(OpCodes.Conv_I8); ilg.Emit(OpCodes.Stloc, loopIndex); // Create labels to jump to within the loop var lblLoopTest = ilg.DefineLabel(); // Comparing counter to map size var lblLoopExit = ilg.DefineLabel(); // The first instruction after the loop var lblLoopStart = ilg.DefineLabel(); // The first instruction within the loop // Run the test first ilg.Emit(OpCodes.Br, lblLoopTest); // Mark the first instruction within the loop ilg.MarkLabel(lblLoopStart); #endregion #region Read field name // Although MsgPack allows map keys to be of any arbitrary type, our convention // is to require keys to be strings. We read the key here. var key = ilg.DeclareLocal(typeof(string)); { ilg.Emit(OpCodes.Ldloc, unpacker); ilg.Emit(OpCodes.Ldloca, key); ilg.Emit(OpCodes.Call, Methods.Unpacker_TryReadString); // If false was returned, the data stream ended throwBlocks.ThrowIfFalse(() => { ilg.Emit(OpCodes.Ldstr, "Data stream ended."); ThrowException(); }); } #endregion #region Match name to expected field, then attempt to deserialise by expected type // Build a chain of if/elseif/elseif... blocks for each of the expected fields. // It could be slightly more efficient here to generate a O(log(N)) tree-based lookup, // but that would take quite some engineering. Let's see if there's a significant perf // hit here or not first. var lblEndIfChain = ilg.DefineLabel(); // TODO how much perf diff if properties sorted lexicographically, so no searching? Label? nextLabel = null; for (var parameterIndex = 0; parameterIndex < parameters.Length; parameterIndex++) { // Mark the beginning of the next block, as used if the previous block's condition failed if (nextLabel != null) ilg.MarkLabel(nextLabel.Value); nextLabel = ilg.DefineLabel(); // Compare map's key with this parameter's name in a case insensitive way ilg.Emit(OpCodes.Ldloc, key); ilg.Emit(OpCodes.Ldstr, parameters[parameterIndex].Name); ilg.Emit(OpCodes.Ldc_I4_5); // StringComparison.OrdinalIgnoreCase ilg.Emit(OpCodes.Callvirt, Methods.String_Equals_String_StringComparison); // If the key doesn't match this property, go to the next block ilg.Emit(OpCodes.Brfalse, nextLabel.Value); #region Test for duplicate fields // Verify we haven't already seen a value for this parameter { // Mask out the LSb and see if it is set. If so, we've seen this property // already in this message, which is invalid. ilg.Emit(OpCodes.Ldloc, valueSetLocals[parameterIndex]); ilg.Emit(OpCodes.Ldc_I4_1); ilg.Emit(OpCodes.And); throwBlocks.ThrowIfTrue(() => { ilg.Emit(OpCodes.Ldstr, "Encountered duplicate field \"{0}\" for type \"{1}\"."); ilg.Emit(OpCodes.Ldloc, key); ilg.Emit(OpCodes.Ldstr, targetType.Name); ilg.Emit(OpCodes.Call, Methods.String_Format_String_Object_Object); ThrowException(); }); // Record the fact that we've seen this property ilg.Emit(OpCodes.Ldloc, valueSetLocals[parameterIndex]); ilg.Emit(OpCodes.Ldc_I4_1); ilg.Emit(OpCodes.Or); ilg.Emit(OpCodes.Stloc, valueSetLocals[parameterIndex]); } #endregion if (!DeserialiserEmitter.TryEmitDeserialiseCode(ilg, throwBlocks, errors, parameters[parameterIndex].Name, targetType, valueLocals[parameterIndex], unpacker, context, contextLocal, unexpectedFieldBehaviour)) throw new Exception($"Unable to deserialise values of type {valueLocals[parameterIndex].LocalType} from MsgPack data."); ilg.Emit(OpCodes.Br, lblEndIfChain); } if (nextLabel != null) ilg.MarkLabel(nextLabel.Value); #region Process unexpected field // If we got here then the property was not recognised. Either throw or ignore, depending upon configuration. if (unexpectedFieldBehaviour == UnexpectedFieldBehaviour.Throw) { throwBlocks.Throw(() => { ilg.Emit(OpCodes.Ldstr, "Encountered unexpected field \"{0}\" of MsgPack format \"{1}\" for CLR type \"{2}\"."); ilg.Emit(OpCodes.Ldloc, key); ilg.PeekFormatString(unpacker); ilg.Emit(OpCodes.Ldstr, targetType.Name); ilg.Emit(OpCodes.Call, Methods.String_Format_String_Object_Object_Object); ThrowException(); }); } else { // skip unexpected value ilg.Emit(OpCodes.Ldloc, unpacker); ilg.Emit(OpCodes.Call, Methods.Unpacker_SkipValue); } #endregion ilg.MarkLabel(lblEndIfChain); #endregion #region Evaluate loop and branch to start unless finished // Increment the loop index ilg.Emit(OpCodes.Ldloc, loopIndex); ilg.Emit(OpCodes.Ldc_I4_1); ilg.Emit(OpCodes.Conv_I8); ilg.Emit(OpCodes.Add); ilg.Emit(OpCodes.Stloc, loopIndex); // Loop condition ilg.MarkLabel(lblLoopTest); ilg.Emit(OpCodes.Ldloc, loopIndex); ilg.Emit(OpCodes.Ldloc, mapSize); ilg.Emit(OpCodes.Conv_I8, mapSize); // If the loop is done, jump to the first instruction after the loop ilg.Emit(OpCodes.Beq_S, lblLoopExit); // Jump back to the start of the loop ilg.Emit(OpCodes.Br, lblLoopStart); // Mark the end of the loop ilg.MarkLabel(lblLoopExit); #endregion } #endregion #region Verify all required values either specified or have a default value var paramName = ilg.DeclareLocal(typeof(string)); for (var i = 0; i < valueSetLocals.Length; i++) { // Store the name of the parameter we are inspecting // for use in the exception later. ilg.Emit(OpCodes.Ldstr, parameters[i].Name); ilg.Emit(OpCodes.Stloc, paramName); // If any value is zero then neither a default nor specified value // exists for that parameter, and we cannot continue. ilg.Emit(OpCodes.Ldloc, valueSetLocals[i]); ilg.Emit(OpCodes.Ldc_I4_0); throwBlocks.ThrowIfEqual(() => { ilg.Emit(OpCodes.Ldstr, "Missing required field \"{0}\" for type \"{1}\"."); ilg.Emit(OpCodes.Ldloc, paramName); ilg.Emit(OpCodes.Ldstr, targetType.Name); ilg.Emit(OpCodes.Call, Methods.String_Format_String_Object_Object); ThrowException(); }); } // If we got here, all value exist and we're good to continue. #endregion #region Construct final complex object via its constructor // Push all values onto the execution stack foreach (var valueLocal in valueLocals) ilg.Emit(OpCodes.Ldloc, valueLocal); // Call the target type's constructor ilg.Emit(OpCodes.Newobj, constructor); ilg.Emit(OpCodes.Stloc, value); #endregion return true; } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V9.Resources { /// <summary>Resource name for the <c>DistanceView</c> resource.</summary> public sealed partial class DistanceViewName : gax::IResourceName, sys::IEquatable<DistanceViewName> { /// <summary>The possible contents of <see cref="DistanceViewName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>customers/{customer_id}/distanceViews/{placeholder_chain_id}~{distance_bucket}</c>. /// </summary> CustomerPlaceholderChainDistanceBucket = 1, } private static gax::PathTemplate s_customerPlaceholderChainDistanceBucket = new gax::PathTemplate("customers/{customer_id}/distanceViews/{placeholder_chain_id_distance_bucket}"); /// <summary>Creates a <see cref="DistanceViewName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="DistanceViewName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static DistanceViewName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new DistanceViewName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="DistanceViewName"/> with the pattern /// <c>customers/{customer_id}/distanceViews/{placeholder_chain_id}~{distance_bucket}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="placeholderChainId">The <c>PlaceholderChain</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="distanceBucketId">The <c>DistanceBucket</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="DistanceViewName"/> constructed from the provided ids.</returns> public static DistanceViewName FromCustomerPlaceholderChainDistanceBucket(string customerId, string placeholderChainId, string distanceBucketId) => new DistanceViewName(ResourceNameType.CustomerPlaceholderChainDistanceBucket, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), placeholderChainId: gax::GaxPreconditions.CheckNotNullOrEmpty(placeholderChainId, nameof(placeholderChainId)), distanceBucketId: gax::GaxPreconditions.CheckNotNullOrEmpty(distanceBucketId, nameof(distanceBucketId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="DistanceViewName"/> with pattern /// <c>customers/{customer_id}/distanceViews/{placeholder_chain_id}~{distance_bucket}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="placeholderChainId">The <c>PlaceholderChain</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="distanceBucketId">The <c>DistanceBucket</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="DistanceViewName"/> with pattern /// <c>customers/{customer_id}/distanceViews/{placeholder_chain_id}~{distance_bucket}</c>. /// </returns> public static string Format(string customerId, string placeholderChainId, string distanceBucketId) => FormatCustomerPlaceholderChainDistanceBucket(customerId, placeholderChainId, distanceBucketId); /// <summary> /// Formats the IDs into the string representation of this <see cref="DistanceViewName"/> with pattern /// <c>customers/{customer_id}/distanceViews/{placeholder_chain_id}~{distance_bucket}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="placeholderChainId">The <c>PlaceholderChain</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="distanceBucketId">The <c>DistanceBucket</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="DistanceViewName"/> with pattern /// <c>customers/{customer_id}/distanceViews/{placeholder_chain_id}~{distance_bucket}</c>. /// </returns> public static string FormatCustomerPlaceholderChainDistanceBucket(string customerId, string placeholderChainId, string distanceBucketId) => s_customerPlaceholderChainDistanceBucket.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(placeholderChainId, nameof(placeholderChainId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(distanceBucketId, nameof(distanceBucketId)))}"); /// <summary>Parses the given resource name string into a new <see cref="DistanceViewName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/distanceViews/{placeholder_chain_id}~{distance_bucket}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="distanceViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="DistanceViewName"/> if successful.</returns> public static DistanceViewName Parse(string distanceViewName) => Parse(distanceViewName, false); /// <summary> /// Parses the given resource name string into a new <see cref="DistanceViewName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/distanceViews/{placeholder_chain_id}~{distance_bucket}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="distanceViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="DistanceViewName"/> if successful.</returns> public static DistanceViewName Parse(string distanceViewName, bool allowUnparsed) => TryParse(distanceViewName, allowUnparsed, out DistanceViewName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="DistanceViewName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/distanceViews/{placeholder_chain_id}~{distance_bucket}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="distanceViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="DistanceViewName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string distanceViewName, out DistanceViewName result) => TryParse(distanceViewName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="DistanceViewName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/distanceViews/{placeholder_chain_id}~{distance_bucket}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="distanceViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="DistanceViewName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string distanceViewName, bool allowUnparsed, out DistanceViewName result) { gax::GaxPreconditions.CheckNotNull(distanceViewName, nameof(distanceViewName)); gax::TemplatedResourceName resourceName; if (s_customerPlaceholderChainDistanceBucket.TryParseName(distanceViewName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerPlaceholderChainDistanceBucket(resourceName[0], split1[0], split1[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(distanceViewName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private DistanceViewName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string distanceBucketId = null, string placeholderChainId = null) { Type = type; UnparsedResource = unparsedResourceName; CustomerId = customerId; DistanceBucketId = distanceBucketId; PlaceholderChainId = placeholderChainId; } /// <summary> /// Constructs a new instance of a <see cref="DistanceViewName"/> class from the component parts of pattern /// <c>customers/{customer_id}/distanceViews/{placeholder_chain_id}~{distance_bucket}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="placeholderChainId">The <c>PlaceholderChain</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="distanceBucketId">The <c>DistanceBucket</c> ID. Must not be <c>null</c> or empty.</param> public DistanceViewName(string customerId, string placeholderChainId, string distanceBucketId) : this(ResourceNameType.CustomerPlaceholderChainDistanceBucket, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), placeholderChainId: gax::GaxPreconditions.CheckNotNullOrEmpty(placeholderChainId, nameof(placeholderChainId)), distanceBucketId: gax::GaxPreconditions.CheckNotNullOrEmpty(distanceBucketId, nameof(distanceBucketId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>DistanceBucket</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string DistanceBucketId { get; } /// <summary> /// The <c>PlaceholderChain</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string PlaceholderChainId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerPlaceholderChainDistanceBucket: return s_customerPlaceholderChainDistanceBucket.Expand(CustomerId, $"{PlaceholderChainId}~{DistanceBucketId}"); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as DistanceViewName); /// <inheritdoc/> public bool Equals(DistanceViewName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(DistanceViewName a, DistanceViewName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(DistanceViewName a, DistanceViewName b) => !(a == b); } public partial class DistanceView { /// <summary> /// <see cref="DistanceViewName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal DistanceViewName ResourceNameAsDistanceViewName { get => string.IsNullOrEmpty(ResourceName) ? null : DistanceViewName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } } }
using System; using System.Collections.Generic; using Newtonsoft.Json.Linq; namespace TMAPIv4 { public class TemplateRevision { protected JObject backing; protected Template template; /// <summary> /// Contains the revision's Data Description, which controls the form interface /// created by TaguchiMail to edit activities using this template. This document /// indirectly determines the structure of the source document used by the /// template's stylesheet. /// </summary> public string Format { get { return (string)backing["format"]; } set { backing["format"] = new JValue(value); } } /// <summary> /// Contains the revision XSLT stylesheet. This is normally created within the /// TaguchiMail UI, and is designed to work with the XML documents created by /// the activity edit interface; these are created based on the format field, /// which defines allowable data types and document structure. /// </summary> public string Content { get { return (string)backing["content"]; } set { backing["format"] = new JValue(value); } } /// <summary> /// ID of the template revision record in the database. /// </summary> public string RecordId { get { return backing["id"].ToString(); } } /// <summary> /// Create a new template revision, given a parent Template, a format document /// (aka Data Description), and a content document (XSL stylesheet). /// </summary> /// <param name="template"> /// A <see cref="Template"/> /// </param> /// <param name="format"> /// A <see cref="System.String"/> /// </param> /// <param name="content"> /// A <see cref="System.String"/> /// </param> public TemplateRevision (Template template, string format, string content) { this.backing = new JObject(); this.template = template; this.Format = format; this.Content = content; } public TemplateRevision (Template template, JObject revision) { this.backing = revision; this.template = template; } } public class Template : Record { protected JArray existingRevisions; public Template (Context context) : base(context) { this.resourceType = "template"; } /// <summary> /// ID of the TaguchiMail template record. /// </summary> public string RecordId { get { return backing["id"].ToString(); } } /// <summary> /// External ID/reference, intended to store external application primary keys. /// /// If not null, this field must be unique. /// </summary> public string Ref { get { return (string)backing["ref"]; } set { backing["ref"] = new JValue(value); } } /// <summary> /// Template name /// </summary> public string Name { get { return (string)backing["name"]; } set { backing["name"] = new JValue(value); } } /// <summary> /// This is matched up with Activity types to determine what /// to show the user in the Suggested Templates/Other Templates sections /// </summary> public string Type { get { return (string)backing["type"]; } set { backing["type"] = new JValue(value); } } /// <summary> /// This can be any application-defined value /// </summary> public string Subtype { get { return (string)backing["subtype"]; } set { backing["subtype"] = new JValue(value); } } /// <summary> /// Arbitrary application XML data store. /// </summary> public string XmlData { get { return (string)backing["data"]; } set { backing["data"] = new JValue(value); } } /// <summary> /// Template status; leave null if not used /// </summary> public string Status { get { return (string)backing["status"]; } } /// <summary> /// Latest template revision content. If set, a new revision will be created upon template create/update. /// </summary> public TemplateRevision LatestRevision { get { if (((JArray)backing["revisions"]).Count > 0) { return new TemplateRevision(this, (JObject)backing["revisions"][0]); } else if (existingRevisions.Count > 0) { return new TemplateRevision(this, (JObject)existingRevisions[0]); } else { return null; } } set { JObject revision = new JObject(); revision["content"] = new JValue(value.Content); revision["format"] = new JValue(value.Format); if (((JArray)backing["revisions"]).Count > 0) { backing["revisions"][0] = revision; } else { ((JArray)backing["revisions"]).Add(revision); } } } /// <summary> /// Save this template to the TaguchiMail database. /// </summary> public override void Update() { base.Update(); // need to move the existing revisions to avoid re-creating the same // ones if this object is saved again this.existingRevisions = (JArray)this.backing["revisions"]; this.backing["revisions"] = new JArray(); } /// <summary> /// Create this template in the TaguchiMail database. /// </summary> public override void Create() { base.Create(); // need to move the existing revisions to avoid re-creating the same // ones if this object is saved again this.existingRevisions = (JArray)this.backing["revisions"]; this.backing["revisions"] = new JArray(); } /// <summary> /// Retrieve a single Template based on its TaguchiMail identifier. /// </summary> /// <param name="context"> /// A <see cref="Context"/> object determining the TM instance and organization to query. /// </param> /// <param name="recordId"> /// A <see cref="System.String"/> containing the template's unique TaguchiMail identifier. /// </param> /// <returns> /// The <see cref="Template"/> with that ID. /// </returns> public static Template Get(Context context, string recordId, Dictionary<string, string> parameters) { JArray results = JArray.Parse(context.MakeRequest("template", "GET", recordId, null, parameters, null)); Template rec = new Template(context); rec.backing = (JObject)results[0]; rec.existingRevisions = (JArray)rec.backing["revisions"]; // clear out existing revisions so they're not sent back to the server on update rec.backing["revisions"] = new JArray(); return rec; } /// <summary> /// Retrieve a single Template based on its TaguchiMail identifier, with its latest revision content. /// </summary> /// <param name="context"> /// A <see cref="Context"/> object determining the TM instance and organization to query. /// </param> /// <param name="recordId"> /// A <see cref="System.String"/> containing the template's unique TaguchiMail identifier. /// </param> /// <returns> /// The <see cref="Template"/> with that ID. /// </returns> public static Template GetWithContent(Context context, string recordId, Dictionary<string, string> parameters) { Dictionary<string, string> newParams = new Dictionary<string, string>(parameters); newParams.Add("revisions", "latest"); return Template.Get(context, recordId, newParams); } /// <summary> /// Retrieve a list of Templates based on a query. /// </summary> /// <param name="context"> /// A <see cref="Context"/> object determining the TM instance and organization to query. /// </param> /// <param name="sort"> /// A <see cref="System.String"/> indicating which of the record's fields should be used to /// sort the output. /// </param> /// <param name="order"> /// A <see cref="System.String"/> containing either 'asc' or 'desc', indicating whether the /// result list should be returned in ascending or descending order. /// </param> /// <param name="offset"> /// A <see cref="System.Int32"/> indicating the index of the first record to be returned in /// the list. /// </param> /// <param name="limit"> /// A <see cref="System.Int32"/> indicating the maximum number of records to return. /// </param> /// <param name="query"> /// An <see cref="System.String[]"/> of query predicates, each of the form: /// [field]-[operator]-[value] /// where [field] is one of the defined resource fields, [operator] is one of the below-listed comparison operators, /// and [value] is a string value to which the field should be compared. /// /// Supported operators: /// * eq: mapped to SQL '=', tests for equality between [field] and [value] (case-sensitive for strings); /// * neq: mapped to SQL '!=', tests for inequality between [field] and [value] (case-sensitive for strings); /// * lt: mapped to SQL '&lt;', tests if [field] is less than [value]; /// * gt: mapped to SQL '&gt;', tests if [field] is greater than [value]; /// * lte: mapped to SQL '&lt;=', tests if [field] is less than or equal to [value]; /// * gte: mapped to SQL '&gt;=', tests if [field] is greater than or equal to [value]; /// * re: mapped to PostgreSQL '~', interprets [value] as a POSIX regular expression and tests if [field] matches it; /// * rei: mapped to PostgreSQL '~*', performs a case-insensitive POSIX regular expression match; /// * like: mapped to SQL 'LIKE' (case-sensitive); /// * is: mapped to SQL 'IS', should be used to test for NULL values in the database as [field]-eq-null is always false; /// * nt: mapped to SQL 'IS NOT', should be used to test for NOT NULL values in the database as [field]-neq-null is always false. /// </param> /// <returns> /// A <see cref="Template[]"/> matching the query. /// </returns> public static Template[] Find(Context context, string sort, string order, int offset, int limit, string[] query) { Dictionary<string,string> parameters = new Dictionary<string, string>(); parameters["sort"] = sort; parameters["order"] = order; parameters["offset"] = offset.ToString(); parameters["limit"] = limit.ToString(); JArray results = JArray.Parse(context.MakeRequest("template", "GET", null, null, parameters, query)); List<Template> recordSet = new List<Template>(); foreach (var result in results) { Template rec = new Template(context); rec.backing = (JObject)result; rec.existingRevisions = (JArray)rec.backing["revisions"]; // clear out existing revisions so they're not sent back to the server on update rec.backing["revisions"] = new JArray(); recordSet.Add(rec); } return recordSet.ToArray(); } } }
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace AspNetCorehandson { public partial class PubsEntities : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder options) { options.UseSqlite($"Filename={Startup.App_Data}/pubs.db"); } public DbSet<Author> Authors { get; set; } public DbSet<Title> Titles { get; set; } public DbSet<Publisher> Publishers { get; set; } public DbSet<Store> Stores { get; set; } public DbSet<Sale> Sales { get; set; } public DbSet<TitleAuthor> TitleAuthors { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Sale>().HasKey(s => new { s.StoreId, s.OrderNumber, s.TitleId }); modelBuilder.Entity<TitleAuthor>().HasKey(ta => new { ta.AuthorId, ta.TitleId }); modelBuilder.Entity<Sale>().HasOne(s => s.Title).WithMany(t => t.Sales).IsRequired(); modelBuilder.Entity<Sale>().HasOne(s => s.Store).WithMany(s => s.Sales).IsRequired(); modelBuilder.Entity<Publisher>().HasMany(p => p.Titles).WithOne(t => t.Publisher).IsRequired(); modelBuilder.Entity<Author>().HasMany(a => a.TitleAuthors).WithOne(ta => ta.Author).IsRequired(); modelBuilder.Entity<Title>().HasMany(t => t.TitleAuthors).WithOne(ta => ta.Title).IsRequired(); } } [Table("authors")] public partial class Author { [Column("au_id"), Required, MaxLength(11), Key] public string AuthorId { get; set; } [Column("au_fname"), Required, MaxLength(20)] public string AuthorFirstName { get; set; } [Column("au_lname"), Required, MaxLength(40)] public string AuthorLastName { get; set; } [Column("phone"), Required, MaxLength(12)] public string Phone { get; set; } [Column("address"), MaxLength(40)] public string Address { get; set; } [Column("city"), MaxLength(20)] public string City { get; set; } [Column("state"), MaxLength(2)] public string State { get; set; } [Column("zip"), MaxLength(5)] public string Zip { get; set; } [Column("contract"), Required] public bool Contract { get; set; } [Column("rowversion"), Timestamp, ConcurrencyCheck] public byte[] RowVersion { get; set; } public ICollection<TitleAuthor> TitleAuthors { get; set; } } [Table("publishers")] public partial class Publisher { [Column("pub_id"), Required, MaxLength(4)] public string PublisherId { get; set; } [Column("pub_name"), MaxLength(40)] public string PublisherName { get; set; } [Column("city"), MaxLength(20)] public string City { get; set; } [Column("state"), MaxLength(2)] public string State { get; set; } [Column("country"), MaxLength(30)] public string Country { get; set; } public ICollection<Title> Titles { get; set; } } [Table("titles")] public partial class Title { [Column("title_id"), Required, MaxLength(6), Key] public string TitleId { get; set; } [Column("title"), Required, MaxLength(80)] public string TitleName { get; set; } [Column("type"), Required, MaxLength(12)] public string Type { get; set; } [Column("price")] public decimal? Price { get; set; } [Column("advance")] public decimal? Advance { get; set; } [Column("royalty")] public int? Royalty { get; set; } [Column("ytd_sales")] public int? YeatToDateSales { get; set; } [Column("notes"), MaxLength(200)] public string Notes { get; set; } [Column("pubdate"), Required] public DateTime PublishedDate { get; set; } [Column("pub_id"), MaxLength(4)] public string PublisherId { get; set; } public Publisher Publisher { get; set; } public ICollection<Sale> Sales { get; set; } public ICollection<TitleAuthor> TitleAuthors { get; set; } } [Table("sales")] public partial class Sale { [Column("stor_id"), Required, MaxLength(4)] public string StoreId { get; set; } [Column("ord_num"), Required, MaxLength(20)] public string OrderNumber { get; set; } [Column("ord_date"), Required] public DateTime OrderDate { get; set; } [Column("qty"), Required] public int Quantity { get; set; } [Column("payterms"), Required, MaxLength(12)] public string PayTerms { get; set; } [Column("title_id"), Required, MaxLength(6)] public string TitleId { get; set; } public Store Store { get; set; } public Title Title { get; set; } } [Table("stores")] public partial class Store { [Column("stor_id"), Required, MaxLength(4), Key] public string StoreId { get; set; } [Column("stor_name"), Required, MaxLength(40)] public string StoreName { get; set; } [Column("stor_addr"), Required, MaxLength(40)] public string Address { get; set; } [Column("city"), Required, MaxLength(20)] public string City { get; set; } [Column("state"), Required, MaxLength(22)] public string State { get; set; } [Column("zip"), Required, MaxLength(5)] public string Zip { get; set; } public ICollection<Sale> Sales { get; set; } } [Table("titleauthor")] public partial class TitleAuthor { [Column("au_id"), Required] public string AuthorId { get; set; } [Column("title_id"), Required] public string TitleId { get; set; } [Column("au_ord")] public byte AuthorOrder { get; set; } [Column("royaltyper")] public int RoyaltyPercentage { get; set; } public Author Author { get; set; } public Title Title { get; set; } } }