HasErrors() 공개 메소드

Determines whether this instance has errors.
public HasErrors ( ) : bool
리턴 bool
예제 #1
0
        /// <summary>
        /// Merges the errors.
        /// </summary>
        /// <param name="toMerge">To merge.</param>
        public void MergeErrors(ErrorResultTO toMerge)
        {
            if (toMerge != null && toMerge.HasErrors())
            {
                // Flipping Union does not appear to work
                foreach (string wtf in toMerge.FetchErrors())
                {
                    _errorList.Add(wtf);
                }

                toMerge.ClearErrors();
            }
        }
        protected override Guid ExecutionImpl(IEsbChannel esbChannel, IDSFDataObject dataObject, string inputs, string outputs, out ErrorResultTO tmpErrors)
        {
            tmpErrors = new ErrorResultTO();
            var webserviceExecution = GetNewWebserviceExecution(dataObject);


            if(webserviceExecution != null && !tmpErrors.HasErrors())
            {
                webserviceExecution.InstanceOutputDefintions = outputs; // set the output mapping for the instance ;)
                webserviceExecution.InstanceInputDefinitions = inputs;
                ErrorResultTO invokeErrors;
                var result = webserviceExecution.Execute(out invokeErrors);
                dataObject.Environment.AddError(invokeErrors.MakeDataListReady());
                return result;
            }
            return Guid.NewGuid();
        }
예제 #3
0
        /// <summary>
        /// Fetches the system model as web model.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dlID">The dl ID.</param>
        /// <param name="errors">The errors.</param>
        /// <returns></returns>
        public string FetchSystemModelAsWebModel <T>(Guid dlID, out ErrorResultTO errors)
        {
            T      model  = FetchSystemModelFromDataList <T>(dlID, out errors);
            string result = "{}"; // empty data set for injection ;)

            if (!errors.HasErrors())
            {
                var dev2DataModel = model as IDev2DataModel;

                if (dev2DataModel != null)
                {
                    result = dev2DataModel.ToWebModel();
                }
            }

            return(result);
        }
예제 #4
0
        protected override IList<OutputTO> ExecuteConcreteAction(IDSFDataObject dataObject, out ErrorResultTO allErrors, int update)
        {
            IList<OutputTO> outputs = new List<OutputTO>();

            allErrors = new ErrorResultTO();
            var colItr = new WarewolfListIterator();

            //get all the possible paths for all the string variables
            var inputItr = new WarewolfIterator(dataObject.Environment.Eval(OutputPath, update));
            colItr.AddVariableToIterateOn(inputItr);

            var unameItr = new WarewolfIterator(dataObject.Environment.Eval(Username, update));
            colItr.AddVariableToIterateOn(unameItr);

            var passItr = new WarewolfIterator(dataObject.Environment.Eval(DecryptedPassword,update));
            colItr.AddVariableToIterateOn(passItr);

            var privateKeyItr = new WarewolfIterator(dataObject.Environment.Eval(PrivateKeyFile, update));
            colItr.AddVariableToIterateOn(privateKeyItr);

            var contentItr =new WarewolfIterator(dataObject.Environment.Eval(FileContents, update));
            colItr.AddVariableToIterateOn(contentItr);

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


            if(dataObject.IsDebugMode())
            {
                AddDebugInputItem(OutputPath, "Output Path", dataObject.Environment, update);
                AddDebugInputItem(new DebugItemStaticDataParams(GetMethod(), "Method"));
                AddDebugInputItemUserNamePassword(dataObject.Environment, update);
                if (!string.IsNullOrEmpty(PrivateKeyFile))
                {
                    AddDebugInputItem(PrivateKeyFile, "Private Key File", dataObject.Environment, update);
                }
                AddDebugInputItem(FileContents, "File Contents", dataObject.Environment, update);
            }

            while(colItr.HasMoreData())
            {
                IActivityOperationsBroker broker = ActivityIOFactory.CreateOperationsBroker();
                var writeType = GetCorrectWriteType();
                Dev2PutRawOperationTO putTo = ActivityIOFactory.CreatePutRawOperationTO(writeType, TextUtils.ReplaceWorkflowNewLinesWithEnvironmentNewLines(colItr.FetchNextValue(contentItr)));
                IActivityIOPath opath = ActivityIOFactory.CreatePathFromString(colItr.FetchNextValue(inputItr),
                                                                                colItr.FetchNextValue(unameItr),
                                                                                colItr.FetchNextValue(passItr),
                                                                                true, colItr.FetchNextValue(privateKeyItr));
                IActivityIOOperationsEndPoint endPoint = ActivityIOFactory.CreateOperationEndPointFromIOPath(opath);

                try
                {
                    if(allErrors.HasErrors())
                    {
                        outputs[0].OutputStrings.Add(null);
                    }
                    else
                    {
                        string result = broker.PutRaw(endPoint, putTo);
                        outputs[0].OutputStrings.Add(result);
                    }
                }
                catch(Exception e)
                {
                    outputs[0].OutputStrings.Add(null);
                    allErrors.AddError(e.Message);
                    break;
                }
            }

            return outputs;
        }
예제 #5
0
        // BUG 9706 - 2013.06.22 - TWR : refactored
        void DispatchDebugErrors(ErrorResultTO errors, IDSFDataObject dataObject, StateType stateType)
        {
            if(errors.HasErrors() && dataObject.IsDebugMode())
            {
                Guid parentInstanceId;
                Guid.TryParse(dataObject.ParentInstanceID, out parentInstanceId);

                var debugState = new DebugState
                {
                    ID = dataObject.DataListID,
                    ParentID = parentInstanceId,
                    WorkspaceID = dataObject.WorkspaceID,
                    StateType = stateType,
                    StartTime = DateTime.Now,
                    EndTime = DateTime.Now,
                    ActivityType = ActivityType.Workflow,
                    DisplayName = dataObject.ServiceName,
                    IsSimulation = dataObject.IsOnDemandSimulation,
                    ServerID = dataObject.ServerID,
                    OriginatingResourceID = dataObject.ResourceID,
                    OriginalInstanceID = dataObject.OriginalInstanceID,
                    SessionID = dataObject.DebugSessionID,
                    EnvironmentID = dataObject.EnvironmentID,
                    ClientID = dataObject.ClientID,
                    Server = string.Empty,
                    Version = string.Empty,
                    Name = GetType().Name,
                    HasError = errors.HasErrors(),
                    ErrorMessage = errors.MakeDisplayReady()
                };

                DebugDispatcher.Instance.Write(debugState, dataObject.RemoteInvoke, dataObject.RemoteInvokerID);
            }
        }
