Example #1
0
    public static void Write(XmlDocument target, DbDataReader source )
    {
        /*
            Style:
            <root>
                <raw><name>name1</name><index>name2</index></raw>
                <raw><name>name1</name><index>name2</index></raw>
                <raw><name>name1</name><index>name2</index></raw>
            </root>
        */

        XmlNode head = target.CreateNode(XmlNodeType.Element, "head", "");
        XmlNode body = target.CreateNode(XmlNodeType.Element, "body", "");

        for (int i = 0; i < source.FieldCount; ++i)
        {
            string vl = source.GetName(i);
            string local =  (string)HttpContext.GetGlobalResourceObject("local", vl);
            if (local != null) vl = local;

            Util.AddNodedText(head, "column", vl, false);
        }

        while (source.Read())
        {
            XmlNode raw = target.CreateNode(XmlNodeType.Element, "raw", "");

            for (int i = 0; i < source.FieldCount; ++i) Util.AddNodedText(raw, "value", Util.GetString( source, i ), false);

            body.AppendChild(raw);
        }

        target.FirstChild.AppendChild(head);
        target.FirstChild.AppendChild(body);
    }
Example #2
0
    public static void SaveConfig()
    {
        try
        {
            string ConfigFile = Path.Combine(ClientSettings.AppPath, "App.config");

            XmlDocument oXml = new XmlDocument();
            XmlNode Root = oXml.CreateNode(XmlNodeType.Element, "configuration", "");
            XmlNode SettingsNode = oXml.CreateNode(XmlNodeType.Element, "appSettings", "");
            foreach(string AppSettingName in AppSettings.Keys)
            {
                XmlNode SettingNode = oXml.CreateNode(XmlNodeType.Element, "add", "");
                XmlAttribute keyatt = oXml.CreateAttribute("key");
                keyatt.Value = AppSettingName;

                XmlAttribute valueatt = oXml.CreateAttribute("value");
                valueatt.Value = AppSettings[AppSettingName];
                SettingNode.Attributes.Append(keyatt);
                SettingNode.Attributes.Append(valueatt);
                SettingsNode.AppendChild(SettingNode);
            }

            XmlNode AccountsNode = oXml.CreateNode(XmlNodeType.Element, "accounts", "");
            foreach (Yedda.Twitter.Account Account in Accounts)
            {
                XmlNode AccountNode = oXml.CreateNode(XmlNodeType.Element, "add", "");
                XmlAttribute userAtt = oXml.CreateAttribute("user");
                userAtt.Value = Account.UserName;

                XmlAttribute passAtt = oXml.CreateAttribute("password");
                passAtt.Value = Account.Password;

                XmlAttribute serverNameAtt = oXml.CreateAttribute("servername");
                serverNameAtt.Value = Account.ServerURL.Name;

                XmlAttribute enabledAtt = oXml.CreateAttribute("enabled");
                enabledAtt.Value = Account.Enabled.ToString();

                AccountNode.Attributes.Append(userAtt);
                AccountNode.Attributes.Append(passAtt);
                AccountNode.Attributes.Append(serverNameAtt);
                AccountNode.Attributes.Append(enabledAtt);
                AccountsNode.AppendChild(AccountNode);
            }

            Root.AppendChild(SettingsNode);
            Root.AppendChild(AccountsNode);
            oXml.AppendChild(Root);

            oXml.Save(ConfigFile);
        }
        catch(Exception ex) 
        {
            System.Diagnostics.Debug.WriteLine(ex.Message);
        }
    }
Example #3
0
 public float getBookPrice(string isbn)
 {
     if (isbnNotValid(isbn))
     {
         XmlDocument doc = new XmlDocument();
         XmlNode node = doc.CreateNode(XmlNodeType.Element, SoapException.DetailElementName.Name, SoapException.DetailElementName.Namespace);
         XmlNode child = doc.CreateNode(XmlNodeType.Element, "error", "http://DEETC.SES.SD");
         child.InnerText = "BookService:Not valid ISBN in getBookPrice operation.";
         node.AppendChild(child);
         throw new SoapException("ISBN not Valid", SoapException.ServerFaultCode, "ActorServer", node);
     }
     return 24.9F;
 }
Example #4
0
	public int GetEmployeesCountError()
	{
		try
		{
			SqlConnection con = new SqlConnection(connectionString);

			// Make a deliberately faulty SQL string
			string sql = "INVALID_SQL COUNT(*) FROM Employees";
			SqlCommand cmd = new SqlCommand(sql, con);

			// Open the connection and get the value.
			cmd.Connection.Open();
			int numEmployees = -1;
			try
			{
				numEmployees = (int)cmd.ExecuteScalar();
			}
			finally
			{
				cmd.Connection.Close();
			}
			return numEmployees;
		}
		catch (Exception err)
		{
			// Create the detail information
			// an <ExceptionType> element with the type name.
			XmlDocument doc = new XmlDocument();
			XmlNode node = doc.CreateNode(
				XmlNodeType.Element, SoapException.DetailElementName.Name,
				SoapException.DetailElementName.Namespace);
			XmlNode child = doc.CreateNode(
				XmlNodeType.Element, "ExceptionType",
				SoapException.DetailElementName.Namespace);
			child.InnerText = err.GetType().ToString();
			node.AppendChild(child);

			// Create the custom SoapException.
			// Use the message from the original exception,
			// and add the detail information.
			SoapException soapErr = new SoapException(
				err.Message, SoapException.ServerFaultCode,
				Context.Request.Url.AbsoluteUri, node);

			// Throw the revised SoapException.
			throw soapErr;
		}
	}
Example #5
0
        private static void VerifyOwnerOfGivenType(XmlNodeType nodeType)
        {
            var xmlDocument = new XmlDocument();
            var node = xmlDocument.CreateNode(nodeType, "test", string.Empty);

            Assert.Equal(xmlDocument, node.OwnerDocument);
        }
Example #6
0
    public void saveXML(string path)
    {
        XmlDocument doc = new XmlDocument ();
        XmlElement main = doc.CreateElement ("Config");
        XmlAttribute version = doc.CreateAttribute ("Version");
        version.Value = configVersion;
        main.Attributes.Append (version);
        XmlAttribute lastMap = doc.CreateAttribute ("lastCompletedMap");
        lastMap.Value = lastCompletedLevel;
        main.Attributes.Append (lastMap);
        XmlNode score = doc.CreateNode (XmlNodeType.Element, "ScoreHistory", "");
        foreach(int i in scoreHistory ){
            XmlElement node = doc.CreateElement("Score");
            XmlAttribute val = doc.CreateAttribute("Value");
            val.Value = i.ToString();
            node.Attributes.Append(val);
            score.AppendChild(node);
        }

        main.AppendChild (score);
        doc.AppendChild (main);
        doc.Save(path);
        /*
        //doc.l
        using (var stream = new FileStream(path, FileMode.Create)) {
            using (StreamWriter writer = new StreamWriter(stream))
                writer.Write (data);
        }
        */
    }
Example #7
0
	/// <summary>
	/// Create a node containing the user
	/// </summary>
	/// <param name="doc">XML configuration document</param>
	/// <returns>base node of new permission</returns>
	public XmlNode Create(XmlDocument doc)
	{
		// create the permission node
		XmlNode user = doc.CreateNode(XmlNodeType.Element, "User", null);

		// assign the user name attribute
		XmlAttribute userName = doc.CreateAttribute("Name");
		userName.Value = Username;
		user.Attributes.Append(userName);

		// create the options
		XmlNode opt;
		opt = CreateOption(doc, "Pass", Filezilla.GetMd5Sum(Password));
		user.AppendChild(opt);
		opt = CreateOption(doc, "Group", "");
		user.AppendChild(opt);
		opt = CreateOption(doc, "Bypass server userlimit", false);
		user.AppendChild(opt);
		opt = CreateOption(doc, "User Limit", "0");
		user.AppendChild(opt);
		opt = CreateOption(doc, "IP Limit", "0");
		user.AppendChild(opt);
		opt = CreateOption(doc, "Enabled", Enabled);
		user.AppendChild(opt);
		opt = CreateOption(doc, "Comments", "FileZilla.NET user");
		user.AppendChild(opt);
		opt = CreateOption(doc, "ForceSsl", "0");
		user.AppendChild(opt);

		// create the ip filters
		XmlNode ipfilter;
		ipfilter = doc.CreateNode(XmlNodeType.Element, "IpFilter", null);
		ipfilter.AppendChild(doc.CreateNode(XmlNodeType.Element, "Disallowed", null));
		ipfilter.AppendChild(doc.CreateNode(XmlNodeType.Element, "Allowed", null));
		user.AppendChild(ipfilter);

		// create the permissions
		XmlNode permissions;
		permissions = doc.CreateNode(XmlNodeType.Element, "Permissions", null);
		foreach (FilezillaPermission p in Permissions)
		{
			permissions.AppendChild(p.Create(doc));
		}
		user.AppendChild(permissions);

		return user;
	}
 public static bool SavePlistToFile(String xmlFile, Hashtable plist)
 {
     // If the hashtable is null, then there's apparently an issue; fail out.
     if (plist == null) {
         Debug.LogError("Passed a null plist hashtable to SavePlistToFile.");
         return false;
     }
     // Create the base xml document that we will use to write the data
     XmlDocument xml = new XmlDocument();
     xml.XmlResolver = null; //Disable schema/DTD validation, it's not implemented for Unity.
     // Create the root XML declaration
     // This, and the DOCTYPE, below, are standard parts of a XML property list file
     XmlDeclaration xmldecl = xml.CreateXmlDeclaration("1.0", "UTF-8", null);
     xml.PrependChild(xmldecl);
     // Create the DOCTYPE
     XmlDocumentType doctype = xml.CreateDocumentType("plist", "-//Apple//DTD PLIST 1.0//EN", "http://www.apple.com/DTDs/PropertyList-1.0.dtd", null);
     xml.AppendChild(doctype);
     // Create the root plist node, with a version number attribute.
     // Every plist file has this as the root element.  We're using version 1.0 of the plist scheme
     XmlNode plistNode = xml.CreateNode(XmlNodeType.Element, "plist", null);
     XmlAttribute plistVers = (XmlAttribute)xml.CreateNode(XmlNodeType.Attribute, "version", null);
     plistVers.Value = "1.0";
     plistNode.Attributes.Append(plistVers);
     xml.AppendChild(plistNode);
     // Now that we've created the base for the XML file, we can add all of our information to it.
     // Pass the plist data and the root dict node to SaveDictToPlistNode, which will write the plist data to the dict node.
     // This function will itterate through the hashtable hierarchy and call itself recursively for child hashtables.
     if (!SaveDictToPlistNode(plistNode, plist)) {
         // If for some reason we failed, post an error and return false.
         Debug.LogError("Failed to save plist data to root dict node: " + plist);
         return false;
     } else { // We were successful
         // Create a StreamWriter and write the XML file to disk.
         // (do not append and UTF-8 are default, but we're defining it explicitly just in case)
         StreamWriter sw = new StreamWriter(xmlFile, false, System.Text.Encoding.UTF8);
         xml.Save(sw);
         sw.Close();
     }
     // We're done here.  If there were any failures, they would have returned false.
     // Return true to indicate success.
     return true;
 }
 protected void btnLaheta_Click(object sender, EventArgs e)
 {
     XmlDocument oXmlDocument = new XmlDocument();
     oXmlDocument.Load(MapPath("~/App_Data/Palautteet.xml"));
     XmlNode oXmlRootNode = oXmlDocument.SelectSingleNode("palautteet");
     XmlNode oXmlRecordNode = oXmlRootNode.AppendChild(oXmlDocument.CreateNode(XmlNodeType.Element, "palaute", ""));
     oXmlRecordNode.AppendChild(oXmlDocument.CreateNode(XmlNodeType.Element, "pvm", "")).InnerText = txtPvm.Text;
     oXmlRecordNode.AppendChild(oXmlDocument.CreateNode(XmlNodeType.Element, "tekija", "")).InnerText = txtNimi.Text;
     oXmlRecordNode.AppendChild(oXmlDocument.CreateNode(XmlNodeType.Element, "opittu", "")).InnerText = txtOppinut.Text;
     oXmlRecordNode.AppendChild(oXmlDocument.CreateNode(XmlNodeType.Element, "haluanoppia", "")).InnerText = txtHaluanoppia.Text;
     oXmlRecordNode.AppendChild(oXmlDocument.CreateNode(XmlNodeType.Element, "hyvaa", "")).InnerText = txtHyvaa.Text;
     oXmlRecordNode.AppendChild(oXmlDocument.CreateNode(XmlNodeType.Element, "parannettavaa", "")).InnerText = txtParannettavaa.Text;
     oXmlRecordNode.AppendChild(oXmlDocument.CreateNode(XmlNodeType.Element, "muuta", "")).InnerText = txtMuuta.Text;
     oXmlDocument.Save(MapPath("~/App_Data/Palautteet.xml"));
 }
Example #10
0
        public static void NamedItemDoesNotExist()
        {
            var xmlDocument = new XmlDocument();
            xmlDocument.LoadXml("<foo />");

            var namedNodeMap = (XmlNamedNodeMap)xmlDocument.FirstChild.Attributes;
            Assert.Equal(0, namedNodeMap.Count);

            var newAttribute = xmlDocument.CreateNode(XmlNodeType.Attribute, "newNode", string.Empty);
            namedNodeMap.SetNamedItem(newAttribute);

            Assert.NotNull(newAttribute);
            Assert.Equal(1, namedNodeMap.Count);
            Assert.Equal(newAttribute, namedNodeMap.GetNamedItem("newNode"));
        }
    protected string GetPlayerChartXML()
    {
        XmlDocument xmlDoc = new XmlDocument();
        XmlNode xmlNode = xmlDoc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
        xmlDoc.AppendChild(xmlNode);
        XmlElement xEle = xmlDoc.CreateElement("graph");
        xEle.SetAttribute("showvalues", "0");
        XmlElement categories = xmlDoc.CreateElement("categories");
        XmlElement pointsPerGame = xmlDoc.CreateElement("dataset");
        pointsPerGame.SetAttribute("seriesname", "Points per Game");
        pointsPerGame.SetAttribute("color", "#000000");
        XmlElement assistsPerGame = xmlDoc.CreateElement("dataset");
        assistsPerGame.SetAttribute("seriesname", "Assists per Game");
        assistsPerGame.SetAttribute("color", "#000066");
        XmlElement goalsPerGame = xmlDoc.CreateElement("dataset");
        goalsPerGame.SetAttribute("seriesname", "Goals per Game");
        goalsPerGame.SetAttribute("color", "#660000");
        XmlElement tmpElement;
        String sqlString = GetDataString();
        SqlCommand sqlCommand = new SqlCommand(sqlString, scripts.GetConnection());
        using (SqlDataReader reader = sqlCommand.ExecuteReader())
        {
            while (reader.Read())
            {
                tmpElement = xmlDoc.CreateElement("category");
                tmpElement.SetAttribute("name", Convert.ToString(reader[3]));
                categories.AppendChild(tmpElement);

                tmpElement = xmlDoc.CreateElement("set");
                tmpElement.SetAttribute("value", Convert.ToString(reader[2]));
                pointsPerGame.AppendChild(tmpElement);

                tmpElement = xmlDoc.CreateElement("set");
                tmpElement.SetAttribute("value", Convert.ToString(reader[1]));
                goalsPerGame.AppendChild(tmpElement);

                tmpElement = xmlDoc.CreateElement("set");
                tmpElement.SetAttribute("value", Convert.ToString(reader[0]));
                assistsPerGame.AppendChild(tmpElement);
            }
        }
        xEle.AppendChild(categories);
        xEle.AppendChild(pointsPerGame);
        xEle.AppendChild(assistsPerGame);
        xEle.AppendChild(goalsPerGame);
        xmlDoc.AppendChild(xEle);
        return xmlDoc.OuterXml;
    }
    // Create example data to sign.
    public static void CreateSomeXml(string FileName)
    {
        // Create a new XmlDocument object.
        XmlDocument document = new XmlDocument();

        // Create a new XmlNode object.
        XmlNode node = document.CreateNode(XmlNodeType.Element, "", "MyElement", "samples");

        // Add some text to the node.
        node.InnerText = "Example text to be signed.";

        // Append the node to the document.
        document.AppendChild(node);

        // Save the XML document to the file name specified.
        XmlTextWriter xmltw = new XmlTextWriter(FileName, new UTF8Encoding(false));
        document.WriteTo(xmltw);
        xmltw.Close();
    }
