Пример #1
0
        public void Execute(ActionExecutionContext context)
        {
            var callContext = SynchronizationContext.Current;

            // Wrap the inner result in a SequentialResult s.t. it gets injected by the container but avoid deep nesting
            var wrapper = (_inner is SequentialResult || _inner is ResultDecoratorBase)
                              ? _inner
                              : new SequentialResult(new SingleResultEnumerator(_inner));

            var task = new ResultExecutionTask(wrapper, context);
            SendOrPostCallback callback = x =>
            {
                var args = (x as ResultExecutionTask).CompletionEventArgs;
                if (callContext != null)
                {
                    _log.Info("Invoking complete on calling context {0}", callContext);
                    callContext.Send(y => Completed(this, y as ResultCompletionEventArgs), args);
                }
                else
                {
                    Completed(this, args);
                }
            };

            _log.Info("Delegating execution of {0} to worker thread", _inner);

            ResultSyncContext.Post(callback, task);
        }
        internal static void PrepareContext(ActionExecutionContext context)
        {
            var contextAwareFilters = FilterManager.GetFiltersFor(context).OfType<IContextAware>().ToArray();
            contextAwareFilters.Apply(x => x.MakeAwareOf(context));

            context.Message.Detaching += (o, e) => contextAwareFilters.Apply(x => x.Dispose());
        }
        public void MakeAwareOf(ActionExecutionContext context)
        {
            var targetType = context.Target.GetType();
            var guard = targetType.GetMethod(this.MethodName);
            if (guard == null)
            {
                guard = targetType.GetMethod("get_" + this.MethodName);
            }

            if (guard == null)
            {
                return;
            }

            var oldCanExecute = context.CanExecute ?? new Func<bool>(() => true);
            context.CanExecute = () =>
                {
                    if (!oldCanExecute())
                    {
                        return false;
                    }

                    return (bool)guard.Invoke(
                        context.Target,
                        MessageBinder.DetermineParameters(context, guard.GetParameters())
                                     );
                };
        }
Пример #4
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);
        }
Пример #5
0
        public override void Execute(ActionExecutionContext context)
        {
            var tool = _toolLocator();

            if (_setData != null)
            {
                _setData(tool);
            }

            if (_onConfigure != null)
            {
                _onConfigure(tool);
            }

            tool.Deactivated += (s, e) =>
            {
                if (!e.WasClosed)
                {
                    return;
                }

                if (_onShutDown != null)
                {
                    _onShutDown(tool);
                }

                OnCompleted(null);
            };

            _shell.ShowTool(tool);
        }
Пример #6
0
        void IResult.Execute(ActionExecutionContext context)
        {
            var dialog = CreateDialog();

            dialog.ShowDialog();

            var resultArgs = new ResultCompletionEventArgs();
            bool cancelled = string.IsNullOrWhiteSpace(dialog.SelectedPath);

            if (cancelled)
            {
                resultArgs.WasCancelled = !_ignoreUserCancel;
            }
            else
            {
                SelectedPath = dialog.SelectedPath;

                if (_pathAction != null)
                {
                    try
                    {
                        _pathAction(SelectedPath);
                    }
                    catch (Exception e)
                    {
                        resultArgs.Error = e;
                    }
                }
            }

            _completed(this, resultArgs);
        }
Пример #7
0
 public ResultExecutionTask(IResult result, ActionExecutionContext context)
 {
     Result = result;
     Context = context;
     CompletionEventArgs = new ResultCompletionEventArgs();
     ExecutionCompleteWaitHandle = new ManualResetEvent(false);
 }
Пример #8
0
        private async Task TryCreateNewNotebook(ActionExecutionContext context)
        {
            if (string.IsNullOrEmpty(NewNotebookName))
            {
                return;
            }

            var keyArgs = context.EventArgs as KeyEventArgs;

            if (keyArgs?.Key == Key.Enter)
            {
                await CreateNotebook();

                NewNotebookName = null;

                ShowReadOnly();

                MessageBus.Publish(new NotebookCreated());
            }

            if (keyArgs?.Key == Key.Escape)
            {
                ShowReadOnly();

                NewNotebookName = null;
            }
        }
