Exemple #1
0
        sealed protected override void Execute(NativeActivityContext context)
        {
            //HACK:节点执行时总是首先设置当前节点索引
            context.GetExtension<DataFieldExtension>().SetCurrentNode(this.FlowNodeIndex);

            var e = context.GetExtension<CustomExtension>();
            var setting = e.GetActivitySetting(this.DisplayName);

            if (setting == null)
            {
                this.InternalExecuteBody(context);
                return;
            }

            var at = setting.StartRule != null && setting.StartRule.IsValid
                ? setting.StartRule.GetStartTime()
                : _emptyTime;
            //触发节点开始规则,创建延迟书签
            if (at.HasValue)
                e.AddDelay(this.DisplayName
                    , context.CreateBookmark(this.GenerateBookmarkName(context)
                    , this.OnDelayBookmarkCallback).Name
                    , at.Value);
            else
                this.InternalExecuteBody(context);
        }
Exemple #2
0
        protected override void ExecuteBody(NativeActivityContext context)
        {
            var log = context.Resolve<ILoggerFactory>() == null
                ? null
                : context.Resolve<ILoggerFactory>().Create(typeof(Server));

            //创建server节点实例
            var server = context.GetExtension<ServerExtension>().AddServer(context, this.DisplayName, this.FlowNodeIndex);
            var data = context.GetExtension<DataFieldExtension>();
            //设置当前节点索引
            data.SetCurrentNode(this.FlowNodeIndex);

            var serverScript = this.Script == null ? null : this.Script.Get(context);
            var parser = context.Resolve<IScriptParser>();

            #region 执行内容解析
            if (!string.IsNullOrEmpty(serverScript))
            {
                var result = parser == null
                    ? serverScript
                    : parser.Evaluate(serverScript, context.GetExtension<DataFieldExtension>());
                if (this.To != null)
                {
                    this.To.Set(context, result);
                    //更新到流程变量中
                    data.Set(this._to, result);
                }

                log.InfoFormat("Server节点执行内容:{0},返回:{1} {2}"
                    , serverScript
                    , result
                    , this.To == null ? "" : "将返回值写入流程变量" + this._to);
            }
            #endregion

            #region 完成规则解析
            if (this.Result != null
                && parser != null
                && this.FinishRule != null
                && this.FinishRule.Count > 0)
            {
                foreach (var i in this.FinishRule)
                    if (parser.EvaluateRule(i.Value, data))
                    {
                        this.Result.Set(context, i.Key);
                        log.InfoFormat("Server节点完成规则“{0}”测试通过,将进入节点“{1}”", i.Value, i.Key);
                        break;
                    }
            }
            #endregion

            //置为完成
            server.SetAsComplete();
        }
        protected override void Execute(NativeActivityContext context)
        {
            CorrelationHandle correlationHandle = (this.Correlation == null) ? null : this.Correlation.Get(context);

            if (correlationHandle == null)
            {
                //throw only if ambient correlation handle is also null
                correlationHandle = context.Properties.Find(CorrelationHandle.StaticExecutionPropertyName) as CorrelationHandle;
                if (correlationHandle == null)
                {
                    throw FxTrace.Exception.AsError(
                        new InvalidOperationException(SR2.NullCorrelationHandleInInitializeCorrelation(this.DisplayName)));
                }
            }
 
            CorrelationExtension extension = context.GetExtension<CorrelationExtension>();
            if (extension != null)
            {
                Dictionary<string, string> dictionary = new Dictionary<string, string>();
                foreach ( KeyValuePair<string, InArgument<string>> pair in this.CorrelationData )
                {
                    Fx.Assert(pair.Value != null, "pair.Value should be validated during cache metadata");
                    dictionary.Add(pair.Key, pair.Value.Get(context));
                }

                correlationHandle.InitializeBookmarkScope(context, extension.GenerateKey(dictionary));
            }
            else
            {
                throw FxTrace.Exception.AsError(new InvalidOperationException(SR2.InitializeCorrelationRequiresWorkflowServiceHost(this.DisplayName)));
            }
        }
        void InternalExecute(NativeActivityContext context, ActivityInstance completedInstance)
        {
            CompensationExtension compensationExtension = context.GetExtension<CompensationExtension>();
            if (compensationExtension == null)
            {
                throw FxTrace.Exception.AsError(new InvalidOperationException(SR.ConfirmWithoutCompensableActivity(this.DisplayName)));
            }

            CompensationToken token = Target.Get(context);
            CompensationTokenData tokenData = token == null ? null : compensationExtension.Get(token.CompensationId);

            Fx.Assert(tokenData != null, "CompensationTokenData must be valid");

            if (tokenData.ExecutionTracker.Count > 0)
            {
                if (this.onChildConfirmed == null)
                {
                    this.onChildConfirmed = new CompletionCallback(InternalExecute);
                }

                this.toConfirmToken.Set(context, new CompensationToken(tokenData.ExecutionTracker.Get()));

                Fx.Assert(Body != null, "Body must be valid");
                context.ScheduleActivity(Body, this.onChildConfirmed);
            }
        }
Exemple #5
0
        private void OnBookmarkCallback(NativeActivityContext context, Bookmark bookmark)
        {
            var log = context.Resolve<ILoggerFactory>() != null
                    ? context.Resolve<ILoggerFactory>().Create(typeof(SubProcess))
                    : null;
            var parser = context.Resolve<IScriptParser>();
            var extension = context.GetExtension<DataFieldExtension>();

            //完成规则解析
            if (this.Result != null
                && parser != null
                && this.FinishRule != null
                && this.FinishRule.Count > 0)
            {
                foreach (var i in this.FinishRule)
                    if (parser.EvaluateRule(i.Value, extension))
                    {
                        this.Result.Set(context, i.Key);
                        if (log != null)
                            log.InfoFormat("SubProcess节点完成规则“{0}”测试通过,将进入节点“{1}”", i.Value, i.Key);
                        break;
                    }
            }
            //所有逻辑完成才可删除,若上述逻辑失败则将此书签用于错误恢复
            context.RemoveBookmark(bookmark);
        }
Exemple #6
0
        private void BookmarkResumed(NativeActivityContext context, Bookmark bookmark, object value)
        {
            var dict = (Dictionary<string,object>)value;
            var company = (Guid)dict["CompanyID"];
            var contact = (Guid)dict["ContactID"];
            this.SubmittedCompanyID.Set(context, company);
            this.SubmittedContactID.Set(context, contact);
            context.GetExtension<ResponsibilityExtension>().CompanyID = company;
            context.GetExtension<ResponsibilityExtension>().ContactID = contact;

            if (System.Diagnostics.Debugger.IsAttached)
            {
                System.Diagnostics.Debug.WriteLine("Bookmark resumed with '{0}'.", value);
            }
            
        }
Exemple #7
0
        protected override void Execute(NativeActivityContext context)
        {
            var bookmark = context.CreateBookmark(BookmarkName.Get(context), BookmarkResumed);
            var extension = context.GetExtension<Helpers.WorkflowInstanceExtensionHelper>();
            //extension.WaitSome(bookmark);

        }
 protected override void Execute(NativeActivityContext context)
 {
     var countModel = context.GetExtension<CountModel>();
     if (countModel.CountCompleted != null)
     {
         countModel.CountCompleted();
     }
 }
        protected override void Execute(NativeActivityContext context)
        {
            var bookMarkName = Guid.NewGuid().ToString();
            var content = new WfContent() { Path = ContentPath.Get(context) };

            notificationId.Set(context, context.GetExtension<ContentWorkflowExtension>().RegisterWait(content, bookMarkName));

            context.CreateBookmark(bookMarkName, new BookmarkCallback(Continue));
        }
 protected override void Execute(NativeActivityContext context)
 {
     Bookmark bookmark = context.CreateBookmark(new BookmarkCallback(this.OnMainRootComplete), BookmarkOptions.NonBlocking);
     context.RegisterMainRootCompleteCallback(bookmark);
     CompensationExtension extension = context.GetExtension<CompensationExtension>();
     extension.WorkflowCompensation = context.CreateBookmark(new BookmarkCallback(this.OnCompensate));
     extension.WorkflowConfirmation = context.CreateBookmark(new BookmarkCallback(this.OnConfirm));
     context.ResumeBookmark(extension.WorkflowCompensationScheduled, null);
 }
 protected override void Execute(NativeActivityContext context)
 {
     CompensationExtension extension = context.GetExtension<CompensationExtension>();
     CompensationToken token = this.Target.Get(context);
     CompensationTokenData data = extension.Get(token.CompensationId);
     data.BookmarkTable[CompensationBookmarkName.Compensated] = context.CreateBookmark(new BookmarkCallback(this.OnCompensated));
     data.CompensationState = CompensationState.Compensating;
     extension.NotifyMessage(context, data.CompensationId, CompensationBookmarkName.OnCompensation);
 }
