예제 #1
0
 public void Execute(ActionExecutionContext context)
 {
     // Server Side Error
     var faultException = Error as System.ServiceModel.FaultException<ServiceFault>;
     if (faultException != null) {
         if (faultException.Reason.ToString() == "Unauthorized") {
             Coroutine.BeginExecute(IoC.Get<IShell>().ExecuteSessionTimeout(), null, null);
         } else {
             if (Manual)
                 Caliburn.Micro.Execute.OnUIThread(()=> WindowManager.Value.Alert(faultException.Detail.Type, faultException.Detail.Message));
             else
                 WindowManager.Value.Alert(faultException.Detail.Type, faultException.Detail.Message);
         }
     } else {
         // General Exception
         var communicationError = Error as System.ServiceModel.CommunicationException;
         if (communicationError != null) {
             if (Manual)
                 Caliburn.Micro.Execute.OnUIThread(() => WindowManager.Value.Alert(faultException.Detail.Type, faultException.Detail.Message));
             else
                 WindowManager.Value.Alert("Communication Error", ValidationMessageResources.CommunicationError);
         } else {
             if (faultException != null) {
                 // Catch All other Errors
                 if (Manual)
                     Caliburn.Micro.Execute.OnUIThread(() => WindowManager.Value.Alert(faultException.Detail.Type, faultException.Detail.Message));
                 else
                     WindowManager.Value.Alert("Error", Error.Message);
             }
         }
     }
     // Execute Last
     if (!Manual)
         Caliburn.Micro.Execute.OnUIThread(() => Completed(this, new ResultCompletionEventArgs()));
 }
예제 #2
0
파일: LoadCatalog .cs 프로젝트: stiano/sl4
        public void Execute(ActionExecutionContext context)
        {
            DeploymentCatalog catalog;

            if (Catalogs.TryGetValue(_uri, out catalog))
                Completed(this, new ResultCompletionEventArgs());
            else
            {
                catalog = new DeploymentCatalog(_uri);
                catalog.DownloadCompleted += (s, e) =>
                                                 {
                                                     if (e.Error == null)
                                                     {
                                                         Catalogs[_uri] = catalog;
                                                         Catalog.Catalogs.Add(catalog);
                                                         catalog.Parts
                                                             .Select(part => ReflectionModelServices.GetPartType(part).Value.Assembly)
                                                             .Where(assembly => !AssemblySource.Instance.Contains(assembly))
                                                             .Apply(x => AssemblySource.Instance.Add(x));
                                                     }
                                                     else Loader.Hide().Execute(context);

                                                     Completed(this, new ResultCompletionEventArgs
                                                                         {
                                                                             Error = e.Error,
                                                                             WasCancelled = false
                                                                         });
                                                 };

                catalog.DownloadAsync();
            }
        }
예제 #3
0
        public void Execute(ActionExecutionContext context)
        {
            var shell = IoC.Get<IShell>();
            shell.IsBusy = _isBusy;

            Completed(this, new ResultCompletionEventArgs());
        }
예제 #4
0
        public override void Execute(ActionExecutionContext context)
        {
            var result = MessageBox.Show(this.messageBoxText, this.caption,
                this.showCancel ? MessageBoxButton.OKCancel : MessageBoxButton.OK);

            this.OnCompleted(new ResultCompletionEventArgs());
        }
예제 #5
0
        ///<summary>
        ///  Uses the action pipeline to invoke the method.
        ///</summary>
        ///<param name="target"> The object instance to invoke the method on. </param>
        ///<param name="methodName"> The name of the method to invoke. </param>
        ///<param name="view"> The view. </param>
        ///<param name="source"> The source of the invocation. </param>
        ///<param name="eventArgs"> The event args. </param>
        ///<param name="parameters"> The method parameters. </param>
        public static void Invoke(object target, string methodName, DependencyObject view = null, FrameworkElement source = null, object eventArgs = null, object[] parameters = null)
        {
            var context = new ActionExecutionContext
            {
                Target = target,
#if WinRT
                Method = target.GetType().GetRuntimeMethods().Single(m => m.Name == methodName),
#else
                Method = target.GetType().GetMethod(methodName),
#endif
                Message = new ActionMessage
                {
                    MethodName = methodName
                },
                View      = view,
                Source    = source,
                EventArgs = eventArgs
            };

            if (parameters != null)
            {
                parameters.Apply(x => context.Message.Parameters.Add(x as Parameter ?? new Parameter {
                    Value = x
                }));
            }

            ActionMessage.InvokeAction(context);
        }