Пример #9
0
        /// <summary>
        /// Executes this action.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="context">The context.</param>
        public override void Execute(RootModel model, ActionExecutionContext context)
        {
            Assert.ArgumentNotNull(model, "model");
            Assert.ArgumentNotNull(context, "context");

            //TODO: Enable OutputEntoreMessageKeepingColors only for triggers?
            //CurrentMessage work only from triggers
            var contextMessage = context.CurrentMessage as TextMessage;

            if (OutputEntireMessageKeepingColors && contextMessage != null)
            {
                model.PushMessageToConveyor(new OutputToAdditionalWindowMessage(contextMessage)
                {
                    SkipTriggers = true, SkipSubstitution = true, SkipHighlight = true
                });
            }
            else
            {
                string str = PostProcessString(TextToOutput + GetParametersString(model, context), model, context);
                if (OutputEntireMessageKeepingColors)
                {
                    model.PushMessageToConveyor(new OutputToAdditionalWindowMessage(str)
                    {
                        SkipTriggers = true, SkipSubstitution = true, SkipHighlight = true
                    });
                }
                else
                {
                    model.PushMessageToConveyor(new OutputToAdditionalWindowMessage(str, TextColor, BackgroundColor)
                    {
                        SkipTriggers = true, SkipSubstitution = true, SkipHighlight = true
                    });
                }
            }
        }
        /// <summary>
        /// Gets the parameter value.
        /// </summary>
        /// <param name="rootModel">The root model.</param>
        /// <param name="context">The context.</param>
        /// <returns>
        /// Parameter value.
        /// </returns>
        public override string GetParameterValue(RootModel rootModel, ActionExecutionContext context)
        {
            Assert.ArgumentNotNull(rootModel, "rootModel");
            Assert.ArgumentNotNull(context, "context");

            return(rootModel.SelectedGroupMate != null ? rootModel.SelectedGroupMate.TargetName : string.Empty);
        }
Пример #11
0
        public int?NavigateToDefinition(ActionExecutionContext executionContext)
        {
            var documentRepository = executionContext.DocumentRepository;
            var terminal           = documentRepository.Statements.GetTerminalAtPosition(executionContext.CaretOffset, n => !n.Id.IsZeroOffsetTerminalId());

            if (terminal == null || !terminal.Id.In(Terminals.Identifier, Terminals.ObjectIdentifier))
            {
                return(null);
            }

            var semanticModel = (OracleStatementSemanticModel)documentRepository.ValidationModels[terminal.Statement].SemanticModel;
            var queryBlock    = semanticModel.GetQueryBlock(executionContext.CaretOffset);

            if (queryBlock == null)
            {
                return(null);
            }

            switch (terminal.Id)
            {
            case Terminals.Identifier:
                return(NavigateToColumnDefinition(queryBlock, terminal));

            case Terminals.ObjectIdentifier:
                return(NavigateToObjectDefinition(queryBlock, terminal));

            default:
                throw new NotSupportedException($"Terminal '{terminal.Id}' is not supported. ");
            }
        }
        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();
        }
Пример #13
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 }));
        }
        public void Execute(ActionExecutionContext context)
        {
            var callContext = SynchronizationContext.Current;

            // Wrap the inner result in a SequentialResult s.t. it gets injected by the container but avoid deep nesting
            var wrapper = (_inner is SequentialResult || _inner is ResultDecoratorBase)
                              ? _inner
                              : new SequentialResult(new SingleResultEnumerator(_inner));

            var task = new ResultExecutionTask(wrapper, context);
            SendOrPostCallback callback = x =>
            {
                var args = (x as ResultExecutionTask).CompletionEventArgs;
                if (callContext != null)
                {
                    _log.Info("Invoking complete on calling context {0}", callContext);
                    callContext.Send(y => Completed(this, y as ResultCompletionEventArgs), args);
                }
                else
                {
                    Completed(this, args);
                }
            };

            _log.Info("Delegating execution of {0} to worker thread", _inner);

            ResultSyncContext.Post(callback, task);
        }
        /// <summary>
        /// Defines the method to be called when the command is invoked.
        /// </summary>
        /// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param>
        public void Execute(object parameter) {
            var target = targetReference.Target;
            if (target == null) return;

            var execute = DynamicDelegate.From(method);
            var returnValue = execute(target, new object[0]);

            var task = returnValue as System.Threading.Tasks.Task;
            if (task != null) {
                returnValue = task.AsResult();
            }

            var result = returnValue as IResult;
            if (result != null) {
                returnValue = new[] { result };
            }

            var enumerable = returnValue as IEnumerable<IResult>;
            if (enumerable != null) {
                returnValue = enumerable.GetEnumerator();
            }

            var enumerator = returnValue as IEnumerator<IResult>;
            if (enumerator != null) {
                var context = new ActionExecutionContext
                {
                    Target = target,
                    Method = method,
                    CanExecute = canExecute.Invoke,
                };

                Coroutine.BeginExecute(enumerator, context);
            }
        }
        public async Task ActivityIntegrationTest()
        {
            const string CollectionUrl = @"http://*****:*****@"$/MattiasDemo2011/Main4", SourceControl = wrapper };

            var context = new ActionExecutionContext();
            await activity.ExecuteAsync(context);

            var checkin = new SccCheckIn { SourceControl = wrapper };

            await checkin.ExecuteAsync(context);

            var branch = new SccCreateBranch
                {
                    BranchSource = @"$/MattiasDemo2011/Main4",
                    BranchTarget = @"$/MattiasDemo2011/Dev4",
                    SourceControl = wrapper
                };

            await branch.ExecuteAsync(context);

            var checkin2 = new SccCheckIn { SourceControl = wrapper };

            await checkin2.ExecuteAsync(context);
        }
