Esempio n. 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()));
 }
Esempio n. 2
0
        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();
            }
        }
Esempio n. 3
0
        public void Execute(ActionExecutionContext context)
        {
            var shell = IoC.Get<IShell>();
            shell.IsBusy = _isBusy;

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

            this.OnCompleted(new ResultCompletionEventArgs());
        }
Esempio n. 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);
        }
Esempio n. 6
0
        public override void Execute(ActionExecutionContext context)
        {
            Window window = Window.GetWindow(context.View);
            if (window != null) window.Close();

            base.Execute(context);
        }
 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));
 }
Esempio n. 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());
        }
                /// <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);
                    }
                }
Esempio n. 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;
        }
Esempio n. 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();
        }
Esempio n. 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);
        }
Esempio n. 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;
                    }
                }
Esempio n. 17
0
 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;
        }
Esempio n. 19
0
        public void Execute(ActionExecutionContext context)
        {
            StockDetailModel stockDetail = this.stockService.Get(this.symbol);
            this.detailModel.SetValue(stockDetail);

            this.Completed(this, new ResultCompletionEventArgs());
        }
Esempio n. 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));
 }
Esempio n. 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()));
		}
Esempio n. 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);
     }
 }
Esempio n. 26
0
        public override void Execute(ActionExecutionContext context)
        {
            if(callback != null)
                callback();

            OnCompleted(this, new ResultCompletionEventArgs{WasCancelled = true});
        }
Esempio n. 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 }));
        }
Esempio n. 28
0
 public void Execute(ActionExecutionContext context)
 {
     _task.ContinueWith(t => Completed(this, new ResultCompletionEventArgs
         {
             WasCancelled = t.IsCanceled,
             Error = t.Exception
         }));
 }
Esempio n. 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();
 }
Esempio n. 30
0
        public override async void Execute(ActionExecutionContext context)
        {
            var repository = WaypointsRepositoryFactory.Create();
            
            await repository.SaveAsync(_waypoints);

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

            var completedHandler = Completed;
            if (completedHandler != null)
                completedHandler(this, new ResultCompletionEventArgs());
        }
Esempio n. 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);
        }
        /// <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());
        }
Esempio n. 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);
        }
Esempio n. 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());
            }
        }
Esempio n. 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);
     }
 }
Esempio n. 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));
            }
        }
Esempio n. 42
0
        private void UpdateContext()
        {
            if (context != null)
            {
                context.Dispose();
            }

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

            PrepareContext(context);
            UpdateAvailabilityCore();
        }
Esempio n. 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);
        }
Esempio n. 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);
        }
Esempio n. 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);
        }
Esempio n. 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);
        }
Esempio n. 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;
        }
Esempio n. 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);
        }
Esempio n. 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);
Esempio n. 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));
 }
Esempio n. 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));
 }
Esempio n. 52
0
 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());
 }