public System.Xml.XmlDocument CreateXmlDocument()
 {
     System.Xml.XmlDocument document = new System.Xml.XmlDocument();
     document.AppendChild(document.CreateXmlDeclaration("1.0", "utf-8", "yes"));
     document.AppendChild(CreateXmlElement(document));
     return(document);
 }
Esempio n. 2
0
 /// <summary>prepare internal XmlDocument with basic Document-Root</summary>
 private void _initializeXML()
 {
     System.Xml.XmlDocument    _tmpdoc  = new System.Xml.XmlDocument();
     System.Xml.XmlDeclaration _tmpdec  = _tmpdoc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
     System.Xml.XmlElement     _tmproot = _tmpdoc.CreateElement("UserSettings");
     _tmpdoc.AppendChild(_tmpdec);
     _tmpdoc.AppendChild(_tmproot);
     _intXml = _tmpdoc;
 }
Esempio n. 3
0
File: Xml.cs Progetto: sopindm/bjeb
            public Xml(string rootName)
            {
                _xml = new System.Xml.XmlDocument();

                System.Xml.XmlDeclaration dec = _xml.CreateXmlDeclaration("1.0", null, null);
                _xml.AppendChild(dec);

                _root = _xml.CreateElement(rootName);
                _xml.AppendChild(_root);
            }
Esempio n. 4
0
File: Xml.cs Progetto: sopindm/bjeb
            public Xml(string rootName)
            {
                _xml = new System.Xml.XmlDocument();

                System.Xml.XmlDeclaration dec = _xml.CreateXmlDeclaration("1.0", null, null);
                _xml.AppendChild(dec);

                _root = _xml.CreateElement(rootName);
                _xml.AppendChild(_root);
            }
Esempio n. 5
0
        /// <summary>
        /// 创建一个新文档
        /// </summary>
        /// <returns></returns>
        public static System.Xml.XmlDocument NewDocment()
        {
            var doc = new System.Xml.XmlDocument();

            doc.AppendChild(doc.CreateProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\""));
            return(doc);
        }
Esempio n. 6
0
        public void WritePictureXMLFile()
        {
            GlobalDataStore.Logger.Debug("Updating Pictures.xml ...");
            List <LabelX.Toolbox.LabelXItem> items        = new List <LabelX.Toolbox.LabelXItem>();
            DirectoryInfo PicturesRootFolderDirectoryInfo = new DirectoryInfo(PicturesRootFolder);

            LabelX.Toolbox.Toolbox.GetPicturesFromFolderTree(PicturesRootFolderDirectoryInfo.FullName, ref items);

            //items = alle ingelezen pictures. Nu gaan wegschrijven.
            System.Xml.XmlDocument doc  = new System.Xml.XmlDocument();
            System.Xml.XmlElement  root = doc.CreateElement("LabelXItems");

            foreach (LabelX.Toolbox.LabelXItem item in items)
            {
                System.Xml.XmlElement itemXML = doc.CreateElement("item");
                itemXML.SetAttribute("name", item.Name);
                itemXML.SetAttribute("hash", item.Hash);

                root.AppendChild(itemXML);
            }

            doc.AppendChild(root);

            MemoryStream ms = new MemoryStream();

            System.Xml.XmlTextWriter tw = new System.Xml.XmlTextWriter(ms, Encoding.UTF8);
            tw.Formatting = System.Xml.Formatting.Indented;
            doc.WriteContentTo(tw);
            doc.Save(PicturesRootFolder + "pictures.xml");


            tw.Close();
        }
Esempio n. 7
0
        public string ToXml()
        {
            StringBuilder sbXml = new StringBuilder();

            System.Xml.XmlDocument document = new System.Xml.XmlDocument();
            System.Xml.XmlNode     root     = document.CreateElement("Condictions");

            foreach (QueryItem qc in queryItems)
            {
                System.Xml.XmlNode node = document.CreateElement("Condiction");

                System.Xml.XmlAttribute attributeName = document.CreateAttribute("Name");
                attributeName.Value = qc.Name;

                System.Xml.XmlAttribute attributeFields = document.CreateAttribute("MappingField");
                attributeFields.Value = qc.MappingFeild;

                System.Xml.XmlAttribute attributeDataType = document.CreateAttribute("DataType");
                attributeDataType.Value = qc.DataType.ToString();

                node.Attributes.Append(attributeName);
                node.Attributes.Append(attributeFields);
                node.Attributes.Append(attributeDataType);

                node.InnerText = qc.Value == null ? "" : qc.Value.ToString();

                root.AppendChild(node);
            }
            document.AppendChild(root);
            return(document.InnerXml.ToString());
        }
Esempio n. 8
0
 private static void CreateUniqueIdsContainer(string filepath)
 {
     System.Xml.XmlDocument doc  = new System.Xml.XmlDocument();
     System.Xml.XmlElement  elem = doc.CreateElement("ids");
     doc.AppendChild(elem);
     doc.Save(filepath);
 }
Esempio n. 9
0
        public void SaveGroups(List <RomGroup> groups)
        {
            if (groups == null)
            {
                return;
            }

            System.Xml.XmlDocument doc      = new System.Xml.XmlDocument();
            System.Xml.XmlElement  groupsEl = doc.CreateElement("Groups");
            doc.AppendChild(groupsEl);
            foreach (RomGroup group in groups)
            {
                groupsEl.AppendChild(group.GetXML(doc));
            }

            string xmlPath = System.IO.Path.Combine(MediaPortal.Configuration.Config.GetFolder(MediaPortal.Configuration.Config.Dir.Config), "Emulators2Groups.xml");

            try
            {
                doc.Save(xmlPath);
            }
            catch (Exception ex)
            {
                Logger.LogError("Unable to save Group xml to location '{0}' - {1}", xmlPath, ex.Message);
            }
        }
Esempio n. 10
0
        public System.Xml.XmlDocument getClaims()
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

            System.Xml.XmlElement claims = doc.CreateElement("claims");

            foreach(TurfWarsGame.Claim c in TurfWars.Global.game.getClaims())
            {
                System.Xml.XmlElement claim = doc.CreateElement("claim");

                System.Xml.XmlElement owners = doc.CreateElement("owners");
                foreach (string u in c.getOwners().Keys)
                {
                    System.Xml.XmlElement owner = doc.CreateElement("owner");
                    owner.SetAttribute("name", u);
                    owner.SetAttribute("share", c.getOwners()[u].ToString());
                    owners.AppendChild(owner);
                }

                System.Xml.XmlElement tile = doc.CreateElement("tile");
                tile.SetAttribute("north",c.box.north.ToString());
                tile.SetAttribute("south",c.box.south.ToString());
                tile.SetAttribute("west", c.box.west.ToString());
                tile.SetAttribute("east", c.box.east.ToString());
                claim.AppendChild(owners);
                claim.AppendChild(tile);
                claims.AppendChild(claim);
            }

            doc.AppendChild(claims);
            return doc;
        }
Esempio n. 11
0
 public static System.IO.Stream GetFileListXML(string startDir)
 {
     System.Xml.XmlDocument  xmlDoc = new System.Xml.XmlDocument();
     System.Xml.XmlNode      node;
     System.IO.DirectoryInfo dir    = new System.IO.DirectoryInfo(startDir);
     System.IO.MemoryStream  stream = new System.IO.MemoryStream();
     xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "yes"));
     //node = xmlDoc.CreateElement( "fil:FileLists", "http://kadgen/filelist.xsd" )
     //xmlDoc.AppendChild( node )
     node = xmlDoc.AppendChild(xmlHelpers.NewElement("fil", "http://kadgen/filelist.xsd", xmlDoc, "FileLists"));
     node = node.AppendChild(xmlHelpers.NewElement("http://kadgen/filelist.xsd", xmlDoc, "fil:FileList"));
     node.Attributes.Append(xmlHelpers.NewAttribute(xmlDoc, "StartDir", startDir));
     node.AppendChild(FileListXML(dir, xmlDoc));
     xmlDoc.Save(stream);
     return(stream);
 }
Esempio n. 12
0
        /// <summary>
        /// Virtual method - override to define appropriate save to XML semantics for
        /// the subclass. Note: Call base class method from override to correctly
        /// save common elements.
        /// </summary>
        public virtual System.Xml.XmlDocument ToXml()
        {
            DateTime Start = Debug.ExecStart;

            try
            {
                System.Xml.XmlDocument xmlData = new System.Xml.XmlDocument();

                System.Xml.XmlElement xmlRoot = xmlData.CreateElement(xmlNodeInstance);
                xmlRoot.SetAttribute(xmlAttrName, Name);
                xmlData.AppendChild(xmlRoot);

                System.Xml.XmlElement xmlLogFile = xmlData.CreateElement(xmlNodeFAHLog);
                xmlLogFile.InnerText = this._RemoteFAHLogFilename;
                xmlRoot.AppendChild(xmlLogFile);

                System.Xml.XmlElement xmlUIFile = xmlData.CreateElement(xmlNodeUnitInfo);
                xmlUIFile.InnerText = this._RemoteUnitInfoFilename;
                xmlRoot.AppendChild(xmlUIFile);

                ClassLogger.Log(LogLevel.Trace, String.Format("{0} Execution Time: {1}", Debug.FunctionName, Debug.GetExecTime(Start)), "");
                return(xmlData);
            }
            catch (Exception Ex)
            {
                ClassLogger.LogException(LogLevel.Error, String.Format("{0} threw exception {1}.", Debug.FunctionName, Ex.Message), null);
            }
            return(null);
        }