예제 #6
0
        public override void Execute(ActionExecutionContext context)
        {
            Window window = Window.GetWindow(context.View);
            if (window != null) window.Close();

            base.Execute(context);
        }
예제 #7
0
 public void Execute(ActionExecutionContext context)
 {
     var currentUser = SessionInfo.Instance.CurrentUser;
     service = new ChannelFactory<IUserService>(ServiceConfig.UserServiceEndpoint);
     var channel = service.CreateChannel();
     ThreadPool.QueueUserWorkItem(x => channel.BeginAuthenticate(currentUser.Username, Security.GetSha2Hash(currentPassword.Trim(), currentUser.Username.Trim()), new AsyncCallback(AuthenticateResponse), channel));
 }
예제 #8
0
 public void Execute(ActionExecutionContext context)
 {
     var currentUser = SessionInfo.Instance.CurrentUser;
     service = new ChannelFactory<IUserService>(ServiceConfig.UserServiceEndpoint);
     var channel = service.CreateChannel();
     ThreadPool.QueueUserWorkItem(x => channel.BeginSaveNewPin(Security.GetSha2Hash(newPin.Trim(), currentUser.Username.Trim()), AppLib.GetIdentification(), new AsyncCallback(SaveNewPinResponse), channel));
 }
        public void Execute(ActionExecutionContext context = null)
        {
            Result = MessageBox.Show(_message, _caption, _button);

            if (Completed != null)
                Completed(this, new ResultCompletionEventArgs());
        }
예제 #10
0
                /// <summary>
                ///   Evaluates the parameter.
                /// </summary>
                /// <param name = "expression">The expression.</param>
                /// <param name = "context">The context.</param>
                /// <param name = "resultType">Type of the result.</param>
                /// <returns>The evaluated parameter.</returns>
                private static object EvaluateParameter(string expression, ActionExecutionContext context, Type resultType)
                {
                    try
                    {
                        var index      = 0;
                        var parameters = new ParameterExpression[MessageBinder.SpecialValues.Count];
                        var values     = new object[MessageBinder.SpecialValues.Count];
                        foreach (var pair in MessageBinder.SpecialValues)
                        {
                            var name = "@" + index;
                            expression = expression.Replace(pair.Key, name);
                            var value = pair.Value(context);
                            parameters[index] = Expression.Parameter(GetParameterType(value), name);
                            values[index]     = value;
                            index++;
                        }

                        var exp = DynamicExpression.ParseLambda(parameters, resultType, expression);
                        return(exp.Compile().DynamicInvoke(values));
                    }
                    catch (Exception exc)
                    {
                        LogManager.GetLog(typeof(MessageBinder)).Error(exc);
                        return(null);
                    }
                }
예제 #11
0
        /// <summary>
        /// Called by the bootstrapper's constructor at runtime to start the framework.
        /// </summary>
        protected virtual void StartRuntime()
        {
            Execute.InitializeWithDispatcher();
            EventAggregator.DefaultPublicationThreadMarshaller = Execute.OnUIThread;

            EventAggregator.HandlerResultProcessing = (target, result) => {
                var coroutine = result as IEnumerable <IResult>;
                if (coroutine != null)
                {
                    var viewAware = target as IViewAware;
                    var view      = viewAware != null?viewAware.GetView() : null;

                    var context = new ActionExecutionContext {
                        Target = target, View = (DependencyObject)view
                    };

                    Coroutine.BeginExecute(coroutine.GetEnumerator(), context);
                }
            };

            AssemblySource.Instance.AddRange(SelectAssemblies());

            if (useApplication)
            {
                Application = Application.Current;
                PrepareApplication();
            }

            Configure();
            IoC.GetInstance     = GetInstance;
            IoC.GetAllInstances = GetAllInstances;
            IoC.BuildUp         = BuildUp;
        }