Пример #17
0
        public void Execute(ActionExecutionContext context)
        {
            FrameworkElement view = GetView(context);

            while (view != null)
            {
                var busyIndicator = //view.FindName(_busyIndicatorName) as BusyIndicator ??
                                    FindChild <BusyIndicator>(view, _busyIndicatorName);

                if (busyIndicator != null)
                {
                    busyIndicator.IsBusy = _isBusy;

                    if (!string.IsNullOrWhiteSpace(_message))
                    {
                        busyIndicator.BusyContent = _message;
                    }

                    break;
                }

                view = view.Parent as FrameworkElement;
            }

            Completed(this, new ResultCompletionEventArgs());
        }
Пример #18
0
        /// <summary>
        /// Executes this action.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="context">The context.</param>
        public override void Execute(RootModel model, ActionExecutionContext context)
        {
            Assert.ArgumentNotNull(model, "model");
            Assert.ArgumentNotNull(context, "context");

            model.PushCommandToConveyor(new TextCommand(PostProcessString(CommandText + GetParametersString(model, context), model, context)));
        }
Пример #19
0
        public void Execute(ActionExecutionContext context)
        {
            DeploymentCatalog catalog;

            if(Catalogs.TryGetValue(uri, out catalog))
                Completed(this, new ResultCompletionEventArgs());
            else
            {
                catalog = new DeploymentCatalog(new Uri("/ClientBin/" + uri, UriKind.RelativeOrAbsolute));
                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();
            }
        }
Пример #20
0
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
        public async Task ExecuteAsync(ActionExecutionContext context)
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
        {
            //TODO: Create a generic emailer with symbols as the default
            // notification system is currently much better than this notification thingy.
            //i.e. it do not add any value currently.
        }
Пример #21
0
        public void Execute(ActionExecutionContext context)
        {
            var manager = (WindowManager)IoC.Get <IWindowManager>();
            var args    = new ResultCompletionEventArgs();
            IDictionary <string, object> settings = null;

            if (FullScreen)
            {
                settings = new Dictionary <string, object> {
                    { "WindowState", WindowState.Maximized }
                };
            }

            if (Resizable || FullScreen)
            {
                manager.ShowDialog(Model, null, settings);
            }
            else
            {
                manager.ShowFixedDialog(Model);
            }

            var cancellable = Model as ICancelable;

            if (cancellable != null)
            {
                args.WasCancelled = cancellable.WasCancelled;
            }
            RaiseCompleted(args);
        }
Пример #22
0
 public void EmailTextBoxChangeFocusToPasswordTextBox(ActionExecutionContext context)
 {
     if (((Windows.UI.Xaml.Input.KeyRoutedEventArgs)context.EventArgs).Key == VirtualKey.Enter)
     {
         _passwordBox.Focus(FocusState.Keyboard);
     }
 }
Пример #23
0
        public void Execute(ActionExecutionContext context)
        {
            var proxy = ServiceFactory.CreateMoneyService();

            proxy.DeleteJournalCompleted += OnDeleteCompleted;
            proxy.DeleteJournalAsync(accountId, transactionId);
        }
Пример #24
0
        private void TryCreateNewNotebook(ActionExecutionContext context)
        {
            if (string.IsNullOrEmpty(NewSectionName) || _selectedNotebook == null || _selectedNotebook.Directory.Exists == false)
            {
                return;
            }

            var keyArgs = context.EventArgs as KeyEventArgs;

            if (keyArgs?.Key == Key.Enter)
            {
                CreateSection();

                NewSectionName = null;

                ShowReadOnly();

                MessageBus.Publish(new SectionCreated(_selectedNotebook));
            }

            if (keyArgs?.Key == Key.Escape)
            {
                ShowReadOnly();
                NewSectionName = null;
            }
        }
Пример #25
0
        public void Execute(ActionExecutionContext context)
        {
            var selectWithShell = false;

            try {
                ProcessHelper.Start(new ProcessStartInfo(Filename)
                {
                    Verb = "Open"
                });
            }
            catch (Win32Exception e) {
                //System.ComponentModel.Win32Exception (0x80004005):
                //Указанному файлу не сопоставлено ни одно приложение для выполнения данной операции
                //если нет сопоставленного приложения выбираем файл в shell
                if ((uint)e.NativeErrorCode == 0x80004005 || e.NativeErrorCode == 1155)
                {
                    selectWithShell = true;
                }
                else
                {
                    log.Error($"Fail to open file {Filename}", e);
                }
            }
            if (selectWithShell)
            {
                ProcessHelper.Start(new ProcessStartInfo("explorer.exe", $"/select,{Filename}"));
            }

            Completed?.Invoke(this, new ResultCompletionEventArgs());
        }