Example #13
0
    private JToken WriteNestedActivity(XmlDocument doc, XmlNode parent, String currentId, JArray controls)
    {
        JToken currentProperty = FindNextActivity(currentId, controls);
        while (currentProperty != null && currentProperty["type"].ToString().LastIndexOf("_E") == -1)
        {
            if (currentProperty["type"].ToString().LastIndexOf("_S") != -1)
            {
                String type = "";
                String branchType = "";
                if (currentProperty["type"].ToString().IndexOf("flowIfElseActivity") != -1)
                {
                    type = "IfElseActivity";
                    branchType = "IfElseBranchActivity";
                }
                else
                {
                    type = "ParallelActivity";
                    branchType = "SequenceActivity";
                }

                XmlNode newNode = doc.CreateNode(XmlNodeType.Element, "", type, "http://schemas.microsoft.com/winfx/2006/xaml/workflow");
                XmlAttribute newAttribute = doc.CreateAttribute("x", "Name", "http://schemas.microsoft.com/winfx/2006/xaml");
                newAttribute.Value = currentProperty["id"].ToString();
                newNode.Attributes.Append(newAttribute);
                parent.AppendChild(newNode);

                var branchCount = 0;
                foreach (var item in controls)
                {
                    if (item["id"] != null && item["id"].ToString().IndexOf(currentProperty["classify"] + "_") != -1 &&
                        item["id"].ToString() != currentProperty["classify"] + "_S" && item["id"].ToString() != currentProperty["classify"] + "_E" &&
                        item["type"].ToString() != "sl" && item["type"].ToString() != "lr")
                    {
                        branchCount++;
                    }
                }
                for (var i = 0; i < branchCount; i++)
                {
                    var nId = currentProperty["classify"] + "_" + (i + 1).ToString();
                    var node = FindCurrentActivity(nId, controls);
                    XmlNode aNode = doc.CreateNode(XmlNodeType.Element, "", branchType, "http://schemas.microsoft.com/winfx/2006/xaml/workflow");
                    XmlAttribute aAttribute = doc.CreateAttribute("x", "Name", "http://schemas.microsoft.com/winfx/2006/xaml");
                    if (node["name"] != null && node["name"].ToString() != "")
                        aAttribute.Value = node["name"].ToString();
                    else
                        aAttribute.Value = nId;
                    aNode.Attributes.Append(aAttribute);
                    for (var j = 0; j < node["properties"].Count(); j++)
                    {
                        if (node["properties"][j]["name"] != null && node["properties"][j]["name"].ToString() == "Description")
                        {
                            XmlAttribute dAttribute = doc.CreateAttribute("Description");
                            dAttribute.Value = node["properties"][j]["value"].ToString();
                            aNode.Attributes.Append(dAttribute);
                        }
                    }
                    newNode.AppendChild(aNode);

                    if (i == branchCount - 1)
                        currentProperty = WriteNestedActivity(doc, aNode, nId, controls);
                    else
                        WriteNestedActivity(doc, aNode, nId, controls);
                }
            }
            else
            {
                XmlNode newNode = doc.CreateNode(XmlNodeType.Element, "ns0", currentProperty["type"].ToString().Replace("FLTools.", String.Empty), "clr-namespace:FLTools;Assembly=FLTools, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
                foreach (var item in currentProperty["properties"])
                {
                    if (item["name"] != null && item["value"] != null)
                    {
                        XmlAttribute newAttribute = null;
                        if (item["name"].ToString() == "name" || item["name"].ToString() == "ID")
                        {
                            newAttribute = doc.CreateAttribute("x", "Name", "http://schemas.microsoft.com/winfx/2006/xaml");
                            newAttribute.Value = item["value"].ToString();
                        }
                        else
                        {
                            newAttribute = doc.CreateAttribute(item["name"].ToString());
                            newAttribute.Value = item["value"].ToString();
                        }
                        newNode.Attributes.Append(newAttribute);
                    }
                }
                parent.AppendChild(newNode);
            }

            currentProperty = FindNextActivity(currentProperty["id"].ToString(), controls);
        }
        return currentProperty;
    }
Example #14
0
        /// <summary>
        /// Validate the configuration and save it
        /// </summary>
        /// <param name="sender">The sender of the event</param>
        /// <param name="e">The event arguments</param>
        private void btnOK_Click(object sender, EventArgs e)
        {
            XmlAttribute     attr;
            XmlNode          root, node;
            UserCredentials  userCreds;
            ProxyCredentials proxyCreds;
            bool             isValid = true;
            Uri ajaxDoc = null, proxyServer = null;

            txtAjaxDocUrl.Text    = txtAjaxDocUrl.Text.Trim();
            txtProjectName.Text   = txtProjectName.Text.Trim();
            txtUserName.Text      = txtUserName.Text.Trim();
            txtPassword.Text      = txtPassword.Text.Trim();
            txtProxyServer.Text   = txtProxyServer.Text.Trim();
            txtProxyUserName.Text = txtProxyUserName.Text.Trim();
            txtProxyPassword.Text = txtProxyPassword.Text.Trim();
            epErrors.Clear();

            if (txtAjaxDocUrl.Text.Length == 0)
            {
                epErrors.SetError(txtAjaxDocUrl, "An AjaxDoc URL is required");
                isValid = false;
            }
            else
            if (!Uri.TryCreate(txtAjaxDocUrl.Text,
                               UriKind.RelativeOrAbsolute, out ajaxDoc))
            {
                epErrors.SetError(txtAjaxDocUrl, "The AjaxDoc URL does " +
                                  "not appear to be valid");
                isValid = false;
            }

            if (txtProjectName.Text.Length == 0)
            {
                epErrors.SetError(txtProjectName, "A project filename " +
                                  "is required");
                isValid = false;
            }

            if (!chkUseDefaultCredentials.Checked)
            {
                if (txtUserName.Text.Length == 0)
                {
                    epErrors.SetError(txtUserName, "A user name is " +
                                      "required if not using default credentials");
                    isValid = false;
                }

                if (txtPassword.Text.Length == 0)
                {
                    epErrors.SetError(txtPassword, "A password is " +
                                      "required if not using default credentials");
                    isValid = false;
                }
            }

            Uri.TryCreate(txtProxyServer.Text, UriKind.RelativeOrAbsolute,
                          out proxyServer);

            if (chkUseProxyServer.Checked)
            {
                if (txtProxyServer.Text.Length == 0)
                {
                    epErrors.SetError(txtProxyServer, "A proxy server is " +
                                      "required if one is used");
                    isValid = false;
                }
                else
                if (proxyServer == null)
                {
                    epErrors.SetError(txtProxyServer, "The proxy server " +
                                      "name does not appear to be valid");
                    isValid = false;
                }

                if (!chkUseProxyDefCreds.Checked)
                {
                    if (txtProxyUserName.Text.Length == 0)
                    {
                        epErrors.SetError(txtProxyUserName, "A user name is " +
                                          "required if not using default credentials");
                        isValid = false;
                    }

                    if (txtProxyPassword.Text.Length == 0)
                    {
                        epErrors.SetError(txtProxyPassword, "A password is " +
                                          "required if not using default credentials");
                        isValid = false;
                    }
                }
            }

            if (!isValid)
            {
                return;
            }

            if (txtAjaxDocUrl.Text[txtAjaxDocUrl.Text.Length - 1] != '/')
            {
                txtAjaxDocUrl.Text += "/";
            }

            // Store the changes
            root = config.SelectSingleNode("configuration");

            node = root.SelectSingleNode("ajaxDoc");
            if (node == null)
            {
                node = config.CreateNode(XmlNodeType.Element,
                                         "ajaxDoc", null);
                root.AppendChild(node);

                attr = config.CreateAttribute("url");
                node.Attributes.Append(attr);
                attr = config.CreateAttribute("project");
                node.Attributes.Append(attr);
                attr = config.CreateAttribute("regenerate");
                node.Attributes.Append(attr);
            }

            node.Attributes["url"].Value        = txtAjaxDocUrl.Text;
            node.Attributes["project"].Value    = txtProjectName.Text;
            node.Attributes["regenerate"].Value =
                chkRegenerateFiles.Checked.ToString().ToLower(
                    CultureInfo.InvariantCulture);

            userCreds = new UserCredentials(chkUseDefaultCredentials.Checked,
                                            txtUserName.Text, txtPassword.Text);
            userCreds.ToXml(config, root);

            proxyCreds = new ProxyCredentials(chkUseProxyServer.Checked,
                                              proxyServer, new UserCredentials(chkUseProxyDefCreds.Checked,
                                                                               txtProxyUserName.Text, txtProxyPassword.Text));
            proxyCreds.ToXml(config, root);

            this.DialogResult = DialogResult.OK;
            this.Close();
        }
Example #15
0
        public XmlElement ToXml(XmlDocument document)
        {
            XmlElement adNode    = document.CreateElement("idmef:AdditionalData", "http://iana.org/idmef");
            XmlNode    adSubNode = document.CreateNode(XmlNodeType.Text, "idmef", EnumDescription.GetEnumDescription(type), "http://iana.org/idmef");

            switch (type)
            {
            case ADEnum.boolean:
                adSubNode.Value = data_boolean.ToString();
                break;

            case ADEnum.adByte:
                adSubNode.Value = data_byte.ToString();
                break;

            case ADEnum.character:
                adSubNode.Value = data_character.ToString();
                break;

            case ADEnum.datetime:
                adSubNode.Value = data_datetime.ToString("o");
                break;

            case ADEnum.integer:
                adSubNode.Value = data_integer.ToString();
                break;

            case ADEnum.ntpstamp:
                adSubNode.Value = data_ntpstamp.ToString();
                break;

            case ADEnum.portlist:
                adSubNode.Value = data_portlist.ToString();
                break;

            case ADEnum.real:
                adSubNode.Value = data_real.ToString();
                break;

            case ADEnum.adString:
                adSubNode.Value = data_string;
                break;

            case ADEnum.byteString:
                adSubNode.Value = Convert.ToBase64String(data_bytestring);
                break;

            case ADEnum.xml:
                try
                {
                    adSubNode          = document.CreateElement("idmef:xml", "http://iana.org/idmef");
                    adSubNode.InnerXml = data_xml.OuterXml;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
                break;
            }

            adNode.SetAttribute("type", EnumDescription.GetEnumDescription(type));
            if (!string.IsNullOrEmpty(meaning))
            {
                adNode.SetAttribute("meaning", meaning);
            }
            adNode.AppendChild(adSubNode);

            return(adNode);
        }
    protected string GetPlayerCompareChartXML()
    {
        int maxGameNumber = 0;
        bool addGameToCategory = false;
        XmlDocument xmlDoc = new XmlDocument();
        XmlNode xmlNode = xmlDoc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
        xmlDoc.AppendChild(xmlNode);
        XmlElement xEle = xmlDoc.CreateElement("graph");
        xEle.SetAttribute("showvalues", "0");
        xEle.SetAttribute("xAxisName", "Games Played");
        xEle.SetAttribute("yAxisName", statId);
        xEle.SetAttribute("decimalPrecision", "0");
        xEle.SetAttribute("rotateName", "1");
        XmlElement categories = xmlDoc.CreateElement("categories");
        XmlElement player1 = xmlDoc.CreateElement("dataset");
        player1.SetAttribute("seriesname", player1Name);
        player1.SetAttribute("color", "#660000");
        player1.SetAttribute("showAnchors", "1");
        player1.SetAttribute("anchorAlpha", "0");
        XmlElement player2 = xmlDoc.CreateElement("dataset");
        player2.SetAttribute("seriesname", player2Name);
        player2.SetAttribute("color", "#000066");
        player2.SetAttribute("showAnchors", "1");
        player2.SetAttribute("anchorAlpha", "0");
        XmlElement tmpElement;
        String sqlString = GetDataString(player1Id);
        SqlCommand sqlCommand = new SqlCommand(sqlString, scripts.GetConnection());
        using (SqlDataReader reader = sqlCommand.ExecuteReader())
        {
            while (reader.Read())
            {
                tmpElement = xmlDoc.CreateElement("category");
                tmpElement.SetAttribute("name", Convert.ToString(reader[0]));
                if (Convert.ToUInt32(reader[0]) % modBy == 0)
                    tmpElement.SetAttribute("showName", "1");
                else
                    tmpElement.SetAttribute("showName", "0");
                categories.AppendChild(tmpElement);

                tmpElement = xmlDoc.CreateElement("set");
                tmpElement.SetAttribute("value", Convert.ToString(reader[1]));
                player1.AppendChild(tmpElement);
                maxGameNumber = Convert.ToInt32(reader[0]);
            }
        }
        String sqlString2 = GetDataString(player2Id);
        SqlCommand sqlCommand2 = new SqlCommand(sqlString2, scripts.GetConnection());
        using (SqlDataReader reader = sqlCommand2.ExecuteReader())
        {
            while (reader.Read())
            {
                tmpElement = xmlDoc.CreateElement("set");
                tmpElement.SetAttribute("value", Convert.ToString(reader[1]));
                player2.AppendChild(tmpElement);

                if(addGameToCategory || Convert.ToInt32(reader[0]) > maxGameNumber)
                {
                    tmpElement = xmlDoc.CreateElement("category");
                    tmpElement.SetAttribute("name", Convert.ToString(reader[0]));
                    if (Convert.ToUInt32(reader[0]) % modBy == 0)
                        tmpElement.SetAttribute("showName", "1");
                    else
                        tmpElement.SetAttribute("showName", "0");
                    categories.AppendChild(tmpElement);
                    addGameToCategory = true;
                }

            }
        }
        if(Request["showTrends"] == "true")
        {
            XmlElement trendline = AddTrends(xmlDoc, player1, player2, xEle);
            xEle.AppendChild(trendline);
        }

        xEle.AppendChild(categories);
        xEle.AppendChild(player1);
        xEle.AppendChild(player2);

        xmlDoc.AppendChild(xEle);
        return xmlDoc.OuterXml;
    }
Example #17
0
        static void Control(MenuEnum menu, XmlDocument docAccount, XmlDocument docTransaction, XmlDocument docSaving)
        {
            switch (menu)
            {
            case MenuEnum.LOGIN:
                do
                {
                    Console.WriteLine("Enter user name: ");
                    string userName = Convert.ToString(Console.ReadLine());
                    Console.WriteLine("Enter pass word: ");
                    string passWord = Convert.ToString(Console.ReadLine());
                    Login(userName, passWord);
                    Transaction newTransaction = new Transaction();
                    Options();
                    int        minimum        = 50000;
                    XmlElement elementAccount = docAccount.DocumentElement;
                    XmlNode    nodeElement    = elementAccount.SelectSingleNode("Account[userName='******']");
                    var        fromAccount    = new double();
                    double.TryParse(nodeElement.ChildNodes[(int)AccountEnum.ACCOUNTNUMBER].InnerText, out fromAccount);
                    OptionEnum option = (OptionEnum)int.Parse(Console.ReadLine());
                    switch (option)
                    {
                    case OptionEnum.DEPOSIT:
                        newTransaction.toAccount   = fromAccount;
                        newTransaction.fromAccount = fromAccount;
                        Deposit(docTransaction, nodeElement, newTransaction, minimum);
                        nodeElement.ChildNodes[8].InnerText = (double.Parse(nodeElement.ChildNodes[(int)AccountEnum.BALANCE].InnerText) + newTransaction.amount).ToString();
                        docAccount.Save("Account.xml");
                        Console.WriteLine("Deposit successful!!!");
                        Console.ReadLine();
                        break;

                    case OptionEnum.WITHDRAW:
                        newTransaction.toAccount   = fromAccount;
                        newTransaction.fromAccount = fromAccount;
                        Withdraw(docTransaction, nodeElement, newTransaction, minimum);
                        if ((double.Parse(nodeElement.ChildNodes[(int)AccountEnum.BALANCE].InnerText) - minimum) > newTransaction.amount)
                        {
                            nodeElement.ChildNodes[(int)AccountEnum.BALANCE].InnerText = (double.Parse(nodeElement.ChildNodes[(int)AccountEnum.BALANCE].InnerText) - newTransaction.amount).ToString();
                            docAccount.Save("Account.xml");
                            Console.WriteLine("Withdraw successful!!!");
                            Console.ReadLine();
                        }
                        else
                        {
                            Notification();
                        }
                        break;

                    case OptionEnum.TRANSFER:
                        newTransaction.fromAccount = fromAccount;
                        Transfer(docTransaction, nodeElement, newTransaction, minimum);
                        XmlNode nodeToAccount = elementAccount.SelectSingleNode("Account[accountNumber='" + newTransaction.toAccount.ToString() + "']");
                        if ((double.Parse(nodeElement.ChildNodes[(int)AccountEnum.BALANCE].InnerText) - minimum) > newTransaction.amount)
                        {
                            nodeToAccount.ChildNodes[(int)AccountEnum.BALANCE].InnerText = (double.Parse(nodeToAccount.ChildNodes[(int)AccountEnum.BALANCE].InnerText) + newTransaction.amount).ToString();
                            nodeElement.ChildNodes[(int)AccountEnum.BALANCE].InnerText   = (double.Parse(nodeElement.ChildNodes[(int)AccountEnum.BALANCE].InnerText) - newTransaction.amount).ToString();
                            docAccount.Save("Account.xml");
                            Console.WriteLine("Transfer successful!!!");
                            Console.ReadLine();
                        }
                        else
                        {
                            Notification();
                        }
                        break;

                    case OptionEnum.OPENSAVING:
                        do
                        {
                            Saving newSaving = new Saving();
                            newSaving.AddSaving();
                            if (newSaving.amount < double.Parse(nodeElement.ChildNodes[(int)AccountEnum.BALANCE].InnerText) - minimum)
                            {
                                Saving(docTransaction, nodeElement, newTransaction, newSaving);
                                XmlNodeList node = docSaving.GetElementsByTagName("Saving");
                                int         id   = 0;
                                for (int i = 0; i < node.Count; i++)
                                {
                                    id = int.Parse(node[node.Count - 1].ChildNodes[(int)SavingEnum.ID].InnerText) + 1;
                                }
                                newSaving.idSaving = id;
                                //create node and element
                                XmlNode nodeChild = docSaving.CreateNode(XmlNodeType.Element, "Saving", null);
                                XmlNode nodeId    = docSaving.CreateElement("id");
                                nodeId.InnerText = newSaving.idSaving.ToString();
                                XmlNode nodeAccount = docSaving.CreateElement("accountNumber");
                                nodeAccount.InnerText = nodeElement.ChildNodes[(int)AccountEnum.ACCOUNTNUMBER].InnerText;
                                XmlNode nodeDuration = docSaving.CreateElement("duration");
                                nodeDuration.InnerText = newSaving.duration.ToString();
                                XmlNode nodeAmount = docSaving.CreateElement("amount");
                                nodeAmount.InnerText = newSaving.amount.ToString();
                                XmlNode nodeInteres = docSaving.CreateElement("interes");
                                nodeInteres.InnerText = newSaving.interesRate.ToString();
                                XmlNode nodeTimeStart = docSaving.CreateElement("timeAccount");
                                nodeTimeStart.InnerText = DateTime.Now.ToString();
                                XmlNode nodeRate = docSaving.CreateElement("rate");
                                nodeRate.InnerText = newSaving.rate.ToString();
                                //append element in node
                                nodeChild.AppendChild(nodeId);
                                nodeChild.AppendChild(nodeAccount);
                                nodeChild.AppendChild(nodeDuration);
                                nodeChild.AppendChild(nodeAmount);
                                nodeChild.AppendChild(nodeInteres);
                                nodeChild.AppendChild(nodeTimeStart);
                                nodeChild.AppendChild(nodeRate);
                                //append node in root and save file
                                docSaving.DocumentElement.AppendChild(nodeChild);
                                docSaving.Save("Saving.xml");
                                nodeElement.ChildNodes[(int)AccountEnum.BALANCE].InnerText = (double.Parse(nodeElement.ChildNodes[(int)AccountEnum.BALANCE].InnerText) - newSaving.amount).ToString();
                                docAccount.Save("Account.xml");
                                Console.WriteLine("Open saving account successful!!!!!");
                                Console.ReadLine();
                                break;
                            }
                            else
                            {
                                Notification();
                            }
                        }while (true);
                        break;

                    case OptionEnum.MATUNITYSAVING:
                        MaturitySaving(docSaving, docAccount, nodeElement);
                        break;

                    case OptionEnum.FREEZEACCOUNT:
                        Console.WriteLine("1.Disable \n2.Active ");
                        FreeZeeAccountEnum freeze = (FreeZeeAccountEnum)int.Parse(Console.ReadLine());
                        switch (freeze)
                        {
                        case FreeZeeAccountEnum.DISABLE:
                            DisableAccount(docAccount, nodeElement);
                            break;

                        case FreeZeeAccountEnum.ACTIVE:
                            ActiveAccount(docAccount, nodeElement);
                            break;
                        }
                        break;

                    case OptionEnum.DISPLAYTRANSACTION:
                        DisplayTransaction(docTransaction, nodeElement);
                        break;

                    case OptionEnum.LOGOUT:
                        break;

                    default:
                        break;
                    }
                    break;
                }while (true);
                break;

            case MenuEnum.REGISTER:
                Register();
                Console.ReadLine();
                break;

            default:
                break;
            }
        }
        /// <summary>
        /// Подготовить объект для отправки адресату по его запросу
        /// </summary>
        /// <param name="s">Событие - идентификатор запрашиваемой информации/операции,действия</param>
        /// <param name="error">Признак выполнения операции/действия по запросу</param>
        /// <param name="outobj">Объект для отправления адресату как результат запроса</param>
        /// <returns>Признак выполнения метода (дополнительный)</returns>
        protected override int StateCheckResponse(int s, out bool error, out object outobj)
        {
            int           iRes  = -1;
            StatesMachine state = (StatesMachine)s;
            PACKAGE       package;
            XmlDocument   xmlDocNew;
            XmlNode       nodeRec;
            string        debugMsg = string.Empty;

            error  = true;
            outobj = null;

            ItemQueue itemQueue = null;

            try {
                switch (state)
                {
                case StatesMachine.NEW:     // новый пакет
                    iRes  = 0;
                    error = false;

                    itemQueue = Peek;

                    // удалить лишние пакеты
                    removePackages();

                    xmlDocNew = (XmlDocument)itemQueue.Pars[1];

                    if (m_xmlDocRecieved == null)
                    {
                        m_xmlDocRecieved = UDPListener.CopyXmlDocument(xmlDocNew);
                    }
                    else
                    {
                        ;
                    }

                    foreach (XmlNode nodeNew in xmlDocNew.ChildNodes[1])       //[0] - header, [1] - xml
                    {
                        debugMsg += string.Format(@"{0}, ", nodeNew.Name);

                        if (_dictBuildingParameterRecieved.ContainsKey(nodeNew.Name) == false)
                        {
                            _dictBuildingParameterRecieved.Add(nodeNew.Name, new GROUP_PARAMETER(DateTime.UtcNow));
                        }
                        else
                        {
                            _dictBuildingParameterRecieved[nodeNew.Name].Update(false);

                            if (_dictBuildingParameterRecieved[nodeNew.Name].IsUpdate == true)
                            {
                                nodeRec = m_xmlDocRecieved.ChildNodes[1].SelectSingleNode(nodeNew.Name);

                                if (nodeRec == null)
                                {
                                    nodeRec          = m_xmlDocRecieved.CreateNode(XmlNodeType.Element, nodeNew.Name, nodeNew.NamespaceURI);
                                    nodeRec.InnerXml = nodeNew.InnerXml;
                                    m_xmlDocRecieved.ChildNodes[1].AppendChild(nodeRec);
                                }
                                else
                                {
                                    //m_xmlDocRecieved.ChildNodes[1].ReplaceChild(xmlNode, node);
                                    nodeRec.InnerXml = nodeNew.InnerXml;
                                }
                            }
                            else
                            {
                                ;
                            }
                        }
                    }
                    //Console.WriteLine(string.Format(@"{0} получены: {1}", DateTime.UtcNow, debugMsg));

                    lock (this) {
                        if (_dictBuildingParameterRecieved.IsUpdate == true)
                        {
                            error = (iRes = addPackage((DateTime)itemQueue.Pars[0], m_xmlDocRecieved)) < 0 ? true : false;

                            _dictBuildingParameterRecieved.Update(true);
                        }
                        else
                        {
                            error = false;
                        }
                    }
                    break;

                case StatesMachine.LIST_PACKAGE:     // список пакетов
                    iRes  = 0;
                    error = false;

                    itemQueue = Peek;

                    outobj = listViewPackageItem;
                    break;

                case StatesMachine.PACKAGE_CONTENT:     // пакет
                    iRes  = 0;
                    error = false;

                    itemQueue = Peek;

                    Console.WriteLine(string.Format(@"{0} - Запрос {1}: за [{2}], индекс={3}, состояние={4}"                                                                                               //
                                                    , DateTime.UtcNow, state.ToString(), (DateTime)itemQueue.Pars[0], (int)itemQueue.Pars[2], ((DataGridViewElementStates)itemQueue.Pars[3]).ToString())); //

                    var selectPackages = from p in _listPackage where p.m_dtRecieved == (DateTime)itemQueue.Pars[0] select p;
                    if (selectPackages.Count() == 1)
                    {
                        package = selectPackages.ElementAt(0);

                        switch ((FormMain.INDEX_CONTROL)itemQueue.Pars[1])
                        {
                        case FormMain.INDEX_CONTROL.TABPAGE_VIEW_PACKAGE_XML:
                            outobj = package.m_xmlSource;
                            break;

                        case FormMain.INDEX_CONTROL.TABPAGE_VIEW_PACKAGE_TREE:
                            outobj = package.m_listXmlTree;
                            break;

                        case FormMain.INDEX_CONTROL.TABPAGE_VIEW_PACKAGE_TABLE_VALUE:
                            outobj = package.m_tableValues;
                            break;

                        case FormMain.INDEX_CONTROL.TABPAGE_VIEW_PACKAGE_TABLE_PARAMETER:
                            outobj = package.m_tableParameters;
                            break;

                        default:         //??? - ошибка неизвестный тип вкладки просмотра XML-документа
                            break;
                        }
                    }
                    else
                    {
                        ;     //??? - ошибка пакет не найден либо пакетов много
                    }
                    break;

                case StatesMachine.STATISTIC:     // статистика
                    iRes  = 0;
                    error = false;

                    itemQueue = Peek;

                    //outobj = ??? объект статический
                    break;

                case StatesMachine.OPTION:
                    iRes  = 0;
                    error = false;

                    itemQueue = Peek;

                    s_Option = (OPTION)itemQueue.Pars[0];
                    m_manualEventSetOption.Set();

                    //outobj = ??? только в одну сторону: форма -> handler
                    break;

                case StatesMachine.TIMER_TABLERES:     // срок отправлять очередной пакет
                    iRes  = 0;
                    error = false;

                    itemQueue = Peek;
                    // отправить строго крайний, при этом XML-пакет д.б. не отправленным
                    var orderPckages = from p in _listPackage /*where p.m_dtSended == DateTime.MinValue*/ orderby p.m_dtRecieved descending select p;
                    if (orderPckages.Count() > 0)
                    {
                        package = orderPckages.ElementAt(0);

                        if (package.m_dtSended == DateTime.MinValue)
                        {
                            package.m_dtSended = DateTime.UtcNow;
                            // объект со структурой DATA_SET
                            outobj = new object[] {
                                package.m_dtSended
                                , package.m_tableValues.Copy()
                                , package.m_tableParameters.Copy()
                            };
                        }
                        else
                        {
                            // не отправлять пакет на обработку
                            outobj = false;
                        }
                    }
                    else
                    {
                        //??? - ошибка пакет не найден либо пакетов много
                        //    iRes = -1;
                        //    error = true;
                        outobj = false;
                    }

                    _dictBuildingParameterRecieved.Update(false);
                    break;

                default:
                    break;
                }
            } catch (Exception e) {
                Logging.Logg().Exception(e, @"PackageHandlerQueue::StateCheckResponse (state=" + state.ToString() + @") - ...", Logging.INDEX_MESSAGE.NOT_SET);

                error = true;
                iRes  = -1 * (int)state;
            }

            return(iRes);
        }
Example #19
0
    protected int PullPrjBoard(bool PullActiveOnly, bool UpdateProjects)
    {
        string output = "";     //holds label output
        int count = 0;          //count of number of projects pulled, will return this value

        Lists listService = new Lists();
        ProjectsBLL project = new ProjectsBLL();

        listService.PreAuthenticate = true;
        listService.Credentials = System.Net.CredentialCache.DefaultCredentials;

        XmlDocument xmlDoc = new XmlDocument();
        XmlNode ndQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
        XmlNode ndViewFields = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
        XmlNode ndQueryOptions = xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");

        ndQueryOptions.InnerXml = "";// "<IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns>" + "<DateInUtc>TRUE</DateInUtc>";
        ndViewFields.InnerXml = "";// "<FieldRef Name='Title'/><FieldRef Name='Column5'/><FieldRef Name='Column4'/><FieldRef Name='Completed'/><FieldRef Name='Column12'/><FieldRef Name='Project_x0020_Site_x0020_URL'/><FieldRef Name='Project_x0020_Manager2'/><FieldRef Name='IT_x0020_Technical_x0020_Lead'/><FieldRef Name='Project_x0020_Phase'/>";

        //query XML with only completed items or all items?
        if (PullActiveOnly)
            ndQuery.InnerXml = "<Where><Eq><FieldRef Name='Completed'/><Value Type='Number'>0</Value></Eq></Where>";
        else
            ndQuery.InnerXml = "";

        try
        {
            XmlNode ndListItems;
            Hashtable prjHash = new Hashtable();

            //call web service to get all the projects from the PMO Project Board
            ndListItems = listService.GetListItems(PROJECT_BOARD_GUID, PROJECT_BOARD_VIEW_GUID, ndQuery, ndViewFields, null, ndQueryOptions);

            //create xml document so we can process
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(ndListItems.OuterXml);

            foreach (XmlNode element in doc.ChildNodes[0].ChildNodes[0].ChildNodes)
            {
                if (element.Attributes != null)
                {
                    foreach (XmlAttribute attr in element.Attributes)
                    {
                        switch (attr.Name)
                        {
                            //TODO: This will be different based on the fields in your SharePoint list.
                            case "ows_Title":
                                prjHash.Add("ProjectNumber", attr.Value);
                                break;
                            case "ows_NSR_x002f_Project_x0020_Name":
                                prjHash.Add("Name", attr.Value);
                                break;
                            case "ows_Completed":
                                //list contains 0 if not compeleted and -1 if completed
                                if (Convert.ToInt32(attr.Value) == 0)
                                    prjHash.Add("Active", true);
                                else
                                    prjHash.Add("Active", false);
                                break;
                            case "ows_Approved":
                                prjHash.Add("Approved", attr.Value);
                                break;
                            case "ows_Current_x0020_Status":
                                prjHash.Add("Status", attr.Value);
                                break;
                            case "ows_Project_x0020_Site_x0020_URL":
                                //list returns value as url,url.  we only need it once, so using split we take the first one
                                prjHash.Add("SiteURL", attr.Value.Split(',')[0]);
                                break;
                            case "ows_Project_x0020_Manager":
                                prjHash.Add("ProjectManager", attr.Value.Split('#')[1]);
                                break;
                            case "ows_Project_x0020_Phase":
                                prjHash.Add("PhaseID", attr.Value);
                                break;
                            case "ows_ID":
                                //once the attribute equals "ows_ID" we know we can process

                                //setup some temp holders
                                int projectID = Convert.ToInt32(attr.Value);
                                string number = prjHash["ProjectNumber"].ToString();
                                string name = prjHash["Name"].ToString();

                                string projectManager;
                                if (prjHash.ContainsKey("ProjectManager"))
                                    projectManager = prjHash["ProjectManager"].ToString();
                                else
                                    projectManager = "";

                                string siteURL;
                                if (prjHash.ContainsKey("SiteURL"))
                                    siteURL = prjHash["SiteURL"].ToString();
                                else
                                    siteURL = null;

                                int phaseID;
                                if (prjHash.ContainsKey("PhaseID"))
                                {
                                    switch (prjHash["PhaseID"].ToString())
                                    {
                                        case "Initiating":
                                            phaseID = 0;
                                            break;
                                        case "Planning":
                                            phaseID = 1;
                                            break;
                                        case "Execution":
                                            phaseID = 2;
                                            break;
                                        case "Monitoring":
                                            phaseID = 3;
                                            break;
                                        case "Closing":
                                            phaseID = 4;
                                            break;
                                        case "Proposals":
                                            phaseID = 5;
                                            break;
                                        case "Startups/Turndowns":
                                            phaseID = 6;
                                            break;
                                        case "Startup":
                                            phaseID = 7;
                                            break;
                                        case "Turndown":
                                            phaseID = 8;
                                            break;
                                        case "Win-awaiting NTP":
                                            phaseID = 9;
                                            break;
                                        default:
                                            phaseID = -1;
                                            break;
                                    }
                                }
                                else
                                    phaseID = -1;

                                bool active;
                                if (Convert.ToBoolean(prjHash["Active"]) && (prjHash["Approved"].ToString() == "Approved as Project" || prjHash["Approved"].ToString() == "NSR Analysis"))
                                    active = true;
                                else
                                    active = false;

                                //DEBUG PRINT
                                //output += "<tr><td>Debug: " + number + " - " + name + "</td><td style=\"color: #FFFFE0;\"> (ID = " + attr.Value + ")</td>";

                                //first we check to see if this project already exists
                                if (project.ProjectIDExists(projectID) < 1)
                                {
                                    output += "<tr><td>Adding: " + number + " - " + name + "</td><td style=\"color: #FFFFE0;\"> (ID = " + attr.Value + ")</td>";

                                    //add the project to the db, first checking to see if SiteURL exists and is not empty
                                    if (prjHash.ContainsKey("SiteURL") && (string)prjHash["SiteURL"] != String.Empty)
                                        project.AddProject(projectID, number, name, siteURL, active, phaseID, projectManager);
                                    else
                                        project.AddProject(projectID, number, name, null, active, phaseID, projectManager);

                                    output += "<td>Complete!</td></tr>";

                                    count++;
                                }
                                else
                                {
                                    //otherwise the project already exists and we can update it
                                    if (UpdateProjects)
                                    {
                                        TimeKeeper.ProjectsDataTable prj = project.GetProjectByProjectID(projectID);
                                        TimeKeeper.ProjectsRow prjRow = prj[0];

                                        //output += "<tr><td>Update - " + number + " - " + name + "</td><td style=\"color: #FFFFE0;\"> (ID = " + attr.Value + ")</td>";
                                        //output += "<tr><td>active = " + active.ToString() + "</tr></td>";
                                        //count++;

                                        if (prjRow.Active != active)
                                        {
                                            //RUN DEACTIVATE PROJECT CODE HERE
                                            if (active == false)
                                            {
                                                ProjectMembersBLL projectMembers = new ProjectMembersBLL();

                                                int membersDeleted = projectMembers.DeleteProjectMembersByProjectID(projectID);

                                                output += "<tr><td>Deactivating: " + number + " - " + name + ", Removed " + membersDeleted.ToString() + " member(s)</td><td style=\"color: #FFFFE0;\"> (ID = " + attr.Value + ")</td>";
                                                project.UpdateProject(projectID, number, name, null, false, phaseID, projectManager);
                                                output += "<td>Complete!</td></tr>";
                                            }
                                            else
                                            {
                                                output += "<tr><td>Activating: " + number + " - " + name + "</td><td style=\"color: #FFFFE0;\"> (ID = " + attr.Value + ")</td>";
                                                project.UpdateProject(projectID, number, name, null, true, phaseID, projectManager);
                                                output += "<td>Complete!</td></tr>";
                                            }
                                            count++;
                                        }

                                        if (prjRow.ProjectNumber != number || prjRow.Name != name || prjRow.PhaseID != phaseID || prjRow.ProjectManager.ToString() != projectManager)
                                        {
                                            //it does exist, print message
                                            output += "<tr><td>Updating: " + number + " - " + name + "</td><td style=\"color: #FFFFE0;\"> (ID = " + attr.Value + ")</td>";

                                            if (prjHash.ContainsKey("SiteURL") && (string)prjHash["SiteURL"] != String.Empty)
                                            {
                                                project.UpdateProject(projectID, number, name, siteURL, active, phaseID, projectManager);
                                            }
                                            else
                                            {
                                                project.UpdateProject(projectID, number, name, null, active, phaseID, projectManager);
                                            }
                                            output += "<td>Complete!</td></tr>";

                                            count++;
                                        }
                                        if (prjRow.IsTeamSiteURLNull() && prjHash.ContainsKey("SiteURL") && (string)prjHash["SiteURL"] != String.Empty)
                                        {
                                            //there is a new team site that we need to add
                                            output += "<tr><td>Team Site added: " + number + " - " + name + "</td><td style=\"color: #FFFFE0;\"> (ID = " + attr.Value + ")</td>";
                                            project.UpdateProject(projectID, number, name, siteURL, active, phaseID, projectManager);
                                            output += "<td>Complete!</td></tr>";

                                            count++;
                                        }
                                    }
                                }
                                break;
                        }
                    }
                }

                //clear the hash for the next element
                prjHash.Clear();
            }
        }
        catch (System.Web.Services.Protocols.SoapException ex)
        {
            output = ex.StackTrace;
        }

        //set label
        PullOutputLabel.Text = output;

        return count;
    }
Example #20
0
        /// <summary>
        /// Adds a dashboard to the config
        /// </summary>
        /// <param name="usercontrols"></param>
        /// <param name="section"></param>
        /// <param name="tabCaption"></param>
        /// <param name="dbconfig"></param>
        /// <returns></returns>
        private ResultItem AddDashboard(List <string> usercontrols, string section, string tabCaption, XmlDocument dbconfig)
        {
            var rs = new ResultItem
            {
                Name = "Adding Dashboard",
                CompletedSuccessfully = true,
                Description           = string.Format("Successfully added {0} Dashboard", tabCaption),
                RequiresConfigUpdate  = true
            };

            if (!DashboardExists(dbconfig, tabCaption))
            {
                try
                {
                    //StartupDeveloperDashboardSection

                    //  <tab caption="Dialogue Importer">
                    //      <control addPanel="true" panelCaption="">
                    //          /usercontrols/dialogueimporter.ascx
                    //      </control>
                    //  </tab>

                    // App settings root
                    var dbSection = dbconfig.SelectSingleNode(string.Format("dashBoard/section[@alias='{0}']", section));

                    // Create new tab
                    var tab         = dbconfig.CreateNode(XmlNodeType.Element, "tab", null);
                    var captionAttr = dbconfig.CreateAttribute("caption");
                    captionAttr.Value = tabCaption;
                    tab.Attributes.Append(captionAttr);

                    // Loop through usercontrols to add controls
                    for (var i = 0; i < usercontrols.Count; i++)
                    {
                        // Create control
                        var control      = dbconfig.CreateNode(XmlNodeType.Element, "control", null);
                        var addPanelAttr = dbconfig.CreateAttribute("addPanel");
                        addPanelAttr.Value = "true";
                        control.Attributes.Append(addPanelAttr);
                        control.InnerText = usercontrols[i];

                        tab.AppendChild(control);
                    }

                    // Append tab to Section
                    dbSection.AppendChild(tab);

                    return(rs);
                }
                catch (Exception ex)
                {
                    rs.Description           = string.Format("Failed to add {0} to dashboard config, error: {1}", tabCaption, ex.InnerException);
                    rs.CompletedSuccessfully = false;
                    rs.RequiresConfigUpdate  = false;
                }
            }
            else
            {
                rs.Description           = string.Format("Skipped adding {0} to dashboard config, already exists", tabCaption);
                rs.CompletedSuccessfully = true;
                rs.RequiresConfigUpdate  = false;
            }
            return(rs);
        }
Example #21
0
        private static void AddEntityFrameworkConfigSections(XmlDocument webconfig)
        {
            // get the configSections
            var configSections = webconfig.SelectSingleNode("configuration/configSections");

            // Create new section
            var newSection = webconfig.CreateNode(XmlNodeType.Element, "section", null);

            // Attributes
            var nameAttr = webconfig.CreateAttribute("name");

            nameAttr.Value = "entityFramework";
            var typeAttr = webconfig.CreateAttribute("type");

            typeAttr.Value = "System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
            var requirePermissionAttr = webconfig.CreateAttribute("requirePermission");

            requirePermissionAttr.Value = "false";
            newSection.Attributes.Append(nameAttr);
            newSection.Attributes.Append(typeAttr);
            newSection.Attributes.Append(requirePermissionAttr);

            // Append it
            configSections.AppendChild(newSection);

            // get the configSections
            var mainConfig = webconfig.SelectSingleNode("configuration");

            // Create <entityFramework>
            var entityFramework = webconfig.CreateNode(XmlNodeType.Element, "entityFramework", null);

            // Create
            var defaultConnectionFactory = webconfig.CreateNode(XmlNodeType.Element, "defaultConnectionFactory", null);
            var dcType = webconfig.CreateAttribute("type");

            dcType.Value = "System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework";
            defaultConnectionFactory.Attributes.Append(dcType);
            entityFramework.AppendChild(defaultConnectionFactory);

            // Create Providers
            var providers = webconfig.CreateNode(XmlNodeType.Element, "providers", null);

            // Create Provider element
            var provider          = webconfig.CreateNode(XmlNodeType.Element, "provider", null);
            var provinvariantName = webconfig.CreateAttribute("invariantName");

            provinvariantName.Value = "System.Data.SqlClient";
            provider.Attributes.Append(provinvariantName);
            var provType = webconfig.CreateAttribute("type");

            provType.Value = "System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer";
            provider.Attributes.Append(provType);

            // Append Provide to Providers
            providers.AppendChild(provider);

            // Append Providers
            entityFramework.AppendChild(providers);

            // Append Providers
            mainConfig.AppendChild(entityFramework);

            //<entityFramework>
            //    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
            //    <providers>
            //        <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
            //    </providers>
            //</entityFramework>
        }
        private void sendEclaimsDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string XMLPATH = Application.StartupPath + "\\syncdata.xml";
            // start by getting the date everything was sent out from the xml file
            DateTime lastWrite    = new DateTime(1999, 12, 31);
            bool     okToContinue = true;

            if (File.Exists(XMLPATH))
            {
                XmlDocument toOpen = new XmlDocument();
                toOpen.Load(XMLPATH);

                try
                {
                    XmlElement ele = toOpen.DocumentElement;
                    lastWrite = System.Convert.ToDateTime(ele.InnerText);
                }
                catch
                {
                    // assume the data is corrupt and there was no last write date.
                    okToContinue = MessageBox.Show(this, "The file that specifies which batches have been sent to eclaims has been corrupted. Would you like to continue and " +
                                                   "send all batches to eclaims?", "Sync File Corrupt", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.Yes;
                }
            }
            int count = 0;

            if (okToContinue)
            {
                // Get the claims to process
                List <claim_batch> cbList    = new List <claim_batch>();
                claim_batch        cb        = new claim_batch();
                string             searchSQL = "SELECT * FROM claim_batch WHERE batch_date > CAST('" + CommonFunctions.ToMySQLDateTime(lastWrite)
                                               + "' AS DATETIME) AND SOURCE = 0";
                DataTable dt = cb.Search(searchSQL);
                count = dt.Rows.Count;

                foreach (DataRow aBatch in dt.Rows)
                {
                    cb = new claim_batch();
                    cb.Load(aBatch);
                    cbList.Add(cb);
                }



                // Add the claims as claims in Dentrix
                // NHDG_CLAIM_BATCHES - CLAIMBATCHID, BATCH_DATE, HANDLING ("Paper", "Electronic (ApexEDI)"
                // NHDG_CLAIM_TRANSACTIONS - CLAIM_ID, CLAIM_DB, CLAIMBATCHID, RESUBMIT_FLAG (char?), BATCH_RESUBMITTED
                data_mapping_schema dms          = new data_mapping_schema(3);
                SqlConnection       dbConnection = new SqlConnection(dms.GetConnectionString(false));

                try
                {
                    dbConnection.Open();

                    foreach (claim_batch aBatch in cbList)
                    {
                        SqlCommand sc = new SqlCommand("INSERT INTO NHDG_CLAIM_BATCHES (batch_date, handling) VALUES ('" +
                                                       CommonFunctions.ToMySQLDateTime(aBatch.batch_date) + "', '" + ConvertHandlingToDentrix(aBatch.handlingAsString) +
                                                       "')", dbConnection);
                        sc.ExecuteNonQuery();

                        sc.CommandText = "SELECT IDENT_CURRENT('NHDG_CLAIM_BATCHES')";
                        SqlDataReader getID = sc.ExecuteReader();
                        getID.Read();
                        int lastID = System.Convert.ToInt32(getID[0]);
                        getID.Close();

                        // Insert all the claims in the batch into nhdg_claim_transactions
                        foreach (claim aClaim in aBatch.GetMatchingClaims())
                        {
                            sc.CommandText = "INSERT INTO NHDG_CLAIM_TRANSACTIONS (CLAIM_ID, CLAIM_DB, CLAIMBATCHID) " +
                                             " VALUES (" + aClaim.claimidnum + "," + aClaim.claimdb + "," + lastID + ")";
                            sc.ExecuteNonQuery();
                        }
                    }
                }
                catch
                {
                    okToContinue = false;
                    MessageBox.Show("There was an error getting the data into the Dentrix database. The process cannot continue.");
                }
            }
            if (okToContinue)
            {
                XmlDocument toSave = new XmlDocument();
                XmlNode     toChange;
                if (File.Exists(XMLPATH))
                {
                    toSave.Load(XMLPATH);
                    toChange = toSave.DocumentElement;
                }
                else
                {
                    toChange = toSave.AppendChild(toSave.CreateNode(XmlNodeType.Element, "SyncData", ""));
                    toChange = toSave.DocumentElement.AppendChild(toSave.CreateTextNode("LastUpdate"));
                }

                toChange.InnerText = DateTime.Now.ToString();
                toSave.Save(XMLPATH);

                MessageBox.Show(count + " batches synced successfully.");
            }


            else
            {
                MessageBox.Show("Please contact a system administrator to fix the problems you encountered while syncing.");
            }
        }
Example #23
0
        internal void CreatePSXMLAll(string SettingName, string Description)
        {
            XmlNamespaceManager manager = new XmlNamespaceManager(xDoc.NameTable);
            string sDC              = "http://schemas.microsoft.com/SystemsCenterConfigurationManager/2009/07/10/DesiredConfiguration";
            string sRules           = "http://schemas.microsoft.com/SystemsCenterConfigurationManager/2009/06/14/Rules";
            string AuthoringScopeId = "ScopeId_709B4C9D-07C0-476D-9CF4-2E760FA01892";

            manager.AddNamespace("dc", sDC);
            manager.AddNamespace("rules", sRules);

            string PSLogicalName = "ScriptSetting_" + Guid.NewGuid().ToString();

            XmlNode xSimpleSetting = xDoc.CreateNode(XmlNodeType.Element, "SimpleSetting", sDC);

            var xLogicalname = xDoc.CreateAttribute("LogicalName");

            xLogicalname.Value = PSLogicalName;
            xSimpleSetting.Attributes.Append(xLogicalname);

            //Add DataType Attribute
            var xDataType = xDoc.CreateAttribute("DataType");

            xDataType.Value = "Boolean"; //PS Script return Boolean
            xSimpleSetting.Attributes.Append(xDataType);

            //Load default Structure
            xSimpleSetting.InnerXml = Properties.Settings.Default.PSScript.Replace("{DISPLAYNAME}", SettingName).Replace("{DESC}", Description).Replace("{RESOURCEID}", "ID-" + Guid.NewGuid().ToString());
            xSimpleSetting.InnerXml = xSimpleSetting.InnerXml.Replace("{PSDISC}", GetPSCheckAll()).Replace("{PSREM}", GetPSRemediateAll()).Replace("{X64}", x64.ToString().ToLower());

            XmlNode RCS = xDoc.SelectSingleNode("//dc:DesiredConfigurationDigest/dc:Application/dc:Settings/dc:RootComplexSetting", manager);

            RCS.AppendChild(xSimpleSetting);

            //Add Rule
            XmlNode xRule = xDoc.CreateNode(XmlNodeType.Element, "Rule", sRules);

            var xRuleid = xDoc.CreateAttribute("id");

            xRuleid.Value = "Rule_" + Guid.NewGuid().ToString();
            xRule.Attributes.Append(xRuleid);

            var xSeverity = xDoc.CreateAttribute("Severity");

            xSeverity.Value = "Warning";
            xRule.Attributes.Append(xSeverity);


            var xNonComp = xDoc.CreateAttribute("NonCompliantWhenSettingIsNotFound");

            xNonComp.Value = "true";
            xRule.Attributes.Append(xNonComp);


            xRule.InnerXml = Properties.Settings.Default.RulePSBool.Replace("{DISPLAYNAME}", SettingName).Replace("{RESOURCEID}", "ID-" + Guid.NewGuid().ToString());
            xRule.InnerXml = xRule.InnerXml.Replace("{AUTHORINGSCOPEID}", AuthoringScopeId).Replace("{LOGICALNAME}", LogicalName).Replace("{DATATYPE}", "Boolean");
            xRule.InnerXml = xRule.InnerXml.Replace("{SETTINGLOGICALNAME}", PSLogicalName);

            XmlNode Rules = xDoc.SelectSingleNode("//dc:DesiredConfigurationDigest/dc:Application/dc:Rules", manager);

            Rules.AppendChild(xRule);
        }
Example #24
0
        public static void inregistrare()
        {
            string      filename = "exemplu2.xml";
            XmlDocument doc      = new XmlDocument(); //create new instance of XmlDocument

            doc.Load(filename);                       //load from file
            XmlNode NodeID = doc.CreateNode(XmlNodeType.Element, "S" + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString(), null);

            //Console.Clear();
            Console.WriteLine("\n\n\t\t\t\t\t╔═══════════════════════════════════════╗");
            Console.WriteLine("\t\t\t\t\t║\t      Introdu Nume \t\t║");
            Console.WriteLine("\t\t\t\t\t╚═══════════════════════════════════════╝");
            Console.Write("\t\t\t\t\t\t    ");
            string  Nume     = Console.ReadLine();
            XmlNode nodeNume = doc.CreateElement("Nume");

            nodeNume.InnerText = Nume;
            Console.Clear();
            Console.WriteLine("\n\n\t\t\t\t\t╔═══════════════════════════════════════╗");
            Console.WriteLine("\t\t\t\t\t║\t      Introdu Prenume \t\t║");
            Console.WriteLine("\t\t\t\t\t╚═══════════════════════════════════════╝");
            Console.Write("\t\t\t\t\t\t     ");
            string  Prenume     = Console.ReadLine();
            XmlNode nodePrenume = doc.CreateElement("Prenume");

            nodePrenume.InnerText = Prenume;
            bool bit = true;

start:
            Console.Clear();
            if (bit == false)
            {
                Console.WriteLine("Acest nickname nu este disponibil!");
            }

            Console.WriteLine("\n\n\t\t\t\t\t╔═══════════════════════════════════════╗");
            Console.WriteLine("\t\t\t\t\t║\t      Introdu Nickname \t\t║");
            Console.WriteLine("\t\t\t\t\t╚═══════════════════════════════════════╝");
            Console.Write("\t\t\t\t\t\t     ");
            string _login = Console.ReadLine();

            for (int i = 0; i < memor; i++)
            {
                if (_login == login[i])
                {
                    bit = false;
                    goto start;
                }
            }

            XmlNode nodelogin = doc.CreateElement("login");

            nodelogin.InnerText = _login;
            Console.Clear();
            Console.WriteLine("\n\n\t\t\t\t\t╔═══════════════════════════════════════╗");
            Console.WriteLine("\t\t\t\t\t║\t      Introdu parola \t\t║");
            Console.WriteLine("\t\t\t\t\t╚═══════════════════════════════════════╝");
            Console.Write("\t\t\t\t\t\t     ");
            string  parola     = Console.ReadLine();
            XmlNode nodeparola = doc.CreateElement("parola");

            nodeparola.InnerText = parola;
            Console.Clear();
            Console.WriteLine("\n\n\t\t\t\t\t╔═══════════════════════════════════════╗");
            Console.WriteLine("\t\t\t\t\t║\t      Introdu email \t\t║");
            Console.WriteLine("\t\t\t\t\t╚═══════════════════════════════════════╝");
            Console.Write("\t\t\t\t\t\t     ");
            string  mail     = Console.ReadLine();
            XmlNode nodemail = doc.CreateElement("mail");

            nodemail.InnerText = mail;
            Console.Clear();

            NodeID.AppendChild(nodeNume);
            NodeID.AppendChild(nodePrenume);
            NodeID.AppendChild(nodelogin);
            NodeID.AppendChild(nodeparola);
            NodeID.AppendChild(nodemail);

            //add to elements collection
            doc.DocumentElement.AppendChild(NodeID);
            //save back
            doc.Save(filename);

            Loading.show();
            //introducem parola, loginul, emailul, numele, prenumele, varsta
            //verificam daca datele sunt introduse corect
        }
Example #25
0
    public void UpdateXml(string filename, string title, string content, string user)
    {
        XmlDocument mydoc = new XmlDocument();
        mydoc.Load( filename);

        XmlElement ele = mydoc.CreateElement("title");
        XmlText text = mydoc.CreateTextNode(title);

        XmlElement ele1 = mydoc.CreateElement("posttime");
        XmlText text1 = mydoc.CreateTextNode(DateTime.Now.ToString());

        XmlElement ele2 = mydoc.CreateElement("content");
        XmlText text2 = mydoc.CreateTextNode(content);

        XmlElement ele3 = mydoc.CreateElement("postuser");
        XmlText text3 = mydoc.CreateTextNode(user);

        XmlNode newElem = mydoc.CreateNode("element", "xmlrecord", "");

        newElem.AppendChild(ele);
        newElem.LastChild.AppendChild(text);
        
        newElem.AppendChild(ele1);
        newElem.LastChild.AppendChild(text1);

        newElem.AppendChild(ele2);
        newElem.LastChild.AppendChild(text2);

        newElem.AppendChild(ele3);
        newElem.LastChild.AppendChild(text3);

        XmlElement root = mydoc.DocumentElement;
        root.AppendChild(newElem);

        mydoc.Save(filename);
    }
Example #26
0
        void UpdateWebConfigRefs()
        {
            var refs = new List <string> ();

            foreach (var reference in References)
            {
                //local copied assemblies are copied to the bin directory so ASP.NET references them automatically
                if (reference.LocalCopy && (reference.ReferenceType == ReferenceType.Project || reference.ReferenceType == ReferenceType.Assembly))
                {
                    continue;
                }
                if (string.IsNullOrEmpty(reference.Reference))
                {
                    continue;
                }
                //these assemblies are referenced automatically by ASP.NET
                if (IsSystemReference(reference.Reference))
                {
                    continue;
                }
                //bypass non dotnet projects
                if ((reference.ReferenceType == ReferenceType.Project) &&
                    (!(reference.OwnerProject.ParentSolution.FindProjectByName(reference.Reference) is DotNetProject)))
                {
                    continue;
                }
                refs.Add(reference.Reference);
            }

            var webConfig = GetWebConfig();

            if (webConfig == null || !File.Exists(webConfig.FilePath))
            {
                return;
            }

            var textFile = MonoDevelop.Ide.TextFileProvider.Instance.GetEditableTextFile(webConfig.FilePath);

            //use textfile API because it's write safe (writes out to another file then moves)
            if (textFile == null)
            {
                textFile = MonoDevelop.Projects.Text.TextFile.ReadFile(webConfig.FilePath);
            }

            //can't use System.Web.Configuration.WebConfigurationManager, as it can only access virtual paths within an app
            //so need full manual handling
            try {
                System.Xml.XmlDocument doc = new XmlDocument();

                //FIXME: PreserveWhitespace doesn't handle whitespace in attribute lists
                //doc.PreserveWhitespace = true;
                doc.LoadXml(textFile.Text);

                //hunt our way to the assemblies element, creating elements if necessary
                XmlElement configElement = doc.DocumentElement;
                if (configElement == null || string.Compare(configElement.Name, "configuration", StringComparison.OrdinalIgnoreCase) != 0)
                {
                    configElement = (XmlElement)doc.AppendChild(doc.CreateNode(XmlNodeType.Document, "configuration", null));
                }
                XmlElement webElement      = GetNamedXmlElement(doc, configElement, "system.web");
                XmlElement compilationNode = GetNamedXmlElement(doc, webElement, "compilation");
                XmlElement assembliesNode  = GetNamedXmlElement(doc, compilationNode, "assemblies");

                List <XmlNode> existingAdds = new List <XmlNode> ();
                foreach (XmlNode node in assembliesNode)
                {
                    if (string.Compare(node.Name, "add", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        existingAdds.Add(node);
                    }
                }

                //add refs to the doc if they're not in it
                foreach (string reference in refs)
                {
                    int  index = 0;
                    bool found = false;
                    while (index < existingAdds.Count)
                    {
                        XmlNode      node = existingAdds[index];
                        XmlAttribute att  = (XmlAttribute)node.Attributes.GetNamedItem("assembly");
                        if (att == null)
                        {
                            continue;
                        }
                        string refAtt = att.Value;
                        if (refAtt != null && refAtt == reference)
                        {
                            existingAdds.RemoveAt(index);
                            found = true;
                            break;
                        }
                        else
                        {
                            index++;
                        }
                    }
                    if (!found)
                    {
                        XmlElement   newAdd = doc.CreateElement("add");
                        XmlAttribute newAtt = doc.CreateAttribute("assembly");
                        newAtt.Value = reference;
                        newAdd.Attributes.Append(newAtt);
                        assembliesNode.AppendChild(newAdd);
                    }
                }

                //any nodes that weren't removed from the existingAdds list are old/redundant, so remove from doc
                foreach (XmlNode node in existingAdds)
                {
                    assembliesNode.RemoveChild(node);
                }

                StringWriter  sw = new StringWriter();
                XmlTextWriter tw = new XmlTextWriter(sw);
                tw.Formatting = Formatting.Indented;
                doc.WriteTo(tw);
                tw.Flush();
                textFile.Text = sw.ToString();

                MonoDevelop.Projects.Text.TextFile tf = textFile as MonoDevelop.Projects.Text.TextFile;
                if (tf != null)
                {
                    tf.Save();
                }
            } catch (Exception e) {
                LoggingService.LogWarning("Could not modify application web.config in project " + this.Name, e);
            }
        }
Example #27
0
        static void Register()
        {
            Account newAccount = new Account();

            newAccount.AddAccount();
            XmlDocument docAccount = new XmlDocument();

            docAccount.Load("Account.xml");
            XmlNodeList node = docAccount.GetElementsByTagName("Account");

            newAccount.idAccount  = node.Count + 1;
            newAccount.idCustomer = node.Count + 1;
            //create node and element
            XmlNode nodeChild     = docAccount.CreateNode(XmlNodeType.Element, "Account", null);
            XmlNode nodeIdAccount = docAccount.CreateElement("idAccount");

            nodeIdAccount.InnerText = newAccount.idAccount.ToString();
            XmlNode nodeAccountNumber = docAccount.CreateElement("accountNumber");

            nodeAccountNumber.InnerText = (newAccount.idAccount + 1000000).ToString();
            XmlNode nodeFullName = docAccount.CreateElement("fullName");

            nodeFullName.InnerText = newAccount.fullName.ToString();
            XmlNode nodeDateOfBirth = docAccount.CreateElement("dateOfBirth");

            nodeDateOfBirth.InnerText = newAccount.dateOfBirth.ToString();
            XmlNode nodePhoneNumber = docAccount.CreateElement("phoneNumber");

            nodePhoneNumber.InnerText = newAccount.phoneNumber.ToString();
            XmlNode nodeEmail = docAccount.CreateElement("email");

            nodeEmail.InnerText = newAccount.email.ToString();
            XmlNode nodeUserName = docAccount.CreateElement("userName");

            nodeUserName.InnerText = newAccount.userName.ToString();
            XmlNode nodePassWord = docAccount.CreateElement("passWord");

            nodePassWord.InnerText = newAccount.passWord.ToString();
            XmlNode nodeBalance = docAccount.CreateElement("balance");

            nodeBalance.InnerText = newAccount.balance.ToString();
            XmlNode nodeAddress = docAccount.CreateElement("address");

            nodeAddress.InnerText = newAccount.address.ToString();
            XmlNode nodeTypeAccount = docAccount.CreateElement("typeAccount");

            nodeTypeAccount.InnerText = newAccount.typeAccount.ToString();
            XmlNode nodeDisable = docAccount.CreateElement("disable");

            nodeDisable.InnerText = newAccount.disable.ToString();
            // append element in node
            nodeChild.AppendChild(nodeIdAccount);
            nodeChild.AppendChild(nodeAccountNumber);
            nodeChild.AppendChild(nodeFullName);
            nodeChild.AppendChild(nodeDateOfBirth);
            nodeChild.AppendChild(nodePhoneNumber);
            nodeChild.AppendChild(nodeEmail);
            nodeChild.AppendChild(nodeUserName);
            nodeChild.AppendChild(nodePassWord);
            nodeChild.AppendChild(nodeBalance);
            nodeChild.AppendChild(nodeAddress);
            nodeChild.AppendChild(nodeTypeAccount);
            nodeChild.AppendChild(nodeDisable);
            //append node in root and save file
            docAccount.DocumentElement.AppendChild(nodeChild);
            docAccount.Save("Account.xml");
            Console.WriteLine("REGISTER SUCCESSFUL!!!!!");
            Console.ReadLine();
        }
Example #28
0
        ///<summary>Creates a default ServiceConfig file at the full file path provided.
        ///The config contains the current connection settings in DataConnection and defaults LogLevelOfApplication to 'Error'.</summary>
        public static bool CreateServiceConfigFile(string filePath, string serverName, string databaseName, string mySqlUser, string mySqlPass
                                                   , string mySqlPassHash, string mySqlUserLow = "", string mySqlUserPassLow = "")
        {
            XmlDocument document = new XmlDocument();
            //Creating Nodes
            XmlNode nodeConnSettings = document.CreateNode(XmlNodeType.Element, "ConnectionSettings", "");
            XmlNode nodeDbeConn      = document.CreateNode(XmlNodeType.Element, "DatabaseConnection", "");
            XmlNode nodeCompName     = document.CreateNode(XmlNodeType.Element, "ComputerName", "");

            nodeCompName.InnerText = serverName;
            XmlNode nodeDatabase = document.CreateNode(XmlNodeType.Element, "Database", "");

            nodeDatabase.InnerText = databaseName;
            XmlNode nodeUser = document.CreateNode(XmlNodeType.Element, "User", "");

            nodeUser.InnerText = mySqlUser;
            XmlNode nodePassword = document.CreateNode(XmlNodeType.Element, "Password", "");

            nodePassword.InnerText = string.IsNullOrEmpty(mySqlPassHash) ? mySqlPass : "";          //write plain text pwd if encryption failed
            XmlNode nodePassHash = document.CreateNode(XmlNodeType.Element, "MySQLPassHash", "");

            nodePassHash.InnerText = mySqlPassHash ?? "";          //write encrypted password, if it's null then write an empty string
            XmlNode nodeUserLow = document.CreateNode(XmlNodeType.Element, "UserLow", "");

            nodeUserLow.InnerText = mySqlUserLow;
            XmlNode nodePasswordLow = document.CreateNode(XmlNodeType.Element, "PasswordLow", "");

            nodePasswordLow.InnerText = mySqlUserPassLow;
            XmlNode nodeDbType = document.CreateNode(XmlNodeType.Element, "DatabaseType", "");

            nodeDbType.InnerText = "MySql";          //Not going to support Oracle until someone complains.
            XmlNode nodeLogLevelOfApp = document.CreateNode(XmlNodeType.Element, "LogLevelOfApplication", "");

            nodeLogLevelOfApp.InnerText = "Error";
            //Assigning Structure
            nodeDbeConn.AppendChild(nodeCompName);
            nodeDbeConn.AppendChild(nodeDatabase);
            nodeDbeConn.AppendChild(nodeUser);
            nodeDbeConn.AppendChild(nodePassword);
            nodeDbeConn.AppendChild(nodePassHash);
            nodeDbeConn.AppendChild(nodeUserLow);
            nodeDbeConn.AppendChild(nodePasswordLow);
            nodeDbeConn.AppendChild(nodeDbType);
            nodeConnSettings.AppendChild(nodeDbeConn);
            nodeConnSettings.AppendChild(nodeLogLevelOfApp);
            document.AppendChild(nodeConnSettings);
            //Outputting completed XML document
            StringBuilder     strb     = new StringBuilder();
            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Indent             = true;
            settings.IndentChars        = "   ";
            settings.NewLineChars       = "\r\n";
            settings.OmitXmlDeclaration = true;
            try {
                using (XmlWriter xmlWriter = XmlWriter.Create(strb, settings)) {
                    document.WriteTo(xmlWriter);
                    xmlWriter.Flush();
                    File.WriteAllText(filePath, strb.ToString());
                }
                return(true);
            }
            catch {
                return(false);
            }
        }
    public static void BuildLegacyPackage()
    {
        var projectPath = Path.GetFullPath(Path.Combine(Application.dataPath, ".."));
        var assetsPath = Path.Combine(projectPath, "Assets");
        var pluginsPath = Path.Combine(assetsPath, "Plugins");
        var androidPluginsPath = Path.Combine(pluginsPath, "Android");
        var originalAssetsPath = Path.Combine(projectPath, "Assets_Original");
        var originalPluginsPath = Path.Combine(originalAssetsPath, "Plugins");
        var originalAndroidPluginsPath = Path.Combine(originalPluginsPath, "Android");
        var playerAndroidManifestPath =
            Path.Combine(EditorApplication.applicationContentsPath, "PlaybackEngines/AndroidPlayer/AndroidManifest.xml");
        var seedsAndroidManifestPath =
            Path.Combine(androidPluginsPath, "AndroidManifest.xml");

        EditorUtility.DisplayProgressBar("Seeds SDK", "Building package", 0.0f);
        try
        {
            if (Directory.Exists(originalAssetsPath))
                Directory.Delete(originalAssetsPath, true);
            Directory.CreateDirectory(originalPluginsPath);
            Directory.Move(androidPluginsPath, originalAndroidPluginsPath);
            Directory.CreateDirectory(androidPluginsPath);
            var androidManifestDocument = new XmlDocument();
            androidManifestDocument.Load(playerAndroidManifestPath);
            var androidNS = "http://schemas.android.com/apk/res/android";
            int? minSdkVersion = null;
            int? maxSdkVersion = null;

            foreach (var pluginFilepath in Directory.GetFiles(originalAndroidPluginsPath))
            {
                var pluginFilename = Path.GetFileName(pluginFilepath);

                if (pluginFilename.EndsWith("SeedsDeepLink.aar"))
                    continue;

                if (pluginFilename.EndsWith(".aar"))
                {
                    // Unpack
                    using (var androidLibraryZip = ZipFile.Read(pluginFilepath))
                    {
                        foreach (var zipEntry in androidLibraryZip.Entries)
                        {
                            if (zipEntry.FileName == "classes.jar")
                            {
                                var targetFilename = Path.GetFileNameWithoutExtension(pluginFilename) + ".jar";
                                var targetFilepath = Path.Combine(androidPluginsPath, targetFilename);
                                using (var stream = File.Open(targetFilepath, FileMode.Create))
                                {
                                    zipEntry.Extract(stream);
                                }

                                //Debug.LogErrorFormat("{0}:{1} unpacked to {2}", pluginFilename, zipEntry.FileName, targetFilename);
                            }
                            else if (zipEntry.FileName.EndsWith(".jar"))
                            {
                                var targetFilename =
                                    Path.GetFileNameWithoutExtension(pluginFilename) +
                                    "_" +
                                    Path.GetFileName(zipEntry.FileName);
                                var targetFilepath = Path.Combine(androidPluginsPath, targetFilename);
                                using (var stream = File.Open(targetFilepath, FileMode.Create))
                                {
                                    zipEntry.Extract(stream);
                                }

                               //Debug.LogFormat("{0}:{1} unpacked to {2}", pluginFilename, zipEntry.FileName, targetFilename);

                            }
                            else if (zipEntry.FileName == "AndroidManifest.xml")
                            {
                                var targetFilename = Path.GetFileNameWithoutExtension(pluginFilename) + "_AndroidManifest.xml";
                                var targetFilepath = Path.Combine(androidPluginsPath, targetFilename);
                                using (var stream = File.Open(targetFilepath, FileMode.Create))
                                {
                                    zipEntry.Extract(stream);
                                }

                                var manifestToMerge = new XmlDocument();
                                manifestToMerge.Load(targetFilepath);

                                var manifestNode = androidManifestDocument.SelectSingleNode("/manifest");
                                var manifestDeclarations = manifestToMerge.SelectNodes("manifest/*");
                                foreach (XmlNode manifestDeclaration in manifestDeclarations)
                                {
                                    if (manifestDeclaration.Name == "application")
                                        continue;
                                    else if (manifestDeclaration.Name == "uses-sdk")
                                    {
                                        var minSdkVersionNode =
                                            manifestDeclaration.Attributes.GetNamedItem("minSdkVersion", androidNS);
                                        if (minSdkVersionNode != null)
                                        {
                                            int value = int.Parse(minSdkVersionNode.Value);
                                            if (minSdkVersion == null)
                                                minSdkVersion = value;
                                            else
                                                minSdkVersion = Math.Max(minSdkVersion.Value, value);
                                        }

                                        var maxSdkVersionNode =
                                            manifestDeclaration.Attributes.GetNamedItem("maxSdkVersion", androidNS);
                                        if (maxSdkVersionNode != null)
                                        {
                                            int value = int.Parse(maxSdkVersionNode.Value);
                                            if (maxSdkVersion == null)
                                                maxSdkVersion = value;
                                            else
                                                maxSdkVersion = Math.Min(maxSdkVersion.Value, value);
                                        }

                                        continue;
                                    }

                                    var importedManifestDeclaration =
                                        androidManifestDocument.ImportNode(manifestDeclaration, true);

                                    manifestNode.AppendChild(importedManifestDeclaration);
                                }

                                var applicationNode = androidManifestDocument.SelectSingleNode("/manifest/application");
                                var applicationDeclarations = manifestToMerge.SelectNodes("manifest/application/*");
                                foreach (XmlNode applicationDeclaration in applicationDeclarations)
                                {
                                    var importedApplicationDeclaration =
                                        androidManifestDocument.ImportNode(applicationDeclaration, true);

                                    applicationNode.AppendChild(importedApplicationDeclaration);
                                }

                                File.Delete(targetFilename);
                            }
                            else if (
                                (zipEntry.Attributes & FileAttributes.Directory) == 0 &&
                                Path.GetFileName(zipEntry.FileName).Length > 0 &&
                                (zipEntry.FileName.StartsWith("res/") || zipEntry.FileName.StartsWith("assets/")))
                            {
                                var targetFilepath = Path.Combine(androidPluginsPath, zipEntry.FileName);
                                Directory.CreateDirectory(Path.GetDirectoryName(targetFilepath));
                                using (var stream = File.Open(targetFilepath, FileMode.Create))
                                {
                                    zipEntry.Extract(stream);
                                }
                                //Debug.LogErrorFormat("{0}:{1} unpacked to {2}", pluginFilename, zipEntry.FileName, zipEntry.FileName);

                            }
                        }
                    }
                    continue;
                }
                else if (pluginFilename.EndsWith(".aar.meta"))
                {
                    // Just skip
                    continue;
                }
                else
                {
                    // Copy as-is
                    File.Copy(pluginFilepath, Path.Combine(androidPluginsPath, pluginFilename));
                }
            }
            if (minSdkVersion != null || maxSdkVersion != null)
            {
                var usesSdkNode = androidManifestDocument.CreateNode(XmlNodeType.Element, "uses-sdk", "");

                if (minSdkVersion != null)
                {
                    var minSdkVersionAttribute = androidManifestDocument.CreateAttribute("android", "minSdkVersion", androidNS);
                    minSdkVersionAttribute.Value = minSdkVersion.Value.ToString();
                    usesSdkNode.Attributes.Append(minSdkVersionAttribute);
                }

                if (maxSdkVersion != null)
                {
                    var maxSdkVersionAttribute = androidManifestDocument.CreateAttribute("android", "maxSdkVersion", androidNS);
                    maxSdkVersionAttribute.Value = maxSdkVersion.Value.ToString();
                    usesSdkNode.Attributes.Append(maxSdkVersionAttribute);
                }

                var manifestNode = androidManifestDocument.SelectSingleNode("/manifest");
                manifestNode.AppendChild(usesSdkNode);
            }
            androidManifestDocument.Save(seedsAndroidManifestPath);

            var packagePath = "SeedsSDK_Legacy.unitypackage";

            EditorUtility.DisplayProgressBar("Seeds SDK", "Building package", 0.25f);

            var importOpts = ImportAssetOptions.Default;
            importOpts |= ImportAssetOptions.ForceSynchronousImport;
            importOpts |= ImportAssetOptions.ForceUpdate;
            importOpts |= ImportAssetOptions.ImportRecursive;
            AssetDatabase.Refresh(importOpts);
            var allAssets = AssetDatabase.GetAllAssetPaths();

            EditorUtility.DisplayProgressBar("Seeds SDK", "Building package", 0.5f);

            var assetsToExport = new List<string>();
            assetsToExport.Add("Assets/Seeds/Seeds.cs");
            assetsToExport.Add("Assets/Seeds/Seeds.prefab");
            assetsToExport.Add("Assets/Seeds/SeedsDeepLinks.cs");
            assetsToExport.Add("Assets/Seeds/SeedsDeepLinks.prefab");
            assetsToExport.Add("Assets/Seeds/Editor/SeedsIntegration.cs");
            assetsToExport.Add("Assets/Seeds/Editor/SeedsIntegrationDialogWindow.cs");
            assetsToExport.Add("Assets/Seeds/Editor/Ionic.Zip.dll");
            assetsToExport.AddRange(allAssets.Where(
                x => x.StartsWith("Assets/Plugins") &&
                File.Exists(Path.Combine(projectPath, x))));
            assetsToExport.AddRange(allAssets.Where(x =>
                x.StartsWith("Assets/Seeds/Demo") &&
                File.Exists(Path.Combine(projectPath, x))));
            var exportOpts = ExportPackageOptions.Recurse;
            AssetDatabase.ExportPackage(assetsToExport.ToArray(), packagePath, exportOpts);

            EditorUtility.DisplayProgressBar("Seeds SDK", "Building package", 0.9f);

            Directory.Delete(androidPluginsPath, true);
            Directory.Move(originalAndroidPluginsPath, androidPluginsPath);
            Directory.Delete(originalAssetsPath, true);
        }

        /*catch (Exception e)
        {
            Debug.LogErrorFormat("[Seeds] Build failed : {0}", e);
        }*/

        finally
        {
            EditorUtility.ClearProgressBar();
        }
    }
Example #30
0
        private Hashtable HandleHttpSessionCommand(Hashtable request)
        {
            DoExpire();

            Hashtable post  = DecodePostString(request["body"].ToString());
            Hashtable reply = new Hashtable();

            reply["str_response_string"] = "";
            reply["int_response_code"]   = 404;
            reply["content_type"]        = "text/plain";

            if (post["ID"] == null)
            {
                return(reply);
            }

            UUID id;

            if (!UUID.TryParse(post["ID"].ToString(), out id))
            {
                return(reply);
            }

            lock (m_Connections)
            {
                if (!m_Connections.ContainsKey(id))
                {
                    return(reply);
                }
            }

            if (post["COMMAND"] == null)
            {
                return(reply);
            }

            lock (m_InputData)
            {
                m_DataEvent.Set();
                m_InputData.Add(post["COMMAND"].ToString());
            }

            XmlDocument xmldoc  = new XmlDocument();
            XmlNode     xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
                                                    "", "");

            xmldoc.AppendChild(xmlnode);
            XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
                                                          "");

            xmldoc.AppendChild(rootElement);

            XmlElement res = xmldoc.CreateElement("", "Result", "");

            res.AppendChild(xmldoc.CreateTextNode("OK"));

            rootElement.AppendChild(res);

            reply["str_response_string"] = xmldoc.InnerXml;
            reply["int_response_code"]   = 200;
            reply["content_type"]        = "text/xml";
            reply = CheckOrigin(reply);

            return(reply);
        }
	/// <summary>
	/// Creaate a string-based option for xml
	/// </summary>
	/// <param name="doc">XML configuration document</param>
	/// <param name="optionName">name attribute of option</param>
	/// <param name="optionValue">value of option</param>
	/// <returns></returns>
	public XmlNode CreateOption(XmlDocument doc, string optionName, string optionValue)
	{
		XmlNode opt = doc.CreateNode(XmlNodeType.Element, "Option", null);
		XmlAttribute name = doc.CreateAttribute("Name");
		XmlText value = doc.CreateTextNode(optionValue);
		name.Value = optionName;
		opt.Attributes.Append(name);
		opt.AppendChild(value);
		return opt;
	}
Example #32
0
        private Hashtable GetEvents(UUID RequestID, UUID sessionID, string request)
        {
            ConsoleConnection c = null;

            lock (m_Connections)
            {
                if (!m_Connections.ContainsKey(sessionID))
                {
                    return(NoEvents(RequestID, UUID.Zero));
                }
                c = m_Connections[sessionID];
            }
            c.last = System.Environment.TickCount;
            if (c.lastLineSeen >= m_LineNumber)
            {
                return(NoEvents(RequestID, UUID.Zero));
            }

            Hashtable result = new Hashtable();

            XmlDocument xmldoc  = new XmlDocument();
            XmlNode     xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
                                                    "", "");

            xmldoc.AppendChild(xmlnode);
            XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
                                                          "");

            if (c.newConnection)
            {
                c.newConnection = false;
                Output("+++" + DefaultPrompt);
            }

            lock (m_Scrollback)
            {
                long startLine = m_LineNumber - m_Scrollback.Count;
                long sendStart = startLine;
                if (sendStart < c.lastLineSeen)
                {
                    sendStart = c.lastLineSeen;
                }

                for (long i = sendStart; i < m_LineNumber; i++)
                {
                    XmlElement res  = xmldoc.CreateElement("", "Line", "");
                    long       line = i + 1;
                    res.SetAttribute("Number", line.ToString());
                    res.AppendChild(xmldoc.CreateTextNode(m_Scrollback[(int)(i - startLine)]));

                    rootElement.AppendChild(res);
                }
            }
            c.lastLineSeen = m_LineNumber;

            xmldoc.AppendChild(rootElement);

            result["str_response_string"] = xmldoc.InnerXml;
            result["int_response_code"]   = 200;
            result["content_type"]        = "application/xml";
            result["keepalive"]           = false;
            result["reusecontext"]        = false;
            result = CheckOrigin(result);

            return(result);
        }
        public ActionResult saveSetting(SettingModel settingModel)
        {
            if (Request.Params["btnUpdate"] == null)
            {
                ModelState.Clear();
                return(View("Index", settingModel));
            }

            if (ModelState.IsValid)
            {
                // save in XML file
                bool        isNew = true;
                string      name  = "ConnectionString";
                string      path  = Server.MapPath("~/Web.Config");
                XmlDocument doc   = new XmlDocument();
                doc.Load(path);
                XmlNodeList list = doc.DocumentElement.SelectNodes(string.Format("connectionStrings/add[@name='{0}']", name));
                XmlNode     node;
                isNew = list.Count == 0;
                if (isNew)
                {
                    node = doc.CreateNode(XmlNodeType.Element, "add", null);
                    XmlAttribute attribute = doc.CreateAttribute("name");
                    attribute.Value = name;
                    node.Attributes.Append(attribute);

                    attribute       = doc.CreateAttribute("connectionString");
                    attribute.Value = "";
                    node.Attributes.Append(attribute);

                    attribute       = doc.CreateAttribute("providerName");
                    attribute.Value = "System.Data.SqlClient";
                    node.Attributes.Append(attribute);
                }
                else
                {
                    node = list[0];
                }
                string conString = node.Attributes["connectionString"].Value;
                SqlConnectionStringBuilder conStringBuilder = new SqlConnectionStringBuilder(conString);
                conStringBuilder.InitialCatalog           = settingModel.DatabaseName;
                conStringBuilder.DataSource               = settingModel.ServerName;
                conStringBuilder.IntegratedSecurity       = false;
                conStringBuilder.UserID                   = settingModel.UserName;
                conStringBuilder.Password                 = settingModel.Password;
                conStringBuilder.PersistSecurityInfo      = true;
                node.Attributes["connectionString"].Value = conStringBuilder.ConnectionString;
                if (isNew)
                {
                    doc.DocumentElement.SelectNodes("connectionStrings")[0].AppendChild(node);
                }

                using (SqlConnection connection = new SqlConnection(conStringBuilder.ConnectionString))
                {
                    try
                    {
                        connection.Open();
                        doc.Save(path);
                    }
                    catch (SqlException e)
                    {
                        ViewBag.MessageError = e.Message;
                        return(View("Index", settingModel));
                    }
                }
                //

                return(RedirectToAction("Index", "Designer"));
            }
            return(View("Index", settingModel));
        }
