private void Trans(XElement serializedExpression)
 {
     serializedExpression.Save("beforeTransit.xml");
     Console.WriteLine("beforeTransit:");
     Console.WriteLine(serializedExpression.ToString());
     Transit(serializedExpression);
     Console.WriteLine("afterTransit:");
     Console.WriteLine(serializedExpression.ToString());
     serializedExpression.Save("afterTransit.xml");
 }
Exemple #2
0
 /// <summary>
 /// 保存xml对象至文件
 /// </summary>
 /// <param name="xe">要保存的内容</param>
 /// <param name="xmlName">保存的文件名(不含扩展名)</param>
 /// <param name="isFullXmlName">True=程序内配置路径地址,只含文件名(不含扩展名)====False=文件绝对地址</param>
 public void SaveXml(XElement xe, string xmlName, bool isFullXmlName)
 {
     if (isFullXmlName)
     {
         CreatNewDirTry();
         xe.Save(GetXMLFileFullName(xmlName));
     }
     else
     {
         xe.Save(GetXMLFileFullName(xmlName));
     }
 }
Exemple #3
0
        private void saveNodeData(string thisID)
        {
            //IEnumerable<XElement> items  = getIDNodes(thisID);

            if (xTree == null)
            {
                xTree = new XElement("root", "");
            }
            XElement xEtappe = makeNewXEtappe(thisID);

            if (!(geaendert || picBsChanged))
            {
                return;
            }

/**********
*       // Etappe hinzufügen oder ersetzen ?
*       DialogResult result = new DialogResult();
*       if (etappeExist(xEtappe))
*               {result = MessageBox.Show("Etappe existiert schon - überschreiben?",
*                                  "Etappe existiert", MessageBoxButtons.YesNoCancel );
*               switch (result) {
*                       case DialogResult.Yes:
*                               break;
*                       case DialogResult.No:
*                               return;
*                       case DialogResult.Cancel:
*                               return;
*               }
*       } else {
**********/
            if (etappeExist(xEtappe)) // etappeExist erzeugt ggf. itemsID
            // etappe überschreiben:
            {
                foreach (XElement xelem in xTree.Elements())
                {
                    if (xelem.Element("ID").Value == thisID)
                    {
                        xelem.ReplaceWith(xEtappe);
                        continue;       // nur einmal, IDs sind eindeutig
                    }
                }
            }
            else
            {
                xTree.Add(xEtappe);
            }
            xTree.Save(XMLfile);
            picBsChanged = false;
            geaendert    = false;
        }
Exemple #4
0
 ///////////////////////////////////////////////////
 /// used to display functions in XML format
 public void XMLFunction(XElement tt)
 {
     try
     {
         XElement tt2 = new XElement("FunctionTable");
         if (repo == null)
             return;
         foreach (Elem elem in repo.locations)
         {
             if (elem.type != "function" || elem.type == "namespace")
                 continue;
             XElement t = new XElement(elem.type);
             XElement n = new XElement("Name");
             n.Value = elem.name;
             t.Add(n);
             XElement s = new XElement("Size");
             s.Value = (elem.end-elem.begin).ToString();
             t.Add(s);
             XElement c = new XElement("Complexity");
             c.Value = elem.complexity.ToString();
             t.Add(c);
             tt2.Add(t);
         }
         tt.Add(tt2);
         tt.Save("output.xml");
     }
     catch (Exception ex)
     {
         Console.Write("\n\n  {0}\n", ex.Message);
     }
 }