Пример #26
0
            internal static void InvokeAction(ActionExecutionContext context)
            {
                var decorators = context.GetFilters()
                    .OfType<IDecorateCoroutineFilter>()
                    .ToArray();

                // Use the default behaviour when no decorators are found
                if (!decorators.Any())
                {
                    BaseInvokeAction(context);
                    return;
                }

                var values = MessageBinder.DetermineParameters(context, context.Method.GetParameters());
                var returnValue = context.Method.Invoke(context.Target, values);

                IEnumerable<IResult> coroutine;
                if (returnValue is IResult)
                {
                    coroutine = new[] { returnValue as IResult };
                }
                else if (returnValue is IEnumerable<IResult>)
                {
                    coroutine = returnValue as IEnumerable<IResult>;
                }
                else return;

                coroutine = decorators.Aggregate(coroutine, (current, decorator) => decorator.Decorate(current, context));

                Coroutine.BeginExecute(coroutine.GetEnumerator(), context);
            }
Пример #27
0
        public void Execute(object parameter)
        {
            if (!string.IsNullOrEmpty(CaliburnAction))
            {
                var methodName = CaliburnAction;
                if (methodName.EndsWith(""))
                {
                    methodName = methodName.Remove(methodName.Length - 2);
                }

                // will be overridden by Caliburn.
                var controls = MetaActionManager.Instance.GetControls(this);
                var source   = controls.First();

                var trigger = Parser.Parse(source, CaliburnAction).FirstOrDefault();
                var action  = trigger.Actions.OfType <ActionMessage>().FirstOrDefault();

                var context = new ActionExecutionContext
                {
                    EventArgs = new EventArgs(),
                    Message   = action,
                    Source    = source,
                };
                ActionMessage.PrepareContext(context);

                if (context.CanExecute == null || context.CanExecute())
                {
                    ActionMessage.InvokeAction(context);
                }
            }
        }
Пример #28
0
 public ContextAction(string name, CommandExecutionHandler executionHandler, ActionExecutionContext executionContext, bool isLongOperation = false)
 {
     Name             = name;
     ExecutionHandler = executionHandler;
     ExecutionContext = executionContext;
     IsLongOperation  = isLongOperation;
 }
Пример #29
0
        public override void Execute(ActionExecutionContext context)
        {
            var doc = document ??
                      (uri == null
                                        ? (IDocument)IoC.GetInstance(documentType, null)
                                        : Shell.GetDocument(uri));

            if (doc == null)
            {
                OnCompleted(null);
                return;
            }

            if (_setData != null)
            {
                _setData(doc);
            }

            if (_onConfigure != null)
            {
                _onConfigure(doc);
            }

            doc.Deactivated += (s, e) =>
            {
                if (_onShutDown != null)
                {
                    _onShutDown(doc);
                }

                OnCompleted(null);
            };

            shell.OpenDocument(doc);
        }
Пример #30
0
        public void TestMultipleStatementSingleLineFormat()
        {
            const string sourceFormat =
                @"SELECT
	DUMMY
FROM
	DUAL
;

SELECT
	DUMMY
FROM
	DUAL @ DBLINK
;";

            _documentRepository.UpdateStatements(sourceFormat);
            var executionContext = new ActionExecutionContext(sourceFormat, 0, 0, sourceFormat.Length, _documentRepository);

            Formatter.SingleLineExecutionHandler.ExecutionHandler(executionContext);

            executionContext.SegmentsToReplace.Count.ShouldBe(2);
            executionContext.SegmentsToReplace[0].Text.ShouldBe("SELECT DUMMY FROM DUAL");
            executionContext.SegmentsToReplace[0].IndextStart.ShouldBe(0);
            executionContext.SegmentsToReplace[0].Length.ShouldBe(27);
            executionContext.SegmentsToReplace[1].Text.ShouldBe("SELECT DUMMY FROM DUAL@DBLINK");
            executionContext.SegmentsToReplace[1].IndextStart.ShouldBe(34);
            executionContext.SegmentsToReplace[1].Length.ShouldBe(36);
        }