Example #34
0
        private void MenuItem_OpenFile_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFile = new OpenFileDialog();

            openFile.Filter = "obj, xml|*.obj;*.xml";
            if (openFile.ShowDialog() == true)
            {
                if (openFile.FileName.EndsWith(".obj"))
                {
                    try
                    {
                        m_xmlDocument = new XmlDocument();
                        m_xmlDocument.AppendChild(m_xmlDocument.CreateProcessingInstruction("xml", "version=\"1.0\"encoding =\"UTF-8\""));
                        XmlElement root = m_xmlDocument.CreateElement("root");
                        m_xmlDocument.AppendChild(root);
                        using (StreamReader sr = new StreamReader(openFile.FileName))
                        {
                            string   line;
                            string[] splitLine;
                            bool     isVertices = false;
                            bool     isNormals  = false;
                            bool     isUVs      = false;
                            bool     isParameterSpaceVertices = false;
                            bool     isLineElement            = false;
                            bool     isSmoothShading          = false;
                            bool     isMtllib = false;
                            XmlNode  xmlNode  = null;
                            while ((line = sr.ReadLine()) != null)
                            {
                                line      = line.Trim();
                                splitLine = line.Split(' ');

                                switch (splitLine[0])
                                {
                                case "v":
                                    if (!isVertices)
                                    {
                                        xmlNode = m_xmlDocument.CreateNode(XmlNodeType.Element, "Vertices", "");
                                        m_xmlDocument.DocumentElement.AppendChild(xmlNode);
                                        isVertices = true;
                                    }

                                    XmlNode vertexNode = m_xmlDocument.CreateNode(XmlNodeType.Element, "Vertex", "");
                                    xmlNode.AppendChild(vertexNode);

                                    XmlNode xVertexNode = m_xmlDocument.CreateNode(XmlNodeType.Element, "X", "");
                                    xVertexNode.InnerText = splitLine[1];
                                    vertexNode.AppendChild(xVertexNode);

                                    xVertexNode           = m_xmlDocument.CreateNode(XmlNodeType.Element, "Y", "");
                                    xVertexNode.InnerText = splitLine[2];
                                    vertexNode.AppendChild(xVertexNode);

                                    xVertexNode           = m_xmlDocument.CreateNode(XmlNodeType.Element, "Z", "");
                                    xVertexNode.InnerText = splitLine[3];
                                    vertexNode.AppendChild(xVertexNode);

                                    if (splitLine.Length > 4)
                                    {
                                        xVertexNode           = m_xmlDocument.CreateNode(XmlNodeType.Element, "W", "");
                                        xVertexNode.InnerText = splitLine[3];
                                        vertexNode.AppendChild(xVertexNode);
                                    }
                                    continue;

                                case "vn":
                                    if (!isNormals)
                                    {
                                        xmlNode = m_xmlDocument.CreateNode(XmlNodeType.Element, "Normals", "");
                                        m_xmlDocument.DocumentElement.AppendChild(xmlNode);
                                        isNormals = true;
                                    }

                                    XmlNode normalNode = m_xmlDocument.CreateNode(XmlNodeType.Element, "Normal", "");
                                    xmlNode.AppendChild(normalNode);

                                    XmlNode xNormalNode = m_xmlDocument.CreateNode(XmlNodeType.Element, "X", "");
                                    xNormalNode.InnerText = splitLine[1];
                                    normalNode.AppendChild(xNormalNode);

                                    xNormalNode           = m_xmlDocument.CreateNode(XmlNodeType.Element, "Y", "");
                                    xNormalNode.InnerText = splitLine[2];
                                    normalNode.AppendChild(xNormalNode);

                                    xNormalNode           = m_xmlDocument.CreateNode(XmlNodeType.Element, "Z", "");
                                    xNormalNode.InnerText = splitLine[3];
                                    normalNode.AppendChild(xNormalNode);
                                    continue;

                                case "vt":
                                    if (!isUVs)
                                    {
                                        xmlNode = m_xmlDocument.CreateNode(XmlNodeType.Element, "UVs", "");
                                        m_xmlDocument.DocumentElement.AppendChild(xmlNode);
                                        isUVs = true;
                                    }

                                    XmlNode uvNode = m_xmlDocument.CreateNode(XmlNodeType.Element, "UV", "");
                                    xmlNode.AppendChild(uvNode);

                                    XmlNode xUvNode = m_xmlDocument.CreateNode(XmlNodeType.Element, "U", "");
                                    xUvNode.InnerText = splitLine[1];
                                    uvNode.AppendChild(xUvNode);

                                    xUvNode           = m_xmlDocument.CreateNode(XmlNodeType.Element, "V", "");
                                    xUvNode.InnerText = splitLine[2];
                                    uvNode.AppendChild(xUvNode);

                                    if (splitLine.Length > 3)
                                    {
                                        xUvNode           = m_xmlDocument.CreateNode(XmlNodeType.Element, "W", "");
                                        xUvNode.InnerText = splitLine[3];
                                        uvNode.AppendChild(xUvNode);
                                    }
                                    continue;

                                case "vp":
                                    if (!isParameterSpaceVertices)
                                    {
                                        xmlNode = m_xmlDocument.CreateNode(XmlNodeType.Element, "VPs", "");
                                        m_xmlDocument.DocumentElement.AppendChild(xmlNode);
                                        isParameterSpaceVertices = true;
                                    }

                                    XmlNode vpNode = m_xmlDocument.CreateNode(XmlNodeType.Element, "VP", "");
                                    xmlNode.AppendChild(vpNode);

                                    XmlNode xVpNode = m_xmlDocument.CreateNode(XmlNodeType.Element, "U", "");
                                    xVpNode.InnerText = splitLine[1];
                                    vpNode.AppendChild(xVpNode);

                                    if (splitLine.Length > 2)
                                    {
                                        xVpNode           = m_xmlDocument.CreateNode(XmlNodeType.Element, "V", "");
                                        xVpNode.InnerText = splitLine[2];
                                        vpNode.AppendChild(xVpNode);
                                    }

                                    if (splitLine.Length > 3)
                                    {
                                        xVpNode           = m_xmlDocument.CreateNode(XmlNodeType.Element, "W", "");
                                        xVpNode.InnerText = splitLine[3];
                                        vpNode.AppendChild(xVpNode);
                                    }
                                    continue;

                                case "l":
                                    if (!isLineElement)
                                    {
                                        xmlNode = m_xmlDocument.CreateNode(XmlNodeType.Element, "LineElements", "");
                                        m_xmlDocument.DocumentElement.AppendChild(xmlNode);
                                        isLineElement = true;
                                    }

                                    XmlNode lineNode = m_xmlDocument.CreateNode(XmlNodeType.Element, "LineElement", "");
                                    xmlNode.AppendChild(lineNode);

                                    XmlNode xLineNode = m_xmlDocument.CreateNode(XmlNodeType.Element, "v", "");
                                    xLineNode.InnerText = splitLine[1];
                                    lineNode.AppendChild(xLineNode);

                                    // TODO!
                                    continue;

                                case "s":
                                    if (!isSmoothShading)
                                    {
                                        xmlNode = m_xmlDocument.CreateNode(XmlNodeType.Element, "SmoothShadings", "");
                                        m_xmlDocument.DocumentElement.AppendChild(xmlNode);
                                        isSmoothShading = true;
                                    }

                                    XmlNode smoothingNode = m_xmlDocument.CreateNode(XmlNodeType.Element, "SmoothShading", "");
                                    xmlNode.AppendChild(smoothingNode);

                                    XmlNode xSmoothingNode = m_xmlDocument.CreateNode(XmlNodeType.Element, "s", "");
                                    xSmoothingNode.InnerText = splitLine[1];
                                    smoothingNode.AppendChild(xSmoothingNode);

                                    // TODO?
                                    continue;

                                case "mtllib":
                                    if (!isMtllib)
                                    {
                                        xmlNode = m_xmlDocument.CreateNode(XmlNodeType.Element, "mtllibs", "");
                                        m_xmlDocument.DocumentElement.AppendChild(xmlNode);
                                        isMtllib = true;
                                    }

                                    XmlNode mtllibNode = m_xmlDocument.CreateNode(XmlNodeType.Element, "mtllib", "");
                                    xmlNode.AppendChild(mtllibNode);

                                    XmlNode xMtllibNode = m_xmlDocument.CreateNode(XmlNodeType.Element, "path", "");
                                    xMtllibNode.InnerText = splitLine[1];
                                    mtllibNode.AppendChild(xMtllibNode);

                                    // TODO?
                                    continue;

                                case "usemtl":

                                    continue;

                                default:
                                    break;
                                }
                            }
                        }
                    }
                    catch (IndexOutOfRangeException _ex)
                    {
                        MessageBox.Show("Invalid file format", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    //    catch (Exception)
                    //  {

                    //    throw;
                    //}
                }
                else if (openFile.FileName.EndsWith(".xml"))
                {
                }
            }
        }
Example #35
0
        private Hashtable HandleHttpStartSession(Hashtable request)
        {
            DoExpire();

            Hashtable post  = DecodePostString(request["body"].ToString());
            Hashtable reply = new Hashtable();

            reply["str_response_string"] = "";
            reply["int_response_code"]   = 401;
            reply["content_type"]        = "text/plain";

            if (m_UserName == String.Empty)
            {
                return(reply);
            }

            if (post["USER"] == null || post["PASS"] == null)
            {
                return(reply);
            }

            if (m_UserName != post["USER"].ToString() ||
                m_Password != post["PASS"].ToString())
            {
                return(reply);
            }

            ConsoleConnection c = new ConsoleConnection();

            c.last         = System.Environment.TickCount;
            c.lastLineSeen = 0;

            UUID sessionID = UUID.Random();

            lock (m_Connections)
            {
                m_Connections[sessionID] = c;
            }

            string uri = "/ReadResponses/" + sessionID.ToString() + "/";

            m_Server.AddPollServiceHTTPHandler(uri, HandleHttpPoll,
                                               new PollServiceEventArgs(null, HasEvents, GetEvents, NoEvents,
                                                                        sessionID));

            XmlDocument xmldoc  = new XmlDocument();
            XmlNode     xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
                                                    "", "");

            xmldoc.AppendChild(xmlnode);
            XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
                                                          "");

            xmldoc.AppendChild(rootElement);

            XmlElement id = xmldoc.CreateElement("", "SessionID", "");

            id.AppendChild(xmldoc.CreateTextNode(sessionID.ToString()));

            rootElement.AppendChild(id);

            XmlElement prompt = xmldoc.CreateElement("", "Prompt", "");

            prompt.AppendChild(xmldoc.CreateTextNode(DefaultPrompt));

            rootElement.AppendChild(prompt);

            rootElement.AppendChild(MainConsole.Instance.Commands.GetXml(xmldoc));

            reply["str_response_string"] = xmldoc.InnerXml;
            reply["int_response_code"]   = 200;
            reply["content_type"]        = "text/xml";
            reply = CheckOrigin(reply);

            return(reply);
        }