Exemple #5
0
 public static void Export(List<Dictionary<string, string>> data, string savepath, string format)
 {
     if (format == "JSON")
     {
         string json = JsonConvert.SerializeObject(data, Formatting.Indented);
         File.WriteAllText(savepath, json);
     }
     else if (format == "XML")
     {
         XElement root = new XElement("Items");
         foreach (var item in data)
         {
             XElement itemEle = new XElement("Item");
             itemEle.Add(item.Select(kv => new XElement(kv.Key, kv.Value)));
             root.Add(itemEle);
         }
         root.Save(savepath);
     }
     else if (format == "CSV")
     {
         string res = "";
         foreach (var item in data)
         {
             res += String.Join(", ",item.Select(kv => string.Format("\"{0}\"", kv.Value)))+"\n";
         }
         File.WriteAllText(savepath, res);
     }
 }
        public static void SetUserRoles(params UserRole[] roles)
        {
            var xml = new XElement("Roles",
                                   roles.Select(role => new XElement("Role", role)));

            xml.Save(TestUserRolesFilePath);
        }
        public static void Generate()
        {
            using (var db = new SalesContext())
            {
                var sales = new XElement("sales");

                foreach (var supermarket in db.Supermarkets)
                {
                    var sale = new XElement("sale");
                    sale.SetAttributeValue("vendor", supermarket.Name);

                    var records = db.Records
                        .Where(x => x.Supermarket.Id == supermarket.Id)
                        .GroupBy(x => x.Date)
                        .OrderBy(x => x.Key)
                        .Select(x => new { Date = x.Key, Sum = x.Sum(y => y.Quantity * y.UnitPrice) });

                    foreach (var record in records)
                    {
                        var summary = new XElement("summary");

                        summary.SetAttributeValue("date", record.Date.ToShortDateString());
                        summary.SetAttributeValue("total-sum", record.Sum.ToString("00"));

                        sale.Add(summary);
                    }

                    sales.Add(sale);
                }

                sales.Save(FilePath);
                //Console.WriteLine(File.ReadAllText(FilePath));
            }
        }
Exemple #8
0
 private void button1_Click(object sender, EventArgs e)
 {
     //var xml = new XElement("repos",
     //    new XComment("repozytorium wita"),
     //    new XElement("Repo",
     //        new XAttribute("type", "git"),
     //        new XElement("url", "http://costam.pl"),
     //        new XElement("user", "user1")
     //    ),
     //    new XElement("Repo",
     //        new XAttribute("type","svn"),
     //        new XElement("url", "http://costam2.pl"),
     //        new XElement("user", "user2")
     //     ),
     //     new XElement("Repo",
     //         new XAttribute("type", "tfs"),
     //         new XElement("url", "http://costam2.pl"),
     //         new XElement("user", "user3")
     //     )
     //     );
     var xml = new XElement("fibs",
         Fib(10).Select(x => new XElement(
             new XElement("value", x)
         ))
     );
     xml.Save("plik.xml");
     richTextBox1.Text = xml.ToString();
     foreach (var item in Fib(10))
     {
         richTextBox1.Text += item.ToString();
     }
 }
Exemple #9
0
    static void Main()
    {
        // reading the text file
        string filePath = "../../../7. PersonInfo.txt";
        List<string> personInfo = new List<string>();

        using (StreamReader reader = new StreamReader(filePath))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                personInfo.Add(line);
            }
        }

        // creating the catalog
        XElement catalogXml = new XElement("catalog",
            new XElement("person",
                new XElement("name", personInfo[0]),
                new XElement("address", personInfo[1]),
                new XElement("phoneNumber", personInfo[2])
                    )
            );

        catalogXml.Save("../../../7. Person.xml");
        Console.WriteLine("Person.xml created!");
    }
Exemple #10
0
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            Label  lblID      = (Label)GridView1.Rows[e.RowIndex].FindControl("lblID");
            string UserID     = Session["UserID"].ToString();
            string pathA      = ConfigurationManager.AppSettings["attactFile"].ToString();
            string pathServer = pathA + @"\XMLFileProjectN.xml";

            System.Xml.Linq.XElement XDoc = System.Xml.Linq.XElement.Load(pathServer);

            IEnumerable <System.Xml.Linq.XElement> Query = (from Q in XDoc.Elements("AttactID")
                                                            where Q.Element("ID").Value == lblID.Text.Trim() && Q.Element("UserID").Value == UserID
                                                            select Q).Distinct();

            if (Query.Count() > 0)
            {
                foreach (System.Xml.Linq.XElement X in Query)
                {
                    X.Remove();
                }


                XDoc.Save(pathServer);
            }
            HienThiDanhSachFileDinhKemTam();
        }
 public static void Main()
 {
     XElement directories = new XElement("directories");
     DirectoiesTravers("../../", directories);
     Console.WriteLine("New file is created with name - Directoies.xml");
     directories.Save("../../Directoies.xml");
 }