Esempio n. 13
0
        /// <summary>
        /// Write registry to file.
        /// </summary>
        public void write()
        {
            try
            {
                lock (_mutex)
                {
                    System.Xml.XmlDocument doc  = new System.Xml.XmlDocument();
                    System.Xml.XmlElement  root = doc.CreateElement("registry");
                    doc.AppendChild(root);

                    foreach (string section in _sections.Keys)
                    {
                        Section hash = this.getSectionHash(section);
                        System.Xml.XmlElement element = doc.CreateElement(section);
                        root.AppendChild(element);
                        foreach (string key in hash.Keys)
                        {
                            string value = hash[key].ToString();
                            System.Xml.XmlElement child = doc.CreateElement(key);
                            child.InnerText = value;
                            element.AppendChild(child);
                        }
                    }

                    doc.Save(this._file());
                }
            }
            catch (System.Exception e)
            {
                System.Console.WriteLine("Error {0}: {1}", 2112056395, e.Message);
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Save this catalog to a file for the next time where WPP start.
        /// </summary>
        internal void Save(string baseFolder)
        {
            Logger.EnteringMethod(baseFolder);

            System.Xml.XmlDocument xmlDoc      = new System.Xml.XmlDocument();
            System.Xml.XmlElement  rootElement = (System.Xml.XmlElement)xmlDoc.AppendChild(xmlDoc.CreateElement("CatalogSubscription"));

            rootElement.AppendChild(xmlDoc.CreateElement("IsActive")).InnerText         = IsActive.ToString();
            rootElement.AppendChild(xmlDoc.CreateElement("Address")).InnerText          = Address;
            rootElement.AppendChild(xmlDoc.CreateElement("CheckEvery")).InnerText       = CheckEvery.ToString();
            rootElement.AppendChild(xmlDoc.CreateElement("Unit")).InnerText             = Unit.ToString();
            rootElement.AppendChild(xmlDoc.CreateElement("LastCheck")).InnerText        = LastCheckDate.ToString();
            rootElement.AppendChild(xmlDoc.CreateElement("LastCheckResult")).InnerText  = LastCheckResult.ToString();
            rootElement.AppendChild(xmlDoc.CreateElement("CatalogName")).InnerText      = CatalogName;
            rootElement.AppendChild(xmlDoc.CreateElement("Hash")).InnerText             = Hash;
            rootElement.AppendChild(xmlDoc.CreateElement("LastDownloadDate")).InnerText = LastDownloadDate.ToString();

            FileInfo catalogFile = new FileInfo(baseFolder + "\\" + this.CatalogName + ".xml");

            if (!catalogFile.Directory.Exists)
            {
                catalogFile.Directory.Create();
            }

            try
            {
                xmlDoc.Save(catalogFile.FullName);
            }
            catch (Exception ex)
            {
                Logger.Write("**** Error when saving " + catalogFile.FullName + ".\r\n" + ex.Message);
            }
        }
        private void SaveToXml(ref string ProductsXml, ref string FilterXml)
        {
            System.Xml.XmlDocument doc    = null;
            System.Xml.XmlElement  rootEl = null;

            // products
            doc    = new System.Xml.XmlDocument();
            rootEl = doc.CreateElement("PRODUCTS");
            doc.AppendChild(rootEl);
            foreach (string serNo in this._productsSerNoList)
            {
                System.Xml.XmlElement childEl = doc.CreateElement("PR");
                childEl.SetAttribute("SN", serNo);
                rootEl.AppendChild(childEl);
            }
            ProductsXml = doc.InnerXml;

            // filter
            doc    = new System.Xml.XmlDocument();
            rootEl = doc.CreateElement("FILTER");
            doc.AppendChild(rootEl);
            for (int i = 0; i < this._filterList.Count; i++)
            {
                string colName = this._filterList.Keys[i];
                string val     = this._filterList[i];

                System.Xml.XmlElement childEl = doc.CreateElement("COL");
                childEl.SetAttribute("N", colName);
                childEl.SetAttribute("V", val);
                rootEl.AppendChild(childEl);
            }
            FilterXml = doc.InnerXml;
        }
Esempio n. 16
0
        CreateSchemePlist(
            Target target)
        {
            var doc = new System.Xml.XmlDocument();

            var schemeEl = doc.CreateElement("Scheme");

            doc.AppendChild(schemeEl);

            this.CreateBuildActions(doc, schemeEl, target);
            this.CreateTestActions(doc, schemeEl, target);
            this.CreateLaunchActions(doc, schemeEl, target);

            var profileActionEl = doc.CreateElement("ProfileAction");

            schemeEl.AppendChild(profileActionEl);
            profileActionEl.SetAttribute("buildConfiguration", target.ConfigurationList.ElementAt(0).Name);

            var analyzeActionEl = doc.CreateElement("AnalyzeAction");

            schemeEl.AppendChild(analyzeActionEl);
            analyzeActionEl.SetAttribute("buildConfiguration", target.ConfigurationList.ElementAt(0).Name);

            var archiveActionEl = doc.CreateElement("ArchiveAction");

            schemeEl.AppendChild(archiveActionEl);
            archiveActionEl.SetAttribute("buildConfiguration", target.ConfigurationList.ElementAt(0).Name);

            return(doc);
        }
Esempio n. 17
0
        public void Persist()
        {
            var doc  = new System.Xml.XmlDocument();
            var root = doc.CreateElement(nameof(Persons));

            doc.AppendChild(root);

            foreach (var p in Persons)
            {
                var e = doc.CreateElement(nameof(Person));
                var firstNameAttribute  = doc.CreateAttribute(nameof(Person.FirstName));
                var suretNameAttribute  = doc.CreateAttribute(nameof(Person.SureName));
                var streetNameAttribute = doc.CreateAttribute(nameof(Person.Street));
                var cityNameAttribute   = doc.CreateAttribute(nameof(Person.City));

                firstNameAttribute.Value  = p.FirstName;
                suretNameAttribute.Value  = p.SureName;
                streetNameAttribute.Value = p.Street;
                cityNameAttribute.Value   = p.City;

                e.Attributes.Append(firstNameAttribute);
                e.Attributes.Append(suretNameAttribute);
                e.Attributes.Append(streetNameAttribute);
                e.Attributes.Append(cityNameAttribute);
                root.AppendChild(e);
            }

            using (var stream = this.databaseFile.Open(FileMode.Create, FileAccess.Write, FileShare.None))
                doc.Save(stream);
        }
Esempio n. 18
0
        private static double MSXMLapproach(int numberOfElements, int numerOfAttributes, List <string> elemetNames, List <string> attributeNames, List <string> attributeValues)
        {
            DateTime now = DateTime.Now;

            System.Xml.XmlDocument    doc    = new System.Xml.XmlDocument();
            System.Xml.XmlDeclaration header = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
            System.Xml.XmlElement     root   = doc.DocumentElement;
            doc.InsertBefore(header, root);
            System.Xml.XmlElement rootElement = doc.CreateElement(string.Empty, "root", string.Empty);
            doc.AppendChild(rootElement);
            for (int i = 0; i < numberOfElements; i++)
            {
                System.Xml.XmlElement element = doc.CreateElement(string.Empty, elemetNames[i], string.Empty);
                for (int j = 0; j < numerOfAttributes; j++)
                {
                    //element.SetAttribute(attributeNameTemplate + j, attributeValueTemplate);
                    element.SetAttribute(attributeNames[j], attributeValues[j]);
                }
                rootElement.AppendChild(element);
            }
            string   output = doc.OuterXml;
            TimeSpan t      = DateTime.Now - now;

            return(t.TotalMilliseconds);
        }
Esempio n. 19
0
        public string SystemXml()
        {
            var doc       = new SystemXmlDocument();
            var subChilds = new List <SystemXmlElement> {
                doc.CreateElement("subChild1"), doc.CreateElement("subChild2")
            };
            var attr2 = doc.CreateAttribute("attr2");

            attr2.Value = "value2";
            subChilds[0].Attributes.Append(attr2);
            var attr3 = doc.CreateAttribute("attr3");

            attr3.Value = "value3";
            subChilds[0].Attributes.Append(attr3);
            var child = doc.CreateElement("child0");
            var attr1 = doc.CreateAttribute("attr1");

            attr1.Value = "value1";
            child.Attributes.Append(attr1);
            var root = doc.CreateElement("root");

            child.AppendChild(subChilds[0]);
            child.AppendChild(subChilds[1]);
            root.AppendChild(child);
            doc.AppendChild(root);
            return(doc.InnerXml);
        }
Esempio n. 20
0
        public static void SaveWindowConfig(string path)
        {
            var size = Manager.NativeManager.GetSize();

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

            System.Xml.XmlElement project_root = doc.CreateElement("Root");
            project_root.AppendChild(doc.CreateTextElement("WindowWidth", size.X.ToString()));
            project_root.AppendChild(doc.CreateTextElement("WindowHeight", size.Y.ToString()));

            System.Xml.XmlElement docks = doc.CreateElement("Docks");

            foreach (var panel in panels)
            {
                if (panel != null)
                {
                    docks.AppendChild(doc.CreateTextElement(panel.GetType().ToString(), "Open"));
                }
            }

            project_root.AppendChild(docks);

            doc.AppendChild(project_root);

            var dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);

            doc.InsertBefore(dec, project_root);
            doc.Save(path);
        }
Esempio n. 21
0
        public static System.Xml.XmlNode SetNode(System.Xml.XmlDocument parentNode, string nodeName, string nodeValue = "")
        {
            System.Xml.XmlDocument xmlDoc = default(System.Xml.XmlDocument);
            xmlDoc = parentNode;


            // search node
            System.Xml.XmlNode xmlNewElem = RoutinesLibrary.Data.Xml.XMLUtils.GetFirstChild(parentNode, nodeName);
            if (xmlNewElem != null)
            {
                if (nodeValue != "")
                {
                    xmlNewElem.InnerText = nodeValue;
                }
            }
            else
            {
                // if not exists, create and append
                xmlNewElem = xmlDoc.CreateElement(nodeName);
                if (nodeValue != null)
                {
                    xmlNewElem.InnerText = nodeValue;
                }
                xmlDoc.AppendChild(xmlNewElem);
            }

            return(xmlNewElem);
        }
Esempio n. 22
0
        public System.Xml.XmlElement GenerateDefinitionXmlElement(EntitiesGenerator.Definitions.DataTable table)
        {
            System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument();
            System.Xml.XmlElement definitionElement = xmlDocument.CreateElement("Definition");
            System.Xml.XmlElement xmlElement = xmlDocument.CreateElement("DataTable");

            System.Xml.XmlAttribute tableNameXmlAttribute = xmlDocument.CreateAttribute("TableName");
            tableNameXmlAttribute.Value = table.TableName.Trim();
            xmlElement.Attributes.Append(tableNameXmlAttribute);

            System.Xml.XmlAttribute sourceNameXmlAttribute = xmlDocument.CreateAttribute("SourceName");
            sourceNameXmlAttribute.Value = table.SourceName.Trim();
            xmlElement.Attributes.Append(sourceNameXmlAttribute);

            foreach (EntitiesGenerator.Definitions.DataColumn column in table.Columns)
            {
                System.Xml.XmlElement dataColumnXmlElement = xmlDocument.CreateElement("DataColumn");

                System.Xml.XmlAttribute dataColumnColumnNameXmlAttribute = xmlDocument.CreateAttribute("ColumnName");
                dataColumnColumnNameXmlAttribute.Value = column.ColumnName.Trim();
                dataColumnXmlElement.Attributes.Append(dataColumnColumnNameXmlAttribute);

                System.Xml.XmlAttribute dataColumnSourceNameXmlAttribute = xmlDocument.CreateAttribute("SourceName");
                dataColumnSourceNameXmlAttribute.Value = column.SourceName.Trim();
                dataColumnXmlElement.Attributes.Append(dataColumnSourceNameXmlAttribute);

                System.Xml.XmlAttribute dataColumnDataTypeXmlAttribute = xmlDocument.CreateAttribute("DataType");
                dataColumnDataTypeXmlAttribute.Value = column.DataType.Trim();
                dataColumnXmlElement.Attributes.Append(dataColumnDataTypeXmlAttribute);

                if (column.PrimaryKey)
                {
                    System.Xml.XmlAttribute dataColumnPrimaryKeyXmlAttribute = xmlDocument.CreateAttribute("PrimaryKey");
                    dataColumnPrimaryKeyXmlAttribute.Value = column.PrimaryKey ? "true" : "false";
                    dataColumnXmlElement.Attributes.Append(dataColumnPrimaryKeyXmlAttribute);
                }

                if (!column.AllowDBNull)
                {
                    System.Xml.XmlAttribute dataColumnAllowDBNullXmlAttribute = xmlDocument.CreateAttribute("AllowDBNull");
                    dataColumnAllowDBNullXmlAttribute.Value = column.AllowDBNull ? "true" : "false";
                    dataColumnXmlElement.Attributes.Append(dataColumnAllowDBNullXmlAttribute);
                }

                if (column.AutoIncrement)
                {
                    System.Xml.XmlAttribute dataColumnAutoIncrementXmlAttribute = xmlDocument.CreateAttribute("AutoIncrement");
                    dataColumnAutoIncrementXmlAttribute.Value = column.AutoIncrement ? "true" : "false";
                    dataColumnXmlElement.Attributes.Append(dataColumnAutoIncrementXmlAttribute);
                }

                // TODO: caption.

                xmlElement.AppendChild(dataColumnXmlElement);
            }
            definitionElement.AppendChild(xmlElement);
            xmlDocument.AppendChild(definitionElement);
            return xmlDocument.DocumentElement;
        }
Esempio n. 23
0
 // TODO: This is not really an extension, more a helper and so should be moved...
 public static System.Xml.XmlElement CreateXmlElement(string tag, string content)
 {
     System.Xml.XmlDocument doc     = new System.Xml.XmlDocument();
     System.Xml.XmlElement  element = doc.CreateElement(tag);
     doc.AppendChild(element);
     element.AppendChild(doc.CreateTextNode(content));
     return(doc.DocumentElement);
 }
 /// <summary>
 /// В строку
 /// </summary>
 /// <returns></returns>
 public override string ToString()
 {
     System.Xml.XmlDocument doc  = new System.Xml.XmlDocument();
     System.Xml.XmlElement  elem = ToXMLElement(doc, this.function);
     elem.SetAttribute("___Name", Name);
     doc.AppendChild(elem);
     return(doc.OuterXml);
 }
Esempio n. 25
0
        CreateRootProject(
            System.Xml.XmlDocument document)
        {
            var project = document.CreateVSElement("Project");

            document.AppendChild(project);
            return(project);
        }
Esempio n. 26
0
 /// <summary>
 /// 保存文档
 /// </summary>
 /// <param name="filename">文件名</param>
 public void Save(string filename)
 {
     System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
     doc.AppendChild(doc.CreateElement("CHMDocument"));
     ToXML(doc.DocumentElement);
     doc.Save(filename);
     _fileName = filename;
 }
Esempio n. 27
0
 public System.Xml.XmlDocument CreateXmlDocument()
 {
     System.Xml.XmlDocument doc  = new System.Xml.XmlDocument();
     System.Xml.XmlNode     node = doc.CreateElement("root");
     doc.AppendChild(node);
     this.AddToXml(node);
     return(doc);
 }
Esempio n. 28
0
 // TODO: This is not really an extension, more a helper and so should be moved...
 public static System.Xml.XmlElement CreateXmlElement( string tag, string content )
 {
     System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
     System.Xml.XmlElement element = doc.CreateElement(tag);
     doc.AppendChild(element);
     element.AppendChild(doc.CreateTextNode(content));
     return doc.DocumentElement;
 }
Esempio n. 29
0
        private void Save(int objId, int tryCount)
        {
            if (this.LogId > 0)
            {
                throw new Exception("日志 " + this.LogId + " 已保存过,不能再次保存");
            }

            DateTime dtmLodId;

            lock (st_LogIdLock)
            {
                dtmLodId = st_LogIdLock.GetLogId();
            }

            string strTableName = Tables.Log.GetTableName(dtmLodId);

            Database.DbConnection dbConnection = this.Application.GetDbConnection();

            if (dbConnection.TableIsExist(strTableName) == false)
            {
                dbConnection.CreateTable(typeof(Tables.Log), strTableName);
            }

            string strConfig = null;

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

            System.Xml.XmlNode xnLogConfig = this.GetLogConfig(xmlDoc);
            if (xnLogConfig != null)
            {
                xmlDoc.AppendChild(xnLogConfig);
                strConfig = xmlDoc.OuterXml;
            }

            try
            {
                string strSql = dtmLodId.Ticks.ToString() + "," + Function.SqlStr(this.GetType().FullName, 250) + "," + objId + "," + Function.SqlStr(strConfig);
                strSql = "INSERT INTO " + strTableName + " (" + Tables.Log.LogId + "," + Tables.Log.LogType + "," + Tables.Log.ObjId + "," + Tables.Log.XMLConfig + ") VALUES (" + strSql + ")";
                dbConnection.ExecuteNonQuery(strSql);

                this.m_LogId = dtmLodId.Ticks;
            }
            catch
            {
                if (tryCount > 3)
                {
                    throw new Exception("保存日志 " + this.GetType().FullName + " 时发生错误,已重试3次。");
                }
                else
                {
                    this.Save(objId, tryCount + 1);
                }
            }
            finally
            {
                dbConnection.Close();
            }
        }
Esempio n. 30
0
        public static string ReplyImage(ReplyImageModel entity)
        {
            if (null != entity && !string.IsNullOrWhiteSpace(entity.ToUserName) && null != entity.Image)
            {
                string xmlString = string.Empty;
                //var s1 = XmlHelper.Serialize(entity);
                #region xmlString
                System.Xml.XmlDocument     xmlDoc = new System.Xml.XmlDocument();
                System.Xml.XmlNode         rootNode;
                System.Xml.XmlElement      ele;
                System.Xml.XmlCDataSection cdata;

                #region xml
                rootNode = xmlDoc.CreateNode(System.Xml.XmlNodeType.Element, "xml", null);

                ele   = xmlDoc.CreateElement(nameof(entity.ToUserName));
                cdata = xmlDoc.CreateCDataSection(entity.ToUserName);
                ele.AppendChild(cdata);
                rootNode.AppendChild(ele);

                ele   = xmlDoc.CreateElement(nameof(entity.FromUserName));
                cdata = xmlDoc.CreateCDataSection(entity.FromUserName);
                ele.AppendChild(cdata);
                rootNode.AppendChild(ele);

                ele          = xmlDoc.CreateElement(nameof(entity.CreateTime));
                ele.InnerXml = entity.CreateTime.ToString();
                rootNode.AppendChild(ele);

                ele   = xmlDoc.CreateElement(nameof(entity.MsgType));
                cdata = xmlDoc.CreateCDataSection(entity.MsgType);
                ele.AppendChild(cdata);
                rootNode.AppendChild(ele);
                #endregion

                System.Xml.XmlNode nodeImage;
                nodeImage = xmlDoc.CreateNode(System.Xml.XmlNodeType.Element, nameof(entity.Image), null);
                if (null != entity.Image)
                {
                    ele   = xmlDoc.CreateElement(nameof(entity.Image.MediaId));
                    cdata = xmlDoc.CreateCDataSection(entity.Image.MediaId);
                    ele.AppendChild(cdata);
                    nodeImage.AppendChild(ele);
                }

                rootNode.AppendChild(nodeImage);
                xmlDoc.AppendChild(rootNode);

                xmlString = xmlDoc.OuterXml;
                #endregion

                if (!string.IsNullOrWhiteSpace(xmlString))
                {
                    return(xmlString);
                }
            }
            return(ReplyEmpty());
        }
Esempio n. 31
0
        public static System.Xml.XmlDocument CreateNewDoc()
        {
            System.Xml.XmlDocument    xmlDoc         = new System.Xml.XmlDocument();
            System.Xml.XmlDeclaration xmlDeclaration = default(System.Xml.XmlDeclaration);
            xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
            xmlDoc.AppendChild(xmlDeclaration);

            return(xmlDoc);
        }
Esempio n. 32
0
        public Skin GetSkin()
        {
            var resources = new Dictionary <string, System.IO.MemoryStream>();

            var doc    = new System.Xml.XmlDocument();
            var declar = doc.CreateXmlDeclaration("1.0", System.Text.Encoding.UTF8.WebName, null);

            doc.AppendChild(declar);

            var root = doc.CreateElement("Theme");

            root.SetAttribute("version", "1.0");
            root.AppendChild(this.ContainerControl.GetXmlElement(doc, resources));

            doc.AppendChild(root);

            return(new Skin(doc, resources));
        }
Esempio n. 33
0
        /// <summary>
        /// Get the xml for this list of datasets
        /// </summary>\
        /// <param name="oDapCommand"></param>
        /// <param name="oDatasets"></param>
        /// <param name="oSelectedDatasets"></param>
        /// <returns></returns>
        public static System.Xml.XmlDocument GetXml(Command oDapCommand, System.Collections.SortedList oDatasets, System.Collections.ArrayList oSelectedDatasets)
        {
            System.Xml.XmlDocument oOutputXml = new System.Xml.XmlDocument();

            oOutputXml.AppendChild(oOutputXml.CreateXmlDeclaration("1.0", "UTF-8", string.Empty));

            System.Xml.XmlElement oGeosoftXml = oOutputXml.CreateElement("geosoft_xml");
            oOutputXml.AppendChild(oGeosoftXml);

            foreach (string strKey in oSelectedDatasets)
            {
                Dap.Common.DataSet oDataset = (Dap.Common.DataSet)oDatasets[strKey];

                if (oDataset != null)
                    OutputDataset(oDapCommand, oGeosoftXml, oDataset);
            }
            return oOutputXml;
        }
        /// <include file='doc\IFormatter.uex' path='docs/doc[@for="IFormatter.Serialize"]/*' />
        public void Serialize(Stream serializationStream, Object graph)
        {

            AccuDataObjectFormatter = new System.Xml.XmlDocument();
            System.Xml.XmlDeclaration Declaration = AccuDataObjectFormatter.CreateXmlDeclaration("1.0", "", "");
            System.Xml.XmlElement Element = AccuDataObjectFormatter.CreateElement("NewDataSet");

            if (graph != null)
            {
                if (graph.GetType().Equals(typeof(System.String)))
                {
                    Element.InnerText = graph.ToString();
                }
                else if (graph.GetType().GetInterface("IEnumerable") != null)
                {
                    Serialize(Element, graph);
                }
                else if (graph.GetType().IsArray)
                {
                    Serialize(Element, graph);
                }
                else if (graph.GetType().IsClass)
                {
                    Serialize(Element, graph);
                }
                else if (graph.GetType().IsPrimitive)
                {
                    Element.InnerText = graph.ToString();
                }
                else if (graph.GetType().IsValueType)
                {
                    System.Xml.XmlElement ValueType = AccuDataObjectFormatter.CreateElement(graph.GetType().Name);
                    Element.AppendChild(ValueType);
                }

            }

            AccuDataObjectFormatter.AppendChild(Declaration);
            AccuDataObjectFormatter.AppendChild(Element);
            System.IO.StreamWriter writer = new StreamWriter(serializationStream);
            writer.Write(AccuDataObjectFormatter.OuterXml);
            writer.Flush();
            writer.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
        }
Esempio n. 35
0
        public void Save(string path)
        {
            System.Xml.XmlDocument doc          = new System.Xml.XmlDocument();
            System.Xml.XmlElement  project_root = doc.CreateElement("Root");

            {
                var e = doc.CreateElement("Target");
                e.AppendChild(doc.CreateTextNode(Target.ToString()));
                project_root.AppendChild(e);
            }

            {
                var e = doc.CreateElement("Port");
                e.AppendChild(doc.CreateTextNode(Port.ToString()));
                project_root.AppendChild(e);
            }

            {
                var e = doc.CreateElement("AutoConnect");
                e.AppendChild(doc.CreateTextNode(AutoConnect.ToString()));
                project_root.AppendChild(e);
            }

            {
                var e = doc.CreateElement("SendOnLoad");
                e.AppendChild(doc.CreateTextNode(SendOnLoad.ToString()));
                project_root.AppendChild(e);
            }

            {
                var e = doc.CreateElement("SendOnEdit");
                e.AppendChild(doc.CreateTextNode(SendOnEdit.ToString()));
                project_root.AppendChild(e);
            }

            {
                var e = doc.CreateElement("SendOnSave");
                e.AppendChild(doc.CreateTextNode(SendOnSave.ToString()));
                project_root.AppendChild(e);
            }

            doc.AppendChild(project_root);

            var dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);

            doc.InsertBefore(dec, project_root);

            // For failing to save
            try
            {
                doc.Save(path);
            }
            catch
            {
            }
        }