예제 #12
0
        /// <summary>
        /// Executes the result using the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public void Execute(ActionExecutionContext context)
        {
            if (string.IsNullOrEmpty(LastFmDataAccess.ApiKey))
            {
                var args = new ResultCompletionEventArgs
                {
                    Error = new Exception("Can't execute query. No API-Key found."),
                    WasCancelled = true
                };
                Completed(this, args);
                EventAgg.Publish(new ErrorMessage(args));
            }

            var stopWatch = new StopWatch(10000);
            var webClient = new WebClient();

            webClient.OpenReadCompleted += (sender, e) =>
            {
                stopWatch.Stop();
                if (e.Error == null)
                {
                    XDocument doc = XDocument.Load(e.Result);
                    XElement ee = doc.Descendants("error").FirstOrDefault();

                    if (ee != null)
                    {
                        stopWatch.Stop();
                        Completed(this, new ResultCompletionEventArgs
                        {
                            Error = new Exception(ee.Value),
                            WasCancelled = false
                        });
                        return;
                    }
                    XmlResult = doc.Root;

                    if (repository != null && addToRepository != LastFmRepository.RepositoryTypes.None)
                        repository.AddData(XmlResult, addToRepository);


                    Completed(this, new ResultCompletionEventArgs());
                    return;
                }
                var args = new ResultCompletionEventArgs { Error = e.Error, WasCancelled = false };
                Completed(this, args);
                EventAgg.Publish(new ErrorMessage(args));
            };
            stopWatch.StopWatchEnded += (sender, e) =>
            {
                var args = new ResultCompletionEventArgs
                {
                    Error = new TimeoutException("Timeout of " + GetType().Name),
                    WasCancelled = false
                };
                EventAgg.Publish(new ErrorMessage(args));
                Completed(this, args);
            };
            stopWatch.Start();
            webClient.OpenReadAsync(new Uri(searchString));
        }
        public void Execute(ActionExecutionContext context)
        {
            Exception error = null;
            var worker = new BackgroundWorker();

            worker.DoWork += (s, e) =>
            {
                try
                {
                    _work();
                }
                catch (Exception ex)
                {
                    error = ex;
                }
            };

            worker.RunWorkerCompleted += (s, e) =>
            {
                if (error == null && _onSuccess != null)
                    _onSuccess.OnUIThread();

                if (error != null && _onFail != null)
                {
                    Caliburn.Micro.Execute.OnUIThread(() => _onFail(error));
                }

                Completed(this, new ResultCompletionEventArgs { Error = error });
            };
            worker.RunWorkerAsync();
        }
예제 #14
0
        ///<summary>
        ///  Uses the action pipeline to invoke the method.
        ///</summary>
        ///<param name="target"> The object instance to invoke the method on. </param>
        ///<param name="methodName"> The name of the method to invoke. </param>
        ///<param name="view"> The view. </param>
        ///<param name="source"> The source of the invocation. </param>
        ///<param name="eventArgs"> The event args. </param>
        ///<param name="parameters"> The method parameters. </param>
        public static void Invoke(object target, string methodName, DependencyObject view = null, FrameworkElement source = null, object eventArgs = null, object[] parameters = null)
        {
            var message = new ActionMessage {
                MethodName = methodName
            };

            var context = new ActionExecutionContext {
                Target = target,
#if WinRT
                Method = target.GetType().GetRuntimeMethods().Single(m => m.Name == methodName),
#else
                Method = target.GetType().GetMethod(methodName),
#endif
                Message   = message,
                View      = view,
                Source    = source,
                EventArgs = eventArgs
            };

            if (parameters != null)
            {
                parameters.Apply(x => context.Message.Parameters.Add(x as Parameter ?? new Parameter {
                    Value = x
                }));
            }

            ActionMessage.InvokeAction(context);

            // This is a bit of hack but keeps message being garbage collected
            Log.Info("Invoking action {0} on {1}.", message.MethodName, target);
        }
