protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
        {
            Func<Int32, List<SalesOrderDetail>> asyncWork = orderId => RetrieveOrderDetail(orderId);
            context.UserState = asyncWork;
            return asyncWork.BeginInvoke(SalesOrderId.Get(context), callback, state);

        }
 internal sealed override void InternalExecute(System.Activities.ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)
 {
     AsyncOperationContext asyncContext = executor.SetupAsyncOperationBlock(instance);
     instance.IncrementBusyCount();
     AsyncCodeActivityContext context = new AsyncCodeActivityContext(asyncContext, instance, executor);
     bool flag = false;
     try
     {
         IAsyncResult result = this.BeginExecute(context, OnExecuteComplete, asyncContext);
         if (result == null)
         {
             throw FxTrace.Exception.AsError(new InvalidOperationException(System.Activities.SR.BeginExecuteMustNotReturnANullAsyncResult));
         }
         if (!object.ReferenceEquals(result.AsyncState, asyncContext))
         {
             throw FxTrace.Exception.AsError(new InvalidOperationException(System.Activities.SR.BeginExecuteMustUseProvidedStateAsAsyncResultState));
         }
         if (result.CompletedSynchronously)
         {
             this.EndExecute(context, result);
             asyncContext.CompleteOperation();
         }
         flag = true;
     }
     finally
     {
         context.Dispose();
         if (!flag)
         {
             asyncContext.CancelOperation();
         }
     }
 }
        protected override sealed IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
        {
            var cts = new CancellationTokenSource();
            context.UserState = cts;

            var tcs = new TaskCompletionSource<bool>(state);

            ExecuteAsync(context, cts.Token).ContinueWith(t =>
            {
                if (t.IsFaulted)
                {
                    tcs.TrySetResult(false);
                    tcs.TrySetException(t.Exception.InnerExceptions);
                }
                else if (t.IsCanceled)
                {
                    tcs.TrySetResult(false);
                    tcs.TrySetCanceled();
                }
                else tcs.TrySetResult(true);

                if (callback != null)
                    callback(tcs.Task);
            });
            return tcs.Task;
        }
        protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state) {
            MailMessage mail = new MailMessage();
            mail.To.Add(ToAddress.Get(context));

            mail.From = new MailAddress(FromAddress.Get(context));

            mail.Subject = Subject.Get(context);


            mail.Body = Body.Get(context);

            mail.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient() ;

            Action action = () => {
                                ManualResetEvent manualResetEvent = new ManualResetEvent(false);
                                smtp.SendCompleted += (o, args) => {
                                                          manualResetEvent.Set();
                                                          Debug.WriteLine("Send Mail Completed");
                                                      };
                                smtp.SendAsync(mail, null);
                                manualResetEvent.WaitOne(TimeSpan.FromSeconds(30));
                            };

            context.UserState = action;

            return action.BeginInvoke(callback, state);
        }
 protected override sealed void Cancel(AsyncCodeActivityContext context)
 {
     if (context.UserState is CancellationTokenSource)
     {
         var cts = (CancellationTokenSource)context.UserState;
         cts.Cancel();
     }
 }
        protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
        {
            var message = Message.Get(context);

            var MarkAsReadDelegate = new Action<EmailMessage>(MarkAsRead);
            context.UserState = MarkAsReadDelegate;
            return MarkAsReadDelegate.BeginInvoke(message, callback, state);            
        }
 protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
 {
     Action<SalesOrderDetail, String> asyncWork =
     (sale, desc) => DisplayInventory(sale, desc);
     context.UserState = asyncWork;
     return asyncWork.BeginInvoke(
     SalesDetail.Get(context), Description.Get(context),
     callback, state);
 }
        protected override void EndExecute(AsyncCodeActivityContext context, IAsyncResult result)
        {
            List<SalesOrderDetail> orderDetail =((Func<Int32, List<SalesOrderDetail>>)context.UserState).EndInvoke(result);
            if (orderDetail != null)
            {
                OrderDetail.Set(context, orderDetail);
            }

        }