Esempio n. 36
0
        public void Dispose()
        {
            if (_closeWriter)
            {
                _wr.Close();
                string str = _sb.ToString();
                _wr = null;
                _tw = null;
                _sb = null;
                if (_cnt > 1)
                {
                    lock (this.GetType())
                    {
                        System.Xml.XmlDocument xdoc = null;
                        bool cl = xdoc == null;
                        if (cl)
                        {
                            xdoc = new System.Xml.XmlDocument();
                            if (!System.IO.File.Exists(_fn))
                            {
                                System.Xml.XmlElement root = xdoc.CreateElement("root");
                                xdoc.AppendChild(root);
                            }
                            else
                            {
                                xdoc.Load(_fn);
                            }
                        }
                        System.Xml.XmlDocumentFragment e = xdoc.CreateDocumentFragment();
                        e.InnerXml = str;
                        xdoc.DocumentElement.AppendChild(e);
                        if (cl)
                        {
                            xdoc.Save(_fn);
                            xdoc = null;
                        }
                    }
                }
                _cnt = 0;
            }
            else
            {
                _wr.WriteEndElement();
            }

            //lock (typeof(CSScopeMgr_Debug))
            //{
            //    if (_first)
            //    {
            //        _xdoc.Save(_fn);
            //        _xdoc = null;
            //    }
            //}

            Unlock(_lock_obj);
        }
Esempio n. 37
0
        public System.Xml.XmlDocument getUserStats(string user)
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

            TurfWarsGame.User u = TurfWars.Global.game.getUser(user);

            System.Xml.XmlElement xmlUser = doc.CreateElement("user");
            xmlUser.SetAttribute("name", user);
            xmlUser.SetAttribute("balance", u.getAccountBalance().ToString());
            xmlUser.SetAttribute("shares", u.shares.ToString());

            doc.AppendChild(xmlUser);
            return doc;
        }
Esempio n. 38
0
 public string ToDocumentXmlText()
 {
     System.Xml.XmlDocument datagram = new System.Xml.XmlDocument();
     System.Xml.XmlNode b1 = datagram.CreateElement(_Datagram.ToUpper());
     foreach (KeyValuePair<string, string> curr in Parameters)
     {
         System.Xml.XmlAttribute b2 = datagram.CreateAttribute(curr.Key);
         b2.Value = curr.Value;
         b1.Attributes.Append(b2);
     }
     b1.InnerText = this._InnerText;
     datagram.AppendChild(b1);
     return datagram.InnerXml;
 }