예제 #15
0
        public void Execute(ActionExecutionContext context)
        {
            var view = context.View as UserControl;
            if (view != null) {

                // add support for controls here
                List<Control> editableControls =
                    view.GetChildrenByType<Control>(c => c is RadComboBox ||
                                                         c is RadMaskedTextBox ||
                                                         c is NotifyButton ||
                                                         c is ModuleButton ||
                                                         c is RadButton);

                var control = editableControls.SingleOrDefault(c =>
                                                                   c.Name == controlToFocus);

                if (control != null)
                    control.Dispatcher.BeginInvoke(() => {
                        control.Focus();
                    });
            }
            // Execute Last
            if (!manual)
                Caliburn.Micro.Execute.OnUIThread(() => Completed(this, new ResultCompletionEventArgs()));
        }
                /// <summary>
                ///   Evaluates the parameter.
                /// </summary>
                /// <param name = "expression">The expression.</param>
                /// <param name = "context">The context.</param>
                /// <param name = "resultType">Type of the result.</param>
                /// <returns>The evaluated parameter.</returns>
                private static object EvaluateParameter(string expression, ActionExecutionContext context, Type resultType)
                {
                    try
                    {
                        var index = 0;
                        var parameters = new ParameterExpression[MessageBinder.SpecialValues.Count];
                        var values = new object[MessageBinder.SpecialValues.Count];
                        foreach (var pair in MessageBinder.SpecialValues)
                        {
                            var name = "@" + index;
                            expression = expression.Replace(pair.Key, name);
                            var value = pair.Value(context);
                            parameters[index] = Expression.Parameter(GetParameterType(value), name);
                            values[index] = value;
                            index++;
                        }

                        var exp = DynamicExpression.ParseLambda(parameters, resultType, expression);
                        return exp.Compile().DynamicInvoke(values);
                    }
                    catch (Exception exc)
                    {
                        LogManager.GetLog(typeof(MessageBinder)).Error(exc);
                        return null;
                    }
                }
예제 #17
0
파일: Run.cs 프로젝트: Slesa/Playground
 public static void Coroutine(IEnumerator<IResult> coroutines, ActionExecutionContext context=null)
 {
     if( context==null )
         Caliburn.Micro.Coroutine.BeginExecute(coroutines);
     else
         Caliburn.Micro.Coroutine.BeginExecute(coroutines, context);
 }
        /// <summary>
        /// Called by the bootstrapper's constructor at runtime to start the framework.
        /// </summary>
        protected virtual void StartRuntime() {
            Execute.InitializeWithDispatcher();
            EventAggregator.DefaultPublicationThreadMarshaller = Execute.OnUIThread;

            EventAggregator.HandlerResultProcessing = (target, result) => {
                var coroutine = result as IEnumerable<IResult>;
                if (coroutine != null) {
                    var viewAware = target as IViewAware;
                    var view = viewAware != null ? viewAware.GetView() : null;
                    var context = new ActionExecutionContext { Target = target, View = (DependencyObject)view };

                    Coroutine.BeginExecute(coroutine.GetEnumerator(), context);
                }
            };

            AssemblySource.Instance.AddRange(SelectAssemblies());

            if (useApplication) {
                Application = Application.Current;
                PrepareApplication();
            }

            Configure();
            IoC.GetInstance = GetInstance;
            IoC.GetAllInstances = GetAllInstances;
            IoC.BuildUp = BuildUp;
        }
예제 #19
0
        public void Execute(ActionExecutionContext context)
        {
            StockDetailModel stockDetail = this.stockService.Get(this.symbol);
            this.detailModel.SetValue(stockDetail);

            this.Completed(this, new ResultCompletionEventArgs());
        }
예제 #20
0
 public void Execute(ActionExecutionContext context)
 {
     service = new ChannelFactory<ISampleService>(ServiceConfig.SampleServiceEndpoint);
     ISampleService channel = service.CreateChannel();
     ThreadPool.QueueUserWorkItem(x => channel.BeginCloneSample(arlNumber, descriptionYN, storageYN, containersYN, containerDescriptionYN,
                                fillVolumeYN, dosageYN, analytesYN, testsYN, chargesYN, notesYN, AppLib.GetIdentification(), new AsyncCallback(GetRequestResponse), channel));
 }
예제 #21
0
        public override void Execute(ActionExecutionContext context)
        {
            var window = Window.GetWindow(context.View);
            window.Close();

            base.Execute(context);
        }
        void IResult.Execute(ActionExecutionContext context)
        {
            var dialog = CreateDialog();

            if (dialog.ShowDialog() != true)
            {
                this.OnCompleted(new ResultCompletionEventArgs
                {
                    WasCancelled = this._IgnoreUserCancel == false
                });
                return;
            }

            var resultArgs = new ResultCompletionEventArgs();

            this.FileNames = dialog.FileNames;

            if (this._FileAction != null)
            {
                try
                {
                    this._FileAction(FileNames);
                }
                catch (Exception e)
                {
                    resultArgs.Error = e;
                }
            }

            this.OnCompleted(resultArgs);
        }
        public void Execute(ActionExecutionContext context)
        {
            IStockTickerContentViewModel contentViewModel = this.contentFactory.CreateContent(this.detailModel.Value);
            this.conductor(contentViewModel);

            this.Completed(this, new ResultCompletionEventArgs());
        }
		public void Execute(ActionExecutionContext context)
		{
			// simulating work
			Task
				.Run(() => Task.Delay(6000))
				.ContinueWith(task => Completed(this, new ResultCompletionEventArgs()));
		}