Exemple #9
0
        protected override IAsyncResult BeginExecute(AsyncCodeActivityContext activityContext, AsyncCallback callback, object state)
        {
            var period = DelayPeriod.Get(activityContext);
            var cancelable = Cancelable.Get(activityContext);

            Guid workflowInstanceGuid = activityContext.WorkflowInstanceId;
            string activityInstanceId = activityContext.ActivityInstanceId;
            return EnqueueAsync(_ => OnAsyncExecute(workflowInstanceGuid, activityInstanceId, period, cancelable), callback, state);
        }
 protected override IAsyncResult BeginExecute(
     AsyncCodeActivityContext context, AsyncCallback callback, object state)
 {
     this.InitializeSmtpClient(context);
     this.mailCompletionSource = new TaskCompletionSource<bool>(state);
     this.workflowCallback = callback;
     this.SendMailAsync(this.CreateMailMessage(context));
     return this.mailCompletionSource.Task;
 }
Exemple #11
0
        /// <summary>
        /// When implemented in a derived class and using the specified execution context, callback method, and user state, enqueues an asynchronous activity in a run-time workflow. 
        /// </summary>
        /// <returns>
        /// The object that saves variable information for an instance of an asynchronous activity.
        /// </returns>
        /// <param name="context">Information that defines the execution environment for the <see cref="T:System.Activities.AsyncCodeActivity"/>.</param><param name="callback">The method to be called after the asynchronous activity and completion notification have occurred.</param><param name="state">An object that saves variable information for an instance of an asynchronous activity.</param>
        protected override IAsyncResult BeginExecute(
            AsyncCodeActivityContext context, AsyncCallback callback, object state)
        {
            var sleep = this.Sleep.Get(context);

            Action action = () => Thread.Sleep(sleep);

            context.UserState = action;

            return action.BeginInvoke(callback, state);
        }
        /// <summary>
        /// The begin execute.
        /// </summary>
        /// <param name="context">
        /// The context. 
        /// </param>
        /// <param name="callback">
        /// The callback. 
        /// </param>
        /// <param name="state">
        /// The state. 
        /// </param>
        /// <returns>
        /// The System.IAsyncResult. 
        /// </returns>
        protected override IAsyncResult BeginExecute(
            AsyncCodeActivityContext context, AsyncCallback callback, object state)
        {
            var token = context.GetExtension<ActivityCancellationToken>();

            var notify = context.GetExtension<SpinNotify>();

            Action<ActivityCancellationToken, SpinNotify> action = this.DoSpinWait;
            context.UserState = action;
            return action.BeginInvoke(token, notify, callback, state);
        }
 protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
 {
     var hc = new HttpClient();
     var task = hc
         .PostAsync(context.GetValue(网址), context.GetValue(Http内容))
         .ToApm(callback, state);
     task.ContinueWith(q =>
             hc.Dispose()
         );
     return task;
 }