Esempio n. 39
0
        /// <summary>
        /// Get the kml for this list of datasets
        /// </summary>
        /// <param name="strWmsUrl"></param>
        /// <param name="oDatasets"></param>
        /// <param name="oSelectedDatasets"></param>
        /// <returns></returns>
        public static System.Xml.XmlDocument GetKML(string strWmsUrl, System.Collections.SortedList oDatasets, System.Collections.ArrayList oSelectedDatasets)
        {
            System.Xml.XmlDocument oOutputXml = new System.Xml.XmlDocument();

            oOutputXml.AppendChild(oOutputXml.CreateXmlDeclaration("1.0", "UTF-8", string.Empty));

            System.Xml.XmlElement oKml = oOutputXml.CreateElement("kml", "http://earth.google.com/kml/2.1");
            oOutputXml.AppendChild(oKml);

            System.Xml.XmlElement oDocument = oOutputXml.CreateElement("Document", "http://earth.google.com/kml/2.1");
            System.Xml.XmlAttribute oAttr = oOutputXml.CreateAttribute("id");
            oAttr.Value = "Geosoft";
            oDocument.Attributes.Append(oAttr);
            oKml.AppendChild(oDocument);

            System.Xml.XmlElement oName = oOutputXml.CreateElement("name", "http://earth.google.com/kml/2.1");
            oName.InnerText = "Geosoft Catalog";
            oDocument.AppendChild(oName);

            System.Xml.XmlElement oVisibility = oOutputXml.CreateElement("visibility", "http://earth.google.com/kml/2.1");
            oVisibility.InnerText = "1";
            oDocument.AppendChild(oVisibility);

            System.Xml.XmlElement oOpen = oOutputXml.CreateElement("open", "http://earth.google.com/kml/2.1");
            oOpen.InnerText = "1";
            oDocument.AppendChild(oOpen);

            foreach (string strKey in oSelectedDatasets)
            {
                Dap.Common.DataSet oDataset = (Dap.Common.DataSet)oDatasets[strKey];

                if (oDataset != null)
                    OutputDataset(strWmsUrl, oDocument, oDataset);
            }
            return oOutputXml;
        }
Esempio n. 40
0
        public System.Xml.XmlDocument addClaim(string user, double lat, double lon)
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

            Geo.Box box = TurfWars.Global.game.addClaim(user, lat, lon);

            System.Xml.XmlElement tile = doc.CreateElement("tile");
            tile.SetAttribute("north", box.north.ToString());
            tile.SetAttribute("south", box.south.ToString());
            tile.SetAttribute("west", box.west.ToString());
            tile.SetAttribute("east", box.east.ToString());

            doc.AppendChild(tile);
            return doc;
        }
		/// <summary> <p>Creates an XML Document that corresponds to the given Message object. </p>
		/// <p>If you are implementing this method, you should create an XML Document, and insert XML Elements
		/// into it that correspond to the groups and segments that belong to the message type that your subclass
		/// of XMLParser supports.  Then, for each segment in the message, call the method
		/// <code>encode(Segment segmentObject, Element segmentElement)</code> using the Element for
		/// that segment and the corresponding Segment object from the given Message.</p>
		/// </summary>
		public override System.Xml.XmlDocument encodeDocument(Message source)
		{
			System.String messageClassName = source.GetType().FullName;
			System.String messageName = messageClassName.Substring(messageClassName.LastIndexOf('.') + 1);
			System.Xml.XmlDocument doc = null;
			try
			{
				doc = new System.Xml.XmlDocument();
				System.Xml.XmlElement root = doc.CreateElement(messageName);
				doc.AppendChild(root);
			}
			catch (System.Exception e)
			{
				throw new NuGenHL7Exception("Can't create XML document - " + e.GetType().FullName, NuGenHL7Exception.APPLICATION_INTERNAL_ERROR, e);
			}
			encode(source, (System.Xml.XmlElement) doc.DocumentElement);
			return doc;
		}
Esempio n. 42
0
        private void BtnAdd_Click(object sender, System.EventArgs e)
        {
            if (doc == null)
            {
                doc = Framework.Class.XmlTool.GetInstance();
                System.Xml.XmlNode project = doc.CreateElement("PROJECT");
                doc.AppendChild(project);

                Framework.Interface.Project.FrmProjectInfo win = new Framework.Interface.Project.FrmProjectInfo();
                win.ShowDialog();
                //doc.Save("aaa.xml");
                RefreshChapterTree();
            }
            else
            {
                DevComponents.DotNetBar.MessageBoxEx.Show("不允许重复创建工程!", "提示", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation);
            }
        }
Esempio n. 43
0
        /// <summary>
        /// Save to a file
        /// </summary>
        public void Save()
        {
            update = true;
            try
            {
                if (File.Exists(datafile_xml))
                {
                    core.backupData(datafile_xml);
                    if (!File.Exists(config.tempName(datafile_xml)))
                    {
                        core.Log("Unable to create backup file for " + this.Channel);
                    }
                }
                System.Xml.XmlDocument data = new System.Xml.XmlDocument();
                System.Xml.XmlNode xmlnode = data.CreateElement("database");

                lock (Alias)
                {
                    foreach (staticalias key in Alias)
                    {
                        System.Xml.XmlAttribute name = data.CreateAttribute("alias_key_name");
                        name.Value = key.Name;
                        System.Xml.XmlAttribute kk = data.CreateAttribute("alias_key_key");
                        kk.Value = key.Key;
                        System.Xml.XmlAttribute created = data.CreateAttribute("date");
                        created.Value = "";
                        System.Xml.XmlNode db = data.CreateElement("alias");
                        db.Attributes.Append(name);
                        db.Attributes.Append(kk);
                        db.Attributes.Append(created);
                        xmlnode.AppendChild(db);
                    }
                }
                lock (text)
                {
                    foreach (item key in text)
                    {
                        System.Xml.XmlAttribute name = data.CreateAttribute("key_name");
                        name.Value = key.key;
                        System.Xml.XmlAttribute kk = data.CreateAttribute("data");
                        kk.Value = key.text;
                        System.Xml.XmlAttribute created = data.CreateAttribute("created_date");
                        created.Value = key.created.ToBinary().ToString();
                        System.Xml.XmlAttribute nick = data.CreateAttribute("nickname");
                        nick.Value = key.user;
                        System.Xml.XmlAttribute last = data.CreateAttribute("touched");
                        last.Value = key.lasttime.ToBinary().ToString();
                        System.Xml.XmlAttribute triggered = data.CreateAttribute("triggered");
                        triggered.Value = key.Displayed.ToString();
                        System.Xml.XmlNode db = data.CreateElement("key");
                        db.Attributes.Append(name);
                        db.Attributes.Append(kk);
                        db.Attributes.Append(nick);
                        db.Attributes.Append(created);
                        db.Attributes.Append(last);
                        db.Attributes.Append(triggered);
                        xmlnode.AppendChild(db);
                    }
                }

                data.AppendChild(xmlnode);
                data.Save(datafile_xml);
                if (File.Exists(config.tempName(datafile_xml)))
                {
                    File.Delete(config.tempName(datafile_xml));
                }
            }
            catch (Exception b)
            {
                try
                {
                    if (core.recoverFile(datafile_xml, Channel))
                    {
                        core.Log("Recovered db for channel " + Channel);
                    }
                    else
                    {
                        core.handleException(b, Channel);
                    }
                }
                catch (Exception bb)
                {
                    core.handleException(bb, Channel);
                }
            }
        }
Esempio n. 44
0
 bool svgconcat(List<string> files, string output, uint delay, uint loop) {
     if (controller_ != null) controller_.appendOutput("TeX2img: Making animation svg...");
     try {
         var outxml = new System.Xml.XmlDocument();
         outxml.XmlResolver = null;
         outxml.AppendChild(outxml.CreateXmlDeclaration("1.0", "utf-8", "no"));
         outxml.AppendChild(outxml.CreateDocumentType("svg", "-//W3C//DTD SVG 1.1//EN", "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd", null));
         var svg = outxml.CreateElement("svg", "http://www.w3.org/2000/svg");
         var attr = outxml.CreateAttribute("xmlns:xlink");
         attr.Value = "http://www.w3.org/1999/xlink";
         svg.Attributes.Append(attr);
         attr = outxml.CreateAttribute("version");
         attr.Value = "1.1";
         svg.Attributes.Append(attr);
         outxml.AppendChild(svg);
         var defs = outxml.CreateElement("defs", "http://www.w3.org/2000/svg");
         svg.AppendChild(defs);
         var idreg = new System.Text.RegularExpressions.Regex(@"(?<!\&)#");
         foreach (var f in files) {
             var id = Path.GetFileNameWithoutExtension(f);
             var xml = new System.Xml.XmlDocument();
             xml.XmlResolver = null;
             xml.Load(Path.Combine(workingDir, f));
             foreach (System.Xml.XmlNode tag in xml.GetElementsByTagName("*")) {
                 foreach (System.Xml.XmlAttribute a in tag.Attributes) {
                     if (a.Name.ToLower() == "id") a.Value = id + "-" + a.Value;
                     else a.Value = idreg.Replace(a.Value, "#" + id + "-");
                 }
             }
             foreach (System.Xml.XmlNode tag in xml.GetElementsByTagName("svg")) {
                 var idattr = xml.CreateAttribute("id");
                 idattr.Value = id;
                 tag.Attributes.Append(idattr);
             }
             foreach (System.Xml.XmlNode n in xml.ChildNodes) {
                 if (n.NodeType != System.Xml.XmlNodeType.DocumentType && n.NodeType != System.Xml.XmlNodeType.XmlDeclaration) {
                     defs.AppendChild(outxml.ImportNode(n, true));
                 }
             }
         }
         var use = outxml.CreateElement("use", "http://www.w3.org/2000/svg");
         svg.AppendChild(use);
         var animate = outxml.CreateElement("animate", "http://www.w3.org/2000/svg");
         use.AppendChild(animate);
         attr = outxml.CreateAttribute("attributeName");
         attr.Value = "xlink:href"; animate.Attributes.Append(attr);
         attr = outxml.CreateAttribute("begin");
         attr.Value = "0s"; animate.Attributes.Append(attr);
         attr = outxml.CreateAttribute("dur");
         attr.Value = ((decimal)(delay * files.Count) / 100).ToString() + "s";
         animate.Attributes.Append(attr);
         attr = outxml.CreateAttribute("repeatCount");
         attr.Value = loop > 0 ? loop.ToString() : "indefinite";
         animate.Attributes.Append(attr);
         attr = outxml.CreateAttribute("values");
         attr.Value = String.Join(";", files.Select(d => "#" + Path.GetFileNameWithoutExtension(d)).ToArray());
         animate.Attributes.Append(attr);
         outxml.Save(Path.Combine(workingDir, output));
         if (controller_ != null) controller_.appendOutput(" done\n");
         return true;
     }
     catch (Exception) { return false; }
 }
		public static multiTable2oneXML_spy2 CreateDocument(string encoding)
		{
			System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
			doc.AppendChild(doc.CreateXmlDeclaration("1.0", encoding, null));
			return new multiTable2oneXML_spy2(doc);
		}
Esempio n. 46
0
        private string EncodeFilterAsXml(List<FilterDialog.FilterEntry> list)
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            System.Xml.XmlNode root = doc.AppendChild(doc.CreateElement("root"));

            foreach (FilterDialog.FilterEntry f in list)
            {
                System.Xml.XmlNode filter = root.AppendChild(doc.CreateElement("filter"));
                filter.Attributes.Append(doc.CreateAttribute("include")).Value = f.Include.ToString();
                filter.Attributes.Append(doc.CreateAttribute("filter")).Value = f.Filter;
                filter.Attributes.Append(doc.CreateAttribute("globbing")).Value = f.Globbing;
            }

            return doc.OuterXml;
        }