예제 #25
0
 public void MakeAwareOf(ActionExecutionContext context)
 {
     this.context = context;
     var inpc = context.Target as INotifyPropertyChanged;
     if (inpc == null)
     {
         return;
     }
     foreach (var viewModelProperty in ViewModelProperties(inpc))
     {
         observers.Add(new PropertyObserver(inpc, viewModelProperty, true, UpdateAvailability));
     }
     var otherProperties = from dependentProperty in dependentProperties.Select(propertyName => propertyName.Split('.'))
                           where dependentProperty.Length > 1
                           select dependentProperty;
     foreach (var args in otherProperties)
     {
         var viewModelProperty = args[0];
         var observer = observers.FirstOrDefault(po => po.PropertyToWatch == viewModelProperty);
         if (observer == null)
         {
             observers.Add(observer = new PropertyObserver(inpc, viewModelProperty, false, UpdateAvailability));
         }
         observer.AddChild(args);
     }
 }
예제 #26
0
        public override void Execute(ActionExecutionContext context)
        {
            if(callback != null)
                callback();

            OnCompleted(this, new ResultCompletionEventArgs{WasCancelled = true});
        }
예제 #27
0
        public void Execute(ActionExecutionContext context)
        {
            var documentWorkspace = _screen.Parent as IDocumentWorkspace;
            if (documentWorkspace != null)
                documentWorkspace.Edit(_screen);

            _closeCheck(Shell.Dialogs, result => Completed(this, new ResultCompletionEventArgs { WasCancelled = !result }));
        }
예제 #28
0
 public void Execute(ActionExecutionContext context)
 {
     _task.ContinueWith(t => Completed(this, new ResultCompletionEventArgs
         {
             WasCancelled = t.IsCanceled,
             Error = t.Exception
         }));
 }
예제 #29
0
 public static void ExecuteSynchronized(this IResult result, ActionExecutionContext actionExecutionContext = null)
 {
     IoC.BuildUp(result);
     var reset = new ManualResetEvent(false);
     result.Completed+= (s,e)=>reset.Set();
     result.Execute(actionExecutionContext);
     reset.WaitOne();
 }
예제 #30
0
        public override async void Execute(ActionExecutionContext context)
        {
            var repository = WaypointsRepositoryFactory.Create();
            
            await repository.SaveAsync(_waypoints);

            OnCompleted();
        }
예제 #31
0
 public override void Execute(ActionExecutionContext context)
 {
     if(Shell.Workspace != null)
     {
         Shell.Workspace.ScriptingEngine.EvaluateAsync(code, sourceFile);
         OnCompleted(null);
     }
 }
예제 #32
0
 public override void Execute(ActionExecutionContext context)
 {
     if(Workspace != null && Workspace.ReplExecutor != null)
     {
         Workspace.ReplExecutor.Execute(code, sourceFile);
         OnCompleted(null);
     }
 }
예제 #33
0
        public void Execute(ActionExecutionContext context)
        {
            _lambda(context);

            var completedHandler = Completed;
            if (completedHandler != null)
                completedHandler(this, new ResultCompletionEventArgs());
        }
예제 #34
0
        public async override void Execute(ActionExecutionContext context)
        {
            var dialog = new MessageDialog(_content, _title);

            await dialog.ShowAsync();

            OnCompleted();
        }
        void UpdateContext()
        {
            context = new ActionExecutionContext {
                Message = this,
                Source  = AssociatedObject
            };

            PrepareContext(context);
            UpdateAvailabilityCore();
        }
        /// <summary>
        /// Executes a coroutine.
        /// </summary>
        /// <param name="coroutine">The coroutine to execute.</param>
        /// <param name="context">The context to execute the coroutine within.</param>
        public static void Execute(IEnumerator <IResult> coroutine, ActionExecutionContext context)
        {
            Log.Info("Executing coroutine.");

            var enumerator = CreateParentEnumerator(coroutine);

            IoC.BuildUp(enumerator);

            enumerator.Completed += Completed;
            enumerator.Execute(context);
        }