Exemple #12
0
 protected override void ExecuteBody(NativeActivityContext context)
 {
     //创建子流程节点实例信息
     context.GetExtension<SubProcessExtension>().AddSubProcess(context
         , context.CreateBookmark(this.GenerateBookmarkName(context)
         , this.OnBookmarkCallback)
         , this.DisplayName
         , this.FlowNodeIndex);
 }
Exemple #13
0
        protected override void Execute(NativeActivityContext context)
        {
            var twilio = context.GetExtension<ITwilioContext>();
            var url = Url.Get(context);
            var loop = Loop.Get(context);

            GetElement(context).Add(new XElement("Play",
                loop != null ? new XAttribute("loop", loop) : null,
                url));
        }
        protected override void Execute(NativeActivityContext context)
        {
            var countModel = context.GetExtension<ICountModel>();

            if (countModel.CountUpdated != null)
            {
                countModel.CountUpdated(
                    this.CurrentCount.Get(context));
            }
        }
Exemple #15
0
        protected override void OnHasCompleted(NativeActivityContext context, ActivityInstance completedInstance)
        {
            base.OnHasCompleted(context, completedInstance);

            //HACK:重写并行节点满足条件退出逻辑
            var e = context.GetExtension<ParallelExtension>();
            e.Cancelled(context.GetChildren()
                .Where(o => o.ID != completedInstance.ID)
                .Select(o => o.ID)
                .ToArray());
        }
Exemple #16
0
        protected override void Execute(NativeActivityContext context)
        {
            var twilio = context.GetExtension<ITwilioContext>();
            var duration = Duration.Get(context);

            GetElement(context).Add(
                new XElement("Pause",
                    new XAttribute("length", (int)duration.TotalSeconds)),
                new XElement("Redirect",
                    twilio.ResolveBookmarkUrl(context.CreateTwilioBookmark(this))));
        }
 private void OnConfirm(NativeActivityContext context, Bookmark bookmark, object value)
 {
     CompensationExtension extension = context.GetExtension<CompensationExtension>();
     CompensationToken token = (CompensationToken) value;
     this.currentCompensationToken.Set(context, token);
     if (extension.Get(token.CompensationId).ExecutionTracker.Count > 0)
     {
         context.ScheduleActivity(this.DefaultConfirmation, new CompletionCallback(this.OnConfirmationComplete));
     }
     else
     {
         this.OnConfirmationComplete(context, null);
     }
 }
        protected override void Execute(NativeActivityContext context)
        {
            Bookmark mainRootCompleteBookmark = context.CreateBookmark(OnMainRootComplete, BookmarkOptions.NonBlocking);
            context.RegisterMainRootCompleteCallback(mainRootCompleteBookmark);

            CompensationExtension compensationExtension = context.GetExtension<CompensationExtension>();
            Fx.Assert(compensationExtension != null, "CompensationExtension must be valid");

            compensationExtension.WorkflowCompensation = context.CreateBookmark(new BookmarkCallback(OnCompensate));
            compensationExtension.WorkflowConfirmation = context.CreateBookmark(new BookmarkCallback(OnConfirm));

            Fx.Assert(compensationExtension.WorkflowCompensationScheduled != null, "compensationExtension.WorkflowCompensationScheduled bookmark must be setup by now");
            context.ResumeBookmark(compensationExtension.WorkflowCompensationScheduled, null);
        }
        /// <summary>
        ///     Transforms a text template that is specified in the <see cref="TemplatePath" /> property by calling the Visual Studio STextTemplatingService.
        /// </summary>
        /// <param name="context">The state of the current activity.</param>
        protected override void Execute(NativeActivityContext context)
        {
            var templateInputs = new Dictionary<string, object>();

            var symbolResolver = context.GetExtension<SymbolResolver>();
            var edmParameterBag = symbolResolver[typeof(EdmParameterBag).Name] as EdmParameterBag;
            if (edmParameterBag == null)
            {
                throw new InvalidOperationException(Resources.DatabaseCreation_ErrorNoEdmParameterBag);
            }

            // Add the EDMX path as a template input if it was populated as a parameter to the workflow
            _edmxPath = edmParameterBag.GetParameter<string>(EdmParameterBag.ParameterName.EdmxPath);
            if (_edmxPath != null)
            {
                templateInputs.Add(EdmParameterBag.ParameterName.EdmxPath.ToString(), _edmxPath);
            }

            // Call OnGetTemplateInputs, which will ask any derived class for inputs they would like the
            // templates to have access to
            OnGetTemplateInputs(context, templateInputs);

            // Retrieve the template name specified on the workflow file
            var unresolvedTemplatePath = TemplatePath.Get(context);
            if (String.IsNullOrEmpty(unresolvedTemplatePath))
            {
                throw new InvalidOperationException(
                    String.Format(CultureInfo.CurrentCulture, Resources.DatabaseCreation_ErrorTemplatePathNotSet, DisplayName));
            }

            // Add the template inputs to CallContext
            foreach (var inputName in templateInputs.Keys)
            {
                CallContext.LogicalSetData(inputName, templateInputs[inputName]);
            }

            try
            {
                TemplateOutput = ProcessTemplate(unresolvedTemplatePath);
            }
            finally
            {
                // We have to make sure we clear the CallContext data slots we set
                foreach (var inputName in templateInputs.Keys)
                {
                    CallContext.FreeNamedDataSlot(inputName);
                }
            }
        }
Exemple #20
0
        protected override void ExecuteNoun(NativeActivityContext context)
        {
            var twilio = context.GetExtension<ITwilioContext>();
            var name = Name.Get(context);

            // add new Number element
            var element = new XElement("Queue",
                name);
            GetElement(context).Add(element);

            // bookmark to execute Caller activity
            if (Pickup != null)
                element.Add(new XAttribute("url",
                    twilio.ResolveBookmarkUrl(context.CreateTwilioBookmark(OnPickup))));
        }
Exemple #21
0
        protected override void ExecuteNoun(NativeActivityContext context)
        {
            var twilio = context.GetExtension<ITwilioContext>();
            var number = Number.Get(context);
            var sendDigits = SendDigits.Get(context);

            // add new Number element
            var element = new XElement("Number",
                !string.IsNullOrWhiteSpace(sendDigits) ? new XAttribute("sendDigits", sendDigits) : null,
                number);
            GetElement(context).Add(element);

            // bookmark to execute Called activity
            if (Pickup != null)
                element.Add(new XAttribute("url", twilio.ResolveBookmarkUrl(context.CreateTwilioBookmark(OnPickup))));
        }
        protected override void Execute(NativeActivityContext context)
        {
            var waitForAll = WaitForAll.Get(context);
            var paths = ContentPaths.Get(context);
            var contents = paths.Select(p => new WfContent { Path = p }).ToArray();
            var ext = context.GetExtension<ContentWorkflowExtension>();

            var bookMarkName = Guid.NewGuid().ToString();
            var waitIds = ext.RegisterWaitForMultipleContent(contents, bookMarkName);
            var waitIdString = String.Join(",", waitIds.Select(w => w.ToString()).ToArray());
            var nodeIdString = String.Join(",", contents.Select(w => w.Id.ToString()).ToArray());

            notificationIds.Set(context, waitIdString);
            counter.Set(context, waitForAll ? contents.Length : 1);

            context.CreateBookmark(bookMarkName, new BookmarkCallback(Continue));
        }
        protected override void Execute(NativeActivityContext context)
        {
            CompensationExtension compensationExtension = context.GetExtension<CompensationExtension>();
            Fx.Assert(compensationExtension != null, "CompensationExtension must be valid");

            CompensationToken compensationToken = Target.Get(context);
            Fx.Assert(compensationToken != null, "compensationToken must be valid");

            // The compensationToken should be a valid one at this point. Ensure its validated in Confirm activity.
            CompensationTokenData tokenData = compensationExtension.Get(compensationToken.CompensationId);
            Fx.Assert(tokenData != null, "The compensationToken should be a valid one at this point. Ensure its validated in Confirm activity.");

            Fx.Assert(tokenData.BookmarkTable[CompensationBookmarkName.Confirmed] == null, "Bookmark should not be already initialized in the bookmark table.");
            tokenData.BookmarkTable[CompensationBookmarkName.Confirmed] = context.CreateBookmark(new BookmarkCallback(OnConfirmed));

            tokenData.CompensationState = CompensationState.Confirming;
            compensationExtension.NotifyMessage(context, tokenData.CompensationId, CompensationBookmarkName.OnConfirmation);
        }
 private void InternalExecute(NativeActivityContext context, System.Activities.ActivityInstance completedInstance)
 {
     CompensationExtension extension = context.GetExtension<CompensationExtension>();
     if (extension == null)
     {
         throw FxTrace.Exception.AsError(new InvalidOperationException(System.Activities.SR.ConfirmWithoutCompensableActivity(base.DisplayName)));
     }
     CompensationToken token = this.Target.Get(context);
     CompensationTokenData data = (token == null) ? null : extension.Get(token.CompensationId);
     if (data.ExecutionTracker.Count > 0)
     {
         if (this.onChildConfirmed == null)
         {
             this.onChildConfirmed = new CompletionCallback(this.InternalExecute);
         }
         this.toConfirmToken.Set(context, new CompensationToken(data.ExecutionTracker.Get()));
         context.ScheduleActivity(this.Body, this.onChildConfirmed);
     }
 }