Esempio n. 47
0
        /// <summary>
        /// Write the latest version of the XML definition file.
        /// Always refer to the schema location as a relative path to the bam executable.
        /// Always reference the default namespace in the first element.
        /// Don't use a namespace prefix on child elements, as the default namespace covers them.
        /// </summary>
        public void Write()
        {
            if (System.IO.File.Exists(this.XMLFilename))
            {
                var attributes = System.IO.File.GetAttributes(this.XMLFilename);
                if (0 != (attributes & System.IO.FileAttributes.ReadOnly))
                {
                    throw new Exception("File '{0}' cannot be written to as it is read only", this.XMLFilename);
                }
            }

            this.Dependents.Sort();

            var document = new System.Xml.XmlDocument();
            var namespaceURI = "http://www.buildamation.com";
            var packageDefinition = document.CreateElement("PackageDefinition", namespaceURI);
            {
                var xmlns = "http://www.w3.org/2001/XMLSchema-instance";
                var schemaAttribute = document.CreateAttribute("xsi", "schemaLocation", xmlns);
                var mostRecentSchemaRelativePath = "./Schema/BamPackageDefinitionV1.xsd";
                schemaAttribute.Value = System.String.Format("{0} {1}", namespaceURI, mostRecentSchemaRelativePath);
                packageDefinition.Attributes.Append(schemaAttribute);
                packageDefinition.SetAttribute("name", this.Name);
                if (null != this.Version)
                {
                    packageDefinition.SetAttribute("version", this.Version);
                }
            }
            document.AppendChild(packageDefinition);

            // package description
            if (!string.IsNullOrEmpty(this.Description))
            {
                var descriptionElement = document.CreateElement("Description", namespaceURI);
                descriptionElement.InnerText = this.Description;
                packageDefinition.AppendChild(descriptionElement);
            }

            // package repositories
            var packageRepos = new StringArray(this.PackageRepositories);
            // TODO: could these be marked as transient?
            // don't write out the repo that this package resides in
            packageRepos.Remove(this.GetPackageRepository());
            // nor an associated repo for tests
            var associatedRepo = this.GetAssociatedPackageDirectoryForTests();
            if (null != associatedRepo)
            {
                packageRepos.Remove(associatedRepo);
            }
            if (packageRepos.Count > 0)
            {
                var packageRootsElement = document.CreateElement("PackageRepositories", namespaceURI);
                var bamDir = this.GetBamDirectory() + System.IO.Path.DirectorySeparatorChar; // slash added to make it look like a directory
                foreach (string repo in packageRepos)
                {
                    var relativePackageRepo = RelativePathUtilities.GetPath(repo, bamDir);
                    if (OSUtilities.IsWindowsHosting)
                    {
                        // standardize on non-Windows directory separators
                        relativePackageRepo = relativePackageRepo.Replace(System.IO.Path.DirectorySeparatorChar, System.IO.Path.AltDirectorySeparatorChar);
                    }

                    var rootElement = document.CreateElement("Repo", namespaceURI);
                    rootElement.SetAttribute("dir", relativePackageRepo);
                    packageRootsElement.AppendChild(rootElement);
                }

                packageDefinition.AppendChild(packageRootsElement);
            }

            if (this.Dependents.Count > 0)
            {
                var dependentsEl = document.CreateElement("Dependents", namespaceURI);
                foreach (var package in this.Dependents)
                {
                    var packageName = package.Item1;
                    var packageVersion = package.Item2;
                    var packageIsDefault = package.Item3;
                    System.Xml.XmlElement packageElement = null;

                    {
                        var node = dependentsEl.FirstChild;
                        while (node != null)
                        {
                            var attributes = node.Attributes;
                            var nameAttribute = attributes["Name"];
                            if ((null != nameAttribute) && (nameAttribute.Value == packageName))
                            {
                                packageElement = node as System.Xml.XmlElement;
                                break;
                            }

                            node = node.NextSibling;
                        }
                    }

                    if (null == packageElement)
                    {
                        packageElement = document.CreateElement("Package", namespaceURI);
                        packageElement.SetAttribute("name", packageName);
                        if (null != packageVersion)
                        {
                            packageElement.SetAttribute("version", packageVersion);
                        }
                        if (packageIsDefault.HasValue)
                        {
                            packageElement.SetAttribute("default", packageIsDefault.Value.ToString().ToLower());
                        }
                        dependentsEl.AppendChild(packageElement);
                    }
                }
                packageDefinition.AppendChild(dependentsEl);
            }

            if (this.BamAssemblies.Count > 0)
            {
                var requiredAssemblies = document.CreateElement("BamAssemblies", namespaceURI);
                foreach (var assembly in this.BamAssemblies)
                {
                    var assemblyElement = document.CreateElement("BamAssembly", namespaceURI);
                    assemblyElement.SetAttribute("name", assembly.Name);
                    if (assembly.MajorVersion.HasValue)
                    {
                        assemblyElement.SetAttribute("major", assembly.MajorVersion.ToString());
                        if (assembly.MinorVersion.HasValue)
                        {
                            assemblyElement.SetAttribute("minor", assembly.MinorVersion.ToString());
                            if (assembly.PatchVersion.HasValue)
                            {
                                // honour any existing BamAssembly with a specific patch version
                                assemblyElement.SetAttribute("patch", assembly.PatchVersion.ToString());
                            }
                        }
                    }
                    requiredAssemblies.AppendChild(assemblyElement);
                }
                packageDefinition.AppendChild(requiredAssemblies);
            }

            if (this.DotNetAssemblies.Count > 0)
            {
                var requiredDotNetAssemblies = document.CreateElement("DotNetAssemblies", namespaceURI);
                foreach (var desc in this.DotNetAssemblies)
                {
                    var assemblyElement = document.CreateElement("DotNetAssembly", namespaceURI);
                    assemblyElement.SetAttribute("name", desc.Name);
                    if (null != desc.RequiredTargetFramework)
                    {
                        assemblyElement.SetAttribute("requiredTargetFramework", desc.RequiredTargetFramework);
                    }
                    requiredDotNetAssemblies.AppendChild(assemblyElement);
                }
                packageDefinition.AppendChild(requiredDotNetAssemblies);
            }

            // supported platforms
            {
                var supportedPlatformsElement = document.CreateElement("SupportedPlatforms", namespaceURI);

                if (EPlatform.Windows == (this.SupportedPlatforms & EPlatform.Windows))
                {
                    var platformElement = document.CreateElement("Platform", namespaceURI);
                    platformElement.SetAttribute("name", "Windows");
                    supportedPlatformsElement.AppendChild(platformElement);
                }
                if (EPlatform.Linux == (this.SupportedPlatforms & EPlatform.Linux))
                {
                    var platformElement = document.CreateElement("Platform", namespaceURI);
                    platformElement.SetAttribute("name", "Linux");
                    supportedPlatformsElement.AppendChild(platformElement);
                }
                if (EPlatform.OSX == (this.SupportedPlatforms & EPlatform.OSX))
                {
                    var platformElement = document.CreateElement("Platform", namespaceURI);
                    platformElement.SetAttribute("name", "OSX");
                    supportedPlatformsElement.AppendChild(platformElement);
                }

                packageDefinition.AppendChild(supportedPlatformsElement);
            }

            // definitions
            this.Definitions.Remove(this.GetPackageDefinitionName());
            if (this.Definitions.Count > 0)
            {
                var definitionsElement = document.CreateElement("Definitions", namespaceURI);

                foreach (string define in this.Definitions)
                {
                    var defineElement = document.CreateElement("Definition", namespaceURI);
                    defineElement.SetAttribute("name", define);
                    definitionsElement.AppendChild(defineElement);
                }

                packageDefinition.AppendChild(definitionsElement);
            }

            var xmlWriterSettings = new System.Xml.XmlWriterSettings();
            xmlWriterSettings.Indent = true;
            xmlWriterSettings.CloseOutput = true;
            xmlWriterSettings.OmitXmlDeclaration = false;
            xmlWriterSettings.NewLineOnAttributes = false;
            xmlWriterSettings.NewLineChars = "\n";
            xmlWriterSettings.ConformanceLevel = System.Xml.ConformanceLevel.Document;
            xmlWriterSettings.Encoding = new System.Text.UTF8Encoding(false);

            using (var xmlWriter = System.Xml.XmlWriter.Create(this.XMLFilename, xmlWriterSettings))
            {
                document.WriteTo(xmlWriter);
                xmlWriter.WriteWhitespace(xmlWriterSettings.NewLineChars);
            }

            if (this.validate)
            {
                this.Validate();
            }
        }
Esempio n. 48
0
        private void CreatePlist()
        {
            var doc = new System.Xml.XmlDocument();
            // don't resolve any URLs, or if there is no internet, the process will pause for some time
            doc.XmlResolver = null;

            {
                var type = doc.CreateDocumentType("plist", "-//Apple Computer//DTD PLIST 1.0//EN", "http://www.apple.com/DTDs/PropertyList-1.0.dtd", null);
                doc.AppendChild(type);
            }
            var plistEl = doc.CreateElement("plist");
            {
                var versionAttr = doc.CreateAttribute("version");
                versionAttr.Value = "1.0";
                plistEl.Attributes.Append(versionAttr);
            }

            var dictEl = doc.CreateElement("dict");
            plistEl.AppendChild(dictEl);
            doc.AppendChild(plistEl);

            #if true
            // TODO: this seems to be the only way to get the target settings working
            CreateKeyValuePair(doc, dictEl, "BuildLocationStyle", "UseTargetSettings");
            #else
            // build and intermediate file locations
            CreateKeyValuePair(doc, dictEl, "BuildLocationStyle", "CustomLocation");
            CreateKeyValuePair(doc, dictEl, "CustomBuildIntermediatesPath", "XcodeIntermediates"); // where xxx.build folders are stored
            CreateKeyValuePair(doc, dictEl, "CustomBuildLocationType", "RelativeToWorkspace");
            CreateKeyValuePair(doc, dictEl, "CustomBuildProductsPath", "."); // has to be the workspace folder, in order to write files to expected locations

            // derived data
            CreateKeyValuePair(doc, dictEl, "DerivedDataCustomLocation", "XcodeDerivedData");
            CreateKeyValuePair(doc, dictEl, "DerivedDataLocationStyle", "WorkspaceRelativePath");
            #endif

            this.Document = doc;
        }
