CreateElement() public method

public CreateElement ( String name ) : XmlElement
name String
return XmlElement
Exemplo n.º 1
1
        protected override void SaveNode(XmlDocument xmlDoc, XmlElement nodeElement, SaveContext context)
        {
            Controller.SaveNode(xmlDoc, nodeElement, context);
            
            var outEl = xmlDoc.CreateElement("Name");
            outEl.SetAttribute("value", NickName);
            nodeElement.AppendChild(outEl);

            outEl = xmlDoc.CreateElement("Description");
            outEl.SetAttribute("value", Description);
            nodeElement.AppendChild(outEl);

            outEl = xmlDoc.CreateElement("Inputs");
            foreach (string input in InPortData.Select(x => x.NickName))
            {
                XmlElement inputEl = xmlDoc.CreateElement("Input");
                inputEl.SetAttribute("value", input);
                outEl.AppendChild(inputEl);
            }
            nodeElement.AppendChild(outEl);

            outEl = xmlDoc.CreateElement("Outputs");
            foreach (string output in OutPortData.Select(x => x.NickName))
            {
                XmlElement outputEl = xmlDoc.CreateElement("Output");
                outputEl.SetAttribute("value", output);
                outEl.AppendChild(outputEl);
            }
            nodeElement.AppendChild(outEl);
        }
Exemplo n.º 2
1
        private bool OverWriting() {
        //private async Task<bool> OverWriting() {
            if (ListingQueue.Any()) {
                XmlDocument xmlDoc;
                XmlElement xmlEle;
                XmlNode newNode;

                xmlDoc = new XmlDocument();
                xmlDoc.Load("ImageData.xml"); // XML문서 로딩

                newNode = xmlDoc.SelectSingleNode("Images"); // 추가할 부모 Node 찾기
                xmlEle = xmlDoc.CreateElement("Image");
                newNode.AppendChild(xmlEle);
                newNode = newNode.LastChild;
                xmlEle = xmlDoc.CreateElement("ImagePath"); // 추가할 Node 생성
                xmlEle.InnerText = ListingQueue.Peek();
                ListingQueue.Dequeue();
                newNode.AppendChild(xmlEle); // 위에서 찾은 부모 Node에 자식 노드로 추가..

                xmlDoc.Save("ImageData.xml"); // XML문서 저장..
                xmlDoc = null;

                return true;
            }
            return false;
        }
Exemplo n.º 3
0
        private string GetXML()
        {
            XmlDocument document = new XmlDocument();

            XmlElement RazaoNode = document.CreateElement("Razao");
            RazaoNode.InnerText = Razao;

            XmlElement ValoresNode = document.CreateElement("Valores");
            XmlElement ValorNode = document.CreateElement("Valor");

            XmlAttribute moeda = document.CreateAttribute("moeda");
            moeda.Value = "BRL";

            ValorNode.Attributes.Append(moeda);
            ValorNode.InnerText = String.Format("{0:0.00}", Valor).Replace(',','.');

            ValoresNode.AppendChild(ValorNode);

            XmlNode EnviarInstrucao = document.CreateElement("EnviarInstrucao");
            XmlNode InstrucaoUnica = EnviarInstrucao.AppendChild(document.CreateNode(XmlNodeType.Element, "InstrucaoUnica", ""));

            InstrucaoUnica.AppendChild(RazaoNode);
            InstrucaoUnica.AppendChild(ValoresNode);

            return EnviarInstrucao.OuterXml;
        }
Exemplo n.º 4
0
        public override string ToText(Subtitle subtitle, string title)
        {
            string xmlStructure =
                "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + Environment.NewLine +
                "<EEG708Captions/>";

            XmlDocument xml = new XmlDocument();
            xml.LoadXml(xmlStructure);

            foreach (Paragraph p in subtitle.Paragraphs)
            {
                XmlNode paragraph = xml.CreateElement("Caption");
                XmlAttribute start = xml.CreateAttribute("timecode");
                start.InnerText = EncodeTimeCode(p.StartTime);
                paragraph.Attributes.Append(start);
                XmlNode text = xml.CreateElement("Text");
                text.InnerText = p.Text;
                paragraph.AppendChild(text);
                xml.DocumentElement.AppendChild(paragraph);

                paragraph = xml.CreateElement("Caption");
                start = xml.CreateAttribute("timecode");
                start.InnerText = EncodeTimeCode(p.EndTime);
                paragraph.Attributes.Append(start);
                xml.DocumentElement.AppendChild(paragraph);
            }

            return ToUtf8XmlString(xml);
        }
Exemplo n.º 5
0
		public XmlNode GetMacro(int Id, string Login, string Password)
		{
		    if (ValidateCredentials(Login, Password)
                && UserHasAppAccess(DefaultApps.developer.ToString(), Login)) 
			{
				var xmlDoc = new XmlDocument();
				var macro = xmlDoc.CreateElement("macro");
				var m = new cms.businesslogic.macro.Macro(Id);
                macro.Attributes.Append(XmlHelper.AddAttribute(xmlDoc, "id", m.Id.ToString()));
                macro.Attributes.Append(XmlHelper.AddAttribute(xmlDoc, "refreshRate", m.RefreshRate.ToString()));
                macro.Attributes.Append(XmlHelper.AddAttribute(xmlDoc, "useInEditor", m.UseInEditor.ToString()));
                macro.Attributes.Append(XmlHelper.AddAttribute(xmlDoc, "alias", m.Alias));
                macro.Attributes.Append(XmlHelper.AddAttribute(xmlDoc, "name", m.Name));
                macro.Attributes.Append(XmlHelper.AddAttribute(xmlDoc, "assembly", m.Assembly));
                macro.Attributes.Append(XmlHelper.AddAttribute(xmlDoc, "type", m.Type));
                macro.Attributes.Append(XmlHelper.AddAttribute(xmlDoc, "xslt", m.Xslt));
				var properties = xmlDoc.CreateElement("properties");
				foreach (var mp in m.Properties) 
				{
					var pXml = xmlDoc.CreateElement("property");
                    pXml.Attributes.Append(XmlHelper.AddAttribute(xmlDoc, "alias", mp.Alias));
                    pXml.Attributes.Append(XmlHelper.AddAttribute(xmlDoc, "name", mp.Name));
                    pXml.Attributes.Append(XmlHelper.AddAttribute(xmlDoc, "public", mp.Public.ToString()));
					properties.AppendChild(pXml);
				}
				macro.AppendChild(properties);
				return macro;
			}
		    return null;
		}
Exemplo n.º 6
0
        protected void Button1_Click(object sender, EventArgs e)
        {

            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(Server.MapPath("Quotes.xml"));
            XmlElement parentelement = xmldoc.CreateElement("Item");

            XmlElement ID = xmldoc.CreateElement("ID");
            ID.InnerText = _txtPN.Value;
            XmlElement QTY = xmldoc.CreateElement("QTY");
            QTY.InnerText = _txtQty.Value;
            XmlElement Product = xmldoc.CreateElement("Product");
            Product.InnerText = _txtProduct.Value;
            XmlElement Cost = xmldoc.CreateElement("Cost");
            Cost.InnerText = _txtCost.Value;

            parentelement.AppendChild(ID);
            parentelement.AppendChild(QTY);
            parentelement.AppendChild(Product);
            parentelement.AppendChild(Cost);
            xmldoc.DocumentElement.AppendChild(parentelement);

            xmldoc.Save(Server.MapPath("Quotes.xml"));
            _txtQty.Value = string.Empty;
            _txtProduct.Value = string.Empty;
            _txtCost.Value = string.Empty;
            _txtPN.Value = string.Empty;

            if (this.IsPostBack)
            {
                this.Get_Xml();
            }

        }
Exemplo n.º 7
0
        /// <summary>
        /// XML-Datei mit XmlDocument erstellen.
        /// </summary>
        static void CreateXmlDocument()
        {
            XmlDocument xmlDoc = new XmlDocument();
            XmlDeclaration declaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", "no");  // XML Deklaration
            xmlDoc.AppendChild(declaration);

            XmlNode rootNode = xmlDoc.CreateElement("books");   // Wurzelelement
            xmlDoc.AppendChild(rootNode);   // Wurzelelement zum Dokument hinzufuegen

            // <book> Element
            XmlNode userNode = xmlDoc.CreateElement("book");
            // mit einem Attribut
            XmlAttribute attribute = xmlDoc.CreateAttribute("release");
            attribute.Value = "2013/02/15";
            userNode.Attributes.Append(attribute);  // Attribut zum <book> Ele hinzufuegen
            // und Textinhalt
            userNode.InnerText = "Elizabeth Corley - Pretty Little Things";
            rootNode.AppendChild(userNode); // Textinhalt zum <book> Ele hinzufuegen

            // und noch ein <book>
            userNode = xmlDoc.CreateElement("book");
            attribute = xmlDoc.CreateAttribute("release");
            attribute.Value = "2011/11/11";
            userNode.Attributes.Append(attribute);
            userNode.InnerText = "Stephen Hawking - A Brief History Of Time";
            rootNode.AppendChild(userNode);

            // XML Dokument speichern
            xmlDoc.Save("xmlDocument_books.xml");   // in ../projectname/bin/debug/
        }
Exemplo n.º 8
0
        private void OutputXML(int interval)
        {
            XmlDocument xDoc = new XmlDocument();
            XmlNode xmlEl = xDoc.AppendChild(xDoc.CreateElement("H2G2"));
            xmlEl.Attributes.Append(xDoc.CreateAttribute("TYPE"));
            xmlEl.Attributes["TYPE"].InnerText = "STATUSPAGE";
            xmlEl = xmlEl.AppendChild(xDoc.CreateElement("STATUS-REPORT"));
            xmlEl.AppendChild(xDoc.ImportNode(Statistics.CreateStatisticsDocument(interval).FirstChild, true));

            XmlDocument xmlSignal = new XmlDocument();
            xmlSignal.LoadXml(StringUtils.SerializeToXmlUsingXmlSerialiser(SignalHelper.GetStatus(Global.dnaDiagnostics)));
            xmlEl.AppendChild(xDoc.ImportNode(xmlSignal.DocumentElement, true));

            try
            {
                var memcachedCacheManager = (MemcachedCacheManager)CacheFactory.GetCacheManager("Memcached");
                xmlEl.AppendChild(xDoc.ImportNode(memcachedCacheManager.GetStatsXml(), true));
            }
            catch (Exception e)
            {
                var childNode = xmlEl.AppendChild(xDoc.CreateElement("MEMCACHED_STATUS"));
                childNode.InnerText = "Error getting memcached stats:" + e.Message;
            }

            Response.ContentType = "text/xml";
            Response.Clear();
            Response.Write(xDoc.InnerXml);
            Response.End();
        }
Exemplo n.º 9
0
        //Saves given Unistroke to file as a new gesture with name specified
        public static void saveGesture(ref SignalProcessing.Unistroke<double> u, string name)
        {
            XmlDocument doc = new XmlDocument();

            doc.Load("gestures.xml");
            XmlNodeList nl = doc.GetElementsByTagName("gesture_set");
            XmlElement gesture_elem= doc.CreateElement("gesture");
            XmlAttribute ident = doc.CreateAttribute("name");
            ident.InnerText = name;
            gesture_elem.Attributes.Append(ident);

            for(int i = 0; i < u.trace.Count; i++){
                XmlElement n = doc.CreateElement("point");
                XmlAttribute x = doc.CreateAttribute("x");
                XmlAttribute y = doc.CreateAttribute("y");
                XmlAttribute z = doc.CreateAttribute("z");
                x.InnerText = u[i].x.ToString();
                y.InnerText = u[i].y.ToString();
                z.InnerText = u[i].z.ToString();
                n.Attributes.Append(x);
                n.Attributes.Append(y);
                n.Attributes.Append(z);
                gesture_elem.AppendChild(n);
            }

            nl[0].AppendChild(gesture_elem);
            doc.Save("gestures.xml");
        }
        /// <summary>
        /// Serializes the specified play list items.
        /// </summary>
        /// <param name="items">The play list.</param>
        /// <returns>The serielized play list as xml document.</returns>
        public XmlDocument Serialize(IEnumerable<ListViewItem> items)
        {
            var doc = new XmlDocument();

            XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "utf-8", "yes");
            doc.AppendChild(declaration);

            XmlElement root = doc.CreateElement("items");
            doc.AppendChild(root);

            foreach (ListViewItem item in items)
            {
                XmlElement element = doc.CreateElement("item");
                element.InnerText = item.Text;

                XmlAttribute startTime = doc.CreateAttribute("start");
                startTime.InnerText = item.SubItems[1].Text;
                element.Attributes.Append(startTime);

                XmlAttribute endTime = doc.CreateAttribute("end");
                endTime.InnerText = item.SubItems[2].Text;
                element.Attributes.Append(endTime);

                XmlAttribute duration = doc.CreateAttribute("duration");
                duration.InnerText = item.SubItems[3].Text;
                element.Attributes.Append(duration);

                root.AppendChild(element);
            }

            return doc;
        }
Exemplo n.º 11
0
        public XmlElement ToXml(XmlDocument document)
        {
            XmlElement addressNode = document.CreateElement("idmef:Address", "http://iana.org/idmef");

            addressNode.SetAttribute("ident", ident);
            addressNode.SetAttribute("category", EnumDescription.GetEnumDescription(category));
            if (!string.IsNullOrEmpty(vlanName)) addressNode.SetAttribute("vlan-name", vlanName);
            if (vlanNum != null) addressNode.SetAttribute("vlan-num", vlanNum.ToString());

            if (string.IsNullOrEmpty(address)) throw new InvalidOperationException("Address must have an address node.");
            XmlElement addressSubNode = document.CreateElement("idmef:address", "http://iana.org/idmef");
            XmlNode subNode = document.CreateNode(XmlNodeType.Text, "idmef", "address", "http://iana.org/idmef");
            subNode.Value = address;
            addressSubNode.AppendChild(subNode);
            addressNode.AppendChild(addressSubNode);

            if (!string.IsNullOrEmpty(netmask))
            {
                addressSubNode = document.CreateElement("idmef:netmask", "http://iana.org/idmef");
                subNode = document.CreateNode(XmlNodeType.Text, "idmef", "netmask", "http://iana.org/idmef");
                subNode.Value = netmask;
                addressSubNode.AppendChild(subNode);
                addressNode.AppendChild(addressSubNode);
            }

            return addressNode;
        }
        //Generate the Terms collection (of Term) based on an xml document
        public static bool Save(XmlDocument xmlTemplateDoc, Template template, bool bValidate)
        {
            //Convert the xml into an xmldocument
            //XmlDocument xmlTemplateDoc = new XmlDocument();
            //xmlTemplateDoc.PreserveWhitespace = false;
            //xmlTemplateDoc.LoadXml(template.TemplateDef);

            //Convert the objects stored in memory to an xmldocument
            XmlDocument xmlDoc = new XmlDocument();
            XmlElement nodeUserDocumentPrinters = xmlDoc.CreateElement(XMLNames._E_UserDocumentPrinters);

            if (template.UserDocumentPrinters != null)
                foreach (Role userDocumentPrinter in template.UserDocumentPrinters)
                {
                    XmlElement nodeUserDocumentPrinter = xmlDoc.CreateElement(XMLNames._E_Role);
                    userDocumentPrinter.Build(xmlDoc, nodeUserDocumentPrinter, bValidate);
                    nodeUserDocumentPrinters.AppendChild(nodeUserDocumentPrinter);
                }

            //Replace the impacted portion of the complete xml with this version from memory
            XmlNode importedNodeUserDocumentPrinters = xmlTemplateDoc.ImportNode(nodeUserDocumentPrinters, true);
            //Find the "Comments" child node
            XmlNode userDocumentPrinterChildNode = xmlTemplateDoc.SelectSingleNode(Utility.XMLHelper.GetXPath(true, XMLNames._E_TemplateDef, XMLNames._E_UserDocumentPrinters));
            if (userDocumentPrinterChildNode != null)
                xmlTemplateDoc.DocumentElement.ReplaceChild(importedNodeUserDocumentPrinters, userDocumentPrinterChildNode);
            else
                xmlTemplateDoc.DocumentElement.AppendChild(importedNodeUserDocumentPrinters);

            return true;
        }
Exemplo n.º 13
0
		/// <summary>
		/// Implements the following function 
		///		node-set tokenize(string, string)
		/// </summary>
		/// <param name="str"></param>
		/// <param name="delimiters"></param>				
		/// <returns>This function breaks the input string into a sequence of strings, 
		/// treating any character in the list of delimiters as a separator. 
		/// The separators themselves are not returned. 
		/// The tokens are returned as a set of 'token' elements.</returns>
		public XPathNodeIterator tokenize(string str, string delimiters)
		{

			XmlDocument doc = new XmlDocument();
			doc.LoadXml("<tokens/>");

			if (delimiters == String.Empty)
			{
				foreach (char c in str)
				{
					XmlElement elem = doc.CreateElement("token");
					elem.InnerText = c.ToString();
					doc.DocumentElement.AppendChild(elem);
				}
			}
			else
			{
				foreach (string token in str.Split(delimiters.ToCharArray()))
				{

					XmlElement elem = doc.CreateElement("token");
					elem.InnerText = token;
					doc.DocumentElement.AppendChild(elem);
				}
			}

			return doc.CreateNavigator().Select("//token");
		}
Exemplo n.º 14
0
        public override string ToText(Subtitle subtitle, string title)
        {
            string xmlStructure = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + Environment.NewLine + "<Subtitle/>";

            XmlDocument xml = new XmlDocument();
            xml.LoadXml(xmlStructure);

            foreach (Paragraph p in subtitle.Paragraphs)
            {
                XmlNode paragraph = xml.CreateElement("Paragraph");

                XmlNode number = xml.CreateElement("Number");
                number.InnerText = p.Number.ToString();
                paragraph.AppendChild(number);

                XmlNode start = xml.CreateElement("StartMilliseconds");
                start.InnerText = p.StartTime.TotalMilliseconds.ToString(CultureInfo.InvariantCulture);
                paragraph.AppendChild(start);

                XmlNode end = xml.CreateElement("EndMilliseconds");
                end.InnerText = p.EndTime.TotalMilliseconds.ToString(CultureInfo.InvariantCulture);
                paragraph.AppendChild(end);

                XmlNode text = xml.CreateElement("Text");
                text.InnerText = HtmlUtil.RemoveHtmlTags(p.Text);
                paragraph.AppendChild(text);

                xml.DocumentElement.AppendChild(paragraph);
            }

            return ToUtf8XmlString(xml);
        }