예제 #6
0
        /// <summary>
        /// Invokes the specified service as per the dataObject against theHost
        /// </summary>
        /// <param name="dataObject">The data object.</param>
        /// <param name="errors">The errors.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception">Can only execute workflows from web browser</exception>
        public Guid Invoke(IDSFDataObject dataObject, out ErrorResultTO errors)
        {
            var result = GlobalConstants.NullDataListID;
            var time = new Stopwatch();
            time.Start();
            errors = new ErrorResultTO();
            int update = 0;
            // BUG 9706 - 2013.06.22 - TWR : added pre debug dispatch
            if(dataObject.Environment.HasErrors())
            {
                errors.AddError(dataObject.Environment.FetchErrors());
                DispatchDebugErrors(errors, dataObject, StateType.Before);
            }
            errors.ClearErrors();
            try
            {
                var serviceId = dataObject.ResourceID;

                // we need to get better at getting this ;)

                var serviceName = dataObject.ServiceName;
                if(serviceId == Guid.Empty && string.IsNullOrEmpty(serviceName))
                {
                    errors.AddError(Resources.DynamicServiceError_ServiceNotSpecified);
                }
                else
                {

                    try
                    {
                        var sl = new ServiceLocator();
                        Dev2Logger.Log.Debug("Finding service");
                        var theService = serviceId == Guid.Empty ? sl.FindService(serviceName, _workspace.ID) : sl.FindService(serviceId, _workspace.ID);

                        if(theService == null)
                        {
                            errors.AddError("Service [ " + serviceName + " ] not found.");
                        }
                        else if(theService.Actions.Count <= 1)
                        {
                            #region Execute ESB container

                            var theStart = theService.Actions.FirstOrDefault();
                            if(theStart != null && theStart.ActionType != Common.Interfaces.Core.DynamicServices.enActionType.InvokeManagementDynamicService && theStart.ActionType != Common.Interfaces.Core.DynamicServices.enActionType.Workflow && dataObject.IsFromWebServer)
                            {
                                throw new Exception("Can only execute workflows from web browser");
                            }
                            Dev2Logger.Log.Debug("Mapping Action Dependencies");
                            MapServiceActionDependencies(theStart, sl);

                            // Invoke based upon type ;)
                            if(theStart != null)
                            {
                                theStart.DataListSpecification = theService.DataListSpecification;
                                Dev2Logger.Log.Debug("Getting container");
                                var container = GenerateContainer(theStart, dataObject, _workspace);
                                ErrorResultTO invokeErrors;
                                result = container.Execute(out invokeErrors, update);
                                errors.MergeErrors(invokeErrors);
                            }
                            #endregion
                        }
                        else
                        {
                            errors.AddError("Malformed Service [ " + serviceId + " ] it contains multiple actions");
                        }
                    }
                    catch(Exception e)
                    {
                        errors.AddError(e.Message);
                    }
                    finally
                    {
                        if (dataObject.Environment.HasErrors())
                        {
                            var errorString = dataObject.Environment.FetchErrors();
                            var executionErrors = ErrorResultTO.MakeErrorResultFromDataListString(errorString);
                            errors.MergeErrors(executionErrors);
                        }

                        dataObject.Environment.AddError(errors.MakeDataListReady());

                        if(errors.HasErrors())
                        {
                            Dev2Logger.Log.Error(errors.MakeDisplayReady());
                        }
                    }
                }
            }
            finally
            {
                time.Stop();
                ServerStats.IncrementTotalRequests();
                ServerStats.IncrementTotalTime(time.ElapsedMilliseconds);
                // BUG 9706 - 2013.06.22 - TWR : added
                DispatchDebugErrors(errors, dataObject, StateType.End);
            }
            return result;
        }
        /// <summary>
        /// Merges the errors.
        /// </summary>
        /// <param name="toMerge">To merge.</param>
        public void MergeErrors(ErrorResultTO toMerge)
        {
            if (toMerge != null && toMerge.HasErrors())
            {
                // Flipping Union does not appear to work
                foreach (string wtf in toMerge.FetchErrors())
                {
                    _errorList.Add(wtf);
                }

                toMerge.ClearErrors();
            }
        }
        /// <summary>
        ///     Configures the decision expression.
        ///     Travis.Frisinger - Developed for new Decision Wizard
        /// </summary>
        /// <param name="wrapper">The wrapper.</param>
        internal void ConfigureDecisionExpression(Tuple<ModelItem, IEnvironmentModel> wrapper)
        {
            IEnvironmentModel environment = wrapper.Item2;
            ModelItem decisionActivity = wrapper.Item1;

            ModelProperty conditionProperty = decisionActivity.Properties[GlobalConstants.ConditionPropertyText];

            if (conditionProperty == null) return;

            var activity = conditionProperty.Value;
            if (activity != null)
            {
                string val = JsonConvert.SerializeObject(DataListConstants.DefaultStack);

                ModelProperty activityExpression = activity.Properties[GlobalConstants.ExpressionPropertyText];

                ErrorResultTO errors = new ErrorResultTO();

                if (errors.HasErrors()) //BUG 8796, Added this if to handle errors
                {
                    // Bad things happened... Tell the user
                    PopupProvider.Show(errors.MakeDisplayReady(), GlobalConstants.DecisionWizardErrorHeading, MessageBoxButton.OK, MessageBoxImage.Error);
                    // Stop configuring!!!
                    return;
                }

                // Push the correct data to the server ;)
                if (activityExpression != null && activityExpression.Value == null)
                {
                    // Its all new, push the empty model
                    //compiler.PushSystemModelToDataList(dataListID, DataListConstants.DefaultStack, out errors);
                }
                else if (activityExpression != null && activityExpression.Value != null)
                {
                    //we got a model, push it in to the Model region ;)
                    // but first, strip and extract the model data ;)

                    val = Dev2DecisionStack.ExtractModelFromWorkflowPersistedData(activityExpression.Value.ToString());

                    if (string.IsNullOrEmpty(val))
                    {

                        val = JsonConvert.SerializeObject(DataListConstants.DefaultStack);
                    }
                }

                // Now invoke the Wizard ;)
                Uri requestUri;
                if (Uri.TryCreate((environment.WebServerAddress + GlobalConstants.DecisionWizardLocation), UriKind.Absolute, out requestUri))
                {
                    string uriString = Browser.FormatUrl(requestUri.AbsoluteUri, GlobalConstants.NullDataListID);


                    _callBackHandler.ModelData = val; // set the model data

                //callBackHandler.Owner = new WebPropertyEditorWindow(callBackHandler, uriString);
                //callBackHandler.Owner.ShowDialog();
                WebSites.ShowWebPageDialog(uriString, _callBackHandler, 824, 508);
                    WebSites.ShowWebPageDialog(uriString, callBackHandler, 824, 508);

                    // Wizard finished...
                    try
                    {
                        // Remove naughty chars...
                        var tmp = callBackHandler.ModelData;
                        // remove the silly Choose... from the string
                        tmp = Dev2DecisionStack.RemoveDummyOptionsFromModel(tmp);
                        // remove [[]], &, !
                        tmp = Dev2DecisionStack.RemoveNaughtyCharsFromModel(tmp);

                        Dev2DecisionStack dds = JsonConvert.DeserializeObject<Dev2DecisionStack>(tmp);

                        if (dds != null)
                        {
                            // Empty check the arms ;)
                            if (string.IsNullOrEmpty(dds.TrueArmText.Trim()))
                            {
                                dds.TrueArmText = GlobalConstants.DefaultTrueArmText;
                            }

                            if (string.IsNullOrEmpty(dds.FalseArmText.Trim()))
                            {
                                dds.FalseArmText = GlobalConstants.DefaultFalseArmText;
                            }

                            // Update the decision node on the workflow ;)
                            string modelData = dds.ToVBPersistableModel();

                            // build up our injected expression handler ;)
                            string expressionToInject = string.Join("", GlobalConstants.InjectedDecisionHandler, "(\"", modelData, "\",", GlobalConstants.InjectedDecisionDataListVariable, ")");

                            if (activityExpression != null)
                            {
                                activityExpression.SetValue(expressionToInject);
                            }

                            // now set arms ;)
                            ModelProperty tArm = decisionActivity.Properties[GlobalConstants.TrueArmPropertyText];

                            if (tArm != null)
                            {
                                tArm.SetValue(dds.TrueArmText);
                            }

                            ModelProperty fArm = decisionActivity.Properties[GlobalConstants.FalseArmPropertyText];

                            if (fArm != null)
                            {
                                fArm.SetValue(dds.FalseArmText);
                            }
                        }
                    }
                    catch
                    {
                        // Bad things happened... Tell the user
                        //PopupProvider.Show("", "")
                        PopupProvider.Buttons = MessageBoxButton.OK;
                        PopupProvider.Description = GlobalConstants.DecisionWizardErrorString;
                        PopupProvider.Header = GlobalConstants.DecisionWizardErrorHeading;
                        PopupProvider.ImageType = MessageBoxImage.Error;
                        PopupProvider.Show();
                    }
                }
            }
        }
        /// <summary>
        ///     Creates the list of data list item view model to bind to.
        /// </summary>
        /// <param name="errorString">The error string.</param>
        /// <returns></returns>
        public void CreateListsOfIDataListItemModelToBindTo(out string errorString)
        {
            errorString = string.Empty;
            IDataListCompiler compiler = DataListFactory.CreateDataListCompiler();
            if(!string.IsNullOrEmpty(Resource.DataList))
            {
                ErrorResultTO errors = new ErrorResultTO();
                try
                {
                    IBinaryDataList binarnyDl = CreateBinaryDataListFromXmlData(Resource.DataList, out errors);
                    if (!errors.HasErrors())
                    {
                        ConvertBinaryDataListToListOfIDataListItemModels(binarnyDl, out errorString);
                    }
                    else
                    {
                        string errorMessage = errors.FetchErrors().Aggregate(string.Empty, (current, error) => current + error);
                        throw new Exception(errorMessage);
                    }
                    if (binarnyDl != null)
                        compiler.ForceDeleteDataListByID(binarnyDl.UID);
                }
                catch(Exception)
                {
                    errors.AddError("Invalid variable list. Please insure that your variable list has valid entries");
                }
               

            }
            else
            {
                RecsetCollection.Clear();
                AddRecordSet();
                ScalarCollection.Clear();
            }

            BaseCollection = new OptomizedObservableCollection<DataListHeaderItemModel>();

            DataListHeaderItemModel varNode = DataListItemModelFactory.CreateDataListHeaderItem("Variable");
            if(ScalarCollection.Count == 0)
            {
                var dataListItemModel = DataListItemModelFactory.CreateDataListModel(string.Empty);
                ScalarCollection.Add(dataListItemModel);
            }
            varNode.Children = ScalarCollection;
            BaseCollection.Add(varNode);

            //AddRecordsetNamesIfMissing();

            DataListHeaderItemModel recordsetsNode = DataListItemModelFactory.CreateDataListHeaderItem("Recordset");
            if(RecsetCollection.Count == 0)
            {
                AddRecordSet();
            }
            recordsetsNode.Children = RecsetCollection;
            BaseCollection.Add(recordsetsNode);
        }