Esempio n. 49
0
        internal VerificationFile(IEnumerable<ManifestEntry> parentChain, FilenameStrategy str)
        {
            m_doc = new System.Xml.XmlDocument();
            System.Xml.XmlNode root = m_doc.AppendChild(m_doc.CreateElement("Verify"));
            root.Attributes.Append(m_doc.CreateAttribute("hash-algorithm")).Value = Utility.Utility.HashAlgorithm;
            root.Attributes.Append(m_doc.CreateAttribute("version")).Value = "1";

            m_node = root.AppendChild(m_doc.CreateElement("Files"));

            foreach (ManifestEntry mfe in parentChain)
            {
                System.Xml.XmlNode f = m_node.AppendChild(m_doc.CreateElement("File"));
                f.Attributes.Append(m_doc.CreateAttribute("type")).Value = "manifest";
                f.Attributes.Append(m_doc.CreateAttribute("name")).Value = mfe.Filename;
                f.Attributes.Append(m_doc.CreateAttribute("size")).Value = mfe.Filesize.ToString();
                f.InnerText = Utility.Utility.ByteArrayAsHexString(Convert.FromBase64String(mfe.RemoteHash));

                for (int i = 0; i < mfe.ParsedManifest.SignatureHashes.Count; i++)
                {
                    string sigfilename = mfe.ParsedManifest.SignatureHashes[i].Name;
                    string contentfilename = mfe.ParsedManifest.ContentHashes[i].Name;
                    bool missing = i >= mfe.Volumes.Count;

                    if (string.IsNullOrEmpty(sigfilename) || string.IsNullOrEmpty(contentfilename))
                    {
                        if (missing)
                        {
                            sigfilename = str.GenerateFilename(new SignatureEntry(mfe.Time, mfe.IsFull, i + 1));
                            contentfilename = str.GenerateFilename(new ContentEntry(mfe.Time, mfe.IsFull, i + 1));

                            //Since these files are missing, we have to guess what their real names were
                            string compressionGuess;
                            if (mfe.Volumes.Count <= 0)
                                compressionGuess = ".zip"; //Default if we have no knowledge
                            else
                                compressionGuess = "." + mfe.Volumes[0].Key.Compression; //Most likely the same as all the others

                            //Encryption will likely be the same as the one the manifest uses
                            string encryptionGuess = string.IsNullOrEmpty(mfe.EncryptionMode) ? "" : "." + mfe.EncryptionMode;

                            sigfilename += compressionGuess + encryptionGuess;
                            contentfilename += compressionGuess + encryptionGuess;
                        }
                        else
                        {
                            sigfilename = mfe.Volumes[i].Key.Filename;
                            contentfilename = mfe.Volumes[i].Value.Filename;
                        }
                    }

                    f = m_node.AppendChild(m_doc.CreateElement("File"));
                    f.Attributes.Append(m_doc.CreateAttribute("type")).Value = "signature";
                    f.Attributes.Append(m_doc.CreateAttribute("name")).Value = sigfilename;
                    f.Attributes.Append(m_doc.CreateAttribute("size")).Value = mfe.ParsedManifest.SignatureHashes[i].Size.ToString();
                    if (missing) f.Attributes.Append(m_doc.CreateAttribute("missing")).Value = "true";
                    f.InnerText = Utility.Utility.ByteArrayAsHexString(Convert.FromBase64String(mfe.ParsedManifest.SignatureHashes[i].Hash));

                    f = m_node.AppendChild(m_doc.CreateElement("File"));
                    f.Attributes.Append(m_doc.CreateAttribute("type")).Value = "content";
                    f.Attributes.Append(m_doc.CreateAttribute("name")).Value = contentfilename;
                    f.Attributes.Append(m_doc.CreateAttribute("size")).Value = mfe.ParsedManifest.ContentHashes[i].Size.ToString();
                    if (missing) f.Attributes.Append(m_doc.CreateAttribute("missing")).Value = "true";
                    f.InnerText = Utility.Utility.ByteArrayAsHexString(Convert.FromBase64String(mfe.ParsedManifest.ContentHashes[i].Hash));
                }
            }
        }
        private string SaveToXml()
        {
            System.Xml.XmlDocument doc=null;
            System.Xml.XmlElement rootEl=null;

            // parameters
            doc=new System.Xml.XmlDocument();
            rootEl=doc.CreateElement("PARAMETERS");
            doc.AppendChild(rootEl);
            /*
            foreach(string serNo in this._productsSerNoList)
            {
                System.Xml.XmlElement childEl=doc.CreateElement("PR");
                childEl.SetAttribute("SN" , serNo);
                rootEl.AppendChild(childEl);
            }
            */
            return doc.InnerXml;
        }
Esempio n. 51
0
            /// <summary>
            /// Saves the USN data to an XmlDocument
            /// </summary>
            /// <returns>An XmlDocument with the USN data</returns>
            public System.Xml.XmlDocument Save()
            {
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                System.Xml.XmlNode root = doc.AppendChild(doc.CreateElement("usnroot"));
                foreach (KeyValuePair<string, KeyValuePair<long, long>> kv in m_values)
                {
                    System.Xml.XmlNode n = root.AppendChild(doc.CreateElement("usnrecord"));
                    n.Attributes.Append(doc.CreateAttribute("root")).Value = kv.Key;
                    n.Attributes.Append(doc.CreateAttribute("journalid")).Value = kv.Value.Key.ToString();
                    n.Attributes.Append(doc.CreateAttribute("usn")).Value = kv.Value.Value.ToString();
                }

                return doc;
            }
Esempio n. 52
0
        private void buttonSaveWhiteReflectanceReference_Click( object sender, EventArgs e )
        {
            string	OldFileName =  m_ImageFileName.FullName;
            saveFileDialogWhiteReflectance.InitialDirectory = System.IO.Path.GetDirectoryName( OldFileName );
            saveFileDialogWhiteReflectance.FileName = System.IO.Path.GetFileNameWithoutExtension( OldFileName ) + ".whiteRef";

            if ( saveFileDialogWhiteReflectance.ShowDialog( this ) != DialogResult.OK )
             				return;

            SetRegKey( "LastWhiteReflectanceFilename", saveFileDialogWhiteReflectance.FileName );
            SetRegKey( "ReloadWhiteReflectanceOnStartup", "true" );

            try
            {
                System.IO.FileInfo	WhiteRefFileName = new System.IO.FileInfo( saveFileDialogWhiteReflectance.FileName );

                // Save
                System.Xml.XmlDocument	Doc = new System.Xml.XmlDocument();
                System.Xml.XmlElement	Root = Doc.CreateElement( "WhiteReflectance" );
                Doc.AppendChild( Root );
                Root.SetAttribute( "Value", m_CalibrationDatabase.WhiteReflectanceReference.ToString() );
                Root.SetAttribute( "ISOSpeed", m_CalibrationDatabase.PreparedForISOSpeed.ToString() );
                Root.SetAttribute( "ShutterSpeed", m_CalibrationDatabase.PreparedForShutterSpeed.ToString() );
                Root.SetAttribute( "Aperture", m_CalibrationDatabase.PreparedForAperture.ToString() );
                Doc.Save( WhiteRefFileName.FullName );
            }
            catch ( Exception _e )
            {
                MessageBox( "An error occurred while saving white reflectance file:\r\n\r\n", _e );
            }
        }
Esempio n. 53
0
        internal static void SaveConfig()
        {
            {
                var rf = GetRecentFiles();

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

                System.Xml.XmlElement project_root = doc.CreateElement("Recent");

                foreach (var f in rf.Reverse())
                {
                    project_root.AppendChild(doc.CreateTextElement("File", f));
                }

                doc.AppendChild(project_root);

                var dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
                doc.InsertBefore(dec, project_root);
                doc.Save(configRecentPath);
            }

            {
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

                System.Xml.XmlElement project_root = doc.CreateElement("GUI");

                if (MainForm.WindowState == FormWindowState.Normal)
                {
                    project_root.AppendChild(doc.CreateTextElement("X", MainForm.Location.X.ToString()));
                    project_root.AppendChild(doc.CreateTextElement("Y", MainForm.Location.Y.ToString()));
                    project_root.AppendChild(doc.CreateTextElement("Width", MainForm.Width.ToString()));
                    project_root.AppendChild(doc.CreateTextElement("Height", MainForm.Height.ToString()));
                }
                else // 最小化、最大化中はその前の位置とサイズを保存
                {
                    project_root.AppendChild(doc.CreateTextElement("X", MainForm.BeforeResizeLocation.X.ToString()));
                    project_root.AppendChild(doc.CreateTextElement("Y", MainForm.BeforeResizeLocation.Y.ToString()));
                    project_root.AppendChild(doc.CreateTextElement("Width", MainForm.BeforeResizeWidth.ToString()));
                    project_root.AppendChild(doc.CreateTextElement("Height", MainForm.BeforeResizeHeight.ToString()));
                }
                doc.AppendChild(project_root);

                var dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
                doc.InsertBefore(dec, project_root);
                doc.Save(configGuiPath);
            }

            MainForm.Panel.SaveAsXml(configGuiPanelPath, Encoding.UTF8);

            Network.Save(configNetworkPath);
        }
Esempio n. 54
0
        public void SaveClassListXML(string filename)
        {
            System.Xml.XmlDocument xdoc = new System.Xml.XmlDocument();
            System.Xml.XmlDeclaration xdec = xdoc.CreateXmlDeclaration("1.0", "utf-8", null);
            xdoc.AppendChild(xdec);
            System.Xml.XmlElement root = xdoc.CreateElement("ClassesList");
            for (int i = 0; i < classList.Count; i++)
            {
                System.Xml.XmlElement classNode = xdoc.CreateElement("Class");
                classNode.Attributes.Append(CreateAttribute("Title", classList[i].Title, xdoc));
                classNode.Attributes.Append(CreateAttribute("Subject", classList[i].Subject.ToString(), xdoc));
                classNode.Attributes.Append(CreateAttribute("Sch", classList[i].Sch.ToString(), xdoc));
                classNode.Attributes.Append(CreateAttribute("Index", classList[i].Index.ToString(), xdoc));
                classNode.Attributes.Append(CreateAttribute("Credits", classList[i].Credits.ToString(), xdoc));
                foreach (ClassSection cs in classList[i].Sections)
                {
                    System.Xml.XmlElement sectionNode = xdoc.CreateElement("Section");
                    sectionNode.Attributes.Append(CreateAttribute("SectionCode", cs.Section, xdoc));
                    sectionNode.Attributes.Append(CreateAttribute("RegistrationIndex", cs.RegistrationIndex, xdoc));

                    foreach (TimeFrame tf in cs.Times)
                    {
                        System.Xml.XmlElement timeframNode = xdoc.CreateElement("TimeFrame");
                        timeframNode.Attributes.Append(CreateAttribute("startDay", Enum.GetName(typeof(DayOfWeek), tf.StartTime.Day), xdoc));
                        timeframNode.Attributes.Append(CreateAttribute("startHour", tf.StartTime.Hour.ToString(), xdoc));
                        timeframNode.Attributes.Append(CreateAttribute("startMin", tf.StartTime.Minute.ToString(), xdoc));

                        timeframNode.Attributes.Append(CreateAttribute("endDay", Enum.GetName(typeof(DayOfWeek), tf.EndTime.Day), xdoc));
                        timeframNode.Attributes.Append(CreateAttribute("endHour", tf.EndTime.Hour.ToString(), xdoc));
                        timeframNode.Attributes.Append(CreateAttribute("endMin", tf.EndTime.Minute.ToString(), xdoc));
                        sectionNode.AppendChild(timeframNode);
                    }

                    classNode.AppendChild(sectionNode);
                }
                root.AppendChild(classNode);
            }
            xdoc.AppendChild(root);
            xdoc.Save(filename);
        }