Example #36
0
        /// <summary>
        /// 发送改判信息给NC
        /// </summary>
        /// <param name="xmlFileName">xml完整路径</param>
        /// <returns></returns>
        public bool SendXml_GP(string xmlFileName)
        {
            try
            {
                //Mod_TMO_CON modCon = tmo_con.GetModel(billId);
                XmlDocument xmlDoc = new XmlDocument();
                //创建类型声明节点
                XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", "no");
                xmlDoc.AppendChild(node);

                //创建根节点
                XmlElement root = xmlDoc.CreateElement("ufinterface");
                #region//给节点属性赋值
                root.SetAttribute("billtype", "4K");
                root.SetAttribute("filename", "ZK1809130045.xml");
                root.SetAttribute("isexchange", "Y");
                root.SetAttribute("operation", "req");
                root.SetAttribute("proc", "update");
                root.SetAttribute("receiver", "101");
                root.SetAttribute("replace", "y");
                root.SetAttribute("roottag", "bill");
                root.SetAttribute("sender", "1107");
                #endregion
                xmlDoc.AppendChild(root);

                //创建子根节点
                XmlElement bill = xmlDoc.CreateElement("bill");
                #region//节点属性
                bill.SetAttribute("id", "P1CI1001NC10000000ARTIFJ");
                #endregion
                root.AppendChild(bill);

                XmlNode head = xmlDoc.CreateNode(XmlNodeType.Element, "bill_head", null);

                #region                                                              //表头_order_head
                CreateNode(xmlDoc, head, "ctjname", "");                             //?
                CreateNode(xmlDoc, head, "bz", "");                                  //?
                CreateNode(xmlDoc, head, "cbilltypecode", "4K");                     //库存单据类型编码
                CreateNode(xmlDoc, head, "cinbsrid", "");                            //入库业务员
                CreateNode(xmlDoc, head, "cinbsrname", "");                          //?
                CreateNode(xmlDoc, head, "cindeptid", "1001NC1000000000036A");       //入库部门ID
                CreateNode(xmlDoc, head, "cindeptname", "储运中心");                     //?
                CreateNode(xmlDoc, head, "cinwarehouseid", "CKDA0000000000000037");  //入库仓库ID
                CreateNode(xmlDoc, head, "cinwarehousename", "线材四车间内货场");            //?
                CreateNode(xmlDoc, head, "isLocatorMgtIn", "0");                     //?
                CreateNode(xmlDoc, head, "isWasteWhIn", "0");                        //?
                CreateNode(xmlDoc, head, "whreservedptyin", "");                     //?
                CreateNode(xmlDoc, head, "islocatormgtin", "0");                     //?
                CreateNode(xmlDoc, head, "iswastewhin", "0");                        //?
                CreateNode(xmlDoc, head, "whreservedptyin", "");                     //?
                CreateNode(xmlDoc, head, "coutbsor", "");                            //出库业务员
                CreateNode(xmlDoc, head, "coutbsorname", "");                        //?
                CreateNode(xmlDoc, head, "coutdeptid", "1001NC1000000000036A");      //出库仓库ID
                CreateNode(xmlDoc, head, "coutdeptname", "储运中心");                    //?
                CreateNode(xmlDoc, head, "coutwarehouseid", "CKDA0000000000000039"); //出库仓库ID
                CreateNode(xmlDoc, head, "coutwarehousename", "钢材市场线材仓库611");        //?
                CreateNode(xmlDoc, head, "isLocatorMgtOut", "0");                    //?
                CreateNode(xmlDoc, head, "isWasteWhOut", "0");                       //?
                CreateNode(xmlDoc, head, "whReservedPtyOut", "");                    //?
                CreateNode(xmlDoc, head, "islocatormgtout", "0");                    //?
                CreateNode(xmlDoc, head, "iswastewhout", "0");                       //?
                CreateNode(xmlDoc, head, "whreservedptyout", "");                    //?
                CreateNode(xmlDoc, head, "cshlddiliverdate", "2018 - 09 - 13");      //单据日期
                CreateNode(xmlDoc, head, "ctj", "");                                 //?
                CreateNode(xmlDoc, head, "dbilldate", "2018 - 09 - 13");             //单据日期
                CreateNode(xmlDoc, head, "nfixdisassemblymny", "");                  //组装拆卸费用
                CreateNode(xmlDoc, head, "pdfs", "");                                //?
                CreateNode(xmlDoc, head, "pk_corp", "1001");                         //公司ID
                CreateNode(xmlDoc, head, "vbillcode", "ZK1809130045");               //单据号
                CreateNode(xmlDoc, head, "vnote", "");                               //备注
                CreateNode(xmlDoc, head, "vshldarrivedate", "2018 - 09 - 13");       //应到货日期
                CreateNode(xmlDoc, head, "vuserdef1", "");                           //自定义项
                CreateNode(xmlDoc, head, "vuserdef2", "");                           //自定义项
                CreateNode(xmlDoc, head, "vuserdef3", "");                           //自定义项
                CreateNode(xmlDoc, head, "vuserdef4", "");                           //自定义项
                CreateNode(xmlDoc, head, "vuserdef5", "");                           //自定义项
                CreateNode(xmlDoc, head, "vuserdef6", "");                           //自定义项
                CreateNode(xmlDoc, head, "vuserdef7", "");                           //自定义项
                CreateNode(xmlDoc, head, "vuserdef8", "");                           //自定义项
                CreateNode(xmlDoc, head, "vuserdef9", "");                           //自定义项
                CreateNode(xmlDoc, head, "vuserdef10", "");                          //自定义项
                CreateNode(xmlDoc, head, "vuserdef11", "");                          //自定义项
                CreateNode(xmlDoc, head, "vuserdef12", "");                          //自定义项
                CreateNode(xmlDoc, head, "vuserdef13", "");                          //自定义项
                CreateNode(xmlDoc, head, "vuserdef14", "");                          //自定义项
                CreateNode(xmlDoc, head, "vuserdef15", "");                          //自定义项
                CreateNode(xmlDoc, head, "vuserdef16", "");                          //自定义项
                CreateNode(xmlDoc, head, "vuserdef17", "");                          //自定义项
                CreateNode(xmlDoc, head, "vuserdef18", "");                          //自定义项
                CreateNode(xmlDoc, head, "vuserdef19", "");                          //自定义项
                CreateNode(xmlDoc, head, "vuserdef20", "");                          //自定义项
                CreateNode(xmlDoc, head, "vuserdef11h", "");                         //?
                CreateNode(xmlDoc, head, "vuserdef12h", "");                         //?
                CreateNode(xmlDoc, head, "vuserdef13h", "");                         //?
                CreateNode(xmlDoc, head, "vuserdef14h", "");                         //?
                CreateNode(xmlDoc, head, "vuserdef15h", "");                         //?
                CreateNode(xmlDoc, head, "vuserdef16h", "");                         //?
                CreateNode(xmlDoc, head, "vuserdef17h", "");                         //?
                CreateNode(xmlDoc, head, "vuserdef18h", "");                         //?
                CreateNode(xmlDoc, head, "vuserdef19h", "");                         //?
                CreateNode(xmlDoc, head, "vuserdef20h", "");                         //?
                CreateNode(xmlDoc, head, "pk_defdoc1", "");                          //自定义项主键
                CreateNode(xmlDoc, head, "pk_defdoc2", "");                          //自定义项主键
                CreateNode(xmlDoc, head, "pk_defdoc3", "");                          //自定义项主键
                CreateNode(xmlDoc, head, "pk_defdoc4", "");                          //自定义项主键
                CreateNode(xmlDoc, head, "pk_defdoc5", "");                          //自定义项主键
                CreateNode(xmlDoc, head, "pk_defdoc6", "");                          //自定义项主键
                CreateNode(xmlDoc, head, "pk_defdoc7", "");                          //自定义项主键
                CreateNode(xmlDoc, head, "pk_defdoc8", "");                          //自定义项主键
                CreateNode(xmlDoc, head, "pk_defdoc9", "");                          //自定义项主键
                CreateNode(xmlDoc, head, "pk_defdoc10", "");                         //自定义项主键
                CreateNode(xmlDoc, head, "pk_defdoc1h", "");                         //?
                CreateNode(xmlDoc, head, "pk_defdoc2h", "");                         //?
                CreateNode(xmlDoc, head, "pk_defdoc3h", "");                         //?
                CreateNode(xmlDoc, head, "pk_defdoc4h", "");                         //?
                CreateNode(xmlDoc, head, "pk_defdoc5h", "");                         //?
                CreateNode(xmlDoc, head, "pk_defdoc6h", "");                         //?
                CreateNode(xmlDoc, head, "pk_defdoc7h", "");                         //?
                CreateNode(xmlDoc, head, "pk_defdoc8h", "");                         //?
                CreateNode(xmlDoc, head, "pk_defdoc9h", "");                         //?
                CreateNode(xmlDoc, head, "pk_defdoc10h", "");                        //?
                CreateNode(xmlDoc, head, "pk_defdoc11", "");                         //自定义项主键
                CreateNode(xmlDoc, head, "pk_defdoc12", "");                         //自定义项主键
                CreateNode(xmlDoc, head, "pk_defdoc13", "");                         //自定义项主键
                CreateNode(xmlDoc, head, "pk_defdoc14", "");                         //自定义项主键
                CreateNode(xmlDoc, head, "pk_defdoc15", "");                         //自定义项主键
                CreateNode(xmlDoc, head, "pk_defdoc16", "");                         //自定义项主键
                CreateNode(xmlDoc, head, "pk_defdoc17", "");                         //自定义项主键
                CreateNode(xmlDoc, head, "pk_defdoc18", "");                         //自定义项主键
                CreateNode(xmlDoc, head, "pk_defdoc19", "");                         //自定义项主键
                CreateNode(xmlDoc, head, "pk_defdoc20", "");                         //自定义项主键
                CreateNode(xmlDoc, head, "pk_defdoc11h", "");                        //?
                CreateNode(xmlDoc, head, "pk_defdoc12h", "");                        //?
                CreateNode(xmlDoc, head, "pk_defdoc13h", "");                        //?
                CreateNode(xmlDoc, head, "pk_defdoc14h", "");                        //?
                CreateNode(xmlDoc, head, "pk_defdoc15h", "");                        //?
                CreateNode(xmlDoc, head, "pk_defdoc16h", "");                        //?
                CreateNode(xmlDoc, head, "pk_defdoc17h", "");                        //?
                CreateNode(xmlDoc, head, "pk_defdoc18h", "");                        //?
                CreateNode(xmlDoc, head, "pk_defdoc19h", "");                        //?
                CreateNode(xmlDoc, head, "pk_defdoc20h", "");                        //?
                CreateNode(xmlDoc, head, "vuserdef1h", "");                          //?
                CreateNode(xmlDoc, head, "vuserdef2h", "");                          //?
                CreateNode(xmlDoc, head, "vuserdef3h", "");                          //?
                CreateNode(xmlDoc, head, "vuserdef4h", "");                          //?
                CreateNode(xmlDoc, head, "vuserdef5h", "");                          //?
                CreateNode(xmlDoc, head, "vuserdef6h", "");                          //?
                CreateNode(xmlDoc, head, "vuserdef7h", "");                          //?
                CreateNode(xmlDoc, head, "vuserdef8h", "");                          //?
                CreateNode(xmlDoc, head, "vuserdef9h", "");                          //?
                CreateNode(xmlDoc, head, "vuserdef10h", "");                         //?
                CreateNode(xmlDoc, head, "cauditorid", "");                          //审核人
                CreateNode(xmlDoc, head, "cauditorname", "");                        //?
                CreateNode(xmlDoc, head, "coperatorid", "1006AA100000000002JD");     //制单人
                CreateNode(xmlDoc, head, "coperatorname", "何兴敏");                    //?
                CreateNode(xmlDoc, head, "vadjuster", "");                           //盘点方式
                CreateNode(xmlDoc, head, "vadjustername", "");                       //?
                CreateNode(xmlDoc, head, "coperatoridnow", "");                      //?
                CreateNode(xmlDoc, head, "ctjname", "");                             //?
                CreateNode(xmlDoc, head, "pk_calbody_in", "1001NC10000000000669");   //?
                CreateNode(xmlDoc, head, "pk_calbody_out", "1001NC10000000000669");  //?
                CreateNode(xmlDoc, head, "vcalbody_inname", "邢钢库存组织");               //?
                CreateNode(xmlDoc, head, "vcalbody_outname", "邢钢库存组织");              //?
                CreateNode(xmlDoc, head, "ts", "2018 - 09 - 13 21:31:03");           //?
                CreateNode(xmlDoc, head, "timestamp", "");                           //?
                CreateNode(xmlDoc, head, "headts", "2018 - 09 - 13 21:31:03");       //?
                CreateNode(xmlDoc, head, "isforeignstor_in", "N");                   //?
                CreateNode(xmlDoc, head, "isgathersettle_in", "N");                  //?
                CreateNode(xmlDoc, head, "isforeignstor_out", "N");                  //?
                CreateNode(xmlDoc, head, "isgathersettle_out", "N");                 //?
                CreateNode(xmlDoc, head, "icheckmode", "");                          //盘点方式
                CreateNode(xmlDoc, head, "fassistantflag", "N");                     //是否计算期间业务量
                CreateNode(xmlDoc, head, "fbillflag", "");                           //单据状态
                CreateNode(xmlDoc, head, "vostatus", "");                            //?
                CreateNode(xmlDoc, head, "iprintcount", "");                         //打印次数
                CreateNode(xmlDoc, head, "clastmodiid", "1006AA100000000002JD");     //最后修改人
                CreateNode(xmlDoc, head, "clastmodiname", "");                       //?
                CreateNode(xmlDoc, head, "tlastmoditime", "2018-09-13 21:31:03");    //最后修改时间
                CreateNode(xmlDoc, head, "cnxtbilltypecode", "4A");                  //?
                CreateNode(xmlDoc, head, "cspecialhid", "1001NC10000000ARTIFJ");     //特殊业务单据ID

                #endregion


                bill.AppendChild(head);
                XmlElement body = xmlDoc.CreateElement("bill_body");
                bill.AppendChild(body);

                XmlNode item = xmlDoc.CreateNode(XmlNodeType.Element, "item", null);
                #region                                                                                                            //表体_item
                CreateNode(xmlDoc, item, "csourcetypename", "");                                                                   //?
                CreateNode(xmlDoc, item, "cinvbasid", "0001NC100000000TC2SX");                                                     //来源单据号
                CreateNode(xmlDoc, item, "pk_invbasdoc", "0001NC100000000TC2SX");                                                  //?
                CreateNode(xmlDoc, item, "fixedflag", "N");                                                                        //?
                CreateNode(xmlDoc, item, "bgssl", "");                                                                             //?
                CreateNode(xmlDoc, item, "castunitid", "jlda0000000000000041");                                                    //辅计量单位ID
                CreateNode(xmlDoc, item, "castunitname", "件【线材】");                                                                 //?
                CreateNode(xmlDoc, item, "cinventorycode", "8021084130");                                                          //?
                CreateNode(xmlDoc, item, "cinventoryid", "1001NC100000005I7S3D");                                                  //存货ID
                CreateNode(xmlDoc, item, "cinvmanid", "0001NC100000000TC2SX");                                                     //?
                CreateNode(xmlDoc, item, "isLotMgt", "1");                                                                         //?
                CreateNode(xmlDoc, item, "isSerialMgt", "0");                                                                      //?
                CreateNode(xmlDoc, item, "isValidateMgt", "0");                                                                    //?
                CreateNode(xmlDoc, item, "isAstUOMmgt", "1");                                                                      //?
                CreateNode(xmlDoc, item, "isFreeItemMgt", "1");                                                                    //?
                CreateNode(xmlDoc, item, "isSet", "0");                                                                            //?
                CreateNode(xmlDoc, item, "standStoreUOM", "");                                                                     //?
                CreateNode(xmlDoc, item, "defaultAstUOM", "jlda0000000000000041");                                                 //?
                CreateNode(xmlDoc, item, "isSellProxy", "0");                                                                      //?
                CreateNode(xmlDoc, item, "qualityDay", "");                                                                        //?
                CreateNode(xmlDoc, item, "invReservedPty", "");                                                                    //?
                CreateNode(xmlDoc, item, "isSolidConvRate", "0");                                                                  //?
                CreateNode(xmlDoc, item, "islotmgt", "1");                                                                         //?
                CreateNode(xmlDoc, item, "isserialmgt", "0");                                                                      //?
                CreateNode(xmlDoc, item, "isvalidatemgt", "0");                                                                    //?
                CreateNode(xmlDoc, item, "isastuommgt", "1");                                                                      //?
                CreateNode(xmlDoc, item, "isfreeitemmgt", "1");                                                                    //?
                CreateNode(xmlDoc, item, "isset", "0");                                                                            //?
                CreateNode(xmlDoc, item, "standstoreuom", "");                                                                     //?
                CreateNode(xmlDoc, item, "defaultastuom", "jlda0000000000000041");                                                 //?
                CreateNode(xmlDoc, item, "issellproxy", "0");                                                                      //?
                CreateNode(xmlDoc, item, "qualityday", "");                                                                        //?
                CreateNode(xmlDoc, item, "invreservedpty", "");                                                                    //?
                CreateNode(xmlDoc, item, "issolidconvrate", "0");                                                                  //?
                CreateNode(xmlDoc, item, "csourcebillbid", "");                                                                    //来源单据表体序列号
                CreateNode(xmlDoc, item, "csourcebillhid", "");                                                                    //来源单据表体序列号
                CreateNode(xmlDoc, item, "csourcetype", "");                                                                       //来源单据类型
                CreateNode(xmlDoc, item, "cspaceid", "");                                                                          //货位ID
                CreateNode(xmlDoc, item, "cspacecode", "");                                                                        //?
                CreateNode(xmlDoc, item, "cspacename", "");                                                                        //?
                CreateNode(xmlDoc, item, "cspecialhid", "1001NC10000000ARTIFJ");                                                   //特殊业务单据ID
                CreateNode(xmlDoc, item, "cwarehouseid", "");                                                                      //仓库ID
                CreateNode(xmlDoc, item, "cwarehousename", "");                                                                    //?
                CreateNode(xmlDoc, item, "isLocatorMgt", "");                                                                      //?
                CreateNode(xmlDoc, item, "isWasteWh", "");                                                                         //?
                CreateNode(xmlDoc, item, "whreservedpty", "");                                                                     //?
                CreateNode(xmlDoc, item, "islocatormgt", "");                                                                      //?
                CreateNode(xmlDoc, item, "iswastewh", "");                                                                         //?
                CreateNode(xmlDoc, item, "whreservedpty", "");                                                                     //?
                CreateNode(xmlDoc, item, "cyfsl", "");                                                                             //?
                CreateNode(xmlDoc, item, "cysl", "");                                                                              //?
                CreateNode(xmlDoc, item, "desl", "");                                                                              //?
                CreateNode(xmlDoc, item, "dshldtransnum", "21.753000");                                                            //应转数量
                CreateNode(xmlDoc, item, "dvalidate", "");                                                                         //失效日期
                CreateNode(xmlDoc, item, "fbillrowflag", "");                                                                      //单据行标志
                CreateNode(xmlDoc, item, "hlzl", "");                                                                              //?
                CreateNode(xmlDoc, item, "hsl", "1.977545");                                                                       //换算率
                CreateNode(xmlDoc, item, "invname", "精品线材");                                                                       //?
                CreateNode(xmlDoc, item, "invspec", "φ13mm");                                                                      //?
                CreateNode(xmlDoc, item, "invtype", "GSCM435-C");                                                                  //?
                CreateNode(xmlDoc, item, "je", "");                                                                                //?
                CreateNode(xmlDoc, item, "jhdj", "3500.000000");                                                                   //?
                CreateNode(xmlDoc, item, "jhje", "76135.50");                                                                      //?
                CreateNode(xmlDoc, item, "jhpdzq", "");                                                                            //?
                CreateNode(xmlDoc, item, "measdocname", "吨");                                                                      //?
                CreateNode(xmlDoc, item, "naccountastnum", "");                                                                    //帐面辅数量
                CreateNode(xmlDoc, item, "naccountnum", "");                                                                       //帐面数量
                CreateNode(xmlDoc, item, "nadjustastnum", "");                                                                     //盘点辅数量
                CreateNode(xmlDoc, item, "nadjustnum", "");                                                                        //盘点辅数量
                CreateNode(xmlDoc, item, "ncheckastnum", "");                                                                      //盘点辅数量
                CreateNode(xmlDoc, item, "nchecknum", "");                                                                         //盘点数量
                CreateNode(xmlDoc, item, "nprice", "");                                                                            //单价
                CreateNode(xmlDoc, item, "nmny", "");                                                                              //金额
                CreateNode(xmlDoc, item, "nplannedmny", "76135.50");                                                               //计划金额
                CreateNode(xmlDoc, item, "nplannedprice", "3500.000000");                                                          //计划单价
                CreateNode(xmlDoc, item, "nshldtransastnum", "11.00");                                                             //应转辅数量
                CreateNode(xmlDoc, item, "pk_measdoc", "jlda0000000000000012");                                                    //?
                CreateNode(xmlDoc, item, "scrq", "2018-09-13");                                                                    //?
                CreateNode(xmlDoc, item, "sjpdzq", "");                                                                            //?
                CreateNode(xmlDoc, item, "vbatchcode", "351808217");                                                               //?
                CreateNode(xmlDoc, item, "vfree0", "[GSCM435-C产品标准:GSCM435-C~协议][GSCM435-C技术要求:GSCM435-C~JSKZ-163-205][包装要求:D5]"); //?
                CreateNode(xmlDoc, item, "vfree1", "GSCM435-C~协议");                                                                //?
                CreateNode(xmlDoc, item, "vfree2", "GSCM435-C~JSKZ-163-205");                                                      //?
                CreateNode(xmlDoc, item, "vfree3", "D5");                                                                          //?
                CreateNode(xmlDoc, item, "vfree4", "");                                                                            //?
                CreateNode(xmlDoc, item, "vfree5", "");                                                                            //?
                CreateNode(xmlDoc, item, "vfree6", "");                                                                            //?
                CreateNode(xmlDoc, item, "vfree7", "");                                                                            //?
                CreateNode(xmlDoc, item, "vfree8", "");                                                                            //?
                CreateNode(xmlDoc, item, "vfree9", "");                                                                            //?
                CreateNode(xmlDoc, item, "vfree10", "");                                                                           //?
                CreateNode(xmlDoc, item, "vfreename1", "GSCM435-C产品标准");                                                           //?
                CreateNode(xmlDoc, item, "vfreename2", "GSCM435-C技术要求");                                                           //?
                CreateNode(xmlDoc, item, "vfreename3", "包装要求");                                                                    //?
                CreateNode(xmlDoc, item, "vfreename4", "");                                                                        //?
                CreateNode(xmlDoc, item, "vfreename5", "");                                                                        //?
                CreateNode(xmlDoc, item, "vfreename6", "");                                                                        //?
                CreateNode(xmlDoc, item, "vfreename7", "");                                                                        //?
                CreateNode(xmlDoc, item, "vfreename8", "");                                                                        //?
                CreateNode(xmlDoc, item, "vfreename9", "");                                                                        //?
                CreateNode(xmlDoc, item, "vfreename10", "");                                                                       //?
                CreateNode(xmlDoc, item, "vsourcebillcode", "");                                                                   //来源单据号
                CreateNode(xmlDoc, item, "vuserdef1", "");                                                                         //自定义项
                CreateNode(xmlDoc, item, "vuserdef2", "");                                                                         //自定义项
                CreateNode(xmlDoc, item, "vuserdef3", "");                                                                         //自定义项
                CreateNode(xmlDoc, item, "vuserdef4", "");                                                                         //自定义项
                CreateNode(xmlDoc, item, "vuserdef5", "");                                                                         //自定义项
                CreateNode(xmlDoc, item, "vuserdef6", "");                                                                         //自定义项
                CreateNode(xmlDoc, item, "vuserdef7", "");                                                                         //自定义项
                CreateNode(xmlDoc, item, "vuserdef8", "");                                                                         //自定义项
                CreateNode(xmlDoc, item, "vuserdef9", "");                                                                         //自定义项
                CreateNode(xmlDoc, item, "vuserdef10", "PCIbody1001NC10000000ARTIFJ");                                             //自定义项
                CreateNode(xmlDoc, item, "vuserdef11", "");                                                                        //自定义项
                CreateNode(xmlDoc, item, "vuserdef12", "");                                                                        //自定义项
                CreateNode(xmlDoc, item, "vuserdef13", "");                                                                        //自定义项
                CreateNode(xmlDoc, item, "vuserdef14", "");                                                                        //自定义项
                CreateNode(xmlDoc, item, "vuserdef15", "");                                                                        //自定义项
                CreateNode(xmlDoc, item, "vuserdef16", "");                                                                        //自定义项
                CreateNode(xmlDoc, item, "vuserdef17", "");                                                                        //自定义项
                CreateNode(xmlDoc, item, "vuserdef18", "");                                                                        //自定义项
                CreateNode(xmlDoc, item, "vuserdef19", "");                                                                        //自定义项
                CreateNode(xmlDoc, item, "vuserdef20", "");                                                                        //自定义项
                CreateNode(xmlDoc, item, "pk_defdoc1", "");                                                                        //自定义项主键
                CreateNode(xmlDoc, item, "pk_defdoc2", "");                                                                        //自定义项主键
                CreateNode(xmlDoc, item, "pk_defdoc3", "");                                                                        //自定义项主键
                CreateNode(xmlDoc, item, "pk_defdoc4", "");                                                                        //自定义项主键
                CreateNode(xmlDoc, item, "pk_defdoc5", "");                                                                        //自定义项主键
                CreateNode(xmlDoc, item, "pk_defdoc6", "");                                                                        //自定义项主键
                CreateNode(xmlDoc, item, "pk_defdoc7", "");                                                                        //自定义项主键
                CreateNode(xmlDoc, item, "pk_defdoc8", "");                                                                        //自定义项主键
                CreateNode(xmlDoc, item, "pk_defdoc9", "");                                                                        //自定义项主键
                CreateNode(xmlDoc, item, "pk_defdoc10", "");                                                                       //自定义项主键
                CreateNode(xmlDoc, item, "pk_defdoc11", "");                                                                       //自定义项主键
                CreateNode(xmlDoc, item, "pk_defdoc12", "");                                                                       //自定义项主键
                CreateNode(xmlDoc, item, "pk_defdoc13", "");                                                                       //自定义项主键
                CreateNode(xmlDoc, item, "pk_defdoc14", "");                                                                       //自定义项主键
                CreateNode(xmlDoc, item, "pk_defdoc15", "");                                                                       //自定义项主键
                CreateNode(xmlDoc, item, "pk_defdoc16", "");                                                                       //自定义项主键
                CreateNode(xmlDoc, item, "pk_defdoc17", "");                                                                       //自定义项主键
                CreateNode(xmlDoc, item, "pk_defdoc18", "");                                                                       //自定义项主键
                CreateNode(xmlDoc, item, "pk_defdoc19", "");                                                                       //自定义项主键
                CreateNode(xmlDoc, item, "pk_defdoc20", "");                                                                       //自定义项主键
                CreateNode(xmlDoc, item, "yy", "");                                                                                //?
                CreateNode(xmlDoc, item, "ztsl", "");                                                                              //?
                CreateNode(xmlDoc, item, "bkxcl", "");                                                                             //?
                CreateNode(xmlDoc, item, "chzl", "");                                                                              //?
                CreateNode(xmlDoc, item, "neconomicnum", "");                                                                      //?
                CreateNode(xmlDoc, item, "nmaxstocknum", "");                                                                      //?
                CreateNode(xmlDoc, item, "nminstocknum", "11");                                                                    //?
                CreateNode(xmlDoc, item, "norderpointnum", "21.753000");                                                           //?
                CreateNode(xmlDoc, item, "xczl", "");                                                                              //?
                CreateNode(xmlDoc, item, "nsafestocknum", "");                                                                     //?
                CreateNode(xmlDoc, item, "fbillflag", "");                                                                         //单据状态
                CreateNode(xmlDoc, item, "vfreeid1", "0001NC100000000Q2VJX");                                                      //?
                CreateNode(xmlDoc, item, "vfreeid2", "0001NC100000000Q2VJZ");                                                      //?
                CreateNode(xmlDoc, item, "vfreeid3", "0001NC10000000001Y8M");                                                      //?
                CreateNode(xmlDoc, item, "vfreeid4", "");                                                                          //?
                CreateNode(xmlDoc, item, "vfreeid5", "");                                                                          //?
                CreateNode(xmlDoc, item, "vfreeid6", "");                                                                          //?
                CreateNode(xmlDoc, item, "vfreeid7", "");                                                                          //?
                CreateNode(xmlDoc, item, "vfreeid8", "");                                                                          //?
                CreateNode(xmlDoc, item, "vfreeid9", "");                                                                          //?
                CreateNode(xmlDoc, item, "vfreeid10", "");                                                                         //?
                CreateNode(xmlDoc, item, "discountflag", "N");                                                                     //?
                CreateNode(xmlDoc, item, "laborflag", "N");                                                                        //?
                CreateNode(xmlDoc, item, "childsnum", "");                                                                         //?
                CreateNode(xmlDoc, item, "invsetparttype", "");                                                                    //?
                CreateNode(xmlDoc, item, "partpercent", "");                                                                       //?
                CreateNode(xmlDoc, item, "vnote", "");                                                                             //备注
                CreateNode(xmlDoc, item, "vbodynote", "");                                                                         //表体备注2
                CreateNode(xmlDoc, item, "ccorrespondtypename", "");                                                               //?
                CreateNode(xmlDoc, item, "cfirstbillbid", "");                                                                     //源头单据表体ID
                CreateNode(xmlDoc, item, "cfirstbillhid", "");                                                                     //源头单据表头ID
                CreateNode(xmlDoc, item, "cfirsttypename", "");                                                                    //?
                CreateNode(xmlDoc, item, "cfirsttype", "");                                                                        //源头单据类型
                CreateNode(xmlDoc, item, "csourcetypename", "");                                                                   //?
                CreateNode(xmlDoc, item, "pk_calbody", "");                                                                        //库存组织PK
                CreateNode(xmlDoc, item, "vcalbodyname", "");                                                                      //?
                CreateNode(xmlDoc, item, "ts", "2018-09-13 21:31:03");                                                             //?
                CreateNode(xmlDoc, item, "timestamp", "");                                                                         //?
                CreateNode(xmlDoc, item, "bodyts", "2018-09-13 21:31:03");                                                         //?
                CreateNode(xmlDoc, item, "crowno", "10");                                                                          //行号
                CreateNode(xmlDoc, item, "nperiodastnum", "");                                                                     //期间业务辅数量
                CreateNode(xmlDoc, item, "nperiodnum", "");                                                                        //期间业务数量
                CreateNode(xmlDoc, item, "isforeignstor", "N");                                                                    //?
                CreateNode(xmlDoc, item, "isgathersettle", "N");                                                                   //?
                CreateNode(xmlDoc, item, "csortrowno", "");                                                                        //?
                CreateNode(xmlDoc, item, "cvendorid", "");                                                                         //供应商
                CreateNode(xmlDoc, item, "cvendorname", "");                                                                       //?
                CreateNode(xmlDoc, item, "pk_cubasdoc", "");                                                                       //客户基本档案ID
                CreateNode(xmlDoc, item, "pk_corp", "1001");                                                                       //公司ID
                CreateNode(xmlDoc, item, "tbatchtime", "2018-09-13 14:39:15");                                                     //?
                CreateNode(xmlDoc, item, "dproducedate", "");                                                                      //?
                CreateNode(xmlDoc, item, "dvalidate", "");                                                                         //失效日期
                CreateNode(xmlDoc, item, "vvendbatchcode", "");                                                                    //?
                CreateNode(xmlDoc, item, "qualitymanflag", "");                                                                    //?
                CreateNode(xmlDoc, item, "qualitydaynum", "");                                                                     //?
                CreateNode(xmlDoc, item, "cqualitylevelid", "1001NC100000000052ZK");                                               //?
                CreateNode(xmlDoc, item, "vnote", "");                                                                             //备注
                CreateNode(xmlDoc, item, "tchecktime", "2018-09-13 14:39:18");                                                     //?
                CreateNode(xmlDoc, item, "vdef1", "");                                                                             //?
                CreateNode(xmlDoc, item, "vdef2", "");                                                                             //?
                CreateNode(xmlDoc, item, "vdef3", "");                                                                             //?
                CreateNode(xmlDoc, item, "vdef4", "");                                                                             //?
                CreateNode(xmlDoc, item, "vdef5", "");                                                                             //?
                CreateNode(xmlDoc, item, "vdef6", "");                                                                             //?
                CreateNode(xmlDoc, item, "vdef7", "");                                                                             //?
                CreateNode(xmlDoc, item, "vdef8", "");                                                                             //?
                CreateNode(xmlDoc, item, "vdef9", "");                                                                             //?
                CreateNode(xmlDoc, item, "vdef10", "");                                                                            //?
                CreateNode(xmlDoc, item, "vdef11", "");                                                                            //?
                CreateNode(xmlDoc, item, "vdef12", "");                                                                            //?
                CreateNode(xmlDoc, item, "vdef13", "");                                                                            //?
                CreateNode(xmlDoc, item, "vdef14", "");                                                                            //?
                CreateNode(xmlDoc, item, "vdef15", "");                                                                            //?
                CreateNode(xmlDoc, item, "vdef16", "");                                                                            //?
                CreateNode(xmlDoc, item, "vdef17", "");                                                                            //?
                CreateNode(xmlDoc, item, "vdef18", "");                                                                            //?
                CreateNode(xmlDoc, item, "vdef19", "");                                                                            //?
                CreateNode(xmlDoc, item, "vdef20", "");                                                                            //?
                CreateNode(xmlDoc, item, "naccountgrsnum", "");                                                                    //帐面毛重数量
                CreateNode(xmlDoc, item, "ncheckgrsnum", "");                                                                      //盘点毛重数量
                CreateNode(xmlDoc, item, "nadjustgrsnum", "");                                                                     //调整毛重数量
                CreateNode(xmlDoc, item, "nshldtransgrsnum", "");                                                                  //应转出毛重数量
                CreateNode(xmlDoc, item, "cspecialbid", "1001NC10000000ARTIFK");                                                   //?
                CreateNode(xmlDoc, item, "vbatchcode_temp", "351808217");                                                          //?
                CreateNode(xmlDoc, item, "cqualitylevelname", "DP");                                                               //?
                CreateNode(xmlDoc, item, "vdef1", "");                                                                             //?
                CreateNode(xmlDoc, item, "vdef2", "");                                                                             //?
                CreateNode(xmlDoc, item, "vdef3", "");                                                                             //?
                #endregion
                body.AppendChild(item);
                xmlDoc.Save(xmlFileName);

                //List<string> parem = dalSendNC.SendXML(xmlFileName);
                //parem.Add(dayplcode);
                //parem.Add(empID);
                //parem.Add("发运单");

                ////日志
                //AddLog(parem);

                //if (parem[2] == "成功")
                //{
                //    return true;
                //}
                //else
                //{
                //    return false;
                //}

                return(false);
            }
            catch
            {
                return(false);
            }
        }