예제 #10
0
        private void AddErrorsToDataList(ErrorResultTO errors, Guid dataListID)
        {
            // Upsert any errors that might have occured into the datalist
            IBinaryDataListEntry be = Dev2BinaryDataListFactory.CreateEntry(enSystemTag.Error.ToString(), string.Empty);
            string error;
            be.TryPutScalar(Dev2BinaryDataListFactory.CreateBinaryItem(errors.MakeDataListReady(), enSystemTag.Error.ToString()), out error);
            if (!string.IsNullOrWhiteSpace(error))
            {
                //At this point there was an error while trying to handle errors so we throw an exception
                throw new Exception(string.Format("The error '{0}' occured while creating the error entry for the following errors: {1}", error, errors.MakeDisplayReady()));
            }

            var upsertErrors = new ErrorResultTO();
            SvrCompiler.Upsert(null, dataListID, DataListUtil.BuildSystemTagForDataList(enSystemTag.Error, true), be, out upsertErrors);
            if (upsertErrors.HasErrors())
            {
                //At this point there was an error while trying to handle errors so we throw an exception
                throw new Exception(string.Format("The error '{0}' occured while upserting the following errors to the datalist: {1}", errors.MakeDisplayReady(), errors.MakeDisplayReady()));
            }
        }
예제 #11
0
        public Guid Invoke(DynamicService service, dynamic xmlRequest, Guid dataListId, out ErrorResultTO errors)
        {
            //dynamic result = new UnlimitedObject();
            //dynamic forwardResult = new UnlimitedObject();
            var allErrors = new ErrorResultTO();
            errors = new ErrorResultTO();

            if(service == null)
            {
                allErrors.AddError("Dynamic Service not found exception");
                return GlobalConstants.NullDataListID;
            }

            string dataList = service.DataListSpecification;


            // PBI : 5376 Amendedment for DataList Server
            Guid result = GlobalConstants.NullDataListID;
            string data = xmlRequest.XmlString.Trim();
            byte[] incomingData = Encoding.UTF8.GetBytes(data);
            Guid serviceDataId;


            var performDataListInMerge = false;

            if(dataList != string.Empty)
            {
                serviceDataId = SvrCompiler.ConvertTo(null, DataListFormat.CreateFormat(GlobalConstants._XML),
                                                       incomingData, dataList, out errors);
                errors = new ErrorResultTO(); // re-set to avoid carring

                // PBI : 5376
                // If dataListID == NullID, create a new list and set it as the current ID
                // Else, create a new list, union the old data into the new and continue on ;)
                if(dataListId != GlobalConstants.NullDataListID)
                {
                    serviceDataId = SvrCompiler.Merge(null, serviceDataId, dataListId, enDataListMergeTypes.Union,
                                                       enTranslationDepth.Data, false, out errors);
                }
                else
                {
                    performDataListInMerge = true;
                }
            }
            else
            {
                serviceDataId = SvrCompiler.CloneDataList(dataListId, out errors);
                performDataListInMerge = true;
            }

            if (errors.HasErrors())
            {
                allErrors.MergeErrors(errors);
            }
            IDSFDataObject dataObject = new DsfDataObject(xmlRequest.XmlString, serviceDataId);
            dataObject.DataList = dataList;

            if(performDataListInMerge)
            {
                SvrCompiler.ConditionalMerge(null, DataListMergeFrequency.Always, serviceDataId,
                                              dataObject.DatalistInMergeID,
                                              DataListMergeFrequency.Always, dataObject.DatalistInMergeType,
                                              dataObject.DatalistInMergeDepth);
            }

            // TODO  : Reset the AmbientDataList to this ID?

            // Fetch data for Input binding...
            DataListTranslatedPayloadTO tmpData = null;
            dynamic inputBinding = null;

            // End PBI Amendments

            foreach(ServiceAction serviceAction in service.Actions)
            {
                //TraceWriter.WriteTrace(_managementChannel, string.Format("Validating the inputs of Service '{0}'", service.Name), Resources.TraceMessageType_Message);
                foreach(ServiceActionInput sai in serviceAction.ServiceActionInputs)
                {
                    //Assigning the input the value from the callers request data
                    //TraceWriter.WriteTrace(_managementChannel, string.Format("Discovered input '{0}'", sai.Name), Resources.TraceMessageType_Message);
                    if(sai.CascadeSource)
                    {
                        TraceWriter.WriteTrace(_managementChannel, string.Format("Input '{0}' is cascaded", sai.Name),
                                               Resources.TraceMessageType_Message);
                        //This is a cascaded input so retrieve the value from the
                        //previous actions response
                        //sai.Value = forwardResult.GetValue(sai.Name);
                    }
                    else
                    {
                        if(tmpData == null)
                        {
                            tmpData = SvrCompiler.ConvertFrom(null, serviceDataId, enTranslationDepth.Data,
                                                               DataListFormat.CreateFormat(GlobalConstants._XML),
                                                               out errors);

                            if(!DataListUtil.isNullADL(tmpData.FetchAsString()))
                            {
                                inputBinding = new UnlimitedObject(tmpData.FetchAsString());
                            }
                            else
                            {
                                // Empty data, try the incoming stream?!
                                inputBinding = new UnlimitedObject(xmlRequest.XmlString);
                            }
                        }

                        // 16.10.2012 : Travis.Frisinger - EmptyToNull amendments
                        string tmpVal = inputBinding.GetValue(sai.Name);
                        if(sai.EmptyToNull && tmpVal == string.Empty)
                        {
                            tmpVal = AppServerStrings.NullConstant;
                        }

                        sai.Value = tmpVal;
                    }

                    //TraceWriter.WriteTrace(string.Format("Assigning value {0} to input '{1}'", sai.Value.ToString(), sai.Name));

                    //Validating inputs if there is validation set up in the service definition
                    if(sai.IsRequired && string.IsNullOrEmpty(sai.DefaultValue))
                    {
                        if(!sai.Validate())
                        {
                            allErrors.AddError(string.Format("Validation Failure. Argument '{0}' failed validation.",
                                                             sai.Name));

                            //TraceWriter.WriteTrace(_managementChannel, string.Format("Argument '{0}' failed validation", sai.Name), Resources.TraceMessageType_Message);
                            //xmlRequest.Error = string.Format("Validation Failure. Argument '{0}' failed validation.", sai.Name);
                            //return xmlRequest;
                        }
                    }
                    //This input does not have any value in the callers request
                    //so we are setting the input value to the full request
                    if(string.IsNullOrEmpty(sai.Value.ToString()))
                    {
                        sai.Value = !string.IsNullOrEmpty(sai.DefaultValue) ? sai.DefaultValue : string.Empty;
                    }
                }

                //if (service.Mode == enDynamicServiceMode.ValidationOnly)
                //{
                //    xmlRequest.ValidationOnly.Result = true;

                //    return xmlRequest;
                //}

                if(serviceAction.ActionType == enActionType.Switch)
                {
                    if(!string.IsNullOrEmpty(serviceAction.Cases.DataElementName))
                    {
                        ////Assigning the input the value from the callers request data
                        //if (serviceAction.Cases.CascadeSource)
                        //{
                        //This is a cascaded input so retrieve the value from the
                        //previous actions response
                        //sai.Value = actionResponse.GetValue(sai.Name);
                        //serviceAction.Cases.DataElementValue = forwardResult.GetValue(serviceAction.Cases.DataElementName);
                        //}
                        //else
                        //{
                        serviceAction.Cases.DataElementValue = xmlRequest.GetValue(serviceAction.Cases.DataElementName);
                        //}
                    }
                }


                //
                //Juries - This is a dirty hack, naughty naughty.
                //Hijacked current functionality to enable erros to be added to an item after its already been added to the tree
                //
                if(allErrors.HasErrors())
                {
                    DebugDispatcher.Instance.Write(new DebugState()
                    {
                        ParentID = dataObject.ParentInstanceID,
                        WorkspaceID = dataObject.WorkspaceID,
                        StartTime = DateTime.Now,
                        EndTime = DateTime.Now,
                        IsSimulation = false,
                        ServerID = dataObject.ServerID,
                        Server = string.Empty,
                        Version = string.Empty,
                        Name = GetType().Name,
                        HasError = true,
                        ErrorMessage = allErrors.MakeDisplayReady(),
                        ActivityType = ActivityType.Workflow,
                        StateType = StateType.Append
                    });
                }
                
                // TODO : properly build up DataList prior to this....
                result = Invoke(serviceAction, dataObject, dataList);

                // Remember to clean up ;)
                if(dataListId != GlobalConstants.NullDataListID)
                {
                    // Merge the execution DL into the mainDL ;)

                    Guid mergeId = SvrCompiler.Merge(null, dataListId, serviceDataId, enDataListMergeTypes.Union,
                                                      enTranslationDepth.Data, false, out errors);
                    SvrCompiler.DeleteDataListByID(serviceDataId, true);

                    // Now reset the DataListID on DataObject ;)
                    if(result != serviceDataId)
                    {
                        throw new Exception("FATAL ERROR : DataList Execution Mis-Match!");
                    }

                    dataObject.DataListID = mergeId;
                    result = mergeId;
                }
                else
                {
                    SvrCompiler.ConditionalMerge(null,
                                                  DataListMergeFrequency.Always | DataListMergeFrequency.OnCompletion,
                                                  dataObject.DatalistOutMergeID, dataObject.DataListID,
                                                  dataObject.DatalistOutMergeFrequency, dataObject.DatalistOutMergeType,
                                                  dataObject.DatalistOutMergeDepth);
                } // else we want to keep the DL around until we end execution

                #region Terminate the service if this Service Action is marked to terminate on fault

                //If this action should immediately terminate the execution of this service 
                //then stop here and return the results thus far
                if(serviceAction.TerminateServiceOnFault && errors.HasErrors())
                {
                    result = GlobalConstants.NullDataListID;
                }

                #endregion
            }

            return result;
        }