Esempio n. 55
0
        private void SaveState()
        {
            //file queue
            System.Xml.XmlDocument XmlDoc = new System.Xml.XmlDocument();
            XmlDoc.AppendChild(XmlDoc.CreateElement("nzb"));

            foreach( Article article in m_ServerManager.m_Articles)
            {
                if( article.Status == ArticleStatus.Decoded || article.Status == ArticleStatus.Deleted || article.Status == ArticleStatus.Error)
                    continue;

                System.Xml.XmlNode XmlArticle = XmlDoc.CreateElement( "file");

                DateTime Date = new DateTime(1970, 1, 1, 0, 0, 0, 0);

                XmlAddAttr( XmlArticle, "subject", article.Subject);
                XmlAddAttr( XmlArticle, "date", ((long)article.Date.Subtract(Date).TotalSeconds).ToString());
                XmlAddAttr( XmlArticle, "poster", article.Poster);
                XmlAddAttr( XmlArticle, "importfile", article.ImportFile);

                System.Xml.XmlNode XmlGroups = XmlDoc.CreateElement( "groups");
                foreach( string group in article.Groups)
                {
                    System.Xml.XmlNode XmlGroup = XmlDoc.CreateElement( "group");
                    XmlGroup.InnerText = group;
                    XmlGroups.AppendChild( XmlGroup);
                }
                XmlArticle.AppendChild( XmlGroups);

                System.Xml.XmlNode XmlSegments = XmlDoc.CreateElement( "segments");
                foreach( Segment segment in article.Segments)
                {
                    System.Xml.XmlNode XmlSegment = XmlDoc.CreateElement( "segment");

                    XmlAddAttr( XmlSegment, "bytes", segment.Bytes.ToString());
                    XmlAddAttr( XmlSegment, "number", segment.Number.ToString());

                    XmlSegment.InnerText = segment.ArticleID;
                    XmlSegments.AppendChild( XmlSegment);
                }
                XmlArticle.AppendChild( XmlSegments);

                XmlDoc.DocumentElement.AppendChild(XmlArticle);
            }

            XmlDoc.Save(Global.m_DataDirectory + "nzb-o-matic.xml");

            //servers
            System.Xml.XmlDocument ServerDoc = new System.Xml.XmlDocument();
            System.Xml.XmlDeclaration decleration = ServerDoc.CreateXmlDeclaration("1.0", "utf-8", "");
            ServerDoc.AppendChild(decleration);

            //create server groups element
            System.Xml.XmlNode servergroups = ServerDoc.CreateElement("servergroups");

            //loop through each servergroup
            foreach(ServerGroup sgs in m_ServerManager.m_ServerGroups)
            {
                //create servergroup tag
                System.Xml.XmlNode servergroup = ServerDoc.CreateElement("servergroup");
                //create servers tag
                System.Xml.XmlNode servers = ServerDoc.CreateElement("servers");
                //loop through each server
                foreach(Server serv in sgs.Servers)
                {
                    //add server tag
                    System.Xml.XmlNode snode = ServerDoc.CreateElement("server");
                    XmlAddAttr(snode, "enabled", serv.Enabled.ToString());

                    XmlAddElement(snode, "address", serv.Hostname);
                    XmlAddElement(snode, "port", serv.Port.ToString());
                    //add login
                    System.Xml.XmlNode login = ServerDoc.CreateElement("login");
                    if(serv.RequiresLogin)
                    {
                        XmlAddElement(login, "username", serv.Username);
                        XmlAddElement(login, "password", serv.Password);
                    }
                    snode.AppendChild(login);
                    XmlAddElement(snode, "connections", serv.NoConnections.ToString());

                    XmlAddElement(snode, "needsgroup", serv.NeedsGroup.ToString());

                    XmlAddElement(snode, "ssl", serv.UseSSL.ToString());

                    //add server to servers
                    servers.AppendChild(snode);
                }
                //add servers to servergroup
                servergroup.AppendChild(servers);

                //add servergroup to servergroups
                servergroups.AppendChild(servergroup);
            }

            ServerDoc.AppendChild(servergroups);
            ServerDoc.Save(Global.m_DataDirectory + "servers.xml");

            //options
            System.Xml.XmlDocument OptionsDoc = new System.Xml.XmlDocument();
            System.Xml.XmlDeclaration dec = OptionsDoc.CreateXmlDeclaration("1.0", "utf-8", "");
            OptionsDoc.AppendChild(dec);

            System.Xml.XmlElement options = OptionsDoc.CreateElement("options");

            XmlAddElement(options, "associate", Global.m_Options.AssociateWithNZB.ToString());
            XmlAddElement(options, "autoprune", Global.m_Options.AutoPrune.ToString());
            XmlAddElement(options, "idledelay", Global.m_Options.IdleDelay.ToString());
            XmlAddElement(options, "limitattempts", Global.m_Options.LimitAttempts.ToString());
            XmlAddElement(options, "minitotray", Global.m_Options.MinimizeToTray.ToString());
            XmlAddElement(options, "retryattempts", Global.m_Options.RetryAttempts.ToString());
            XmlAddElement(options, "retryconnections", Global.m_Options.RetryConnections.ToString());
            XmlAddElement(options, "retrydelay", Global.m_Options.RetryDelay.ToString());
            XmlAddElement(options, "connectonstart", Global.m_Options.ConnectOnStart.ToString());
            XmlAddElement(options, "savepath", Global.m_Options.SavePath.ToString());
            XmlAddElement(options, "savefolder", Global.m_Options.SaveFolder.ToString());
            XmlAddElement(options, "deletenzb", Global.m_Options.DeleteNZB.ToString());
            XmlAddElement(options, "disconnectidle", Global.m_Options.DisconnectOnIdle.ToString());
            XmlAddElement(options, "monitorfolder", Global.m_Options.MonitorFolder.ToString());
            XmlAddElement(options, "monitorpath", Global.m_Options.MonitorPath.ToString());
            XmlAddElement(options, "pausepar2", Global.m_Options.PausePar2.ToString());

            XmlAddElement(options, "downloadoffset", ((((double)m_ServerManager.LifetimeBytesReceived / 1024) / 1024) + m_TotalDownloadOffset).ToString());

            XmlAddElement(options, "savewindowstatus", Menu_Main_SaveWindowStatus.Checked.ToString());
            if( Menu_Main_SaveWindowStatus.Checked)
            {
                XmlAddElement(options, "height", Height.ToString());
                XmlAddElement(options, "width", Width.ToString());

                int xLoc = this.Location.X;
                int yLoc = this.Location.Y;
                if (xLoc + this.Width < 0)
                {
                    xLoc = 0;
                }
                if (yLoc + this.Height < 0)
                {
                    yLoc = 0;
                }
                XmlAddElement(options, "xloc", xLoc.ToString());
                XmlAddElement(options, "yloc", yLoc.ToString());
                bool maximized = false;
                if (this.WindowState == FormWindowState.Maximized)
                {
                    maximized = true;
                }
                XmlAddElement(options, "maximized", maximized.ToString());

                XmlAddElement(options, "connections_height", Panel_Connections.Height.ToString());
                XmlAddElement(options, "connections_width_server", chServer.Width.ToString());
                XmlAddElement(options, "connections_width_number", chID.Width.ToString());
                XmlAddElement(options, "connections_width_status", chConnStatus.Width.ToString());
                XmlAddElement(options, "connections_width_progress", chProgress.Width.ToString());
                XmlAddElement(options, "connections_width_speed", chSpeed.Width.ToString());

                XmlAddElement(options, "queue_width_article", chArticle.Width.ToString());
                XmlAddElement(options, "queue_width_size", chSize.Width.ToString());
                XmlAddElement(options, "queue_width_parts", chParts.Width.ToString());
                XmlAddElement(options, "queue_width_status", chStatus.Width.ToString());
                XmlAddElement(options, "queue_width_date", chDate.Width.ToString());
                XmlAddElement(options, "queue_width_groups", chGroups.Width.ToString());
            }

            OptionsDoc.AppendChild(options);

            OptionsDoc.Save(Global.m_DataDirectory + "options.xml");
        }
Esempio n. 56
0
		public static Asn1OutXml2 CreateDocument(string encoding)
		{
			System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
			doc.AppendChild(doc.CreateXmlDeclaration("1.0", encoding, null));
			return new Asn1OutXml2(doc);
		}
Esempio n. 57
0
 public static ResidualsDataSet22 CreateDocument(string encoding)
 {
     System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
     doc.AppendChild(doc.CreateXmlDeclaration("1.0", encoding, null));
     return new ResidualsDataSet22(doc);
 }
Esempio n. 58
0
		protected virtual void WriteToStream(System.IO.Stream stream, PersistenceFlags flags)
		{
//			System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(stream, System.Text.Encoding.UTF8);
//			
//			writer.Formatting = System.Xml.Formatting.Indented;
//			writer.WriteStartDocument();
//			writer.WriteStartElement("settings");
//
//			writer.WriteStartElement("items");
//			writer.WriteAttributeString("schemaversion", "1");
//			
//			foreach (PersistableItem item in m_Dictionary.Values)
//			{
//				if ( (flags & PersistenceFlags.OnlyChanges) == PersistenceFlags.OnlyChanges &&
//					item.IsChanged == false)
//					continue;
//
//				writer.WriteStartElement("item");
//				writer.WriteAttributeString("name", item.Name);
//				writer.WriteAttributeString("type", item.Type.FullName);
//				writer.WriteAttributeString("schemaversion", "1");
//				writer.WriteString(item.Validator.ValueToString(item.Value));
//				writer.WriteEndElement();
//			}
//
//			writer.WriteEndElement();
//
//			writer.WriteEndElement();
//			writer.WriteEndDocument();
//			writer.Flush();


			System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
			doc.AppendChild(doc.CreateElement("settings"));
			WriteToXmlElement(doc.DocumentElement, flags);

			System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(stream, System.Text.Encoding.UTF8);
			writer.Formatting = System.Xml.Formatting.Indented;
			doc.WriteTo(writer);
			writer.Flush();
		}
Esempio n. 59
0
        /// <summary>
        /// Returns an Xml document containing information on all of the functions in the TemplateGen
        /// type from the current assembly
        /// </summary>
        /// <returns></returns>
        public string GetFunctionsXml()
        {
            object obj = CurrentAssembly.CreateInstance(_ProjectNamespace + ".TemplateGen");
            Type objType = obj.GetType();

            MethodInfo[] methods = objType.GetMethods(BindingFlags.Public | BindingFlags.Static);

            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            System.Xml.XmlNode rootNode = doc.CreateNode(System.Xml.XmlNodeType.Element, "functions", "");

            foreach (MethodInfo method in methods)
            {
                System.Xml.XmlNode functionNode = doc.CreateNode(System.Xml.XmlNodeType.Element, "function", "");
                System.Xml.XmlAttribute attName = doc.CreateAttribute("name");
                attName.Value = method.Name;
                System.Xml.XmlAttribute attParamTypeName = doc.CreateAttribute("parametertypename");
                ParameterInfo[] parameters = method.GetParameters();

                switch (parameters.Length)
                {
                    case 0:
                        attParamTypeName.Value = "";
                        break;
                    case 1:
                        attParamTypeName.Value = parameters[0].ParameterType.ToString();
                        break;
                    default:
                        attParamTypeName.Value = parameters[0].ParameterType.ToString();
                        // TODO: Determine how to handle Template vs. normal functions WRT number of parameters
                        //throw new Exception("Template functions can't have more than one parameter: "+ method.Name);
                        break;
                }
                functionNode.Attributes.Append(attName);
                functionNode.Attributes.Append(attParamTypeName);
                rootNode.AppendChild(functionNode);
            }
            doc.AppendChild(rootNode);
            return doc.OuterXml;
        }