Exemple #14
0
        protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
        {
            string tempFileName = Path.GetTempFileName();
            Console.WriteLine("Writing to file: " + tempFileName);

            FileStream file = File.Open(tempFileName, FileMode.Create);

            context.UserState = file;

            byte[] bytes = UnicodeEncoding.Unicode.GetBytes("123456789");
            return file.BeginWrite(bytes, 0, bytes.Length, callback, state);
        }
 /// <summary>
 /// When implemented in a derived class and using the specified execution context, callback method, and user state, enqueues an asynchronous activity in a run-time workflow. 
 /// </summary>
 /// <returns>
 /// The object that saves variable information for an instance of an asynchronous activity.
 /// </returns>
 /// <param name="context">Information that defines the execution environment for the <see cref="T:System.Activities.AsyncCodeActivity"/>.</param><param name="callback">The method to be called after the asynchronous activity and completion notification have occurred.</param><param name="state">An object that saves variable information for an instance of an asynchronous activity.</param>
 protected override IAsyncResult BeginExecute(
     AsyncCodeActivityContext context, AsyncCallback callback, object state)
 {
     return
         ((Action<string, RegistrationData, Guid, int>)LoadTemplate).BeginInvoke(
             this.Data.Get(context).EmailTemplates.ElementAt(this.EmailTemplateIndex.Get(context)),
             this.Data.Get(context),
             context.WorkflowInstanceId,
             this.EmailTemplateIndex.Get(context),
             callback,
             state);
 }
 internal sealed override void InternalCancel(System.Activities.ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)
 {
     AsyncOperationContext context;
     if (executor.TryGetPendingOperation(instance, out context))
     {
         using (AsyncCodeActivityContext context2 = new AsyncCodeActivityContext(context, instance, executor))
         {
             context.HasCalledAsyncCodeActivityCancel = true;
             this.Cancel(context2);
         }
     }
 }
        protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
        {
            var provider = Provider.Get(context);

            Action work = () =>
            {
                provider.Reinitialize();
            };

            context.UserState = work;

            return work.BeginInvoke(callback, state);
        }
 public IAsyncResult BeginExecuteMethod(AsyncCodeActivityContext context, AsyncCallback callback, object state)
 {
     object target = null;
     if (!this.MethodIsStatic)
     {
         target = this.targetObject.Get(context);
         if (target == null)
         {
             throw FxTrace.Exception.ArgumentNull("TargetObject");
         }
     }
     return this.BeginMakeMethodCall(context, target, callback, state);
 }
Exemple #19
0
        protected override IAsyncResult BeginExecute(AsyncCodeActivityContext activityContext, AsyncCallback callback, object state)
        {
            QueryPartitionBase querypartition = QueryPartition.Get(activityContext);

            using (var context = querypartition.Query.CreateContext(this, activityContext, ConnectionMode.AutoOpen, TransactionMode.AutoCommit))
            {
                querypartition.PrepareCopyResultset(context);
            }

            Guid workflowInstanceGuid = activityContext.WorkflowInstanceId;
            string activityInstanceId = activityContext.ActivityInstanceId;
            return EnqueueAsync(_ => OnAsyncExecute(workflowInstanceGuid, activityInstanceId, querypartition), callback, state);
        }
        protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
        {
            sourceConnection =
                   new SqlConnection(connectionStringOrigem.Get(context));

            sourceConnection.Open();

            commandSourceData = new SqlCommand(Query.Get(context), sourceConnection);
            var task =
                commandSourceData.BeginExecuteReader(callback, state, System.Data.CommandBehavior.Default);

            return task;
        }
Exemple #21
0
        protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
        {
            if (Application.Current == null)
            {
                throw new InvalidOperationException("Must have an application");
            }

            DispatcherSynchronizationContext syncContext = new DispatcherSynchronizationContext(Application.Current.Dispatcher);
            object dataContext = context.DataContext;
            Action showDelegate = () => syncContext.Send(Show, dataContext);
            context.UserState = showDelegate;

            return showDelegate.BeginInvoke(callback, state);
        }
        /// <summary>
        /// Cancels the execution of the activity.
        /// </summary>
        /// <param name="context"></param>
        /// <remarks>
        /// This method cancels all registered runnin cancelable tasks before marking the
        /// activity canceled.
        /// </remarks>
        protected override void Cancel(AsyncCodeActivityContext context)
        {
            string id = String.Format("{0}_{1}", context.WorkflowInstanceId.ToString(), context.ActivityInstanceId);

            if (cancelableTasks.ContainsKey(id))
            {
                cancelableTasks[id].Cancel();
            }

            // This is absolutely important here:
            context.MarkCanceled();

            base.Cancel(context);
        }