Exemple #12
0
        public static void SaveElement(string path, XElement element)
        {
            string targetFile = GetFullFilePath(path);
            string folder = Path.GetDirectoryName(targetFile);

            OnPreSave(new XmlDocFileEventArgs(targetFile));

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
            else if (File.Exists(targetFile))
            {
                if (_versions)
                {
                    ArchiveFile(
                        Path.GetDirectoryName(path),
                        Path.GetFileNameWithoutExtension(path),
                        false);
                }

                File.Delete(targetFile);
            }

            element.Save(targetFile);

            OnSaved(new XmlDocFileEventArgs(targetFile));
        }
Exemple #13
0
        public static void Search()
        {
            db = new BookStoreDbContext();

            var xmlQueries = XElement.Load(@"..\..\..\reviews-queries.xml").Elements();
            var result = new XElement("search-results");

            foreach (var xmlQuery in xmlQueries)
            {
                var queryInReviews = db.Reviews.AsQueryable();

                if (xmlQuery.Attribute("type").Value == "by-period")
                {
                    var startDate = DateTime.Parse(xmlQuery.Element("start-date").Value);
                    var endDate = DateTime.Parse(xmlQuery.Element("end-date").Value);

                    queryInReviews = queryInReviews.Where(r => r.CreatedOn >= startDate && r.CreatedOn <= endDate);
                }
                else if (xmlQuery.Attribute("type").Value == "by-author")
                {
                    var authorName = xmlQuery.Element("author-name").Value;

                    queryInReviews = queryInReviews.Where(r => r.Autor.Name == authorName);
                }

                var resultSet = queryInReviews
                    .OrderBy(r => r.CreatedOn)
                    .ThenBy(r => r.Content)
                    .Select(r => new
                    {
                        Date = r.CreatedOn,
                        Content = r.Content,
                        Book = new
                        {
                            Title = r.Book.Title,
                            // TODO ordre after select
                            Authors = r.Book.Authors
                                .OrderBy(a => a.Name)
                                .Select(a => a.Name),
                            ISBN = r.Book.ISBN,
                            URL = r.Book.WebSite
                        }
                    }).ToList();

                var xmlResultSet = new XElement("result-set");
                foreach (var reviewInResult in resultSet)
                {
                    var xmlReview=new XElement("review");
                    xmlReview.Add(new XElement("date", reviewInResult.Date.ToString("d-MMM-yyyy")));
                    xmlReview.Add(new XElement("content", reviewInResult.Content));

                    xmlResultSet.Add(xmlReview);
                }
                result.Add(xmlResultSet);


            }

            result.Save(@"..\..\..\reviews-search-results.xml");
        }
        public void Export(ICollection<ICollection<Review>> resultSets, string pathToSaveXml)
        {
            var searchResultsXml = new XElement("search-results");

            foreach (var resultSet in resultSets)
            {
                var resultSetXml = new XElement("result-set");

                foreach (var review in resultSet)
                {
                    var reviewXml = new XElement("review",
                        new XElement("date", review.DateOfCreation.ToString(DateTimeFormat, this.usDtfi)),
                        new XElement("content", review.Content));

                    var reviewBook = review.Book;
                    var bookXml = new XElement("book",
                        new XElement("title", reviewBook.Title));

                    this.AddAuthorsXElement(reviewBook, bookXml);
                    this.AddIsbnXElement(reviewBook, bookXml);
                    this.AddOfficialWebSiteXElement(reviewBook, bookXml);

                    reviewXml.Add(bookXml);
                    resultSetXml.Add(reviewXml);
                }

                searchResultsXml.Add(resultSetXml);
            }

            searchResultsXml.Save(new StreamWriter(pathToSaveXml, false, Encoding.UTF8));
        }
Exemple #15
0
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            Label  lblID      = (Label)GridView1.Rows[e.RowIndex].FindControl("lblID");
            string UserID     = Session["UserID"].ToString();
            string pathA      = ConfigurationManager.AppSettings["attactFile"].ToString();
            string pathServer = pathA + @"\XMLFileSystem.xml";

            //System.Xml.Linq.XElement XDoc = System.Xml.Linq.XElement.Load(Server.MapPath("~/XML/XMLFileSystem.xml"));
            System.Xml.Linq.XElement XDoc = System.Xml.Linq.XElement.Load(pathServer);

            IEnumerable <System.Xml.Linq.XElement> Query = (from Q in XDoc.Elements("AttactID")
                                                            where Q.Element("ID").Value == lblID.Text.Trim() && Q.Element("UserID").Value == UserID
                                                            select Q).Distinct();


            // Check the count is grether thae equal 1
            if (Query.Count() > 0)
            {
                // Remove the element
                foreach (System.Xml.Linq.XElement X in Query)
                {
                    X.Remove();
                }

                // Save the Xml File
                //XDoc.Save(Server.MapPath("~/XML/XMLFileSystem.xml"));
                // XDoc.Save(Server.MapPath("~/AttactFilePDN/XML/XMLFileSystem.xml"));
                XDoc.Save(pathServer);
            }

            HienThiFileDinhKem();
        }