Пример #31
0
        public void TestSelectedTextNormalization()
        {
            var formatOptions = OracleConfiguration.Configuration.Formatter.FormatOptions;

            formatOptions.Identifier   = FormatOption.Upper;
            formatOptions.Alias        = FormatOption.Upper;
            formatOptions.ReservedWord = FormatOption.InitialCapital;

            const string sourceFormat = "SELECT dummy alias FROM dual";

            _documentRepository.UpdateStatements(sourceFormat);
            var executionContext = new ActionExecutionContext(sourceFormat, 9, 9, 15, _documentRepository);

            Formatter.NormalizeHandler.ExecutionHandler(executionContext);

            executionContext.SegmentsToReplace.Count.ShouldBe(3);
            executionContext.SegmentsToReplace[0].IndextStart.ShouldBe(7);
            executionContext.SegmentsToReplace[0].Length.ShouldBe(5);
            executionContext.SegmentsToReplace[0].Text.ShouldBe("DUMMY");
            executionContext.SegmentsToReplace[1].IndextStart.ShouldBe(13);
            executionContext.SegmentsToReplace[1].Length.ShouldBe(5);
            executionContext.SegmentsToReplace[1].Text.ShouldBe("ALIAS");
            executionContext.SegmentsToReplace[2].IndextStart.ShouldBe(19);
            executionContext.SegmentsToReplace[2].Length.ShouldBe(4);
            executionContext.SegmentsToReplace[2].Text.ShouldBe("From");
        }
Пример #32
0
        public void TestSingleLineFormat()
        {
            const string sourceFormat =
                @"SELECT
	SELECTION.NAME,
	COUNT(*) OVER (PARTITION BY NAME ORDER BY RESPONDENTBUCKET_ID, SELECTION_ID) DUMMY_COUNT,
	MAX(RESPONDENTBUCKET_ID) KEEP (DENSE_RANK FIRST ORDER BY PROJECT_ID, SELECTION_ID)
FROM
	SELECTION
	LEFT JOIN RESPONDENTBUCKET
		ON SELECTION.RESPONDENTBUCKET_ID = RESPONDENTBUCKET.RESPONDENTBUCKET_ID
	LEFT JOIN TARGETGROUP
		ON RESPONDENTBUCKET.TARGETGROUP_ID = TARGETGROUP.TARGETGROUP_ID
ORDER BY
	NAME,
	SELECTION_ID;"    ;

            _documentRepository.UpdateStatements(sourceFormat);
            var executionContext = new ActionExecutionContext(sourceFormat, 0, 0, 0, _documentRepository);

            Formatter.SingleLineExecutionHandler.ExecutionHandler(executionContext);

            const string expectedFormat = "SELECT SELECTION.NAME, COUNT (*) OVER (PARTITION BY NAME ORDER BY RESPONDENTBUCKET_ID, SELECTION_ID) DUMMY_COUNT, MAX (RESPONDENTBUCKET_ID) KEEP (DENSE_RANK FIRST ORDER BY PROJECT_ID, SELECTION_ID) FROM SELECTION LEFT JOIN RESPONDENTBUCKET ON SELECTION.RESPONDENTBUCKET_ID = RESPONDENTBUCKET.RESPONDENTBUCKET_ID LEFT JOIN TARGETGROUP ON RESPONDENTBUCKET.TARGETGROUP_ID = TARGETGROUP.TARGETGROUP_ID ORDER BY NAME, SELECTION_ID";

            AssertFormattedResult(executionContext, expectedFormat);
        }
Пример #33
0
        private Func<Exception, IEnumerable<IResult>> CreateHandler(ActionExecutionContext context, Type targetType)
        {
            Func<Exception, IEnumerable<IResult>> handler = null;
#if SILVERLIGHT
            // you may not invoke private methods in SL
            const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static;
#elif WPF
            const BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static;
#endif

            var method = targetType.GetMethod(MethodName, bindingFlags, Type.DefaultBinder, new[] { typeof(Exception) }, null)
                ?? targetType.GetMethod(MethodName, bindingFlags);

            if (method == null)
                throw new Exception(string.Format("Could not find method {0} on type {1}",
                                                  MethodName,
                                                  targetType.Name));

            var obj = method.IsStatic ? null : context.Target;
            handler = ex =>
                      {
                          var param = method.GetParameters().Any() ? new object[] { ex } : new object[0];
                          object result = method.Invoke(obj, param);

                          if (result is IResult) return new[] { result as IResult };
                          if (result is IEnumerable<IResult>) return result as IEnumerable<IResult>;

                          return new IResult[0];
                      };

            return handler;
        }
Пример #34
0
        public void Execute(ActionExecutionContext context)
        {
            var screen = IoC.Get <T>();

            initialization.Invoke(screen);

            Dialog = screen;
            WindowManager.ShowDialog(screen);

            var deactivated = screen as IDeactivate;

            if (deactivated == null)
            {
                Completed(this, new ResultCompletionEventArgs());
            }
            else
            {
                deactivated.Deactivated += (o, e) => {
                    if (e.WasClosed)
                    {
                        Completed(this, new ResultCompletionEventArgs());
                    }
                };
            }
        }
Пример #35
0
        /// <summary>
        /// Executes this action.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="context">The context.</param>
        public override void Execute(RootModel model, ActionExecutionContext context)
        {
            Assert.ArgumentNotNull(model, "model");
            Assert.ArgumentNotNull(context, "context");

            model.SetVariableValue(VariableName, ValueToSet.GetParameterValue(model, context), SilentSet);
        }