예제 #12
0
        /// <summary>
        ///     Responsible for the processing of all inbound requests
        ///     This method is reentrant and will call itself to
        ///     for every invocation required in every generation
        ///     of nesting. e.g services made up of services
        /// </summary>
        /// <param name="resourceDirectory">The singleton instance of the service library that contains all the logical services</param>
        /// <param name="xmlRequest">The actual client request message</param>
        /// <param name="dataListId">The id of the data list</param>
        /// <param name="errors">Errors resulting from this invoke</param>
        /// <returns></returns>
        public Guid Invoke(IDynamicServicesHost resourceDirectory, dynamic xmlRequest, Guid dataListId,
                           out ErrorResultTO errors)
        {
            // Host = resourceDirectory

            #region Async processing of client request - queue the work item asynchronously

            //Get an UnlimitedObject from the xml string provided by the caller
            //TraceWriter.WriteTraceIf(_managementChannel != null && _loggingEnabled, "Inspecting inbound data request", Resources.TraceMessageType_Message);
            Guid result = GlobalConstants.NullDataListID;

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

            if(xmlRequest.Async is string)
            {
                //TraceWriter.WriteTrace(_managementChannel, "Caller requested async execution");
                bool isAsync;

                bool.TryParse(xmlRequest.Async, out isAsync);

                if(isAsync)
                {
                    ThreadPool.QueueUserWorkItem(delegate
                    {
                        ErrorResultTO tmpErrors;
                        //TraceWriter.WriteTrace(_managementChannel, "Queuing Asynchronous work", Resources.TraceMessageType_Message);
                        xmlRequest.RemoveElementByTagName("Async");
                        IDynamicServicesInvoker invoker = new DynamicServicesInvoker(_dsfChannel, _managementChannel);
                        result = invoker.Invoke(resourceDirectory, xmlRequest, dataListId, out tmpErrors);
                        if(tmpErrors.HasErrors())
                        {
                            allErrors.MergeErrors(tmpErrors);
                        }
                        //TraceWriter.WriteTrace(result.XmlString);
                        if(result != GlobalConstants.NullDataListID)
                        {
                            // PBI : 5376
                            SvrCompiler.DeleteDataListByID(result, true); //TODO: Clean it up ;)
                        }
                    });
                    dynamic returnData = new UnlimitedObject();
                    returnData.Load(string.Format("<ServiceResponse>{0} Work Item Queued..</ServiceResponse>",
                                                  DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss.fff")));
                    return returnData;
                }
            }

            #endregion

            #region Get a handle on the service that is being requested from the service directory

            string serviceName = string.Empty;

            //Set the service name as this is a complex message
            //with multiple services requests embedded in the inbound data
            //This will allow us to 
            if(xmlRequest.Service is IEnumerable<UnlimitedObject>)
            {
                IEnumerable<UnlimitedObject> services = xmlRequest.Service;
                dynamic serviceData = services.First();
                if(serviceData.Service is string)
                {
                    serviceName = serviceData.Service;
                }
            }


            //If there is only a single service request then get the service name
            if(xmlRequest.Service is string)
            {
                serviceName = xmlRequest.Service;
            }

            //If the service name does not exist return an error to the caller
            if(string.IsNullOrEmpty(serviceName))
            {
                xmlRequest.Error = Resources.DynamicServiceError_ServiceNotSpecified;
            }

            //Try to retrieve the service from the service directory

            IEnumerable<DynamicService> service;
            Host.LockServices();

            try
            {
                service = from c in resourceDirectory.Services
                          where serviceName != null
                          && c.Name.Trim().Equals(serviceName.Trim(), StringComparison.CurrentCultureIgnoreCase)
                          select c;
            }
            finally
            {
                Host.UnlockServices();
            }

            service = service.ToList();

            if(!service.Any())
            {
                TraceWriter.WriteTrace(_managementChannel, string.Format("Service '{0}' Not Found", serviceName),
                                       Resources.TraceMessageType_Error);

                allErrors.AddError(string.Format("Service '{0}' Not Found", serviceName));

                throw new InvalidOperationException(string.Format("Service '{0}' Not Found", serviceName));

                //xmlRequest.Error = Resources.DynamicServiceError_ServiceNotFound;
            }

            #endregion

            //Instantiate a Dynamic Invocation type to invoke the service

            #region  Transactionalized Service Invocation with support for MS-DTC

            dynamic dseException = null;

            //The transactionScope is used to create an ambient transaction that every action will be subject to
            //This transaction 
            try
            {
                //TraceWriter.WriteTrace(_managementChannel, string.Format("Setting up transaction scope", serviceName), Resources.TraceMessageType_Message);
                using(var transactionScope = new TransactionScope())
                {
                    //TraceWriter.WriteTrace(_managementChannel, string.Format("Invoking Service '{0}'", serviceName), Resources.TraceMessageType_Message);

                    #region Process several requests to different services as a single unit of work

                    //Type 3 request (read above)
                    //This is handled differently to type 1 and 2 requests
                    //as it can execute in the context of either a single or 
                    //multiple services.
                    //if (xmlRequest.IsMultipleRequests) {
                    //    TraceWriter.WriteTrace(_managementChannel, "Caller requested multiple service execution in single request", Resources.TraceMessageType_Message);
                    //    dynamic results = new UnlimitedObject();

                    //    foreach (dynamic request in xmlRequest.Requests) {

                    //        dynamic result = new DynamicServicesInvoker(_dsfChannel, _managementChannel).Invoke(resourceDirectory, request);
                    //        if (result.HasError) {
                    //            return result;
                    //        }
                    //        results.AddResponse(result);
                    //    }
                    //    transactionScope.Complete();

                    //    return results;
                    //}

                    #endregion

                    DynamicService s = service.First();
                    result = Invoke(s, xmlRequest, dataListId, out errors);
                    if(result == GlobalConstants.NullDataListID)
                    {
                        allErrors.AddError("Failed to invoke service");
                 
                    }
                    
                    if(!ClientCompiler.HasErrors(result))
                    {
                        transactionScope.Complete();
                    }

                    //The service exists so invoke the service which runs all actions defined for the service
                    //Return the response
                    //return xmlResponses;
                }
            }
            //Occurs when an operation is attempted on a rolled back transaction
            catch(TransactionAbortedException abortEx)
            {
                dseException = abortEx;
            }
            //This exception is thrown when an action is attempted on a transaction that is in doubt. 
            //A transaction is in doubt when the state of the transaction cannot be determined. 
            //Specifically, the final outcome of the transaction, whether it commits or aborts, is never known for this transaction.
            catch(TransactionInDoubtException inDoubtEx)
            {
                dseException = inDoubtEx;
            }
            //Thrown when a resource manager cannot communicate with the transaction manager. 
            catch(TransactionManagerCommunicationException transactionManagerEx)
            {
                dseException = transactionManagerEx;
            }
            //Thrown when a promotion fails
            catch(TransactionPromotionException promotionException)
            {
                dseException = promotionException;
            }
            catch(TransactionException transactionEx)
            {
                dseException = transactionEx;
            }

            if(dseException != null)
            {
                TraceWriter.WriteTrace(_managementChannel,
                                       string.Format("Service Execution Failed With Error\r\n{0}",
                                                     new UnlimitedObject(dseException).XmlString),
                                       Resources.TraceMessageType_Error);
            }

            // set error variable
            errors = allErrors;
            if(errors.HasErrors())
            {
                DispatchDebugState(xmlRequest, dataListId, allErrors);
            }

            return result;

            #endregion
        }
예제 #13
0
        /// <summary>
        /// Invoke a management method which is a statically coded method in the service implementation for service engine administrators
        /// </summary>
        /// <param name="serviceAction">Action of type InvokeManagementDynamicService</param>
        /// <param name="xmlRequest">The XML request.</param>
        /// <returns>
        /// UnlimitedObject
        /// </returns>
        public Guid  ManagementDynamicService(ServiceAction serviceAction, IDSFDataObject xmlRequest)
        {
            var errors = new ErrorResultTO();
            var allErrors = new ErrorResultTO();
            Guid result = GlobalConstants.NullDataListID;

            try
            {
                object[] parameterValues = null;
                //Instantiate a Endpoint object that contains all static management methods
                object o = this;
                //Activator.CreateInstance(typeof(Unlimited.Framework.DynamicServices.DynamicServicesEndpoint), new object[] {string.Empty});

                //Get the management method
                MethodInfo m = o.GetType().GetMethod(serviceAction.SourceMethod);
                //Infer the parameters of the management method
                ParameterInfo[] parameters = m.GetParameters();
                //If there are parameters then retrieve them from the service action input values
                if(parameters.Count() > 0)
                {
                    IEnumerable<object> parameterData = from c in serviceAction.ServiceActionInputs
                                                        select c.Value;

                    parameterValues = parameterData.ToArray();
                }
                //Invoke the management method and store the return value
                string val = m.Invoke(o, parameterValues).ToString();

                result = ClientCompiler.UpsertSystemTag(xmlRequest.DataListID, enSystemTag.ManagmentServicePayload, val,
                                                         out errors);

                //_clientCompiler.Upsert(xmlRequest.DataListID, DataListUtil.BuildSystemTagForDataList(enSystemTag.ManagmentServicePayload, true), val, out errors);
                allErrors.MergeErrors(errors);

                //returnval = new UnlimitedObject(GetXElement(val));
            }
            catch(Exception ex)
            {
                allErrors.AddError(ex.Message);
            }
            finally
            {
                // handle any errors that might have occured

                if(allErrors.HasErrors())
                {
                    IBinaryDataListEntry be = Dev2BinaryDataListFactory.CreateEntry(enSystemTag.Error.ToString(),
                                                                                    string.Empty);
                    string error;
                    be.TryPutScalar(
                        Dev2BinaryDataListFactory.CreateBinaryItem(allErrors.MakeDataListReady(),
                                                                   enSystemTag.Error.ToString()), out error);
                    if(error != string.Empty)
                    {
                        errors.AddError(error);
                    }
                }

                // No cleanup to happen ;)
            }

            return result;
        }
        // Travis.Frisinger : 25.01.2013 - Amended to be like decision
        internal void ConfigureSwitchCaseExpression(Tuple<ModelItem, IEnvironmentModel> payload)
        {
            IEnvironmentModel environment = payload.Item2;
            ModelItem switchCase = payload.Item1;
            string modelData = JsonConvert.SerializeObject(DataListConstants.DefaultCase);

            ErrorResultTO errors = new ErrorResultTO();
            Guid dataListID = GlobalConstants.NullDataListID;

            if (errors.HasErrors()) //BUG 8796, Added this if to handle errors
            {
                // Bad things happened... Tell the user
                PopupProvider.Show(errors.MakeDisplayReady(), GlobalConstants.SwitchWizardErrorHeading,
                                   MessageBoxButton.OK, MessageBoxImage.Error);
                // Stop configuring!!!
                return;
            }

            // now invoke the wizard ;)
            Uri requestUri;
            if (Uri.TryCreate((environment.WebServerAddress + GlobalConstants.SwitchDragWizardLocation), UriKind.Absolute, out requestUri))
            {
                string uriString = Browser.FormatUrl(requestUri.AbsoluteUri, dataListID);

                //var callBackHandler = new Dev2DecisionCallbackHandler();
                //callBackHandler.Owner = new WebPropertyEditorWindow(callBackHandler, uriString) { Width = 580, Height = 270 };
                //callBackHandler.Owner.ShowDialog();
                _callBackHandler.ModelData = modelData;

                WebSites.ShowWebPageDialog(uriString, _callBackHandler, 470, 285);


                // Wizard finished...
                // Now Fetch from DL and push the model data into the workflow
                try
                {
                    Dev2Switch ds = JsonConvert.DeserializeObject<Dev2Switch>(callBackHandler.ModelData);

                    if (ds != null)
                    {
                        ModelProperty keyProperty = switchCase.Properties["Key"];

                        if (keyProperty != null)
                        {
                            keyProperty.SetValue(ds.SwitchVariable);
                        }
                    }
                }
                catch
                {
                    // Bad things happened... Tell the user
                    PopupProvider.Buttons = MessageBoxButton.OK;
                    PopupProvider.Description = GlobalConstants.SwitchWizardErrorString;
                    PopupProvider.Header = GlobalConstants.SwitchWizardErrorHeading;
                    PopupProvider.ImageType = MessageBoxImage.Error;
                    PopupProvider.Show();
                }
            }
        }
        internal void ConfigureSwitchExpression(Tuple<ModelItem, IEnvironmentModel> wrapper)
        {
            IEnvironmentModel environment = wrapper.Item2;
            ModelItem switchActivity = wrapper.Item1;

            ModelProperty switchProperty = switchActivity.Properties[GlobalConstants.SwitchExpressionPropertyText];

            if (switchProperty != null)
            {
                ModelItem activity = switchProperty.Value;

                if (activity != null)
                {
                    IDataListCompiler compiler = DataListFactory.CreateDataListCompiler(environment.DataListChannel);
                    ModelProperty activityExpression =
                        activity.Properties[GlobalConstants.SwitchExpressionTextPropertyText];

                    ErrorResultTO errors = new ErrorResultTO();
                    Guid dataListID = GlobalConstants.NullDataListID;

                    if (errors.HasErrors()) //BUG 8796, Added this if to handle errors
                    {
                        // Bad things happened... Tell the user
                        PopupProvider.Show(errors.MakeDisplayReady(), GlobalConstants.SwitchWizardErrorHeading,
                                           MessageBoxButton.OK, MessageBoxImage.Error);
                        // Stop configuring!!!
                        return;
                    }

                    string webModel = JsonConvert.SerializeObject(DataListConstants.DefaultSwitch);

                    if (activityExpression != null && activityExpression.Value == null)
                    {
                        // Its all new, push the default model
                        //compiler.PushSystemModelToDataList(dataListID, DataListConstants.DefaultSwitch, out errors);
                    }
                    else
                    {
                        if (activityExpression != null)
                        {
                            if (activityExpression.Value != null)
                            {
                                string val = activityExpression.Value.ToString();

                                if (val.IndexOf(GlobalConstants.InjectedSwitchDataFetch, StringComparison.Ordinal) >= 0)
                                {
                                    // Time to extract the data
                                    int start = val.IndexOf("(", StringComparison.Ordinal);
                                    if (start > 0)
                                    {
                                        int end = val.IndexOf(@""",AmbientData", StringComparison.Ordinal);

                                        if (end > start)
                                        {
                                            start += 2;
                                            val = val.Substring(start, (end - start));

                                            // Convert back for usage ;)
                                            val = Dev2DecisionStack.FromVBPersitableModelToJSON(val);

                                            if (!string.IsNullOrEmpty(val))
                                            {

                                                var ds = new Dev2Switch { SwitchVariable = val };
                                                webModel = JsonConvert.SerializeObject(ds);

                                            }

                                        }
                                    }
                                }
                            }
                        }
                    }

                    // now invoke the wizard ;)
                    Uri requestUri;
                    if (Uri.TryCreate((environment.WebServerAddress + GlobalConstants.SwitchDropWizardLocation), UriKind.Absolute, out requestUri))
                    {
                        string uriString = Browser.FormatUrl(requestUri.AbsoluteUri, dataListID);

                        callBackHandler.ModelData = webModel;
                        WebSites.ShowWebPageDialog(uriString, callBackHandler, 470, 285);


                        // Wizard finished...
                        // Now Fetch from DL and push the model data into the workflow
                        try
                        {
                            Dev2Switch ds = JsonConvert.DeserializeObject<Dev2Switch>(_callBackHandler.ModelData);

                            if (ds != null)
                            {
                                // FetchSwitchData
                                string expressionToInject = string.Join("", GlobalConstants.InjectedSwitchDataFetch, "(\"", ds.SwitchVariable, "\",", GlobalConstants.InjectedDecisionDataListVariable, ")");

                                if (activityExpression != null)
                                {
                                    activityExpression.SetValue(expressionToInject);
                                }
                            }
                        }
                        catch
                        {
                            // Bad things happened... Tell the user
                            PopupProvider.Show(GlobalConstants.SwitchWizardErrorString,
                                               GlobalConstants.SwitchWizardErrorHeading, MessageBoxButton.OK,
                                               MessageBoxImage.Error);
                        }
                    }
                }
            }
        }
        // ReSharper disable InconsistentNaming
        public void DsfPluginActivity_DsfPluginActivityUnitTest_ExecutePluginService_ServiceExecuted()
        // ReSharper restore InconsistentNaming
        {
            //init
            var pluginActivity = new MockDsfPluginActivity();
            var errors = new ErrorResultTO();
            var mockContainer = new Mock<PluginServiceExecution>(new DsfDataObject(It.IsAny<string>(), It.IsAny<Guid>()), It.IsAny<bool>());
            mockContainer.Setup(c => c.Execute(out errors, 0)).Verifiable();

            //exe
            pluginActivity.MockExecutePluginService(mockContainer.Object);

            //assert
            Assert.IsFalse(errors.HasErrors(), "Errors where thrown while executing a plugin service");
            mockContainer.Verify(c => c.Execute(out errors, 0), Times.Once());
        }
        /// <summary>
        ///     Creates a binary data list from XML data.
        /// </summary>
        /// <param name="xmlDataList">The XML data list.</param>
        /// <param name="errors">The errors.</param>
        /// <returns></returns>
        private IBinaryDataList CreateBinaryDataListFromXmlData(string xmlDataList, out ErrorResultTO errors)
        {
            IDataListCompiler compiler = DataListFactory.CreateDataListCompiler();
            IBinaryDataList result = null;
            var allErrors = new ErrorResultTO();
            Guid dlGuid = compiler.ConvertTo(
                DataListFormat.CreateFormat(GlobalConstants._Studio_XML), xmlDataList.ToStringBuilder(), xmlDataList.ToStringBuilder(), out errors);

            if(!errors.HasErrors())
            {
                result = compiler.FetchBinaryDataList(dlGuid, out errors);
                if(errors.HasErrors())
                {
                    allErrors.MergeErrors(errors);
                }
            }

            compiler.ForceDeleteDataListByID(dlGuid);
            return result;
        }
        // 28.01.2013 - Travis.Frisinger : Added for Case Edits
        internal void EditSwitchCaseExpression(Tuple<ModelProperty, IEnvironmentModel> payload)
        {
            IEnvironmentModel environment = payload.Item2;
            ModelProperty switchCaseValue = payload.Item1;

            string modelData = JsonConvert.SerializeObject(DataListConstants.DefaultCase);


            ErrorResultTO errors = new ErrorResultTO();
            IDataListCompiler compiler = DataListFactory.CreateDataListCompiler(environment.DataListChannel);
            Guid dataListID = GlobalConstants.NullDataListID;

            if (errors.HasErrors()) //BUG 8796, Added this if to handle errors
            {
                // Bad things happened... Tell the user
                PopupProvider.Show(errors.MakeDisplayReady(), GlobalConstants.SwitchWizardErrorHeading,
                                   MessageBoxButton.OK, MessageBoxImage.Error);
                // Stop configuring!!!
                return;
            }

            // Extract existing value ;)

            if (switchCaseValue != null)
            {
                string val = switchCaseValue.ComputedValue.ToString();
                modelData = JsonConvert.SerializeObject(new Dev2Switch() { SwitchVariable = val });
            }
            else
            {
                // Problems, push empty model ;)
                compiler.PushSystemModelToDataList(dataListID, DataListConstants.DefaultCase, out errors);
            }

            // now invoke the wizard ;)
            Uri requestUri;
            if (Uri.TryCreate((environment.WebServerAddress + GlobalConstants.SwitchDragWizardLocation),
                              UriKind.Absolute, out requestUri))
            {
                string uriString = Browser.FormatUrl(requestUri.AbsoluteUri, dataListID);

                //var callBackHandler = new Dev2DecisionCallbackHandler();
                //callBackHandler.Owner = new WebPropertyEditorWindow(callBackHandler, uriString) { Width = 580, Height = 270 };
                //callBackHandler.Owner.ShowDialog();
                _callBackHandler.ModelData = modelData;
                WebSites.ShowWebPageDialog(uriString, _callBackHandler, 470, 285);


                // Wizard finished...
                // Now Fetch from DL and push the model data into the workflow
                try
                {
                    var ds = compiler.FetchSystemModelFromDataList<Dev2Switch>(dataListID, out errors);

                    if (ds != null)
                    {
                        // ReSharper disable PossibleNullReferenceException
                        switchCaseValue.SetValue(ds.SwitchVariable);
                        // ReSharper restore PossibleNullReferenceException
                    }
                }
                catch
                {
                    // Bad things happened... Tell the user
                    PopupProvider.Buttons = MessageBoxButton.OK;
                    PopupProvider.Description = GlobalConstants.SwitchWizardErrorString;
                    PopupProvider.Header = GlobalConstants.SwitchWizardErrorHeading;
                    PopupProvider.ImageType = MessageBoxImage.Error;
                    PopupProvider.Show();
                }
            }
        }