Exemple #16
0
        public void Load_XmlFile_To_List()
        {
            string configPath = Environment.CurrentDirectory + "\\UrlList.xml";
            BanUrlList.Clear();
            if(!File.Exists(configPath))
            {
                XElement tmp = new XElement("BanUrlList");
                tmp.Save(configPath);
            }

            try
            {
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(configPath);
                XmlElement root = xmldoc.DocumentElement;

                XmlNodeList nodes = root.ChildNodes;
                foreach (XmlNode node in nodes)
                {
                    string Url = node.InnerText;
                    BanUrlList.Add(Url);
                }
            }
            catch (IOException ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
        private static string ConvertXElementToString(XElement xElement)
        {
            if (xElement == null)
            {
                throw new ArgumentNullException("xElement");
            }

            // Convert the xml to a string.
            string xmlResult;
            using (var memoryStream = new MemoryStream())
            {
                using (var writer = new StreamWriter(memoryStream, Encoding.UTF8))
                {
                    xElement.Save(writer);
                }

                xmlResult = Encoding.UTF8.GetString(memoryStream.ToArray());
            }

            if (!string.IsNullOrWhiteSpace(xmlResult) &&
                xmlResult.StartsWith(ByteOrderMarkUtf8))
            {
                xmlResult = xmlResult.Remove(0, ByteOrderMarkUtf8.Length);
            }

            return xmlResult;
        }
 static void Main()
 {
     DirectoryInfo directory = new DirectoryInfo(@"../../../../02.XMLProcessingIn.NET");
     XElement dirXml = new XElement("directory");
     dirXml.Add(TraverseDirectory(directory));
     dirXml.Save("../../../dirsX.xml");
 }
        static void Main()
        {
            //Write a program to traverse given directory and write to a XML file its contents together with all subdirectories and files.
            //Use tags <file> and <dir> with attributes. Use XDocument, XElement and XAttribute.
            XElement directoryXml =
                new XElement("root-dir",
                    new XAttribute("path", "C:/Example"),
                    new XElement("dir",
                        new XAttribute("name", "docs"),
                        new XElement("file",
                            new XAttribute("name", "tutorial.pdf")),
                        new XElement("file",
                            new XAttribute("name", "TODO.txt")),
                        new XElement("file",
                            new XAttribute("name", "Presentation.pptx"))),
                    new XElement("dir",
                        new XAttribute("name", "photos"),
                        new XElement("file",
                            new XAttribute("name", "friends.jpg")),
                        new XElement("file",
                            new XAttribute("name", "the_cake.jpg"))
                        )
                    );

            Console.WriteLine(directoryXml);
            directoryXml.Save("../../../directoryXml.xml");
        }
    static void Main(string[] args)
    {
        XNamespace ns = "http://linqinaction.net";
        XNamespace anotherNS = "http://publishers.org";

        XElement booksXml = new XElement(
            XName.Get("books", "http://bookstore.org"));
        XElement bookLINQ = new XElement(ns + "book",
            new XElement(ns + "title", "LINQ in Action"),
            new XElement(ns + "author", "Manning"),
            new XElement(ns + "author", "Steve Eichert"),
            new XElement(ns + "author", "Jim Wooley"),
            new XElement(anotherNS + "publisher", "Manning")
        );
        booksXml.Add(bookLINQ);

        XElement bookSilverlight = new XElement(ns + "book",
            new XElement(ns + "title", "Silverlight in Action"),
            new XElement(ns + "author", "Pete Brown"),
            new XElement(anotherNS + "publisher", "Manning")
        );
        booksXml.Add(bookSilverlight);

        System.Console.WriteLine(booksXml);

        booksXml.Save("../../books.xml");
    }
        private void SaveMenuItem_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();

            //XmlSerializer ser = new XmlSerializer(typeof(List<Item>));
            sfd.Filter     = "XML files (.xml) | *.xml";
            sfd.DefaultExt = ".xml";
            Nullable <bool> result = sfd.ShowDialog();

            if (result == true)
            {
                //TextWriter writer = new StreamWriter(sfd.FileName);
                //ser.Serialize(writer, itemList);
                //writer.Close();
                List <System.Xml.Linq.XElement> intNodeList = new List <System.Xml.Linq.XElement>();
                foreach (var item in itemList)
                {
                    intNodeList.Add(new System.Xml.Linq.XElement("Item", new System.Xml.Linq.XElement("ItemName", item.Name),
                                                                 new System.Xml.Linq.XElement("ItemDescription", item.Description),
                                                                 new System.Xml.Linq.XElement("ItemCategory", item.Category),
                                                                 new System.Xml.Linq.XElement("ItemPrice", item.Price)));
                }
                System.Xml.Linq.XElement externalNode = new System.Xml.Linq.XElement("ItemsCollection", intNodeList);
                externalNode.Save(sfd.FileName);
            }
        }
Exemple #22
0
        public DataSafe(string path, string name)
        {
            Ints = new IntGetter(this);
            Longs = new LongGetter(this);
            Bools = new BoolGetter(this);
            Strings = new StringGetter(this);
            Doubles = new DoubleGetter(this);

            path = path + Path.DirectorySeparatorChar + name;
            if(!path.EndsWith(".xml",true,System.Globalization.CultureInfo.CurrentCulture))
                path +=".xml";

            this.path = path;
            this.names = new HashSet<string>();
            if (!File.Exists(path))
            {
                data = new XElement(name);
                data.Save(path);
            }
            else
            {
                data = XElement.Load(path);
                foreach (XElement elem in data.Descendants())
                {
                    names.Add(elem.Name.ToString());
                }
            }
        }
Exemple #23
0
        // creates folder, .xml file, and inserts data
        public static bool CreateXmlFile(string root, XElement fileSystemTree)
        {


            string pathString = System.IO.Path.Combine(root, "XMLFolder");

            System.IO.Directory.CreateDirectory(pathString);

            string fileName = "XMLFile.xml";
            // Using Combine to add the file name to the path.
            pathString = System.IO.Path.Combine(pathString, fileName);


            if (!System.IO.File.Exists(pathString))
            {
                using (System.IO.FileStream fs = System.IO.File.Create(pathString))
                {

                    fileSystemTree.Save(fs);
                    return true;
                }
            }
            else
            {
                return false;
            }


        }
Exemple #24
0
        public void SaveConfiguration(string filepath, MidiTouchMessage[] fm)
        {
            try
            {
                _fingerMessages = fm;

                XElement configuration = new XElement("MidiTouchSettings");

                for (int i = 0; i < 5; i++)
                {
                    XElement finger = new XElement("Finger" + (i + 1));

                    finger.Add(new XElement("XCntrl", _fingerMessages[i].MessageX.MidiCtrlr.ToString() ),
                        new XElement("XChannel", _fingerMessages[i].MessageX.MidiChannel.ToString() ),
                        new XElement("XMinVal", _fingerMessages[i].MessageX.MinValue.ToString() ),
                        new XElement("XMaxVal", _fingerMessages[i].MessageX.MaxValue.ToString() ),
                        new XElement("YCntrl", _fingerMessages[i].MessageY.MidiCtrlr.ToString() ),
                        new XElement("YChannel", _fingerMessages[i].MessageY.MidiChannel.ToString() ),
                        new XElement("YMinVal", _fingerMessages[i].MessageY.MinValue.ToString() ),
                        new XElement("YMaxVal", _fingerMessages[i].MessageY.MaxValue.ToString()) );

                    configuration.Add(finger);
                }

                configuration.Save(filepath);
            }
            catch(Exception ex)
            {
                throw (ex);
            }
                
        }
Exemple #25
0
        static void Main()
        {
            // Creating person.txt
            string textFilePath = "../../person.txt";
            StreamWriter writer = new StreamWriter(textFilePath);

            using (writer)
            {
                writer.WriteLine("Иван Иванов");
                writer.WriteLine("Перущица, ул.'Освобождение', №1");
                writer.WriteLine("+359888123456");
            }

            StreamReader reader = new StreamReader(textFilePath);

            using (reader)
            {
                var person = new
                {
                    Name = reader.ReadLine(),
                    Address = reader.ReadLine(),
                    Phone = reader.ReadLine()
                };

                XElement personXElement = new XElement("Person",
                    new XElement("Name", person.Name),
                    new XElement("Address", person.Address),
                    new XElement("Phone", person.Phone));

                personXElement.Save("../../person.xml");
            }
        }
        public void GenerateSalesReportByVendor(Dictionary<string, Dictionary<DateTime, Decimal>> reports, string outputPath)
        {
            var sales = GetSales(reports);
            var allSales = new XElement("sales", sales);

            allSales.Save(outputPath);
        }
Exemple #27
0
        protected override void backupXML(string plikXml,string serwis,string typ)
        {
            if (numKolekcja.Count > 0)
                    {
                    var xmlFile = new XElement(typ.Replace(' ', '_'), new XAttribute("Data", DateTime.Now.ToString("dd-MM-yyyy")));

                    foreach (var elem in numKolekcja)
                        {
                        var x = new XElement("Row",
                            new XAttribute("Nazwa", elem.Nazwa),
                            new XAttribute("Symbol", elem.Symbol),
                            new XAttribute("Data", elem.Data),
                            new XAttribute("Kurs", elem.Kurs),
                            new XAttribute("MaxMin", elem.MaxMin),
                            new XAttribute("Zmiana", elem.Zmiana),
                            new XAttribute("ZmianaProc", elem.ZmianaProc),
                            new XAttribute("Otwarcie", elem.Otwarcie),
                            new XAttribute("Odniesienie", elem.Odniesienie),
                            new XAttribute("Wolumen", elem.Wolumen),
                            new XAttribute("Obrot", elem.Obrot),
                            new XAttribute("Transakcje", elem.Transakcje));

                        xmlFile.Add(x);
                        }

                    xmlFile.Save(plikXml);
                    Loger.dodajDoLogaInfo(serwis + typ + messages.xmlOutOK);
                    }
                else
                    Loger.dodajDoLogaError(serwis + typ + messages.xmlOutFail);
        }
Exemple #28
0
        private static void Main(string[] args)
        {
            IEnumerable<Process> processlist = Process.GetProcesses().AsEnumerable();

            XElement xElement = new XElement("ProcessList");
            foreach (var process in Process.GetProcesses().AsEnumerable())
            {
                xElement.Add(new XElement("Process", process.ProcessName));
                var StartInfo = new XElement("StartInfo");
                StartInfo.Add(new XElement("FileName", process.StartInfo.FileName));
                StartInfo.Add(new XElement("Arguments", process.StartInfo.Arguments));
                StartInfo.Add(new XElement("CreateNoWindow", process.StartInfo.CreateNoWindow));
                StartInfo.Add(new XElement("Domain", process.StartInfo.Domain));
                StartInfo.Add(new XElement("EnvironmentVariables", process.StartInfo.EnvironmentVariables));
                StartInfo.Add(new XElement("ErrorDialog", process.StartInfo.ErrorDialog));
                StartInfo.Add(new XElement("ErrorDialogParentHandle", process.StartInfo.ErrorDialogParentHandle));
                StartInfo.Add(new XElement("LoadUserProfile", process.StartInfo.LoadUserProfile));
                StartInfo.Add(new XElement("Password", process.StartInfo.Password));
                StartInfo.Add(new XElement("RedirectStandardError", process.StartInfo.RedirectStandardError));
                StartInfo.Add(new XElement("Arguments", process.StartInfo.WorkingDirectory));
                StartInfo.Add(new XElement("IsFixedSize", process.StartInfo.Verbs.IsFixedSize));
                StartInfo.Add(new XElement("FileName", process.StartInfo.FileName));
                StartInfo.Add(new XElement("FileName", process.StartInfo.FileName));
                StartInfo.Add(new XElement("FileName", process.StartInfo.FileName));
                StartInfo.Add(new XElement("FileName", process.StartInfo.FileName));
                StartInfo.Add(new XElement("FileName", process.StartInfo.FileName));
                StartInfo.Add(new XElement("FileName", process.StartInfo.FileName));
                StartInfo.Add(new XElement("FileName", process.StartInfo.FileName));
                xElement.Add(StartInfo);
            }

            xElement.Save(string.Format(@"D:\temp\Process{0}.xml", DateTime.Now.ToString("yyyyMMddHHmmss")));
        }
        public override Task WriteToStreamAsync(Type type, object value,
            Stream writeStream, System.Net.Http.HttpContent content,
            System.Net.TransportContext transportContext)
        {
            return Task.Factory.StartNew(() =>
            {
                if (typeof(IEnumerable<IData>).IsAssignableFrom(type))
                {
                    Type elementType = type.GetGenericArguments().First();

                    var resultXElement = new XElement("Data");

                    foreach (var element in (value as IEnumerable))
                    {
                        resultXElement.Add(GetXNode(elementType.Name, element).Root);
                    }

                    resultXElement.Save(writeStream);
                    return;
                }

                XDocument xNode = GetXNode(type.Name, value);

                xNode.Save(writeStream);
            });
        }
        void ExportSites()
        {
            if (!System.IO.File.Exists(filepath))
            {
                MessageBox.Show("File does not exist anymore!\r\nPlease select a new file.");
                return;
            }

            XElement root_old = XElement.Load(filepath);

            if (!ValidateXmlFile(root_old))
            {
                MessageBox.Show("The XML file selected does not appear to be a valid Filezilla XML file.\r\nIt might be that the file does not have any site manager entries.");
                return;
            }

            if (diaSaveXml.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                XElement servers_new = new XElement(servers_element);
                XElement root_new = new XElement(root_element,
                    servers_new);

                foreach (string item in clstSites.CheckedItems)
                {
                    XElement server = (from server_old in root_old.Descendants(server_element)
                                       where server_old.Element(name_element).Value == item
                                       select server_old).FirstOrDefault();

                    servers_new.Add(server);
                }

                root_new.Save(diaSaveXml.FileName);
            }
        }
 public void ExitSave()
 {
     XElement xRoot = new XElement("ChosenPath");
     XAttribute xPath = new XAttribute("Path", filepath);
     xRoot.Add(xPath);
     xRoot.Save("Config.xml");
 }
Exemple #32
0
 public static void Main()
 {
     string[] directories = Directory.GetDirectories("..\\..\\..\\");
     XElement document = new XElement("directories");
     CreateXML(directories, document);
     document.Save("../../dirs.xml");
 }
Exemple #33
0
 public XmlTuple(XElement xml)
 {
     var cms = ChunkedMemoryStream.Create();
     xml.Save(cms);
     cms.Position = 0;
     Reader = new StreamReader(cms);
 }
Exemple #34
0
        public void ValidateSave()
        {
            WorldEntity world = createTestWorld();

            XElement xElement = WorldTransformer.Instance.ToXElement(world, TransformerSettings.WorldNamespace + "World");

            xElement.Save("unittestsave.xml", SaveOptions.OmitDuplicateNamespaces);

            XmlSchemaSet schemaSet = new XmlSchemaSet();

            schemaSet.Add(null, "WorldSchema1.xsd");

            XDocument xDocument = new XDocument(xElement);
            xDocument.AddAnnotation(SaveOptions.OmitDuplicateNamespaces);
            xDocument.Save("unittest2.xml", SaveOptions.OmitDuplicateNamespaces);

            XElement x1 = new XElement(TransformerSettings.WorldNamespace + "Outer");
            x1.Add(new XElement(TransformerSettings.WorldNamespace + "Inner"));
            x1.Save("unittest3.xml", SaveOptions.OmitDuplicateNamespaces);
            string val = "";
            xDocument.Validate(schemaSet, (o, vea) => {
                val += o.GetType().Name + "\n";
                val += vea.Message + "\n";
            }, true);

            Assert.AreEqual("", val);
        }
Exemple #35
0
        public static void CompareWithBaseline(this System.Xml.Linq.XElement x, string baseline)
        {
            string Temp = "../../Temp.xml";

            x.Save(Temp);
            StreamReader srBaseline = null;
            StreamReader srActual   = null;

            try
            {
                srBaseline = File.OpenText("../../Baselines/" + baseline);
                srActual   = File.OpenText(Temp);
                string strBaseline = srBaseline.ReadToEnd();
                string strActual   = srActual.ReadToEnd();
                //
                // If you see this exception this means ...
                //   ... that the self-checking sample suite has been modified.
                //
                if (strBaseline != strActual)
                {
                    throw new LinqToXsdAPIException();
                }
            }
            finally
            {
                srBaseline.Close();
                srActual.Close();
                if (File.Exists(Temp))
                {
                    File.Delete(Temp);
                }
            }
        }
Exemple #36
0
        static private void saveXmlFile(System.Xml.Linq.XElement xml)
        {
            if (File.Exists("result.xml"))
            {
                File.Delete("result.xml");
            }

            xml.Save("result.xml");
            Console.WriteLine("XML dosyası kaydedildi..");
        }
Exemple #37
0
        /// <summary>
        /// Carrega a definição do relatório.
        /// </summary>
        /// <param name="localReport"></param>
        protected override void LoadDefinition(Microsoft.Reporting.WebForms.LocalReport localReport)
        {
            if (Document is Colosoft.Reports.IReportDefinitionContainer)
            {
                //if (_alteraStatus != null)
                //    _alteraStatus("Carregando definição");

                System.Xml.Linq.XElement root = null;

                using (var stream = ((Colosoft.Reports.IReportDefinitionContainer)Document).GetDefinition())
                    root = System.Xml.Linq.XElement.Load(stream, System.Xml.Linq.LoadOptions.None);

                const string reportDefinition = "http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition";

                var codeElement = root.Elements(System.Xml.Linq.XName.Get("Code", reportDefinition)).FirstOrDefault();

                const string translateMethodHeader = "Public Function Translate";
                const string endMethod             = "End Function";
                int          index = 0;

                if (codeElement != null &&
                    !codeElement.IsEmpty &&
                    !string.IsNullOrEmpty(codeElement.Value) &&
                    (index = codeElement.Value.IndexOf(translateMethodHeader, StringComparison.InvariantCultureIgnoreCase)) >= 0)
                {
                    var endIndex = codeElement.Value.IndexOf(endMethod, index, StringComparison.InvariantCultureIgnoreCase);

                    // Alterar o método de tradução
                    codeElement.Value = codeElement.Value.Substring(0, index) +
                                        @"Public Function Translate(ByVal instance As Object, ByVal enumTypeName As String) As String
                            return Glass.Relatorios.UI.Web.GlassReportViewer.Translate(instance, enumTypeName)
                          End Function" + codeElement.Value.Substring(endIndex + endMethod.Length);
                }

                const string translate2MethodHeader = "Public Function Translate2";
                index = 0;

                if (codeElement != null &&
                    !codeElement.IsEmpty &&
                    !string.IsNullOrEmpty(codeElement.Value) &&
                    (index = codeElement.Value.IndexOf(translate2MethodHeader, StringComparison.InvariantCultureIgnoreCase)) >= 0)
                {
                    var endIndex = codeElement.Value.IndexOf(endMethod, index, StringComparison.InvariantCultureIgnoreCase);

                    // Alterar o método de tradução
                    codeElement.Value = codeElement.Value.Substring(0, index) +
                                        @"Public Function Translate2(ByVal instance As Object, ByVal enumTypeName As String, ByVal groupKey As String) As String
                            return Glass.Relatorios.UI.Web.GlassReportViewer.Translate2(instance, enumTypeName, groupKey)
                          End Function" + codeElement.Value.Substring(endIndex + endMethod.Length);
                }

                var codeModules =
                    root.Elements(System.Xml.Linq.XName.Get("CodeModules", reportDefinition))
                    .FirstOrDefault();

                if (codeModules == null)
                {
                    codeModules = new XElement(XName.Get("CodeModules", reportDefinition));
                    root.Add(codeModules);
                }

                codeModules.Add(new XElement(XName.Get("CodeModule", reportDefinition))
                {
                    Value = "Colosoft.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d3b3c440aed9b980"
                });

                codeModules.Add(new XElement(XName.Get("CodeModule", reportDefinition))
                {
                    Value = "Colosoft.Reports, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ec8331ec4228d300"
                });

                codeModules.Add(new XElement(XName.Get("CodeModule", reportDefinition))
                {
                    Value = "Colosoft.Reports.Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b0156e5c4c7a6003"
                });

                codeModules.Add(new XElement(XName.Get("CodeModule", reportDefinition))
                {
                    Value = "Glass.Relatorios, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
                });

                codeModules.Add(new XElement(XName.Get("CodeModule", reportDefinition))
                {
                    Value = "Glass.Relatorios.UI.Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
                });

                using (var stream = new System.IO.MemoryStream())
                {
                    root.Save(stream);
                    stream.Seek(0, System.IO.SeekOrigin.Begin);
                    localReport.LoadReportDefinition(stream);
                }
            }
        }