Пример #36
0
 public void Perform(ActionExecutionContext context)
 {
     context.Out.WriteLine(ConsoleColor.Green, "\nЗарплата сотрудников");
     var employees = EmployeeService.GetEmployees();
     foreach (var employee in employees)
     {
         context.Out.Write(ConsoleColor.Yellow, "============\nИмя: ");
         context.Out.WriteLine(employee.Name);
         context.Out.Write(ConsoleColor.Yellow, "Оклад: ");
         context.Out.WriteLine(employee.Rate + " руб/час");
         context.Out.Write(ConsoleColor.Yellow, "Процентная ставка: ");
         context.Out.WriteLine(employee.Position.Percent*100 + "% ");
         context.Out.WriteLine(ConsoleColor.Yellow, "Выплаты: ");
         var payments = PaymentService.GetListByEmployeeId(employee.Id);
         foreach (var payment in payments)
         {
             context.Out.Write(ConsoleColor.Blue, "Начало периода оплаты: ");
             context.Out.WriteLine(payment.DateFrom.ToShortDateString());
             context.Out.Write(ConsoleColor.Blue, "Конец периода оплаты: ");
             context.Out.WriteLine(payment.DateTo.ToShortDateString());
             context.Out.Write(ConsoleColor.Blue, "Отработано часов: ");
             context.Out.WriteLine(PaymentService.GetWorkedHours(employee.Id, payment.DateFrom, payment.DateTo).HoursWorked.ToString());
             context.Out.Write(ConsoleColor.Blue, "Переработано часов: ");
             context.Out.WriteLine(PaymentService.GetWorkedHours(employee.Id, payment.DateFrom, payment.DateTo).OverHoursWorked.ToString());
             context.Out.Write(ConsoleColor.Blue, "Общая сумма выплаты: ");
             context.Out.WriteLine(ConsoleColor.Red, payment.Summ.ToString());
             context.Out.Write(ConsoleColor.Blue, "Информация по выплате: ");
             context.Out.WriteLine(payment.Information);
         }
     }
 }
Пример #37
0
        public void UpdateKey(ActionExecutionContext context)
        {
            var eventArgs = (KeyEventArgs)context.EventArgs;

            if (eventArgs.Key == Key.None ||
                eventArgs.Key == Key.LeftShift ||
                eventArgs.Key == Key.RightShift ||
                eventArgs.Key == Key.LeftAlt ||
                eventArgs.Key == Key.RightAlt)
            {
                return;
            }

            KeyBinding keyGesture;

            try
            {
                keyGesture = new KeyBinding
                {
                    Key       = eventArgs.Key == Key.System ? eventArgs.SystemKey : eventArgs.Key,
                    Modifiers = eventArgs.KeyboardDevice.Modifiers
                };
            }
            catch (Exception)
            {
                return;
            }

            CurrentGesture    = keyGesture;
            eventArgs.Handled = true;
        }
 public void Execute(ActionExecutionContext context)
 {
     CommandInvoker.InvokeBusy(_command, _busyScope,
                               exception => Completed(this, new ResultCompletionEventArgs {
         Error = exception
     }));
 }
Пример #39
0
        public Guid CreateNewCustomer(ActionExecutionContext context)
        {
            var customer = new CustomerDto();

            context.Out.WriteLine(ConsoleColor.Yellow, "NEW CUSTOMER");
            context.Out.WriteLine("Enter address");
            var adress = context.In.ReadLine();

            context.Out.WriteLine("Enter phone");
            var phone = context.In.ReadLine();

            context.Out.WriteLine("Does customer have a card(y/n):");
            var temp = context.In.ReadLine();

            if (!temp.Equals("y") && !temp.Equals("n"))
            {
                context.Out.WriteLine("Does customer have a card(y/n):");
                temp = context.In.ReadLine();
            }
            bool card = temp.Equals("y") ? true : false;

            customer.Address = adress;
            customer.Phone   = phone;
            customer.Card    = card;
            Guid customerId = _customerApi.AddNewCustomer(customer);

            return(customerId);
        }
        /// <summary>
        /// Gets the parameter value.
        /// </summary>
        /// <param name="rootModel">The root model.</param>
        /// <param name="context">The context.</param>
        /// <returns>
        /// Parameter value.
        /// </returns>
        public override string GetParameterValue(RootModel rootModel, ActionExecutionContext context)
        {
            Assert.ArgumentNotNull(rootModel, "rootModel");
            Assert.ArgumentNotNull(context, "context");

            return(rootModel.GetVariableValue(VariableName));
        }
Пример #41
0
 public ResultExecutionTask(IResult result, ActionExecutionContext context)
 {
     Result                      = result;
     Context                     = context;
     CompletionEventArgs         = new ResultCompletionEventArgs();
     ExecutionCompleteWaitHandle = new ManualResetEvent(false);
 }