Exemple #25
0
        protected override void ExecuteNoun(NativeActivityContext context)
        {
            var twilio = context.GetExtension<ITwilioContext>();

            // insert Sip element
            var element = new XElement("Sip");
            GetElement(context).Add(element);

            if (Called != null)
                // url attribute will execute the Called activity
                element.Add(new XAttribute("url",
                    twilio.ResolveBookmarkUrl(context.CreateTwilioBookmark(OnCalled))));

            // schedule URI activities
            if (Uris.Count > 0)
            {
                twilio.SetElement(context, element);
                foreach (var uri in Uris)
                    context.ScheduleActivity(uri);
            }
        }
 private void OnCompensated(NativeActivityContext context, Bookmark bookmark, object value)
 {
     CompensationExtension extension = context.GetExtension<CompensationExtension>();
     CompensationToken token = this.Target.Get(context);
     CompensationTokenData compensationToken = extension.Get(token.CompensationId);
     compensationToken.CompensationState = CompensationState.Compensated;
     if (TD.CompensationStateIsEnabled())
     {
         TD.CompensationState(compensationToken.DisplayName, compensationToken.CompensationState.ToString());
     }
     if (compensationToken.ParentCompensationId != 0L)
     {
         extension.Get(compensationToken.ParentCompensationId).ExecutionTracker.Remove(compensationToken);
     }
     else
     {
         extension.Get(0L).ExecutionTracker.Remove(compensationToken);
     }
     compensationToken.RemoveBookmark(context, CompensationBookmarkName.Compensated);
     extension.Remove(token.CompensationId);
 }
        // Successfully received Confirmed response.
        void OnConfirmed(NativeActivityContext context, Bookmark bookmark, object value)
        {
            CompensationExtension compensationExtension = context.GetExtension<CompensationExtension>();
            Fx.Assert(compensationExtension != null, "CompensationExtension must be valid");

            CompensationToken compensationToken = Target.Get(context);
            Fx.Assert(compensationToken != null, "compensationToken must be valid");

            // The compensationToken should be a valid one at this point. Ensure its validated in Confirm activity.
            CompensationTokenData tokenData = compensationExtension.Get(compensationToken.CompensationId);
            Fx.Assert(tokenData != null, "The compensationToken should be a valid one at this point. Ensure its validated in Confirm activity.");

            tokenData.CompensationState = CompensationState.Confirmed;
            if (TD.CompensationStateIsEnabled())
            {
                TD.CompensationState(tokenData.DisplayName, tokenData.CompensationState.ToString());
            }

            // Remove the token from the parent! 
            if (tokenData.ParentCompensationId != CompensationToken.RootCompensationId)
            {
                CompensationTokenData parentToken = compensationExtension.Get(tokenData.ParentCompensationId);
                Fx.Assert(parentToken != null, "parentToken must be valid");

                parentToken.ExecutionTracker.Remove(tokenData);
            }
            else
            {
                // remove from workflow root...
                CompensationTokenData parentToken = compensationExtension.Get(CompensationToken.RootCompensationId);
                Fx.Assert(parentToken != null, "parentToken must be valid");

                parentToken.ExecutionTracker.Remove(tokenData);
            }

            tokenData.RemoveBookmark(context, CompensationBookmarkName.Confirmed);

            // Remove the token from the extension...
            compensationExtension.Remove(compensationToken.CompensationId);
        }
 protected override void Execute(NativeActivityContext context)
 {
     CorrelationHandle handle = (this.Correlation == null) ? null : this.Correlation.Get(context);
     if (handle == null)
     {
         handle = context.Properties.Find(CorrelationHandle.StaticExecutionPropertyName) as CorrelationHandle;
         if (handle == null)
         {
             throw System.ServiceModel.Activities.FxTrace.Exception.AsError(new InvalidOperationException(System.ServiceModel.Activities.SR.NullCorrelationHandleInInitializeCorrelation(base.DisplayName)));
         }
     }
     CorrelationExtension extension = context.GetExtension<CorrelationExtension>();
     if (extension == null)
     {
         throw System.ServiceModel.Activities.FxTrace.Exception.AsError(new InvalidOperationException(System.ServiceModel.Activities.SR.InitializeCorrelationRequiresWorkflowServiceHost(base.DisplayName)));
     }
     Dictionary<string, string> keyData = new Dictionary<string, string>();
     foreach (KeyValuePair<string, InArgument<string>> pair in this.CorrelationData)
     {
         keyData.Add(pair.Key, pair.Value.Get(context));
     }
     handle.InitializeBookmarkScope(context, extension.GenerateKey(keyData));
 }
        /// <summary>
        ///     Returns the output produced by the output generator with the specified output generator type name.
        /// </summary>
        /// <typeparam name="T">The type of the output.</typeparam>
        /// <param name="outputGeneratorTypeName">The name of the type of the output generator.</param>
        /// <param name="context">The state of the current activity.</param>
        /// <param name="inputs">Inputs for the activity as key-value pairs.</param>
        /// <returns>The output produced by the output generator along with the specified output generator type name.</returns>
        protected T ProcessOutputGenerator <T>(
            string outputGeneratorTypeName, NativeActivityContext context, IDictionary <string, object> inputs) where T : class
        {
            var outputGeneratorType = Type.GetType(outputGeneratorTypeName);

            if (outputGeneratorType == null)
            {
                // if the type name is correct, then the assembly may not be loaded. Try to load it
                // via the assembly loader, which can provide custom logic on how to load assemblies
                // (for the 'Generate Database' wizard, we will only look in the project/website references)
                // NOTE that this will only apply to assembly-qualified type names
                var assemblyName     = String.Empty;
                var fqTypeName       = String.Empty;
                var indexOfDelimiter = outputGeneratorTypeName.IndexOf(',');
                if (indexOfDelimiter != -1)
                {
                    assemblyName = outputGeneratorTypeName.Substring(indexOfDelimiter + 1).Trim();
                    fqTypeName   = outputGeneratorTypeName.Substring(0, indexOfDelimiter).Trim();
                }

                if (false == String.IsNullOrEmpty(assemblyName) &&
                    false == String.IsNullOrEmpty(fqTypeName))
                {
                    var symbolResolver = context.GetExtension <SymbolResolver>();
                    if (symbolResolver != null)
                    {
                        var edmParameterBag = symbolResolver[typeof(EdmParameterBag).Name] as EdmParameterBag;
                        if (edmParameterBag != null)
                        {
                            var assemblyLoader = edmParameterBag.GetParameter <IAssemblyLoader>(EdmParameterBag.ParameterName.AssemblyLoader);
                            if (assemblyLoader != null)
                            {
                                var loadedAssembly = assemblyLoader.LoadAssembly(assemblyName);
                                if (loadedAssembly != null)
                                {
                                    try
                                    {
                                        outputGeneratorType = loadedAssembly.GetType(fqTypeName);
                                    }
                                    catch (Exception e)
                                    {
                                        throw new InvalidOperationException(
                                                  String.Format(CultureInfo.CurrentCulture, Resources.ErrorNoCodeViewType, outputGeneratorType), e);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if (outputGeneratorType == null)
            {
                throw new InvalidOperationException(
                          String.Format(CultureInfo.CurrentCulture, Resources.ErrorNoCodeViewType, outputGeneratorTypeName));
            }

            var outputGeneratorConstructorInfo =
                outputGeneratorType.GetConstructor(
                    BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, new Type[] { }, null);

            Debug.Assert(
                outputGeneratorConstructorInfo != null,
                "Should have found a constructor if we were able to find the type in OutputGeneratorActivity.ProcessOutputGenerator");
            if (outputGeneratorConstructorInfo != null)
            {
                OutputGenerator = outputGeneratorConstructorInfo.Invoke(new object[] { }) as IGenerateActivityOutput;
                if (OutputGenerator != null)
                {
                    return(OutputGenerator.GenerateActivityOutput <T>(this, context, inputs));
                }
            }
            return(null);
        }
Exemple #30
0
        // ReSharper restore RedundantOverridenMember

        /// <summary>
        /// The execute method that is called when the activity is executed at run time and will hold all the logic of the activity
        /// </summary>
        protected override void OnExecute(NativeActivityContext context)
        {
            _debugInputs  = new List <DebugItem>();
            _debugOutputs = new List <DebugItem>();
            IDSFDataObject dataObject = context.GetExtension <IDSFDataObject>();



            IDataListCompiler compiler = DataListFactory.CreateDataListCompiler();

            ErrorResultTO allErrors   = new ErrorResultTO();
            ErrorResultTO errors      = new ErrorResultTO();
            Guid          executionId = DataListExecutionID.Get(context);

            allErrors.MergeErrors(errors);
            InitializeDebug(dataObject);
            // Process if no errors
            try
            {
                IDev2DataListUpsertPayloadBuilder <string> toUpsert = Dev2DataListBuilderFactory.CreateStringDataListUpsertBuilder(true);

                toUpsert.IsDebug = dataObject.IsDebugMode();
                IDev2IteratorCollection colItr = Dev2ValueObjectFactory.CreateIteratorCollection();
                var datalist = compiler.ConvertFrom(dataObject.DataListID, DataListFormat.CreateFormat(GlobalConstants._Studio_XML), enTranslationDepth.Shape, out errors).ToString();
                if (!string.IsNullOrEmpty(datalist))
                {
                    ValidateInput(datalist, allErrors, Input1);
                    ValidateInput(datalist, allErrors, Input2);
                }
                IBinaryDataListEntry input1Entry = compiler.Evaluate(executionId, enActionType.User, string.IsNullOrEmpty(Input1) ? GlobalConstants.CalcExpressionNow : Input1, false, out errors);
                allErrors.MergeErrors(errors);
                IDev2DataListEvaluateIterator input1Itr = Dev2ValueObjectFactory.CreateEvaluateIterator(input1Entry);
                colItr.AddIterator(input1Itr);

                IBinaryDataListEntry input2Entry = compiler.Evaluate(executionId, enActionType.User, string.IsNullOrEmpty(Input2) ? GlobalConstants.CalcExpressionNow : Input2, false, out errors);
                allErrors.MergeErrors(errors);
                IDev2DataListEvaluateIterator input2Itr = Dev2ValueObjectFactory.CreateEvaluateIterator(input2Entry);
                colItr.AddIterator(input2Itr);

                IBinaryDataListEntry inputFormatEntry = compiler.Evaluate(executionId, enActionType.User, InputFormat ?? string.Empty, false, out errors);
                allErrors.MergeErrors(errors);
                IDev2DataListEvaluateIterator ifItr = Dev2ValueObjectFactory.CreateEvaluateIterator(inputFormatEntry);
                colItr.AddIterator(ifItr);

                if (dataObject.IsDebugMode())
                {
                    AddDebugInputItem(string.IsNullOrEmpty(Input1) ? GlobalConstants.CalcExpressionNow : Input1, "Input 1", input1Entry, executionId);
                    AddDebugInputItem(string.IsNullOrEmpty(Input2) ? GlobalConstants.CalcExpressionNow : Input2, "Input 2", input2Entry, executionId);
                    AddDebugInputItem(InputFormat, "Input Format", inputFormatEntry, executionId);
                    AddDebugInputItem(new DebugItemStaticDataParams(OutputType, "Output In"));
                }

                int indexToUpsertTo = 1;

                while (colItr.HasMoreData())
                {
                    IDateTimeDiffTO transObj = ConvertToDateTimeDiffTo(colItr.FetchNextRow(input1Itr).TheValue,
                                                                       colItr.FetchNextRow(input2Itr).TheValue,
                                                                       colItr.FetchNextRow(ifItr).TheValue,
                                                                       OutputType);
                    //Create a DateTimeComparer using the DateTimeConverterFactory
                    IDateTimeComparer comparer = DateTimeConverterFactory.CreateComparer();
                    //Call the TryComparer method on the DateTimeComparer and pass it the IDateTimeDiffTO created from the ConvertToDateTimeDiffTO Method
                    string result;
                    string error;
                    if (comparer.TryCompare(transObj, out result, out error))
                    {
                        string expression;
                        if (DataListUtil.IsValueRecordset(Result) &&
                            DataListUtil.GetRecordsetIndexType(Result) == enRecordsetIndexType.Star)
                        {
                            expression = Result.Replace(GlobalConstants.StarExpression, indexToUpsertTo.ToString(CultureInfo.InvariantCulture));
                        }
                        else
                        {
                            expression = Result;
                        }

                        //2013.06.03: Ashley Lewis for bug 9498 - handle multiple regions in result
                        var rule   = new IsSingleValueRule(() => Result);
                        var single = rule.Check();
                        if (single != null)
                        {
                            allErrors.AddError(single.Message);
                        }
                        else
                        {
                            toUpsert.Add(expression, result);
                        }
                    }
                    else
                    {
                        DoDebugOutput(dataObject, Result, result, executionId, indexToUpsertTo);
                        allErrors.AddError(error);
                    }
                    indexToUpsertTo++;
                }

                compiler.Upsert(executionId, toUpsert, out errors);
                allErrors.MergeErrors(errors);
                if (dataObject.IsDebugMode() && !allErrors.HasErrors())
                {
                    foreach (var debugOutputTo in toUpsert.DebugOutputs)
                    {
                        AddDebugOutputItem(new DebugItemVariableParams(debugOutputTo));
                    }
                }
            }
            catch (Exception e)
            {
                Dev2Logger.Log.Error("DSFDateTime", e);
                allErrors.AddError(e.Message);
            }
            finally
            {
                // Handle Errors
                if (allErrors.HasErrors())
                {
                    DisplayAndWriteError("DsfDateTimeDifferenceActivity", allErrors);
                    compiler.UpsertSystemTag(dataObject.DataListID, enSystemTag.Dev2Error, allErrors.MakeDataListReady(), out errors);
                    compiler.Upsert(executionId, Result, (string)null, out errors);
                }
                if (dataObject.IsDebugMode())
                {
                    DispatchDebugState(context, StateType.Before);
                    DispatchDebugState(context, StateType.After);
                }
            }
        }
        /// <summary>
        /// The execute method that is called when the activity is executed at run time and will hold all the logic of the activity
        /// </summary>
        protected override void OnExecute(NativeActivityContext context)
        {
            _debugInputs  = new List <DebugItem>();
            _debugOutputs = new List <DebugItem>();
            IDSFDataObject dataObject = context.GetExtension <IDSFDataObject>();

            IDataListCompiler compiler = DataListFactory.CreateDataListCompiler();

            ErrorResultTO allErrors = new ErrorResultTO();
            ErrorResultTO errors;
            Guid          executionId = DataListExecutionID.Get(context);

            InitializeDebug(dataObject);
            // Process if no errors
            try
            {
                IsSingleValueRule.ApplyIsSingleValueRule(Result, allErrors);
                IDev2DataListUpsertPayloadBuilder <string> toUpsert = Dev2DataListBuilderFactory.CreateStringDataListUpsertBuilder(true);
                toUpsert.IsDebug    = (dataObject.IsDebugMode());
                toUpsert.ResourceID = dataObject.ResourceID;
                IDev2IteratorCollection colItr = Dev2ValueObjectFactory.CreateIteratorCollection();

                IDev2DataListEvaluateIterator dtItr = CreateDataListEvaluateIterator(string.IsNullOrEmpty(DateTime) ? GlobalConstants.CalcExpressionNow : DateTime, executionId, compiler, colItr, allErrors);
                colItr.AddIterator(dtItr);
                IDev2DataListEvaluateIterator ifItr = CreateDataListEvaluateIterator(InputFormat, executionId, compiler, colItr, allErrors);
                colItr.AddIterator(ifItr);
                IDev2DataListEvaluateIterator ofItr = CreateDataListEvaluateIterator(OutputFormat, executionId, compiler, colItr, allErrors);
                colItr.AddIterator(ofItr);
                IDev2DataListEvaluateIterator tmaItr = CreateDataListEvaluateIterator(TimeModifierAmountDisplay, executionId, compiler, colItr, allErrors);
                colItr.AddIterator(tmaItr);

                if (dataObject.IsDebugMode())
                {
                    if (string.IsNullOrEmpty(DateTime))
                    {
                        var defaultDateTimeDebugItem = new DebugItem();
                        AddDebugItem(new DebugItemStaticDataParams("System Date Time", "Input"), defaultDateTimeDebugItem);
                        AddDebugItem(new DebugItemStaticDataParams(System.DateTime.Now.ToString(CultureInfo.CurrentCulture), "="), defaultDateTimeDebugItem);
                        _debugInputs.Add(defaultDateTimeDebugItem);
                    }
                    else
                    {
                        AddDebugInputItem(new DebugItemVariableParams(DateTime, "Input", dtItr.FetchEntry(), executionId));
                    }

                    var dateTimePattern = string.Format("{0} {1}", CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern, CultureInfo.CurrentCulture.DateTimeFormat.LongTimePattern);

                    if (string.IsNullOrEmpty(InputFormat))
                    {
                        var defaultDateTimeDebugItem = new DebugItem();
                        AddDebugItem(new DebugItemStaticDataParams("System Date Time Format", "Input Format"), defaultDateTimeDebugItem);
                        AddDebugItem(new DebugItemStaticDataParams(dateTimePattern, "="), defaultDateTimeDebugItem);
                        _debugInputs.Add(defaultDateTimeDebugItem);
                    }
                    else
                    {
                        AddDebugInputItem(new DebugItemVariableParams(InputFormat, "Input Format", ifItr.FetchEntry(), executionId));
                    }

                    var debugItem = new DebugItem();
                    AddDebugItem(new DebugItemStaticDataParams(TimeModifierType, "Add Time"), debugItem);
                    AddDebugItem(new DebugItemVariableParams(TimeModifierAmountDisplay, "", tmaItr.FetchEntry(), executionId, true), debugItem);
                    _debugInputs.Add(debugItem);

                    if (string.IsNullOrEmpty(OutputFormat))
                    {
                        var defaultDateTimeDebugItem = new DebugItem();
                        AddDebugItem(new DebugItemStaticDataParams("System Date Time Format", "Output Format"), defaultDateTimeDebugItem);
                        AddDebugItem(new DebugItemStaticDataParams(dateTimePattern, "="), defaultDateTimeDebugItem);
                        _debugInputs.Add(defaultDateTimeDebugItem);
                    }
                    else
                    {
                        AddDebugInputItem(new DebugItemVariableParams(OutputFormat, "Output Format", ofItr.FetchEntry(), executionId));
                    }
                }

                if (!allErrors.HasErrors())
                {
                    while (colItr.HasMoreData())
                    {
                        IDateTimeOperationTO transObj = ConvertToDateTimeTo(colItr.FetchNextRow(dtItr).TheValue,
                                                                            colItr.FetchNextRow(ifItr).TheValue,
                                                                            colItr.FetchNextRow(ofItr).TheValue,
                                                                            TimeModifierType,
                                                                            colItr.FetchNextRow(tmaItr).TheValue
                                                                            );

                        //Create a DateTimeFomatter using the DateTimeConverterFactory.DONE
                        IDateTimeFormatter format = DateTimeConverterFactory.CreateFormatter();
                        string             result;
                        string             error;
                        if (format.TryFormat(transObj, out result, out error))
                        {
                            string expression = Result;
                            //2013.06.03: Ashley Lewis for bug 9498 - handle multiple regions in result

                            toUpsert.Add(expression, result);

                            toUpsert.FlushIterationFrame();
                        }
                        else
                        {
                            allErrors.AddError(error);
                        }
                    }
                    compiler.Upsert(executionId, toUpsert, out errors);
                    allErrors.MergeErrors(errors);
                    if (dataObject.IsDebugMode() && !allErrors.HasErrors())
                    {
                        foreach (var debugOutputTo in toUpsert.DebugOutputs)
                        {
                            AddDebugOutputItem(new DebugItemVariableParams(debugOutputTo));
                        }
                    }
                    allErrors.MergeErrors(errors);
                }
            }
            catch (Exception e)
            {
                Dev2Logger.Log.Error("DSFDateTime", e);
                allErrors.AddError(e.Message);
            }
            finally
            {
                // Handle Errors
                var hasErrors = allErrors.HasErrors();
                if (hasErrors)
                {
                    DisplayAndWriteError("DsfDateTimeActivity", allErrors);
                    compiler.UpsertSystemTag(dataObject.DataListID, enSystemTag.Dev2Error, allErrors.MakeDataListReady(), out errors);
                    compiler.Upsert(executionId, Result, (string)null, out errors);
                }
                if (dataObject.IsDebugMode())
                {
                    if (hasErrors)
                    {
                        AddDebugOutputItem(new DebugItemStaticDataParams("", Result, ""));
                    }
                    DispatchDebugState(context, StateType.Before);
                    DispatchDebugState(context, StateType.After);
                }
            }
        }
        // ReSharper restore RedundantOverridenMember

        protected override void OnExecute(NativeActivityContext context)
        {
            _debugInputs  = new List <DebugItem>();
            _debugOutputs = new List <DebugItem>();
            IDSFDataObject    dataObject = context.GetExtension <IDSFDataObject>();
            IDataListCompiler compiler   = DataListFactory.CreateDataListCompiler();
            Guid executionId             = dataObject.DataListID;

            ErrorResultTO allErrors = new ErrorResultTO();
            ErrorResultTO errors    = new ErrorResultTO();

            InitializeDebug(dataObject);
            try
            {
                ValidateRecordsetName(RecordsetName, errors);
                allErrors.MergeErrors(errors);

                if (!allErrors.HasErrors())
                {
                    var tmpRecsetIndex = DataListUtil.ExtractIndexRegionFromRecordset(RecordsetName);
                    IBinaryDataListEntry indexEntry = compiler.Evaluate(executionId, enActionType.User, tmpRecsetIndex, false, out errors);

                    IDev2DataListEvaluateIterator itr        = Dev2ValueObjectFactory.CreateEvaluateIterator(indexEntry);
                    IDev2IteratorCollection       collection = Dev2ValueObjectFactory.CreateIteratorCollection();
                    collection.AddIterator(itr);

                    while (collection.HasMoreData())
                    {
                        var evaluatedRecordset = RecordsetName.Remove(RecordsetName.IndexOf("(", StringComparison.Ordinal) + 1) + collection.FetchNextRow(itr).TheValue + ")]]";
                        if (dataObject.IsDebugMode())
                        {
                            IBinaryDataListEntry tmpentry = compiler.Evaluate(executionId, enActionType.User, evaluatedRecordset, false, out errors);
                            AddDebugInputItem(new DebugItemVariableParams(RecordsetName, "Records", tmpentry, executionId));
                        }

                        IBinaryDataListEntry entry = compiler.Evaluate(executionId, enActionType.Internal, evaluatedRecordset, false, out errors);

                        allErrors.MergeErrors(errors);
                        compiler.Upsert(executionId, Result, entry.FetchScalar().TheValue, out errors);

                        if (dataObject.IsDebugMode() && !allErrors.HasErrors())
                        {
                            AddDebugOutputItem(new DebugItemVariableParams(Result, "", entry, executionId));
                        }
                        allErrors.MergeErrors(errors);
                    }
                }
            }
            catch (Exception e)
            {
                allErrors.AddError(e.Message);
            }
            finally
            {
                // Handle Errors
                var hasErrors = allErrors.HasErrors();
                if (hasErrors)
                {
                    DisplayAndWriteError("DsfDeleteRecordsActivity", allErrors);
                    compiler.UpsertSystemTag(dataObject.DataListID, enSystemTag.Dev2Error, allErrors.MakeDataListReady(), out errors);
                    compiler.Upsert(executionId, Result, (string)null, out errors);
                }

                if (dataObject.IsDebugMode())
                {
                    if (hasErrors)
                    {
                        AddDebugOutputItem(new DebugItemStaticDataParams("", Result, ""));
                    }
                    DispatchDebugState(context, StateType.Before);
                    DispatchDebugState(context, StateType.After);
                }
            }
        }
Exemple #33
0
        protected override void Execute(NativeActivityContext context)
        {
            var edmItemCollection = CsdlInput.Get(context);

            if (edmItemCollection == null)
            {
                throw new InvalidOperationException(Resources.ErrorCouldNotFindCSDL);
            }

            var symbolResolver  = context.GetExtension <SymbolResolver>();
            var edmParameterBag = symbolResolver[typeof(EdmParameterBag).Name] as EdmParameterBag;

            if (edmParameterBag == null)
            {
                throw new InvalidOperationException(Resources.ErrorNoEdmParameterBag);
            }

            // Find the TargetVersion parameter
            var targetFrameworkVersion = edmParameterBag.GetParameter <Version>(EdmParameterBag.ParameterName.TargetVersion);

            if (targetFrameworkVersion == null)
            {
                throw new InvalidOperationException(
                          String.Format(
                              CultureInfo.CurrentCulture, Resources.ErrorNoParameterDefined,
                              EdmParameterBag.ParameterName.TargetVersion.ToString()));
            }

            // Validate the TargetVersion parameter
            if (false == EntityFrameworkVersion.IsValidVersion(targetFrameworkVersion))
            {
                throw new InvalidOperationException(
                          String.Format(CultureInfo.CurrentCulture, Resources.ErrorNonValidTargetVersion, targetFrameworkVersion));
            }

            // Construct the Code View inputs in a dictionary
            var inputs = new Dictionary <string, object>
            {
                { EdmConstants.csdlInputName, edmItemCollection }
            };

            // Process the SSDL and MSL code views, feeding in the CSDL
            var ssdl = ProcessOutputGenerator <string>(OutputGeneratorType.Get(context), context, inputs);
            var msl  = ProcessOutputGenerator <string>(MslOutputGeneratorType.Get(context), context, inputs);

            // Validate the SSDL, but catch any naming errors and throw a friendlier one
            var ssdlCollection = EdmExtension.CreateAndValidateStoreItemCollection(
                ssdl, targetFrameworkVersion, DependencyResolver.Instance, true);

#if DEBUG
            // Validate the MSL in Debug mode
            IList <EdmSchemaError> mslErrors;
            EdmExtension.CreateStorageMappingItemCollection(
                edmItemCollection, ssdlCollection, msl, out mslErrors);
            if (mslErrors != null &&
                mslErrors.Count > 0)
            {
                var errorSb = new StringBuilder();
                errorSb.AppendLine("Encountered the following errors while validating the MSL:");
                foreach (var error in mslErrors)
                {
                    errorSb.AppendLine(error.Message);
                }

                Debug.Fail(errorSb.ToString());
            }
#endif

            // We are done processing, save off all the outputs for the next stage
            SsdlOutput.Set(context, ssdl);
            MslOutput.Set(context, msl);
        }
Exemple #34
0
        // TODO perhaps build an in-memory "inference" model that keeps track of the assumptions we make (association/entity type names, etc.)
        /// <summary>
        ///     Generates store schema definition language (SSDL) based on the provided conceptual schema definition language (CSDL).
        /// </summary>
        /// <typeparam name="T"> The type of the activity output. </typeparam>
        /// <param name="owningActivity"> The currently executing activity. </param>
        /// <param name="context"> The activity context that contains the state of the workflow. </param>
        /// <param name="inputs"> Contains the incoming CSDL. </param>
        /// <returns> Store schema definition language (SSDL) of type T based on the provided conceptual schema definition language (CSDL). </returns>
        public T GenerateActivityOutput <T>(
            OutputGeneratorActivity owningActivity, NativeActivityContext context, IDictionary <string, object> inputs) where T : class
        {
            _activity = owningActivity;

            // First attempt to get the CSDL represented by the EdmItemCollection from the inputs
            object o;

            inputs.TryGetValue(EdmConstants.csdlInputName, out o);
            var edmItemCollection = o as EdmItemCollection;

            if (edmItemCollection == null)
            {
                throw new InvalidOperationException(Resources.ErrorCouldNotFindCSDL);
            }

            var symbolResolver  = context.GetExtension <SymbolResolver>();
            var edmParameterBag = symbolResolver[typeof(EdmParameterBag).Name] as EdmParameterBag;

            if (edmParameterBag == null)
            {
                throw new InvalidOperationException(Resources.ErrorNoEdmParameterBag);
            }

            // Find the ProviderInvariantName parameter
            var providerInvariantName = edmParameterBag.GetParameter <string>(EdmParameterBag.ParameterName.ProviderInvariantName);

            if (String.IsNullOrEmpty(providerInvariantName))
            {
                throw new InvalidOperationException(
                          String.Format(
                              CultureInfo.CurrentCulture, Resources.ErrorNoParameterDefined, EdmParameterBag.ParameterName.ProviderInvariantName));
            }

            // Find the ProviderManifestToken parameter
            var providerManifestToken = edmParameterBag.GetParameter <string>(EdmParameterBag.ParameterName.ProviderManifestToken);

            if (String.IsNullOrEmpty(providerManifestToken))
            {
                throw new InvalidOperationException(
                          String.Format(
                              CultureInfo.CurrentCulture, Resources.ErrorNoParameterDefined, EdmParameterBag.ParameterName.ProviderManifestToken));
            }

            // Find the TargetVersion parameter
            var targetFrameworkVersion = edmParameterBag.GetParameter <Version>(EdmParameterBag.ParameterName.TargetVersion);

            if (targetFrameworkVersion == null)
            {
                throw new InvalidOperationException(
                          String.Format(
                              CultureInfo.CurrentCulture, Resources.ErrorNoParameterDefined, EdmParameterBag.ParameterName.TargetVersion));
            }

            // Find the DatabaseSchemaName parameter
            var databaseSchemaName = edmParameterBag.GetParameter <string>(EdmParameterBag.ParameterName.DatabaseSchemaName);

            if (String.IsNullOrEmpty(databaseSchemaName))
            {
                throw new InvalidOperationException(
                          String.Format(
                              CultureInfo.CurrentCulture, Resources.ErrorNoParameterDefined, EdmParameterBag.ParameterName.DatabaseSchemaName));
            }

            DbProviderManifest providerManifest = null;

            try
            {
                providerManifest =
                    DependencyResolver.GetService <DbProviderServices>(providerInvariantName).GetProviderManifest(providerManifestToken);
            }
            catch (ArgumentException ae)
            {
                // This can happen if the ProviderInvariantName is not valid
                throw new InvalidOperationException(
                          String.Format(
                              CultureInfo.CurrentCulture, Resources.ErrorProviderManifestEx_ProviderInvariantName, providerInvariantName), ae);
            }
            catch (ProviderIncompatibleException pie)
            {
                // This can happen if the ProviderManifestToken is not valid
                throw new InvalidOperationException(
                          String.Format(
                              CultureInfo.CurrentCulture, Resources.ErrorProviderManifestEx_ProviderManifestToken, providerManifestToken), pie);
            }

            if (providerManifest == null)
            {
                throw new InvalidOperationException(
                          String.Format(
                              CultureInfo.CurrentCulture, Resources.ErrorCouldNotFindProviderManifest, providerInvariantName,
                              providerManifestToken));
            }

            // Resolve the SSDL namespace
            _ssdlUri = SchemaManager.GetSSDLNamespaceName(targetFrameworkVersion);
            _ssdl    = _ssdlUri;

            // Resolve the ESSG namespace
            _essgUri = SchemaManager.GetEntityStoreSchemaGeneratorNamespaceName();
            _essg    = _essgUri;

            var csdlNamespace = edmItemCollection.GetNamespace();
            var ssdlNamespace = String.IsNullOrEmpty(csdlNamespace) ? "Store" : csdlNamespace + ".Store";

            var schemaElement          = ConstructSchemaElement(providerInvariantName, providerManifestToken, ssdlNamespace);
            var entityContainerElement = ConstructEntityContainer(edmItemCollection, databaseSchemaName, csdlNamespace, ssdlNamespace);

            schemaElement.Add(entityContainerElement);

            var entityTypes = ConstructEntityTypes(edmItemCollection, providerManifest, targetFrameworkVersion);

            schemaElement.Add(entityTypes);

            var associations = ConstructAssociations(edmItemCollection, ssdlNamespace);

            schemaElement.Add(associations);

            var serializedSchemaElement = String.Empty;

            try
            {
                serializedSchemaElement = EdmExtension.SerializeXElement(schemaElement);
            }
            catch (Exception e)
            {
                throw new ArgumentException(
                          String.Format(CultureInfo.CurrentCulture, Resources.ErrorSerializing_CsdlToSsdl, e.Message), e);
            }
            return(serializedSchemaElement as T);
        }
Exemple #35
0
        protected override IList <OutputTO> ExecuteConcreteAction(NativeActivityContext context, out ErrorResultTO allErrors)
        {
            IList <OutputTO> outputs    = new List <OutputTO>();
            IDSFDataObject   dataObject = context.GetExtension <IDSFDataObject>();

            IDataListCompiler compiler = DataListFactory.CreateDataListCompiler();

            allErrors = new ErrorResultTO();
            ErrorResultTO           errors;
            Guid                    executionId = dataObject.DataListID;
            IDev2IteratorCollection colItr      = Dev2ValueObjectFactory.CreateIteratorCollection();

            //get all the possible paths for all the string variables
            IBinaryDataListEntry inputPathEntry = compiler.Evaluate(executionId, enActionType.User, InputPath, false, out errors);

            allErrors.MergeErrors(errors);
            IDev2DataListEvaluateIterator inputItr = Dev2ValueObjectFactory.CreateEvaluateIterator(inputPathEntry);

            colItr.AddIterator(inputItr);

            IBinaryDataListEntry usernameEntry = compiler.Evaluate(executionId, enActionType.User, Username, false, out errors);

            allErrors.MergeErrors(errors);
            IDev2DataListEvaluateIterator unameItr = Dev2ValueObjectFactory.CreateEvaluateIterator(usernameEntry);

            colItr.AddIterator(unameItr);

            IBinaryDataListEntry passwordEntry = compiler.Evaluate(executionId, enActionType.User, Password, false, out errors);

            allErrors.MergeErrors(errors);
            IDev2DataListEvaluateIterator passItr = Dev2ValueObjectFactory.CreateEvaluateIterator(passwordEntry);

            colItr.AddIterator(passItr);

            outputs.Add(DataListFactory.CreateOutputTO(Result));

            if (dataObject.IsDebugMode())
            {
                AddDebugInputItem(InputPath, "Input Path", inputPathEntry, executionId);
                AddDebugInputItemUserNamePassword(executionId, usernameEntry);
            }

            while (colItr.HasMoreData())
            {
                IActivityOperationsBroker broker = ActivityIOFactory.CreateOperationsBroker();

                try
                {
                    IActivityIOPath dst = ActivityIOFactory.CreatePathFromString(colItr.FetchNextRow(inputItr).TheValue,
                                                                                 colItr.FetchNextRow(unameItr).TheValue,
                                                                                 colItr.FetchNextRow(passItr).TheValue,
                                                                                 true);

                    IActivityIOOperationsEndPoint dstEndPoint = ActivityIOFactory.CreateOperationEndPointFromIOPath(dst);
                    string result = broker.Delete(dstEndPoint);
                    outputs[0].OutputStrings.Add(result);
                }
                catch (Exception e)
                {
                    outputs[0].OutputStrings.Add(null);
                    allErrors.AddError(e.Message);
                    break;
                }
            }

            return(outputs);
        }
        /// <summary>
        /// Gets the PSComputerName argument from the context
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string[] GetPSComputerName(NativeActivityContext context)
        {
            if (PSComputerName.Expression != null)
            {
                return PSComputerName.Get(context);
            }

            // Retrieve our host overrides
            var hostValues = context.GetExtension<HostParameterDefaults>();

            if (hostValues != null)
            {
                Dictionary<string, object> incomingArguments = hostValues.Parameters;
                if (incomingArguments.ContainsKey("PSComputerName"))
                {
                    return incomingArguments["PSComputerName"] as string[];
                }
            }

            return null;
        }
        protected override void OnBeforeExecute(NativeActivityContext context)
        {
            var dataObject = context.GetExtension <IDSFDataObject>();

            _previousParentID = dataObject.ParentInstanceID;
        }
        private void OnWorkflowCompensationBehaviorScheduled(NativeActivityContext context, Bookmark bookmark, object value)
        {
            CompensationExtension compensationExtension = context.GetExtension <CompensationExtension>();

            this.ScheduleBody(context, compensationExtension);
        }
        // ReSharper restore RedundantOverridenMember

        protected override void OnExecute(NativeActivityContext context)
        {
            IDSFDataObject dataObject = context.GetExtension <IDSFDataObject>();

            ExecuteTool(dataObject, 0);
        }
Exemple #40
0
        protected override void OnExecute(NativeActivityContext context)
        {
            // ???? Why is this here....
            context.Properties.ToObservableCollection();

            IEsbChannel    esbChannel = DataObject.EsbChannel;
            IDSFDataObject dataObject = context.GetExtension <IDSFDataObject>();

            dataObject.EnvironmentID = context.GetValue(EnvironmentID);
            Guid datalistId = DataListExecutionID.Get(context);

            ParentWorkflowInstanceId     = context.WorkflowInstanceId.ToString();
            dataObject.RemoteServiceType = context.GetValue(Type);
            var           resourceId = context.GetValue(ResourceID);
            ErrorResultTO allErrors  = new ErrorResultTO();


            ParentServiceName = dataObject.ServiceName;


            string parentServiceName = string.Empty;
            string serviceName       = string.Empty;

            // BUG 9634 - 2013.07.17 - TWR - changed isRemoteExecution to check EnvironmentID instead
            // This is now the wrong behavior - We need to keep the original EnvironmentID when not a remote workflow
            // This is because we put and empty GUID in when designing against a remote server that uses it's resources
            // The first time through this value is set correctly when executing those designed resource from our localhost
            // If we change it as per what was here, we always get a localhost tag instead of the remote host we are design against
            var isRemote = dataObject.IsRemoteWorkflow();

            if ((isRemote || dataObject.IsRemoteInvokeOverridden) && dataObject.EnvironmentID == Guid.Empty)
            {
                dataObject.IsRemoteInvokeOverridden = true;
            }

            var oldResourceId = dataObject.ResourceID;

            InitializeDebug(dataObject);

            try
            {
                //compiler.ClearErrors(dataObject.DataListID);

                if (ServiceServer != Guid.Empty)
                {
                    // we need to adjust the originating server id so debug reflect remote server instead of localhost ;)
                    dataObject.RemoteInvokerID = ServiceServer.ToString();
                }


                dataObject.RunWorkflowAsync = RunWorkflowAsync;
                if (dataObject.IsDebugMode() || (dataObject.RunWorkflowAsync && !dataObject.IsFromWebServer))
                {
                    DispatchDebugState(dataObject, StateType.Before, 0);
                }


                if (resourceId != Guid.Empty)
                {
                    dataObject.ResourceID = resourceId;
                }

                // scrub it clean ;)

                // set the parent service
                parentServiceName            = dataObject.ParentServiceName;
                serviceName                  = dataObject.ServiceName;
                dataObject.ParentServiceName = serviceName;

                _previousInstanceId = dataObject.ParentInstanceID;
                dataObject.ParentID = oldResourceId;

                dataObject.ParentInstanceID         = UniqueID;
                dataObject.ParentWorkflowInstanceId = ParentWorkflowInstanceId;

                if (!DeferExecution)
                {
                    // In all cases the ShapeOutput will have merged the execution data up into the current
                    ErrorResultTO tmpErrors = new ErrorResultTO();

                    if (esbChannel == null)
                    {
                        throw new Exception("FATAL ERROR : Null ESB channel!!");
                    }
                    else
                    {
                        // NEW EXECUTION MODEL ;)
                        // PBI 7913
                        if (datalistId != GlobalConstants.NullDataListID)
                        {
                            BeforeExecutionStart(dataObject, allErrors);
                            allErrors.MergeErrors(tmpErrors);

                            dataObject.ServiceName = ServiceName; // set up for sub-exection ;)
                            dataObject.ResourceID  = ResourceID.Expression == null ? Guid.Empty : Guid.Parse(ResourceID.Expression.ToString());

                            // Execute Request
                            ExecutionImpl(esbChannel, dataObject, InputMapping, OutputMapping, out tmpErrors, 0); // careful of zero if wf comes back

                            allErrors.MergeErrors(tmpErrors);

                            AfterExecutionCompleted(tmpErrors);
                            allErrors.MergeErrors(tmpErrors);
                            dataObject.DataListID  = datalistId; // re-set DL ID
                            dataObject.ServiceName = ServiceName;
                        }
                    }

                    bool whereErrors = dataObject.Environment.HasErrors();

                    SetValues(context, whereErrors);
                }
            }
            finally
            {
                // Handle Errors
                if (allErrors.HasErrors())
                {
                    DisplayAndWriteError("DsfActivity", allErrors);
                    dataObject.Environment.AddError(allErrors.MakeDataListReady());
                    // add to datalist in variable specified
                    if (!String.IsNullOrEmpty(OnErrorVariable))
                    {
                        var upsertVariable = DataListUtil.AddBracketsToValueIfNotExist(OnErrorVariable);
                        dataObject.Environment.Assign(upsertVariable, allErrors.MakeDataListReady(), 0);
                    }
                }

                if (dataObject.IsDebugMode() || (dataObject.RunWorkflowAsync && !dataObject.IsFromWebServer))
                {
                    DispatchDebugState(dataObject, StateType.After, 0);
                }

                dataObject.ParentInstanceID        = _previousInstanceId;
                dataObject.ParentServiceName       = parentServiceName;
                dataObject.ServiceName             = serviceName;
                dataObject.RemoteInvokeResultShape = new StringBuilder(); // reset targnet shape ;)
                dataObject.RunWorkflowAsync        = false;
                dataObject.RemoteInvokerID         = Guid.Empty.ToString();
                dataObject.EnvironmentID           = Guid.Empty;
                dataObject.ResourceID = oldResourceId;
            }
        }
Exemple #41
0
        protected override void StartLoop(NativeActivityContext context)
        {
            WindowsCacheExtension ext = context.GetExtension <WindowsCacheExtension>();
            var sw = new Stopwatch();

            sw.Start();
            Log.Selector(string.Format("Windows.GetElement::begin {0:mm\\:ss\\.fff}", sw.Elapsed));

            UIElement[] elements = null;
            var         selector = Selector.Get(context);

            selector = OpenRPA.Interfaces.Selector.Selector.ReplaceVariables(selector, context.DataContext);
            var sel        = new WindowsSelector(selector);
            var timeout    = Timeout.Get(context);
            var maxresults = MaxResults.Get(context);
            var minresults = MinResults.Get(context);

            if (maxresults < 1)
            {
                maxresults = 1;
            }
            var interactive = Interactive.Get(context);
            var from        = From.Get(context);
            int failcounter = 0;

            if (timeout.Minutes > 5 || timeout.Hours > 1)
            {
                Activity _Activity = null;
                try
                {
                    var strProperty = context.GetType().GetProperty("Activity", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                    var strGetter   = strProperty.GetGetMethod(nonPublic: true);
                    _Activity = (Activity)strGetter.Invoke(context, null);
                }
                catch (Exception)
                {
                }
                if (_Activity != null)
                {
                    Log.Warning("Timeout for Activity " + _Activity.Id + " is above 5 minutes, was this the intention ? calculated value " + timeout.ToString());
                }
                else
                {
                    Log.Warning("Timeout for on of your Windows.GetElements is above 5 minutes, was this the intention ? calculated value " + timeout.ToString());
                }
            }
            do
            {
                if (ClearCache != null && ClearCache.Get(context))
                {
                    Log.Selector(string.Format("Windows.GetElement::Clearing windows element cache {0:mm\\:ss\\.fff}", sw.Elapsed));
                    WindowsSelectorItem.ClearCache();
                }
                if (PluginConfig.get_elements_in_different_thread)
                {
                    elements = OpenRPA.AutomationHelper.RunSTAThread <UIElement[]>(() =>
                    {
                        try
                        {
                            Log.Selector(string.Format("Windows.GetElement::GetElementsWithuiSelector in non UI thread {0:mm\\:ss\\.fff}", sw.Elapsed));
                            return(WindowsSelector.GetElementsWithuiSelector(sel, from, maxresults, ext));
                        }
                        catch (System.Threading.ThreadAbortException)
                        {
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex.ToString());
                        }
                        return(new UIElement[] { });
                    }, PluginConfig.search_timeout).Result;
                }
                else
                {
                    Log.Selector(string.Format("Windows.GetElement::GetElementsWithuiSelector using UI thread {0:mm\\:ss\\.fff}", sw.Elapsed));
                    elements = WindowsSelector.GetElementsWithuiSelector(sel, from, maxresults, ext);
                    if (elements == null || elements.Length == 0)
                    {
                        elements = WindowsSelector.GetElementsWithuiSelector(sel, from, maxresults, ext);
                    }
                }
                //elements = WindowsSelector.GetElementsWithuiSelector(sel, from, maxresults);
                if (elements == null)
                {
                    elements = new UIElement[] { };
                }
                if (elements.Length == 0)
                {
                    Log.Selector(string.Format("Windows.GetElement::Found no elements {0:mm\\:ss\\.fff}", sw.Elapsed));
                    failcounter++;
                }
                if (failcounter > 2)
                {
                    WindowsSelectorItem.ClearCache();
                }
            } while (elements != null && elements.Length == 0 && sw.Elapsed < timeout);
            if (PluginConfig.get_elements_in_different_thread && elements.Length > 0)
            {
                // Get them again, we need the COM objects to be loaded in the UI thread
                elements = WindowsSelector.GetElementsWithuiSelector(sel, from, maxresults, ext);
            }
            context.SetValue(Elements, elements);

            var lastelements = context.GetValue(_lastelements);

            if (lastelements == null)
            {
                lastelements = new UIElement[] { }
            }
            ;
            context.SetValue(_lastelements, elements);
            if ((elements.Length + lastelements.Length) < minresults)
            {
                Log.Selector(string.Format("Windows.GetElement::Failed locating " + minresults + " item(s) {0:mm\\:ss\\.fff}", sw.Elapsed));
                throw new ElementNotFoundException("Failed locating " + minresults + " item(s)");
            }
            IEnumerator <UIElement> _enum = elements.ToList().GetEnumerator();
            bool more = _enum.MoveNext();

            if (lastelements.Length == elements.Length && lastelements.Length > 0)
            {
                more = !System.Collections.StructuralComparisons.StructuralEqualityComparer.Equals(lastelements, elements);
            }
            if (more)
            {
                if (interactive)
                {
                    var testelement = _enum.Current;
                    Wait.UntilResponsive(testelement.RawElement, PluginConfig.search_timeout);
                }
                context.SetValue(_elements, _enum);
                context.SetValue(_sw, sw);
                Log.Selector(string.Format("Windows.GetElement::end:: call ScheduleAction: {0:mm\\:ss\\.fff}", sw.Elapsed));
                IncIndex(context);
                SetTotal(context, elements.Length);
                context.ScheduleAction <UIElement>(Body, _enum.Current, OnBodyComplete);
            }
            else
            {
                Log.Selector(string.Format("Windows.GetElement:end {0:mm\\:ss\\.fff}", sw.Elapsed));
            }
        }
Exemple #42
0
        private void BookmarkResumed(NativeActivityContext context, Bookmark bookmark, object value)
        {
            var dict = (Dictionary<string,object>)value;
            object company = null, contact = null, recordState = null, isCompleted = null, referenceClass = null, referenceTable = null, referenceID = null;
            if (dict.TryGetValue("CompanyID", out company))
            {
                var temp = (string)company;
                this.SubmittedCompanyID.Set(context, temp);
                context.GetExtension<MetadataExtension>().CompanyID = temp;
            }
            if (dict.TryGetValue("ContactID", out contact))
            {
                var temp = (string)contact;
                this.SubmittedContactID.Set(context, temp);
                context.GetExtension<MetadataExtension>().ContactID = temp;
            }
            if (dict.TryGetValue("RecordState", out recordState))
            {
                this.SubmittedRecordState.Set(context, (string)dict["RecordState"]);
                context.GetExtension<MetadataExtension>().RecordState = (string)dict["RecordState"];
            }
            if (dict.TryGetValue("IsCompleted", out isCompleted))
            {
                var temp = (string)isCompleted;
                this.SubmittedRecordState.Set(context, temp);
                context.GetExtension<MetadataExtension>().IsCompleted = temp;
            }
            if (dict.TryGetValue("ReferenceClass", out referenceClass))
            {
                var temp = (string)referenceClass;
                this.SubmittedRecordState.Set(context, temp);
                context.GetExtension<MetadataExtension>().ReferenceClass = temp;
            }
            if (dict.TryGetValue("ReferenceTable", out referenceTable))
            {
                var temp = (string)referenceTable;
                this.SubmittedRecordState.Set(context, temp);
                context.GetExtension<MetadataExtension>().ReferenceTable = temp;
            }
            if (dict.TryGetValue("ReferenceID", out referenceID))
            {
                var temp = (string)referenceID;
                this.SubmittedRecordState.Set(context, temp);
                context.GetExtension<MetadataExtension>().ReferenceID = temp;
            }

            if (System.Diagnostics.Debugger.IsAttached)
            {
                System.Diagnostics.Debug.WriteLine("Bookmark resumed with '{0}'.", dict);
            }
        }
        private void OnConfirmationComplete(NativeActivityContext context, System.Activities.ActivityInstance completedInstance)
        {
            CompensationExtension extension = context.GetExtension <CompensationExtension>();

            context.RemoveBookmark(extension.WorkflowCompensation);
        }