Exemple #23
0
        protected override void EndExecute(AsyncCodeActivityContext context, IAsyncResult result)
        {
            FileStream file = (FileStream)context.UserState;

            try
            {
                file.EndWrite(result);
                file.Flush();
            }
            finally
            {
                file.Close();
            }
        }
        protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
        {
            DependentTransaction dependentTran = null;
            if (Transaction.Current != null)
            {
                dependentTran = Transaction.Current.DependentClone(
                DependentCloneOption.BlockCommitUntilComplete);
            }

            Action<DependentTransaction, SalesOrderDetail> asyncWork =(dt, sale) => UpdateInventory(dt, sale);
            context.UserState = asyncWork;
            return asyncWork.BeginInvoke(dependentTran, SalesDetail.Get(context), callback, state);


        }
        protected override IAsyncResult BeginExecute(AsyncCodeActivityContext activityContext, AsyncCallback callback, object state)
        {
            var query = Query.Get(activityContext);
            var tableReference = TableReference.Get(activityContext);
            string connectionString, sql;

            using (Context context = query.CreateContext(this, activityContext, ConnectionMode.AutoOpen, TransactionMode.AutoCommit))
            {
                query.InitializeQueryObject(context, activityContext.GetExtension<IScheduler>(), false);
                query.PrepareComputeTableStatistics(context, tableReference, out connectionString, out sql);
            }

            Guid workflowInstanceGuid = activityContext.WorkflowInstanceId;
            string activityInstanceId = activityContext.ActivityInstanceId;
            return EnqueueAsync(_ => OnAsyncExecute(workflowInstanceGuid, activityInstanceId, query, tableReference, connectionString, sql), callback, state);
        }
        protected override IAsyncResult BeginExecute(AsyncCodeActivityContext activityContext, AsyncCallback callback, object state)
        {
            Guid sourcefileguid = SourceFileGuid.Get(activityContext);
            Guid destinationdatabaseinstanceguid = DestinationDatabaseInstanceGuid.Get(activityContext);
            FileCopyDirection filecopydirection = FileCopyDirection.Get(activityContext);

            string sourcefilename, destinationfilename;
            string hostname;

            // Load files
            using (Context context = ContextManager.Instance.CreateContext(this, activityContext, ConnectionMode.AutoOpen, TransactionMode.AutoCommit))
            {
                // Load destination database instance
                DatabaseInstance di = new DatabaseInstance(context);
                di.Guid = destinationdatabaseinstanceguid;
                di.Load();
                di.LoadFileGroups(false);

                EntityGuid.Set(activityContext, di.Guid);

                // Load database instance from the schema database
                DatabaseInstanceFile df;

                DatabaseInstanceFile sf = new DatabaseInstanceFile(context);
                sf.Guid = sourcefileguid;
                sf.Load();

                EntityGuidFrom.Set(activityContext, sourcefileguid);

                sourcefilename = sf.GetFullUncFilename();

                DatabaseInstanceFileGroup fg = di.FileGroups[sf.DatabaseInstanceFileGroup.Name];
                fg.LoadFiles(false);
                df = fg.Files[sf.Name];

                EntityGuidTo.Set(activityContext, df.Guid);

                destinationfilename = df.GetFullUncFilename();

                DatabaseInstanceFile ssf = filecopydirection == Jhu.Graywulf.Registry.FileCopyDirection.Push ? sf : df;
                hostname = ssf.DatabaseInstanceFileGroup.DatabaseInstance.ServerInstance.Machine.HostName.ResolvedValue;
            }

            Guid workflowInstanceGuid = activityContext.WorkflowInstanceId;
            string activityInstanceId = activityContext.ActivityInstanceId;
            return EnqueueAsync(_ => OnAsyncExecute(workflowInstanceGuid, activityInstanceId, hostname, sourcefilename, destinationfilename), callback, state);
        }
        /// <summary>
        /// Begin async execute
        /// </summary>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <param name="callback">
        /// The callback.
        /// </param>
        /// <param name="state">
        /// The state.
        /// </param>
        /// <returns>
        /// An IAsync result
        /// </returns>
        protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
        {
            var stub = context.GetExtension<IMessagingStub>();

            if (stub == null)
            {
                throw new InvalidOperationException("Cannot locate extension of type IMessagingStub");
            }

            if (this.Content is SendParametersContent)
            {
                {
                    var parametersContent = this.Content as SendParametersContent;
                    this.Send(stub, parametersContent.Parameters.ToDictionary(pair => pair.Key, pair => parametersContent.Parameters[pair.Key].Get(context)));
                }
            }
            else if (this.Content is SendMessageContent)
            {
                var messageContent = this.Content as SendMessageContent;
                this.Send(stub, messageContent.Message.Get(context));
            }
            else
            {
                this.Send(stub, null);
            }

            var task = Task.Factory.StartNew(
                _ =>
                {
                    // Allow for subclasses to provide different implementations based on the activity
                    // They can override GetImplementation to provide it
                    var implementation = stub.GetImplementation(this);
                    if (implementation != null)
                    {
                        implementation();
                    }
                },
                state);

            if (callback != null)
            {
                task.ContinueWith(_ => callback(task));
            }

            return task;
        }
        protected override IAsyncResult BeginExecute(AsyncCodeActivityContext activityContext, AsyncCallback callback, object state)
        {
            QueryPartitionBase querypartition = (QueryPartitionBase)QueryPartition.Get(activityContext);

            TableReference remotetable = null;
            SourceQueryParameters source;

            using (Context context = querypartition.Query.CreateContext(this, activityContext, ConnectionMode.AutoOpen, TransactionMode.AutoCommit))
            {
                remotetable = querypartition.RemoteTableReferences[RemoteTable.Get(activityContext)];
                source = querypartition.PrepareCopyRemoteTable(remotetable);
            }

            Guid workflowInstanceGuid = activityContext.WorkflowInstanceId;
            string activityInstanceId = activityContext.ActivityInstanceId;
            return EnqueueAsync(_ => OnAsyncExecute(workflowInstanceGuid, activityInstanceId, querypartition, remotetable, source), callback, state);
        }
 protected override void EndExecute(AsyncCodeActivityContext context, IAsyncResult result)
 {
     try
     {
         ((Task)result).Wait();
     }
     catch (AggregateException ex)
     {
         if (ex.InnerException is OperationCanceledException)
         {
             // This is a normal way of operation
         }
         else
         {
             throw;
         }
     }
 }