Example #37
0
    private void PluginConfig(HttpContext context)
    {
        string str = "<![CDATA[\n" + context.Request.Form["datastr"] + "]]>\n";
        string pluginid = context.Request.Form["id"];
        string type = context.Request.Form["type"];
        string parasstr = "<![CDATA[" + context.Request.Form["paras"] + "]]>";
        string fn = context.Request.Form["fn"];
        Dukey.Model.WebConfig mysite = BLL.WebConfig.instance.GetModelByCache();//网站配置信息
        if (!File.Exists(context.Server.MapPath("~/template/" + mysite.folder + "/theme.xml")))
        {
            using (StreamWriter sw = File.CreateText(context.Server.MapPath("~/template/" + mysite.folder + "/theme.xml")))
            {
                sw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
                sw.WriteLine("<config>");
                sw.WriteLine(string.Format("<page url=\"{0}\">", fn));
                sw.WriteLine("<plugins>");
                sw.WriteLine(string.Format("<plugin id=\"{0}\" type=\"{1}\">", pluginid, type));
                sw.WriteLine(string.Format("<paras>{0}</paras>", parasstr));
                sw.WriteLine("<content>");
                sw.WriteLine(str);
                sw.WriteLine("</content>");
                sw.WriteLine("</plugin>");
                sw.WriteLine("</plugins>");
                sw.WriteLine("</page>");
                sw.WriteLine("</config>");
            }
        }
        else
        {
            string path = context.Server.MapPath("~/template/" + mysite.folder + "/theme.xml");
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(path); //加载XML文档
                XmlNode root = xmlDoc.SelectSingleNode("//config");
                if (root == null)
                {
                    root = xmlDoc.CreateNode("element", "config", "");
                    xmlDoc.AppendChild(root);
                }
                XmlNode page = xmlDoc.SelectSingleNode("//config/page[@url='" + fn + "']");
                if (page == null)
                {
                    page = xmlDoc.CreateNode("element", "page", "");
                    XmlAttribute xmlAttribute = xmlDoc.CreateAttribute("url");
                    xmlAttribute.Value = fn;
                    page.Attributes.Append(xmlAttribute);
                    root.AppendChild(page);
                }
                XmlNode plugins = xmlDoc.SelectSingleNode("//config/page[@url='" + fn + "']/plugins");
                if (plugins == null)
                {
                    plugins = xmlDoc.CreateNode("element", "plugins", "");
                    page.AppendChild(plugins);
                }
                XmlNode plugin = xmlDoc.SelectSingleNode("//config/page[@url='" + fn + "']/plugins/plugin[@id='" + pluginid + "' and @type='" + type + "']");
                if (plugin == null)
                {
                    plugin = xmlDoc.CreateNode("element", "plugin", "");
                    XmlAttribute att1 = xmlDoc.CreateAttribute("id");
                    att1.Value = pluginid;
                    XmlAttribute att2 = xmlDoc.CreateAttribute("type");
                    att2.Value = type;
                    plugin.Attributes.Append(att1);
                    plugin.Attributes.Append(att2);
                    plugins.AppendChild(plugin);
                }
                XmlNode paras = xmlDoc.SelectSingleNode("//config/page[@url='" + fn + "']/plugins/plugin[@id='" + pluginid + "' and @type='" + type + "']/paras");
                if (paras == null)
                {
                    paras = xmlDoc.CreateNode("element", "paras", "");
                    plugin.AppendChild(paras);
                }
                paras.InnerXml = parasstr;
                XmlNode content = xmlDoc.SelectSingleNode("//config/page[@url='" + fn + "']/plugins/plugin[@id='" + pluginid + "' and @type='" + type + "']/content");
                if (content == null)
                {
                    content = xmlDoc.CreateNode("element", "content", "");
                    plugin.AppendChild(content);
                }

                content.InnerXml = str;
                xmlDoc.Save(path);
                context.Response.Write("ok");
            }
            catch (Exception ex) { context.Response.Write(ex.Message); }
        }
    }