Exemplo n.º 15
0
        public ControlResponse GetResponse(Exception ex)
        {
            var env = new XmlDocument();
            env.AppendChild(env.CreateXmlDeclaration("1.0", "utf-8", "yes"));
            var envelope = env.CreateElement("SOAP-ENV", "Envelope", NS_SOAPENV);
            env.AppendChild(envelope);
            envelope.SetAttribute("encodingStyle", NS_SOAPENV, "http://schemas.xmlsoap.org/soap/encoding/");

            var rbody = env.CreateElement("SOAP-ENV:Body", NS_SOAPENV);
            env.DocumentElement.AppendChild(rbody);

            var fault = env.CreateElement("SOAP-ENV", "Fault", NS_SOAPENV);
            var faultCode = env.CreateElement("faultcode");
            faultCode.InnerText = "500";
            fault.AppendChild(faultCode);
            var faultString = env.CreateElement("faultstring");
            faultString.InnerText = ex.ToString();
            fault.AppendChild(faultString);
            var detail = env.CreateDocumentFragment();
            detail.InnerXml = "<detail><UPnPError xmlns=\"urn:schemas-upnp-org:control-1-0\"><errorCode>401</errorCode><errorDescription>Invalid Action</errorDescription></UPnPError></detail>";
            fault.AppendChild(detail);
            rbody.AppendChild(fault);

            return new ControlResponse
            {
                Xml = env.OuterXml,
                IsSuccessful = false
            };
        }
        public static XmlElement GetHttpRuntime(XmlDocument configuration, bool createIfMissing = false)
        {
            var systemWeb = configuration.SelectSingleElement("/configuration/system.web");
              if (systemWeb == null)
              {
            if (!createIfMissing)
            {
              return null;
            }

            systemWeb = configuration.CreateElement("system.web");
            configuration.DocumentElement.AppendChild(systemWeb);
              }

              var httpRuntime = systemWeb.SelectSingleElement("httpRuntime");
              if (httpRuntime != null)
              {
            return httpRuntime;
              }

              if (!createIfMissing)
              {
            return null;
              }

              httpRuntime = configuration.CreateElement("httpRuntime");
              systemWeb.AppendChild(httpRuntime);

              return httpRuntime;
        }
Exemplo n.º 17
0
        public static void Save(string languageID, NameValueCollection translations)
        {
            string stub = Resource1.ResourceManager.GetString("ResxTemplate");
              string xml = BuildFileName(languageID);
              StreamWriter writer = new StreamWriter(xml, false, Encoding.UTF8);
              writer.Write(stub);
              writer.Close();
              XmlDocument doc = new XmlDocument();
              doc.Load(xml);
              XmlNode nRoot = doc.SelectSingleNode("/root");
              foreach (string key in translations.Keys)
              {
            if (translations[key] == null) continue;
            XmlNode nValue = doc.CreateElement("value");

            nValue.InnerText = translations[key];
            XmlNode nKey = doc.CreateElement("data");
            XmlAttribute attr = nKey.OwnerDocument.CreateAttribute("name");
            attr.InnerText = key;
            nKey.Attributes.Append(attr);
            attr = nKey.OwnerDocument.CreateAttribute("xml:space");
            attr.InnerText = "preserve";
            nKey.Attributes.Append(attr);
            nKey.AppendChild(nValue);
            nRoot.AppendChild(nKey);
              }
              doc.Save(xml);
        }
Exemplo n.º 18
0
        public override XmlNode ToXml(XmlDocument doc)
        {
            var root = doc.CreateElement("secDNS:update", "urn:ietf:params:xml:ns:secDNS-1.1");
            root.SetAttribute("xmlns:secDNS", "urn:ietf:params:xml:ns:secDNS-1.1");

            var xsd = doc.CreateAttribute("xsi", "schemaLocation", "http://www.w3.org/2001/XMLSchema-instance");
            xsd.Value = "urn:ietf:params:xml:ns:secDNS-1.1 secDNS-1.1.xsd";
            root.Attributes.Append(xsd);

            if (ToRemove.Any())
            {
                var removeNode = doc.CreateElement("secDNS:rem", "urn:ietf:params:xml:ns:secDNS-1.1");

                foreach (var data in ToRemove)
                {
                    removeNode.AppendChild(data.ToXml(doc));
                }

                root.AppendChild(removeNode);
            }

            if (ToAdd.Any())
            {
                var addNode = doc.CreateElement("secDNS:add", "urn:ietf:params:xml:ns:secDNS-1.1");

                foreach (var data in ToAdd)
                {
                    addNode.AppendChild(data.ToXml(doc));
                }

                root.AppendChild(addNode);
            }

            return root;
        }
Exemplo n.º 19
0
 public void Save(string path)
 {
     this.time = DateTime.Now;
     if (!File.Exists(path))
     {
         XmlWriter writer = XmlWriter.Create(path);
         writer.WriteStartElement("head");
         writer.WriteFullEndElement();
         writer.Close();
     }
     XmlDocument doc = new XmlDocument();
     doc.Load(path);
     XmlNode root = doc.DocumentElement;
     XmlElement newOrder = doc.CreateElement("OrderId");
     XmlElement newUser = doc.CreateElement("UserId");
     XmlElement newTime = doc.CreateElement("Time");
     XmlText orderId = doc.CreateTextNode(this.IdOrder.ToString());
     XmlText userId = doc.CreateTextNode(this.IdUser.ToString());
     XmlText checkTime = doc.CreateTextNode(this.time.ToString("o"));
     newOrder.AppendChild(orderId);
     newUser.AppendChild(userId);
     newTime.AppendChild(checkTime);
     root.InsertAfter(newOrder, root.LastChild);
     root.InsertAfter(newUser, root.LastChild);
     root.InsertAfter(newTime, root.LastChild);
     doc.Save(path);
 }
Exemplo n.º 20
0
        public void AddItem(string cardKey, string name, string lastname, string username, string password, string XMLFile)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("userdatabase.xml");

            XmlElement newUser = doc.CreateElement("user");

            newUser.SetAttribute("cardkey", cardKey);

            XmlElement newUserName = doc.CreateElement("username");
            newUserName.InnerText = username;
            newUser.AppendChild(newUserName);

            XmlElement newPassword = doc.CreateElement("password");
            newPassword.InnerText = password;
            newUser.AppendChild(newPassword);

            XmlElement newName = doc.CreateElement("name");
            newName.InnerText = name;
            newUser.AppendChild(newName);

            XmlElement newLastName = doc.CreateElement("lastname");
            newLastName.InnerText = lastname;
            newUser.AppendChild(newLastName);

            doc.FirstChild.AppendChild(newUser);

            doc.Save("userdatabase.xml");
        }