Exemple #30
0
        protected override IAsyncResult BeginExecute(AsyncCodeActivityContext activityContext, AsyncCallback callback, object state)
        {
            var export = Parameters.Get(activityContext);

            // TODO: try to generalize connection string loading logic and move this from here
            // Use connection string of the database instance, if only database instance name is supplied
            if (export.Source.Dataset is GraywulfDataset)
            {
                // Load database instace and get connection string to make it cached
                using (var context = ContextManager.Instance.CreateContext(this, activityContext, ConnectionMode.AutoOpen, TransactionMode.AutoCommit))
                {
                    var gwds = (GraywulfDataset)export.Source.Dataset;
                    gwds.Context = context;
                    gwds.DatabaseInstance.Value.GetConnectionString();
                }
            }

            Guid workflowInstanceGuid = activityContext.WorkflowInstanceId;
            string activityInstanceId = activityContext.ActivityInstanceId;
            return EnqueueAsync(_ => OnAsyncExecute(workflowInstanceGuid, activityInstanceId, export), callback, state);
        }
Exemple #31
0
 protected abstract void EndExecute(AsyncCodeActivityContext context, IAsyncResult result);
 public Transaction GetCurrentTransaction(AsyncCodeActivityContext context)
 {
     return(GetCurrentTransactionCore(context));
 }
Exemple #33
0
        void IAsyncCodeActivity.FinishExecution(AsyncCodeActivityContext context, IAsyncResult result)
        {
            TResult local = this.EndExecute(context, result);

            base.Result.Set(context, local);
        }
Exemple #34
0
 void IAsyncCodeActivity.FinishExecution(AsyncCodeActivityContext context, IAsyncResult result)
 {
     this.EndExecute(context, result);
 }
Exemple #35
0
 protected abstract IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state);
Exemple #36
0
 // called on the Cancel and Abort paths to allow cleanup of outstanding async work
 protected virtual void Cancel(AsyncCodeActivityContext context)
 {
 }
Exemple #37
0
 public Transaction GetCurrentTransaction(AsyncCodeActivityContext context)
 {
     throw new NotImplementedException();
 }