Example #38
0
        public void WriteValues(RecorderProperties rsProps)
        {
            int i = 0;

            while (File.Exists(@"C:\ProgramData\Milestone\XProtect Recording Server\RecorderConfig (" + i + ").xml"))
            {
                i++;
            }

            xDoc.Save(@"C:\ProgramData\Milestone\XProtect Recording Server\RecorderConfig (" + i + ").xml");

            // RS
            xDoc.SelectSingleNode("/recorderconfig/recorder/id").InnerText          = rsProps.id;
            xDoc.SelectSingleNode("/recorderconfig/recorder/displayname").InnerText = rsProps.displayName;
            xDoc.SelectSingleNode("/recorderconfig/webapi/port").InnerText          = rsProps.rsWebApiPort;
            xDoc.SelectSingleNode("/recorderconfig/webapi/publicUri").InnerText     = rsProps.rsWebApiAddress + ":" + rsProps.rsWebApiPort;


            xDoc.SelectSingleNode("/recorderconfig/webserver/host").InnerText = rsProps.rsWebServerAddress;
            xDoc.SelectSingleNode("/recorderconfig/webserver/port").InnerText = rsProps.rsWebServerPort;

            // MS
            xDoc.SelectSingleNode("/recorderconfig/server/address").InnerText    = rsProps.msWebApiAddress;
            xDoc.SelectSingleNode("/recorderconfig/server/webapiport").InnerText = rsProps.msWebApiPort;
            xDoc.SelectSingleNode("/recorderconfig/server/authorizationserveraddress").InnerText = rsProps.authorizationServerAddress;


            // Pipeline Settings
            xDoc.SelectSingleNode("/recorderconfig/pipeline/maxframesinqueue").InnerText       = rsProps.maxFramesInQueue;
            xDoc.SelectSingleNode("/recorderconfig/pipeline/maxbytesinqueue").InnerText        = rsProps.maxBytesInQueue;
            xDoc.SelectSingleNode("/recorderconfig/pipeline/maxactivetimepipeline2").InnerText = rsProps.maxActiveTimeForPipeline2;

            //Archiving Threads
            xDoc.SelectSingleNode("/recorderconfig/database/database_server/thread_pools/delete_thread_pool_size").InnerText = rsProps.deleteThreadPoolSize;
            xDoc.SelectSingleNode("/recorderconfig/database/database_server/thread_pools/low_priority_archive_thread_pool_size").InnerText  = rsProps.lowPriorityArchiveThread;
            xDoc.SelectSingleNode("/recorderconfig/database/database_server/thread_pools/high_priority_archive_thread_pool_size").InnerText = rsProps.highPriorityArchiveThread;

            //Disk Utilization
            xDoc.SelectSingleNode("/recorderconfig/database/database_server/disk_utilization/media_block_files/read_buffer_size").InnerText  = rsProps.mediaFileReadBuffer;
            xDoc.SelectSingleNode("/recorderconfig/database/database_server/disk_utilization/media_block_files/write_buffer_size").InnerText = rsProps.mediaFileWriteBuffer;
            xDoc.SelectSingleNode("/recorderconfig/database/database_server/disk_utilization/chunk_files/read_buffer_size").InnerText        = rsProps.chunkFileReadBuffer;
            xDoc.SelectSingleNode("/recorderconfig/database/database_server/disk_utilization/chunk_files/write_buffer_size").InnerText       = rsProps.chunkFileWriteBuffer;


            //Disk Usage Monitor
            xDoc.SelectSingleNode("/recorderconfig/database/database_server/disk_usage_monitor/force_archive_limit_in_mb").InnerText = rsProps.forceArchiveLimit;
            xDoc.SelectSingleNode("/recorderconfig/database/database_server/disk_usage_monitor/force_delete_limit_in_mb").InnerText  = rsProps.forceDeleteLimit;


            try
            {
                xDoc.SelectSingleNode("/recorderconfig/recorder/proxyServerSplitting").Attributes.GetNamedItem("maxVideoStreamsPerProxy").InnerText = rsProps.maxVideoStreamsPerProxy;
            }
            catch (Exception)
            {
                XmlNode      maxVideoStreamsPerProxy_node = xDoc.CreateNode(XmlNodeType.Element, "proxyServerSplitting", null);
                XmlAttribute attr = xDoc.CreateAttribute("maxVideoStreamsPerProxy");
                attr.Value = rsProps.maxVideoStreamsPerProxy;
                maxVideoStreamsPerProxy_node.Attributes.SetNamedItem(attr);
                xDoc.SelectSingleNode("/recorderconfig/recorder").AppendChild(maxVideoStreamsPerProxy_node);
            }



            try
            {
                xDoc.Save(@"C:\ProgramData\Milestone\XProtect Recording Server\RecorderConfig.xml");
            }

            catch {
                MessageBox.Show("ERROR SAVING");
            }
        }
Example #39
0
    public string CreateXoml(string name, JArray controls)
    {
        //save xoml
        System.IO.FileStream fStream = new System.IO.FileStream(name, System.IO.FileMode.OpenOrCreate);
        try
        {
            XmlTextWriter writer = new XmlTextWriter(fStream, new System.Text.UTF8Encoding());
            writer.Formatting = System.Xml.Formatting.Indented;
            writer.WriteStartDocument();// ("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            writer.WriteStartElement("ns0", "FLSequentialWorkflow", "clr-namespace:FLTools;Assembly=FLTools, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
            writer.WriteEndElement();
            writer.Close();
        }
        finally
        {
            fStream.Close();
        }
        fStream = new System.IO.FileStream(name, System.IO.FileMode.Open);

        try
        {

            XmlDocument doc = new XmlDocument();
            doc.Load(fStream);
            XmlNode root = doc.SelectSingleNode("FLSequentialWorkflow");
            XmlElement xeRoot = doc.DocumentElement;
            JObject mainProperty = null;
            foreach (JObject item in controls)
            {
                if (item["type"] != null && item["type"].ToString() == "mainProperty")
                {
                    mainProperty = item;
                    break;
                }
            }
            foreach (var item in mainProperty["properties"]["rows"])
            {
                if (item["name"] != null && item["value"] != null)
                {
                    if (item["name"].ToString() == "Description")
                    {
                        XmlAttribute aXmlAttribute = doc.CreateAttribute("x", "Name", "http://schemas.microsoft.com/winfx/2006/xaml");
                        aXmlAttribute.Value = "FLSequentialWorkflow";// item["value"].ToString();
                        xeRoot.Attributes.Append(aXmlAttribute);

                        aXmlAttribute = doc.CreateAttribute("Description");
                        aXmlAttribute.Value = item["value"].ToString();
                        xeRoot.Attributes.Append(aXmlAttribute);
                    }
                    if (item["name"].ToString() == "Keys")
                    {
                        var keys = "";
                        foreach (var key in item["value"])
                        {
                            keys += key["KeyName"].ToString() + ",";
                        }
                        if (!String.IsNullOrEmpty(keys))
                            keys = keys.Substring(0, keys.Length - 1);
                        xeRoot.SetAttribute(item["name"].ToString(), keys);
                    }
                    else
                        xeRoot.SetAttribute(item["name"].ToString(), item["value"].ToString());
                }
            }
            //XmlAttribute xmlnsAttribute = doc.CreateAttribute("xmlns");
            //xmlnsAttribute.Value = "http://schemas.microsoft.com/winfx/2006/xaml/workflow";
            //xeRoot.Attributes.Append(xmlnsAttribute);

            JToken currentProperty = FindNextActivity("start_node", controls);
            while (currentProperty != null && currentProperty["type"].ToString() != "flowend")
            {
                if (currentProperty["type"].ToString().LastIndexOf("_S") != -1)
                {
                    String type = "";
                    String branchType = "";
                    if (currentProperty["type"].ToString().IndexOf("flowIfElseActivity") != -1)
                    {
                        type = "IfElseActivity";
                        branchType = "IfElseBranchActivity";
                    }
                    else
                    {
                        type = "ParallelActivity";
                        branchType = "SequenceActivity";
                    }
                    XmlNode newNode = doc.CreateNode(XmlNodeType.Element, "", type, "http://schemas.microsoft.com/winfx/2006/xaml/workflow");
                    XmlAttribute newAttribute = doc.CreateAttribute("x", "Name", "http://schemas.microsoft.com/winfx/2006/xaml");
                    newAttribute.Value = currentProperty["id"].ToString();
                    newNode.Attributes.Append(newAttribute);
                    if (currentProperty["properties"] != null)
                    {
                        for (var j = 0; j < currentProperty["properties"].Count(); j++)
                        {
                            if (currentProperty["properties"][j]["name"] != null && currentProperty["properties"][j]["name"].ToString() == "Description")
                            {
                                XmlAttribute dAttribute = doc.CreateAttribute("Description");
                                dAttribute.Value = currentProperty["properties"][j]["value"].ToString();
                                newNode.Attributes.Append(dAttribute);
                            }
                        }
                    }

                    xeRoot.AppendChild(newNode);

                    var branchCount = 0;
                    foreach (var item in controls)
                    {
                        if (item["id"] != null && item["id"].ToString().IndexOf(currentProperty["classify"] + "_") != -1 &&
                            item["id"].ToString() != currentProperty["classify"] + "_S" && item["id"].ToString() != currentProperty["classify"] + "_E" &&
                            item["type"].ToString() != "sl" && item["type"].ToString() != "lr")
                        {
                            branchCount++;
                        }
                    }
                    for (var i = 0; i < branchCount; i++)
                    {
                        var nId = currentProperty["classify"] + "_" + (i + 1).ToString();
                        var node = FindCurrentActivity(nId, controls);
                        XmlNode aNode = doc.CreateNode(XmlNodeType.Element, "", branchType, "http://schemas.microsoft.com/winfx/2006/xaml/workflow");
                        XmlAttribute aAttribute = doc.CreateAttribute("x", "Name", "http://schemas.microsoft.com/winfx/2006/xaml");
                        if (node["name"] != null && node["name"].ToString() != "")
                            aAttribute.Value = node["name"].ToString();
                        else
                            aAttribute.Value = nId;
                        aNode.Attributes.Append(aAttribute);

                        for (var j = 0; j < node["properties"].Count(); j++)
                        {
                            if (node["properties"][j]["name"] != null && node["properties"][j]["name"].ToString() == "Description")
                            {
                                XmlAttribute dAttribute = doc.CreateAttribute("Description");
                                dAttribute.Value = node["properties"][j]["value"].ToString();
                                aNode.Attributes.Append(dAttribute);
                            }
                        }

                        newNode.AppendChild(aNode);

                        if (i == branchCount - 1)
                            currentProperty = WriteNestedActivity(doc, aNode, nId, controls);
                        else
                            WriteNestedActivity(doc, aNode, nId, controls);
                    }
                }
                else
                {
                    XmlNode newNode = doc.CreateNode(XmlNodeType.Element, "ns0", currentProperty["type"].ToString().Replace("FLTools.", String.Empty), "clr-namespace:FLTools;Assembly=FLTools, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
                    foreach (var item in currentProperty["properties"])
                    {
                        if (item["name"] != null && item["value"] != null)
                        {
                            XmlAttribute newAttribute = null;
                            if (item["name"].ToString() == "name" || item["name"].ToString() == "ID")
                            {
                                newAttribute = doc.CreateAttribute("x", "Name", "http://schemas.microsoft.com/winfx/2006/xaml");
                                newAttribute.Value = item["value"].ToString();
                                newNode.Attributes.Append(newAttribute);
                            }
                            else if (item["name"].ToString() == "ApproveRights")
                            {
                                //<ns0:FLApprove.ApproveRights>
                                XmlNode xnApproveRights = doc.CreateNode(XmlNodeType.Element, "ns0", "FLApprove.ApproveRights", "clr-namespace:FLTools;Assembly=FLTools, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
                                //<ns1:ApproveRightCollection xmlns:ns1="clr-namespace:FLCore;Assembly=FLTools, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
                                XmlNode xnApproveRightCollection = doc.CreateNode(XmlNodeType.Element, "ns1", "ApproveRightCollection", "clr-namespace:FLCore;Assembly=FLTools, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
                                for (var i = 0; i < item["value"].Count(); i++)
                                {
                                    XmlNode xnApproveRight = doc.CreateNode(XmlNodeType.Element, "ns1", "ApproveRight", "clr-namespace:FLCore;Assembly=FLTools, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
                                    XmlAttribute xaGrade = doc.CreateAttribute("Grade");
                                    xaGrade.Value = item["value"][i]["Grade"].ToString();
                                    xnApproveRight.Attributes.Append(xaGrade);
                                    XmlAttribute xaExpression = doc.CreateAttribute("Expression");
                                    xaExpression.Value = item["value"][i]["Expression"].ToString();
                                    xnApproveRight.Attributes.Append(xaExpression);
                                    xnApproveRightCollection.AppendChild(xnApproveRight);
                                }
                                xnApproveRights.AppendChild(xnApproveRightCollection);
                                newNode.AppendChild(xnApproveRights);
                            }
                            else
                            {
                                newAttribute = doc.CreateAttribute(item["name"].ToString());
                                newAttribute.Value = item["value"].ToString();
                                newNode.Attributes.Append(newAttribute);
                            }
                        }
                    }
                    xeRoot.AppendChild(newNode);
                }

                currentProperty = FindNextActivity(currentProperty["id"].ToString(), controls);
            }
            fStream.Close();
            var sXml = doc.OuterXml;
            CodeWriter = new StringBuilder(sXml);
        }
        finally
        {
            fStream.Close();
            System.IO.File.Delete(name);
        }
        return CodeWriter.ToString();
    }
Example #40
0
        void SetEventLogCollector(XmlNode node)
        {
            XmlAttribute attribEventLogCollectorEnabled = doc.CreateAttribute("enabled");

            attribEventLogCollectorEnabled.Value = m_Setting[Res.CollectEventLogs];
            XmlAttribute attribEventLogCollectorStartup = doc.CreateAttribute("startup");

            attribEventLogCollectorStartup.Value = m_Setting[Res.CollectEventLogsStartup];

            XmlAttribute attribEventLogCollectorShutdown = doc.CreateAttribute("shutdown");

            attribEventLogCollectorShutdown.Value = m_Setting[Res.CollectEventLogShutdown];

            node.Attributes.Append(attribEventLogCollectorEnabled);
            node.Attributes.Append(attribEventLogCollectorStartup);
            node.Attributes.Append(attribEventLogCollectorShutdown);

            XmlNode Eventlogs = doc.CreateNode(XmlNodeType.Element, "Eventlogs", "");

            node.AppendChild(Eventlogs);


            //create the application eventlog node with attributes
            XmlNode EventLogTypeApp = doc.CreateNode(XmlNodeType.Element, "EventlogType", "");

            Eventlogs.AppendChild(EventLogTypeApp);

            XmlAttribute attribEventLogCollectorAppName = doc.CreateAttribute("name");

            attribEventLogCollectorAppName.Value = "Application";
            EventLogTypeApp.Attributes.Append(attribEventLogCollectorAppName);

            XmlAttribute attribEventLogCollectorAppEnabled = doc.CreateAttribute("enabled");

            attribEventLogCollectorAppEnabled.Value = "true";
            EventLogTypeApp.Attributes.Append(attribEventLogCollectorAppEnabled);


            //create the system eventlog node with attributes
            XmlNode EventLogTypeSys = doc.CreateNode(XmlNodeType.Element, "EventlogType", "");

            Eventlogs.AppendChild(EventLogTypeSys);

            XmlAttribute attribEventLogCollectorSysName = doc.CreateAttribute("name");

            attribEventLogCollectorSysName.Value = "System";
            EventLogTypeSys.Attributes.Append(attribEventLogCollectorSysName);

            XmlAttribute attribEventLogCollectorSysEnabled = doc.CreateAttribute("enabled");

            attribEventLogCollectorSysEnabled.Value = "true";
            EventLogTypeSys.Attributes.Append(attribEventLogCollectorSysEnabled);


            //create the Security eventlog node with attributes
            XmlNode EventLogTypeSec = doc.CreateNode(XmlNodeType.Element, "EventlogType", "");

            Eventlogs.AppendChild(EventLogTypeSec);

            XmlAttribute attribEventLogCollectorSecName = doc.CreateAttribute("name");

            attribEventLogCollectorSecName.Value = "Security";
            EventLogTypeSec.Attributes.Append(attribEventLogCollectorSecName);

            XmlAttribute attribEventLogCollectorSecEnabled = doc.CreateAttribute("enabled");

            attribEventLogCollectorSecEnabled.Value = "false";
            EventLogTypeSec.Attributes.Append(attribEventLogCollectorSecEnabled);
        }
    void AddNodes(string fileName, int UserID,string FirstName,string LastName, string UserName,bool IsUserNameVisible)
    {
        FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read,
                                FileShare.ReadWrite);
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.Load(fs);
        XmlNode node = xmldoc.CreateNode(XmlNodeType.Element, "User", null);

        ArrayList strArr = new ArrayList();
        strArr.Add("UserID");
        strArr.Add("UserName");
        strArr.Add("FirstName");
        strArr.Add("LastName");
        strArr.Add("IsUserNameVisible");
        foreach (string str in strArr)
        {
           string  Name = str;
           XmlElement Blankelement = xmldoc.CreateElement(Name.Trim());
           if (str == "UserID")
               Blankelement.InnerText =UserID.ToString();
           else if (str == "UserName")
               Blankelement.InnerText = UserName;
           else if (str == "FirstName")
               Blankelement.InnerText = FirstName;
           else if (str == "LastName")
               Blankelement.InnerText = LastName;
           else if (str == "IsUserNameVisible")
               Blankelement.InnerText = IsUserNameVisible.ToString();
            node.AppendChild(Blankelement);
        }
        XmlNodeList nodeList = xmldoc.GetElementsByTagName("User");
        nodeList[0].AppendChild(node);

        FileStream fsxml = new FileStream(fileName, FileMode.Truncate,
                                          FileAccess.Write,
                                          FileShare.ReadWrite);
        xmldoc.Save(fsxml);
        fsxml.Close();
        fsxml.Dispose();
    }
Example #42
0
        void SetCollection(XmlNode node)
        {
            XmlAttribute attribCollectionCaseNumber = m_doc.CreateAttribute("casenumber");

            attribCollectionCaseNumber.Value = "SRX000000000000";
            XmlAttribute attribCollectionSetupVer = m_doc.CreateAttribute("setupver");

            attribCollectionSetupVer.Value = "12.0.0.1001";
            node.Attributes.Append(attribCollectionCaseNumber);
            node.Attributes.Append(attribCollectionSetupVer);
            XmlNode MachinesNode = m_doc.CreateNode(XmlNodeType.Element, "Machines", "");

            node.AppendChild(MachinesNode);
            SetMachines(MachinesNode);

            //Logger.LogMessage(m_Setting.XEventCategoryList.GetCheckedDiagItemList().GetSQLScript(), LogLevel.INFO);
        }
Example #43
0
    //将发帖内容保存到XML文件中的方法
    public void AddXML(string filename, string title, string content, string user)
    {
        XmlDocument mydoc = new XmlDocument();
        mydoc.Load(filename);

        //添加帖子主题
        XmlElement ele = mydoc.CreateElement("title");
        XmlText text = mydoc.CreateTextNode(title);

        //添加发帖时间
        XmlElement ele1 = mydoc.CreateElement("posttime");
        XmlText text1 = mydoc.CreateTextNode(DateTime.Now.ToString());

        //添加发帖内容
        XmlElement ele2 = mydoc.CreateElement("content");
        XmlText text2 = mydoc.CreateTextNode(content);

        //添加发帖人
        XmlElement ele3 = mydoc.CreateElement("postuser");
        XmlText text3 = mydoc.CreateTextNode(user);

        //添加文件的节点-msgrecord
        XmlNode newElem = mydoc.CreateNode("element", "xmlrecord", "");
        //在节点中添加元素

        newElem.AppendChild(ele);
        newElem.LastChild.AppendChild(text);
        
        newElem.AppendChild(ele1);
        newElem.LastChild.AppendChild(text1);

        newElem.AppendChild(ele2);
        newElem.LastChild.AppendChild(text2);

        newElem.AppendChild(ele3);
        newElem.LastChild.AppendChild(text3);

        //将结点添加到文档中
        XmlElement root = mydoc.DocumentElement;
        root.AppendChild(newElem);

        //获取文件路径
        int index = filename.LastIndexOf(@"\");
        string path = filename.Substring(0, index);

        //新文件名
        path = path + @"\" + xmlfilename + "file.xml";
        FileStream mystream = File.Create(path);
        mystream.Close();

        //保存所有修改-到指定文件中:注意编码语言的选择
        XmlTextWriter mytw = new XmlTextWriter(path, Encoding.Default);
        mydoc.Save(mytw);
        mytw.Close();
       
    }
Example #44
0
    private void _Associar()
    {
        try
        {
            END_Endereco entityEndereco = new END_Endereco
            {
                end_id = _VS_end_id
                ,
                end_cep = txtCEP.Text
                ,
                end_logradouro = txtLogradouro.Text
                ,
                end_distrito = txtDistrito.Text
                ,
                end_zona = UCComboZona1._Combo.SelectedValue == "-1" ? Convert.ToByte(0) : Convert.ToByte(UCComboZona1._Combo.SelectedValue)
                ,
                end_bairro = txtBairro.Text
                ,
                cid_id = _VS_cid_id
                ,
                end_situacao = 1
                ,
                IsNew = (_VS_end_id != Guid.Empty) ? false : true
            };

            XmlDocument xDoc      = new XmlDocument();
            XmlNode     xElem     = xDoc.CreateNode(XmlNodeType.Element, "Coluna", "");
            XmlNode     xNodeCoor = xDoc.CreateNode(XmlNodeType.Element, "ColunaValorAntigo", "");
            XmlNode     xNode;

            for (int i = 0; i < _VS_AssociarEnderecos.Rows.Count; i++)
            {
                if (_VS_AssociarEnderecos.Rows[i]["end_id"].ToString() != _VS_end_id.ToString())
                {
                    xNodeCoor       = xDoc.CreateNode(XmlNodeType.Element, "ColunaValorAntigo", "");
                    xNode           = xDoc.CreateNode(XmlNodeType.Element, "valor", "");
                    xNode.InnerText = _VS_AssociarEnderecos.Rows[i]["end_id"].ToString();
                    xNodeCoor.AppendChild(xNode);
                    xElem.AppendChild(xNodeCoor);
                }
            }
            xDoc.AppendChild(xElem);

            if (END_EnderecoBO.AssociarEnderecos(entityEndereco, _VS_cid_idAntigo, xDoc))
            {
                ApplicationWEB._GravaLogSistema(LOG_SistemaTipo.Update, "end_id: " + entityEndereco.end_id);
                __SessionWEB.PostMessages = UtilBO.GetErroMessage("Endereços associados com sucesso.", UtilBO.TipoMensagem.Sucesso);

                Response.Redirect(__SessionWEB._AreaAtual._Diretorio + "ManutencaoEndereco/Busca.aspx", false);
            }
            else
            {
                _lblMessage.Text = UtilBO.GetErroMessage("Erro ao tentar associar os endereços.", UtilBO.TipoMensagem.Erro);
            }
        }
        catch (CoreLibrary.Validation.Exceptions.ValidationException ex)
        {
            _lblMessage.Text = UtilBO.GetErroMessage(ex.Message, UtilBO.TipoMensagem.Alerta);
        }
        catch (ArgumentException ex)
        {
            _lblMessage.Text = UtilBO.GetErroMessage(ex.Message, UtilBO.TipoMensagem.Alerta);
        }
        catch (DuplicateNameException ex)
        {
            _lblMessage.Text = UtilBO.GetErroMessage(ex.Message, UtilBO.TipoMensagem.Alerta);
        }
        catch (Exception ex)
        {
            ApplicationWEB._GravaErro(ex);
            _lblMessage.Text = UtilBO.GetErroMessage("Erro ao tentar associar os endereços.", UtilBO.TipoMensagem.Erro);
        }
        finally
        {
            _updEnderecos.Update();
        }
    }
Example #45
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        con.Open();
        string img = TextBox1.Text.Trim();
        string name = movname.Text;

        if (System.Text.RegularExpressions.Regex.IsMatch(duration.Value, "[^0-9]") ||  duration.Value=="")
        {
            MessageBox.Show("Please enter only numbers.");
            //duration.Value.Remove(duration.Value.Length - 1);
            duration.Focus();
        }
        else if (!img.Contains(".jpg") || !img.Contains(".png") || !img.Contains(".bmp") || !img.Contains(".gif") || img == "")
        {
            MessageBox.Show("Please provide image name with extension.");
            TextBox1.Focus();
        }
        else
        {
            try
            {

                cmd = new SqlCommand("insert into moviedb values(@id,@name,@gen,@cast,@dir,@dur,@time,@tname,@hid,@path)", con);
                cmd.Parameters.AddWithValue("@id", movid.Value);
                cmd.Parameters.AddWithValue("@name", movname.Text);
                cmd.Parameters.AddWithValue("@gen", categeory.Value);
                cmd.Parameters.AddWithValue("@cast", cast.Value);
                cmd.Parameters.AddWithValue("@dir", dir.Value);
                cmd.Parameters.AddWithValue("@dur", duration.Value);
                cmd.Parameters.AddWithValue("@time", DropDownList1.SelectedItem.ToString());
                cmd.Parameters.AddWithValue("@tname", thname.Value);
                cmd.Parameters.AddWithValue("@hid", hallid.Value);
                if (img != "")
                { cmd.Parameters.AddWithValue("@path", img); }
                else { cmd.Parameters.AddWithValue("@path", null); }

                cmd.ExecuteNonQuery();

                MessageBox.Show("Movie Added Successfully", "Success");
                Button2_Click(sender, e);

                string filename = Server.MapPath("../addmovies.xml");
                XmlDocument doc = new XmlDocument();
                doc.Load(filename);
                XmlNode node = doc.CreateNode(XmlNodeType.Element, "Ad", null);

                XmlNode nodeUrl = doc.CreateElement("ImageUrl");
                XmlNode nodeUrl1 = doc.CreateElement("AlternateText");

                nodeUrl.InnerText = "../images/" + img;
                nodeUrl1.InnerText = img;
                //nodeUrl1.InnerText = name.Trim();

               //This code will add the ImageUrl and Alternate Text to the addmovies xml file.
                node.AppendChild(nodeUrl1);
                node.AppendChild(nodeUrl);

                //This line will add the child nodes ImageURl and Alternate text to the xml root node Ad
                doc.DocumentElement.AppendChild(node);

                //This piece of code will save the nodes in the xml document addmovies.
                doc.Save(filename);
            }
            catch (SqlException sqlerr)
            {
                MessageBox.Show("Duplicate Movie ID provided. Please provide another id for the movie." + "\nError Message: " + sqlerr.Message);
            }
            catch (Exception ee)
            {
                MessageBox.Show("Please Fill in all the Details required..\nError Message: " + ee.Message);
            }
        }
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="DtIndicator"></param>
    /// <param name="DictIndicator"></param>
    /// <param name="DictIndicatorMapping"></param>
    /// <param name="DBOrDSDFlag"></param>
    /// <param name="DBNId"></param>
    /// <returns></returns>
    private string GetPublishDataGrid(DataTable DtIndicator, Dictionary<string, string> DictIndicator, Dictionary<string, string> DictIndicatorMapping, bool DBOrDSDFlag, string DBNId)
    {
        string RetVal;
        string chkAttribute = "";
        string IndicatorNIdForGID = string.Empty;
        string areas = string.Empty;
        string timeperiods = "";
        string sources = "";
        string selectedState = "false";
        string selectedJson = string.Empty;
        RetVal = string.Empty;
        DataSet ds = new DataSet();
        string xml = string.Empty;
        try
        {
            xml = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, Constants.FolderName.Data + DBNId + "\\sdmx" + "\\DataPublishedUserSelection.xml");
            if (File.Exists(xml) == false)
            {
                XmlDocument docConfig = new XmlDocument();
                XmlNode xmlNode = docConfig.CreateNode(XmlNodeType.XmlDeclaration, "", "");
                XmlElement rootElement = docConfig.CreateElement("root");
                docConfig.AppendChild(rootElement);
                foreach (DataRow DrowIndicator in DtIndicator.Rows)
                {
                    if (DictIndicatorMapping.ContainsKey(DrowIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorGId].ToString()))
                    {
                        // Create <Data> Node
                        XmlElement DataElement = docConfig.CreateElement("Data");
                        DataElement.SetAttribute("Ind", DrowIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString());
                        DataElement.SetAttribute("areas", "");
                        DataElement.SetAttribute("timeperiods", "");
                        DataElement.SetAttribute("source", "");
                        DataElement.SetAttribute("selectedState", "false");
                        rootElement.AppendChild(DataElement);
                    }
                }

                docConfig.Save(xml);
            }
            else
            {
                XmlDocument docConfig = new XmlDocument();
                docConfig.Load(xml);
                string IndNId = string.Empty;
                ArrayList ALItemAdded = new ArrayList();
                XmlNode rootElement = docConfig.SelectSingleNode("/root");
                foreach (XmlElement element in docConfig.SelectNodes("/root/Data"))
                {
                    if (!ALItemAdded.Contains(element.GetAttribute("Ind")))
                    {
                        ALItemAdded.Add(element.GetAttribute("Ind"));
                    }
                }
                foreach (DataRow DrowIndicator in DtIndicator.Rows)
                {
                    foreach (XmlElement element in docConfig.SelectNodes("/root/Data"))
                    {
                        if (DictIndicatorMapping.ContainsKey(DrowIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorGId].ToString()))
                        {
                            IndNId = DrowIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString();
                            if (!ALItemAdded.Contains(IndNId))
                            {
                                if (element.GetAttribute("Ind") != DrowIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString())
                                {
                                    XmlElement DataElement = docConfig.CreateElement("Data");
                                    DataElement.SetAttribute("Ind", DrowIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString());
                                    DataElement.SetAttribute("areas", "");
                                    DataElement.SetAttribute("timeperiods", "");
                                    DataElement.SetAttribute("source", "");
                                    DataElement.SetAttribute("selectedState", "false");
                                    rootElement.AppendChild(DataElement);
                                }
                                docConfig.Save(xml);
                                ALItemAdded.Add(IndNId);
                            }

                        }
                    }
                }

            }

            if (File.Exists(xml))
            {
                using (FileStream fs = new FileStream(xml, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    ds = new DataSet();
                    ds.ReadXml(fs);
                }
            }

            RetVal = "<table id=\"tblIATSGrid\" class=\"pivot_table\" style=\"width:100%; height:50%; overflow:auto;\">";
            RetVal += "<tr>";
            RetVal += "<th class=\"h1\" style=\"width:5%\"> <input id=\"chkIndicator_0\" type=\"checkbox\" value=\"0\" onclick=\"SelectUnselectAllIndicators();\"/>";
            RetVal += "</th>";
            RetVal += "<th class=\"h1\" style=\"width:35%\"> Indicators";
            RetVal += "</th>";
            RetVal += "<th class=\"h1\" style=\"width:20%\"> Area";
            RetVal += "</th>";
            RetVal += "<th class=\"h1\" style=\"width:20%\"> Time";
            RetVal += "</th>";
            RetVal += "<th class=\"h1\" style=\"width:20%\"> Source";
            RetVal += "</th>";
            RetVal += "</tr>";
            foreach (DataRow DrIndicator in DtIndicator.Rows)
            {

                chkAttribute = "";
                areas = "";
                timeperiods = "";
                sources = "";
                selectedState = "false";
                if (DictIndicatorMapping.ContainsKey(DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorGId].ToString()))
                {
                    IndicatorNIdForGID = DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString();
                    if (File.Exists(xml))
                    {
                        if (ds.Tables.Count > 0)
                        {
                            foreach (DataRow DSRow in ds.Tables["Data"].Select("Ind='" + IndicatorNIdForGID + "'"))
                            {
                                chkAttribute = "";
                                areas = DSRow["areas"].ToString();
                                timeperiods = DSRow["timeperiods"].ToString();
                                sources = DSRow["source"].ToString();
                                selectedState = DSRow["selectedState"].ToString();
                                if (selectedState == "true")
                                {
                                    chkAttribute = "checked";
                                }
                            }
                        }
                    }

                    RetVal += "<tr>";

                    RetVal += "<th class=\"h2\">";
                    if (chkAttribute == "checked")
                    {
                        RetVal += "<input checked=\"" + chkAttribute + "\" id=\"chkIndicator_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" type=\"checkbox\" value=\"" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\"/>";
                        RetVal += "</th>";

                        RetVal += "<th class=\"h2\" style=\"padding-left: 10px;\">";
                        RetVal += "<span style=\"float:left\" id=\"spanIndicator_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\">" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorName].ToString() + "</span>";
                        RetVal += "</th>";
                        if (string.IsNullOrEmpty(areas))
                        {
                            RetVal += "<th id=\"spanArea_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" class=\"h2\"   style=\"padding-left: 10px;\"> Select <a rel=\" " + areas + "\" id=\"lkArea_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" href=\"#\" onclick=\"OpenAreaPopup(this);\">[+]</a> <a rel=\" " + areas + "\" id=\"clrArea_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" href=\"#\" onclick=\"RemoveAreas(this);\">[X]</a> <span id=\"spanArea_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\"></span> ";
                            RetVal += "</th>";
                        }
                        else
                        {
                            RetVal += "<th id=\"spanArea_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" class=\"h2\"   style=\"padding-left: 10px;\"> <b>Select</b> <a rel=\" " + areas + "\" id=\"lkArea_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" href=\"#\" onclick=\"OpenAreaPopup(this);\">[+]</a> <a rel=\" " + areas + "\" id=\"clrArea_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" href=\"#\" onclick=\"RemoveAreas(this);\">[X]</a> <span id=\"spanArea_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\"></span> ";
                            RetVal += "</th>";
                        }
                        if (string.IsNullOrEmpty(timeperiods))
                        {
                            RetVal += "<th id=\"spanTime_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" class=\"h2\"  style=\"padding-left: 10px;\">  Select <a rel=\" " + timeperiods + "\" id=\"lkTP_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" href=\"#\" onclick=\"OpenTPPopup(this);\">[+]</a> <a rel=\" " + timeperiods + "\" id=\"clrTP_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" href=\"#\" onclick=\"RemoveTimeperiods(this);\">[X]</a>";
                            RetVal += "</th>";
                        }
                        else
                        {
                            RetVal += "<th id=\"spanTime_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" class=\"h2\"  style=\"padding-left: 10px;\">  <b>Select</b> <a rel=\" " + timeperiods + "\" id=\"lkTP_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" href=\"#\" onclick=\"OpenTPPopup(this);\">[+]</a> <a rel=\" " + timeperiods + "\" id=\"clrTP_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" href=\"#\" onclick=\"RemoveTimeperiods(this);\">[X]</a>";
                            RetVal += "</th>";
                        }
                        if (string.IsNullOrEmpty(sources))
                        {
                            RetVal += "<th id=\"spanSource_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" class=\"h2\"  style=\"padding-left: 10px;\">  Select <a rel=\" " + sources + "\" id=\"lkSource_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" href=\"#\" onclick=\"OpenSourcePopup(this);\">[+]</a>  <a rel=\" " + sources + "\" id=\"clrSource_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" href=\"#\" onclick=\"RemoveSource(this);\">[X]</a>";
                            RetVal += "</th>";
                        }
                        else
                        {
                            RetVal += "<th id=\"spanSource_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" class=\"h2\"  style=\"padding-left: 10px;\">  <b>Select</b> <a rel=\" " + sources + "\" id=\"lkSource_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" href=\"#\" onclick=\"OpenSourcePopup(this);\">[+]</a>  <a rel=\" " + sources + "\" id=\"clrSource_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" href=\"#\" onclick=\"RemoveSource(this);\">[X]</a>";
                            RetVal += "</th>";
                        }

                        RetVal += "</tr>";
                    }
                    else
                    {
                        RetVal += "<input id=\"chkIndicator_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" type=\"checkbox\" value=\"" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\"/>";
                        RetVal += "</th>";
                        //DictIndicator[DictIndicatorMapping[DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorGId].ToString()].ToString()]
                        RetVal += "<th class=\"h2\" style=\"padding-left: 10px;\">";
                        RetVal += "<span style=\"float:left\" id=\"spanIndicator_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\">" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorName].ToString() + "</span>";
                        RetVal += "</th>";
                        if (string.IsNullOrEmpty(areas))
                        {
                            RetVal += "<th id=\"spanArea_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" class=\"h2\"  style=\"padding-left: 10px;\"> Select <a rel=\" " + areas + "\" id=\"lkArea_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" href=\"#\" onclick=\"OpenAreaPopup(this);\">[+]</a>  <a rel=\" " + areas + "\" id=\"clrArea_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" href=\"#\" onclick=\"RemoveAreas(this);\">[X]</a>";
                            RetVal += "</th>";
                        }
                        else
                        {
                            RetVal += "<th id=\"spanArea_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" class=\"h2\"  style=\"padding-left: 10px;\"> <b>Select</b> <a rel=\" " + areas + "\" id=\"lkArea_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" href=\"#\" onclick=\"OpenAreaPopup(this);\">[+]</a>  <a rel=\" " + areas + "\" id=\"clrArea_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" href=\"#\" onclick=\"RemoveAreas(this);\">[X]</a>";
                            RetVal += "</th>";
                        }
                        if (string.IsNullOrEmpty(timeperiods))
                        {
                            RetVal += "<th id=\"spanTime_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" class=\"h2\"  style=\"padding-left: 10px;\">  Select <a rel=\" " + timeperiods + "\" id=\"lkTP_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" href=\"#\" onclick=\"OpenTPPopup(this);\">[+]</a> <a rel=\" " + timeperiods + "\" id=\"clrTP_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" href=\"#\" onclick=\"RemoveTimeperiods(this);\">[X]</a>  <span id=\"spanTime_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\"></span>";
                            RetVal += "</th>";
                        }
                        else
                        {
                            RetVal += "<th id=\"spanTime_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" class=\"h2\"  style=\"padding-left: 10px;\">  <b>Select</b> <a rel=\" " + timeperiods + "\" id=\"lkTP_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" href=\"#\" onclick=\"OpenTPPopup(this);\">[+]</a> <a rel=\" " + timeperiods + "\" id=\"clrTP_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" href=\"#\" onclick=\"RemoveTimeperiods(this);\">[X]</a>  <span id=\"spanTime_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\"></span>";
                            RetVal += "</th>";
                        }
                        if (string.IsNullOrEmpty(sources))
                        {
                            RetVal += "<th id=\"spanSource_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" class=\"h2\"  style=\"padding-left: 10px;\">  Select <a  rel=\" " + sources + "\" id=\"lkSource_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" href=\"#\" onclick=\"OpenSourcePopup(this);\">[+]</a> <a rel=\" " + sources + "\" id=\"clrSource_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" href=\"#\" onclick=\"RemoveSource(this);\">[X]</a>  <span id=\"spanSource_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\"></span>";
                            RetVal += "</th>";
                        }
                        else
                        {
                            RetVal += "<th id=\"spanSource_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" class=\"h2\"  style=\"padding-left: 10px;\">  <b>Select</b> <a  rel=\" " + sources + "\" id=\"lkSource_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" href=\"#\" onclick=\"OpenSourcePopup(this);\">[+]</a> <a rel=\" " + sources + "\" id=\"clrSource_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\" href=\"#\" onclick=\"RemoveSource(this);\">[X]</a>  <span id=\"spanSource_" + DrIndicator[DevInfo.Lib.DI_LibDAL.Queries.DIColumns.Indicator.IndicatorNId].ToString() + "\"></span>";
                            RetVal += "</th>";
                        }
                        RetVal += "</tr>";
                    }

                }

            }

            RetVal += "</table>";
            if (ds.Tables.Contains("Data") == true)
            {
                if (ds.Tables["Data"].Rows.Count > 0)
                {
                    DataTable newTable = ds.Tables["Data"].DefaultView.ToTable(false, "Ind", "areas", "timeperiods", "source");

                    selectedJson = GetJSONString(newTable);

                    RetVal += Constants.Delimiters.EndDelimiter + selectedJson;
                }
            }
        }
        catch (Exception ex)
        {
            RetVal = "false" + Constants.Delimiters.ParamDelimiter + ex.Message;
            Global.CreateExceptionString(ex, null);
        }
        finally
        {

            ds = null;
            xml = null;
        }

        return RetVal;
    }
    /// <summary>
    /// Adds the appointment.
    /// </summary>
    /// <param name="appt">The appt.</param>
    /// <param name="apptDate">The appt date.</param>
    public static void AddAppointment(Appointments appt, DateTime apptDate)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(HttpContext.Current.Server.MapPath("Appointments.xml"));

        string xpath = "appointments/year[@value='" + apptDate.Year.ToString() + "']/" + ((Helper.Month)apptDate.Month).ToString().ToLower();
        XmlNode node = doc.SelectSingleNode(xpath);

        if (node != null)
        {
            XmlNode childNode = doc.CreateNode(XmlNodeType.Element, "appt", "");

            XmlAttribute attribDay = doc.CreateAttribute("day");
            attribDay.Value = appt.Day.ToString();

            XmlAttribute attribBegin = doc.CreateAttribute("begin");
            attribBegin.Value = appt.AppointmentStart;

            XmlAttribute attribEnd = doc.CreateAttribute("end");
            attribEnd.Value = appt.AppointmentEnd;

            XmlAttribute attribDesc = doc.CreateAttribute("description");
            attribDesc.Value = appt.Description;

            XmlAttribute attribPopUpDesc = doc.CreateAttribute("popupdescription");
            attribPopUpDesc.Value = appt.PopupDescription;

            childNode.Attributes.Append(attribDay);
            childNode.Attributes.Append(attribBegin);
            childNode.Attributes.Append(attribEnd);
            childNode.Attributes.Append(attribDesc);
            childNode.Attributes.Append(attribPopUpDesc);

            node.AppendChild(childNode);
        }

        doc.Save(HttpContext.Current.Server.MapPath("Appointments.xml"));
    }