Exemplo n.º 21
0
        public void CreateXml(string xmlPath, string xmlName, string[] value, string[] xmlElementNode)
        {
            try
            {
                string str = inType.ToString();
                if (str.Length < 5)
                {
                    return;
                }
                string rootName = str.Substring(str.Length - 5, 4);
                XmlDocument doc = new XmlDocument();
                XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
                doc.AppendChild(dec);

                XmlElement root = doc.CreateElement(rootName);
                doc.AppendChild(root);
                XmlNode childElement = doc.CreateElement(str);
                for (int i = 0; i < xmlElementNode.Length; i++)
                {
                    XmlElement xe = doc.CreateElement(xmlElementNode[i]);
                    xe.InnerText = value[i];
                    childElement.AppendChild(xe);
                }
                root.AppendChild(childElement);
                doc.Save(string.Concat(@"", xmlPath, xmlName));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        public string InvokeResponse(string funcName, List<UPnPArg> args)
        {
            XmlDocument doc = new XmlDocument();
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null);
            doc.AppendChild(dec);

            XmlElement env = doc.CreateElement("s", "Envelope", "http://schemas.xmlsoap.org/soap/envelope/");
            doc.AppendChild(env);
            env.SetAttribute("encodingStyle", "http://schemas.xmlsoap.org/soap/envelope/", "http://schemas.xmlsoap.org/soap/encoding/");

            XmlElement body = doc.CreateElement("Body", "http://schemas.xmlsoap.org/soap/envelope/");
            body.Prefix = "s";
            env.AppendChild(body);

            XmlElement func = doc.CreateElement("u", funcName + "Response", "urn:schemas-upnp-org:service:AVTransport:1");
            body.AppendChild(func);
            func.SetAttribute("xmlns:u", "urn:schemas-upnp-org:service:AVTransport:1");

            if (args != null)
            {
                foreach (UPnPArg s in args)
                {
                    XmlElement f = doc.CreateElement(s.ArgName);
                    func.AppendChild(f);
                    f.InnerText = s.ArgVal;
                }
            }

            //Saved for debugging:
            doc.Save(@"InvokeResponse.xml");

            string msg = AppendHead(doc.OuterXml);
            return msg;
        }
Exemplo n.º 23
0
        private XmlDocument CreateMessage(string data, object recipients)
        {
            var doc = new XmlDocument();

            XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
            XmlElement root = doc.DocumentElement;
            doc.InsertBefore(xmlDeclaration, root);

            XmlElement e0 = doc.CreateElement(string.Empty, "Message", string.Empty);
            doc.AppendChild(e0);

            XmlElement e2 = doc.CreateElement(string.Empty, "Data", string.Empty);
            e2.AppendChild(doc.CreateTextNode(data));
            e0.AppendChild(e2);

            XmlElement e3 = doc.CreateElement(string.Empty, "Recipients", string.Empty);
            e0.AppendChild(e3);

            foreach (string s in ObjectToStringArray(recipients))
            {
                XmlElement e4 = doc.CreateElement(string.Empty, "Recipient", string.Empty);
                e4.AppendChild(doc.CreateTextNode(s));
                e3.AppendChild(e4);
            }

            return doc;
        }
Exemplo n.º 24
0
        /// <summary>
        /// Generates a new floating license.
        /// </summary>
        /// <param name="name">Name of the license holder</param>
        /// <param name="publicKey">public key of the license server</param>
        /// <returns>license content</returns>
        public string GenerateFloatingLicense(string name, string publicKey)
        {
            using (var rsa = Encryptor.Current.CreateAsymmetrical())
            {
                rsa.FromXmlString(privateKey);
                var doc = new XmlDocument();
                var license = doc.CreateElement("floating-license");
                doc.AppendChild(license);

                var publicKeyEl = doc.CreateElement("license-server-public-key");
                license.AppendChild(publicKeyEl);
                publicKeyEl.InnerText = publicKey;

                var nameEl = doc.CreateElement("name");
                license.AppendChild(nameEl);
                nameEl.InnerText = name;

                var signature = GetXmlDigitalSignature(doc, rsa.Algorithm);
                doc.FirstChild.AppendChild(doc.ImportNode(signature, true));

                var ms = new MemoryStream();
                var writer = XmlWriter.Create(ms, new XmlWriterSettings
                {
                    Indent = true,
                    Encoding = Encoding.UTF8
                });
                doc.Save(writer);
                ms.Position = 0;
                return new StreamReader(ms).ReadToEnd();
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Saves the contents of this instance to the defined config file.
        /// </summary>
        /// <param name="force">If false, will only save if the flag indicates that changes have been made. If true, always saves.</param>
        public void Save( bool force = false ) {
            if( force || outOfDate ) {
                Type t = this.GetType();

                PropertyInfo[] properties = t.GetProperties();
                XmlDocument doc = new XmlDocument();
                XmlElement config = doc.CreateElement( "config" );
                lock( threadLock ) {
                    foreach( PropertyInfo pi in properties ) {
                        object val = pi.GetValue( this, null );
                        if( val != null ) {
                            XmlElement element = doc.CreateElement( pi.Name );
                            element.InnerText = val.ToString();
                            config.AppendChild( element );
                        }
                    }
                }
                doc.AppendChild( config );
                try {
                    doc.Save( FilePath );
                } catch( IOException ) {
                }
                outOfDate = false;
            }
        }
        private void btn_OK_Click(object sender, EventArgs e)
        {
            XmlDocument xmlDoc = new XmlDocument();
            XmlNode docNode = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
            xmlDoc.AppendChild(docNode);

            XmlNode version = xmlDoc.CreateElement("version");
            xmlDoc.AppendChild(version);

            XmlNode sbtNode = xmlDoc.CreateElement("SBT");
            XmlAttribute sbtAttribute = xmlDoc.CreateAttribute("Path");
            sbtAttribute.Value = textBox1.Text;
            sbtNode.Attributes.Append(sbtAttribute);
            version.AppendChild(sbtNode);

            XmlNode garenaNode = xmlDoc.CreateElement("Garena");
            XmlAttribute garenaAttribute = xmlDoc.CreateAttribute("Path");
            garenaAttribute.Value = textBox2.Text;
            garenaNode.Attributes.Append(garenaAttribute);
            version.AppendChild(garenaNode);

            XmlNode superNode = xmlDoc.CreateElement("Super");
            XmlAttribute superAttribute = xmlDoc.CreateAttribute("Path");
            superAttribute.Value = textBox3.Text;
            superNode.Attributes.Append(superAttribute);
            version.AppendChild(superNode);

            xmlDoc.Save("path");
            this.Close();
        }
Exemplo n.º 27
0
        private void GenerateStrings(string inputPath, string outputFile)
        {
            XElement rootElement = XElement.Load(inputPath);
            IEnumerable<Tuple<string, string>> items = from dataElement in rootElement.Descendants("data")
                                                       let key = dataElement.Attribute("name").Value
                                                       let valueElement = dataElement.Element("value")
                                                       where valueElement != null
                                                       let value = valueElement.Value
                                                       select new Tuple<string, string>(key, value);
            XmlDocument document = new XmlDocument();
            document.AppendChild(document.CreateXmlDeclaration("1.0", "utf-8", null));
            XmlNode rootNode = document.CreateElement("resources");
            document.AppendChild(rootNode);

            foreach (var pair in items)
            {
                XmlNode elementNode = document.CreateElement("string");
                elementNode.InnerText = processValue(pair.Item2);
                XmlAttribute attributeName = document.CreateAttribute("name");
                attributeName.Value = processKey(pair.Item1);
                // ReSharper disable once PossibleNullReferenceException
                elementNode.Attributes.Append(attributeName);

                rootNode.AppendChild(elementNode);
            }

            document.Save(outputFile);
        }
Exemplo n.º 28
0
        public void addData(string XmlFilePath,StringBuilder str)
        {
            XmlDocument document = new XmlDocument();

                document.Load(XmlFilePath);
                XmlNode element = document.CreateElement("info");
                document.DocumentElement.AppendChild(element);

                XmlNode title = document.CreateElement("title");
                title.InnerText = XmlFilePath;
                element.AppendChild(title);

                XmlNode chapter = document.CreateElement("chapter");
                document.DocumentElement.AppendChild(chapter); // указываем родителя

                XmlNode para = document.CreateElement("para");
                para.InnerText = str.ToString();
                chapter.AppendChild(para);

                document.Save(XmlFilePath);

               // Console.WriteLine("Data have been added to xml!");

               // Console.ReadKey();
               // Console.WriteLine(XmlToJSON(document));
        }
        public override string ToText(Subtitle subtitle, string title)
        {
            // <Phrase TimeStart="4020" TimeEnd="6020">
            // <Text>XYZ PRESENTS</Text>
            // </Phrase>
            string xmlStructure = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + Environment.NewLine + "<Subtitle xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"></Subtitle>";

            XmlDocument xml = new XmlDocument();
            xml.LoadXml(xmlStructure);

            int id = 1;
            foreach (Paragraph p in subtitle.Paragraphs)
            {
                XmlNode paragraph = xml.CreateElement("Phrase");

                XmlAttribute start = xml.CreateAttribute("TimeStart");
                start.InnerText = p.StartTime.TotalMilliseconds.ToString();
                paragraph.Attributes.Append(start);

                XmlAttribute duration = xml.CreateAttribute("TimeEnd");
                duration.InnerText = p.EndTime.TotalMilliseconds.ToString();
                paragraph.Attributes.Append(duration);

                XmlNode text = xml.CreateElement("Text");
                text.InnerText = HtmlUtil.RemoveHtmlTags(p.Text).Replace(Environment.NewLine, "\\n");
                paragraph.AppendChild(text);

                xml.DocumentElement.AppendChild(paragraph);
                id++;
            }

            return ToUtf8XmlString(xml);
        }
        public string Subscribe(string deliveryUrl, string eventType)
        {
            string subscriptionId = Guid.NewGuid().ToString();

            XmlDocument subscriptionStore = new XmlDocument();
            subscriptionStore.Load(subscriptionStorePath);

            // Add a new subscription
            XmlNode newSubNode = subscriptionStore.CreateElement("Subscription");

            XmlNode subscriptionIdStart = subscriptionStore.CreateElement("SubscriptionID");
            subscriptionIdStart.InnerText = subscriptionId;
            newSubNode.AppendChild(subscriptionIdStart);

            XmlNode deliveryAddressStart = subscriptionStore.CreateElement("DeliveryAddress");
            deliveryAddressStart.InnerText = deliveryUrl;
            newSubNode.AppendChild(deliveryAddressStart);

            XmlNode eventTypeStart = subscriptionStore.CreateElement("EventType");
            eventTypeStart.InnerText = eventType;
            newSubNode.AppendChild(eventTypeStart);

            subscriptionStore.DocumentElement.AppendChild(newSubNode);

            subscriptionStore.Save(subscriptionStorePath);

            return subscriptionId;
        }
Exemplo n.º 31
0
    public override void toValues(Hashtable values)
    {
        System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
        if (!values.ContainsKey(fieldName))
        {
            System.Xml.XmlElement rootNode = xmlDoc.CreateElement(fieldName);
            xmlDoc.AppendChild(rootNode);
            values.Add(fieldName, xmlDoc.InnerXml);
        }
        else
        {
            xmlDoc.LoadXml(values[fieldName].ToString());
        }

        if (!label.Text.Equals(string.Empty))
        {
            System.Xml.XmlElement xmlElement = xmlDoc.CreateElement(xmlNodeName);
            xmlElement.InnerText = label.Text.Trim();
            xmlDoc.DocumentElement.AppendChild(xmlElement);
            values[fieldName] = xmlDoc.InnerXml;
        }
    }
Exemplo n.º 32
0
    public override void toValues(Hashtable values)
    {
        System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
        if (!values.ContainsKey(fieldName))
        {
            System.Xml.XmlElement rootNode = xmlDoc.CreateElement(fieldName);
            xmlDoc.AppendChild(rootNode);
            values.Add(fieldName, xmlDoc.InnerXml);
        }
        else
        {
            xmlDoc.LoadXml(values[fieldName].ToString());
        }

        if (checkbox.Checked)
        {
            System.Xml.XmlElement xmlElement = xmlDoc.CreateElement(xmlNodeName);
            xmlElement.InnerText = "YES";
            xmlDoc.DocumentElement.AppendChild(xmlElement);
            values[fieldName] = xmlDoc.InnerXml;
        }
    }
Exemplo n.º 33
0
    /// <summary>
    /// log error in xml file
    /// </summary>
    /// <param name="ErrorMsg"></param>
    /// <param name="strModule"></param>
    public static void WriteErrorLog(string ErrorMsg, string strModule, bool IsWeb)
    {
        System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
        System.Xml.XmlElement  xmlErrorElemnt;
        System.Xml.XmlElement  xmlErrorMsgElemnt;
        System.Xml.XmlElement  xmlModuleElemnt;
        System.Xml.XmlElement  xmlTimeElemnt;
        try
        {
            if (ErrorMsg == "Thread was being aborted.")
            {
                return;
            }
            CreateLogFile(IsWeb);
            xmlDoc.Load(strDocName);

            xmlErrorElemnt = xmlDoc.CreateElement("Error");

            xmlErrorMsgElemnt           = xmlDoc.CreateElement("ErrorMsg");
            xmlErrorMsgElemnt.InnerText = ErrorMsg;
            xmlErrorElemnt.AppendChild(xmlErrorMsgElemnt);

            xmlModuleElemnt           = xmlDoc.CreateElement("Module");
            xmlModuleElemnt.InnerText = strModule;
            xmlErrorElemnt.AppendChild(xmlModuleElemnt);

            xmlTimeElemnt           = xmlDoc.CreateElement("DateTime");
            xmlTimeElemnt.InnerText = DateTime.Now.ToString();
            xmlErrorElemnt.AppendChild(xmlTimeElemnt);

            xmlDoc.DocumentElement.AppendChild(xmlErrorElemnt);
            xmlDoc.Save(strDocName);
        }

        catch
        {
        }
    }
Exemplo n.º 34
0
    public void testNotifyOfServerChanges()
    {
        System.Xml.XmlDocument doc        = new System.Xml.XmlDocument();
        System.Xml.XmlElement  serverNode = doc.CreateElement("server");
        System.Xml.XmlElement  child1     = doc.CreateElement("child1");
        System.Xml.XmlElement  child2     = doc.CreateElement("child2");

        serverNode.AppendChild(child1);
        serverNode.AppendChild(child2);
        doc.AppendChild(serverNode);

        bool called = false;

        Action <object> callback = o => { called = true; Console.WriteLine(o.ToString()); };

        RoarManager.roarServerAllEvent += callback;

        RoarManager.NotifyOfServerChanges(serverNode);

        Assert.IsTrue(called);

        this.mockery.VerifyAllExpectationsHaveBeenMet();
    }
Exemplo n.º 35
0
    public System.Xml.XmlElement SaveXML(System.Xml.XmlDocument xmlDoc)
    {
        System.Xml.XmlElement wdDoc = xmlDoc.CreateElement(xmlName);
        wdDoc.SetAttribute("name", this.name);
        wdDoc.SetAttribute("id", this.guid);
        wdDoc.SetAttribute("cat", this.GetCategoryName());

        if (this.output != null)
        {
            wdDoc.SetAttribute("output", this.output.GUID);
        }

        foreach (LLDNBase gnb in this.generators)
        {
            LLDNBase.CreateSaveElement(wdDoc, gnb);
        }

        return(wdDoc);
    }
Exemplo n.º 36
0
    /// <summary>
    /// Convert the wiring documents to an XML *.phon form.
    /// </summary>
    /// <returns>The wiring document.</returns>
    public System.Xml.XmlDocument SaveDocument()
    {
        System.Xml.XmlDocument doc  = new System.Xml.XmlDocument();
        System.Xml.XmlElement  root = doc.CreateElement("phonics");
        doc.AppendChild(root);

        foreach (WiringDocument wd in this.Documents)
        {
            System.Xml.XmlElement eleWD = wd.SaveXML(doc);
            root.AppendChild(eleWD);
        }

        if (this.activeDocument != null)
        {
            root.SetAttribute("active", this.activeDocument.guid);
        }

        return(doc);
    }
Exemplo n.º 37
0
        /// <summary>
        /// Configure the feature
        /// </summary>
        public void Configure(System.Xml.XmlDocument configurationDom)
        {
            if (!this.EnableConfiguration || this.m_panel.Targets.Count == 0)
            {
                return;
            }

            XmlElement configSectionsNode = configurationDom.SelectSingleNode("//*[local-name() = 'configSections']") as XmlElement,
                       notificationNode   = configurationDom.SelectSingleNode("//*[local-name() = 'marc.hi.ehrs.cr.notification.pixpdq']") as XmlElement,
                       coreNode           = configurationDom.SelectSingleNode("//*[local-name() = 'marc.hi.ehrs.svc.core']") as XmlElement,
                       everestNode        = configurationDom.SelectSingleNode("//*[local-name() = 'marc.everest.connectors.wcf']") as XmlElement;

            // Config sections node
            if (configSectionsNode == null)
            {
                configSectionsNode = configurationDom.CreateElement("configSections");
                configurationDom.DocumentElement.PrependChild(configSectionsNode);
            }
            XmlElement configSectionNode = configSectionsNode.SelectSingleNode("./*[local-name() = 'section'][@name = 'marc.hi.ehrs.cr.notification.pixpdq']") as XmlElement;

            if (configSectionNode == null)
            {
                configSectionNode = configurationDom.CreateElement("section");
                configSectionNode.Attributes.Append(configurationDom.CreateAttribute("name"));
                configSectionNode.Attributes.Append(configurationDom.CreateAttribute("type"));
                configSectionNode.Attributes["name"].Value = "marc.hi.ehrs.cr.notification.pixpdq";
                configSectionNode.Attributes["type"].Value = typeof(ConfigurationSectionHandler).AssemblyQualifiedName;
                configSectionsNode.AppendChild(configSectionNode);
            }
            configSectionNode = configSectionsNode.SelectSingleNode("./*[local-name() = 'section'][@name = 'marc.everest.connectors.wcf']") as XmlElement;
            if (configSectionNode == null)
            {
                configSectionNode = configurationDom.CreateElement("section");
                configSectionNode.Attributes.Append(configurationDom.CreateAttribute("name"));
                configSectionNode.Attributes.Append(configurationDom.CreateAttribute("type"));
                configSectionNode.Attributes["name"].Value = "marc.everest.connectors.wcf";
                configSectionNode.Attributes["type"].Value = typeof(MARC.Everest.Connectors.WCF.Configuration.ConfigurationSection).AssemblyQualifiedName;
                configSectionsNode.AppendChild(configSectionNode);
            }



            // Persistence section node
            if (notificationNode == null)
            {
                notificationNode = configurationDom.CreateElement("marc.hi.ehrs.cr.notification.pixpdq");
                configurationDom.DocumentElement.AppendChild(notificationNode);
            }

            // Ensure the assembly is loaded and the provider registered
            if (coreNode == null)
            {
                coreNode = configurationDom.CreateElement("marc.hi.ehrs.svc.core");
                configurationDom.DocumentElement.AppendChild(coreNode);
            }
            XmlElement serviceAssemblyNode = coreNode.SelectSingleNode("./*[local-name() = 'serviceAssemblies']") as XmlElement,
                       serviceProviderNode = coreNode.SelectSingleNode("./*[local-name() = 'serviceProviders']") as XmlElement;

            if (serviceAssemblyNode == null)
            {
                serviceAssemblyNode = configurationDom.CreateElement("serviceAssemblies");
                coreNode.AppendChild(serviceAssemblyNode);
            }
            if (serviceProviderNode == null)
            {
                serviceProviderNode = configurationDom.CreateElement("serviceProviders");
                coreNode.AppendChild(serviceProviderNode);
            }


            XmlElement addServiceAsmNode  = serviceAssemblyNode.SelectSingleNode("./*[local-name() = 'add'][@assembly = 'MARC.HI.EHRS.CR.Notification.PixPdq.dll']") as XmlElement,
                       addServiceProvNode = serviceProviderNode.SelectSingleNode(String.Format("./*[local-name() = 'add'][@type = '{0}']", typeof(PixNotifier).AssemblyQualifiedName)) as XmlElement;

            if (addServiceAsmNode == null)
            {
                addServiceAsmNode = configurationDom.CreateElement("add");
                addServiceAsmNode.Attributes.Append(configurationDom.CreateAttribute("assembly"));
                addServiceAsmNode.Attributes["assembly"].Value = "MARC.HI.EHRS.CR.Notification.PixPdq.dll";
                serviceAssemblyNode.AppendChild(addServiceAsmNode);
            }
            if (addServiceProvNode == null)
            {
                addServiceProvNode = configurationDom.CreateElement("add");
                addServiceProvNode.Attributes.Append(configurationDom.CreateAttribute("type"));
                addServiceProvNode.Attributes["type"].Value = typeof(PixNotifier).AssemblyQualifiedName;
                serviceProviderNode.AppendChild(addServiceProvNode);
            }



            // Write the configuration
            XmlElement targetsNode = notificationNode.SelectSingleNode("./*[local-name() = 'targets']") as XmlElement;

            if (targetsNode == null)
            {
                targetsNode = notificationNode.AppendChild(configurationDom.CreateElement("targets")) as XmlElement;
            }

            // Now loop through configuration
            foreach (var targ in this.m_panel.Targets)
            {
                // Find an add with the device id
                XmlElement addNode = targetsNode.SelectSingleNode(string.Format("./*[local-name() = 'add'][@name = '{0}']", targ.Configuration.Name)) as XmlElement;
                if (addNode == null)
                {
                    addNode = targetsNode.AppendChild(configurationDom.CreateElement("add")) as XmlElement;
                }



                // Setup WCF endpoint
                if (targ.Configuration.Notifier.GetType().Name.Contains("HL7v3"))
                {
                    CreateWcfClient(configurationDom, targ);
                }
                else
                {
                    targ.Configuration.ConnectionString = targ.Address.ToString();
                }

                // Clear add node
                addNode.RemoveAll();


                // Certificate info
                XmlElement certificateNode = addNode.SelectSingleNode("./*[local-name() = 'trustedIssuerCertificate']") as XmlElement;
                if (targ.ServerCertificate != null)
                {
                    if (certificateNode == null)
                    {
                        certificateNode = addNode.AppendChild(configurationDom.CreateElement("trustedIssuerCertificate")) as XmlElement;
                    }

                    certificateNode.RemoveAll();
                    certificateNode.Attributes.Append(configurationDom.CreateAttribute("storeLocation"));
                    certificateNode.Attributes.Append(configurationDom.CreateAttribute("storeName"));
                    certificateNode.Attributes.Append(configurationDom.CreateAttribute("x509FindType"));
                    certificateNode.Attributes.Append(configurationDom.CreateAttribute("findValue"));
                    certificateNode.Attributes["storeLocation"].Value = targ.ServerCertificateLocation.ToString();
                    certificateNode.Attributes["storeName"].Value     = targ.ServerCertificateStore.ToString();
                    certificateNode.Attributes["x509FindType"].Value  = X509FindType.FindByThumbprint.ToString();
                    certificateNode.Attributes["findValue"].Value     = targ.ServerCertificate.Thumbprint;
                }
                else if (certificateNode != null)
                {
                    certificateNode.ParentNode.RemoveChild(certificateNode);
                }

                // LLP Certificate
                certificateNode = addNode.SelectSingleNode("./*[local-name() = 'clientLLPCertificate']") as XmlElement;
                if (targ.ClientCertificate != null)
                {
                    if (certificateNode == null)
                    {
                        certificateNode = addNode.AppendChild(configurationDom.CreateElement("clientLLPCertificate")) as XmlElement;
                    }

                    certificateNode.RemoveAll();
                    certificateNode.Attributes.Append(configurationDom.CreateAttribute("storeLocation"));
                    certificateNode.Attributes.Append(configurationDom.CreateAttribute("storeName"));
                    certificateNode.Attributes.Append(configurationDom.CreateAttribute("x509FindType"));
                    certificateNode.Attributes.Append(configurationDom.CreateAttribute("findValue"));
                    certificateNode.Attributes["storeLocation"].Value = targ.ClientCertificateLocation.ToString();
                    certificateNode.Attributes["storeName"].Value     = targ.ClientCertificateStore.ToString();
                    certificateNode.Attributes["x509FindType"].Value  = X509FindType.FindByThumbprint.ToString();
                    certificateNode.Attributes["findValue"].Value     = targ.ClientCertificate.Thumbprint;
                }
                else if (certificateNode != null)
                {
                    certificateNode.ParentNode.RemoveChild(certificateNode);
                }

                // Setup core attribute
                addNode.Attributes.Append(configurationDom.CreateAttribute("connectionString"));
                addNode.Attributes["connectionString"].Value = targ.Configuration.ConnectionString;
                addNode.Attributes.Append(configurationDom.CreateAttribute("deviceId"));
                addNode.Attributes["deviceId"].Value = targ.Configuration.DeviceIdentifier;
                addNode.Attributes.Append(configurationDom.CreateAttribute("name"));
                addNode.Attributes["name"].Value = targ.Configuration.Name;
                addNode.Attributes.Append(configurationDom.CreateAttribute("myActor"));
                addNode.Attributes["myActor"].Value = targ.Configuration.Notifier.GetType().Name;

                // Now append notification domain
                foreach (var ntfy in targ.Configuration.NotificationDomain)
                {
                    var notifyNode = addNode.AppendChild(configurationDom.CreateElement("notify")) as XmlElement;
                    notifyNode.Attributes.Append(configurationDom.CreateAttribute("domain"));
                    notifyNode.Attributes["domain"].Value = ntfy.Domain;
                    foreach (var act in ntfy.Actions)
                    {
                        var actionNode = notifyNode.AppendChild(configurationDom.CreateElement("action")) as XmlElement;
                        actionNode.Attributes.Append(configurationDom.CreateAttribute("type"));
                        actionNode.Attributes["type"].Value = act.Action.ToString();
                    }
                }
            }

            // Everest configuration
            if (everestNode == null)
            {
                everestNode = configurationDom.DocumentElement.AppendChild(configurationDom.CreateElement("marc.everest.connectors.wcf")) as XmlElement;
            }

            // Load and import
            XmlDocument tEverestConfig = new XmlDocument();

            tEverestConfig.LoadXml("<marc.everest.connectors.wcf><action type=\"MARC.Everest.RMIM.UV.NE2008.Interactions.PRPA_IN201301UV02\" action=\"urn:hl7-org:v3:PRPA_IN201301UV02\"/><action type=\"MARC.Everest.RMIM.UV.NE2008.Interactions.PRPA_IN201302UV02\" action=\"urn:hl7-org:v3:PRPA_IN201301UV02\"/><action type=\"MARC.Everest.RMIM.UV.NE2008.Interactions.PRPA_IN201304UV02\" action=\"urn:hl7-org:v3:PRPA_IN201304UV02\"/></marc.everest.connectors.wcf>");
            var tEverestNode = configurationDom.ImportNode(tEverestConfig.DocumentElement, true) as XmlElement;

            foreach (XmlElement child in tEverestNode.ChildNodes)
            {
                if (everestNode.SelectSingleNode(String.Format("./*[local-name() = 'action'][@type='{0}']", child.Attributes["type"].Value)) == null)
                {
                    everestNode.AppendChild(child);
                }
            }

            if (everestNode.Attributes["formatter"] == null)
            {
                everestNode.Attributes.Append(configurationDom.CreateAttribute("formatter"));
                everestNode.Attributes["formatter"].Value = typeof(XmlIts1Formatter).AssemblyQualifiedName;
            }
            if (everestNode.Attributes["aide"] == null)
            {
                everestNode.Attributes.Append(configurationDom.CreateAttribute("aide"));
                everestNode.Attributes["aide"].Value = typeof(DatatypeFormatter).AssemblyQualifiedName;
            }

            this.m_needSync = true;
        }
Exemplo n.º 38
0
        public string GetListData(object count)
        {
            /*Declare and initialize a variable for the Lists Web service.*/
            Web_Reference.Lists listService = new Web_Reference.Lists();

            /*Authenticate the current user by passing their default
             * credentials to the Web service from the system credential cache.*/
            listService.Credentials =
                System.Net.CredentialCache.DefaultCredentials;

            /*Set the Url property of the service for the path to a subsite.*/
            listService.Url =
                "http://spwfedevv002:6907/sites/Importad/_vti_bin/lists.asmx";

            // Instantiate an XmlDocument object
            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();

            /* Assign values to the string parameters of the GetListItems method, using GUIDs for the listName and viewName variables. For listName, using the list display name will also work, but using the list GUID is recommended. For viewName, only the view GUID can be used. Using an empty string for viewName causes the default view
             * to be used.*/
            string listName = "{6C3EEF09-72D7-4BBD-857E-3E368DCB5859}";
            string viewName = "{062B24E9-C4BD-4B2D-8550-3529394970D2}";
            string rowLimit = "150";

            /*Use the CreateElement method of the document object to create elements for the parameters that use XML.*/
            System.Xml.XmlElement query      = xmlDoc.CreateElement("Query");
            System.Xml.XmlElement viewFields =
                xmlDoc.CreateElement("ViewFields");
            System.Xml.XmlElement queryOptions =
                xmlDoc.CreateElement("QueryOptions");

            /*To specify values for the parameter elements (optional), assign CAML fragments to the InnerXml property of each element.*/
            query.InnerXml        = "<Where></Where>";
            viewFields.InnerXml   = "<FieldRef Name=\"Title\" />";
            queryOptions.InnerXml = "";

            /* Declare an XmlNode object and initialize it with the XML response from the GetListItems method. The last parameter specifies the GUID of the Web site containing the list. Setting it to null causes the Web site specified by the Url property to be used.*/
            System.Xml.XmlNode Result =
                listService.GetListItems
                    (listName, viewName, query, viewFields, rowLimit, queryOptions, null);

            /*Loop through each node in the XML response and display each item.*/


            XmlDocument NewxmlDoc = new XmlDocument();

            string ListItemsNamespacePrefix = "z";
            string ListItemsNamespaceURI    = "#RowsetSchema";

            string PictureLibrariesNamespacePrefix = "s";
            string PictureLibrariesNamespaceURI    = "uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882";

            string WebPartsNamespacePrefix = "dt";
            string WebPartsNamespaceURI    = "uuid:C2F41010-65B3-11d1-A29F-00AA00C14882";

            string DirectoryNamespacePrefix = "rs";
            string DirectoryNamespaceURI    = "urn:schemas-microsoft-com:rowset";

            //now associate with the xmlns namespaces (part of all XML nodes returned
            //from SharePoint) a namespace prefix which we can then use in the queries
            System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(NewxmlDoc.NameTable);

            nsmgr.AddNamespace(ListItemsNamespacePrefix, ListItemsNamespaceURI);
            nsmgr.AddNamespace(PictureLibrariesNamespacePrefix, PictureLibrariesNamespaceURI);
            nsmgr.AddNamespace(WebPartsNamespacePrefix, WebPartsNamespaceURI);
            nsmgr.AddNamespace(DirectoryNamespacePrefix, DirectoryNamespaceURI);


            XmlNodeList nodeList = Result.SelectNodes("//z:row", nsmgr);


            int test = 1;

            foreach (XmlNode node in nodeList)
            {
                StatusValue += test.ToString() + '-' + node.Attributes["ows_Title"].InnerText;
                test++;
            }

            return(StatusValue);
        }
Exemplo n.º 39
0
        //string parsing for CRMOnline URLs
        static async System.Threading.Tasks.Task <System.Xml.XmlDocument> DoWork2(Uri url)
        {
            System.Xml.XmlDocument _result = new System.Xml.XmlDocument();
            XmlElement             root    = _result.CreateElement("crmonline");

            _result.AppendChild(root);
            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();

            //,downloadData={base_0:{url:"https://download.microsoft.com/download/0/1/8/018E208D-54F8-44CD-AA26-CD7BC9524A8C/PublicIPs_20160418.xml",id:41653,oldid:"9d8be98c-9d86-4068-8a88-51bb2e0d1ca6"}}
            String output;

            using (var stream = await client.GetStreamAsync(url))
            {
                System.IO.StreamReader reader = new System.IO.StreamReader(stream);
                output = reader.ReadToEnd();
            }

            output = RemoveStrayHTML(output);

            //this splits everything into 7 objects
            string[] stringSeparators = new string[] { "<span class='text-base'>" };
            String[] output2          = output.Split(stringSeparators, StringSplitOptions.None);

            //since the first one is all the text *before* the URLs,
            //we can drop the first one
            foreach (String org in output2.Skip(1))
            {
                //now, split it on <br/>
                //skip the first one
                String       url1;
                XmlElement   region     = _result.CreateElement("region");
                XmlAttribute regionname = _result.CreateAttribute("name");
                regionname.Value = org.Substring(0, org.IndexOf("based organizations")).Replace(" area", "").Trim();
                region.Attributes.Append(regionname);

                //build the addresslist type attribute
                XmlElement   addressTypeNode = _result.CreateElement("addresslist");
                XmlAttribute addressTypeName = _result.CreateAttribute("type");
                addressTypeName.Value = "url";
                addressTypeNode.Attributes.Append(addressTypeName);

                foreach (string url0 in org.Split(new string[] { @"<br/>" }, StringSplitOptions.None).Skip(1))
                {
                    if (url0.Length > 0)
                    {
                        url1 = ReplaceNonPrintableCharacters(url0);
                        Debug.WriteLine("org: " + org.Substring(0, org.IndexOf(":")));
                        Debug.WriteLine(url1.IndexOf(@"://"));
                        if (url1.IndexOf(@"://") > 0 && url1.IndexOf(@"://") < 7)
                        {
                            url1 = url1.Substring(url1.IndexOf("h"));
                            XmlElement urlnode = _result.CreateElement("address");
                            urlnode.InnerText = url1;
                            addressTypeNode.AppendChild(urlnode);
                        }
                    }
                }
                region.AppendChild(addressTypeNode);
                root.AppendChild(region);
            }
            return(_result);
        }
Exemplo n.º 40
0
        private void SetSetting(SettingsPropertyValue setProp)
        {
            // Define the XML path under which we want to write our settings if they do not already exist
            XmlNode SettingNode = null;

            try
            {
                // Search for the specific settings node we want to update.
                // If it exists, return its first child node, (the <value>data here</value> node)
                SettingNode = XMLConfig.SelectSingleNode("//setting[@name='" + setProp.Name + "']").FirstChild;
            }
            catch (Exception)
            {
                SettingNode = null;
            }

            // If we have a pointer to an actual XML node, update the value stored there
            if ((SettingNode != null))
            {
                if (setProp.Property.SerializeAs.ToString() == "String")
                {
                    SettingNode.InnerText = setProp.SerializedValue.ToString();
                }
                else
                {
                    // Write the object to the config serialized as Xml - we must remove the Xml declaration when writing
                    // the value, otherwise .Net's configuration system complains about the additional declaration.
                    SettingNode.InnerXml = setProp.SerializedValue.ToString().Replace(@"<?xml version=""1.0"" encoding=""utf-16""?>", "");
                }
            }
            else
            {
                // If the value did not already exist in this settings file, create a new entry for this setting

                // Search for the application settings node (<Appname.Properties.Settings>) and store it.
                XmlNode tmpNode = XMLConfig.SelectSingleNode("//" + APPNODE);

                // Create a new settings node and assign its name as well as how it will be serialized
                XmlElement newSetting = xmlDoc.CreateElement("setting");
                newSetting.SetAttribute("name", setProp.Name);

                if (setProp.Property.SerializeAs.ToString() == "String")
                {
                    newSetting.SetAttribute("serializeAs", "String");
                }
                else
                {
                    newSetting.SetAttribute("serializeAs", "Xml");
                }

                // Append this node to the application settings node (<Appname.Properties.Settings>)
                tmpNode.AppendChild(newSetting);

                // Create an element under our named settings node, and assign it the value we are trying to save
                XmlElement valueElement = xmlDoc.CreateElement("value");
                if (setProp.Property.SerializeAs.ToString() == "String")
                {
                    valueElement.InnerText = setProp.SerializedValue.ToString();
                }
                else
                {
                    // Write the object to the config serialized as Xml - we must remove the Xml declaration when writing
                    // the value, otherwise .Net's configuration system complains about the additional declaration
                    valueElement.InnerXml = setProp.SerializedValue.ToString().Replace(@"<?xml version=""1.0"" encoding=""utf-16""?>", "");
                }

                //Append this new element under the setting node we created above
                newSetting.AppendChild(valueElement);
            }
        }
Exemplo n.º 41
0
        public void NestedFile(ProjectItem projectItem, string itemType, string fileName, string subItemType)
        {
            string projectFileName = projectItem.ContainingProject.FileName;
            var    property        = projectItem.ContainingProject.Properties;
            bool   hasModify       = false;

            if (File.Exists(projectFileName))
            {
                XmlDocument doc = new System.Xml.XmlDocument();
                doc.Load(projectFileName);
                XmlNode compileNode   = doc.SelectSingleNode("/Project/ItemGroup/Compile");
                XmlNode itemGroupNode = null;
                bool    hasItemGroup  = false;
                if (compileNode == null)
                {
                    hasModify     = true;
                    hasItemGroup  = false;
                    itemGroupNode = doc.CreateElement("ItemGroup");
                }
                else
                {
                    hasItemGroup  = true;
                    itemGroupNode = compileNode.ParentNode;
                }

                string  parentFileName         = projectItem.FileNames[0];
                string  parentRelativeFileName = parentFileName.Substring(Path.GetDirectoryName(projectFileName).Length + 1);
                string  parentNodePath         = string.Format("//{0}[@Update='{1}']", itemType, parentRelativeFileName);
                XmlNode parentNode             = doc.SelectSingleNode(parentNodePath);
                if (parentNode == null)
                {
                    hasModify  = true;
                    parentNode = doc.CreateElement(itemType);
                    var updateAttribute = doc.CreateAttribute("Update");
                    updateAttribute.Value = parentRelativeFileName;
                    parentNode.Attributes.Append(updateAttribute);
                    var generatorNode = doc.CreateElement("Generator");
                    parentNode.AppendChild(generatorNode);
                    itemGroupNode.AppendChild(parentNode);
                }

                string  relativeFileName = fileName.Substring(Path.GetDirectoryName(projectFileName).Length + 1);
                string  NeestedNodePath  = string.Format("//{0}[@Update='{1}']", subItemType, relativeFileName);
                XmlNode NestedNode       = itemGroupNode.SelectSingleNode(NeestedNodePath);
                if (NestedNode == null)
                {
                    hasModify = true;
                    var manager = projectItem.ContainingProject.ConfigurationManager;
                    NestedNode = doc.CreateElement(subItemType);
                    var updateAttribute = doc.CreateAttribute("Update");
                    updateAttribute.Value = relativeFileName;
                    NestedNode.Attributes.Append(updateAttribute);
                    NestedNode.InnerXml = string.Format("<DependentUpon>{0}</DependentUpon>", Path.GetFileName(parentFileName));
                    itemGroupNode.AppendChild(NestedNode);
                }
                else
                {
                    XmlNode dependentUponNode = null;
                    dependentUponNode = NestedNode.SelectSingleNode("./DependentUpon");
                    if (dependentUponNode == null)
                    {
                        hasModify                   = true;
                        dependentUponNode           = doc.CreateElement("DependentUpon");
                        dependentUponNode.InnerText = Path.GetFileName(parentFileName);
                        NestedNode.AppendChild(dependentUponNode);
                    }
                    else
                    {
                        if (dependentUponNode.InnerText != Path.GetFileName(parentFileName))
                        {
                            hasModify = true;
                            dependentUponNode.InnerText = Path.GetFileName(parentFileName);
                        }
                    }
                }


                if (!hasItemGroup)
                {
                    doc.DocumentElement.AppendChild(itemGroupNode);
                }
                if (hasModify)
                {
                    doc.Save(projectFileName);
                }
            }
        }
Exemplo n.º 42
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // --- Database initialization ---
        string Path = System.IO.Path.GetDirectoryName(Context.Request.PhysicalPath);

        System.Data.IDbConnection        Conn = null;
        System.Data.Common.DbDataAdapter Sql  = null;
        string SqlStr = "SELECT * FROM TableData";

        System.Reflection.Assembly SQLite = null; // Required only for SQLite database

        if (UseMDB)                               // For MS Acess database
        {
            Conn = new System.Data.OleDb.OleDbConnection("Data Source=\"" + Path + "\\..\\Database.mdb\";Mode=Share Deny None;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Registry Path=;Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Engine Type=5;Provider=\"Microsoft.Jet.OLEDB.4.0\";Jet OLEDB:System database=;Jet OLEDB:SFP=False;persist security info=False;Extended Properties=;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Create System Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;User ID=Admin;Jet OLEDB:Global Bulk Transactions=1");
            Sql  = new System.Data.OleDb.OleDbDataAdapter(SqlStr, (System.Data.OleDb.OleDbConnection)Conn);
        }
        else // For SQLite database
        {
            SQLite = System.Reflection.Assembly.LoadFrom(Path + "\\..\\..\\..\\Server\\SQLite" + (IntPtr.Size == 4 ? "32" : "64") + "\\System.Data.SQLite.DLL");
            Conn   = (System.Data.IDbConnection)Activator.CreateInstance(SQLite.GetType("System.Data.SQLite.SQLiteConnection"), "Data Source=" + Path + "\\..\\Database.db");
            Sql    = (System.Data.Common.DbDataAdapter)Activator.CreateInstance(SQLite.GetType("System.Data.SQLite.SQLiteDataAdapter"), SqlStr, Conn); //*/
        }
        System.Data.DataTable D = new System.Data.DataTable();
        Sql.Fill(D);

        // --- Response initialization ---
        Response.ContentType = "text/html";
        Response.Charset     = "utf-8";
        Response.AppendHeader("Cache-Control", "max-age=1, must-revalidate");
        System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");

        System.Xml.XmlDocument X = new System.Xml.XmlDocument();

        // --- Save data to database ---
        string XML = TGData.Value;

        if (XML != "" && XML != null)
        {
            X.LoadXml(HttpUtility.HtmlDecode(XML));
            System.Xml.XmlNodeList Ch = X.GetElementsByTagName("Changes");
            if (Ch.Count > 0)
            {
                foreach (System.Xml.XmlElement I in Ch[0])
                {
                    string id = I.GetAttribute("id");
                    System.Data.DataRow R;
                    if (I.GetAttribute("Added") == "1")
                    {
                        R       = D.NewRow();
                        R["ID"] = id;
                        D.Rows.Add(R);
                    }
                    else
                    {
                        R = D.Select("[ID]='" + id + "'")[0];
                    }

                    if (I.GetAttribute("Deleted") == "1")
                    {
                        R.Delete();
                    }
                    else if (I.GetAttribute("Added") == "1" || I.GetAttribute("Changed") == "1")
                    {
                        if (I.HasAttribute("Project"))
                        {
                            R["Project"] = I.GetAttribute("Project");
                        }
                        if (I.HasAttribute("Resource"))
                        {
                            R["Resource"] = I.GetAttribute("Resource");
                        }
                        if (I.HasAttribute("Week"))
                        {
                            R["Week"] = System.Double.Parse(I.GetAttribute("Week"));
                        }
                        if (I.HasAttribute("Hours"))
                        {
                            R["Hours"] = System.Double.Parse(I.GetAttribute("Hours"));
                        }
                    }
                }
            }
            if (UseMDB)
            {
                new System.Data.OleDb.OleDbCommandBuilder((System.Data.OleDb.OleDbDataAdapter)Sql);      // For MS Acess database
            }
            else
            {
                Activator.CreateInstance(SQLite.GetType("System.Data.SQLite.SQLiteCommandBuilder"), Sql); // For SQLite database
            }
            Sql.Update(D);                                                                                // Updates changed to database
            D.AcceptChanges();
            X.RemoveAll();
        }

        // --- Load data from database ---
        {
            System.Xml.XmlElement G, BB, B, I;
            G  = X.CreateElement("Grid"); X.AppendChild(G);
            BB = X.CreateElement("Body"); G.AppendChild(BB);
            B  = X.CreateElement("B"); BB.AppendChild(B);
            foreach (System.Data.DataRow R in D.Rows)
            {
                I = X.CreateElement("I");
                B.AppendChild(I);
                I.SetAttribute("id", R[0].ToString());
                I.SetAttribute("Project", R[1].ToString());
                I.SetAttribute("Resource", R[2].ToString());
                I.SetAttribute("Week", R[3].ToString());
                I.SetAttribute("Hours", R[4].ToString());
            }
            TGData.Value = X.InnerXml;
        }
    }
Exemplo n.º 43
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            // By default (false) it uses SQLite database (Database.db). You can switch to MS Access database (Database.mdb) by setting UseMDB = true
            // The SQLite loads dynamically its DLL from TreeGrid distribution, it chooses 32bit or 64bit assembly
            // The MDB can be used only on 32bit IIS mode !!! The ASP.NET service program must have write access to the Database.mdb file !!!
            bool UseMDB = false;

            // --- Response initialization ---
            Response.ContentType = "text/xml";
            Response.Charset     = "utf-8";
            Response.AppendHeader("Cache-Control", "max-age=1, must-revalidate");
            System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");

            // --- Database initialization ---
            string Path = System.IO.Path.GetDirectoryName(Context.Request.PhysicalPath);
            System.Data.IDbConnection           Conn = null;
            System.Data.Common.DbDataAdapter    Sql  = null;
            System.Data.Common.DbCommandBuilder Bld  = null;
            string SqlStr = "SELECT * FROM TableData";
            System.Reflection.Assembly SQLite = null; // Required only for SQLite database

            if (UseMDB)                               // For MS Acess database
            {
                Conn = new System.Data.OleDb.OleDbConnection("Data Source=\"" + Path + "\\..\\Database.mdb\";Mode=Share Deny None;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Registry Path=;Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Engine Type=5;Provider=\"Microsoft.Jet.OLEDB.4.0\";Jet OLEDB:System database=;Jet OLEDB:SFP=False;persist security info=False;Extended Properties=;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Create System Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;User ID=Admin;Jet OLEDB:Global Bulk Transactions=1");
                Sql  = new System.Data.OleDb.OleDbDataAdapter(SqlStr, (System.Data.OleDb.OleDbConnection)Conn);
            }
            else // For SQLite database
            {
                SQLite = System.Reflection.Assembly.LoadFrom(Path + "\\..\\..\\..\\Server\\SQLite" + (IntPtr.Size == 4 ? "32" : "64") + "\\System.Data.SQLite.DLL");
                Conn   = (System.Data.IDbConnection)Activator.CreateInstance(SQLite.GetType("System.Data.SQLite.SQLiteConnection"), "Data Source=" + Path + "\\..\\Database.db");
                Sql    = (System.Data.Common.DbDataAdapter)Activator.CreateInstance(SQLite.GetType("System.Data.SQLite.SQLiteDataAdapter"), SqlStr, Conn); //*/
            }

            System.Data.DataTable D = new System.Data.DataTable();
            Sql.Fill(D);

            // --- Save data to database ---
            System.Xml.XmlDocument X = new System.Xml.XmlDocument();
            string XML = Request["TGData"];
            if (XML != "" && XML != null)
            {
                X.LoadXml(HttpUtility.HtmlDecode(XML));
                System.Xml.XmlNodeList Ch = X.GetElementsByTagName("Changes");
                if (Ch.Count > 0)
                {
                    foreach (System.Xml.XmlElement I in Ch[0])
                    {
                        string id = I.GetAttribute("id");
                        System.Data.DataRow R;
                        if (I.GetAttribute("Added") == "1")
                        {
                            R       = D.NewRow();
                            R["ID"] = id;
                            D.Rows.Add(R);
                        }
                        else
                        {
                            R = D.Select("[ID]='" + id + "'")[0];
                        }

                        if (I.GetAttribute("Deleted") == "1")
                        {
                            R.Delete();
                        }
                        else if (I.GetAttribute("Added") == "1" || I.GetAttribute("Changed") == "1")
                        {
                            if (I.HasAttribute("Project"))
                            {
                                R["Project"] = I.GetAttribute("Project");
                            }
                            if (I.HasAttribute("Resource"))
                            {
                                R["Resource"] = I.GetAttribute("Resource");
                            }
                            if (I.HasAttribute("Week"))
                            {
                                R["Week"] = System.Double.Parse(I.GetAttribute("Week"));
                            }
                            if (I.HasAttribute("Hours"))
                            {
                                R["Hours"] = System.Double.Parse(I.GetAttribute("Hours"));
                            }
                        }
                    }
                }

                if (UseMDB)
                {
                    new System.Data.OleDb.OleDbCommandBuilder((System.Data.OleDb.OleDbDataAdapter)Sql);     // For MS Acess database
                }
                else
                {
                    Activator.CreateInstance(SQLite.GetType("System.Data.SQLite.SQLiteCommandBuilder"), Sql); // For SQLite database
                }
                Sql.Update(D);                                                                                // Updates changed to database
                D.AcceptChanges();
                X.RemoveAll();
                Response.Write("<Grid><IO Result='0'/></Grid>");
            }

            // --- Load data from database ---
            else
            {
                System.Xml.XmlElement G, BB, B, I;
                G  = X.CreateElement("Grid"); X.AppendChild(G);
                BB = X.CreateElement("Body"); G.AppendChild(BB);
                B  = X.CreateElement("B"); BB.AppendChild(B);
                foreach (System.Data.DataRow R in D.Rows)
                {
                    I = X.CreateElement("I");
                    B.AppendChild(I);
                    I.SetAttribute("id", R[0].ToString());
                    I.SetAttribute("Project", R[1].ToString());
                    I.SetAttribute("Resource", R[2].ToString());
                    I.SetAttribute("Week", R[3].ToString());
                    I.SetAttribute("Hours", R[4].ToString());
                }
                Response.Write(X.InnerXml);
            }
        }  catch (Exception E)
        {
            Response.Write("<Grid><IO Result=\"-1\" Message=\"Error in TreeGrid example:&#x0a;&#x0a;" + E.Message.Replace("&", "&amp;").Replace("<", "&lt;").Replace("\"", "&quot;") + "\"/></Grid>");
        }
    }
        public string createXMLBatchPost()
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", null));
            //create nodes
            System.Xml.XmlElement root = doc.CreateElement("batch");

            //"    <username>" & username & "</username>" &
            //"    <password>" & password & "</password>" &
            //"    <filename>" & fileName & "</filename>" &
            //"    <appSignature>MyTest App</appSignature>" &
            System.Xml.XmlElement attr = doc.CreateElement("username");
            attr.InnerXml = this._username;
            root.AppendChild(attr);

            attr          = doc.CreateElement("password");
            attr.InnerXml = this._password;
            root.AppendChild(attr);

            attr          = doc.CreateElement("filename");
            attr.InnerXml = this.pdf;
            root.AppendChild(attr);


            attr          = doc.CreateElement("appSignature");
            attr.InnerXml = ".NET SDK API";
            root.AppendChild(attr);
            foreach (batchJob b in jobList)
            {
                dynamic job = doc.CreateElement("job");

                attr          = doc.CreateElement("startingPage");
                attr.InnerXml = b.startingPage.ToString();
                job.AppendChild(attr);

                attr          = doc.CreateElement("endingPage");
                attr.InnerXml = b.endingPage.ToString();
                job.AppendChild(attr);

                dynamic printProductIOptions = doc.CreateElement("printProductionOptions");
                job.AppendChild(printProductIOptions);
                //<documentClass>Letter 8.5 x 11</documentClass>" &
                //"            <layout>Address on First Page</layout>" &
                //"            <productionTime>Next Day</productionTime>" &
                //"            <envelope>#10 Double Window</envelope>" &
                //"            <color>Full Color</color>" &
                //"            <paperType>White 24#</paperType>" &
                //"            <printOption>Printing One side</printOption>" &
                //"            <mailClass>First Class</mailClass>" &
                attr          = doc.CreateElement("documentClass");
                attr.InnerXml = b.documentClass;
                printProductIOptions.AppendChild(attr);

                attr          = doc.CreateElement("layout");
                attr.InnerXml = b.layout;
                printProductIOptions.AppendChild(attr);

                attr          = doc.CreateElement("productionTime");
                attr.InnerXml = b.productionTime;
                printProductIOptions.AppendChild(attr);
                attr          = doc.CreateElement("envelope");
                attr.InnerXml = b.envelope;
                printProductIOptions.AppendChild(attr);
                attr          = doc.CreateElement("color");
                attr.InnerXml = b.color;
                printProductIOptions.AppendChild(attr);

                attr          = doc.CreateElement("paperType");
                attr.InnerXml = b.paperType;
                printProductIOptions.AppendChild(attr);
                attr          = doc.CreateElement("printOption");
                attr.InnerXml = b.printOption;
                printProductIOptions.AppendChild(attr);
                attr          = doc.CreateElement("mailClass");
                attr.InnerXml = b.mailClass;
                printProductIOptions.AppendChild(attr);

                XmlElement addressList = doc.CreateElement("recipients");
                job.AppendChild(addressList);
                foreach (addressItem ai in b.addressList)
                {
                    XmlElement address = doc.CreateElement("address");
                    addressList.AppendChild(address);
                    attr = doc.CreateElement("name");
                    if ((ai._First_name.Length > 0 & ai._Last_name.Length > 0))
                    {
                        attr.InnerText = ai._Last_name + ", " + ai._First_name;
                    }
                    else
                    {
                        attr.InnerText = (ai._First_name + " " + ai._Last_name).Trim();
                    }
                    address.AppendChild(attr);

                    attr           = doc.CreateElement("organization");
                    attr.InnerText = ai._Organization.Trim();
                    address.AppendChild(attr);

                    attr           = doc.CreateElement("address1");
                    attr.InnerText = ai._Address1.Trim();
                    address.AppendChild(attr);

                    attr           = doc.CreateElement("address2");
                    attr.InnerText = ai._Address2.Trim();
                    address.AppendChild(attr);

                    attr           = doc.CreateElement("address3");
                    attr.InnerText = "";
                    address.AppendChild(attr);

                    attr           = doc.CreateElement("city");
                    attr.InnerText = ai._City.Trim();
                    address.AppendChild(attr);

                    attr           = doc.CreateElement("state");
                    attr.InnerText = ai._State.Trim();
                    address.AppendChild(attr);

                    attr           = doc.CreateElement("postalCode");
                    attr.InnerText = ai._Zip.Trim();;
                    address.AppendChild(attr);

                    attr           = doc.CreateElement("country");
                    attr.InnerText = (ai._Country_nonUS).Trim();;
                    address.AppendChild(attr);
                }
                root.AppendChild(job);
            }

            doc.AppendChild(root);

            //doc.Declaration = New XDeclaration("1.0", "utf-8", Nothing)
            string xmlString = null;

            using (StringWriter stringWriter = new StringWriter())
            {
                using (XmlWriter xmlTextWriter = XmlWriter.Create(stringWriter))
                {
                    doc.WriteTo(xmlTextWriter);
                    xmlTextWriter.Flush();

                    xmlString = stringWriter.GetStringBuilder().ToString();
                }
            }



            return(xmlString);
        }
