/// <summary>
        /// Extracts the data list.
        /// </summary>
        /// <param name="serviceDef">The service def.</param>
        /// <returns></returns>
        public static string ExtractDataList(StringBuilder serviceDef)
        {
            string result = string.Empty;

            var xe = serviceDef.ToXElement();

            var dl = xe.Elements().FirstOrDefault(c => c.Name == GlobalConstants.DataListRootTag);

            if (dl != null)
            {
                result = dl.ToString(SaveOptions.DisableFormatting);
            }
            
            return result;
        }
        public void ExtensionMethods_ToStreamForXmlLoad_WhenLoadingXElement_ExpectValidXElement()
        {
            //------------Setup for test--------------------------
            const string val = "<x><y>1</y></x>";
            StringBuilder value = new StringBuilder(val);

            //------------Execute Test---------------------------
            var xe = value.ToXElement();

            string result = xe.ToString(SaveOptions.DisableFormatting);

            //------------Assert Results-------------------------
            Assert.AreEqual(val, result);
        }
        public void ExtensionMethods_ToStreamForXmlLoad_WhenLoadingXElement_ExpectException()
        {
            //------------Setup for test--------------------------
            const string val = "<x><y>1</y>.</</x>";
            StringBuilder value = new StringBuilder(val);

            //------------Execute Test---------------------------
            value.ToXElement();
        }
        public void ExtensionMethods_CleanEncodingHeaderForXmlSave_WhenSavingXElement_ExpectEncodingHeaderRemoved()
        {
            //------------Setup for test--------------------------
            StringBuilder value = new StringBuilder("<x><y>1</y></x>");

            //------------Execute Test---------------------------
            var xe = value.ToXElement();

            var sb = new StringBuilder();
            using(var sw = new StringWriter(sb))
            {
                xe.Save(sw, SaveOptions.DisableFormatting);
            }

            var res = sb.CleanEncodingHeaderForXmlSave();

            //------------Assert Results-------------------------
            var result = res.Contains("encoding=");

            Assert.IsFalse(result, "Encoding Header Not Removed");
        }
        public void ExtensionMethods_AttributeSafe_WhenAttributeDoesNotExist_ExpectEmptyString()
        {
            //------------Setup for test--------------------------
            const string msg = "<x foo=\"bar\">test message</x>";
            var sb = new StringBuilder(msg);

            //------------Execute Test---------------------------

            var xe = sb.ToXElement();
            var result = xe.AttributeSafe("foo2");

            //------------Assert Results-------------------------
            Assert.AreEqual(result, string.Empty);
        }
        public void ExtensionMethods_AttributeSafe_WhenAttributeExist_ExpectAttributeValue()
        {
            //------------Setup for test--------------------------
            const string msg = "<x foo=\"bar\">test message</x>";
            var sb = new StringBuilder(msg);

            //------------Execute Test---------------------------

            var xe = sb.ToXElement();
            var result = xe.AttributeSafe("foo");

            //------------Assert Results-------------------------
            StringAssert.Contains(result, "bar");
        }
        public void ExtensionMethods_ElementSafe_WhenElementDoesNotExist_ExpectEmptyString()
        {
            //------------Setup for test--------------------------
            const string msg = "<x><y>y value</y></x>";
            var sb = new StringBuilder(msg);

            //------------Execute Test---------------------------

            var xe = sb.ToXElement();
            var result = xe.ElementSafe("q");

            //------------Assert Results-------------------------
            Assert.AreEqual(result, string.Empty);
        }
        public void ExtensionMethods_ElementSafe_WhenElementExist_ExpectElement()
        {
            //------------Setup for test--------------------------
            const string msg = "<x><y>y value</y></x>";
            var sb = new StringBuilder(msg);

            //------------Execute Test---------------------------

            var xe = sb.ToXElement();
            var result = xe.ElementSafe("y");

            //------------Assert Results-------------------------
            StringAssert.Contains(result, "y");
        }
        public void AppServer_Update_Resource_Correctly()
        {
            CommunicationController coms = new CommunicationController { ServiceName = "SaveResourceService" };

            var tmp = new StringBuilder(TestResource.Service_Update_Request_String);
            var xe = tmp.ToXElement();
            var xml = xe.Element("ResourceXml");

            var wtf = xml.ToStringBuilder().Unescape();
            wtf = wtf.Replace("<XmlData>", "").Replace("</XmlData>", "").Replace("<ResourceXml>", "").Replace("</ResourceXml>", "");

            coms.AddPayloadArgument("ResourceXml", wtf);
            coms.AddPayloadArgument("WorkspaceID", Guid.Empty.ToString());

            const string expected = @"Updated WorkflowService 'ServiceToBindFrom'";

            var result = coms.ExecuteCommand<ExecuteMessage>(_connection, Guid.Empty);

            StringAssert.Contains(result.Message.ToString(), expected);

        }
        public static string ExtractOutputMapping(StringBuilder serviceDef)
        {
            string result = string.Empty;

            var xe = serviceDef.ToXElement();

            // could have service as its root ;(
            var tmpB = xe.Elements().FirstOrDefault(c => c.Name == GlobalConstants.ActionsRootTag);

            var tmpA = xe.Elements().FirstOrDefault(c => c.Name == GlobalConstants.ActionRootTag);

            if (tmpB != null)
            {
                tmpA = tmpB.Elements().FirstOrDefault(c => c.Name == GlobalConstants.ActionRootTag);
            }


            if (tmpA != null)
            {
                var dl = tmpA.Elements().FirstOrDefault(c => c.Name == GlobalConstants.OutputRootTag);

                if (dl != null)
                {
                    result = dl.ToString();
                }
            }


            return result;
        }
        public List<DynamicServiceObjectBase> GenerateServiceGraph(StringBuilder serviceData)
        {
            if(serviceData == null || serviceData.Length == 0)
            {
                throw new ArgumentException("serviceData");
            }

            List<DynamicServiceObjectBase> result = new List<DynamicServiceObjectBase>();
            var xe = serviceData.ToXElement();

            if(IsSource(serviceData))
            {
                Source src = new Source();
                var tmp = src as DynamicServiceObjectBase;
                ServiceMetaData.ExtractMetaData(xe, ref tmp);

                var typeOf = xe.AttributeSafe("ResourceType");

                enSourceType sourceType;
                src.Type = !Enum.TryParse(typeOf, out sourceType) ? enSourceType.Unknown : sourceType;

                src.ConnectionString = xe.AttributeSafe("ConnectionString");
                var tmpUri = xe.AttributeSafe("Uri");
                if(!string.IsNullOrEmpty(tmpUri))
                {
                    src.WebServiceUri = new Uri(tmpUri);
                }

                src.AssemblyName = xe.AttributeSafe("AssemblyName");
                src.AssemblyLocation = xe.AttributeSafe("AssemblyLocation");

                // PBI 6597: TWR - added source ID check
                var id = ServiceMetaData.SetID(ref xe);
                src.ID = id;
                src.ResourceDefinition = serviceData;

                result.Add(src);

            }
            else
            {
                DynamicService ds = new DynamicService();
                var tmp = ds as DynamicServiceObjectBase;
                ServiceMetaData.ExtractMetaData(xe, ref tmp);

                // set the resource def ;)
                ds.ResourceDefinition = serviceData;

                var actions = xe.Element("Actions");
                XElement action = actions != null ? actions.Element("Action") : xe.Element("Action");

                if(action != null)
                {
                    ServiceAction sa = new ServiceAction { Name = action.AttributeSafe("Name"), ResourceDefinition = serviceData };

                    // Set service action ;)
                    enActionType actionType;
                    var typeOf = action.AttributeSafe("Type");
                    if(Enum.TryParse(typeOf, out actionType))
                    {
                        sa.ActionType = actionType;
                    }

                    var element = action.Element("Outputs");
                    if(element != null)
                    {
                        sa.OutputSpecification = element.Value;
                    }

                    // set name and id ;)
                    sa.ServiceName = ds.Name;
                    var id = ServiceMetaData.SetID(ref xe);
                    ds.ID = id;

                    if(IsWorkflow(serviceData))
                    {
                        // Convert to StringBuilder
                        var xElement = action.Element("XamlDefinition");
                        if(xElement != null)
                        {
                            var def = xElement.ToStringBuilder();
                            def = def.Replace("<XamlDefinition>", "").Replace("</XamlDefinition>", "");
                            sa.XamlDefinition = def.Unescape();
                        }

                        var dataList = xe.Element("DataList");
                        if(dataList != null)
                        {
                            ds.DataListSpecification = dataList.ToStringBuilder();
                        }
                    }
                    else
                    {
                        if(sa.ActionType == enActionType.InvokeStoredProc)
                        {
                            int timeout;
                            Int32.TryParse(action.AttributeSafe("CommandTimeout"), out timeout);
                            sa.CommandTimeout = timeout;
                        }

                        var xElement = action.Element("OutputDescription");
                        if(xElement != null)
                        {
                            sa.OutputDescription = xElement.Value;
                        }

                        // process inputs and outputs ;)
                        var inputs = action.Element("Inputs");

                        if(inputs != null)
                        {
                            var inputCollection = inputs.Elements("Input");

                            foreach(var inputItem in inputCollection)
                            {
                                bool emptyToNull;
                                bool.TryParse(inputItem.AttributeSafe("EmptyToNull"), out emptyToNull);

                                ServiceActionInput sai = new ServiceActionInput
                                {
                                    Name = inputItem.AttributeSafe("Name"),
                                    Source = inputItem.AttributeSafe("Source"),
                                    DefaultValue = inputItem.AttributeSafe("DefaultValue"),
                                    EmptyToNull = emptyToNull,
                                    NativeType = inputItem.AttributeSafe("NativeType")
                                };

                                if(string.IsNullOrEmpty(sai.NativeType))
                                {
                                    sai.NativeType = "object";
                                }

                                // handle validators ;)
                                var validators = inputItem.Elements("Validator");
                                foreach(var validator in validators)
                                {
                                    Validator v = new Validator();

                                    enValidationType validatorType;
                                    v.ValidatorType = !Enum.TryParse(validator.AttributeSafe("Type"), out validatorType) ? enValidationType.Required : validatorType;

                                    sai.Validators.Add(v);
                                }

                                sa.ServiceActionInputs.Add(sai);
                            }
                        }
                    }

                    // add the action
                    ds.Actions.Add(sa);
                    result.Add(ds);
                }

            }

            return result;
        }
        /// <summary>
        /// Builds the graph.
        /// </summary>
        /// <param name="xmlData">The XML data.</param>
        /// <param name="modelName">Name of the model.</param>
        /// <param name="width">The width.</param>
        /// <param name="height">The height.</param>
        /// <returns></returns>
        public Graph BuildGraph(StringBuilder xmlData, string modelName, double width, double height)
        {

            if(xmlData == null || xmlData.Length == 0)
            {
                return new Graph("Dependency information could not be retrieved");
            }

            XElement xe = xmlData.ToXElement();

            // Create a graph.
            var graphElem = xe.AncestorsAndSelf("graph").FirstOrDefault();
            if(graphElem == null)
            {
                return new Graph("Dependency information is malformed");
            }

            try
            {
                string title = graphElem.Attribute("title").Value;
                var graph = new Graph(title);
                double count = 0;

                var nodeElems = graphElem.Elements("node").ToList();

                // Create all of the nodes and add them to the graph.
                foreach(XElement nodeElem in nodeElems)
                {
                    // build the graph position data
                    string id = nodeElem.Attribute("id").Value;
                    var node = CreateNode(nodeElem, modelName, width, height, ref count);

                    bool alreadyAdded = false;
                    foreach(Node n in graph.Nodes)
                    {
                        if(n.ID == id)
                        {
                            alreadyAdded = true;
                        }
                    }

                    if(!alreadyAdded)
                    {
                        graph.Nodes.Add(node);
                    }
                }

                // Associate each node with its dependencies.
                foreach(Node node in graph.Nodes)
                {
                    var nodeElem = nodeElems.First(elem => elem.Attribute("id").Value == node.ID);
                    var dependencyElems = nodeElem.Elements("dependency");
                    foreach(XElement dependencyElem in dependencyElems)
                    {
                        string depID = dependencyElem.Attribute("id").Value;

                        var dependency = graph.Nodes.FirstOrDefault(n => n.ID == depID);
                        if(dependency != null)
                            node.NodeDependencies.Add(dependency);
                    }

                    //Now adjust position according to nodesize
                    node.LocationX = node.LocationX - node.NodeWidth;
                    node.LocationY = node.LocationY - node.NodeHeight / 2;
                }

                // Tell the graph to inspect itself for circular dependencies.
                graph.CheckForCircularDependencies();

                return graph;
            }
            catch
            {
                return new Graph("Dependency information is malformed");
            }
        }