Example #48
0
        /// <summary>
        /// Serializes the given graph to the given stream using TriX data format.
        /// </summary>
        internal static void Serialize(RDFGraph graph, Stream outputStream)
        {
            try
            {
                #region serialize
                using (XmlTextWriter trixWriter = new XmlTextWriter(outputStream, Encoding.UTF8))
                {
                    XmlDocument trixDoc = new XmlDocument();
                    trixWriter.Formatting = Formatting.Indented;

                    #region xmlDecl
                    XmlDeclaration trixDecl = trixDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
                    trixDoc.AppendChild(trixDecl);
                    #endregion

                    #region trixRoot
                    XmlNode      trixRoot       = trixDoc.CreateNode(XmlNodeType.Element, "TriX", null);
                    XmlAttribute trixRootNS     = trixDoc.CreateAttribute("xmlns");
                    XmlText      trixRootNSText = trixDoc.CreateTextNode("http://www.w3.org/2004/03/trix/trix-1/");
                    trixRootNS.AppendChild(trixRootNSText);
                    trixRoot.Attributes.Append(trixRootNS);

                    #region graph
                    XmlNode graphElement     = trixDoc.CreateNode(XmlNodeType.Element, "graph", null);
                    XmlNode graphUriElement  = trixDoc.CreateNode(XmlNodeType.Element, "uri", null);
                    XmlText graphUriElementT = trixDoc.CreateTextNode(graph.ToString());
                    graphUriElement.AppendChild(graphUriElementT);
                    graphElement.AppendChild(graphUriElement);

                    #region triple
                    foreach (var t in graph)
                    {
                        XmlNode tripleElement = trixDoc.CreateNode(XmlNodeType.Element, "triple", null);

                        #region subj
                        XmlNode subjElement = (((RDFResource)t.Subject).IsBlank ? trixDoc.CreateNode(XmlNodeType.Element, "id", null) :
                                               trixDoc.CreateNode(XmlNodeType.Element, "uri", null));
                        XmlText subjElementText = trixDoc.CreateTextNode(t.Subject.ToString());
                        subjElement.AppendChild(subjElementText);
                        tripleElement.AppendChild(subjElement);
                        #endregion

                        #region pred
                        XmlNode uriElementP = trixDoc.CreateNode(XmlNodeType.Element, "uri", null);
                        XmlText uriTextP    = trixDoc.CreateTextNode(t.Predicate.ToString());
                        uriElementP.AppendChild(uriTextP);
                        tripleElement.AppendChild(uriElementP);
                        #endregion

                        #region object
                        if (t.TripleFlavor == RDFModelEnums.RDFTripleFlavors.SPO)
                        {
                            XmlNode objElement = (((RDFResource)t.Object).IsBlank ? trixDoc.CreateNode(XmlNodeType.Element, "id", null) :
                                                  trixDoc.CreateNode(XmlNodeType.Element, "uri", null));
                            XmlText objElementText = trixDoc.CreateTextNode(t.Object.ToString());
                            objElement.AppendChild(objElementText);
                            tripleElement.AppendChild(objElement);
                        }
                        #endregion

                        #region literal
                        else
                        {
                            #region plain literal
                            if (t.Object is RDFPlainLiteral)
                            {
                                XmlNode plainLiteralElement = trixDoc.CreateNode(XmlNodeType.Element, "plainLiteral", null);
                                if (((RDFPlainLiteral)t.Object).Language != String.Empty)
                                {
                                    XmlAttribute xmlLang     = trixDoc.CreateAttribute(RDFVocabulary.XML.PREFIX + ":lang", RDFVocabulary.XML.BASE_URI);
                                    XmlText      xmlLangText = trixDoc.CreateTextNode(((RDFPlainLiteral)t.Object).Language);
                                    xmlLang.AppendChild(xmlLangText);
                                    plainLiteralElement.Attributes.Append(xmlLang);
                                }
                                XmlText plainLiteralText = trixDoc.CreateTextNode(RDFModelUtilities.EscapeControlCharsForXML(HttpUtility.HtmlDecode(((RDFLiteral)t.Object).Value)));
                                plainLiteralElement.AppendChild(plainLiteralText);
                                tripleElement.AppendChild(plainLiteralElement);
                            }
                            #endregion

                            #region typed literal
                            else
                            {
                                XmlNode      typedLiteralElement = trixDoc.CreateNode(XmlNodeType.Element, "typedLiteral", null);
                                XmlAttribute datatype            = trixDoc.CreateAttribute("datatype");
                                XmlText      datatypeText        = trixDoc.CreateTextNode(RDFModelUtilities.GetDatatypeFromEnum(((RDFTypedLiteral)t.Object).Datatype));
                                datatype.AppendChild(datatypeText);
                                typedLiteralElement.Attributes.Append(datatype);
                                XmlText typedLiteralText = trixDoc.CreateTextNode(RDFModelUtilities.EscapeControlCharsForXML(HttpUtility.HtmlDecode(((RDFLiteral)t.Object).Value)));
                                typedLiteralElement.AppendChild(typedLiteralText);
                                tripleElement.AppendChild(typedLiteralElement);
                            }
                            #endregion
                        }
                        #endregion

                        graphElement.AppendChild(tripleElement);
                    }
                    #endregion

                    trixRoot.AppendChild(graphElement);
                    #endregion

                    trixDoc.AppendChild(trixRoot);
                    #endregion

                    trixDoc.Save(trixWriter);
                }
                #endregion
            }
            catch (Exception ex)
            {
                throw new RDFModelException("Cannot serialize TriX because: " + ex.Message, ex);
            }
        }
Example #49
0
    protected void WriteUploadMonitorFile(string temporaryFileId, int state, string message)
    {
        // Write the file that contains information about the current upload process
        XmlDocument doc = new XmlDocument();

        XmlNode declaration = doc.CreateNode(XmlNodeType.XmlDeclaration, null, null);
        doc.AppendChild(declaration);

        XmlElement uploadMonitor = doc.CreateElement("uploadMonitor");
        doc.AppendChild(uploadMonitor);
        uploadMonitor.SetAttribute("state", state.ToString(System.Globalization.CultureInfo.InvariantCulture));
        uploadMonitor.InnerText = message;

        string uploadMonitorFilePath = TemporaryFileManager.GetTemporaryFilePath(temporaryFileId, "_um.xml");
        File.WriteAllText(uploadMonitorFilePath, doc.OuterXml, System.Text.Encoding.UTF8);
    }
Example #50
0
        /// <summary>
        /// Encrypts the NameID attribute of the AttributeQuery request.
        /// </summary>
        /// <param name="certValue">
        /// Encoded X509 certificate retrieved from the identity provider's metadata
        /// and used to encrypt generated symmetric key.
        /// </param>
        /// <param name="xmlDoc">
        /// XML document to be encrypted.
        /// </param>
        /// <param name="symmetricAlgorithmUri">
        /// Symmetric algorithm uri used for encryption.
        /// </param>
        public static void EncryptAttributeQueryNameID(string certValue, string symmetricAlgorithmUri, XmlDocument xmlDoc)
        {
            if (string.IsNullOrWhiteSpace(certValue))
            {
                throw new Saml2Exception(Resources.EncryptedXmlCertNotFound);
            }

            if (string.IsNullOrWhiteSpace(symmetricAlgorithmUri))
            {
                throw new Saml2Exception(Resources.EncryptedXmlInvalidEncrAlgorithm);
            }

            if (xmlDoc == null)
            {
                throw new Saml2Exception(Resources.SignedXmlInvalidXml);
            }

            byte[]           byteArray = Encoding.UTF8.GetBytes(certValue);
            X509Certificate2 cert      = new X509Certificate2(byteArray);

            if (cert == null)
            {
                throw new Saml2Exception(Resources.EncryptedXmlCertNotFound);
            }

            XmlNamespaceManager nsMgr = new XmlNamespaceManager(xmlDoc.NameTable);

            nsMgr.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);
            nsMgr.AddNamespace("saml", Saml2Constants.NamespaceSamlAssertion);
            nsMgr.AddNamespace("samlp", Saml2Constants.NamespaceSamlProtocol);

            string  xpath = "/samlp:AttributeQuery/saml:Subject/saml:NameID";
            XmlNode root  = xmlDoc.DocumentElement;
            XmlNode node  = root.SelectSingleNode(xpath, nsMgr);

            XmlNode encryptedID = xmlDoc.CreateNode(XmlNodeType.Element, "EncryptedID", Saml2Constants.NamespaceSamlAssertion);

            node.ParentNode.PrependChild(encryptedID);

            XmlElement elementToEncrypt = (XmlElement)encryptedID.AppendChild(node.Clone());

            if (elementToEncrypt == null)
            {
                throw new Saml2Exception(Resources.EncryptedXmlInvalidXml);
            }
            encryptedID.ParentNode.RemoveChild(node);

            SymmetricAlgorithm alg = Saml2Utils.GetAlgorithm(symmetricAlgorithmUri);

            if (alg == null)
            {
                throw new Saml2Exception(Resources.EncryptedXmlInvalidEncrAlgorithm);
            }

            alg.GenerateKey();

            string        encryptionElementID    = Saml2Utils.GenerateId();
            string        encryptionKeyElementID = Saml2Utils.GenerateId();
            EncryptedData encryptedData          = new EncryptedData();

            encryptedData.Type             = EncryptedXml.XmlEncElementUrl;
            encryptedData.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES128Url);
            encryptedData.Id = encryptionElementID;

            EncryptedXml encryptedXml = new EncryptedXml();

            byte[] encryptedElement = encryptedXml.EncryptData(elementToEncrypt, alg, false);
            encryptedData.CipherData.CipherValue = encryptedElement;
            encryptedData.KeyInfo = new KeyInfo();

            EncryptedKey encryptedKey = new EncryptedKey();

            encryptedKey.Id = encryptionKeyElementID;
            RSA publicKeyRSA = cert.PublicKey.Key as RSA;

            encryptedKey.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url);
            encryptedKey.CipherData       = new CipherData(EncryptedXml.EncryptKey(alg.Key, publicKeyRSA, false));

            encryptedData.KeyInfo.AddClause(new KeyInfoRetrievalMethod("#" + encryptionKeyElementID, "http://www.w3.org/2001/04/xmlenc#EncryptedKey"));

            KeyInfoName kin = new KeyInfoName();

            kin.Value = cert.SubjectName.Name;
            encryptedKey.KeyInfo.AddClause(kin);

            EncryptedXml.ReplaceElement(elementToEncrypt, encryptedData, false);

            XmlNode importKeyNode = xmlDoc.ImportNode(encryptedKey.GetXml(), true);

            encryptedID.AppendChild(importKeyNode);
        }
	/// <summary>
	/// Create a node containing the permission
	/// </summary>
	/// <param name="doc">XML configuration document</param>
	/// <returns>base node of new permission</returns>
	public XmlNode Create(XmlDocument doc)
	{
		// create the permission node
		XmlNode perm = doc.CreateNode(XmlNodeType.Element, "Permission", null);

		// assign the directory attribute
		XmlAttribute dir = doc.CreateAttribute("Dir");
		dir.Value = Dir;
		perm.Attributes.Append(dir);

		// create and add the options
		perm.AppendChild(CreateOption(doc, "FileRead",OptionFileRead));
		perm.AppendChild(CreateOption(doc, "FileWrite", OptionFileWrite));
		perm.AppendChild(CreateOption(doc, "FileDelete", OptionFileDelete));
		perm.AppendChild(CreateOption(doc, "FileAppend", OptionFileAppend));
		perm.AppendChild(CreateOption(doc, "DirCreate", OptionDirCreate));
		perm.AppendChild(CreateOption(doc, "DirDelete", OptionDirDelete));
		perm.AppendChild(CreateOption(doc, "DirList", OptionDirList));
		perm.AppendChild(CreateOption(doc, "DirSubdirs", OptionDirSubdirs));
		perm.AppendChild(CreateOption(doc, "IsHome", OptionIsHome));
		perm.AppendChild(CreateOption(doc, "AutoCreate", OptionAutoCreate));

		// add the aliases
		if (Aliases.Count > 0)
		{
			XmlNode aliasesNode = doc.CreateElement("Aliases");
			foreach (string alias in Aliases)
			{
				XmlNode aliasNode = doc.CreateElement("Alias");
				aliasNode.Value = alias;
				aliasesNode.AppendChild(aliasNode);
			}
			perm.AppendChild(aliasesNode);
		}
		return perm;
	}
        /// <summary>
        /// Updates the Project Nodes for Later Versions.
        /// </summary>
        private void UpdateProjectFile()
        {
            _DeXml.XmlResolver = FileStreamXmlResolver.GetNullResolver();
            _DeXml.Load(_projectFileWithPath);
            XmlElement   root       = GetRootNode();
            const string xPath      = "/Project/SolutionExplorer";
            XmlNode      searchNode = root.SelectSingleNode(xPath);

            if (searchNode == null)
            {
                const string filePath = "/Project/File";
                XmlNodeList  fileNode = root.SelectNodes(filePath);
                XmlNode      newNode  = _DeXml.CreateNode("element", "SolutionExplorer", "");
                if (fileNode != null)
                {
                    foreach (XmlNode item in fileNode)
                    {
                        newNode.AppendChild(item);
                    }
                }
                root.AppendChild(newNode);
                _DeXml.Save(_projectFileWithPath);
                _DeXml.Load(_projectFileWithPath);
            }
        }