예제 #37
0
        /// <summary>
        /// Executes a coroutine.
        /// </summary>
        /// <param name="coroutine">The coroutine to execute.</param>
        /// <param name="context">The context to execute the coroutine within.</param>
        /// /// <param name="callback">The completion callback for the coroutine.</param>
        public static void BeginExecute(IEnumerator<IResult> coroutine, ActionExecutionContext context = null, EventHandler<ResultCompletionEventArgs> callback = null) {
            Log.Info("Executing coroutine.");

            var enumerator = CreateParentEnumerator(coroutine);
            IoC.BuildUp(enumerator);

            if(callback != null)
                enumerator.Completed += callback;
            enumerator.Completed += Completed;

            enumerator.Execute(context ?? new ActionExecutionContext());
        }
예제 #38
0
        /// <summary>
        ///     Try to find a candidate for guard function, having:
        ///     - a name matching any of <paramref name="possibleGuardNames" />
        ///     - no generic parameters
        ///     - a bool return type
        ///     - no parameters or a set of parameters corresponding to the action method
        /// </summary>
        /// <param name="context">The execution context</param>
        /// <param name="possibleGuardNames">Method names to look for.</param>
        /// <returns>A MethodInfo, if found; null otherwise</returns>
        private static MethodInfo TryFindGuardMethod(ActionExecutionContext context,
                                                     IEnumerable <string> possibleGuardNames)
        {
            var        targetType = context.Target.GetType();
            MethodInfo guard      = null;

            foreach (var possibleGuardName in possibleGuardNames)
            {
                guard = GetMethodInfo(targetType, possibleGuardName);
                if (guard != null)
                {
                    break;
                }
            }

            if (guard == null)
            {
                return(null);
            }
            if (guard.ContainsGenericParameters)
            {
                return(null);
            }
            if (!typeof(bool).Equals(guard.ReturnType))
            {
                return(null);
            }

            var guardPars  = guard.GetParameters();
            var actionPars = context.Method.GetParameters();

            if (guardPars.Length == 0)
            {
                return(guard);
            }
            if (guardPars.Length != actionPars.Length)
            {
                return(null);
            }

            var comparisons = guardPars.Zip(
                context.Method.GetParameters(),
                (x, y) => x.ParameterType == y.ParameterType
                );

            if (comparisons.Any(x => !x))
            {
                return(null);
            }

            return(guard);
        }
예제 #39
0
        public void Execute(ActionExecutionContext context)
        {
            var dialog = OpenReadOnly ? (FileDialog) new OpenFileDialog() : new SaveFileDialog();

            dialog.Filter = Filter;

            if (dialog.ShowDialog() == true)
            {
                // Screw you WPF, I know that method is there
                Stream   = () => ((dynamic)dialog).OpenFile();
                FileName = dialog.FileName;
                Completed(this, new ResultCompletionEventArgs());
            }
        }
예제 #40
0
 /// <summary>
 /// Executes the result using the specified context.
 /// </summary>
 /// <param name="context">The context.</param>
 public void Execute(ActionExecutionContext context)
 {
     if (innerTask.IsCompleted)
     {
         OnCompleted(innerTask);
     }
     else
     {
         innerTask.ContinueWith(OnCompleted,
                                System.Threading.SynchronizationContext.Current != null
                                    ? TaskScheduler.FromCurrentSynchronizationContext()
                                    : TaskScheduler.Current);
     }
 }
예제 #41
0
        static IEnumerable <string> BuildPossibleGuardNames(ActionExecutionContext context)
        {
            const string GuardPrefix = "Can";

            var methodName = context.Method.Name;

            yield return(GuardPrefix + methodName);

            const string AsyncMethodSuffix = "Async";

            if (methodName.EndsWith(AsyncMethodSuffix, StringComparison.OrdinalIgnoreCase))
            {
                yield return(GuardPrefix + methodName.Substring(0, methodName.Length - AsyncMethodSuffix.Length));
            }
        }
예제 #42
0
        private void UpdateContext()
        {
            if (context != null)
            {
                context.Dispose();
            }

            context = new ActionExecutionContext
            {
                Message = this,
                Source  = AssociatedObject
            };

            PrepareContext(context);
            UpdateAvailabilityCore();
        }