Exemplo n.º 45
0
        private void GenerateContent()
        {
            try
            {
                //var sortedList = new SortedList<int, Guid>();
                //var remainder = new List<Guid>();

                //foreach (var item in _model.Database.CustomStoredProcedures.ToList())
                //{
                //  if (!sortedList.Keys.Contains(item.PrecedenceOrder))
                //    sortedList.Add(item.PrecedenceOrder, new Guid(item.Key));
                //  else
                //    remainder.Add(new Guid(item.Key));
                //}
                //foreach (var item in _model.Database.CustomViews.ToList())
                //{
                //  if (!sortedList.Keys.Contains(item.PrecedenceOrder))
                //    sortedList.Add(item.PrecedenceOrder, new Guid(item.Key));
                //  else
                //    remainder.Add(new Guid(item.Key));
                //}
                //foreach (var item in _model.Database.Functions.ToList())
                //{
                //  if (!sortedList.Keys.Contains(item.PrecedenceOrder))
                //    sortedList.Add(item.PrecedenceOrder, new Guid(item.Key));
                //  else
                //    remainder.Add(new Guid(item.Key));
                //}

                //var index = 0;
                //if (sortedList.Keys.Count > 0)
                //  index = sortedList.Keys.Max();

                //foreach (var item in remainder)
                //  sortedList.Add(++index, item);

                //var document = new System.Xml.XmlDocument();
                //document.LoadXml("<root type=\"installer\"></root>");
                //XmlHelper.AddLineBreak(document.DocumentElement);
                //foreach (var k in sortedList.Keys)
                //{
                //  var n = document.CreateElement("key");
                //  n.InnerText = sortedList[k].ToString();
                //  document.DocumentElement.AppendChild(n);
                //  XmlHelper.AddLineBreak(document.DocumentElement);
                //}
                //sb.Append(document.OuterXml);


                var document = new System.Xml.XmlDocument();
                document.LoadXml("<root type=\"installer\"></root>");
                XmlHelper.AddLineBreak(document.DocumentElement);
                if (_model.Database.PrecedenceOrderList != null)
                {
                    foreach (var k in _model.Database.PrecedenceOrderList)
                    {
                        var n = document.CreateElement("key");
                        n.InnerText = k.ToString();
                        document.DocumentElement.AppendChild(n);
                        XmlHelper.AddLineBreak(document.DocumentElement);
                    }
                }
                sb.Append(document.OuterXml);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Exemplo n.º 46
0
        public override bool Update(System.Xml.XmlDocument document)
        {
            List <System.Xml.XmlNode> nodes = new List <System.Xml.XmlNode>();

            Action <System.Xml.XmlNode> collectNodes = null;

            collectNodes = (node) =>
            {
                if (node.Name == "Node")
                {
                    nodes.Add(node);
                }

                for (int i = 0; i < node.ChildNodes.Count; i++)
                {
                    collectNodes(node.ChildNodes[i]);
                }
            };

            collectNodes((XmlNode)document);

            foreach (var node in nodes)
            {
                var labs = node["LocationAbsValues"];

                if (labs != null)
                {
                    // old gravity and attractive force to new
                    if (labs["Type"] != null && labs["Type"].GetTextAsInt() != 0)
                    {
                        var lff = document.CreateElement("LocalForceField4");

                        var type = labs["Type"].GetTextAsInt();
                        if (type == 1)
                        {
                            lff.AppendChild(document.CreateTextElement("Type", (int)LocalForceFieldType.Gravity));
                        }
                        else if (type == 2)
                        {
                            lff.AppendChild(document.CreateTextElement("Type", (int)LocalForceFieldType.AttractiveForce));
                        }

                        if (labs["Gravity"] != null)
                        {
                            lff.AppendChild(labs["Gravity"]);
                        }

                        if (labs["AttractiveForce"] != null)
                        {
                            lff.AppendChild(labs["AttractiveForce"]);

                            if (lff["AttractiveForce"]["Force"] != null)
                            {
                                var force = lff["AttractiveForce"]["Force"].GetTextAsFloat();
                                lff.AppendChild(document.CreateTextElement("Power", force.ToString()));
                            }
                        }

                        labs.AppendChild(lff);
                    }

                    Action <XmlElement> convert = (elm) =>
                    {
                        if (elm == null)
                        {
                            return;
                        }

                        var typeInt = elm["Type"]?.GetTextAsInt();
                        var type    = typeInt.HasValue ? (Data.LocalForceFieldType)(typeInt.Value) : Data.LocalForceFieldType.None;

                        if (type == LocalForceFieldType.Turbulence)
                        {
                            if (elm["Turbulence"] != null && elm["Turbulence"]["Strength"] != null)
                            {
                                var strength = elm["Turbulence"]["Strength"].GetTextAsFloat();
                                elm.AppendChild(document.CreateTextElement("Power", strength.ToString()));
                            }
                        }

                        float defaultPower = 1.0f;

                        if (type == LocalForceFieldType.Turbulence)
                        {
                            defaultPower = 0.1f;
                        }

                        if (elm["Power"] != null)
                        {
                            defaultPower = elm["Power"].GetTextAsFloat();
                        }

                        if (type == LocalForceFieldType.Turbulence)
                        {
                            defaultPower *= 10.0f;
                        }

                        if (type == LocalForceFieldType.Vortex)
                        {
                            defaultPower /= 5.0f;
                        }

                        if (elm["Power"] != null)
                        {
                            elm.RemoveChild(elm["Power"]);
                        }

                        elm.AppendChild(document.CreateTextElement("Power", defaultPower.ToString()));

                        if (type == LocalForceFieldType.Vortex)
                        {
                            if (elm["Vortex"] == null)
                            {
                                elm.AppendChild(document.CreateElement("Vortex"));
                            }

                            elm["Vortex"].AppendChild(document.CreateTextElement("VortexType", ((int)ForceFieldVortexType.ConstantSpeed).ToString()));
                        }

                        if (type == LocalForceFieldType.Turbulence)
                        {
                            if (elm["Turbulence"] == null)
                            {
                                elm.AppendChild(document.CreateElement("Turbulence"));
                            }

                            elm["Turbulence"].AppendChild(document.CreateTextElement("TurbulenceType", ((int)ForceFieldTurbulenceType.Complicated).ToString()));
                        }
                    };

                    convert(labs["LocalForceField1"]);
                    convert(labs["LocalForceField2"]);
                    convert(labs["LocalForceField3"]);
                }
            }

            return(true);
        }
Exemplo n.º 47
0
        public override bool Update(System.Xml.XmlDocument document)
        {
            List <System.Xml.XmlNode> nodes = new List <System.Xml.XmlNode>();

            Action <System.Xml.XmlNode> collectNodes = null;

            collectNodes = (node) =>
            {
                if (node.Name == "Node")
                {
                    nodes.Add(node);
                }

                for (int i = 0; i < node.ChildNodes.Count; i++)
                {
                    collectNodes(node.ChildNodes[i]);
                }
            };

            collectNodes((XmlNode)document);

            foreach (var node in nodes)
            {
                var rcv1 = node["AdvancedRendererCommonValuesValues"];
                if (rcv1 != null)
                {
                    var enableAlphaTexture = rcv1["EnableAlphaTexture"];
                    if (enableAlphaTexture != null)
                    {
                        var alphaTextureParam = rcv1["AlphaTextureParam"] as XmlNode;
                        alphaTextureParam?.PrependChild(document.CreateTextElement("Enabled", enableAlphaTexture.InnerText));
                    }

                    var enableUVDistortion = rcv1["EnableUVDistortion"];
                    if (enableUVDistortion != null)
                    {
                        var uvDistortionParam = rcv1["UVDistortionParam"] as XmlNode;
                        uvDistortionParam?.PrependChild(document.CreateTextElement("Enabled", enableUVDistortion.InnerText));
                    }

                    var alphaCutoffParam = rcv1["AlphaCutoffParam"] as XmlNode;
                    if (alphaCutoffParam != null)
                    {
                        var  typeNode          = alphaCutoffParam["Type"];
                        var  fixedNode         = alphaCutoffParam["Fixed"];
                        bool enableAlphaCutoff =
                            (typeNode != null && int.Parse(typeNode.InnerText) != 0) ||
                            (fixedNode != null && float.Parse(fixedNode["Threshold"].InnerText) != 0.0f);
                        alphaCutoffParam.PrependChild(document.CreateTextElement("Enabled", enableAlphaCutoff.ToString()));
                    }

                    var enableFalloff = rcv1["EnableFalloff"];
                    if (enableFalloff != null)
                    {
                        var falloffParam = rcv1["FalloffParam"] as XmlNode;
                        falloffParam.PrependChild(document.CreateTextElement("Enabled", enableFalloff.InnerText));
                    }

                    var softParticleDistance           = rcv1["SoftParticleDistance"];
                    var softParticleDistanceNear       = rcv1["SoftParticleDistanceNear"];
                    var softParticleDistanceNearOffset = rcv1["SoftParticleDistanceNearOffset"];

                    if (softParticleDistance != null || softParticleDistanceNear != null || softParticleDistanceNearOffset != null)
                    {
                        var softParticleParams = document.CreateElement("SoftParticleParams");

                        if (softParticleDistance != null)
                        {
                            softParticleParams.AppendChild(document.CreateTextElement("Enabled", (softParticleDistance.GetTextAsFloat() != 0.0f).ToString()));
                            softParticleParams.AppendChild(document.CreateTextElement("Distance", softParticleDistance.InnerText));
                        }
                        if (softParticleDistanceNear != null)
                        {
                            softParticleParams.AppendChild(document.CreateTextElement("DistanceNear", softParticleDistanceNear.InnerText));
                        }
                        if (softParticleDistanceNearOffset != null)
                        {
                            softParticleParams.AppendChild(document.CreateTextElement("DistanceNearOffset", softParticleDistanceNearOffset.InnerText));
                        }

                        rcv1.AppendChild(softParticleParams);
                    }
                }

                var rcv2 = node["AdvancedRendererCommonValues2Values"];
                if (rcv2 != null)
                {
                    node.RemoveChild(rcv2);

                    if (rcv1 == null)
                    {
                        rcv1 = document.CreateElement("AdvancedRendererCommonValuesValues");
                        node.AppendChild(rcv1);
                    }

                    var blendTextureParams = rcv2["BlendTextureParams"];
                    var enableBlendTexture = rcv2["EnableBlendTexture"];

                    if (enableBlendTexture != null && blendTextureParams != null)
                    {
                        rcv2.RemoveChild(blendTextureParams);
                        rcv2.RemoveChild(enableBlendTexture);
                        blendTextureParams.AppendChild(document.CreateTextElement("Enabled", enableBlendTexture.InnerText));
                        rcv1.AppendChild(blendTextureParams);
                    }
                }
            }

            return(true);
        }
Exemplo n.º 48
0
        public override bool Update(System.Xml.XmlDocument document)
        {
            var proceduralElement = document["EffekseerProject"]["ProcedualModel"];

            if (proceduralElement != null)
            {
                document["EffekseerProject"].RemoveChild(proceduralElement);
                var newNode  = document.CreateElement("ProceduralModel");
                var newNode2 = document.CreateElement("ProceduralModels");
                newNode.AppendChild(newNode2);

                List <XmlNode> children = new List <XmlNode>();

                for (int i = 0; i < proceduralElement.FirstChild.ChildNodes.Count; i++)
                {
                    children.Add(proceduralElement.FirstChild.ChildNodes[i]);
                }

                foreach (var child in children)
                {
                    Action <XmlNode, XmlNode, string> moveElement = (XmlNode dst, XmlNode src, string name) =>
                    {
                        var node = src[name];
                        if (node != null)
                        {
                            dst.AppendChild(node);
                        }
                    };

                    Action <XmlNode, XmlNode, string, string> moveAndRenameElement = (XmlNode dst, XmlNode src, string newName, string name) =>
                    {
                        var node = src[name];
                        if (node != null)
                        {
                            src.RemoveChild(node);

                            var nn = document.CreateElement(newName);
                            while (node.ChildNodes.Count > 0)
                            {
                                nn.AppendChild(node.FirstChild);
                            }
                            dst.AppendChild(nn);
                        }
                    };

                    var mesh        = document.CreateElement("Mesh");
                    var ribbon      = document.CreateElement("Ribbon");
                    var shape       = document.CreateElement("Shape");
                    var shapeNoise  = document.CreateElement("ShapeNoise");
                    var vertexColor = document.CreateElement("VertexColor");

                    moveElement(mesh, child, "AngleBeginEnd");
                    moveElement(mesh, child, "Divisions");

                    moveElement(ribbon, child, "CrossSection");
                    moveElement(ribbon, child, "Rotate");
                    moveElement(ribbon, child, "Vertices");
                    moveElement(ribbon, child, "RibbonScales");
                    moveElement(ribbon, child, "RibbonAngles");
                    moveElement(ribbon, child, "RibbonNoises");
                    moveElement(ribbon, child, "Count");

                    moveElement(shape, child, "PrimitiveType");
                    moveElement(shape, child, "Radius");
                    moveElement(shape, child, "Radius2");
                    moveElement(shape, child, "Depth");
                    moveElement(shape, child, "DepthMin");
                    moveElement(shape, child, "DepthMax");
                    moveElement(shape, child, "Point1");
                    moveElement(shape, child, "Point2");
                    moveElement(shape, child, "Point3");
                    moveElement(shape, child, "Point4");
                    moveElement(shape, child, "AxisType");

                    moveElement(shapeNoise, child, "TiltNoiseFrequency");
                    moveElement(shapeNoise, child, "TiltNoiseOffset");
                    moveElement(shapeNoise, child, "TiltNoisePower");
                    moveElement(shapeNoise, child, "WaveNoiseFrequency");
                    moveElement(shapeNoise, child, "WaveNoiseOffset");
                    moveElement(shapeNoise, child, "WaveNoisePower");
                    moveElement(shapeNoise, child, "CurlNoiseFrequency");
                    moveElement(shapeNoise, child, "CurlNoiseOffset");
                    moveElement(shapeNoise, child, "CurlNoisePower");

                    moveAndRenameElement(vertexColor, child, "ColorUpperLeft", "ColorLeft");
                    moveAndRenameElement(vertexColor, child, "ColorUpperCenter", "ColorCenter");
                    moveAndRenameElement(vertexColor, child, "ColorUpperRight", "ColorRight");
                    moveAndRenameElement(vertexColor, child, "ColorMiddleLeft", "ColorLeftMiddle");
                    moveAndRenameElement(vertexColor, child, "ColorMiddleCenter", "ColorCenterMiddle");
                    moveAndRenameElement(vertexColor, child, "ColorMiddleRight", "ColorRightMiddle");
                    moveElement(vertexColor, child, "ColorCenterArea");

                    child.AppendChild(mesh);
                    child.AppendChild(ribbon);
                    child.AppendChild(shape);
                    child.AppendChild(shapeNoise);
                    child.AppendChild(vertexColor);

                    newNode2.AppendChild(child);
                }

                document["EffekseerProject"].AppendChild(newNode);
            }
            return(true);
        }
        protected void GCheckoutButton_Click(object sender, ImageClickEventArgs e)
        {
            if (_BasketGrid != null)
            {
                //First Save the updated Basket
                AbleCommerce.Code.BasketHelper.SaveBasket(_BasketGrid);
            }

            GCheckoutButton.Currency = AbleContext.Current.Store.BaseCurrency.ISOCode;
            CheckoutShoppingCartRequest Req = GCheckoutButton.CreateRequest();

            System.Xml.XmlDocument tempDoc = new System.Xml.XmlDocument();

            Basket basket = AbleContext.Current.User.Basket;

            // Add a "BasketId" node.
            System.Xml.XmlNode tempNode2 = tempDoc.CreateElement("BasketId");
            tempNode2.InnerText = basket.Id.ToString();
            Req.AddMerchantPrivateDataNode(tempNode2);

            tempNode2           = tempDoc.CreateElement("BasketContentHash");
            tempNode2.InnerText = GetBasketContentHash(basket);
            Req.AddMerchantPrivateDataNode(tempNode2);

            // We just created this structure on the order level:
            // <merchant-private-data>
            //   <BasketId xmlns="">xxxxxx</BasketId>
            // </merchant-private-data>

            // Now we are going to add the basket items.
            XmlNode[] itemPrivateData;
            foreach (BasketItem item in basket.Items)
            {
                switch (item.OrderItemType)
                {
                case OrderItemType.Product:
                    itemPrivateData = BuildPrivateData(item);
                    bool isDigitalContent = item.Product == null ? false : item.Product.IsDigitalGood;
                    if (isDigitalContent)
                    {
                        Req.AddItem(AcHelper.SanitizeText(item.Name), AcHelper.SanitizeText(item.Product.Description), (Decimal)item.Price, item.Quantity, isDigitalContent, AcHelper.SanitizeText(string.Format("The download will be available from your {0} order receipt once payment is processed.", AbleContext.Current.Store.Name)), itemPrivateData);
                    }
                    else
                    {
                        Req.AddItem(AcHelper.SanitizeText(item.Name), AcHelper.SanitizeText(item.Product.Description), (Decimal)item.Price, item.Quantity, itemPrivateData);
                    }
                    break;

                case OrderItemType.Charge:
                    itemPrivateData = BuildPrivateData(item);
                    Req.AddItem(AcHelper.SanitizeText(item.Name), "Charge", (Decimal)item.Price, item.Quantity, itemPrivateData);
                    break;

                case OrderItemType.Credit:
                    itemPrivateData = BuildPrivateData(item);
                    Req.AddItem(AcHelper.SanitizeText(item.Name), "Credit", (Decimal)item.Price, item.Quantity, itemPrivateData);
                    break;

                case OrderItemType.GiftWrap:
                    itemPrivateData = BuildPrivateData(item);
                    Req.AddItem(AcHelper.SanitizeText(item.Name), "Gift Wrapping", (Decimal)item.Price, item.Quantity, itemPrivateData);
                    break;

                case OrderItemType.Coupon:     //on callback as well
                    itemPrivateData = BuildPrivateData(item);
                    Req.AddItem(AcHelper.SanitizeText(item.Name), "Your coupon has been applied.", (Decimal)item.Price, item.Quantity, itemPrivateData);
                    break;

                case OrderItemType.Discount:
                    itemPrivateData = BuildPrivateData(item);
                    Req.AddItem(AcHelper.SanitizeText(item.Name), "Discount", (Decimal)item.Price, item.Quantity, itemPrivateData);
                    break;

                case OrderItemType.GiftCertificate:     //on callback
                    break;

                case OrderItemType.Handling:     //on callback
                    break;

                case OrderItemType.Shipping:     //on callback
                    break;

                case OrderItemType.Tax:     //on callback
                    break;
                }
            }

            //setup other settings
            Req.AcceptMerchantCoupons          = GCheckoutButton.GatewayInstance.CouponsEnabled;
            Req.AcceptMerchantGiftCertificates = GCheckoutButton.GatewayInstance.GiftCertificatesEnabled;
            //Req.CartExpiration = expirationDate;
            string storeDomain  = UrlHelper.GetDomainFromUrl(AbleContext.Current.Store.StoreUrl);
            string storeBaseUrl = "http://" + storeDomain;

            Req.ContinueShoppingUrl   = storeBaseUrl + this.ResolveUrl("~/Default.aspx");
            Req.EditCartUrl           = storeBaseUrl + this.ResolveUrl("~/Basket.aspx");
            Req.MerchantCalculatedTax = true;
            //add at least one tax rule
            Req.AddZipTaxRule("99999", 0F, false);
            string storeBaseSecureUrl = AbleContext.Current.Store.Settings.SSLEnabled ? storeBaseUrl.Replace("http://", "https://") : storeBaseUrl;

            Req.MerchantCalculationsUrl = storeBaseSecureUrl + this.ResolveUrl("~/Checkout/Google/MerchantCalc.ashx");
            Req.PlatformID = 769150108975916;
            Req.RequestBuyerPhoneNumber = true;
            Req.SetExpirationMinutesFromNow(GCheckoutButton.GatewayInstance.ExpirationMinutes);

            //add ship methods
            IList <ShipMethod>   shipMethods      = ShipMethodDataSource.LoadAll();
            List <string>        shipMethodsAdded = new List <string>();
            string               shipMethName;
            decimal              basketTotal      = basket.Items.TotalPrice();
            decimal              defaultRate      = GCheckoutButton.GatewayInstance.DefaultShipRate;
            ShippingRestrictions shipRestrictions = new ShippingRestrictions();

            shipRestrictions.AddAllowedWorldArea();

            foreach (ShipMethod shipMethod in shipMethods)
            {
                if (!shipMethod.Name.Equals("Unknown(GoogleCheckout)") &&
                    (shipMethod.MinPurchase <= 0 || shipMethod.MinPurchase <= basketTotal))
                {
                    //add all other shipmethods as merchant calculated irrespective of whether they
                    //are applicable or not. It will be determined on call-back
                    //GoogleCheckout does not allow to mix merchant calculated shipping methods with other methods
                    if (shipMethod.ShipMethodType == ShipMethodType.FlatRate)
                    {
                        defaultRate = GetFlatShipRate(shipMethod);
                    }
                    else
                    {
                        defaultRate = GCheckoutButton.GatewayInstance.DefaultShipRate;
                    }
                    shipMethName = BuildShipMethodName(shipMethod, shipMethodsAdded);
                    Req.AddMerchantCalculatedShippingMethod(shipMethName, defaultRate, shipRestrictions, shipRestrictions);
                    shipMethodsAdded.Add(shipMethName.ToLowerInvariant());
                }
            }

            GCheckoutResponse Resp = Req.Send();

            if (Resp.IsGood)
            {
                Response.Redirect(Resp.RedirectUrl, true);
            }
            else
            {
                DataList msgList;
                if (_WarningMessageList != null)
                {
                    msgList = _WarningMessageList;
                }
                else
                {
                    msgList            = GCWarningMessageList;
                    phWarnings.Visible = true;
                }
                if (msgList != null)
                {
                    List <string> googleMessages = new List <string>();
                    googleMessages.Add("Google Checkout Failed.");
                    googleMessages.Add("Google Checkout Response.IsGood = " + Resp.IsGood);
                    googleMessages.Add("Google Checkout Error Message = " + Resp.ErrorMessage);
                    msgList.DataSource = googleMessages;
                    msgList.DataBind();
                }
            }
        }
        /// <summary>
        /// Configure the panel
        /// </summary>
        /// <param name="configurationDom"></param>
        public void Configure(System.Xml.XmlDocument configurationDom)
        {
            if (this.m_configuration.Services.Count == 0)
            {
                return; // No active configurations
            }
            XmlElement configSectionsNode = configurationDom.SelectSingleNode("//*[local-name() = 'configSections']") as XmlElement,
                       hapiNode           = configurationDom.SelectSingleNode("//*[local-name() = 'marc.hi.ehrs.cr.messaging.hl7']") as XmlElement,
                       multiNode          = configurationDom.SelectSingleNode("//*[local-name() = 'marc.hi.ehrs.svc.messaging.multi']") as XmlElement,
                       coreNode           = configurationDom.SelectSingleNode("//*[local-name() = 'marc.hi.ehrs.svc.core']") as XmlElement;

            Type mmhType       = Type.GetType("MARC.HI.EHRS.SVC.Messaging.Multi.MultiMessageHandler, MARC.HI.EHRS.SVC.Messaging.Multi"),
                 mmhConfigType = Type.GetType("MARC.HI.EHRS.SVC.Messaging.Multi.Configuration.ConfigurationSectionHandler, MARC.HI.EHRS.SVC.Messaging.Multi");

            // Ensure the assembly is loaded and the provider registered
            if (coreNode == null)
            {
                coreNode = configurationDom.CreateElement("marc.hi.ehrs.svc.core");
                configurationDom.DocumentElement.AppendChild(coreNode);
            }

            // Config sections node
            if (configSectionsNode == null)
            {
                configSectionsNode = configurationDom.CreateElement("configSections");
                configurationDom.DocumentElement.PrependChild(configSectionsNode);
            }
            XmlElement configSectionNode = configSectionsNode.SelectSingleNode("./*[local-name() = 'section'][@name = 'marc.hi.ehrs.cr.messaging.hl7']") as XmlElement;

            if (configSectionNode == null)
            {
                configSectionNode = configurationDom.CreateElement("section");
                configSectionNode.Attributes.Append(configurationDom.CreateAttribute("name"));
                configSectionNode.Attributes.Append(configurationDom.CreateAttribute("type"));
                configSectionNode.Attributes["name"].Value = "marc.hi.ehrs.cr.messaging.hl7";
                configSectionNode.Attributes["type"].Value = typeof(ConfigurationSectionHandler).AssemblyQualifiedName;
                configSectionsNode.AppendChild(configSectionNode);
            }

            configSectionNode = configSectionsNode.SelectSingleNode("./*[local-name() = 'section'][@name = 'marc.hi.ehrs.svc.messaging.multi']") as XmlElement;
            if (configSectionNode == null && mmhConfigType != null)
            {
                configSectionNode = configurationDom.CreateElement("section");
                configSectionNode.Attributes.Append(configurationDom.CreateAttribute("name"));
                configSectionNode.Attributes.Append(configurationDom.CreateAttribute("type"));
                configSectionNode.Attributes["name"].Value = "marc.hi.ehrs.svc.messaging.multi";
                configSectionNode.Attributes["type"].Value = mmhConfigType.AssemblyQualifiedName;
                configSectionsNode.AppendChild(configSectionNode);
            }

            // Persistence section node
            if (hapiNode == null)
            {
                hapiNode = configurationDom.CreateElement("marc.hi.ehrs.cr.messaging.hl7");
                configurationDom.DocumentElement.AppendChild(hapiNode);
            }
            XmlElement servicesNode = hapiNode.SelectSingleNode("./*[local-name() = 'services']") as XmlElement;

            if (servicesNode == null)
            {
                servicesNode = hapiNode.AppendChild(configurationDom.CreateElement("services")) as XmlElement;
            }

            XmlElement serviceAssemblyNode = coreNode.SelectSingleNode("./*[local-name() = 'serviceAssemblies']") as XmlElement,
                       serviceProviderNode = coreNode.SelectSingleNode("./*[local-name() = 'serviceProviders']") as XmlElement;

            if (serviceAssemblyNode == null)
            {
                serviceAssemblyNode = configurationDom.CreateElement("serviceAssemblies");
                coreNode.AppendChild(serviceAssemblyNode);
            }
            if (serviceProviderNode == null)
            {
                serviceProviderNode = configurationDom.CreateElement("serviceProviders");
                coreNode.AppendChild(serviceProviderNode);
            }

            // Add service provider (Multi if available, Everest if otherwise)
            XmlElement addServiceAsmNode  = serviceAssemblyNode.SelectSingleNode("./*[local-name() = 'add'][@assembly = 'MARC.HI.EHRS.CR.Messaging.HL7.dll']") as XmlElement,
                       addServiceProvNode = serviceProviderNode.SelectSingleNode(String.Format("./*[local-name() = 'add'][@type = '{0}']", (mmhType ?? typeof(HL7MessageHandler)).AssemblyQualifiedName)) as XmlElement;

            if (addServiceAsmNode == null)
            {
                addServiceAsmNode = configurationDom.CreateElement("add");
                addServiceAsmNode.Attributes.Append(configurationDom.CreateAttribute("assembly"));
                addServiceAsmNode.Attributes["assembly"].Value = "MARC.HI.EHRS.CR.Messaging.HL7.dll";
                serviceAssemblyNode.AppendChild(addServiceAsmNode);
            }
            if (addServiceProvNode == null)
            {
                addServiceProvNode = configurationDom.CreateElement("add");
                addServiceProvNode.Attributes.Append(configurationDom.CreateAttribute("type"));
                addServiceProvNode.Attributes["type"].Value = (mmhType ?? typeof(HL7MessageHandler)).AssemblyQualifiedName;
                serviceProviderNode.AppendChild(addServiceProvNode);
            }

            // Multi-message handler registration?
            if (mmhType != null)
            {
                XmlElement mmhNode = configurationDom.SelectSingleNode(".//*[local-name() = 'marc.hi.ehrs.svc.messaging.multi']") as XmlElement;
                if (mmhNode == null)
                {
                    mmhNode = configurationDom.DocumentElement.AppendChild(configurationDom.CreateElement("marc.hi.ehrs.svc.messaging.multi")) as XmlElement;
                }
                // Handler node
                XmlElement handlerNode = mmhNode.SelectSingleNode("./*[local-name() = 'handlers']") as XmlElement;
                if (handlerNode == null)
                {
                    handlerNode = mmhNode.AppendChild(configurationDom.CreateElement("handlers")) as XmlElement;
                }
                // Add node?
                if (handlerNode.SelectSingleNode(String.Format("./*[local-name() = 'add'][@type = '{0}']", typeof(HL7MessageHandler).AssemblyQualifiedName)) == null)
                {
                    var addNode = handlerNode.AppendChild(configurationDom.CreateElement("add"));
                    addNode.Attributes.Append(configurationDom.CreateAttribute("type")).Value = typeof(HL7MessageHandler).AssemblyQualifiedName;
                }
            }

            // Loop through enabled revisions and see if we need to configure them
            servicesNode.RemoveAll();
            foreach (var serviceDefn in this.m_configuration.Services)
            {
                XmlElement serviceNode = configurationDom.CreateElement("service");
                serviceNode.Attributes.Append(configurationDom.CreateAttribute("name"));
                serviceNode.Attributes["name"].Value = serviceDefn.Name;
                serviceNode.Attributes.Append(configurationDom.CreateAttribute("timeout"));
                serviceNode.Attributes["timeout"].Value = serviceDefn.ReceiveTimeout.ToString();
                serviceNode.Attributes.Append(configurationDom.CreateAttribute("address"));
                serviceNode.Attributes["address"].Value = serviceDefn.Address.ToString();

                // Attributes
                foreach (var attr in serviceDefn.Attributes)
                {
                    XmlElement attrNode = configurationDom.CreateElement("attribute");
                    attrNode.Attributes.Append(configurationDom.CreateAttribute("name"));
                    attrNode.Attributes["name"].Value = attr.Key;
                    attrNode.Attributes.Append(configurationDom.CreateAttribute("value"));
                    attrNode.Attributes["value"].Value = attr.Value;
                    serviceNode.AppendChild(attrNode);
                }

                // Handlers
                foreach (var handlr in serviceDefn.Handlers)
                {
                    XmlSerializer xsz = new XmlSerializer(typeof(HandlerDefinition));
                    MemoryStream  ms  = new MemoryStream();
                    xsz.Serialize(ms, handlr);
                    ms.Seek(0, SeekOrigin.Begin);
                    XmlDocument loadDoc = new XmlDocument();
                    loadDoc.Load(ms);
                    serviceNode.AppendChild(configurationDom.ImportNode(loadDoc.DocumentElement, true));
                }

                servicesNode.AppendChild(serviceNode);
            }

            this.m_needsSync = true;
        }
    protected void btnSavedetail1_Click(object sender, EventArgs e)
    {
        try
        {
            /* if (txtEmpid.Text == "") { }
             * if (txtFname.Text == "") { }
             * if (txtMname.Text == "") { }
             * if (txtLname.Text == "") { }
             * if (txtDate.Text == "") { }
             * if (cboGender.SelectedValue == "") { }
             * if (txtHiredate.Text == "") { }
             * if (txtAdrss1.Text == "") { }
             * if (txtAddrss2.Text == "") { }
             * if (txtEmail.Text == "") { }
             * if (txtDeptid.Text == "") { }
             * if (txtDeptname.Text == "") { }
             * if (cboDeptsection.SelectedValue == "") { }
             * if (txtSupervisor.Text == "") { } */
            if (txtEmpid.Text == "" && txtFname.Text == "" && txtMname.Text == "" && txtLname.Text == "" && txtDate.Text == "" && cboGender.SelectedValue == "" && txtHiredate.Text == "" && txtAdrss1.Text == "" && txtAddrss2.Text == "" && txtEmail.Text == "" && cboEmpCity.SelectedValue == "" && txtEmpZipcode.Text == "" && cboEmpState.SelectedValue == "" && cboEmpCountry.SelectedValue == "" && txtTel.Text == "" && txtMobile.Text == "" && txtDeptid.Text == "" && txtDeptname.Text == "" && cboDeptsection.SelectedValue == "" && txtSupervisor.Text == "")
            {
                lblNotification.Text = "...NULL VALUES NOT ACCEPTABLE !...";
            }
            else if (EmpPhotoUpload.PostedFile != null && txtEmpid.Text != null && txtFname.Text != null && txtMname.Text != null && txtLname.Text != null && txtDate.Text != null && cboGender.SelectedValue != null && txtHiredate.Text != null && txtAdrss1.Text != null && txtAddrss2.Text != null && txtEmail.Text != null && cboEmpCity.SelectedValue != null && txtEmpZipcode.Text != null && cboEmpState.SelectedValue != null && cboEmpCountry.SelectedValue != null && txtTel.Text != null && txtMobile.Text != null && txtDeptid.Text != null && txtDeptname.Text != null && cboDeptsection.SelectedValue != null && txtSupervisor.Text != null)
            {
                System.Xml.XmlDocument omrokEmpXml = new System.Xml.XmlDocument();
                omrokEmpXml.Load(Server.MapPath("~/App_Data/OmrokEmployeeManagementSystem.xml"));
                System.Xml.XmlNode    omrokXMLemployeeNode = omrokEmpXml.DocumentElement.FirstChild;
                System.Xml.XmlElement xmlElement           = omrokEmpXml.CreateElement("OmrokEmployeeInformation");

                string empPhotoname = Path.GetFileName(EmpPhotoUpload.PostedFile.FileName);
                EmpPhotoUpload.PostedFile.SaveAs(Server.MapPath("~/Employee photograph/") + empPhotoname);
                //Response.Redirect(Request.Url.AbsoluteUri);
                xmlElement.SetAttribute("EmployeePhoto", Server.HtmlEncode("~/Employee photograph/" + EmpPhotoUpload.FileName));
                xmlElement.SetAttribute("EmployeeId", Server.HtmlEncode(txtEmpid.Text));
                xmlElement.SetAttribute("Firstname", Server.HtmlEncode(txtFname.Text));
                xmlElement.SetAttribute("Midname", Server.HtmlEncode(txtMname.Text));
                xmlElement.SetAttribute("Lastname", Server.HtmlEncode(txtLname.Text));
                xmlElement.SetAttribute("Birthdate", Server.HtmlEncode(txtDate.Text));
                xmlElement.SetAttribute("Sex", Server.HtmlEncode(cboGender.SelectedValue));
                xmlElement.SetAttribute("Hiringdate", Server.HtmlEncode(txtHiredate.Text));
                xmlElement.SetAttribute("Address", Server.HtmlEncode(txtAdrss1.Text));
                xmlElement.SetAttribute("Addres", Server.HtmlEncode(txtAddrss2.Text));
                xmlElement.SetAttribute("Email", Server.HtmlEncode(txtEmail.Text));
                xmlElement.SetAttribute("City", Server.HtmlEncode(cboEmpCity.SelectedValue));
                xmlElement.SetAttribute("ZipCode", Server.HtmlEncode(txtEmpZipcode.Text));
                xmlElement.SetAttribute("State", Server.HtmlEncode(cboEmpState.SelectedValue));
                xmlElement.SetAttribute("Country", Server.HtmlEncode(cboEmpCountry.SelectedValue));
                xmlElement.SetAttribute("Telephone", Server.HtmlEncode(txtTel.Text));
                xmlElement.SetAttribute("Mobile", Server.HtmlEncode(txtMobile.Text));
                xmlElement.SetAttribute("DepartmentId", Server.HtmlEncode(txtDeptid.Text));
                xmlElement.SetAttribute("DeparmentName", Server.HtmlEncode(txtDeptname.Text));
                xmlElement.SetAttribute("DepartmentSection", Server.HtmlEncode(cboDeptsection.Text));
                xmlElement.SetAttribute("Fax", Server.HtmlEncode(txtSupervisor.Text));

                omrokEmpXml.DocumentElement.InsertBefore(xmlElement, omrokXMLemployeeNode);

                omrokEmpXml.Save(Server.MapPath("~/App_Data/OmrokEmployeeManagementSystem.xml"));

                BindData();

                lblNotification.Text        = "Omrok DYNAMICS Employee Information saved !";
                txtEmpid.Text               = "";
                txtFname.Text               = "";
                txtMname.Text               = "";
                txtLname.Text               = "";
                txtDate.Text                = "";
                cboGender.SelectedValue     = "";
                txtHiredate.Text            = "";
                txtAdrss1.Text              = "";
                txtAddrss2.Text             = "";
                txtEmail.Text               = "";
                cboEmpCity.SelectedValue    = "";
                txtEmpZipcode.Text          = "";
                cboEmpState.SelectedValue   = "";
                cboEmpCountry.SelectedValue = "";
                txtTel.Text                  = "";
                txtMobile.Text               = "";
                txtDeptid.Text               = "";
                txtDeptname.Text             = "";
                cboDeptsection.SelectedValue = "";
                txtSupervisor.Text           = "";
                Response.Redirect("~/DisplayOmrokEmployeeProfile.aspx");
            }
        }
        catch (Exception ex)
        {
            lblNotification.Text = ex.ToString();
        }
    }
Exemplo n.º 52
0
        /// <summary>
        /// Loads the site collection of a Sharepoint server
        /// </summary>
        /// <param name="srcWebs">webs web service</param>
        /// <param name="srcLists">lists web service</param>
        /// <param name="loadListData">load data items or not</param>
        /// <returns>A Sharepoint site collection tree</returns>
        private SSiteCollection LoadSharepointTree(WebsWS.Webs srcWebs, ListsWS.Lists srcLists, bool loadListData)
        {
            SSiteCollection siteCollection = new SSiteCollection();

            // get all webs names (first is the site collection)
            XmlNode allSrcWebs = srcWebs.GetAllSubWebCollection();

            // result<List>: <Web Title="F*****g site collection" Url="http://ss13-css-009:31920" xmlns="http://schemas.microsoft.com/sharepoint/soap/" />
            Dictionary <string, string> webs = new Dictionary <string, string>();

            foreach (XmlNode web in allSrcWebs)
            {
                webs.Add(web.Attributes["Url"].InnerText, web.Attributes["Title"].InnerText);
            }

            bool   firstRun          = true;
            string srcListsUrlBuffer = srcLists.Url;
            var    allSrcWebsXml     = new List <XmlNode>();

            foreach (KeyValuePair <string, string> web in webs)
            {
                // load details on each web
                XmlNode w = srcWebs.GetWeb(web.Key);
                allSrcWebsXml.Add(w);
                SSite site = new SSite();
                site.ParentObject = siteCollection;
                site.XmlData      = w;

                string url = w.Attributes["Url"].InnerText + WebService.UrlLists;

                // only do this, if destination site is being loaded
                if (!loadListData)
                {
                    this.destinationSiteUrls.Add(w.Attributes["Url"].InnerText);
                }

                // get all lists
                srcLists.Url = url;
                XmlNode lc = srcLists.GetListCollection();

                // lists to migrate: Hidden="False"
                foreach (XmlNode list in lc.ChildNodes)
                {
                    // if BaseType==1 --> its a document library
                    if (list.Attributes["Hidden"].InnerText.ToUpper().Equals("FALSE") && !list.Attributes["BaseType"].InnerText.Equals("1"))
                    {
                        // load list details with all fields
                        XmlNode listDetails = srcLists.GetList(list.Attributes["Title"].InnerText);
                        Console.WriteLine(list.Attributes["Title"].InnerText + ", BaseType=" + listDetails.Attributes["BaseType"].InnerText);
                        SList shareList = new SList();
                        shareList.ParentObject = site;
                        shareList.XmlList      = listDetails;

                        // load list data
                        if (loadListData)
                        {
                            // attention: GetListItems only returns the elements of the default view, if you do not specify the viewfields you want
                            XmlDocument xmlDoc     = new System.Xml.XmlDocument();
                            XmlElement  viewFields = xmlDoc.CreateElement("ViewFields");

                            XmlElement field;
                            foreach (XmlElement f in shareList.XmlList["Fields"])
                            {
                                field = xmlDoc.CreateElement("FieldRef");
                                field.SetAttribute("Name", f.Attributes["Name"].InnerText);
                                viewFields.AppendChild(field);
                            }

                            XmlNode listItems = srcLists.GetListItems(list.Attributes["Title"].InnerText, null, null, viewFields, null, null, null);
                            shareList.XmlListData = listItems;
                        }

                        site.AddList(shareList, false);
                        Console.WriteLine("\t\t" + list.Attributes["Title"].InnerText);
                    }
                }

                if (firstRun)
                {
                    site.IsSiteCollectionSite = true;
                    firstRun = false;
                }
                else
                {
                    site.IsSiteCollectionSite = false;
                }

                siteCollection.AddSite(site, false);
            }

            srcLists.Url           = srcListsUrlBuffer;
            siteCollection.XmlData = allSrcWebsXml;

            return(siteCollection);
        }
Exemplo n.º 53
0
        System.Xml.XmlDocument Decompress(byte[] buffer)
        {
            var decompressBuffer = Utils.Zlib.Decompress(buffer);

            var doc    = new System.Xml.XmlDocument();
            var reader = new Utl.BinaryReader(decompressBuffer);

            var   keys    = new Dictionary <Int16, string>();
            Int16 keySize = -1;

            reader.Get(ref keySize);
            for (int i = 0; i < keySize; i++)
            {
                Int16  key  = -1;
                string name = "";
                reader.Get(ref name, Encoding.UTF8, false, 2);
                reader.Get(ref key);
                keys.Add(key, name);
            }

            var   values    = new Dictionary <Int16, string>();
            Int16 valueSize = -1;

            reader.Get(ref valueSize);
            for (int i = 0; i < valueSize; i++)
            {
                Int16  key   = -1;
                string value = "";
                reader.Get(ref value, Encoding.UTF8, false, 2);
                reader.Get(ref key);
                values.Add(key, value);
            }

            Action <System.Xml.XmlNode> decomp = null;

            decomp = (node) =>
            {
                Int16 elementSize = 0;
                reader.Get(ref elementSize);
                for (int i = 0; i < elementSize; i++)
                {
                    Int16 nameKey = -1;
                    reader.Get(ref nameKey);
                    var element = doc.CreateElement(keys[nameKey]);
                    node.AppendChild(element);

                    bool isHaveValue = false;
                    reader.Get(ref isHaveValue);
                    if (isHaveValue)
                    {
                        Int16 value = -1;
                        reader.Get(ref value);
                        var valueNode = doc.CreateNode(System.Xml.XmlNodeType.Text, "", "");
                        valueNode.Value = values[value];
                        element.AppendChild(valueNode);
                    }

                    bool isHaveChildren = false;
                    reader.Get(ref isHaveChildren);
                    if (isHaveChildren)
                    {
                        decomp(element);
                    }
                }
            };


            var declare = doc.CreateXmlDeclaration("1.0", "UTF-8", null);

            doc.AppendChild(declare);
            decomp(doc);

            return(doc);
        }
Exemplo n.º 54
0
    //
    //createListElement
    //
    private static void createListElement(
        ref System.Xml.XmlDocument pdoc,
        string pname,
        string pcore,
        System.Collections.Generic.List <pvMetadata.ListtemplateContenttype> ptypestable,
        System.Collections.Generic.List <pvMetadata.ListtemplateColumn> pfieldstable)
    {
        //
        // Insert ContentTypeRef
        //
        System.Xml.XmlNode contenttypes = pdoc.SelectSingleNode("//mha:List/mha:MetaData/mha:ContentTypes", s_nsMgr);
        foreach (ListtemplateContenttype typ in ptypestable)
        {
            string ContentTypeID;
            switch (typ.BasedOn)
            {
            case "Element":
                ContentTypeID = "0x01" + "00" + typ.typeGUID;
                break;

            case "Annoncering":
                ContentTypeID = "0x0104" + "00" + typ.typeGUID;
                break;

            case "Hyperlink":
                ContentTypeID = "0x0105" + "00" + typ.typeGUID;
                break;

            case "'Kontaktperson":
                ContentTypeID = "0x0106" + "00" + typ.typeGUID;
                break;

            case "'Meddelelse":
                ContentTypeID = "0x0107" + "00" + typ.typeGUID;
                break;

            case "'Opgave":
                ContentTypeID = "0x0108" + "00" + typ.typeGUID;
                break;

            case "'Problem":
                ContentTypeID = "0x0103" + "00" + typ.typeGUID;
                break;

            default:
                ContentTypeID = "Error" + "00" + typ.typeGUID;
                break;
            }

            System.Xml.XmlElement contenttyperef      = pdoc.CreateElement("", "ContentTypeRef", s_ns);
            System.Xml.XmlComment contenttypescomment = pdoc.CreateComment(typ.SysName);
            contenttyperef.SetAttribute("ID", ContentTypeID);

            System.Xml.XmlNode ContentTypeRef0x01 = pdoc.SelectSingleNode("//mha:List/mha:MetaData/mha:ContentTypes/mha:ContentTypeRef[@ID=\"0x01\"]", s_nsMgr);
            if (ContentTypeRef0x01 == null)
            {
                System.Xml.XmlNode lastContentTypeRef = contenttypes.AppendChild(contenttyperef);
                contenttypes.InsertBefore(contenttypescomment, lastContentTypeRef);
            }
            else
            {
                System.Xml.XmlNode Folder = pdoc.SelectSingleNode("//mha:List/mha:MetaData/mha:ContentTypes/mha:ContentTypeRef[@ID=\"0x01\"]/mha:Folder", s_nsMgr);
                if (Folder != null)
                {
                    System.Xml.XmlNode copyFolder = Folder.CloneNode(true);
                    contenttyperef.AppendChild(copyFolder);
                }
                contenttypes.InsertBefore(contenttypescomment, ContentTypeRef0x01);
                contenttypes.ReplaceChild(contenttyperef, ContentTypeRef0x01);
            }
        }


        System.Collections.Generic.SortedDictionary <string, ListtemplateColumn> scol = new System.Collections.Generic.SortedDictionary <string, ListtemplateColumn>();
        foreach (ListtemplateColumn col in pfieldstable)
        {
            scol.Add(col.Seqnr, col);
        }

        //
        // Insert Field in Fields
        //
        System.Xml.XmlNode fields = pdoc.SelectSingleNode("//mha:List/mha:MetaData/mha:Fields", s_nsMgr);
        foreach (ListtemplateColumn col in scol.Values)
        {
            if (!col.SysCol)
            {
                System.Xml.XmlElement fieldref = pdoc.CreateElement("", "Field", s_ns);
                fieldref.SetAttribute("Name", col.SysName);
                fieldref.SetAttribute("ID", col.colGUID);

                fieldref.SetAttribute("DisplayName", "$Resources:" + pcore + "," + col.SysName + ";");
                switch (col.KolonneType)
                {
                case "Text":
                    fieldref.SetAttribute("Type", "Text");
                    break;

                case "Note":
                    fieldref.SetAttribute("Type", "Note");
                    fieldref.SetAttribute("NumLines", "3");
                    fieldref.SetAttribute("RichText", "TRUE");
                    break;

                case "Choice":
                    fieldref.SetAttribute("Type", "Choice");
                    break;

                case "Number":
                    fieldref.SetAttribute("Type", "Number");
                    fieldref.SetAttribute("Decimals", "0");
                    break;

                case "Percentage":
                    fieldref.SetAttribute("Type", "Number");
                    fieldref.SetAttribute("Percentage", "TRUE");
                    fieldref.SetAttribute("Min", "0");
                    fieldref.SetAttribute("Max", "1");
                    break;

                case "Currency":
                    fieldref.SetAttribute("Type", "Currency");
                    fieldref.SetAttribute("Decimals", "2");
                    break;

                case "DateOnly":
                    fieldref.SetAttribute("Type", "DateTime");
                    fieldref.SetAttribute("Format", "DateOnly");
                    break;

                case "DateTime":
                    fieldref.SetAttribute("Type", "DateTime");
                    break;

                case "Boolean":
                    fieldref.SetAttribute("Type", "Boolean");
                    break;

                case "Counter":
                    fieldref.SetAttribute("Type", "Counter");
                    break;

                case "Picture":
                    fieldref.SetAttribute("Type", "Picture");
                    break;

                case "Hyperlink":
                    fieldref.SetAttribute("Type", "Hyperlink");
                    break;

                default:
                    break;
                }

                fields.AppendChild(fieldref);
            }
        }


        //
        // Insert FieldsRef in ViewFields
        //
        System.Xml.XmlNode viewfields = pdoc.SelectSingleNode("//mha:List/mha:MetaData/mha:Views/mha:View[@BaseViewID=\"1\"]/mha:ViewFields", s_nsMgr);
        foreach (ListtemplateColumn col in scol.Values)
        {
            if (!col.SysCol)
            {
                System.Xml.XmlElement fieldref = pdoc.CreateElement("", "FieldRef", s_ns);
                fieldref.SetAttribute("ID", col.colGUID);
                fieldref.SetAttribute("Name", col.SysName);
                viewfields.AppendChild(fieldref);
            }
        }
    }
Exemplo n.º 55
0
        public void Init(System.Xml.XmlElement xmlElement, ref System.Xml.XmlDocument doc)
        {
            XmlElement e = doc.CreateElement("optionalCalendars");

            xmlElement.AppendChild(e);
        }
        /// <summary>
        /// Saves a string to a resource file.
        /// </summary>
        /// <param name="key">The key to save (e.g. "MyWidget.Text").</param>
        /// <param name="value">The text value for the key.</param>
        /// <param name="resourceFileRoot">Relative path for the resource file root (e.g. "DesktopModules/Admin/Lists/App_LocalResources/ListEditor.ascx.resx").</param>
        /// <param name="language">The locale code in lang-region format (e.g. "fr-FR").</param>
        /// <param name="portalSettings">The current portal settings.</param>
        /// <param name="resourceType">Specifies whether to save as portal, host or system resource file.</param>
        /// <param name="createFile">if set to <c>true</c> a new file will be created if it is not found.</param>
        /// <param name="createKey">if set to <c>true</c> a new key will be created if not found.</param>
        /// <returns>If the value could be saved then true will be returned, otherwise false.</returns>
        /// <exception cref="System.Exception">Any file io error or similar will lead to exceptions</exception>
        public bool SaveString(string key, string value, string resourceFileRoot, string language, PortalSettings portalSettings, DotNetNuke.Services.Localization.LocalizationProvider.CustomizedLocale resourceType, bool createFile, bool createKey)
        {
            try
            {
                if (key.IndexOf(".", StringComparison.Ordinal) < 1)
                {
                    key += ".Text";
                }
                string resourceFileName = GetResourceFileName(resourceFileRoot, language);
                resourceFileName = resourceFileName.Replace("." + language.ToLower() + ".", "." + language + ".");
                switch (resourceType)
                {
                case DotNetNuke.Services.Localization.LocalizationProvider.CustomizedLocale.Host:
                    resourceFileName = resourceFileName.Replace(".resx", ".Host.resx");
                    break;

                case DotNetNuke.Services.Localization.LocalizationProvider.CustomizedLocale.Portal:
                    resourceFileName = resourceFileName.Replace(".resx", ".Portal-" + portalSettings.PortalId + ".resx");
                    break;
                }
                resourceFileName = resourceFileName.TrimStart('~', '/', '\\');
                string      filePath = HostingEnvironment.MapPath("~/" + Globals.ApplicationPath + resourceFileName);
                XmlDocument doc      = null;
                if (File.Exists(filePath))
                {
                    doc = new XmlDocument();
                    doc.Load(filePath);
                }
                else
                {
                    if (createFile)
                    {
                        doc = new System.Xml.XmlDocument();
                        doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", "yes"));
                        XmlNode root = doc.CreateElement("root");
                        doc.AppendChild(root);
                        AddResourceFileNode(ref root, "resheader", "resmimetype", "text/microsoft-resx");
                        AddResourceFileNode(ref root, "resheader", "version", "2.0");
                        AddResourceFileNode(ref root, "resheader", "reader", "System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                        AddResourceFileNode(ref root, "resheader", "writer", "System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
                    }
                }
                if (doc == null)
                {
                    return(false);
                }
                XmlNode reskeyNode = doc.SelectSingleNode("root/data[@name=\"" + key + "\"]");
                if (reskeyNode != null)
                {
                    reskeyNode.SelectSingleNode("value").InnerText = value;
                }
                else
                {
                    if (createKey)
                    {
                        XmlNode root = doc.SelectSingleNode("root");
                        AddResourceFileNode(ref root, "data", key, value);
                    }
                    else
                    {
                        return(false);
                    }
                }
                doc.Save(filePath);
                DataCache.RemoveCache("/" + resourceFileName.ToLower());
                return(true);
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Error while trying to create resource in {0}", resourceFileRoot), ex);
            }
        }
        public static void SetConfig(string strXmlFile, string strSection, string strConfigKey, string strValue)
        {
            try
            {
                System.Uri u = new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);

                string sFileName = System.IO.Path.GetDirectoryName(u.LocalPath) + "\\" + strXmlFile;

                if (!File.Exists(sFileName))
                {
                    FileStream fs = File.Create(sFileName);
                    byte[]     byData;
                    char[]     charData;
                    //获得字符数组
                    charData = "<CONFIG></CONFIG>".ToCharArray();
                    //初始化字节数组
                    byData = new byte[charData.Length];
                    //将字符数组转换为正确的字节格式
                    Encoder enc = Encoding.UTF8.GetEncoder();
                    enc.GetBytes(charData, 0, charData.Length, byData, 0, true);
                    fs.Seek(0, SeekOrigin.Begin);
                    fs.Write(byData, 0, byData.Length);
                    fs.Close();
                }

                System.Xml.XmlDocument XmlDoc = new System.Xml.XmlDocument();

                XmlDoc.Load(sFileName);

                string xPath = "/" + CONFIG_ROOT_NODE + "/" + strSection;

                if (!string.IsNullOrEmpty(strConfigKey))
                {
                    xPath += "/" + strConfigKey;
                }

                System.Xml.XmlNode n = XmlDoc.SelectSingleNode(xPath);

                if (n != null)
                {
                    n.InnerText = strValue;
                }
                else
                {
                    System.Xml.XmlNode root = XmlDoc.SelectSingleNode(CONFIG_ROOT_NODE);
                    System.Xml.XmlNode xe0  = XmlDoc.SelectSingleNode("/" + CONFIG_ROOT_NODE + "/" + strSection);
                    if (xe0 == null)
                    {
                        xe0 = XmlDoc.CreateElement(strSection);    //创建一个节点
                        root.AppendChild(xe0);
                    }
                    if (!string.IsNullOrEmpty(strConfigKey))
                    {
                        System.Xml.XmlElement xe1 = XmlDoc.CreateElement(strConfigKey);    //创建一个节点
                        xe1.InnerText = strValue;
                        xe0.AppendChild(xe1);
                    }
                    else
                    {
                        xe0.InnerText = strValue;
                    }
                }

                //保存。
                XmlDoc.Save(sFileName);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 58
0
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Xml.Linq.XElement xeErrors = commonVariables.ErrorsXML;

        #region initialiseVariables
        int    intProcessSerialId = 0;
        string strProcessId       = Guid.NewGuid().ToString().ToUpper();
        string strPageName        = "ProcessLogin";

        string strResultCode    = string.Empty;
        string strResultDetail  = string.Empty;
        string strErrorCode     = string.Empty;
        string strErrorDetail   = string.Empty;
        string strProcessRemark = string.Empty;
        bool   isProcessAbort   = false;
        bool   isSystemError    = false;

        long   lngOperatorId = long.MinValue;
        string strMemberCode = string.Empty;
        string strPassword   = string.Empty;
        string strSiteURL    = string.Empty;
        string strLoginIp    = string.Empty;
        string strDeviceId   = string.Empty;

        string strVCode          = string.Empty;
        string strSessionVCode   = string.Empty;
        string strProcessCode    = string.Empty;
        string strProcessMessage = string.Empty;
        string strCountryCode    = string.Empty;
        string strLastLoginIP    = string.Empty;
        string strPermission     = string.Empty;
        int    login_attemps     = 0;
        bool   runIovation       = false;

        System.Xml.XmlDocument xdResponse = new System.Xml.XmlDocument();

        #endregion

        #region populateVariables
        lngOperatorId   = long.Parse(commonVariables.OperatorId);
        strMemberCode   = Request.Form.Get("txtUsername");
        strPassword     = Request.Form.Get("txtPassword");
        strSiteURL      = commonVariables.SiteUrl;
        strLoginIp      = string.IsNullOrEmpty(Request.Form.Get("txtIPAddress")) ? commonIp.UserIP : Request.Form.Get("txtIPAddress");
        strDeviceId     = HttpContext.Current.Request.UserAgent;
        strVCode        = Request.Form.Get("txtCaptcha");
        strSessionVCode = commonVariables.GetSessionVariable("vCode");
        strCountryCode  = Request.Form.Get("txtCountry");
        strPermission   = Request.Form.Get("txtPermission");
        login_attemps   = int.Parse(Request.Form.Get("login_attemps"));
        #endregion

        #region parametersValidation
        if (string.IsNullOrEmpty(strMemberCode))
        {
            strProcessCode = "-1"; strProcessMessage = commonCulture.ElementValues.getResourceXPathString("Login/MissingUsername", xeErrors); isProcessAbort = true;
        }
        else if (string.IsNullOrEmpty(strPassword))
        {
            strProcessCode = "-1"; strProcessMessage = commonCulture.ElementValues.getResourceXPathString("Login/MissingPassword", xeErrors); isProcessAbort = true;
        }
        else if (login_attemps > 2 && string.IsNullOrEmpty(strVCode))
        {
            strProcessCode = "-1"; strProcessMessage = commonCulture.ElementValues.getResourceString("MissingVCode", xeErrors); isProcessAbort = true;
        }
        else if (commonValidation.isInjection(strMemberCode))
        {
            strProcessCode = "-1"; strProcessMessage = commonCulture.ElementValues.getResourceXPathString("Login/InvalidUsername", xeErrors); isProcessAbort = true;
        }
        else if (commonValidation.isInjection(strPassword))
        {
            strProcessCode = "-1"; strProcessMessage = commonCulture.ElementValues.getResourceXPathString("Login/InvalidPassword", xeErrors); isProcessAbort = true;
        }
        else if (login_attemps > 2 && commonValidation.isInjection(strVCode))
        {
            strProcessCode = "-1"; strProcessMessage = commonCulture.ElementValues.getResourceString("IncorrectVCode", xeErrors); isProcessAbort = true;
        }
        else if (login_attemps > 2 && string.Compare(commonEncryption.encrypting(strVCode), strSessionVCode, true) != 0)
        {
            strProcessCode = "-1"; strProcessMessage = commonCulture.ElementValues.getResourceString("IncorrectVCode", xeErrors); isProcessAbort = true;
        }
        else
        {
            strPassword = commonEncryption.Encrypt(strPassword);
        }

        strProcessRemark = string.Format("MemberCode: {0} | Password: {1} | VCode: {2} | EVCode: {3} | SVCode: {4} | IP: {5} | Country: {6} | ProcessCode: {7}", strMemberCode, strPassword, strVCode, commonEncryption.encrypting(strVCode), strSessionVCode, strLoginIp, strCountryCode, strProcessCode);

        intProcessSerialId += 1;
        commonAuditTrail.appendLog("system", strPageName, "ParameterValidation", "DataBaseManager.DLL", strResultCode, strResultDetail, strErrorCode, strErrorDetail, strProcessRemark, Convert.ToString(intProcessSerialId), strProcessId, isSystemError);

        #endregion

        #region initiateLogin
        if (!isProcessAbort)
        {
            try
            {
                //using (wsAffiliateMS1.affiliateWSSoapClient svcInstance = new wsAffiliateMS1.affiliateWSSoapClient())
                using (mwsAffiliate.mws_affiliateSoapClient svcInstance = new mwsAffiliate.mws_affiliateSoapClient())
                {
                    System.Data.DataSet dsSignin = null;
                    //dsSignin = svcInstance.MemberSignin(lngOperatorId, strMemberCode, strPassword, strSiteURL, strLoginIp, strDeviceId);
                    dsSignin = svcInstance.MobileMemberSignin(lngOperatorId, strMemberCode, strPassword, strSiteURL, strLoginIp, strDeviceId);

                    if (dsSignin.Tables[0].Rows.Count > 0)
                    {
                        strProcessRemark = string.Format("OpID: {0} | MemberCode: {1} | Password: {2} | URL: {3} | LoginIp: {4} | Device: {5}", lngOperatorId, strMemberCode, strPassword, strSiteURL, strLoginIp, strDeviceId);

                        intProcessSerialId += 1;
                        commonAuditTrail.appendLog("system", strPageName, "ParameterValidation", "DataBaseManager.DLL", strResultCode, strResultDetail, strErrorCode, strErrorDetail, strProcessRemark, Convert.ToString(intProcessSerialId), strProcessId, isSystemError);


                        strProcessCode = Convert.ToString(dsSignin.Tables[0].Rows[0]["RETURN_VALUE"]);
                        switch (strProcessCode)
                        {
                        case "0":
                            strProcessMessage = commonCulture.ElementValues.getResourceString("Exception", xeErrors);
                            break;

                        case "1":
                            string strMemberSessionId = Convert.ToString(dsSignin.Tables[0].Rows[0]["memberSessionId"]);
                            HttpContext.Current.Session.Add("MemberSessionId", Convert.ToString(dsSignin.Tables[0].Rows[0]["memberSessionId"]));
                            HttpContext.Current.Session.Add("MemberId", Convert.ToString(dsSignin.Tables[0].Rows[0]["affiliateID"]));
                            //affiliate id
                            HttpContext.Current.Session.Add("AffiliateId", Convert.ToString(dsSignin.Tables[0].Rows[0]["affiliateID"]));
                            HttpContext.Current.Session.Add("MemberCode", Convert.ToString(dsSignin.Tables[0].Rows[0]["memberCode"]));
                            HttpContext.Current.Session.Add("CountryCode", Convert.ToString(dsSignin.Tables[0].Rows[0]["countryCode"]));
                            HttpContext.Current.Session.Add("CurrencyCode", Convert.ToString(dsSignin.Tables[0].Rows[0]["currency"]));
                            HttpContext.Current.Session.Add("LanguageCode", Convert.ToString(dsSignin.Tables[0].Rows[0]["languageCode"]));
                            //HttpContext.Current.Session.Add("RiskId", Convert.ToString(dsSignin.Tables[0].Rows[0]["riskId"]));
                            //HttpContext.Current.Session.Add("PartialSignup", Convert.ToString(dsSignin.Tables[0].Rows[0]["partialSignup"]));
                            HttpContext.Current.Session.Add("ResetPassword", Convert.ToString(dsSignin.Tables[0].Rows[0]["resetPassword"]));

                            commonCookie.CookieAffiliateId = Convert.ToString(dsSignin.Tables[0].Rows[0]["affiliateID"]);
                            commonCookie.CookieS           = strMemberSessionId;
                            commonCookie.CookieG           = strMemberSessionId;
                            HttpContext.Current.Session.Add("LoginStatus", "success");

                            //strLastLoginIP = Convert.ToString(dsSignin.Tables[0].Rows[0]["lastLoginIP"]);
                            if (HttpContext.Current.Request.Cookies[strMemberCode] == null)
                            {
                                runIovation = true;
                            }
                            else if (HttpContext.Current.Request.Cookies[strMemberCode] != null && string.Compare(strLastLoginIP, strLoginIp, true) != 0)
                            {
                                runIovation = true;
                            }
                            if (runIovation)
                            {
                                this.IovationSubmit(ref intProcessSerialId, strProcessId, strPageName, strMemberCode, strLoginIp, strPermission);
                            }
                            break;

                        case "21":
                            strProcessMessage = commonCulture.ElementValues.getResourceXPathString("Login/InvalidUsername", xeErrors);
                            break;

                        case "22":
                            strProcessMessage = commonCulture.ElementValues.getResourceXPathString("Login/InactiveAccount", xeErrors);
                            break;

                        case "23":
                            strProcessMessage = commonCulture.ElementValues.getResourceXPathString("Login/InvalidPassword", xeErrors);
                            break;

                        case "24":
                            strProcessMessage = commonCulture.ElementValues.getResourceXPathString("Login/AccountPending", xeErrors);
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                strProcessCode    = "0";
                strProcessMessage = commonCulture.ElementValues.getResourceString("Exception", xeErrors);
                strProcessRemark  = string.Format("{0} | Message: {1}", strProcessRemark, ex.Message);
            }

            strProcessRemark = string.Format("{0} | strProcessCode: {1}", strProcessRemark, strProcessCode);

            intProcessSerialId += 1;
            commonAuditTrail.appendLog("system", strPageName, "MemberSignin", "DataBaseManager.DLL", strResultCode, strResultDetail, strErrorCode, strErrorDetail, strProcessRemark, Convert.ToString(intProcessSerialId), strProcessId, isSystemError);
        }
        #endregion

        #region Response
        System.Xml.XmlNode xnRootNode    = xdResponse.CreateElement("Login");
        System.Xml.XmlNode xnCodeNode    = xdResponse.CreateElement("ErrorCode");
        System.Xml.XmlNode xnMessageNode = xdResponse.CreateElement("Message");

        xnCodeNode.InnerText    = strProcessCode;
        xnMessageNode.InnerText = strProcessMessage;
        xnRootNode.AppendChild(xnCodeNode);
        xnRootNode.AppendChild(xnMessageNode);
        xdResponse.AppendChild(xnRootNode);

        Response.ContentType = "text/xml";
        Response.Write(xdResponse.DocumentElement.OuterXml);
        Response.End();
        #endregion
    }
Exemplo n.º 59
0
        public void addtoDB(string title, string url, List <string> genres, string console)  // Adiciona um jogo à base de dados
        {
            XmlDocument newgame_doc  = new System.Xml.XmlDocument();
            XmlElement  game         = newgame_doc.CreateElement("game");
            XmlElement  genres_toadd = newgame_doc.CreateElement("genres");


            if (genres.Count == 0 || (genres.Count == 1 && genres[0].Equals("")))
            {
                XmlElement   newgenre     = newgame_doc.CreateElement("genre");
                XmlAttribute newgenre_att = newgame_doc.CreateAttribute("name");
                newgenre_att.InnerText = "unavailable";
                newgenre.Attributes.Append(newgenre_att);
                genres_toadd.AppendChild(newgenre);
            }
            else
            {
                foreach (string genre in genres)
                {
                    XmlElement   newgenre     = newgame_doc.CreateElement("genre");
                    XmlAttribute newgenre_att = newgame_doc.CreateAttribute("name");
                    newgenre_att.InnerText = genre;
                    newgenre.Attributes.Append(newgenre_att);
                    genres_toadd.AppendChild(newgenre);
                }
            }
            game.AppendChild(genres_toadd);

            XmlElement romhashes_toadd = newgame_doc.CreateElement("romhashes");

            game.AppendChild(romhashes_toadd);

            XmlAttribute title_toadd   = newgame_doc.CreateAttribute("title");
            XmlAttribute url_toadd     = newgame_doc.CreateAttribute("url");
            XmlAttribute console_toadd = newgame_doc.CreateAttribute("console");
            XmlAttribute xmlns         = newgame_doc.CreateAttribute("xmlns");

            title_toadd.InnerText   = title;
            url_toadd.InnerText     = url;
            console_toadd.InnerText = console;
            xmlns.InnerText         = "http://ect2016/GamesSchema";

            game.Attributes.Append(xmlns);
            game.Attributes.Append(title_toadd);
            game.Attributes.Append(url_toadd);
            game.Attributes.Append(console_toadd);

            newgame_doc.AppendChild(game);

            System.Data.SqlClient.SqlConnection sqlCon =
                new System.Data.SqlClient.SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Nuno\\Documents\\finaldb.mdf;Integrated Security=True;Connect Timeout=30");
            System.Data.SqlClient.SqlCommand Cmd = new System.Data.SqlClient.SqlCommand();
            Cmd.CommandText = "insert into dbo.Games(xmlContent) values(@newgame)";
            Cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter()
            {
                ParameterName = "newgame",
                Value         = newgame_doc.OuterXml
            });
            Cmd.Connection = sqlCon;
            sqlCon.Open();
            int result = Cmd.ExecuteNonQuery();

            sqlCon.Close();
        }
Exemplo n.º 60
0
    private static void createFieldElement(ref System.Xml.XmlDocument pdoc, string pid, string pname, string pcore, string KolonneType)
    {
        System.Xml.XmlElement field = pdoc.CreateElement("", "Field", ns);
        field.SetAttribute("ID", pid);
        field.SetAttribute("Name", pname);
        field.SetAttribute("DisplayName", "$Resources:" + pcore + "," + pname + ";");

        switch (KolonneType)
        {
        case "Text":
            field.SetAttribute("Type", "Text");
            field.SetAttribute("MaxLength", "255");
            break;

        case "Note":
            field.SetAttribute("Type", "Note");
            field.SetAttribute("NumLines", "3");
            field.SetAttribute("RichText", "TRUE");
            break;

        case "Choice":
            field.SetAttribute("Type", "Choice");
            break;

        case "Number":
            field.SetAttribute("Type", "Number");
            field.SetAttribute("Decimals", "0");
            break;

        case "Percentage":
            field.SetAttribute("Type", "Number");
            field.SetAttribute("Percentage", "TRUE");
            field.SetAttribute("Min", "0");
            field.SetAttribute("Max", "1");
            break;

        case "Currency":
            field.SetAttribute("Type", "Currency");
            field.SetAttribute("Decimals", "2");
            break;

        case "DateOnly":
            field.SetAttribute("Type", "DateTime");
            field.SetAttribute("Format", "DateOnly");
            break;

        case "DateTime":
            field.SetAttribute("Type", "DateTime");
            break;

        case "Boolean":
            field.SetAttribute("Type", "Boolean");
            break;

        default:
            break;
        }

        field.SetAttribute("Group", "$Resources:" + pcore + ",FieldsGroupName;");

        System.Xml.XmlNode elements = pdoc.SelectSingleNode("//mha:Elements", nsMgr);
        string             filter   = "//mha:Field[@ID=\"" + pid + "\"]";

        System.Xml.XmlNode old_field = elements.SelectSingleNode(filter, nsMgr);

        if (old_field == null)
        {
            elements.AppendChild(field);
        }
        else
        {
            elements.ReplaceChild(field, old_field);
        }
    }