Example #53
0
    /// <summary>
    /// To Check if the appsetting already exists or not, if not then add it with suitable value
    /// </summary>
    /// <param name="xmlDoc"></param>
    /// <param name="keyName"></param>
    /// <returns></returns>
    public static string CheckAppSetting(XmlDocument xmlDocument, string keyName, string keyValue)
    {
        string RetVal = string.Empty;
        XmlDocument XmlDoc;
        string AppSettingsFile = string.Empty;

        try
        {
            if (xmlDocument.SelectSingleNode("/" + Constants.XmlFile.AppSettings.Tags.Root + "/" + Constants.XmlFile.AppSettings.Tags.Item + "[@" + Constants.XmlFile.AppSettings.Tags.ItemAttributes.Name + "='" + keyName + "']") == null)
            {
                AppSettingsFile = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, ConfigurationManager.AppSettings[Constants.WebConfigKey.AppSettingFile]);
                XmlDoc = new XmlDocument();
                XmlDoc.Load(AppSettingsFile);
                XmlNode xNode = XmlDoc.CreateNode(XmlNodeType.Element, "item", "");
                XmlAttribute xKey = XmlDoc.CreateAttribute("n");
                XmlAttribute xValue = XmlDoc.CreateAttribute("v");
                xKey.Value = keyName;
                xValue.Value = keyValue;
                xNode.Attributes.Append(xKey);
                xNode.Attributes.Append(xValue);
                XmlDoc.GetElementsByTagName("appsettings")[0].InsertAfter(xNode,
                XmlDoc.GetElementsByTagName("appsettings")[0].LastChild);
                File.SetAttributes(AppSettingsFile, FileAttributes.Normal);
                XmlDoc.Save(AppSettingsFile);
            }

        }
        catch (Exception ex)
        {
            Global.CreateExceptionString(ex, null);
        }

        return RetVal;
    }
    public void UpdateLinkerContent(LinkerData _target)
    {
        _target.LinkContentUpdateDone = false;

        _target.Asset = PlayMakerEditorUtils.GetAssetByName("link.xml") as TextAsset;

        string _assetPath = Application.dataPath + "/link.xml";


        // create xml doc
        XmlDocument _doc = new XmlDocument();

        XmlNode _rootNode;

        if (_target.Asset != null)
        {
            _assetPath = AssetDatabase.GetAssetPath(_target.Asset);
            _doc.LoadXml(_target.Asset.text);
            _rootNode = _doc.SelectSingleNode("linker");
        }
        else
        {
            _rootNode = _doc.CreateNode(XmlNodeType.Element, "linker", null);
            _doc.AppendChild(_rootNode);
        }

        if (_rootNode == null)
        {
            Debug.LogError("Link.xml seems to be badly formatted");
            return;
        }

        foreach (KeyValuePair <string, List <string> > entry in _target.linkerEntries)
        {
            string assemblyName = entry.Key;

            XmlNode _assemblyNode = _doc.SelectSingleNode("//assembly[@fullname='" + assemblyName + "']");
            if (_assemblyNode == null)
            {
                _assemblyNode = _doc.CreateNode(XmlNodeType.Element, "assembly", null);
                _rootNode.AppendChild(_assemblyNode);

                XmlAttribute _fullnameAttr = _doc.CreateAttribute("fullname");
                _fullnameAttr.Value = assemblyName;
                _assemblyNode.Attributes.Append(_fullnameAttr);
            }

            foreach (string _type in entry.Value)
            {
                XmlNode _typeNode = _assemblyNode.SelectSingleNode("./type[@fullname='" + _type + "']");
                if (_typeNode == null)
                {
                    _typeNode = _doc.CreateNode(XmlNodeType.Element, "type", null);
                    _assemblyNode.AppendChild(_typeNode);

                    XmlAttribute _fullnameAttr = _doc.CreateAttribute("fullname");
                    _fullnameAttr.Value = _type;
                    _typeNode.Attributes.Append(_fullnameAttr);

                    XmlAttribute _preserveAttr = _doc.CreateAttribute("preserve");
                    _preserveAttr.Value = "all";
                    _typeNode.Attributes.Append(_preserveAttr);
                }
            }
        }

        Debug.Log("Updated and Saving linker xml content to : " + _assetPath);
        _doc.Save(_assetPath);

        AssetDatabase.Refresh();
        EditorUtility.FocusProjectWindow();
        _target.Asset = AssetDatabase.LoadAssetAtPath(_assetPath, typeof(TextAsset)) as TextAsset;

        _target.LinkContentUpdateDone = true;
    }
        /// <summary>
        /// 发送炉次计划给NC
        /// </summary>
        /// <param name="xmlFileName">xml完整路径</param>
        /// <param name="urlname">xml名称</param>
        /// <param name="urlname">计划表主键</param>
        /// <param name="c_stove">炉号</param>
        /// <returns></returns>
        public bool SendXml_SLAB_A2(string xmlFileName, string tsp_plan_sms_id, string stove)
        {
            try
            {
                string urlname = "A2LC" + stove + ".XML";//XML名称

                string url = xmlFileName + "\\NCXML";
                if (!Directory.Exists(url))
                {
                    Directory.CreateDirectory(url);
                }
                //DataTable dt = dal_slab_mes.GetList("", "", stove, "", "").Tables[0];
                Mod_TSP_PLAN_SMS  mod_plan_sms   = dal_plan_sms.GetModel(tsp_plan_sms_id);           //连铸生产计划表
                Mod_TPP_CAST_PLAN mod_cast_plan  = dal_cast_plan.GetModel_PLAN_ID(tsp_plan_sms_id);
                Mod_TB_MATRL_MAIN mod_mater_main = dal_mater_main.GetModel(mod_plan_sms.C_MATRL_NO); //物料主表
                Mod_TS_USER       mod_ts_user    = dal_user.GetModel(mod_plan_sms.C_EMP_ID);         //用户主表
                Mod_TMO_ORDER     mod_Order      = dal_tmo_order.GetModel(mod_plan_sms.C_ORDER_NO);
                Mod_TB_STA        modSta         = dalSta.GetModel(mod_plan_sms.C_CCM_ID);
                if (mod_plan_sms == null)
                {
                    return(false);
                }
                if (mod_cast_plan == null)
                {
                    return(false);
                }
                if (mod_mater_main == null)
                {
                    return(false);
                }
                if (mod_ts_user == null)
                {
                    return(false);
                }
                if (mod_Order == null)
                {
                    return(false);
                }
                if (modSta == null)
                {
                    return(false);
                }


                XmlDocument xmlDoc = new XmlDocument();
                //创建类型声明节点
                XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", "no");
                xmlDoc.AppendChild(node);

                //创建根节点
                XmlElement root = xmlDoc.CreateElement("ufinterface");
                #region//给节点属性赋值
                root.SetAttribute("billtype", "A2");
                root.SetAttribute("filename", "");
                root.SetAttribute("isexchange", "Y");
                root.SetAttribute("operation", "req");
                root.SetAttribute("proc", "add");
                root.SetAttribute("receiver", "101");
                root.SetAttribute("replace", "Y");
                root.SetAttribute("roottag", "bill");
                root.SetAttribute("sender", "1107");
                #endregion
                xmlDoc.AppendChild(root);

                //创建子根节点
                XmlElement bill = xmlDoc.CreateElement("bill");
                #region//节点属性
                bill.SetAttribute("id", mod_cast_plan.C_HEAT_ID);
                #endregion
                root.AppendChild(bill);

                XmlNode head = xmlDoc.CreateNode(XmlNodeType.Element, "bill_head", null);

                #region                                                                                                                          //表头_order_head
                CreateNode(xmlDoc, head, "scddh", "");                                                                                           //生产订单号 (空)
                CreateNode(xmlDoc, head, "pk_poid", "");                                                                                         //计划订单主键 (空)
                CreateNode(xmlDoc, head, "jhddh", "");                                                                                           //计划订单号 (空)
                CreateNode(xmlDoc, head, "wlbmid", mod_mater_main.C_PK_INVBASDOC);                                                               //物料编码ID (C_PK_INVBASDOC)
                CreateNode(xmlDoc, head, "pk_produce", "");                                                                                      //物料PK
                CreateNode(xmlDoc, head, "invcode", mod_mater_main.C_ID);                                                                        //物料编码
                CreateNode(xmlDoc, head, "invname", "");
                CreateNode(xmlDoc, head, "pch", stove);                                                                                          //批次号
                CreateNode(xmlDoc, head, "scbmid", "1001NC1000000000037T");                                                                      //生产部门ID
                CreateNode(xmlDoc, head, "gzzxid", modSta.C_ERP_PK);                                                                             //工作中心ID-连铸机号
                CreateNode(xmlDoc, head, "gzzxbm", "");                                                                                          //工作中心编码ID
                CreateNode(xmlDoc, head, "ksid", "");                                                                                            //客商ID
                CreateNode(xmlDoc, head, "memo", "");                                                                                            //备注
                CreateNode(xmlDoc, head, "sfjj", "");                                                                                            //是否加急
                CreateNode(xmlDoc, head, "yxj", "");                                                                                             //有效机时
                CreateNode(xmlDoc, head, "bcid", "1001NC1000000000103W");                                                                        //班次ID
                CreateNode(xmlDoc, head, "bzid", "1001NC100000002E7W1K");                                                                        //班组
                CreateNode(xmlDoc, head, "jhkgrq", Convert.ToDateTime(mod_plan_sms.D_P_START_TIME.ToString()).ToString("yyyy-MM-dd"));           //计划开工日期
                CreateNode(xmlDoc, head, "jhwgrq", Convert.ToDateTime(mod_plan_sms.D_P_END_TIME.ToString()).ToString("yyyy-MM-dd"));             //计划完工日期
                CreateNode(xmlDoc, head, "jhkssj", Convert.ToDateTime(mod_plan_sms.D_P_START_TIME.ToString()).ToString("HH:mm:ss"));             //计划开始时间
                CreateNode(xmlDoc, head, "jhjssj", Convert.ToDateTime(mod_plan_sms.D_P_END_TIME.ToString()).ToString("HH:mm:ss"));               //计划结束时间
                CreateNode(xmlDoc, head, "sjkgrq", Convert.ToDateTime(mod_cast_plan.D_AIM_CASTINGSTART_TIME.ToString()).ToString("yyyy-MM-dd")); //实际开工日期
                CreateNode(xmlDoc, head, "sjwgrq", Convert.ToDateTime(mod_cast_plan.D_AIM_CASTINGEND_TIME.ToString()).ToString("yyyy-MM-dd"));   //实际完工日期
                CreateNode(xmlDoc, head, "sjkssj", Convert.ToDateTime(mod_cast_plan.D_AIM_CASTINGSTART_TIME.ToString()).ToString("HH:mm:ss"));   //实际开始时间
                CreateNode(xmlDoc, head, "sjjssj", Convert.ToDateTime(mod_cast_plan.D_AIM_CASTINGEND_TIME.ToString()).ToString("HH:mm:ss"));     //实际结束时间
                CreateNode(xmlDoc, head, "jhwgsl", mod_plan_sms.N_SLAB_WGT.ToString());                                                          //计划完工数量
                CreateNode(xmlDoc, head, "fjhsl", mod_plan_sms.C_QUA);                                                                           //辅计量数量
                CreateNode(xmlDoc, head, "jldwid", mod_mater_main.C_PK_MEASDOC);                                                                 //计量单位ID
                CreateNode(xmlDoc, head, "fjlid", mod_mater_main.C_FJLDW);                                                                       //辅计量ID
                CreateNode(xmlDoc, head, "sjwgsl", mod_plan_sms.N_SLAB_WGT.ToString());                                                          //实际完工数量
                CreateNode(xmlDoc, head, "fwcsl", "");
                CreateNode(xmlDoc, head, "zdy1", "");                                                                                            //自定义项1
                CreateNode(xmlDoc, head, "zdy2", "");                                                                                            //自定义项2
                CreateNode(xmlDoc, head, "zdy3", "");                                                                                            //自定义项3
                CreateNode(xmlDoc, head, "zdy4", "");                                                                                            //自定义项4
                CreateNode(xmlDoc, head, "zdy5", "");                                                                                            //自定义项5
                CreateNode(xmlDoc, head, "freeitemvalue1", mod_Order.C_FREE1);
                CreateNode(xmlDoc, head, "freeitemvalue2", mod_Order.C_FREE2);
                CreateNode(xmlDoc, head, "freeitemvalue3", "");
                CreateNode(xmlDoc, head, "freeitemvalue4", "");
                CreateNode(xmlDoc, head, "freeitemvalue5", mod_plan_sms.C_ID); //PCI计划订单主键(tsp_plan_sms主键)
                CreateNode(xmlDoc, head, "pk_corp", "1001");                   //公司ID
                CreateNode(xmlDoc, head, "gcbm", "1001NC10000000000669");      //工厂
                CreateNode(xmlDoc, head, "zdrid", mod_ts_user.C_ACCOUNT);      //制单人
                CreateNode(xmlDoc, head, "pk_moid", "");                       //生产定单ID

                #endregion

                bill.AppendChild(head);
                XmlElement body = xmlDoc.CreateElement("bill_body");
                bill.AppendChild(body);

                XmlNode item = xmlDoc.CreateNode(XmlNodeType.Element, "item", null);


                body.AppendChild(item);


                xmlDoc.Save(url + "\\" + urlname);
                List <string> parem = dalSendNC.SendXML(url + "\\" + urlname);

                if (parem[0] == "1")
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch
            {
                return(false);
            }
        }
Example #56
0
        /// <summary>
        /// 写入配置文件 Config.xml
        /// </summary>
        /// <param name="cfg"></param>
        /// <returns></returns>
        public static bool XMLWriterByConfig(Config cfg, string startupPath)
        {
            bool   flag           = true;
            string configFilePath = startupPath + SysConstant.FILE_CONFIG;

            try
            {
                if (!Directory.Exists(startupPath + SysConstant.FOLDER_FILE))
                {
                    Directory.CreateDirectory(startupPath + SysConstant.FOLDER_FILE);
                }

                XmlDocument xmlDoc = new XmlDocument();


                //判断文件是否存在,不存在 则为 新增,存在则为 修改
                if (!File.Exists(configFilePath))
                {
                    //创建类型声明节点
                    XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");
                    xmlDoc.AppendChild(node);

                    //创建 根节点
                    XmlNode root = xmlDoc.CreateElement("ConfigRoot");
                    xmlDoc.AppendChild(root);

                    XmlNode configNode = xmlDoc.CreateNode(XmlNodeType.Element, "Config", null);
                    myUtils.CreateNode(xmlDoc, configNode, "SenderEmail", cfg.SenderEmail);
                    myUtils.CreateNode(xmlDoc, configNode, "EmailPwd", cfg.EmailPwd);
                    myUtils.CreateNode(xmlDoc, configNode, "IsSaveEmail", cfg.IsSaveEmail.ToString());
                    root.AppendChild(configNode);

                    xmlDoc.Save(configFilePath);
                }
                else
                {
                    //修改
                    xmlDoc.Load(configFilePath);

                    XmlNode root = xmlDoc.SelectSingleNode("ConfigRoot");//获取根节点

                    //获取Config 节点
                    XmlNode configNode = root.SelectSingleNode("Config");

                    //SenderEmail
                    XmlNode SenderEmail = configNode.SelectSingleNode("SenderEmail");
                    SenderEmail.InnerText = cfg.SenderEmail;

                    //RecipientName
                    XmlNode EmailPwd = configNode.SelectSingleNode("EmailPwd");
                    EmailPwd.InnerText = cfg.EmailPwd;

                    //IsSaveEmail
                    XmlNode IsSaveEmail = configNode.SelectSingleNode("IsSaveEmail");
                    IsSaveEmail.InnerText = cfg.IsSaveEmail.ToString();

                    xmlDoc.Save(configFilePath);
                }
            }
            catch (Exception e)
            {
                flag = false;
            }
            return(flag);
        }
Example #57
0
File: Map.cs Project: allfa/Reborn
    public void saveXML(string path)
    {
        XmlDocument doc = new XmlDocument ();
        XmlElement main = doc.CreateElement ("Map");
        XmlAttribute version = doc.CreateAttribute ("MapperVersion");
        version.Value = MapperVersion;
        main.Attributes.Append (version);
        XmlNode _Elements = doc.CreateNode (XmlNodeType.Element, "Elements", "");
        foreach(Element e in this.Elements ){
            XmlElement node = doc.CreateElement("Element");
            XmlAttribute x = doc.CreateAttribute("x");
            x.Value = e.x.ToString();
            XmlAttribute y = doc.CreateAttribute("y");
            y.Value = e.y.ToString();
            XmlAttribute dat = doc.CreateAttribute("data");
            dat.Value = e.data.ToString();
            node.Attributes.Append(x);
            node.Attributes.Append(y);
            node.Attributes.Append(dat);
            _Elements.AppendChild(node);
        }

        main.AppendChild (_Elements);
        doc.AppendChild (main);
        doc.Save(path);
        /*
        //doc.l
        using (var stream = new FileStream(path, FileMode.Create)) {
            using (StreamWriter writer = new StreamWriter(stream))
                writer.Write (data);
        }
        */
    }
Example #58
0
        public XmlNode RequestSnapshotData(XmlDocument nodeFactory)
        {
            m_log.Debug("[DATASNAPSHOT]: Generating object data for scene " + m_scene.RegionInfo.RegionName);

            XmlNode parent = nodeFactory.CreateNode(XmlNodeType.Element, "objectdata", "");
            XmlNode node;

            EntityBase[] entities = m_scene.Entities.GetEntities();
            foreach (EntityBase entity in entities)
            {
                // only objects, not avatars
                if (entity is SceneObjectGroup)
                {
                    SceneObjectGroup obj = (SceneObjectGroup)entity;

//                    m_log.Debug("[DATASNAPSHOT]: Found object " + obj.Name + " in scene");

                    // libomv will complain about PrimFlags.JointWheel
                    // being obsolete, so we...
                    #pragma warning disable 0612
                    if ((obj.RootPart.Flags & PrimFlags.JointWheel) == PrimFlags.JointWheel)
                    {
                        SceneObjectPart m_rootPart = obj.RootPart;

                        ILandObject land = m_scene.LandChannel.GetLandObject(m_rootPart.AbsolutePosition.X, m_rootPart.AbsolutePosition.Y);

                        XmlNode xmlobject = nodeFactory.CreateNode(XmlNodeType.Element, "object", "");
                        node           = nodeFactory.CreateNode(XmlNodeType.Element, "uuid", "");
                        node.InnerText = obj.UUID.ToString();
                        xmlobject.AppendChild(node);

                        node           = nodeFactory.CreateNode(XmlNodeType.Element, "title", "");
                        node.InnerText = m_rootPart.Name;
                        xmlobject.AppendChild(node);

                        node           = nodeFactory.CreateNode(XmlNodeType.Element, "description", "");
                        node.InnerText = m_rootPart.Description;
                        xmlobject.AppendChild(node);

                        node           = nodeFactory.CreateNode(XmlNodeType.Element, "flags", "");
                        node.InnerText = String.Format("{0:x}", (uint)m_rootPart.Flags);
                        xmlobject.AppendChild(node);

                        node           = nodeFactory.CreateNode(XmlNodeType.Element, "regionuuid", "");
                        node.InnerText = m_scene.RegionInfo.RegionSettings.RegionUUID.ToString();
                        xmlobject.AppendChild(node);

                        if (land != null && land.LandData != null)
                        {
                            node           = nodeFactory.CreateNode(XmlNodeType.Element, "parceluuid", "");
                            node.InnerText = land.LandData.GlobalID.ToString();
                            xmlobject.AppendChild(node);
                        }
                        else
                        {
                            // Something is wrong with this object. Let's not list it.
                            m_log.WarnFormat("[DATASNAPSHOT]: Bad data for object {0} ({1}) in region {2}", obj.Name, obj.UUID, m_scene.RegionInfo.RegionName);
                            continue;
                        }

                        node = nodeFactory.CreateNode(XmlNodeType.Element, "location", "");
                        Vector3 loc = obj.AbsolutePosition;
                        node.InnerText = loc.X.ToString() + "/" + loc.Y.ToString() + "/" + loc.Z.ToString();
                        xmlobject.AppendChild(node);

                        string bestImage = GuessImage(obj);
                        if (bestImage != string.Empty)
                        {
                            node           = nodeFactory.CreateNode(XmlNodeType.Element, "image", "");
                            node.InnerText = bestImage;
                            xmlobject.AppendChild(node);
                        }

                        parent.AppendChild(xmlobject);
                    }
                    #pragma warning disable 0612
                }
            }
            this.Stale = false;
            return(parent);
        }
Example #59
0
    public static XmlDocument CreateReplyDocument(int id)
    {
        XmlDocument xmlD = new XmlDocument();
        xmlD.LoadXml("<xml></xml>");

        string from = "";
        string to = "";
        string msgType = "";
        int msgCount = 1;
        string content = "";

        SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["constr"].Trim());
        SqlCommand cmd = new SqlCommand(" select * from wxreplymsg where wxreplymsg_id = " + id.ToString(), conn);
        conn.Open();
        SqlDataReader sqlDr = cmd.ExecuteReader();
        if (sqlDr.Read())
        {
            msgType = sqlDr["wxreplymsg_msgtype"].ToString().Trim();
            from = sqlDr["wxreplymsg_from"].ToString().Trim();
            to = sqlDr["wxreplymsg_to"].ToString().Trim();
            msgCount = int.Parse(sqlDr["wxreplymsg_msgcount"].ToString().Trim());

            XmlNode n = xmlD.CreateNode(XmlNodeType.Element, "FromUserName", "");
            n.InnerXml = "<![CDATA[" + from + "]]>";
            xmlD.SelectSingleNode("//xml").AppendChild(n);

            n = xmlD.CreateNode(XmlNodeType.Element, "ToUserName", "");
            n.InnerXml = "<![CDATA[" + to + "]]>";
            xmlD.SelectSingleNode("//xml").AppendChild(n);

            n = xmlD.CreateNode(XmlNodeType.Element, "CreateTime", "");
            n.InnerText = GetTimeStamp().Trim();
            xmlD.SelectSingleNode("//xml").AppendChild(n);

            n = xmlD.CreateNode(XmlNodeType.Element, "MsgType", "");
            n.InnerXml = "<![CDATA[" + msgType + "]]>";
            xmlD.SelectSingleNode("//xml").AppendChild(n);

            switch (msgType)
            {
                case "text":
                    content = sqlDr["wxreplymsg_content"].ToString().Trim();
                    n = xmlD.CreateNode(XmlNodeType.Element, "Content", "");
                    n.InnerXml = "<![CDATA[" + content + "]]>";
                    xmlD.SelectSingleNode("//xml").AppendChild(n);

                    break;
                case "news":
                    n = xmlD.CreateNode(XmlNodeType.Element, "ArticleCount", "");
                    n.InnerXml = "<![CDATA[" + sqlDr["wxreplymsg_msgcount"].ToString().Trim() + "]]>";
                    xmlD.SelectSingleNode("//xml").AppendChild(n);
                    n = xmlD.CreateNode(XmlNodeType.Element, "Articles", "");
                    n.InnerXml = sqlDr["wxreplymsg_content"].ToString().Trim();
                    xmlD.SelectSingleNode("//xml").AppendChild(n);

                    break;
                case "image":
                    n = xmlD.CreateNode(XmlNodeType.Element, "Image", "");
                    XmlNode subN = xmlD.CreateNode(XmlNodeType.Element, "MediaId", "");
                    subN.InnerXml = "<![CDATA[" + sqlDr["wxreplymsg_content"].ToString().Trim() + "]]>";
                    n.AppendChild(subN);
                    xmlD.SelectSingleNode("//xml").AppendChild(n);
                    break;
                default:

                    break;
            }
        }

        sqlDr.Close();
        conn.Close();
        cmd.Dispose();
        conn.Dispose();

        return xmlD;
    }
Example #60
0
        public List <string> SendXml_ROLL_A2(string dayplcode, string xmlFileName, NcRollA2 nc, string path)
        {
            try
            {
                string url = path + "\\NCXML";
                if (!Directory.Exists(url))
                {
                    Directory.CreateDirectory(url);
                }

                //Bll_TMP_DAYPLAN tmp_dayplan = new Bll_TMP_DAYPLAN();
                //Mod_TMP_DAYPLAN modPlan = tmp_dayplan.GetModel(dayplcode);

                XmlDocument xmlDoc = new XmlDocument();
                //创建类型声明节点
                XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", "no");
                xmlDoc.AppendChild(node);

                //创建根节点
                XmlElement root = xmlDoc.CreateElement("ufinterface");
                #region//给节点属性赋值
                root.SetAttribute("billtype", "A2");
                root.SetAttribute("filename", "" + dayplcode + ".xml");
                root.SetAttribute("isexchange", "Y");
                root.SetAttribute("operation", "req");
                root.SetAttribute("proc", "add");
                root.SetAttribute("receiver", "101");
                root.SetAttribute("replace", "Y");
                root.SetAttribute("roottag", "bill");
                root.SetAttribute("sender", "1107");
                #endregion
                xmlDoc.AppendChild(root);

                //创建子根节点
                XmlElement so_order = xmlDoc.CreateElement("bill");
                //#region//节点属性
                //so_order.SetAttribute("id", dayplcode);
                //#endregiond
                root.AppendChild(so_order);

                XmlNode head = xmlDoc.CreateNode(XmlNodeType.Element, "bill_head", null);

                #region                                                //表头_order_head

                CreateNode(xmlDoc, head, "scddh", "");                 //生产订单号
                CreateNode(xmlDoc, head, "pk_poid", "");               //计划订单主键
                CreateNode(xmlDoc, head, "jhddh", "");                 //计划订单号
                CreateNode(xmlDoc, head, "wlbmid", nc.wlbmid);         //物料编码ID
                CreateNode(xmlDoc, head, "pk_produce", nc.pk_produce); //物料PK
                CreateNode(xmlDoc, head, "invcode", nc.invcode);
                CreateNode(xmlDoc, head, "invname", "");
                CreateNode(xmlDoc, head, "pch", nc.pch);                              //批次号
                CreateNode(xmlDoc, head, "scbmid", nc.scbmid);                        //生产部门ID
                CreateNode(xmlDoc, head, "gzzxid", nc.gzzxid);                        //工作中心ID
                CreateNode(xmlDoc, head, "gzzxbm", "");                               //工作中心编码ID
                CreateNode(xmlDoc, head, "ksid", "");                                 //客商ID
                CreateNode(xmlDoc, head, "memo", "");                                 //备注
                CreateNode(xmlDoc, head, "sfjj", "");                                 //是否加急
                CreateNode(xmlDoc, head, "yxj", "");
                CreateNode(xmlDoc, head, "bcid", nc.bcid);                            //班次ID
                CreateNode(xmlDoc, head, "bzid", nc.bzid);                            //班组
                CreateNode(xmlDoc, head, "jhkgrq", nc.jhkgrq.ToString("yyyy-MM-dd")); //计划开工日期
                CreateNode(xmlDoc, head, "jhwgrq", nc.jhwgrq.ToString("yyyy-MM-dd")); //计划完工日期
                CreateNode(xmlDoc, head, "jhkssj", nc.jhkssj.ToString("HH:mm:ss"));   //计划开始时间
                CreateNode(xmlDoc, head, "jhjssj", nc.jhjssj.ToString("HH:mm:ss"));   //计划结束时间
                CreateNode(xmlDoc, head, "sjkgrq", nc.sjkgrq.ToString("yyyy-MM-dd")); //实际开工日期
                CreateNode(xmlDoc, head, "sjwgrq", nc.sjwgrq.ToString("yyyy-MM-dd")); //实际完工日期
                CreateNode(xmlDoc, head, "sjkssj", nc.sjkssj.ToString("HH:mm:ss"));   //实际开始时间
                CreateNode(xmlDoc, head, "sjjssj", nc.sjjssj.ToString("HH:mm:ss"));   //实际结束时间
                CreateNode(xmlDoc, head, "jhwgsl", nc.jhwgsl);                        //计划完工数量
                CreateNode(xmlDoc, head, "fjhsl", nc.fjhsl);                          //辅计量数量
                CreateNode(xmlDoc, head, "jldwid", nc.jldwid);                        //计量单位ID
                CreateNode(xmlDoc, head, "fjlid", nc.fjlid);
                CreateNode(xmlDoc, head, "sjwgsl", "");                               //实际完工数量
                CreateNode(xmlDoc, head, "fwcsl", "");
                CreateNode(xmlDoc, head, "zdy1", "");                                 //自定义项1
                CreateNode(xmlDoc, head, "zdy2", "");                                 //自定义项2
                CreateNode(xmlDoc, head, "zdy3", "");                                 //自定义项3
                CreateNode(xmlDoc, head, "zdy4", "");                                 //自定义项4
                CreateNode(xmlDoc, head, "zdy5", "");                                 //自定义项5
                CreateNode(xmlDoc, head, "freeitemvalue1", nc.freeitemvalue1);
                CreateNode(xmlDoc, head, "freeitemvalue2", nc.freeitemvalue2);
                CreateNode(xmlDoc, head, "freeitemvalue3", nc.freeitemvalue3);
                CreateNode(xmlDoc, head, "freeitemvalue4", "");
                CreateNode(xmlDoc, head, "freeitemvalue5", nc.freeitemvalue5); //PCI计划订单主键
                CreateNode(xmlDoc, head, "pk_corp", "1001");                   //公司编码
                CreateNode(xmlDoc, head, "gcbm", "1001NC10000000000669");      //工厂
                CreateNode(xmlDoc, head, "zdrid", nc.zdrid);                   //制单人 用户编码
                CreateNode(xmlDoc, head, "pk_moid", "");                       //生产定单ID

                #endregion

                so_order.AppendChild(head);
                xmlDoc.Save(url + "\\" + xmlFileName);
                var             result = dalSendNC.SendXML(url + "\\" + xmlFileName);
                Mod_TB_NCIF_LOG log    = new Mod_TB_NCIF_LOG();
                log.C_TYPE            = "A2";
                log.C_RESULT          = result[0];
                log.C_REMARK          = result[1];
                log.C_RELATIONSHIP_ID = nc.pch;
                dal_TB_NCIF_LOG.Add(log);
                return(result);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }