/// <exception cref="InvalidOperationException">Invalid property type.</exception> internal override void Initialize() { base.Initialize(); if (PropertyName.IsNullOrEmpty()) { return; } var tNode = typeof(TNode); var tParent = typeof(TParent); var tProperty = typeof(TProperty); propertyInfo = tParent.GetProperty(PropertyName); if (propertyInfo == null) { throw new InvalidOperationException(string.Format( Strings.ExBindingFailedForX, tParent.GetShortName() + "." + PropertyName)); } if (propertyInfo.PropertyType != tProperty) { throw new InvalidOperationException(String.Format( Strings.ExTypeOfXPropertyMustBeY, propertyInfo.GetShortName(true), tProperty.GetShortName())); } isNestedToCollection = typeof(NodeCollection).IsAssignableFrom(tProperty); // Getter var typedGetter = DelegateHelper.CreateGetMemberDelegate <TParent, TProperty>(PropertyName); if (typedGetter == null) { throw new InvalidOperationException(string.Format( Strings.ExBindingFailedForX, propertyInfo.GetShortName(true))); } propertyGetter = n => typedGetter.Invoke((TParent)n); // Setter var typedSetter = DelegateHelper.CreateSetMemberDelegate <TParent, TProperty>(PropertyName); if (typedSetter == null) { throw new InvalidOperationException(string.Format( Strings.ExBindingFailedForX, propertyInfo.GetShortName(true))); } propertySetter = (n, v) => typedSetter.Invoke((TParent)n, (TProperty)v); }
static void Main(string[] args) { exceptions obj1 = new exceptions(); obj1.readFromStream(); try { try { Console.WriteLine("Enter fiorst number:"); string a = Console.ReadLine(); Console.WriteLine("Enter Second Number:"); string b = Console.ReadLine(); int c = Convert.ToInt32(a) / Convert.ToInt32(b); // converting into int int num; if (int.TryParse("2", out num)) { // we can use this instead of convert to avoid exceptions } Console.WriteLine(c.ToString()); } catch (FormatException ex) { Console.WriteLine("fe" + ex.Message); throw new Exception("Inner Exception", ex); } catch (DivideByZeroException ex) { Console.WriteLine(ex.Message); throw new Exception("Inner Exception", ex); } catch (OverflowException ex) { Console.WriteLine(ex.Message); throw new Exception("Inner Exception", ex); } } catch (Exception ex) { Console.WriteLine("exception re thrown:" + ex.Message); } DelegateHelper DH = new DelegateHelper(printHello); DH(); Console.Read(); }
/// <summary> /// Initializes a new instance of the <see cref="EventTarget"/> class. /// </summary> /// <param name="associatedObject">The associated object.</param> /// <param name="eventTarget">The event target as string representation.</param> /// <remarks> /// If the parsing fails, no exception will be thrown but the <see cref="ControlName"/> /// and <see cref="EventName"/> will remain empty. /// </remarks> /// <exception cref="ArgumentNullException">The <paramref name="associatedObject"/> is <c>null</c>.</exception> /// <exception cref="ArgumentException">The <paramref name="eventTarget"/> is <c>null</c> or whitespace.</exception> /// <exception cref="InvalidOperationException">The <paramref name="associatedObject"/> is not yet loaded.</exception> public EventTarget(FrameworkElement associatedObject, string eventTarget) { Argument.IsNotNull("associatedObject", associatedObject); Argument.IsNotNullOrWhitespace("eventTarget", eventTarget); #if NET if (!associatedObject.IsLoaded) { throw new InvalidOperationException("The associated object is not yet loaded, which is required"); } #endif _associatedObject = associatedObject; ControlName = string.Empty; EventName = string.Empty; int dotIndex = eventTarget.IndexOf('.'); if (dotIndex == -1) { ControlName = eventTarget; EventName = "Click"; } else { ControlName = eventTarget.Substring(0, dotIndex); EventName = eventTarget.Substring(dotIndex + 1, eventTarget.Length - dotIndex - 1); } _target = _associatedObject.FindName(ControlName); if (_target == null) { throw new InvalidOperationException(string.Format("'{0}' resulted in control name '{1}', which cannot be found on the associated object", eventTarget, ControlName)); } _eventInfo = _target.GetType().GetEventEx(EventName); if (_eventInfo == null) { throw new InvalidOperationException(string.Format("'{0}' resulted in event name '{1}', which cannot be found on target '{2}'", eventTarget, EventName, ControlName)); } var methodInfo = GetType().GetMethodEx("OnEvent", BindingFlagsHelper.GetFinalBindingFlags(true, false)); var boundEventHandler = methodInfo.MakeGenericMethod(new[] { _eventInfo.EventHandlerType.GetMethodEx("Invoke").GetParameters()[1].ParameterType }); _delegate = DelegateHelper.CreateDelegate(_eventInfo.EventHandlerType, this, boundEventHandler); _eventInfo.AddEventHandler(_target, _delegate); }
static SqlClientSqlCommandSet() { var sysData = Assembly.Load("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); sqlCmdSetType = sysData.GetType("System.Data.SqlClient.SqlCommandSet"); Debug.Assert(sqlCmdSetType != null, "Could not find SqlCommandSet!"); connectionSetter = DelegateHelper.BuildPropertySetter <SqlConnection>(sqlCmdSetType, "Connection"); connectionGetter = DelegateHelper.BuildPropertyGetter <SqlConnection>(sqlCmdSetType, "Connection"); transactionSetter = DelegateHelper.BuildPropertySetter <SqlTransaction>(sqlCmdSetType, "Transaction"); commandTimeoutSetter = DelegateHelper.BuildPropertySetter <int>(sqlCmdSetType, "CommandTimeout"); batchCommandGetter = DelegateHelper.BuildPropertyGetter <SqlCommand>(sqlCmdSetType, "BatchCommand"); doAppend = DelegateHelper.BuildAction <SqlCommand>(sqlCmdSetType, "Append"); doExecuteNonQuery = DelegateHelper.BuildFunc <int>(sqlCmdSetType, "ExecuteNonQuery"); doDispose = DelegateHelper.BuildAction(sqlCmdSetType, "Dispose"); }
private static void InitializeSystems() { IEnumerable <Type> systemTypes = Assembly.GetExecutingAssembly().GetTypes().Where(t => !t.IsAbstract && t != typeof(SystemBase) && typeof(SystemBase).IsAssignableFrom(t)); systems = systemTypes.DependencySort().Select(type => (SystemBase)Activator.CreateInstance(type)).ToArray(); foreach (SystemBase system in systems) { DelegateHelper.AddToDelegate(ref SystemBase.HookLoad, system.Load); DelegateHelper.AddToDelegate(ref SystemBase.HookPostSetupContent, system.PostSetupContent); DelegateHelper.AddToDelegate(ref SystemBase.HookUnload, system.Unload); DelegateHelper.AddToDelegate(ref SystemBase.HookOnUpdate, system.OnUpdate); DelegateHelper.AddToDelegate(ref SystemBase.HookOnMenuModeChange, system.OnMenuModeChange); DelegateHelper.AddToDelegate(ref SystemBase.HookPreDrawMenu, system.PreDrawMenu); DelegateHelper.AddToDelegate(ref SystemBase.HookPostDrawMenu, system.PostDrawMenu); } }
/// <summary> /// 取数据Collection /// </summary> /// <param name="doc"></param> /// <returns></returns> public static CSAModelCollection GetCollection(Document doc) { //if (Collection != null) // return Collection; Collection = DelegateHelper.DelegateTryCatch( () => { string data = ExtensibleStorageHelper.GetData(doc, CStorageEntity, CStorageEntity.FieldOfData); return(new CSAModelCollection(data)); }, () => { return(new CSAModelCollection("")); } ); return(Collection); }
public void UnsafeOnCompleted(Action continuation) { if (this.collection == null) { throw new InvalidOperationException(); } DelegateHelper.InterlockedCombine(ref this.unsafeContinuation, continuation); if (this.IsCompleted) { if (DelegateHelper.InterlockedRemove(ref this.unsafeContinuation, continuation)) { DelegateHelper.UnsafeQueueContinuation(continuation, this.ContinueOnCapturedContext, this.Schedule); } } }
public void Setup() { var harmony = new Harmony($"{nameof(JsonSerializationTests)}.{nameof(Setup)}"); harmony.Patch(SymbolExtensions.GetMethodInfo(() => FSIOHelper.GetConfigPath()), prefix: new HarmonyMethod(DelegateHelper.GetMethodInfo(MockedGetConfigPath))); var binFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) !; var d1 = Directory.GetFiles(binFolder, "TaleWorlds*.dll"); var d2 = Directory.GetFiles(binFolder, "StoryMode*.dll"); var d3 = Directory.GetFiles(binFolder, "SandBox*.dll"); foreach (string dll in d1.Concat(d2).Concat(d3)) { Assembly.LoadFile(dll); } }
public void PropertySetter() { { string s = "a string"; Assert.Throws <InvalidOperationException>(() => DelegateHelper.CreateSetter(s, x => x.Length)); Assert.That(DelegateHelper.CreateSetter(s, x => x.Length, DelegateHelper.CreateInvalidSetterOption.NullAction), Is.Null); var p = DelegateHelper.CreateSetter(s, x => x.Length, DelegateHelper.CreateInvalidSetterOption.VoidAction); p(s, 4554); } { System.IO.StringWriter a = new System.IO.StringWriter(); var setter = DelegateHelper.CreateSetter(a, x => x.NewLine); Assert.That(a.NewLine, Is.EqualTo(Environment.NewLine)); setter(a, "Hello World!"); Assert.That(a.NewLine, Is.EqualTo("Hello World!")); } }
public Task <ICollection <MessageToken> > Execute(BPMNExecutionContext context, ICollection <MessageToken> incoming, DelegateConfigurationAggregate delegateConfiguration, CancellationToken cancellationToken) { var user = incoming.FirstOrDefault(i => i.Name == "user"); if (user == null) { throw new BPMNProcessorException("user must be passed in the request"); } var email = user.GetProperty("email"); if (string.IsNullOrWhiteSpace(email)) { throw new BPMNProcessorException("email is not passed in the request"); } var parameter = SendDelegateParameter.Build(delegateConfiguration); using (var smtpClient = new SmtpClient()) { smtpClient.EnableSsl = parameter.SmtpEnableSsl; smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = new NetworkCredential(parameter.SmtpUserName, parameter.SmtpPassword); smtpClient.Host = parameter.SmtpHost; smtpClient.Port = parameter.SmtpPort; smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; var mailMessage = new MailMessage { From = new MailAddress(parameter.FromEmail), Subject = parameter.Subject, Body = DelegateHelper.Parse(delegateConfiguration, incoming, parameter.HttpBody), IsBodyHtml = true }; mailMessage.To.Add(email.ToString()); smtpClient.Send(mailMessage); } ICollection <MessageToken> result = new List <MessageToken> { MessageToken.EmptyMessage(context.Pointer.InstanceFlowNodeId, "sendEmail") }; return(Task.FromResult(result)); }
/// <summary> /// 结束Revit控件选择 /// </summary> /// <param name="selectedElementId"></param> public void FinishSelection() { var doc = PipeAnnotationCmd.UIApplication.ActiveUIDocument.Document; switch (ActionType) { case ActionType.SelectSinglePipe: DelegateHelper.DelegateTransaction(doc, "生成单管直径标注", () => { var pipe = doc.GetElement(SelectedElementIds.First()) as Pipe; var setting = PipeAnnotationCmd.PipeAnnotationUIData.SettingForSingle; var headerPoint = setting.GetHeaderPoint(pipe); var tag = doc.Create.NewTag(View, pipe, setting.NeedLeader, TagMode.TM_ADDBY_CATEGORY, TagOrientation.Horizontal, headerPoint); tag.TagHeadPosition = headerPoint; return(true); }); break; case ActionType.SelectMultiplePipe: if (SelectedElementIds.Count < 2) { TaskDialog.Show("警告", "多管直径标注需选择两个以上的管道"); } else { DelegateHelper.DelegateTransaction(doc, "生成多管直径标注", () => { new AnnotationCreater().GenerateMultipleTagSymbol(Doc, SelectedElementIds, PipeAnnotationCmd.PipeAnnotationUIData.SettingForMultiple, true); return(true); }); } break; default: throw new NotImplementedException("暂未实现该类型的动作:" + ActionType.ToString()); } if (SelectedElementIds.Count > 0) { DialogResult = DialogResult.Retry; } else { ActionType = ActionType.Idle; } }
/// <summary> /// Subscribes all methods of the specified instance that are decorated with the <see cref="MessageRecipientAttribute"/>. /// </summary> /// <param name="instance">The instance to subscribe.</param> /// <param name="messageMediator">The message mediator. If <c>null</c>, the default will be used.</param> /// <exception cref="ArgumentNullException">The <paramref name="instance"/> is <c>null</c>.</exception> /// <exception cref="NotSupportedException">The object has non-public methods decorated with the <see cref="MessageRecipientAttribute"/>, but the /// application is not written in .NET (but in SL, WP7 or WinRT).</exception> /// <exception cref="InvalidCastException">One of the methods cannot be casted to a valid message method.</exception> public static void SubscribeRecipient(object instance, IMessageMediator messageMediator = null) { Argument.IsNotNull("instance", instance); var mediator = messageMediator ?? ServiceLocator.Default.ResolveType <IMessageMediator>(); var methodInfos = instance.GetType().GetMethodsEx(BindingFlagsHelper.GetFinalBindingFlags(true, false)); foreach (var methodInfo in methodInfos) { var customAttributes = methodInfo.GetCustomAttributesEx(typeof(MessageRecipientAttribute), true); foreach (var customAttribute in customAttributes) { var attribute = (MessageRecipientAttribute)customAttribute; var parameterInfos = methodInfo.GetParameters(); Type actionType; Type actionParameterType; switch (parameterInfos.Length) { case 0: actionType = typeof(Action <object>); actionParameterType = typeof(object); break; case 1: actionType = typeof(Action <>).MakeGenericType(parameterInfos[0].ParameterType); actionParameterType = parameterInfos[0].ParameterType; break; default: var error = string.Format("Cannot cast '{0}' to Action or Action<T> delegate type.", methodInfo.Name); Log.Error(error); throw new InvalidCastException(error); } var tag = attribute.Tag; var action = DelegateHelper.CreateDelegate(actionType, instance, methodInfo); var registerMethod = mediator.GetType().GetMethodEx("Register").MakeGenericMethod(actionParameterType); registerMethod.Invoke(mediator, new[] { instance, action, tag }); } } }
private void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { var ev = DelegateHelper.GetEvent(); try { Tuple <string, bool, List <FileInfo> > para = e.Argument.Cast <Tuple <string, bool, List <FileInfo> > >(); string pathTo = StateSaver.Default.Get <string>(Strings.tbScanDirectory, "C:\\"); var timeout = StateSaver.Default.Get <TimeSpan>(Strings.ScanCopyTimeout, TimeSpan.FromSeconds(20)); var wait = StateSaver.Default.Get <TimeSpan>(Strings.ScanCopyWait, TimeSpan.FromSeconds(2)); backgroundWorker1.ReportProgress(0); var files = (para.Item3 != null && para.Item3.Count > 0) ? para.Item3.ToArray() : new DirectoryInfo(para.Item1).GetFiles(); int count = 0; foreach (var file in files) { var newFileName = Path.Combine(pathTo, file.Name); file.CopyTo(newFileName, true); backgroundWorker1.ReportProgress(Convert.ToInt32(((float)++count / files.Length) * 100)); if (para.Item2) { if (!ev.WaitOne(timeout)) { throw new TimeoutException(); } } else { Thread.Sleep(wait); } if (backgroundWorker1.CancellationPending) { break; } } } finally { ev.Close(); } }
/// <summary> /// Initializes a new instance of the <see cref="WeakAction"/> class. /// </summary> /// <param name="target">The target.</param> /// <param name="func">The action.</param> /// <exception cref="ArgumentNullException">The <paramref name="func"/> is <c>null</c>.</exception> /// <exception cref="NotSupportedException">The <paramref name="func"/> is an anonymous delegate.</exception> public WeakFunc(object target, Func <TResult> func) : base(target) { Argument.IsNotNull("action", func); var methodInfo = func.GetMethodInfoEx(); MethodName = methodInfo.ToString(); if (MethodName.Contains("_AnonymousDelegate>")) { throw Log.ErrorAndCreateException <NotSupportedException>("Anonymous delegates are not supported because they are located in a private class"); } var targetType = target?.GetType() ?? typeof(object); var delegateType = typeof(OpenInstanceAction <>).MakeGenericType(typeof(TResult), targetType); _action = DelegateHelper.CreateDelegate(delegateType, methodInfo); }
/// <summary> /// 取数据Collection /// </summary> /// <param name="doc"></param> /// <returns></returns> public static PipeAnnotationEntityCollection GetCollection(Document doc) { if (Collection != null) { return(Collection); } Collection = DelegateHelper.DelegateTryCatch( () => { string data = ExtensibleStorageHelper.GetData(doc, CStorageEntity, CStorageEntity.FieldOfData); return(new PipeAnnotationEntityCollection(data)); }, () => { return(null); } ); return(Collection); }
public override void SaveConfig(Document doc) { DelegateHelper.DelegateTransaction(doc, "加载配置记忆", (Func <bool>)(() => { List <string> values = new List <string>(); values.Add((string)SettingForSingle.LengthFromLine_Milimeter.ToString()); values.Add(SettingForSingle.Location.ToString()); values.Add(SettingForSingle.NeedLeader.ToString()); values.Add(SettingForMultiple.LengthBetweenPipe_Milimeter.ToString()); values.Add(SettingForMultiple.Location.ToString()); values.Add(SettingForCommon.IncludeLinkPipe.ToString()); values.Add(SettingForCommon.AutoPreventCollision.ToString()); //0728长度过滤 values.Add(SettingForCommon.MinLength_Milimeter.ToString()); values.Add(SettingForCommon.FilterVertical.ToString()); PAContext.SaveSetting(doc, string.Join(Splitter, values)); return(true); })); }
protected virtual Type CreateNativeDelegateType(Type returnType, Type[] arguments, out bool isInRegistry, out Func <object, object[], object> caller) { isInRegistry = false; StaticDelegateCallback staticDelegate; if (StaticDelegateRegistry.TryFind(returnType, arguments, out staticDelegate)) { isInRegistry = true; caller = staticDelegate.Caller; return(staticDelegate.DelegateType); } else { // Else we try to do it with a dynamic call var type = DelegateHelper.NewDelegateType(returnType, arguments); caller = StaticDynamicDelegateCaller; return(type); } }
private OracleDataClientDriverBase(string driverAssemblyName, string clientNamespace) : base(clientNamespace, driverAssemblyName, clientNamespace + ".OracleConnection", clientNamespace + "." + _commandClassName) { var oracleCommandType = ReflectHelper.TypeFromAssembly(clientNamespace + "." + _commandClassName, driverAssemblyName, true); _commandBindByNameSetter = DelegateHelper.BuildPropertySetter <bool>(oracleCommandType, "BindByName"); var parameterType = ReflectHelper.TypeFromAssembly(clientNamespace + ".OracleParameter", driverAssemblyName, true); _parameterOracleDbTypeSetter = DelegateHelper.BuildPropertySetter <object>(parameterType, "OracleDbType"); var oracleDbTypeEnum = ReflectHelper.TypeFromAssembly(clientNamespace + ".OracleDbType", driverAssemblyName, true); _oracleDbTypeRefCursor = Enum.Parse(oracleDbTypeEnum, "RefCursor"); _oracleDbTypeXmlType = Enum.Parse(oracleDbTypeEnum, "XmlType"); _oracleDbTypeBlob = Enum.Parse(oracleDbTypeEnum, "Blob"); _oracleDbTypeNVarchar2 = Enum.Parse(oracleDbTypeEnum, "NVarchar2"); _oracleDbTypeNChar = Enum.Parse(oracleDbTypeEnum, "NChar"); }
/// <summary> /// 保存Collection /// </summary> /// <param name="doc"></param> public static void SaveCollection(Document doc, bool isSecondTry = false) { if (Collection == null) { return; } var data = Collection.ToData(); DelegateHelper.DelegateTryCatch( () => { ExtensibleStorageHelper.SetData(doc, CStorageEntity, CStorageEntity.FieldOfData, data); }, () => { ExtensibleStorageHelper.RemoveStorage(doc, CStorageEntity); ExtensibleStorageHelper.SetData(doc, CStorageEntity, CStorageEntity.FieldOfData, data); } ); }
static void Main(string[] args) { List <Type> allEntityClasses = (from x in Assembly.GetAssembly(typeof(Entity)) .GetTypes().Where(t => typeof(Entity).IsAssignableFrom(t)) where !x.IsAbstract && !x.IsInterface select x).ToList(); foreach (var type in allEntityClasses) { var genericType = typeof(BaseGeneric <>).MakeGenericType(type); var helper = new DelegateHelper(); var myLambda = helper.GetLambdaForType(type); var allInst = genericType.GetProperty("AllInstances").GetValue(null); if (allInst == null) { allInst = Activator.CreateInstance(genericType.GetProperty("AllInstances").PropertyType); } allInst.GetType().GetProperty("FindAll").SetValue(allInst, myLambda); } }
public void UnsafeOnCompleted(Action continuation) { if (this.conditionSource == null) { throw new InvalidOperationException(); } if (this.IsCompleted) { DelegateHelper.UnsafeQueueContinuation(continuation, this.conditionSource.ContinueOnCapturedContext, this.conditionSource.Schedule); return; } DelegateHelper.InterlockedCombine(ref this.conditionSource.unsafeContinuation, continuation); if (this.IsCompleted) { this.conditionSource.ResumeContinuations(); } }
public void WrapDelegateTest() { // Parameter and return type wrapping. Func <int, int, int> add = (a, b) => a + b; Func <object, object, object> addWrapped = DelegateHelper.WrapDelegate <Func <object, object, object> >(add); Assert.Equal(10, addWrapped(5, 5)); // One-level recursive delegate return type wrapping. Func <int, Func <int> > addFive = a => () => a + 5; Func <object, Func <object> > addFiveWrapped = DelegateHelper.WrapDelegate <Func <object, Func <object> > >(addFive); Assert.Equal(10, addFiveWrapped(5)()); // Dynamically generated methods. Expression <Func <int, int, int> > expression = (a, b) => a + b; Func <int, int, int> addDynamic = expression.Compile(); Func <object, object, object> addDynamicWrapped = DelegateHelper.WrapDelegate <Func <object, object, object> >(addDynamic); Assert.Equal(10, addDynamicWrapped(5, 5)); }
public static void smethod_2() { if (GClass82.bool_0) { return; } GClass82.bool_0 = true; GClass82.smethod_1(new Dictionary <int, LinkedList <GClass82.GClass83> >()); Logger logger = LogManager.GetLogger("Base-Net-Handlers"); logger.Info("Discovering packet handlers..."); int num = 0; foreach (Type type in typeof(GClass82).Assembly.GetTypes()) { if (typeof(GInterface4).IsAssignableFrom(type)) { GInterface4 ginterface = GClass85.smethod_0(type) as GInterface4; if (ginterface != null) { foreach (MethodInfo methodInfo in type.GetMethods(BindingFlags.Instance | BindingFlags.Public)) { ParameterInfo parameterInfo = methodInfo.GetParameters().SingleOrDefault <ParameterInfo>(); int num2; if (parameterInfo != null && typeof(GInterface0).IsAssignableFrom(parameterInfo.ParameterType) && GClass86.smethod_0(parameterInfo.ParameterType, out num2)) { IDictionary <int, LinkedList <GClass82.GClass83> > d = GClass82.dictionary_0; int key = num2; GClass82.GClass83 gclass = new GClass82.GClass83(); gclass.method_3(ginterface); gclass.method_1(DelegateHelper.ConstructDelegateCallVoid(methodInfo, type)); d.Append(key, gclass); num++; } } } } } logger.Info("Found {count} packet handlers", num); }
public override void LoadConfig(Document doc) { IsSuccess = DelegateHelper.DelegateTransaction(doc, "标注族加载", () => { return(PAContext.LoadFamilySymbols(doc)); });// && PipeAnnotationContext.LoadParameterOfSymbols(doc); if (!IsSuccess) { TaskDialog.Show("错误", "加载必要的族时失败"); return; } //PipeAnnotationContext.LoadParameterOfSymbols(doc); DelegateHelper.DelegateTransaction(doc, "加载配置记忆", () => { SettingForSingle = new SinglePipeAnnotationSettings(this); SettingForMultiple = new MultiPipeAnnotationSettings(this); SettingForCommon = new CommonAnnotationSettings(); var data = PAContext.GetSetting(doc); var values = data.Split(Splitter.ToCharArray().First()); if (values.Count() >= 7) { SettingForSingle.LengthFromLine_Milimeter = Convert.ToInt32(values[0]); SettingForSingle.Location = (SinglePipeTagLocation)Enum.Parse(typeof(SinglePipeTagLocation), values[1]); SettingForSingle.NeedLeader = Convert.ToBoolean(values[2]); SettingForMultiple.LengthBetweenPipe_Milimeter = Convert.ToInt32(values[3]); SettingForMultiple.Location = (MultiPipeTagLocation)Enum.Parse(typeof(MultiPipeTagLocation), values[4]); SettingForCommon.IncludeLinkPipe = Convert.ToBoolean(values[5]); SettingForCommon.AutoPreventCollision = Convert.ToBoolean(values[6]); //0728长度过滤 if (values.Count() > 7) { SettingForCommon.MinLength_Milimeter = Convert.ToInt32(values[7]); SettingForCommon.FilterVertical = Convert.ToBoolean(values[8]); } } return(true); }); IsSuccess = true; }
// public static Action<EventHandler<TEvent>> StaticEventAdd<TEvent>(this Type source, string eventName) //#if NET35||NET4||PORTABLE // where TEvent : EventArgs //#endif // { // var eventInfo = source.GetEventInfo(eventName); // return eventInfo?.AddMethod.CreateDelegate<Action<EventHandler<TEvent>>>(); // } private static Action <TSource, TDelegate> EventAccessor <TSource, TDelegate> (string eventName, string accessorName) where TDelegate : class { var sourceType = typeof(TSource); var accessor = sourceType.GetEventAccessor(eventName, accessorName); if (accessor != null) { var handlerType = accessor.GetParameters()[0].ParameterType; if (typeof(TDelegate) == handlerType) { var eventArgsType = typeof(TDelegate).GetDelegateSecondParameter(); accessor.IsEventArgsTypeCorrect(eventArgsType); return(accessor.CreateDelegate <Action <TSource, TDelegate> >()); } DelegateHelper.IsCompatible <TDelegate>(handlerType); return(EventAccessorImpl <Action <TSource, TDelegate> >(typeof(TSource), eventName, accessorName)); } return(null); }
/// <summary> /// 保存Collection /// </summary> /// <param name="doc"></param> public static bool Save(Document doc) { if (Collection == null) { return(false); } var data = Collection.ToData(); return(DelegateHelper.DelegateTryCatch( () => { ExtensibleStorageHelper.SetData(doc, CStorageEntity, CStorageEntity.FieldOfData, data); return true; }, () => { ExtensibleStorageHelper.RemoveStorage(doc, CStorageEntity); ExtensibleStorageHelper.SetData(doc, CStorageEntity, CStorageEntity.FieldOfData, data); return false; } )); }
private void InnerInitialize <TType, TProperty>() { Default = default(TProperty); var propertyInfo = PropertyInfo; if (propertyInfo.GetGetMethod() != null) { var d = DelegateHelper.CreateGetMemberDelegate <TType, TProperty>(PropertyInfo.Name); if (d != null) { getter = o => d((TType)o); } } if (propertyInfo.GetSetMethod() != null) { var d = DelegateHelper.CreateSetMemberDelegate <TType, TProperty>(PropertyInfo.Name); if (d != null) { setter = (o, v) => d((TType)o, (TProperty)v); } } }
/// <summary> /// Bind grid collection. /// </summary> /// <param name="controllerContext">The context within which the controller operates. The context information includes the controller, HTTP content, request context, and route data.</param> /// <param name="bindingContext">The context within which the model is bound. The context includes information such as the model object, model name, model type, property filter, and value provider.</param> /// <returns>A <see cref="IEnumerable{T}" /> binded with its corresponding values from the binding context value provider.</returns> public object BindGrid(ControllerContext controllerContext, ModelBindingContext bindingContext) { #if DEBUG var step = MiniProfiler.Current.Step("InfrastructureModelBinder.BindGrid"); try { #endif var elementType = bindingContext.ModelType.HasElementType ? bindingContext.ModelType.GetElementType() : bindingContext.ModelType.GetGenericArguments().FirstOrDefault(); if (elementType == null) { return(null); } var elementInstance = DelegateHelper.CreateConstructorDelegate(elementType)(); var elementMetadata = System.Web.Mvc.ModelMetadataProviders.Current.GetMetadataForType(() => elementInstance, elementType); if (elementMetadata.GetAttribute <SerializableAttribute>() != null) { var listAccessor = (IList)DelegateHelper.CreateConstructorDelegate(typeof(List <>).MakeGenericType(new[] { elementType }))(); return(BindSerializedGrid(controllerContext, bindingContext, listAccessor)); } return(base.BindModel(controllerContext, bindingContext)); #if DEBUG } finally { if (step != null) { step.Dispose(); } } #endif }
public EndMethodDelegate BeforeWrappedMethod(TraceMethodInfo traceMethodInfo) { var dbCommand = (DbCommand)traceMethodInfo.InvocationTarget; var scope = _tracer.BuildSpan("mysql.command") .WithTag(Tags.SpanKind, Tags.SpanKindClient) .WithTag(Tags.Component, "MySqlConnector") .WithTag(Tags.DbInstance, dbCommand.Connection.ConnectionString) .WithTag(Tags.DbStatement, dbCommand.CommandText) .WithTag(TagMethod, traceMethodInfo.MethodBase.Name) .StartActive(false); traceMethodInfo.TraceContext = scope; return(delegate(object returnValue, Exception ex) { DelegateHelper.AsyncMethodEnd(Leave, traceMethodInfo, ex, returnValue); // for async method , at method end restore active scope, important var tempScope = (IScope)traceMethodInfo.TraceContext; tempScope.Dispose(); }); }
protected virtual Type CreateNativeDelegateType(Type returnType, Type[] arguments, out bool isInRegistry, out Func<object, object[], object> caller) { isInRegistry = false; StaticDelegateCallback staticDelegate; if (StaticDelegateRegistry.TryFind(returnType, arguments, out staticDelegate)) { isInRegistry = true; caller = staticDelegate.Caller; return staticDelegate.DelegateType; } else { #if BURST_TESTS_ONLY // Else we try to do it with a dynamic call var type = DelegateHelper.NewDelegateType(returnType, arguments); caller = StaticDynamicDelegateCaller; return type; #else throw new Exception("Couldn't find delegate in static registry and not able to use a dynamic call."); #endif } }