예제 #43
0
        /// <summary>
        /// Try to find a candidate for guard function, having:
        ///		- a name in the form "CanXXX"
        ///		- no generic parameters
        ///		- a bool return type
        ///		- no parameters or a set of parameters corresponding to the action method
        /// </summary>
        /// <param name="context">The execution context</param>
        /// <returns>A MethodInfo, if found; null otherwise</returns>
        static MethodInfo TryFindGuardMethod(ActionExecutionContext context)
        {
            var guardName  = "Can" + context.Method.Name;
            var targetType = context.Target.GetType();
            var guard      = targetType.GetMethod(guardName);

            if (guard == null)
            {
                return(null);
            }
            if (guard.ContainsGenericParameters)
            {
                return(null);
            }
            if (!typeof(bool).Equals(guard.ReturnType))
            {
                return(null);
            }

            var guardPars  = guard.GetParameters();
            var actionPars = context.Method.GetParameters();

            if (guardPars.Length == 0)
            {
                return(guard);
            }
            if (guardPars.Length != actionPars.Length)
            {
                return(null);
            }

            var comparisons = guardPars.Zip(
                context.Method.GetParameters(),
                (x, y) => x.ParameterType.Equals(y.ParameterType)
                );

            if (comparisons.Any(x => !x))
            {
                return(null);
            }

            return(guard);
        }
예제 #44
0
        /// <summary>
        /// Determines the parameters that a method should be invoked with.
        /// </summary>
        /// <param name="context">The action execution context.</param>
        /// <param name="requiredParameters">The parameters required to complete the invocation.</param>
        /// <returns>The actual parameter values.</returns>
        public static object[] DetermineParameters(ActionExecutionContext context, ParameterInfo[] requiredParameters)
        {
            var providedValues = context.Message.Parameters.Select(x => x.Value).ToArray();
            var values         = new object[requiredParameters.Length];

            for (int i = 0; i < requiredParameters.Length; i++)
            {
                var    value       = providedValues[i];
                var    stringValue = value as string;
                object potentialValue;

                if (stringValue != null)
                {
                    switch (stringValue.ToLower(CultureInfo.InvariantCulture))
                    {
                    case "$eventargs":
                        potentialValue = context.EventArgs;
                        break;

                    case "$datacontext":
                        potentialValue = context.Source.DataContext;
                        break;

                    case "$source":
                        potentialValue = context.Source;
                        break;

                    default:
                        potentialValue = stringValue;
                        break;
                    }
                }
                else
                {
                    potentialValue = value;
                }

                values[i] = CoerceValue(requiredParameters[i].ParameterType, potentialValue);
            }

            return(values);
        }
예제 #45
0
        /// <summary>
        /// Executes a coroutine asynchronous.
        /// </summary>
        /// <param name="coroutine">The coroutine to execute.</param>
        /// <param name="context">The context to execute the coroutine within.</param>
        /// <returns>A task that represents the asynchronous coroutine.</returns>
        public static Task ExecuteAsync(IEnumerator <IResult> coroutine, ActionExecutionContext context = null)
        {
            var taskSource = new TaskCompletionSource <object>();

            BeginExecute(coroutine, context, (s, e) => {
                if (e.Error != null)
                {
                    taskSource.SetException(e.Error);
                }
                else if (e.WasCancelled)
                {
                    taskSource.SetCanceled();
                }
                else
                {
                    taskSource.SetResult(null);
                }
            });

            return(taskSource.Task);
        }
예제 #46
0
        /// <summary>
        /// Determines the parameters that a method should be invoked with.
        /// </summary>
        /// <param name="context">The action execution context.</param>
        /// <param name="requiredParameters">The parameters required to complete the invocation.</param>
        /// <returns>The actual parameter values.</returns>
        public static object[] DetermineParameters(ActionExecutionContext context, ParameterInfo[] requiredParameters)
        {
            var providedValues = context.Message.Parameters.Select(x => x.Value).ToArray();
            var finalValues    = new object[requiredParameters.Length];

            for (int i = 0; i < requiredParameters.Length; i++)
            {
                var parameterType     = requiredParameters[i].ParameterType;
                var parameterValue    = providedValues[i];
                var parameterAsString = parameterValue as string;

                if (parameterAsString != null)
                {
                    finalValues[i] = CoerceValue(parameterType, EvaluateParameter(parameterAsString, parameterType, context), context);
                }
                else
                {
                    finalValues[i] = CoerceValue(parameterType, parameterValue, context);
                }
            }

            return(finalValues);
        }