Esempio n. 60
0
        static void Main(string[] args)
        {
            int msgprocessthreads = 4;
            string pstfile = string.Empty;
            string pathtopstfiles = string.Empty;
            string pathtoemlfiles = string.Empty;
            string pathtoeidfile = string.Empty;
            string pathtofolderfile = string.Empty;
            string host = string.Empty;
            PSTMsgParser.PSTMsgParserData.SaveAsType saveas = PSTMsgParser.PSTMsgParserData.SaveAsType.Msg;
            string tracefile = string.Empty;
            uint offset = 0;
            uint count = Int32.MaxValue;
            bool isclient = false;
            bool isserver = true;
            bool docount = false;
            bool unicode = false;
            List<string> entryids = new List<string>();
            List<FolderData> folderdata = new List<FolderData>();
            string queuetype = ".netqueue";

            Logger.NLogger.Info("Running: {0}", Environment.CommandLine);

            for (int i = 0; i < args.Length; i++)
            {
                switch (args[i].ToUpper())
                {
                    case "-OFFSET":
                        offset = Convert.ToUInt32(args[i + 1]);
                        break;

                    case "-COUNT":
                        count = Convert.ToUInt32(args[i + 1]);
                        break;

                    case "-HOST":
                        host = args[i + 1];
                        break;

                    case "-CLIENT":
                        isclient = true;
                        break;

                    case "-SERVER":
                        isserver = true;
                        break;

                    case "-MSGPROCESSTHREADS":
                        msgprocessthreads = Convert.ToInt32(args[i + 1]);
                        break;

                    case "-INPUTDIR":
                        pathtopstfiles = args[i + 1];
                        pathtopstfiles = pathtopstfiles + (pathtopstfiles.EndsWith("\\") ? string.Empty : "\\");
                        break;

                    case "-OUTPUTDIR":
                        pathtoemlfiles = args[i + 1];
                        pathtoemlfiles = pathtoemlfiles + (pathtoemlfiles.EndsWith("\\") ? string.Empty : "\\");
                        break;

                    case "-QUEUETYPE":
                        queuetype = args[i + 1];
                        break;
                }
            }

            // added this code to support old Pst2Msg command line parameters
            List<string> pst2msgparameters = new List<string>() { "-E", "-F", "-M", "-O", "-R", "-S", "-T", "-U"};
            List<string> pst2msgargs = new List<string>();
            string pst2msgargument = string.Empty;
            for (int i = 0; i < args.Length; i++)
            {
                if (args[i].Length >= 2 && pst2msgparameters.Contains(args[i].ToUpper().Substring(0, 2)))
                {
                    if (pst2msgargument != string.Empty)
                    {
                        pst2msgargs.Add(pst2msgargument);
                        pst2msgargument = args[i];
                    }
                    else
                        pst2msgargument = args[i];
                }
                else
                    pst2msgargument += (" " + args[i]);
            }
            if (pst2msgargument != string.Empty)
                pst2msgargs.Add(pst2msgargument);
            for (int i = 0; i < pst2msgargs.Count; i++)
            {
                if (pst2msgargs[i].Length > 2)
                {
                    switch (pst2msgargs[i].ToUpper().Substring(0, 2))
                    {
                        case "-E":
                            if (pst2msgargs[i].Substring(0, 4).ToUpper() == "-EID")
                                pathtoeidfile = pst2msgargs[i].Substring(4);
                            break;

                        case "-F":
                            pstfile = pst2msgargs[i].Substring(2);
                            break;

                        case "-M":
                            if (pst2msgargs[i].Substring(2).ToUpper() == "MSG")
                                saveas = PSTMsgParser.PSTMsgParserData.SaveAsType.Msg;
                            else if (pst2msgargs[i].Substring(2).ToUpper() == "META")
                                saveas = PSTMsgParser.PSTMsgParserData.SaveAsType.Xml;
                            else if (pst2msgargs[i].Substring(2).ToUpper() == "ALL")
                                saveas = PSTMsgParser.PSTMsgParserData.SaveAsType.Xml | PSTMsgParser.PSTMsgParserData.SaveAsType.Msg;//						| PSTMsgParser.SaveAsType.Text;
                            else if (pst2msgargs[i].Substring(2).ToUpper() == "COUNT")
                                docount = true;
                            break;

                        case "-O":
                            if (pst2msgargs[i].ToUpper() != "-OFFSET" && pst2msgargs[i].ToUpper() != "-OUTPUTDIR")
                                pathtoemlfiles = pst2msgargs[i].Substring(2);
                            break;

                        case "-R":
                            if (pst2msgargs[i].ToUpper().Substring(0, 3) != "-RT")
                            {
                                pathtoemlfiles = pst2msgargs[i].Substring(2);
                                pathtoemlfiles = pathtoemlfiles + (pathtoemlfiles.EndsWith("\\") ? string.Empty : "\\");
                            }
                            break;

                        case "-S":
                            if (pst2msgargs[i].ToUpper() != "-SERVER")
                                pathtofolderfile = pst2msgargs[i].Substring(2);
                            break;

                        case "-T":
                            tracefile = pst2msgargs[i].Substring(2);
                            break;

                        case "-U":
                            unicode = true;
                            break;
                    }
                }
            }

            if (docount)
            {
                offset = 0;
                count = Int32.MaxValue;
                msgprocessthreads = 0;
                pathtoeidfile = string.Empty;
                pathtofolderfile = string.Empty;
            }

            if (pathtoeidfile != string.Empty)
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader(pathtoeidfile))
                {
                    String line = string.Empty;
                    while ((line = sr.ReadLine()) != null)
                    {
                        entryids.Add(line.Split(new char[]{'\t'})[1]);
                    }
                }
            }

            if (pathtofolderfile != string.Empty)
            {
                if (System.IO.File.Exists(pathtofolderfile))
                {
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(pathtofolderfile, true))
                    {
                        String line = string.Empty;
                        while ((line = sr.ReadLine()) != null)
                        {
                            folderdata.Add(new FolderData(line));
                        }
                    }
                }
            }

            if (msgprocessthreads > 0)
                isclient = true;

            KRSrcWorkflow.Interfaces.IWFMessageQueue<PSTMsgParser.PSTMsgParser> msgqueue = null;
            if (queuetype == "rabbbitmq" || queuetype == "msmq")
            {
                if (host == string.Empty)
                    KRSrcWorkflow.WFUtilities.SetHostAndIPAddress(System.Net.Dns.GetHostName(), ref host);
            //				if (queuetype == "rabbbitmq")
            //					msgqueue = new KRSrcWorkflow.MessageQueueImplementations.WFMessageQueue_RabbitMQ<PSTMsgParser.PSTMsgParser>(host, 5672, "msgqueue", KRSrcWorkflow.Abstracts.WFMessageQueueType.Publisher);
            //				else if (queuetype == "msmq")
            //					msgqueue = new KRSrcWorkflow.MessageQueueImplementations.WFMessageQueue_MessageQueue<PSTMsgParser.PSTMsgParser>(host, "msgqueue");
            }
            //			else
            //				msgqueue = new KRSrcWorkflow.MessageQueueImplementations.WFMessageQueue_Queue<PSTMsgParser.PSTMsgParser>();

            List<ManualResetEvent> msgthreadevents = new List<ManualResetEvent>();

            ManualResetEvent msgthreadinterrupt = null;
            if (isclient)
            {
                int threadid = 0;
                KRSrcWorkflow.WFGenericThread<PSTMsgParser.PSTMsgParser> iothread = null;
                if (msgprocessthreads > 0)
                {
                    msgthreadinterrupt = new ManualResetEvent(false);
                    for (int i = 0; i < msgprocessthreads; i++)
                    {
            //						ThreadPool.QueueUserWorkItem((iothread = new KRSrcWorkflow.WFThread<PSTMsgParser.PSTMsgParserData>(msgthreadinterrupt, msgqueue, null, threadid++)).Run);
                        msgthreadevents.Add(iothread.ThreadExitEvent);
                    }
                }
            }

            if (isserver)
            {
                string[] pstfiles = null;

                if (pathtopstfiles != string.Empty)
                    pstfiles = System.IO.Directory.GetFiles(pathtopstfiles, "*.pst", System.IO.SearchOption.TopDirectoryOnly);
                else if (pstfile != string.Empty)
                    pstfiles = new string[1] { pstfile };
                if (pstfiles.Length != 0)
                {
                    foreach (string pfile in pstfiles)
                    {
                        bool append = false;

                        Logger.NLogger.Info("Processing: {0}", pfile);
                        string exportdir = pathtoemlfiles;
                        if(pathtopstfiles != string.Empty)
                            exportdir = pathtoemlfiles + pfile.Substring((pfile.LastIndexOf("\\") == -1 ? 0 : pfile.LastIndexOf("\\")) + 1, pfile.Length - 5 - (pfile.LastIndexOf("\\") == -1 ? 0 : pfile.LastIndexOf("\\")));
                        Logger.NLogger.Info("Export Directory: {0}", exportdir);

                        if (docount)
                        {
                            if (System.IO.File.Exists(exportdir + "\\AllEntryID.txt"))
                                System.IO.File.Delete(exportdir + "\\AllEntryID.txt");

                            if (System.IO.File.Exists(exportdir + "\\FolderInfo.xml"))
                                System.IO.File.Delete(exportdir + "\\FolderInfo.xml");
                        }

                        if (!System.IO.Directory.Exists(exportdir + @"MSG\"))
                            System.IO.Directory.CreateDirectory(exportdir + @"MSG\");

                        if (!System.IO.Directory.Exists(exportdir + @"XML\"))
                            System.IO.Directory.CreateDirectory(exportdir + @"XML\");

                        Logger.NLogger.Info("Logon to PST store: {0}", pfile);
                        pstsdk.definition.pst.IPst rdopststore = null;
                        try
                        {
                            rdopststore = new pstsdk.layer.pst.Pst(pfile);
                        }
                        catch (Exception ex)
                        {
                            Logger.NLogger.ErrorException("Pst constructor failed for " + pfile, ex);
                        }
                        if (rdopststore != null)
                        {
                            Logger.NLogger.Info("Successfully logged on to PST store: {0}", pfile);
                            GetFolderData(rdopststore.OpenRootFolder(), string.Empty, folderdata.Count > 0 ? true : false, docount == true, ref folderdata);
                            uint totmessages = (uint)folderdata.Sum(x => x.NumMessages);
                            uint totattachments = (uint)folderdata.Sum(x => x.NumAttachments);

                            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                            System.Xml.XmlNode foldersnode = null;
                            if (docount == true)
                            {
                                doc = new System.Xml.XmlDocument();// Create the XML Declaration, and append it to XML document
                                System.Xml.XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "windows-1252", null);
                                doc.AppendChild(dec);
                                // create message element
                                System.Xml.XmlElement folders = doc.CreateElement("Folders");
                                foldersnode = doc.AppendChild(folders);
                            }
            //							List<pstsdk.definition.util.primitives.NodeID> foldernodeids = docount == true ? folderdata.Where(x => x.NodeId != 0).Select(x => x.NodeId).ToList() : rdopststore.Folders.Where(x => x.Node != 0).Select(x => x.Node).ToList();
            //							foreach (pstsdk.definition.util.primitives.NodeID foldernodeid in foldernodeids)
                            foreach (FolderData fd in folderdata)
                            {
                                pstsdk.definition.util.primitives.NodeID foldernodeid = fd.NodeId;

                                pstsdk.definition.pst.folder.IFolder folder = null;
                                try
                                {
                                    folder = rdopststore.OpenFolder(foldernodeid);
                                    if (docount == true)
                                        HandleFolder(folder, doc, foldersnode, fd.FolderPath, unicode);
                                    uint idx = 0;
                                    foreach (pstsdk.definition.pst.message.IMessage msg in folder.Messages)
                                    {
                                        if (docount == true)
                                        {
                                            using (System.IO.StreamWriter outfile = new System.IO.StreamWriter(exportdir + "\\AllEntryID.txt", append))
                                            {
                                                outfile.WriteLine(folder.EntryID.ToString() + "\t" + msg.EntryID.ToString());
                                            }
                                            append = true;
                                        }
                                        else
                                        {
                                            if (idx >= offset)
                                            {
            //												if ((entryids.Count == 0) || entryids.Contains(msg.EntryID.ToString()))
            //													msgqueue.Enqueue(new PSTMsgParser.PSTMsgParser(pfile, msg.Node, exportdir) { SaveAsTypes = PSTMsgParser.PSTMsgParser.SaveAsType.Msg | PSTMsgParser.PSTMsgParser.SaveAsType.Xml, SaveAttachments = false, FileToProcess = msg.Node.Value.ToString(), FolderPath = fd.FolderPath, ExportDirectory = exportdir, Pst2MsgCompatible = true });
                                            }
                                            idx++;
                                            if (count != UInt32.MaxValue)
                                            {
                                                if (idx == (offset + count))
                                                    break;
                                            }
                                        }
                                        msg.Dispose();
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Logger.NLogger.ErrorException("OpenFolder failed!" + " NodeId=" + foldernodeid + " FolderPath=" + folderdata.FirstOrDefault(x => x.NodeId == foldernodeid).FolderPath, ex);
                                }
                                finally
                                {
                                    if (folder != null)
                                        folder.Dispose();
                                }
                            }
                            if (docount == true)
                            {
                                System.Xml.XmlElement numoffolders = doc.CreateElement("numOfFolders");
                                System.Xml.XmlNode numoffoldersnode = foldersnode.AppendChild(numoffolders);
                                numoffoldersnode.InnerText = rdopststore.Folders.Count().ToString();

                                System.Xml.XmlElement numofmsgs = doc.CreateElement("numOfMsgs");
                                System.Xml.XmlNode numofmsgsnode = foldersnode.AppendChild(numofmsgs);
                                numofmsgsnode.InnerText = totmessages.ToString();

                                System.Xml.XmlElement numoftotattachments = doc.CreateElement("numOfAttachments");
                                System.Xml.XmlNode numoftotattachmentsnode = foldersnode.AppendChild(numoftotattachments);
                                numoftotattachmentsnode.InnerText = totattachments.ToString();

                                System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(exportdir + "\\FolderInfo.xml", System.Text.Encoding.GetEncoding("windows-1252"));
                                writer.Formatting = System.Xml.Formatting.Indented;
                                doc.Save(writer);
                                writer.Close();
                            }
                            rdopststore.Dispose();
                        }
                    }
                }
                else
                    Console.WriteLine("ERROR: No pst files found in directory " + pathtopstfiles);
                if (msgprocessthreads > 0)
                {
                    do
                    {
                        Thread.Sleep(100);
                    } while (msgqueue.Count > 0);
                    System.Diagnostics.Debug.WriteLine("Setting msgthreadinterrupt");
                    msgthreadinterrupt.Set();
                    WaitHandle.WaitAll(msgthreadevents.ToArray());
                    System.Diagnostics.Debug.WriteLine("All message threads exited");
                    Thread.Sleep(5000);
                }
            }
            else
                Thread.Sleep(Int32.MaxValue);
        }