Пример #42
0
        void IResult.Execute(ActionExecutionContext context)
        {
            if (!CanExecute(context))
            {
                CompletedEvent(this, new ResultCompletionEventArgs {
                    WasCancelled = true
                });
                return;
            }

            try
            {
                EventHandler <ResultCompletionEventArgs> onCompletion = null;
                onCompletion = (o, e) =>
                {
                    inner.Completed -= onCompletion;
                    AfterExecute(context);
                    FinalizeExecution(context, e.WasCancelled, e.Error);
                };
                inner.Completed += onCompletion;

                BeforeExecute(context);
                Execute(inner, context);
            }
            catch (Exception ex)
            {
                FinalizeExecution(context, false, ex);
            }
        }
 public void MakeAwareOf(ActionExecutionContext context)
 {
     this._context = context;
     this._inpc = context.Target as INotifyPropertyChanged;
     if (this._inpc != null)
     {
         this._inpc.PropertyChanged += this.inpc_PropertyChanged;
     }
 }
 /// <summary>
 /// Called when the execution of the decorated result has completed.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="innerResult">The decorated result.</param>
 /// <param name="args">The <see cref="ResultCompletionEventArgs" /> instance containing the event data.</param>
 protected override void OnInnerResultCompleted(ActionExecutionContext context, IResult innerResult, ResultCompletionEventArgs args) {
     if (args.Error != null || !args.WasCancelled) {
         OnCompleted(new ResultCompletionEventArgs {Error = args.Error});
     }
     else {
         Log.Info(string.Format("Executing coroutine because {0} was cancelled.", innerResult.GetType().Name));
         Continue(context);
     }
 }
 /// <summary>
 /// Executes the result using the specified context.
 /// </summary>
 /// <param name="context">The context.</param>
 public void Execute(ActionExecutionContext context) {
     try {
         toExecute();
         Completed(this, new ResultCompletionEventArgs());
     }
     catch (Exception ex) {
         Completed(this, new ResultCompletionEventArgs {Error = ex});
     }
 }
		public void OnExecuting(ActionExecutionContext context)
		{
			Precondition.Require(context, () => Error.ArgumentNull("context"));

			IAsyncManagerContainer container = (context.Context.Controller as IAsyncManagerContainer);
			Precondition.Require(container, () => Error.ControllerMustImplementAsyncManagerContainer(
				context.Context.Controller.GetType()));
			
			container.AsyncManager.Timeout = Duration;
		}
Пример #47
0
        public void Execute(ActionExecutionContext context)
        {
            var message = _args.Any()
                              ? string.Format(_format, _args)
                              : _format;

            Shell.Log(message);

            Completed(this, new ResultCompletionEventArgs());
        }
Пример #48
0
 private void ContinueSaleCreation(ActionExecutionContext context, Guid employeeId)
 {
     context.Out.Write(ConsoleColor.Blue, "Введите сумму продажи: ");
     var summ = context.In.ReadDecimal();
     var employee = EmployeeService.GetEmployeeById(employeeId);
     context.Out.Write(ConsoleColor.Blue, "Введите дату продажи (dd-mm-yyyy): ");
     var date = context.In.ReadLine();
     DateTime dateResult;
     DateTime.TryParse(date, out dateResult);
     SaleService.AddSale(employee, dateResult, summ);
 }
Пример #49
0
        public virtual void Execute(ActionExecutionContext context)
        {
            // Wrap the inner result in a SequentialResult s.t. it gets injected by the container but avoid deep nesting
            var wrapper = (_inner is SequentialResult || _inner is ResultDecoratorBase)
                              ? _inner
                              : new SequentialResult(new SingleResultEnumerator(_inner));

            wrapper.Completed += InnerCompleted;

            wrapper.Execute(context);
        }
Пример #50
0
        public override IEnumerable<IResult> Decorate(IEnumerable<IResult> coroutine, ActionExecutionContext context)
        {
            var targetType = context.Target.GetType();

            Func<Exception, IEnumerable<IResult>> handler = CreateHandler(context, targetType);

            var sequentialResult = new SequentialResult(coroutine.GetEnumerator());

            yield return sequentialResult
                .Rescue().Execute(handler);
        }
        /// <summary>
        /// Executes the result using the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public void Execute(ActionExecutionContext context) {
            this.context = context;

            try {
                innerResult.Completed += InnerResultCompleted;
                IoC.BuildUp(innerResult);
                innerResult.Execute(this.context);
            }
            catch (Exception ex) {
                InnerResultCompleted(innerResult, new ResultCompletionEventArgs { Error = ex });
            }
        }
