private void WriteToModelItemDataProperty(string propertyName, string propertyValue)
        {
            string xmlConfig = _webActivity.XMLConfiguration;

            UnlimitedObject d = UnlimitedObject.GetStringXmlDataAsUnlimitedObject(xmlConfig);

            d.GetElement(propertyName).SetValue(propertyValue);

            _webActivity.XMLConfiguration = d.XmlString;
        }
        public override List <UnlimitedObject> GetSources(IEnvironmentModel environmentModel)
        {
            List <UnlimitedObject> list             = new List <UnlimitedObject>();
            UnlimitedObject        unlimitedObject1 = new UnlimitedObject(@"<Source ID=""6f6fda2f-4060-4c06-bfbb-7a38a1088604"" Version=""1.0"" Name=""MoEmailTest1"" ResourceType=""EmailSource"" ConnectionString=""Host=smtp.mail.yahoo.com;[email protected];Password=Q38qrDmsi36ei1R;Port=25;EnableSsl=False;Timeout=100000"" Type=""EmailSource"" ServerID=""51a58300-7e9d-4927-a57b-e5d700b11b55"">
  <DisplayName>MoEmailTest1</DisplayName>
  <Category>MoEmailTestSources</Category>
  <AuthorRoles></AuthorRoles>
  <TypeOf>EmailSource</TypeOf>
  <Signature xmlns=""http://www.w3.org/2000/09/xmldsig#"">
    <SignedInfo>
      <CanonicalizationMethod Algorithm=""http://www.w3.org/TR/2001/REC-xml-c14n-20010315"" />
      <SignatureMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#rsa-sha1"" />
      <Reference URI="""">
        <Transforms>
          <Transform Algorithm=""http://www.w3.org/2000/09/xmldsig#enveloped-signature"" />
        </Transforms>
        <DigestMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#sha1"" />
        <DigestValue>mnY5GQkRM6RQpvYYx6p40rmDrWw=</DigestValue>
      </Reference>
    </SignedInfo>
    <SignatureValue>pMuNyT8uHzb3C++wGl058QdOdRNSxKcTKm7MeqwtRkuiLM9we0EItMyzAEJ/8ZyxZCDUi3GoosCTsND8X+HJh1EmHj6AZJ59PIX+ypZK4d+IGlqSrS29oeVZ1tIKOxIrVxc1HaGfRRibh33mxW/OWFxl7JeQQnLVlQ17SGsTl2s=</SignatureValue>
  </Signature>
</Source>");
            UnlimitedObject        unlimitedObject2 = new UnlimitedObject(@"<Source ID=""8f803242-a0cf-45d1-8449-d4dab2662718"" Version=""1.0"" Name=""MoEmailTest2"" ResourceType=""EmailSource"" ConnectionString=""Host=smtp.mail.yahoo.com;[email protected];Password=Q38qrDmsi36ei1R;Port=25;EnableSsl=False;Timeout=100000"" Type=""EmailSource"" ServerID=""51a58300-7e9d-4927-a57b-e5d700b11b55"">
  <DisplayName>MoEmailTest2</DisplayName>
  <Category>MoEmailTestSources</Category>
  <AuthorRoles></AuthorRoles>
  <TypeOf>EmailSource</TypeOf>
  <Signature xmlns=""http://www.w3.org/2000/09/xmldsig#"">
    <SignedInfo>
      <CanonicalizationMethod Algorithm=""http://www.w3.org/TR/2001/REC-xml-c14n-20010315"" />
      <SignatureMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#rsa-sha1"" />
      <Reference URI="""">
        <Transforms>
          <Transform Algorithm=""http://www.w3.org/2000/09/xmldsig#enveloped-signature"" />
        </Transforms>
        <DigestMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#sha1"" />
        <DigestValue>epBzm31clckPtICoVs0f5PL36qs=</DigestValue>
      </Reference>
    </SignedInfo>
    <SignatureValue>Vn6taCw3fFFL/NyuERfgHw0X9+JgeRAkmVWbtDmrhB6LsLB07o/rQXtf/FUJrKa9jDiiyS6G6WVhVYJ/zo3cBXZq6sBzOdYxPQHVtjf322p22rvCRaY3zw2hhZArvyc26YxpX8vjdIYmxPCJ6tbn5Hpg4ftB+ciHTo+MYS7zHN0=</SignatureValue>
  </Signature>
</Source>");

            list.Add(unlimitedObject1);
            list.Add(unlimitedObject2);
            return(list);
        }
        public override List<UnlimitedObject> GetSources(IEnvironmentModel environmentModel)
        {
            List<UnlimitedObject> list = new List<UnlimitedObject>();
            UnlimitedObject unlimitedObject1 = new UnlimitedObject(@"<Source ID=""6f6fda2f-4060-4c06-bfbb-7a38a1088604"" Version=""1.0"" Name=""MoEmailTest1"" ResourceType=""EmailSource"" ConnectionString=""Host=smtp.mail.yahoo.com;[email protected];Password=Q38qrDmsi36ei1R;Port=25;EnableSsl=False;Timeout=100000"" Type=""EmailSource"" ServerID=""51a58300-7e9d-4927-a57b-e5d700b11b55"">
  <DisplayName>MoEmailTest1</DisplayName>
  <Category>MoEmailTestSources</Category>
  <AuthorRoles></AuthorRoles>
  <TypeOf>EmailSource</TypeOf>
  <Signature xmlns=""http://www.w3.org/2000/09/xmldsig#"">
    <SignedInfo>
      <CanonicalizationMethod Algorithm=""http://www.w3.org/TR/2001/REC-xml-c14n-20010315"" />
      <SignatureMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#rsa-sha1"" />
      <Reference URI="""">
        <Transforms>
          <Transform Algorithm=""http://www.w3.org/2000/09/xmldsig#enveloped-signature"" />
        </Transforms>
        <DigestMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#sha1"" />
        <DigestValue>mnY5GQkRM6RQpvYYx6p40rmDrWw=</DigestValue>
      </Reference>
    </SignedInfo>
    <SignatureValue>pMuNyT8uHzb3C++wGl058QdOdRNSxKcTKm7MeqwtRkuiLM9we0EItMyzAEJ/8ZyxZCDUi3GoosCTsND8X+HJh1EmHj6AZJ59PIX+ypZK4d+IGlqSrS29oeVZ1tIKOxIrVxc1HaGfRRibh33mxW/OWFxl7JeQQnLVlQ17SGsTl2s=</SignatureValue>
  </Signature>
</Source>");
            UnlimitedObject unlimitedObject2 = new UnlimitedObject(@"<Source ID=""8f803242-a0cf-45d1-8449-d4dab2662718"" Version=""1.0"" Name=""MoEmailTest2"" ResourceType=""EmailSource"" ConnectionString=""Host=smtp.mail.yahoo.com;[email protected];Password=Q38qrDmsi36ei1R;Port=25;EnableSsl=False;Timeout=100000"" Type=""EmailSource"" ServerID=""51a58300-7e9d-4927-a57b-e5d700b11b55"">
  <DisplayName>MoEmailTest2</DisplayName>
  <Category>MoEmailTestSources</Category>
  <AuthorRoles></AuthorRoles>
  <TypeOf>EmailSource</TypeOf>
  <Signature xmlns=""http://www.w3.org/2000/09/xmldsig#"">
    <SignedInfo>
      <CanonicalizationMethod Algorithm=""http://www.w3.org/TR/2001/REC-xml-c14n-20010315"" />
      <SignatureMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#rsa-sha1"" />
      <Reference URI="""">
        <Transforms>
          <Transform Algorithm=""http://www.w3.org/2000/09/xmldsig#enveloped-signature"" />
        </Transforms>
        <DigestMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#sha1"" />
        <DigestValue>epBzm31clckPtICoVs0f5PL36qs=</DigestValue>
      </Reference>
    </SignedInfo>
    <SignatureValue>Vn6taCw3fFFL/NyuERfgHw0X9+JgeRAkmVWbtDmrhB6LsLB07o/rQXtf/FUJrKa9jDiiyS6G6WVhVYJ/zo3cBXZq6sBzOdYxPQHVtjf322p22rvCRaY3zw2hhZArvyc26YxpX8vjdIYmxPCJ6tbn5Hpg4ftB+ciHTo+MYS7zHN0=</SignatureValue>
  </Signature>
</Source>");
            list.Add(unlimitedObject1);
            list.Add(unlimitedObject2);
            return list;
        }
        private void SetConfigFragment(string webPartElementName, dynamic xmlConfiguration)
        {
            string          configuration = WebActivity.XMLConfiguration;
            UnlimitedObject configData    = UnlimitedObject.GetStringXmlDataAsUnlimitedObject(configuration);

            if (configData.ElementExists(webPartElementName.ToLower()))
            {
                configData.RemoveElementsByTagName(webPartElementName.ToLower());
            }

            configData.CreateElement(webPartElementName.ToLower()).Add(xmlConfiguration);

            //Write xml configuration to the layout cell
            dynamic layoutXml = new UnlimitedObject(webPartElementName.ToLower());

            layoutXml.Add(xmlConfiguration);
            SelectedLayoutObject.XmlConfiguration = layoutXml.XmlString;


            _webActivity.XMLConfiguration = configData.XmlString;
            Deploy();
        }
        public void Deploy()
        {
            if (_webActivity != null && _webActivity.ResourceModel != null && _webActivity.ResourceModel.Environment != null)
            {
                //Flush the workflow designer so changes are written back into the Resource Model
                //so that we can save the workflow at its latest state
                Mediator.SendMessage(MediatorMessages.BindViewToViewModel, _resource);
                Mediator.SendMessage(MediatorMessages.SaveResourceModel, _resource);

                //Create the necessary folder structure on the web server if it does not already exist.
                dynamic package = new UnlimitedObject();
                package.Service         = StringResources.Website_BootStrap_Service;
                package.Dev2WebsiteName = _resource.ResourceName;
                var workspaceID = ((IStudioClientContext)_webActivity.ResourceModel.Environment.DsfChannel).AccountID;

                var result = _webActivity.ResourceModel.Environment.DsfChannel.ExecuteCommand(package.XmlString, workspaceID, GlobalConstants.NullDataListID);
                if (result == null)
                {
                    throw new Exception(string.Format(GlobalConstants.NetworkCommunicationErrorTextFormat, StringResources.Website_BootStrap_Service));
                }
            }
        }
        private void SetConfigFragment(string webPartElementName, dynamic xmlConfiguration)
        {
            string configuration = WebActivity.XMLConfiguration;
            UnlimitedObject configData = UnlimitedObject.GetStringXmlDataAsUnlimitedObject(configuration);

            if(configData.ElementExists(webPartElementName.ToLower()))
            {
                configData.RemoveElementsByTagName(webPartElementName.ToLower());
            }

            configData.CreateElement(webPartElementName.ToLower()).Add(xmlConfiguration);

            //Write xml configuration to the layout cell
            dynamic layoutXml = new UnlimitedObject(webPartElementName.ToLower());
            layoutXml.Add(xmlConfiguration);
            SelectedLayoutObject.XmlConfiguration = layoutXml.XmlString;

            _webActivity.XMLConfiguration = configData.XmlString;
            Deploy();
        }
        public void Deploy()
        {
            if(_webActivity != null && _webActivity.ResourceModel != null && _webActivity.ResourceModel.Environment != null)
            {
                //Flush the workflow designer so changes are written back into the Resource Model
                //so that we can save the workflow at its latest state
                Mediator.SendMessage(MediatorMessages.BindViewToViewModel, _resource);
                Mediator.SendMessage(MediatorMessages.SaveResourceModel, _resource);

                //Create the necessary folder structure on the web server if it does not already exist.
                dynamic package = new UnlimitedObject();
                package.Service = StringResources.Website_BootStrap_Service;
                package.Dev2WebsiteName = _resource.ResourceName;
                var workspaceID = ((IStudioClientContext)_webActivity.ResourceModel.Environment.DsfChannel).AccountID;

                var result = _webActivity.ResourceModel.Environment.DsfChannel.ExecuteCommand(package.XmlString, workspaceID, GlobalConstants.NullDataListID);
                if (result == null)
                {
                    throw new Exception(string.Format(GlobalConstants.NetworkCommunicationErrorTextFormat, StringResources.Website_BootStrap_Service));
                }

            }
        }
        //public dynamic WorkflowApplication(ServiceAction action, dynamic xmlRequest, string dataList)
        public dynamic WorkflowApplication(ServiceAction action, IDSFDataObject dataObj, string dataList)
        {
            //var dataObject = new DsfDataObject(xmlRequest.XmlString);
            ErrorResultTO errors;
            Guid instanceId = Guid.Empty;
            Guid parentWorkflowInstanceId;
            Guid parentInstanceId = Guid.Empty;
            string bookmark = string.Empty;

            // PBI : 5376 Refactored 
            IBinaryDataListEntry tmp = SvrCompiler.Evaluate(null, dataObj.DataListID,
                                                             DataList.Contract.enActionType.System,
                                                             enSystemTag.Bookmark.ToString(), out errors);
            if(tmp != null)
            {
                bookmark = tmp.FetchScalar().TheValue;
            }

            tmp = SvrCompiler.Evaluate(null, dataObj.DataListID, DataList.Contract.enActionType.System,
                                        enSystemTag.InstanceId.ToString(), out errors);
            if(tmp != null)
            {
                Guid.TryParse(tmp.FetchScalar().TheValue, out instanceId);
            }

            tmp = SvrCompiler.Evaluate(null, dataObj.DataListID, DataList.Contract.enActionType.System,
                                        enSystemTag.ParentWorkflowInstanceId.ToString(), out errors);
            if(tmp != null)
            {
                Guid.TryParse(tmp.FetchScalar().TheValue, out parentWorkflowInstanceId);
            }

            //tmp = SvrCompiler.Evaluate(null, dataObj.DataListID, DataList.Contract.enActionType.System,
            //                            enSystemTag.ParentInstanceID.ToString(), out errors);
            //if (tmp != null)
            //{
            //    Guid.TryParse(tmp.FetchScalar().TheValue, out parentInstanceId);
            //}

            //bool isDebug = false;

            //if (xmlRequest.BDSDebugMode is string)
            //{
            //    bool.TryParse(xmlRequest.BDSDebugMode, out isDebug);
            //}

            // End PBI Mods

            dataObj.ServiceName = action.ServiceName;

            // Travis : Now set Data List
            dataObj.DataList = dataList;

            Exception wfException = null;
            IDSFDataObject data = null;
            PooledServiceActivity activity = action.PopActivity();

            try
            {

                data = _wf.InvokeWorkflow(activity.Value, dataObj, new List<object> { _dsfChannel }, instanceId, _workspace, bookmark, dataObj.IsDebug);
            }
            catch(Exception ex)
            {
                wfException = ex;
            }
            finally
            {
                action.PushActivity(activity);
            }

            if(data != null)
            {
                return data.DataListID;

                //return UnlimitedObject.GetStringXmlDataAsUnlimitedObject(data.XmlData);
            }
            // ReSharper disable RedundantIfElseBlock
            else
            // ReSharper restore RedundantIfElseBlock
            {
                dynamic returnError = new UnlimitedObject("Error");
                if(wfException != null)
                {
                    returnError.ErrorDetail = new UnlimitedObject(wfException);
                }

                return GlobalConstants.NullDataListID;
            }
        }
        // Travis : Fixed all of Zuko's crap service defs
        private string GetAllDefsAsXML(string source, dynamic serviceData)
        {
            var doc = new XmlDocument();
            doc.LoadXml(source);
            XmlNodeList list = doc.ChildNodes;
            XmlNode root = list[0];
            XmlNodeList workerServices = root.ChildNodes;
            foreach(XmlNode node in workerServices)
            {
                dynamic serviceInfo = new UnlimitedObject("Dev2Resource");
                if(node.Name.Equals("Service"))
                {
                    if (node.Attributes != null)
                    {
                        serviceInfo.Dev2WorkerService = node.Attributes["Name"].Value;
                    }
                    XmlNode tmpNode =
                        // ReSharper disable ReplaceWithSingleCallToFirstOrDefault
                        node.ChildNodes.OfType<XmlNode>().Where(x => x.Name == "Category").FirstOrDefault();
                        // ReSharper restore ReplaceWithSingleCallToFirstOrDefault
                    if(tmpNode != null)
                    {
                        serviceInfo.Dev2WorkerServiceCategory = tmpNode.InnerText;
                    }
                    serviceInfo.Dev2WorkerServiceContents = node.OuterXml;
                    serviceData.AddResponse(serviceInfo);
                }
                else if(node.Name.Equals("Source"))
                {
                    if (node.Attributes != null)
                    {
                        serviceInfo.Dev2WorkerService = node.Attributes["Name"].Value;
                    }

                    XmlNode tmpNode =
                        node.ChildNodes.OfType<XmlNode>().Where(x => x.Name == "Category").FirstOrDefault();
                    if(tmpNode != null)
                    {
                        serviceInfo.Dev2WorkerServiceCategory = tmpNode.InnerText;
                    }
                    serviceInfo.Dev2SourceContents = node.OuterXml;
                    serviceData.AddResponse(serviceInfo);
                }
            }
            return serviceData.XmlString;
        }
        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;
        }
 // Find MachineName
 public string FindMachineName()
 {
     dynamic returnData = new UnlimitedObject();
     returnData.Dev2MachineName = Environment.MachineName;
     return returnData.XmlString;
 }
        private string GetResourceNameAsXml(string source, dynamic serviceData)
        {
            XElement elements = XElement.Parse(source);
            elements.Descendants()
                    .Where(node => node.Descendants().All(c => c.Name.LocalName == "XamlDefinition"))
                    .Remove();
            elements.DescendantsAndSelf().Where(node => node.Name.LocalName == "DataList").Remove();
            elements.DescendantsAndSelf().Where(node => node.Name.LocalName == "Plugin").Remove();

            if(elements.HasElements)
            {
                //foreach(XElement element in elements.Elements())
                //{
                //    //dynamic orphan = GetResourceNameAsXml(element.ToString(), serviceData);
                //    //serviceData.Dev2Service = orphan;
                //}
            }
            while(elements.HasAttributes)
            {
                XAttribute attrib = elements.LastAttribute;
                dynamic serviceInfo = new UnlimitedObject("Dev2Resource");
                if(attrib.Name == "Name")
                {
                    serviceInfo.Dev2ResourceName = attrib.Value;
                    serviceData.AddResponse(serviceInfo);
                }
                attrib.Remove();
            }
            return serviceData.XmlString;
        }
        public string FindResources(string resourceName, string type, string roles)
        {
            dynamic returnData = new UnlimitedObject();

            if(resourceName == "*")
                resourceName = string.Empty;

            switch(type)
            {
                case "WorkflowService":
                    {
                        IEnumerable<DynamicService> services;
                        Host.LockServices();

                        try
                        {
                            services = Host.Services.Where(c => c.Name.Contains(resourceName));
                        }
                        finally
                        {
                            Host.UnlockServices();
                        }

                        IEnumerable<DynamicService> workflowServices =
                            services.Where(c => c.Actions.Where(d => d.ActionType == enActionType.Workflow).Count() > 0);
                                    //.Where(
                                        //c =>
                                        //c.IsUserInRole(roles, c.AuthorRoles) || roles.Contains("Domain Admins") ||
                                        //roles == "*");
                        workflowServices.ToList()
                                        .ForEach(
                                            c =>
                                            returnData.AddResponse(
                                                UnlimitedObject.GetStringXmlDataAsUnlimitedObject(
                                                    c.ResourceDefinition ?? "<NoDef/>")));
                        break;
                    }
                case "Service":
                    {
                        IEnumerable<DynamicService> svc;
                        Host.LockServices();

                        try
                        {
                            svc = Host.Services.Where(c => c.Name.Contains(resourceName));
                        }
                        finally
                        {
                            Host.UnlockServices();
                        }

                        IEnumerable<DynamicService> svcs =
                            svc.Where(c => c.Actions.Where(d => d.ActionType != enActionType.Workflow).Count() > 0);
                               //.Where(
                                   //c =>
                                   //c.IsUserInRole(roles, c.AuthorRoles) || roles.Contains("Domain Admins") ||
                                   //roles == "*");
                        svcs.ToList()
                            .ForEach(
                                c =>
                                returnData.AddResponse(
                                    UnlimitedObject.GetStringXmlDataAsUnlimitedObject(c.ResourceDefinition ?? "<NoDef/>")));
                        break;
                    }

                case "Source":
                    {
                        IEnumerable<Source> sources;
                        Host.LockSources();

                        try
                        {
                            sources =
                                Host.Sources.Where(c => c.Name.Contains(resourceName));
                                    //.Where(
                                        //c =>
                                        //c.IsUserInRole(roles, c.AuthorRoles) || roles.Contains("Domain Admins") ||
                                        //roles == "*");
                        }
                        finally
                        {
                            Host.UnlockSources();
                        }

                        sources.ToList()
                               .ForEach(
                                   c =>
                                   returnData.AddResponse(
                                       UnlimitedObject.GetStringXmlDataAsUnlimitedObject(c.ResourceDefinition ??
                                                                                         "<NoDef/>")));
                        break;
                    }
                case "Activity":
                    {
                        IEnumerable<WorkflowActivityDef> activitydefs;
                        Host.LockActivities();

                        try
                        {
                            activitydefs =
                                Host.WorkflowActivityDefs.Where(c => c.Name.Contains(resourceName));
                                    //.Where(
                                        //c =>
                                        //c.IsUserInRole(roles, c.AuthorRoles) || roles.Contains("Domain Admins") ||
                                        //roles == "*");
                        }
                        finally
                        {
                            Host.UnlockActivities();
                        }


                        activitydefs.ToList()
                                    .ForEach(
                                        c =>
                                        returnData.AddResponse(
                                            UnlimitedObject.GetStringXmlDataAsUnlimitedObject(c.ResourceDefinition ??
                                                                                              "<NoDef/>")));
                        break;
                    }
                case "*":
                    {
                        IEnumerable<Source> resources;
                        Host.LockSources();

                        try
                        {
                            resources =
                                Host.Sources.Where(c => c.Name.Contains(resourceName));
                                    //.Where(
                                        //c =>
                                        //c.IsUserInRole(roles, c.AuthorRoles) || roles.Contains("Domain Admins") ||
                                        //roles == "*");
                        }
                        finally
                        {
                            Host.UnlockSources();
                        }

                        resources.ToList()
                                 .ForEach(
                                     c =>
                                     returnData.AddResponse(
                                         UnlimitedObject.GetStringXmlDataAsUnlimitedObject(c.ResourceDefinition ??
                                                                                           "<NoDef/>")));
                        IEnumerable<DynamicService> wfservices;
                        Host.LockServices();

                        try
                        {
                            wfservices = Host.Services.Where(c => c.Name.Contains(resourceName));
                        }
                        finally
                        {
                            Host.UnlockServices();
                        }

                        IEnumerable<DynamicService> workflows =
                            wfservices.Where(
                                c => c.Actions.Where(d => d.ActionType == enActionType.Workflow).Count() > 0);
                                      //.Where(
                                          //c =>
                                          //c.IsUserInRole(roles, c.AuthorRoles) || roles.Contains("Domain Admins") ||
                                          //roles == "*");
                        workflows.ToList()
                                 .ForEach(
                                     c =>
                                     returnData.AddResponse(
                                         UnlimitedObject.GetStringXmlDataAsUnlimitedObject(c.ResourceDefinition ??
                                                                                           "<NoDef/>")));

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

                        try
                        {
                            svc2 = Host.Services.Where(c => c.Name.Contains(resourceName));
                        }
                        finally
                        {
                            Host.UnlockServices();
                        }

                        IEnumerable<DynamicService> svcs2 =
                            svc2.Where(c => c.Actions.Where(d => d.ActionType != enActionType.Workflow).Count() > 0);
                                //.Where(
                                    //c =>
                                    //c.IsUserInRole(roles, c.AuthorRoles) || roles.Contains("Domain Admins") ||
                                    //roles == "*");
                        svcs2.ToList()
                             .ForEach(
                                 c =>
                                 returnData.AddResponse(
                                     UnlimitedObject.GetStringXmlDataAsUnlimitedObject(c.ResourceDefinition ??
                                                                                       "<NoDef/>")));

                        /* 
                         * Travis : 02-07-2012
                         * why the flip have a specific condition above only to blindly add all services bar the role and other meta data??????!!!!!!!
                         * 
                         */
                        //var intsvc = Host.Services.Where(c => c.Name.Contains(resourceName));
                        //intsvc.ToList().ForEach(c => returnData.AddResponse(UnlimitedObject.GetStringXmlDataAsUnlimitedObject(c.ResourceDefinition ?? "<NoDef/>")));

                        IEnumerable<WorkflowActivityDef> activityinfo;
                        Host.LockActivities();

                        try
                        {
                            activityinfo =
                                Host.WorkflowActivityDefs.Where(c => c.Name.Contains(resourceName));
                                    //.Where(
                                        //c =>
                                        //c.IsUserInRole(roles, c.AuthorRoles) || roles.Contains("Domain Admins") ||
                                        //roles == "*");
                        }
                        finally
                        {
                            Host.UnlockActivities();
                        }

                        activityinfo.ToList()
                                    .ForEach(
                                        c =>
                                        returnData.AddResponse(
                                            UnlimitedObject.GetStringXmlDataAsUnlimitedObject(c.ResourceDefinition ??
                                                                                              "<NoDef/>")));
                        break;
                    }
            }
            
            dynamic serviceData = new UnlimitedObject("Dev2Resources");
            string returnVal;
            //[email protected]
            //18/06/2010
            //we need to be able to return the worker service name and the category it belongs to
            if(type.Equals("Service"))
            {
                returnVal = GetWorkerServiceResourceAsXml(returnData.XmlString, serviceData);
            }
            else if(type.Equals("Source"))
            {
                returnVal = GetSourceResourceAsXml(returnData.XmlString, serviceData);
            }
            else
            {
                returnVal = GetAllDefsAsXML(returnData.XmlString, serviceData);
                //returnVal = GetSourceResourceAsXml(returnData.XmlString, serviceData);
            }

            return returnVal;
        }
        public string FindResource(string resourceName, string type, string roles)
        {
            dynamic returnData = new UnlimitedObject();

            if(resourceName == "*")
                resourceName = string.Empty;

            switch(type)
            {
                case "WorkflowService":
                    {
                        IEnumerable<DynamicService> services;
                        Host.LockServices();

                        try
                        {
                            services = Host.Services.Where(c => c.Name.Contains(resourceName));
                        }
                        finally
                        {
                            Host.UnlockServices();
                        }

                        IEnumerable<DynamicService> workflowServices =
                            services.Where(c => c.Actions.Where(d => d.ActionType == enActionType.Workflow).Count() > 0);
                                    //.Where(c => c.IsUserInRole(roles, c.AuthorRoles) || roles.Contains("Domain Admins"));
                        workflowServices.ToList()
                                        .ForEach(
                                            c =>
                                            returnData.AddResponse(
                                                UnlimitedObject.GetStringXmlDataAsUnlimitedObject(
                                                    c.ResourceDefinition ?? "<NoDef/>")));
                        break;
                    }
                case "Service":
                    {
                        IEnumerable<DynamicService> svc;
                        Host.LockServices();

                        try
                        {
                            svc = Host.Services.Where(c => c.Name.Contains(resourceName));
                        }
                        finally
                        {
                            Host.UnlockServices();
                        }

                        IEnumerable<DynamicService> svcs =
                            svc.Where(c => c.Actions.Where(d => d.ActionType != enActionType.Workflow).Count() > 0);
                               //.Where(c => c.IsUserInRole(roles, c.AuthorRoles) || roles.Contains("Domain Admins"));
                        svcs.ToList()
                            .ForEach(
                                c =>
                                returnData.AddResponse(
                                    UnlimitedObject.GetStringXmlDataAsUnlimitedObject(c.ResourceDefinition ?? "<NoDef/>")));
                        break;
                    }

                case "Source":
                    {
                        IEnumerable<Source> sources;
                        Host.LockSources();

                        try
                        {
                            sources =
                                Host.Sources.Where(c => c.Name.Contains(resourceName));
                                    //.Where(c => c.IsUserInRole(roles, c.AuthorRoles) || roles.Contains("Domain Admins"));
                        }
                        finally
                        {
                            Host.UnlockSources();
                        }


                        sources.ToList()
                               .ForEach(
                                   c =>
                                   returnData.AddResponse(
                                       UnlimitedObject.GetStringXmlDataAsUnlimitedObject(c.ResourceDefinition ??
                                                                                         "<NoDef/>")));
                        break;
                    }
                case "Activity":
                    {
                        IEnumerable<WorkflowActivityDef> activitydefs;
                        Host.LockActivities();

                        try
                        {
                            activitydefs =
                                Host.WorkflowActivityDefs.Where(c => c.Name.Contains(resourceName));
                                    //.Where(c => c.IsUserInRole(roles, c.AuthorRoles) || roles.Contains("Domain Admins"));
                        }
                        finally
                        {
                            Host.UnlockActivities();
                        }

                        activitydefs.ToList()
                                    .ForEach(
                                        c =>
                                        returnData.AddResponse(
                                            UnlimitedObject.GetStringXmlDataAsUnlimitedObject(c.ResourceDefinition ??
                                                                                              "<NoDef/>")));
                        break;
                    }
                case "ReservedService":
                    {
                        IEnumerable<DynamicService> reserved;
                        Host.LockReservedServices();

                        try
                        {
                            reserved = Host.ReservedServices.Where(c => c.Name.Contains(resourceName));
                        }
                        finally
                        {
                            Host.UnlockReservedServices();
                        }

                        reserved.ToList()
                                .ForEach(
                                    c =>
                                    returnData.AddResponse(
                                        UnlimitedObject.GetStringXmlDataAsUnlimitedObject("<ReservedName>" + c.Name +
                                                                                          "</ReservedName>")));
                        break;
                    }
            }
           
            return returnData.XmlString;
        }
        // Travis.Frisinger : 09.08.2012 - List service data in a manor we can bind from it ;)
        public string FindResourceForBinding(string resourceName, string type, string roles)
        {
            dynamic returnData = new UnlimitedObject();

            if(resourceName == "*")
            {
                resourceName = string.Empty;
            }

            switch(type)
            {
                case "WorkflowService":
                    {
                        IEnumerable<DynamicService> services;
                        Host.LockServices();

                        try
                        {
                            services = Host.Services.Where(c => c.Name.Contains(resourceName));
                        }
                        finally
                        {
                            Host.UnlockServices();
                        }

                        IEnumerable<DynamicService> workflowServices =
                            services.Where(c => c.Actions.Where(d => d.ActionType == enActionType.Workflow).Count() > 0);
                                    //.Where(c => c.IsUserInRole(roles, c.AuthorRoles) || roles.Contains("Domain Admins"));

                        workflowServices.ToList()
                                        .ForEach(
                                            c =>
                                            returnData.AddResponse(
                                                UnlimitedObject.GetStringXmlDataAsUnlimitedObject(
                                                    c.ResourceDefinition ?? "<NoDef/>")));
                        break;
                    }
                case "Service":
                    {
                        IEnumerable<DynamicService> svc;
                        Host.LockServices();

                        try
                        {
                            svc = Host.Services.Where(c => c.Name.Contains(resourceName));
                        }
                        finally
                        {
                            Host.UnlockServices();
                        }


                        IEnumerable<DynamicService> svcs =
                            // ReSharper disable UseMethodAny.0
                            // ReSharper disable ReplaceWithSingleCallToCount
                        svc.Where(c => c.Actions.Where(d => d.ActionType != enActionType.Workflow).Count() > 0);
                        // ReSharper restore ReplaceWithSingleCallToCount
                        // ReSharper restore UseMethodAny.0
                               //.Where(c => c.IsUserInRole(roles, c.AuthorRoles) || roles.Contains("Domain Admins"));
                        svcs.ToList()
                            .ForEach(
                                c =>
                                returnData.AddResponse(
                                    UnlimitedObject.GetStringXmlDataAsUnlimitedObject(c.ResourceDefinition ?? "<NoDef/>")));
                        break;
                    }

                //case "Source":

                //    var sources = Host.Sources.Where(c => c.Name.Contains(resourceName)).Where(c => c.IsUserInRole(roles, c.AuthorRoles) || roles.Contains("Domain Admins"));
                //    sources.ToList().ForEach(c => returnData.AddResponse(UnlimitedObject.GetStringXmlDataAsUnlimitedObject(c.ResourceDefinition ?? "<NoDef/>")));
                //break;

                //case "Activity":
                //    var activitydefs = Host.WorkflowActivityDefs.Where(c => c.Name.Contains(resourceName)).Where(c => c.IsUserInRole(roles, c.AuthorRoles) || roles.Contains("Domain Admins"));
                //    activitydefs.ToList().ForEach(c => returnData.AddResponse(UnlimitedObject.GetStringXmlDataAsUnlimitedObject(c.ResourceDefinition ?? "<NoDef/>")));
                //break;
            }
            

            // now extract the attributed junk for the server to properly use
            var attributes = new[] { "Name" };
            var childTags = new[] { "Category" };
            string returnValue = DataListUtil.ExtractAttributeFromTagAndMakeRecordset(returnData.XmlString, "Service",
                                                                                      attributes, childTags);
            returnValue = returnValue.Replace("<Service>", "<Dev2Service>").Replace("</Service>", "</Dev2Service>");

            return returnValue;
        }
        /// <summary>
        ///     This is a management method and allows administrative
        ///     users to reload services.
        ///     This will be called when service definitions have
        ///     been ammended and need to become live
        /// </summary>
        /// <returns>string containing the response(s) to the request</returns>
        public string ReloadServices()
        {
            dynamic xmlResponse = new UnlimitedObject(Resources.DynamicService_ServiceResponseTag);

            try
            {
                Host.RestoreResources(new[] { "Sources", "Services", "ActivityDefs" });
                xmlResponse.Response = "All Services Reloaded...";
            }
            catch(Exception ex)
            {
                xmlResponse.Error = "Error reloading services...";
                xmlResponse.ErrorDetail = ex.Message;
                xmlResponse.ErrorStackTrace = ex.StackTrace;
            }

            return xmlResponse.XmlString;
        }
        public string DeleteResource(string resourceName, string type, string roles)
        {
            dynamic returnData = new UnlimitedObject();

            if(resourceName == "*")
            {
                returnData.Error = "Delete resources does not accept wildcards.";
            }
            else
            {
                switch(type)
                {
                    case "WorkflowService":
                        {
                            IEnumerable<DynamicService> services;

                            Host.LockServices();

                            try
                            {
                                services = Host.Services
                                    .Where(c => c.Name.Equals(resourceName, StringComparison.CurrentCultureIgnoreCase));
                            }
                            finally
                            {
                                Host.UnlockServices();
                            }

                            //IEnumerable<DynamicService> workflowServices =
                            //    services.Where(
                            //        c => c.Actions.Where(d => d.ActionType == enActionType.Workflow).Count() > 0)
                            //            .Where(
                            //                c => c.IsUserInRole(roles, c.AuthorRoles) || roles.Contains("Domain Admins"));

                            IEnumerable<DynamicService> workflowServices =
                                services.Where(
                                    c => c.Actions.Where(d => d.ActionType == enActionType.Workflow).Any());
                            List<DynamicService> match = workflowServices.ToList();

                            if(match.Count != 1)
                            {
                                if(match.Count == 0)
                                {
                                    returnData.Error = "WorkflowService \"" + resourceName + "\" was not found.";
                                }
                                else
                                {
                                    returnData.Error = "Multiple matches found for WorkflowService \"" + resourceName +
                                                       "\".";
                                }
                            }
                            else
                            {
                                // ReSharper disable RedundantArgumentDefaultValue
                                returnData = Host.RemoveDynamicService(match[0], roles, true);
                                // ReSharper restore RedundantArgumentDefaultValue
                            }

                            //workflowServices.ToList().ForEach(c => returnData.AddResponse(UnlimitedObject.GetStringXmlDataAsUnlimitedObject(c.ResourceDefinition ?? "<NoDef/>")));
                            break;
                        }

                    case "Service":
                        {
                            IEnumerable<DynamicService> svc;

                            Host.LockServices();

                            try
                            {
                                svc = Host.Services.Where(c => c.Name.Contains(resourceName));
                            }
                            finally
                            {
                                Host.UnlockServices();
                            }

                            IEnumerable<DynamicService> svcs =
                                // ReSharper disable UseMethodAny.0
                                // ReSharper disable ReplaceWithSingleCallToCount
                                svc.Where(c => c.Actions.Where(d => d.ActionType != enActionType.Workflow).Count() > 0);
                                // ReSharper restore ReplaceWithSingleCallToCount
                                // ReSharper restore UseMethodAny.0
                                   //.Where(c => c.IsUserInRole(roles, c.AuthorRoles) || roles.Contains("Domain Admins"));
                            List<DynamicService> match = svcs.ToList();

                            if(match.Count != 1)
                            {
                                if(match.Count == 0)
                                {
                                    returnData.Error = "Service \"" + resourceName + "\" was not found.";
                                }
                                else
                                {
                                    returnData.Error = "Multiple matches found for Service \"" + resourceName + "\".";
                                }
                            }
                            else
                            {
                                // ReSharper disable RedundantArgumentDefaultValue
                                returnData = Host.RemoveDynamicService(match[0], roles, true);
                                // ReSharper restore RedundantArgumentDefaultValue
                            }


                            //svcs.ToList().ForEach(c => returnData.AddResponse(UnlimitedObject.GetStringXmlDataAsUnlimitedObject(c.ResourceDefinition ?? "<NoDef/>")));
                            break;
                        }

                    case "Source":
                        {
                            IEnumerable<Source> sources;
                            Host.LockSources();

                            try
                            {
                                //Juries - Bug cant delete resources when more than one contains the name
                                //Shoot me if everything uses a fuzzy lookup.
                                sources =
                                    Host.Sources.Where(c => c.Name.Equals(resourceName, StringComparison.CurrentCultureIgnoreCase));
                                        //.Where(
                                            //c => c.IsUserInRole(roles, c.AuthorRoles) || roles.Contains("Domain Admins"));
                            }
                            finally
                            {
                                Host.UnlockSources();
                            }

                            List<Source> match = sources.ToList();

                            if(match.Count != 1)
                            {
                                if(match.Count == 0)
                                {
                                    returnData.Error = "Source \"" + resourceName + "\" was not found.";
                                }
                                else
                                {
                                    returnData.Error = "Multiple matches found for Source \"" + resourceName + "\".";
                                }
                            }
                            else
                            {
                                // ReSharper disable RedundantArgumentDefaultValue
                                returnData = Host.RemoveSource(match[0], roles, true);
                                // ReSharper restore RedundantArgumentDefaultValue
                            }

                            //sources.ToList().ForEach(c => returnData.AddResponse(UnlimitedObject.GetStringXmlDataAsUnlimitedObject(c.ResourceDefinition ?? "<NoDef/>")));
                            break;
                        }
                }
                
            }

            return returnData.XmlString;
        }
        public void UpdateModelItem()
        {
            if (!string.IsNullOrEmpty(Html) && _webActivity != null && _webActivity.ResourceModel != null && _webActivity.ResourceModel.Environment != null)
            {
                int rows = 0;

                UnlimitedObject tags = new UnlimitedObject();

                try
                {
                    tags = UnlimitedObject.GetStringXmlDataAsUnlimitedObject(Html.ToLower());
                }
                catch { IsValidMarkup = false; return; }

                if (tags.HasError)
                {
                    IsValidMarkup = false;
                    return;
                }
                else
                {
                    IsValidMarkup = true;
                }

                var tagItems = tags.GetAllElements("dev2html");

                bool copyToPrevious = false;

                if (lastGood == null)
                {
                    copyToPrevious = true;
                }
                else
                {
                    previous = new ILayoutObjectViewModel[lastGood.Length];
                    lastGood.CopyTo(previous, 0);
                }

                _layoutObjects.Clear();

                foreach (dynamic tag in tagItems)
                {
                    IResourceModel res = null;

                    string name     = null;
                    string type     = null;
                    string iconpath = null;

                    if (tag.name is string)
                    {
                        name = tag.name;
                    }

                    if (tag.type is string)
                    {
                        type = tag.type;
                        res  = _webActivity.ResourceModel.Environment.Resources.All().FirstOrDefault(c => c.ResourceName.Equals(type, StringComparison.InvariantCultureIgnoreCase));
                        if (res != null)
                        {
                            iconpath = res.IconPath;
                        }
                    }

                    var exclusions = new List <string>()
                    {
                        "form", "meta", "pagetitle"
                    };
                    if (!exclusions.Contains(type.ToLower()))
                    {
                        if (string.IsNullOrEmpty(name))
                        {
                            IsValidMarkup = false;
                            return;
                        }

                        if (string.IsNullOrEmpty(type))
                        {
                            IsValidMarkup = false;
                            return;
                        }

                        if (string.IsNullOrEmpty(StringResources.Website_Supported_Webparts))
                        {
                            throw new Exception(StringResources.Error_Supported_Webparts_Not_Set);
                        }

                        List <string> inclusions = StringResources.Website_Supported_Webparts.Split(new char[] { ',' }).ToList();
                        if (!inclusions.Contains(type.ToLower()))
                        {
                            IsValidMarkup = false;
                            return;
                        }

                        var newobject = LayoutObjectViewModelFactory.CreateLayoutObject(type, name, iconpath, GetConfigFragment(name));

                        //Check if another webpart with the same name - not type - exists
                        //If so then we want to mark the website html as invalid
                        //as we don't allow multiple parts with the same name
                        var match = _layoutObjects.Any(c => c.WebpartServiceDisplayName.Equals(newobject.WebpartServiceDisplayName, StringComparison.InvariantCultureIgnoreCase));

                        if (match)
                        {
                            IsValidMarkup = false;
                            return;
                        }

                        IsValidMarkup = true;
                        _layoutObjects.Add(newobject);
                        _webActivity.Html = Html;
                        rows++;
                    }
                }

                if (_layoutObjects.Count > 0)
                {
                    lastGood = new ILayoutObjectViewModel[_layoutObjects.Count];
                    _layoutObjects.CopyTo(lastGood, 0);
                }

                //Initial load only
                if (copyToPrevious)
                {
                    if (lastGood != null)
                    {
                        previous = new ILayoutObjectViewModel[lastGood.Length];
                        lastGood.CopyTo(previous, 0);
                    }
                    copyToPrevious = false;
                }
                if (lastGood != null)
                {
                    CompareAndRemoveDeleted(lastGood.ToList().ToObservableCollection(), previous.ToObservableCollection());
                }
                // Update the HTML markup
                if (IsValidMarkup)
                {
                    _webActivity.Html = Html;
                }
                Rows = rows;
            }
        }
        public string CheckPermissions(string path, string username, string password)
        {
            dynamic returnData = new UnlimitedObject();


            if(username == string.Empty)
            {
                if(!FileIO.CheckPermissions(WindowsIdentity.GetCurrent(), path, FileSystemRights.Read) &&
                    !FileIO.CheckPermissions(WindowsIdentity.GetCurrent(), path, FileSystemRights.ReadData))
                {
                    returnData.Error = string.Concat("Insufficient permission for '", path, "'.");
                }
            }
            else
            {
                // we have a username and password set :)

                if(!FileIO.CheckPermissions(username, password, path, FileSystemRights.Read) &&
                    FileIO.CheckPermissions(username, password, path, FileSystemRights.ReadData))
                {
                    returnData.Error = string.Concat("Insufficient permission for '", path, "'.");
                }
            }

            return returnData.XmlString;
        }
 //This returns a list of supported database servers in the system
 public string FindSupportedDatabaseServers()
 {
     dynamic returnData = new UnlimitedObject();
     dynamic serviceData = new UnlimitedObject("Dev2Resources");
     dynamic serviceInfo = new UnlimitedObject("Dev2Resource");
     serviceInfo.Dev2DatabaseServer = enSourceType.MySqlDatabase;
     serviceData.AddResponse(serviceInfo);
     serviceInfo = new UnlimitedObject("Dev2Resource");
     serviceInfo.Dev2DatabaseServer = enSourceType.SqlDatabase;
     serviceData.AddResponse(serviceInfo);
     string returnVal = GetResourceNameAsXml(returnData.XmlString, serviceData);
     return returnVal;
 }
        public string CompileResource(string resourceDefinition)
        {
            dynamic returnData = new UnlimitedObject();

            List<DynamicServiceObjectBase> compiledResources = Host.GenerateObjectGraphFromString(resourceDefinition);
            if(compiledResources.Count == 0)
            {
                return string.Format("<{0}>{1}</{0}>", "Result", Resources.CompilerMessage_BuildFailed);
            }

            compiledResources.ForEach(c =>
            {
                if(c.ObjectType == enDynamicServiceObjectType.DynamicService)
                {
                    var dynamicService = c as DynamicService;
                    if (dynamicService != null)
                        dynamicService.Actions.ForEach(action => Host.MapServiceActionDependencies(action));
                }
                if(c.ObjectType == enDynamicServiceObjectType.WorkflowActivity)
                {
                    Host.MapActivityToService((c as WorkflowActivityDef));
                }
                c.Compile();
                returnData.AddResponse(c.GetCompilerErrors());
            });

            return returnData.XmlString;
        }
        //Returns SQL SERVER database schema
        // 26.09.2012 - Travis.Frisinger : Amended to properly intergate the schema
        public string FindSqlDatabaseSchema(string serverName, string databaseName, string username, string password)
        {
            dynamic xmlResponse = new UnlimitedObject();

            IDBHelper helper = DBHelperFactory.GenerateNewHelper(enSupportedDBTypes.MSSQL);
            var props = new DBConnectionProperties();
            props.Server = serverName;
            props.DB = databaseName;
            props.User = username;
            props.Pass = password;
            string result = helper.ExtractCodedEntities(helper.CreateConnectionString(props));

            return result;
        }
        public string SetDynamicServiceMode(string xmlRequest)
        {
            dynamic xmlReq = new UnlimitedObject();
            xmlReq.Load(xmlRequest);

            dynamic service = xmlReq.Service;

            if(service is string)
            {
                DynamicService svc;
                Host.LockServices();

                try
                {
                    svc = Host.Services.Find(c => c.Name == service);
                }
                finally
                {
                    Host.UnlockServices();
                }


                if(svc != null)
                {
                    dynamic mode = xmlReq.Mode;
                    if(mode is string)
                    {
                        enDynamicServiceMode modeToSet;
                        if(Enum.TryParse<enDynamicServiceMode>(xmlReq.Mode, out modeToSet))
                        {
                            svc.Mode = modeToSet;
                        }
                        else
                        {
                            xmlReq.Error = "Bad Mode in Request";
                        }
                    }
                }
            }
            else
            {
                xmlReq.Error = "Bad Request";
            }
            return xmlReq.XmlString;
        }
        public string FindDirectory(string directoryPath, string domain, string username, string password)
        {
            IntPtr accessToken = IntPtr.Zero;
            const int logon32ProviderDefault = 0;
            const int logon32LogonInteractive = 2;
            dynamic returnData = new UnlimitedObject();
            bool isDir = false;
            try
            {
                if(username.Length > 0)
                {
                    domain = (domain.Length > 0 && domain != ".") ? domain : Environment.UserDomainName;
                    bool success = LogonUser(username, domain, password, logon32LogonInteractive,
                                             logon32ProviderDefault, ref accessToken);
                    if(success)
                    {
                        var identity = new WindowsIdentity(accessToken);
                        WindowsImpersonationContext context = identity.Impersonate();
                        // get the file attributes for file or directory
                        FileAttributes attr = File.GetAttributes(directoryPath);

                        //detect whether its a directory or file
                        // ReSharper disable ConvertIfStatementToConditionalTernaryExpression
                        if((attr & FileAttributes.Directory) == FileAttributes.Directory)
                        // ReSharper restore ConvertIfStatementToConditionalTernaryExpression
                        {
                            isDir = true;
                        }

                        if(isDir)
                        {
                            var directory = new DirectoryInfo(directoryPath);
                            returnData.JSON = GetDirectoryInfoAsJSON(directory);
                        }
                        else
                        {
                            returnData.JSON = "[]";
                        }
                        context.Undo();
                    }
                    else
                    {
                        returnData.Result = new Win32Exception(Marshal.GetLastWin32Error());
                    }
                }
                else
                {
                    // get the file attributes for file or directory
                    FileAttributes attr = File.GetAttributes(directoryPath);

                    //detect whether its a directory or file
                    // ReSharper disable ConvertIfStatementToConditionalTernaryExpression
                    if((attr & FileAttributes.Directory) == FileAttributes.Directory)
                    // ReSharper restore ConvertIfStatementToConditionalTernaryExpression
                    {
                        isDir = true;
                    }

                    if(isDir)
                    {
                        var directory = new DirectoryInfo(directoryPath);
                        returnData.JSON = GetDirectoryInfoAsJSON(directory);
                    }
                    else
                    {
                        returnData.JSON = "[]";
                    }
                }
            }
            catch(Exception ex)
            {
                returnData.Error = new UnlimitedObject(ex).XmlString;
            }
            return returnData.XmlString;
        }
        //Author: Zuko Mgwili
        //Date: 18/06/2012
        //Purpose of the method is to return worker service name and worker service category
        private string GetWorkerServiceResourceAsXml(string source, dynamic serviceData)
        {
            var doc = new XmlDocument();
            doc.LoadXml(source);
            XmlNodeList list = doc.ChildNodes;
            XmlNode root = list[0];
            XmlNodeList workerServices = root.ChildNodes;
            foreach(XmlNode node in workerServices)
            {
                dynamic serviceInfo = new UnlimitedObject("Dev2Resource");
                if(node.Name.Equals("Service"))
                {
                    if (node.Attributes != null)
                    {
                        serviceInfo.Dev2WorkerService = node.Attributes["Name"].Value;
                    }

                    XmlNode tmpNode = node.SelectSingleNode("//Category");
                    if(tmpNode != null)
                    {
                        serviceInfo.Dev2WorkerServiceCategory = tmpNode.InnerText;
                    }
                    //serviceInfo.Dev2WorkerServiceCategory = node.ChildNodes[3].InnerText;
                    serviceInfo.Dev2WorkerServiceContents = node.OuterXml;
                    serviceData.AddResponse(serviceInfo);
                }
            }
            return serviceData.XmlString;
        }
 public string FindDrive(string domain, string username, string password)
 {
     IntPtr accessToken = IntPtr.Zero;
     const int logon32ProviderDefault = 0;
     const int logon32LogonInteractive = 2;
     dynamic returnData = new UnlimitedObject();
     try
     {
         if(username.Length > 0)
         {
             domain = (domain.Length > 0 && domain != ".") ? domain : Environment.UserDomainName;
             bool success = LogonUser(username, domain, password, logon32LogonInteractive,
                                      logon32ProviderDefault, ref accessToken);
             if(success)
             {
                 var identity = new WindowsIdentity(accessToken);
                 WindowsImpersonationContext context = identity.Impersonate();
                 DriveInfo[] drives = DriveInfo.GetDrives();
                 returnData.JSON = GetDriveInfoAsJSON(drives);
                 context.Undo();
             }
             else
             {
                 returnData.Result = new Win32Exception(Marshal.GetLastWin32Error());
             }
         }
         else
         {
             DriveInfo[] drives = DriveInfo.GetDrives();
             returnData.JSON = GetDriveInfoAsJSON(drives);
         }
     }
     catch(Exception ex)
     {
         returnData.Error = new UnlimitedObject(ex.Message).XmlString;
     }
     return returnData.XmlString;
 }
 //Author: Zuko Mgwili
 //Date: 19/06/2012
 //Purpose of the method is to return source name and type
 private string GetSourceResourceAsXml(string source, dynamic serviceData)
 {
     var doc = new XmlDocument();
     doc.LoadXml(source);
     XmlNodeList list = doc.ChildNodes;
     XmlNode root = list[0];
     XmlNodeList sourceItem = root.ChildNodes;
     foreach(XmlNode node in sourceItem)
     {
         dynamic serviceInfo = new UnlimitedObject("Dev2Resource");
         if(node.Name.Equals("Source"))
         {
             if (node.Attributes != null)
             {
                 serviceInfo.Dev2SourceName = node.Attributes["Name"].Value;
                 serviceInfo.Dev2SourceType = node.Attributes["Type"].Value;
             }
             serviceInfo.Dev2SourceContents = node.OuterXml;
             serviceData.AddResponse(serviceInfo);
         }
     }
     return serviceData.XmlString;
 }
 public string FindServerUsername()
 {
     dynamic returnData = new UnlimitedObject();
     returnData.Result = Environment.UserDomainName + "\\" + Environment.UserName;
     return returnData.XmlString;
 }
        // PBI : 5376 - Broke this signature to avoid use ;)
        public dynamic Workflow(ServiceAction workflowAction, dynamic xmlRequest, int i)
        {
            dynamic returnVal = new UnlimitedObject();
            IDictionary<string, object> inputs = new Dictionary<string, object>();
            inputs.Add("AmbientDataList", new List<string> { xmlRequest.XmlString });

            // ReSharper disable RedundantAssignment
            IDictionary<string, object> output = new Dictionary<string, object>();
            // ReSharper restore RedundantAssignment

            var workflowInvoker = new WorkflowInvoker(workflowAction.WorkflowActivity);
            workflowInvoker.Extensions.Add(_dsfChannel);


            try
            {
                output = workflowInvoker.Invoke(inputs);
                foreach(var data in output)
                {
                    if(data.Value != null)
                    {
                        if(data.Value is List<string>)
                        {
                            foreach(string result in (data.Value as List<string>))
                            {
                                returnVal.AddResponse(
                                    UnlimitedObject.GetStringXmlDataAsUnlimitedObject(string.Format("<{0}>{1}</{0}>",
                                                                                                    Resources
                                                                                                        .DynamicService_ServiceResponseTag,
                                                                                                    result)));
                            }
                        }
                    }
                    else
                    {
                        returnVal = xmlRequest;
                    }
                }
            }
            catch(WorkflowApplicationAbortedException workflowAbortedEx)
            {
                returnVal.Error = "Workflow Execution Was Aborted";
                returnVal.ErrorDetail = new UnlimitedObject(workflowAbortedEx).XmlString;
            }
            catch(Exception workflowEx)
            {
                returnVal.Error = "Error occurred executing workflow";
                returnVal.ErrorDetail = new UnlimitedObject(workflowEx).XmlString;
            }


            //ExceptionHandling.WriteEventLogEntry(
            //    "Application",
            //    string.Format("{0}.{1}", this.GetType().Name, "WorkflowCommand"),
            //    string.Format("Exception:{0}\r\n", returnVal.XmlString),
            //    EventLogEntryType.Error
            //);

            //if (returnVal.DSFResult is string) {
            //    return UnlimitedObject.GetStringXmlDataAsUnlimitedObject(returnVal.DSFResult);
            //}
            //else {
            //    if (returnVal.DSFResult is UnlimitedObject) {

            //        if (!string.IsNullOrEmpty(returnVal.DSFResult.XmlString)) {
            //            return returnVal.DSFResult;
            //        }
            //    }
            //}

            return returnVal;
        }
 public string FindNetworkComputers()
 {
     dynamic returnData = new UnlimitedObject();
     string json = "[";
     try
     {
         var root = new DirectoryEntry("WinNT:");
         foreach(DirectoryEntry dom in root.Children)
         {
             foreach(DirectoryEntry entry in dom.Children)
             {
                 if(entry.SchemaClassName == "Computer")
                 {
                     json += @"{""ComputerName"":""" + entry.Name + @"""},";
                 }
             }
         }
         json += "]";
         json = json.Replace(",]", "]"); // remove last comma
         returnData.JSON = json;
     }
     catch(Exception ex)
     {
         returnData.Error = new UnlimitedObject(ex).XmlString;
     }
     return returnData.XmlString;
 }
        public void UpdateModelItem()
        {
            if(!string.IsNullOrEmpty(Html) && _webActivity != null && _webActivity.ResourceModel != null && _webActivity.ResourceModel.Environment != null)
            {
                int rows = 0;

                UnlimitedObject tags = new UnlimitedObject();

                try
                {
                    tags = UnlimitedObject.GetStringXmlDataAsUnlimitedObject(Html.ToLower());
                }
                catch { IsValidMarkup = false; return; }

                if(tags.HasError)
                {
                    IsValidMarkup = false;
                    return;
                }
                else
                {
                    IsValidMarkup = true;
                }

                var tagItems = tags.GetAllElements("dev2html");

                bool copyToPrevious = false;

                if(lastGood == null)
                {
                    copyToPrevious = true;
                }
                else
                {

                    previous = new ILayoutObjectViewModel[lastGood.Length];
                    lastGood.CopyTo(previous, 0);
                }

                _layoutObjects.Clear();

                foreach(dynamic tag in tagItems)
                {

                    IResourceModel res = null;

                    string name = null;
                    string type = null;
                    string iconpath = null;

                    if(tag.name is string)
                    {
                        name = tag.name;
                    }

                    if(tag.type is string)
                    {
                        type = tag.type;
                        res = _webActivity.ResourceModel.Environment.Resources.All().FirstOrDefault(c => c.ResourceName.Equals(type, StringComparison.InvariantCultureIgnoreCase));
                        if(res != null)
                        {
                            iconpath = res.IconPath;
                        }
                    }

                    var exclusions = new List<string>() { "form", "meta", "pagetitle" };
                    if(!exclusions.Contains(type.ToLower()))
                    {

                        if(string.IsNullOrEmpty(name))
                        {
                            IsValidMarkup = false;
                            return;
                        }

                        if(string.IsNullOrEmpty(type))
                        {
                            IsValidMarkup = false;
                            return;
                        }

                        if(string.IsNullOrEmpty(StringResources.Website_Supported_Webparts))
                        {
                            throw new Exception(StringResources.Error_Supported_Webparts_Not_Set);
                        }

                        List<string> inclusions = StringResources.Website_Supported_Webparts.Split(new char[] { ',' }).ToList();
                        if(!inclusions.Contains(type.ToLower()))
                        {
                            IsValidMarkup = false;
                            return;
                        }

                        var newobject = LayoutObjectViewModelFactory.CreateLayoutObject(type, name, iconpath, GetConfigFragment(name));

                        //Check if another webpart with the same name - not type - exists
                        //If so then we want to mark the website html as invalid
                        //as we don't allow multiple parts with the same name
                        var match = _layoutObjects.Any(c => c.WebpartServiceDisplayName.Equals(newobject.WebpartServiceDisplayName, StringComparison.InvariantCultureIgnoreCase));

                        if(match)
                        {
                            IsValidMarkup = false;
                            return;
                        }

                        IsValidMarkup = true;
                        _layoutObjects.Add(newobject);
                        _webActivity.Html = Html;
                        rows++;
                    }
                }

                if(_layoutObjects.Count > 0)
                {
                    lastGood = new ILayoutObjectViewModel[_layoutObjects.Count];
                    _layoutObjects.CopyTo(lastGood, 0);
                }

                //Initial load only
                if(copyToPrevious)
                {
                    if(lastGood != null)
                    {
                        previous = new ILayoutObjectViewModel[lastGood.Length];
                        lastGood.CopyTo(previous, 0);
                    }
                    copyToPrevious = false;
                }
                if(lastGood != null)
                {
                    CompareAndRemoveDeleted(lastGood.ToList().ToObservableCollection(), previous.ToObservableCollection());
                }
                // Update the HTML markup
                if(IsValidMarkup)
                {
                    _webActivity.Html = Html;

                }
                Rows = rows;

            }
        }
Beispiel #32
0
        private void SetupForDelete()
        {
            _popupController.Setup(c => c.Show()).Verifiable();
            _popupController.Setup(s => s.Show()).Returns(MessageBoxResult.Yes);
            _resourceDependencyService.Setup(s => s.HasDependencies(_firstResource.Object)).Returns(false).Verifiable();
            var succesResponse = new UnlimitedObject(@"<DataList>Success</DataList>");

            _resourceRepo.Setup(s => s.DeleteResource(_firstResource.Object)).Returns(succesResponse);
        }
 public string RegisteredAssembly()
 {
     dynamic returnData = new UnlimitedObject();
     try
     {
         IAssemblyName assemblyName;
         IAssemblyEnum assemblyEnum = GAC.CreateGACEnum();
         string json = "[";
         while(GAC.GetNextAssembly(assemblyEnum, out assemblyName) == 0)
         {
             json += @"{""AssemblyName"":""" + GAC.GetName(assemblyName) + @"""}";
             json += ",";
         }
         json += "]";
         json = json.Replace(",]", "]"); //remove the last comma in the string in order to have valid json
         returnData.JSON = json;
     }
     catch(Exception ex)
     {
         returnData.Error = new UnlimitedObject(ex).XmlString;
     }
     return returnData.XmlString;
 }
        private string ReadFromModelItemDataProperty(string propertyName)
        {
            dynamic data = UnlimitedObject.GetStringXmlDataAsUnlimitedObject(_webActivity.XMLConfiguration);

            return(data.GetValue(propertyName));
        }
Beispiel #35
0
        public void DeleteResourceConfirmedWithInvalidResponseExpectNoMessage()
        {
            lock (syncroot)
            {
                CreateFullExportsAndVm();
                SetupForDelete();
                var response = new UnlimitedObject(@"<DataList>Invalid</DataList>");
                _resourceRepo.Setup(s => s.DeleteResource(_firstResource.Object)).Returns(response);

                var msg = new DeleteResourceMessage(_firstResource.Object, false);
                _mainViewModel.Handle(msg);
                _eventAggregator.Verify(e => e.Publish(It.IsAny<RemoveNavigationResourceMessage>()), Times.Never());
            }
        }
        public string CheckCredentials(string domain, string username, string password)
        {
            dynamic returnData = new UnlimitedObject();
            try
            {
                if (domain.Equals("."))
                {
                    domain = Environment.UserDomainName;
                }
                bool isValid;
                using(var context = new PrincipalContext(ContextType.Domain, domain))
                {
                    isValid = context.ValidateCredentials(username, password);

                    context.Dispose();
                }
                if(isValid)
                {
                    returnData.Result = "Connection successful!";
                }
                else
                {
                    returnData.Result = "Connection failed. Ensure your username and password are valid";
                }
            }
            catch
            {
                returnData.Result = "Connection failed. Ensure your username and password are valid";
            }
            return returnData.XmlString;
        }