예제 #47
0
        /// <summary>
        /// Called by the bootstrapper's constructor at runtime to start the framework.
        /// </summary>
        protected virtual void StartRuntime()
        {
            Execute.InitializeWithDispatcher();
            EventAggregator.DefaultPublicationThreadMarshaller = Execute.OnUIThread;

            EventAggregator.HandlerResultProcessing = (target, result) => {
#if !SILVERLIGHT || SL5 || WP8
                var task = result as System.Threading.Tasks.Task;
                if (task != null)
                {
                    result = new IResult[] { task.AsResult() };
                }
#endif

                var coroutine = result as IEnumerable <IResult>;
                if (coroutine != null)
                {
                    var viewAware = target as IViewAware;
                    var view      = viewAware != null?viewAware.GetView() : null;

                    var context = new ActionExecutionContext {
                        Target = target, View = (DependencyObject)view
                    };

                    Coroutine.BeginExecute(coroutine.GetEnumerator(), context);
                }
            };

            AssemblySource.Instance.AddRange(SelectAssemblies());

            PrepareApplication();
            Configure();

            IoC.GetInstance     = GetInstance;
            IoC.GetAllInstances = GetAllInstances;
            IoC.BuildUp         = BuildUp;
        }
예제 #48
0
        static Task <TResult> InternalExecuteAsync <TResult>(IResult result, ActionExecutionContext context)
        {
            var taskSource = new TaskCompletionSource <TResult>();

            EventHandler <ResultCompletionEventArgs> completed = null;

            completed = (s, e) => {
                result.Completed -= completed;

                if (e.Error != null)
                {
                    taskSource.SetException(e.Error);
                }
                else if (e.WasCancelled)
                {
                    taskSource.SetCanceled();
                }
                else
                {
                    var rr = result as IResult <TResult>;
                    taskSource.SetResult(rr != null ? rr.Result : default(TResult));
                }
            };

            try {
                IoC.BuildUp(result);
                result.Completed += completed;
                result.Execute(context ?? new ActionExecutionContext());
            }
            catch (Exception ex) {
                result.Completed -= completed;
                taskSource.SetException(ex);
            }

            return(taskSource.Task);
        }
예제 #49
0
 /// <summary>
 /// Executes a coroutine.
 ///
 /// </summary>
 /// <param name="coroutine">The coroutine to execute.</param><param name="context">The context to execute the coroutine within.</param>/// <param name="callback">The completion callback for the coroutine.</param>
 public static void BeginExecute(IEnumerator <IResult> coroutine, ActionExecutionContext context = null, EventHandler <ResultCompletionEventArgs> callback = null);
예제 #50
0
 /// <summary>
 /// Executes an <see cref="Caliburn.Micro.IResult"/> asynchronous.
 /// </summary>
 /// <param name="result">The coroutine to execute.</param>
 /// <param name="context">The context to execute the coroutine within.</param>
 /// <returns>A task that represents the asynchronous coroutine.</returns>
 public static Task ExecuteAsync(this IResult result, ActionExecutionContext context = null)
 {
     return(InternalExecuteAsync <object>(result, context));
 }
예제 #51
0
 /// <summary>
 /// Executes an <see cref="Caliburn.Micro.IResult&lt;TResult&gt;"/> asynchronous.
 /// </summary>
 /// <typeparam name="TResult">The type of the result.</typeparam>
 /// <param name="result">The coroutine to execute.</param>
 /// <param name="context">The context to execute the coroutine within.</param>
 /// <returns>A task that represents the asynchronous coroutine.</returns>
 public static Task <TResult> ExecuteAsync <TResult>(this IResult <TResult> result,
                                                     ActionExecutionContext context = null)
 {
     return(InternalExecuteAsync <TResult>(result, context));
 }
예제 #52
0
파일: DragResult.cs 프로젝트: Kha/YUV.KA
 public void Execute(ActionExecutionContext context)
 {
     DragDrop.DoDragDrop(context.Source, data, allowedEffects);
     Completed(this, new ResultCompletionEventArgs());
 }
 /// <summary>
 ///   Executes the result using the specified context.
 /// </summary>
 /// <param name = "context">The context.</param>
 public void Execute(ActionExecutionContext context)
 {
     this.context = context;
     ChildCompleted(null, new ResultCompletionEventArgs());
 }