public static void IndexerSet(Type type, object obj, object value, bool throwOnPropertyNotExist, params object[] indexerParameters) { if (indexerParameters == null || indexerParameters.Length <= 0) { throw new ArgumentException("索引器必须要有参数.", "indexerParamTypes"); } IInvoke invoker = InvokerFactory.GetInvoker(type); Type[] indexerParamTypes = new Type[indexerParameters.Length]; for (int i = 0; i < indexerParameters.Length; i++) { indexerParamTypes[i] = indexerParameters[i].GetType(); } if (!ExistIndexerSet(type, indexerParamTypes)) { if (throwOnPropertyNotExist) { string tmp = string.Empty; foreach (Type t in indexerParamTypes) { if (tmp.Length > 0) { tmp += ", "; } tmp += t.FullName; } throw new ApplicationException("无法找到类型'" + type.FullName + "'的public的可读的索引器[" + tmp + "]."); } return; } invoker.IndexerSet(obj, value, indexerParameters); }
public NullSourceContext(IDescribeMappableProperty sourceProperty, ICreateValueAssignment valueAssignments, IInvoke invoke, IActivate activate) { this.valueAssignments = valueAssignments; this.invoke = invoke; this.activate = activate; SourceType = sourceProperty.PropertyType; Source = null; }
public NullSourceContext(IDescribeMappableProperty sourceProperty, ICreateValueAssignment valueAssignments, IInvoke invoke, IActivate activate) { this.valueAssignments = valueAssignments; this.invoke = invoke; this.activate = activate; SourceType = sourceProperty.PropertyType; Source = null; }
private static void Main() { //检测.net版本。 if (!VersionCheck.Check4FromRegistry()) { MessageBox.Show(".net版本过低。本程序需要运行在.net4.0或.net4.0以后的版本!", "提示"); return; } App.Instance.ApplicationDirectory = Environment.CurrentDirectory + "\\"; //同时只能运行一个实例。 if (SingletonApp.IsMutexExsited) { SingletonApp.ShowRunningInstance(); return; } //指定运行日志要保存的目录 RunningLog.Start(App.Instance.ApplicationDirectory + "\\history\\"); //判断当前登录用户是否为管理员 if (WindowsAuthority.IsAdministrator) { //设置应用程序退出和异常的事件 Application.ApplicationExit += App.Instance.RaiseApplicationExist; Application.ThreadExit += App.Instance.RaiseMainThreadExist; Application.ThreadException += (o, e) => MessageBox.Show(e.Exception.ToString()); try { //运行应用程序内核 App.Instance.BuildModule(); App.Instance.Initialize(); App.Instance.RaiseStarting(); //启动Ui界面 IInvoke invoker = ObjectGenerator.Create("FlightViewerUI.dll", "BinHong.FlightViewerUI.UiInvoker") as IInvoke; invoker.Invoke(); } catch (Exception e) { string msg = e.Message; #if DEBUG msg = e.Message + e.StackTrace; #endif RunningLog.Record(LogType.System, LogLevel.Error, msg); Thread.Sleep(200); MessageBox.Show(msg); } finally { SingletonApp.ReleaseMutex(); } } else { WindowsAuthority.RunAsAdministrator(Application.ExecutablePath); } }
public ValueAssignment(object destination, IDescribeMappableProperty destinationProperty,IValueConverterContainer valueConverters, IInvoke invoke) { if (destinationProperty == null) throw new ArgumentNullException("destinationProperty"); this.destination = destination; this.destinationProperty = destinationProperty; this.invoke = invoke; this.valueConverters = valueConverters ?? NullValueConverterContainer.Instance; }
public static bool ExistIndexerSet(Type type, params Type[] indexerParamTypes) { if (indexerParamTypes == null || indexerParamTypes.Length <= 0) { throw new ArgumentException("索引器必须要有参数.", "indexerParamTypes"); } IInvoke invoker = InvokerFactory.GetInvoker(type); return(invoker.ExistPropertyOrIndexerSet("Item", indexerParamTypes)); }
public ValueAssignment(object destination, IDescribeMappableProperty destinationProperty, IValueConverterContainer valueConverters, IInvoke invoke) { if (destinationProperty == null) { throw new ArgumentNullException("destinationProperty"); } this.destination = destination; this.destinationProperty = destinationProperty; this.invoke = invoke; this.valueConverters = valueConverters ?? NullValueConverterContainer.Instance; }
public DefaultInvokeEvaluator(IInvoke invoke) { _invoke = invoke ?? throw new ArgumentNullException(nameof(invoke)); TypeExpressionEvaluator = invoke.TypeExpression?.As <IStringEvaluator>(); SourceExpressionEvaluator = invoke.SourceExpression?.As <IStringEvaluator>(); ContentExpressionEvaluator = invoke.Content?.Expression?.As <IObjectEvaluator>(); ContentBodyEvaluator = invoke.Content?.Body?.As <IValueEvaluator>(); IdLocationEvaluator = invoke.IdLocation?.As <ILocationEvaluator>(); NameEvaluatorList = invoke.NameList.AsArrayOf <ILocationExpression, ILocationEvaluator>(); ParameterList = invoke.Parameters.AsArrayOf <IParam, DefaultParam>(); }
public static bool ExistPropertySet(Type type, string propertyName, bool ignoreCase) { IInvoke invoker = InvokerFactory.GetInvoker(type); if (ignoreCase) { propertyName = GetPropertyNameIgnoreCase(type, propertyName); } if (propertyName == null || propertyName.Trim().Length <= 0 || propertyName == "Item") { return(false); } return(invoker.ExistPropertyOrIndexerSet(propertyName)); }
public static Type GetPropertyType(Type type, string propertyName, bool ignoreCase, bool throwOnPropertyNotExist) { IInvoke invoker = InvokerFactory.GetInvoker(type); if (ignoreCase) { propertyName = GetPropertyNameIgnoreCase(type, propertyName); } Type rst = (propertyName == null || propertyName.Trim().Length <= 0) ? null : invoker.GetPropertyType(propertyName); if (rst == null && throwOnPropertyNotExist) { throw new ApplicationException("无法找到类型'" + type.FullName + "'的公开实例属性" + propertyName + "."); } return(rst); }
public InvokeNode(DocumentIdNode documentIdNode, IInvoke invoke) { documentIdNode.SaveToSlot(out _documentIdSlot); _invoke = invoke; Finalize = invoke.Finalize?.As <FinalizeNode>(); var startInvokeEvaluator = invoke.As <IStartInvokeEvaluator>(); Infra.NotNull(startInvokeEvaluator); _startInvokeEvaluator = startInvokeEvaluator; var cancelInvokeEvaluator = invoke.As <ICancelInvokeEvaluator>(); Infra.NotNull(cancelInvokeEvaluator); _cancelInvokeEvaluator = cancelInvokeEvaluator; }
public static IInvoke GetInvoker(Type type) { if (!s_Cache.ContainsKey(type)) { lock (s_SyncObject) { if (!s_Cache.ContainsKey(type)) { Type implType = EmitHelper.CreateType(typeof(IInvoke), new InvokerEmitter(type), InvokerFactory.SaveDll, type.FullName + "_Invoker"); IInvoke invoker = (IInvoke)Activator.CreateInstance(implType); s_Cache.Add(type, invoker); return(invoker); } } } return(s_Cache[type]); }
public static void PropertySet(Type type, object obj, string propertyName, object value, bool ignoreCase, bool throwOnPropertyNotExist) { IInvoke invoker = InvokerFactory.GetInvoker(type); if (ignoreCase) { propertyName = GetPropertyNameIgnoreCase(type, propertyName); } if (propertyName == null || propertyName.Trim().Length <= 0 || !ExistPropertySet(type, propertyName)) { if (throwOnPropertyNotExist) { throw new ApplicationException("无法找到类型'" + type.FullName + "'的公开实例属性" + propertyName + "."); } return; } invoker.PropertySet(obj, propertyName, value); }
public DefaultResolutionContext(object source, object destination, IContextualizeResolution contextualizer, ICreateValueAssignment valueAssignments, IInvoke invoke) { if (source == null) throw new ArgumentNullException("source"); if (destination == null) throw new ArgumentNullException("destination"); if (valueAssignments == null) throw new ArgumentNullException("valueAssignments"); this.source = source; this.destination = destination; this.contextualizer = contextualizer; this.valueAssignments = valueAssignments; this.invoke = invoke; }
///// <summary> ///// Выполнение act в потоке sender.StaDispatcher асинхронно в конструкции try..catch ///// </summary> ///// <param name="sender">Расширяемый интерфейс</param> ///// <param name="act">Действие</param> ///// <param name="onError">Метод обработки исключений</param> ///// <param name="priotity">Приоритет задания : /////<para/>Inactive - Элементы работы поставлены в очередь, но не выполняются. /////<para/>SystemIdle - Элементы работы направлены в поток интерфейса пользователя во время бездействия системы. Это низший приоритет элементов, выполняемых в данный момент. /////<para/>ApplicationIdle - Элементы работы доставлены в поток интерфейса пользователя во время бездействия приложения. /////<para/>ContextIdle - Элементы работы доставлены в поток интерфейса пользователя после того, как выполнены элементы с более высоким приоритетом. /////<para/>Background - Элементы работы доставлены после обработки макета, прорисовки и обработки входных данных. /////<para/>Input - Элементы работы доставлены в поток интерфейса пользователя с тем же приоритетом, что и входные данные пользователя. /////<para/>Loaded - Элементы работы доставлены после завершения обработки макета и прорисовки. /////<para/>Render - Элементы работы доставлены в поток интерфейса пользователя с тем же приоритетом, что и механизм визуализации. /////<para/>DataBind - Элементы работы доставлены в поток интерфейса пользователя с тем же приоритетом, что и привязка данных. /////<para/>Normal - Элементы работы доставлены в поток интерфейса пользователя с обычным приоритетом. Это приоритет, с которым должно доставляться большинство рабочих элементов приложения. /////<para/>Send - Элементы работы доставлены в поток интерфейса пользователя с высшим ///// </param> //public static DispatcherOperation AppBeginInvoke(this IInvoke sender, Action act, Action<Exception> onError = null, DispatcherPriority priotity = DispatcherPriority.Background) //{ // try // { // //if (IVM_Invoke_Extention.CheckAccess(null))act(); // return UIDispatcher.BeginInvoke((Action)(() => // { // try // { // act(); // } // catch (Exception ex) // { // if (onError != null) // onError(ex); // else // { // sender.Error(ex, "() inner"); // } // } // }), priotity); // } // catch (Exception ex) // { // if (onError != null) // onError(ex); // else // { // sender.Error(ex, "()"); // } // } // return null; //} ///// <summary> ///// Выполнение act в потоке sender.StaDispatcher ///// </summary> ///// <param name="sender">Расширяемый интерфейс</param> ///// <param name="act">Действие</param> ///// <param name="onError">Метод обработки исключений</param> //public static R AppInvoke<R>(this IInvoke sender, Func<R> act, Func<Exception, R> onError = null) //{ // return sender.AppInvoke<R>(act, TimeSpan.FromMilliseconds(-1.0), onError); //} ///// <summary> ///// Выполнение act в потоке sender.StaDispatcher ///// </summary> ///// <param name="sender">Расширяемый интерфейс</param> ///// <param name="act">Действие</param> ///// <param name="timeout">Время ожидания действия</param> ///// <param name="onError">Метод обработки исключений</param> //public static R AppInvoke<R>(this IInvoke sender, Func<R> act, TimeSpan timeout, Func<Exception, R> onError = null) //{ // try // { // if (IVM_Invoke_Extention.CheckAccess(null)) // return act(); // else // return (R)UIDispatcher.Invoke(act, timeout); // } // catch (Exception ex) // { // if (onError != null) // { // return onError(ex); // } // else // { // sender.Error(ex, "()"); // throw; // } // } //} /// <summary> /// Выполнение act в главном потоке /// </summary> /// <param name="sender">Расширяемый интерфейс</param> /// <param name="act">Действие</param> /// <param name="onError">Метод обработки исключений</param> public static void AppInvoke(this IInvoke sender, Action act, Action <Exception> onError = null) { try { Context.Exec(act); } catch (Exception ex) { if (onError != null) { onError(ex); } else { sender.Error(ex, "()"); throw; } } }
/// <summary> /// Выполнение задачи в ThreadPool с подсчетом времени, запускат onFynally/onError в контексте вызывавшего потока /// </summary> /// <param name="sender">Расширяемый интерфейс</param> /// <param name="doWork">Метод, выполняющий полезную работу</param> /// <param name="onError">Метод, вызываемый при ошибке</param> /// <param name="onFynally"></param> public static void GoAsync(this IInvoke sender, Action doWork, Action <TimeSpan> onFynally = null, Action <Exception> onError = null) { Contract.NotNull(doWork, "act"); Contract.NotNull(onFynally, "onFynally"); var res = SynchronizationContext.Current; ThreadPool.QueueUserWorkItem(o => { var context = o as SynchronizationContext; var sw = Stopwatch.StartNew(); try { doWork(); } catch (Exception ex) { if (onError == null) { throw; } //onError(ex); context.Exec(onError, ex); } finally { sw.Stop(); if (onFynally != null) { //onFynally(sw.Elapsed); context.Exec(onFynally, sw.Elapsed); } } }, res); //return res; }
/// <summary> /// Выполнение задачи в ThreadPool с подсчетом времени, запускат onFynally/onError в контексте вызывавшего потока /// Выполнение задачи в Task с подсчетом времени /// </summary> /// <param name="sender">Расширяемый интерфейс</param> /// <param name="doWork"></param> /// <param name="onComplete"></param> /// <param name="onError"></param> /// <param name="onFynally"></param> public static void GoAsync <R>(this IInvoke sender, Func <R> doWork, Action <R> onComplete, Action <TimeSpan> onFynally = null, Action <Exception> onError = null) { Contract.NotNull(null != doWork, "act"); Contract.NotNull(null != onComplete, "onComplete"); //Contract.NotNull(null != onFynally, "onFynally"); ThreadPool.QueueUserWorkItem(o => { var context = o as SynchronizationContext; var sw = Stopwatch.StartNew(); try { var r = doWork(); //onComplete(r); context.Exec(onComplete, r); return; } catch (Exception ex) { if (onError == null) { throw; } //onError(ex); context.Exec(onError, ex); } finally { sw.Stop(); if (onFynally != null) { //onFynally(sw.Elapsed); context.Exec(onFynally, sw.Elapsed); } } }, SynchronizationContext.Current); }
public DefaultResolutionContext(object source, object destination, IContextualizeResolution contextualizer, ICreateValueAssignment valueAssignments, IInvoke invoke) { if (source == null) { throw new ArgumentNullException("source"); } if (destination == null) { throw new ArgumentNullException("destination"); } if (valueAssignments == null) { throw new ArgumentNullException("valueAssignments"); } this.source = source; this.destination = destination; this.contextualizer = contextualizer; this.valueAssignments = valueAssignments; this.invoke = invoke; }
public static Type GetIndexerType(Type type, bool throwOnIndexerNotExist, params Type[] indexerParamTypes) { if (indexerParamTypes == null || indexerParamTypes.Length <= 0) { throw new ArgumentException("索引器必须要有参数.", "indexerParamTypes"); } IInvoke invoker = InvokerFactory.GetInvoker(type); Type rst = invoker.GetIndexerType(indexerParamTypes); if (rst == null && throwOnIndexerNotExist) { string tmp = string.Empty; foreach (Type t in indexerParamTypes) { if (tmp.Length > 0) { tmp += ", "; } tmp += t.FullName; } throw new ApplicationException("无法找到类型'" + type.FullName + "'中参数为'" + tmp + "'的public索引器."); } return(rst); }
/// <summary> /// Выполняет указанное действие по истечению указанного времени /// </summary> /// <param name="sender">Расширяемый интерфейс</param> /// <param name="action"></param> /// <param name="delaySecond"></param> public static Timer ActionDelay(this IInvoke sender, Action action, int delaySecond) { return(new Timer(o => (o as SynchronizationContext).Exec(action), SynchronizationContext.Current, delaySecond * 1000, -1)); }
public static object CreateInstance(Type type, params object[] parameters) { IInvoke invoker = InvokerFactory.GetInvoker(type); return(invoker.CreateInstance(parameters)); }
public ValueAssignments(IValueConverterContainer converters, IInvoke invoke) { this.converters = converters; this.invoke = invoke; }
public static object MethodInvoke(Type type, object obj, string methodName, params object[] parameters) { IInvoke invoker = InvokerFactory.GetInvoker(type); return(invoker.MethodInvoke(obj, methodName, parameters)); }
private void Invoke(IInvoke invoke) { var targetSocket = GetSocket(invoke.Target); if (Util.IsNull(targetSocket)) { return; } var type = GetSocketType(targetSocket); var target = GetSocketValue(targetSocket); var flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy | BindingFlags.Public; object value; object[] args; switch (invoke.InvokeType) { case InvokeType.GetField: var gField = type.GetField(invoke.MemberName, flags); value = gField.GetValue(target); SetSocketValue(invoke.Result, value); break; case InvokeType.SetField: var sField = type.GetField(invoke.MemberName, flags); value = GetSocketValue(invoke.Args[0]); sField.SetValue(target, value); break; case InvokeType.GetProperty: var gProperty = type.GetProperty(invoke.MemberName, flags); args = BuildArgs(0, invoke.Args); value = gProperty.GetValue(target, args); SetSocketValue(invoke.Result, value); break; case InvokeType.SetProperty: var sProperty = type.GetProperty(invoke.MemberName, flags); args = BuildArgs(1, invoke.Args); value = GetSocketValue(invoke.Args[0]); sProperty.SetValue(target, value, args); break; case InvokeType.CallMethod: var method = type.GetMethod(invoke.MemberName, flags); args = BuildArgs(0, invoke.Args); value = method.Invoke(target, args); if (method.ReturnType != typeof(void)) { SetSocketValue(invoke.Result, value); } break; default: var msg = string.Format( "Invoke type {0} not supported!", invoke.InvokeType); throw new InvalidOperationException(msg); } }
public DefaultContextualizer(IActivate activate, ICreateValueAssignment valueAssignments, IInvoke invoke) { this.activate = activate; this.valueAssignments = valueAssignments; this.invoke = invoke; }
public DefaultContextualizer(IActivate activate, ICreateValueAssignment valueAssignments, IInvoke invoke) { this.activate = activate; this.valueAssignments = valueAssignments; this.invoke = invoke; }
void Initialize() { this._invokePattern = new InvokeImplementation(uiObject: this); }
public ValueAssignments(IValueConverterContainer converters, IInvoke invoke) { this.converters = converters; this.invoke = invoke; }
public void Add(IInvoke routine) { routines.Add(routine); }
public static string GetPropertyNameIgnoreCase(Type type, string propertyName) { IInvoke invoker = InvokerFactory.GetInvoker(type); return(invoker.GetPropertyNameIgnoreCase(propertyName)); }
public CloningMapCommand(IInvoke invoke, IMapCommand inner) { this.inner = inner; this.invoke = invoke; }
public void Add(IInvoke invoker) { _subscribers.Add(invoker); }
void Initialize() { this._expandCollapsePattern = new ExpandCollapseImplementation(uiObject: this); this._invokePattern = new InvokeImplementation(uiObject: this); }