Пример #52
0
 public void ContinueTimesheetCreation(ActionExecutionContext context, Guid employeeId)
 {
     var employee = EmployeeService.GetEmployeeById(employeeId);
     context.Out.WriteLine("Введите количество отработанных часов: ");
     decimal hours = context.In.ReadDecimal();
     context.Out.WriteLine("Введите дату отработки (dd-mm-yyyy): ");
     var date = context.In.ReadLine();
     DateTime dateResult;
     bool tryParse = DateTime.TryParse(date, out dateResult);
     context.Out.WriteLine("Это переработка? (1/0) ");
     var overWork = context.In.ReadInt32() == 1;
     TimesheetService.AddTimesheet(employee, dateResult, hours, overWork);
 }
Пример #53
0
        void IResult.Execute(ActionExecutionContext context)
        {
            var dialog = CreateDialog();

            dialog.FileOk += FileOk;

            dialog.ShowDialog();

            if (_cancelled)
            {
                OnCompleted(dialog, new ResultCompletionEventArgs {WasCancelled = !_ignoreUserCancel});
            }
        }
Пример #54
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());
        }
Пример #55
0
        public override void Execute(ActionExecutionContext context)
        {
            _context = context;

            UpdateIndicator(context, _message);

            // Wrap the inner result in a SequentialResult s.t. it gets injected by the container but avoid deep nesting
            var wrapper = new WorkerThreadResultDecorator(_inner);

            wrapper.Completed += OnInnerCompleted;

            wrapper.Execute(context);
        }
Пример #56
0
 public void ContinueAwardCreation(ActionExecutionContext context, Guid employeeId)
 {
     context.Out.Write(ConsoleColor.Blue, "Введите сумму премии: ");
     var summ = context.In.ReadDecimal();
     var employee = EmployeeService.GetEmployeeById(employeeId);
     context.Out.Write(ConsoleColor.Blue, "Введите дату премии (dd-mm-yyyy): ");
     var date = context.In.ReadLine();
     context.Out.Write(ConsoleColor.Blue, "Описание");
     var description = context.In.ReadLine();
     DateTime dateResult;
     DateTime.TryParse(date, out dateResult);
     AwardService.AddAward(employeeId, dateResult, summ, description);
 }
Пример #57
0
 public void Perform(ActionExecutionContext context)
 {
     context.Out.WriteLine(ConsoleColor.Green, "\nЗарплата сотрудников");
     var employees = EmployeeService.GetEmployees();
     foreach (var type in employees)
     {
         context.Out.Write(ConsoleColor.Yellow, "============\nИмя: ");
         context.Out.WriteLine(type.Name);
         context.Out.Write(ConsoleColor.Yellow, "Оклад: ");
         context.Out.WriteLine(type.Rate + " руб/час");
         context.Out.Write(ConsoleColor.Yellow, "З/п: ");
         context.Out.WriteLine(PaymentService.Payroll(type) + " руб.");
     }
 }
Пример #58
0
 public void Perform(ActionExecutionContext context)
 {
     var submenuBuilder = new MenuBuilder()
         .RunnableOnce();
     var employees = EmployeeService.GetEmployees();
     foreach (var employee in employees)
     {
         var employeeId = employee.Id;
         submenuBuilder.Item(
             string.Format("{0}", employee.Name),
             ctx => ContinuePaymentCreation(ctx, employeeId));
     }
     submenuBuilder.GetMenu().Run();
 }
        internal static void InvokeAction(ActionExecutionContext context, object[] values)
        {
            var returnValue = context.Method.Invoke(context.Target, values);

            var task = returnValue as System.Threading.Tasks.Task;
            if (task != null)
            {
                returnValue = task.AsResult();
            }

            var result = returnValue as IResult;
            if (result != null)
            {
                returnValue = new[] { result };
            }

            var enumerable = returnValue as IEnumerable<IResult>;
            if (enumerable != null)
            {
                returnValue = enumerable.GetEnumerator();
            }

            var enumerator = returnValue as IEnumerator<IResult>;
            if (enumerator != null)
            {
                result = Coroutine.CreateParentEnumerator(enumerator);
                var wrappers = FilterManager.GetFiltersFor(context).OfType<IExecutionWrapper>();
                var pipeline = result.WrapWith(wrappers);
                //if pipeline has error, action execution should throw! 
                pipeline.Completed += (o, e) => Execute.OnUIThread(
                    () =>
                    {
                        if (e.Error != null)
                        {
                            throw new Exception(
                                string.Format("An error occurred while executing {0}", context.Message),
                                e.Error
                                );
                        }
                    });
                pipeline.Execute(
                    new CoroutineExecutionContext
                        {
                            Source = context.Source,
                            View = context.View,
                            Target = context.Target
                        });
            }
        }
Пример #60
0
        public void Execute(ActionExecutionContext context)
        {
            var resultArgs = new ResultCompletionEventArgs();

            try
            {
                _action();
            }
            catch (Exception e)
            {
                resultArgs.Error = e;
            }

            Completed(this, resultArgs);
        }