/// <summary>
        /// 探测本地数据库文件是否存在,不存在则创建
        /// </summary>
        private void DetectLocalDbFile()
        {
            //检查目录和文件是否存在
            string containerDirectory = Directory.GetParent(LocalDbFilePath).FullName;

            if (!Directory.Exists(containerDirectory))
            {
                Directory.CreateDirectory(containerDirectory);
            }
            if (!File.Exists(LocalDbFilePath))
            {
                File.Create(LocalDbFilePath);
            }
            //检查文件的内容是否符合要求,不符合则在文件中建立新的xml文档,并建立Persons节点作为根节点
            XDocument xd = null;

            try
            {
                xd = XDocument.Load(LocalDbFilePath);
                XElement xe = xd.Element("DeviceCommands");
            }
            catch (Exception)
            {
                xd = new XDocument(new XElement("DeviceCommands"));
            }
            finally
            {
                xd?.Save(LocalDbFilePath);
            }
        }
Exemplo n.º 2
0
 public void Save(string filename)
 {
     if (File.Exists(filename))
     {
         Console.WriteLine("Output file already exists");
         return;
     }
     document?.Save(filename);
 }
Exemplo n.º 3
0
        /// <summary>
        /// Runs this instance.
        /// </summary>
        /// <returns></returns>
        public CppModule Run(CppModule groupSkeleton, string[] additionalCompilationArguments)
        {
            _group = groupSkeleton;
            Logger.Message("Config files changed.");

            const string progressMessage = "Parsing C++ headers starts, please wait...";

            StreamReader xmlReader = null;

            try
            {
                Logger.Progress(15, progressMessage);

                var configRootHeader = Path.Combine(OutputPath, _configRoot.Id + ".h");

                xmlReader = _gccxml.Process(configRootHeader, additionalCompilationArguments);
                if (xmlReader != null)
                {
                    Parse(xmlReader);
                }

                Logger.Progress(30, progressMessage);
            }
            catch (Exception ex)
            {
                Logger.Error(null, "Unexpected error", ex);
            }
            finally
            {
                xmlReader?.Dispose();

                // Write back GCCXML document on the disk
                using (var stream = File.OpenWrite(Path.Combine(OutputPath, GccXmlFileName)))
                {
                    GccXmlDoc?.Save(stream);
                }
                Logger.Message("Parsing headers is finished.");
            }


            // Track number of included macros for statistics
            foreach (var cppInclude in _group.Includes)
            {
                IncludeMacroCounts.TryGetValue(cppInclude.Name, out int count);
                foreach (var cppDefine in cppInclude.Macros)
                {
                    count++;
                }
                IncludeMacroCounts[cppInclude.Name] = count;
            }

            return(_group);
        }
        protected void btnConvert_OnClick(object sender, EventArgs e)
        {
            var books = new List <Book>
            {
                new Book
                {
                    Title     = "红楼梦",
                    Genre     = "小说",
                    FirstName = "曹",
                    LastName  = "雪芹",
                    Price     = 9.99
                },
                new Book
                {
                    Title     = "西游记",
                    Genre     = "小说",
                    FirstName = "吴",
                    LastName  = "承恩",
                    Price     = 20.13
                },
                new Book
                {
                    Title     = "三国演义",
                    Genre     = "小说",
                    FirstName = "罗",
                    LastName  = "贯中",
                    Price     = 30.82
                },
                new Book()
                {
                    Title     = "水浒传",
                    Genre     = "小说",
                    FirstName = "施",
                    LastName  = "耐庵",
                    Price     = 15.45
                }
            };

            var xDoc = new XDocument(
                new XDeclaration("1.0", "UTF-8", "yes"),
                new XElement("bookstore",
                             books.Select(
                                 b => new XElement("book", new XAttribute("genre", b.Genre),
                                                   new XElement("title", b.Title),
                                                   new XElement("author",
                                                                new XElement("first-name", b.FirstName),
                                                                new XElement("last-name", b.LastName)),
                                                   new XElement("price", b.Price)))));

            xDoc?.Save(Server.MapPath("books_4.xml"));
        }
Exemplo n.º 5
0
    public void Delete(int id)
    {
        XDocument packagesXml = EnsureStorage(out var packagesFile);
        XElement? packageXml  = packagesXml?.Root?.Elements("package")
                                .FirstOrDefault(x => x.AttributeValue <int>("id") == id);

        if (packageXml == null)
        {
            return;
        }

        packageXml.Remove();

        packagesXml?.Save(packagesFile);
    }
Exemplo n.º 6
0
        /// <summary>
        /// Runs this instance.
        /// </summary>
        /// <returns></returns>
        public CppModule Run(CppModule groupSkeleton, StreamReader xmlReader)
        {
            _group = groupSkeleton;
            Logger.Message("Config files changed.");

            const string progressMessage = "Parsing C++ headers starts, please wait...";

            try
            {
                Logger.Progress(15, progressMessage);

                if (xmlReader != null)
                {
                    Parse(xmlReader);
                }

                Logger.Progress(30, progressMessage);
            }
            catch (Exception ex)
            {
                Logger.Error(null, "Unexpected error", ex);
            }
            finally
            {
                // Write back GCCXML document on the disk
                using (var stream = File.OpenWrite(GccXmlFileName))
                {
                    GccXmlDoc?.Save(stream);
                }

                Logger.Message("Parsing headers is finished.");
            }


            // Track number of included macros for statistics
            foreach (var cppInclude in _group.Includes)
            {
                IncludeMacroCounts.TryGetValue(cppInclude.Name, out var count);
                count += cppInclude.Macros.Count();
                IncludeMacroCounts[cppInclude.Name] = count;
            }

            return(_group);
        }
 private void SetProvisioningTemplatePropertyValue(string name, string value)
 {
     if (!string.IsNullOrWhiteSpace(name) && !string.IsNullOrWhiteSpace(itemPath))
     {
         try
         {
             XDocument xml = null;
             using (var stream = new FileStream(itemPath, FileMode.Open, FileAccess.Read))
             {
                 xml = XmlHelper.SetProvisioningTemplatePropertyValue(stream, name, value);
             }
             xml?.Save(itemPath);
         }
         catch (Exception e)
         {
             //TODO trace
         }
     }
 }
Exemplo n.º 8
0
        public bool SaveFile(string path, IDataModule passCollection)
        {
            if (passCollection == null)
            {
                return(false);
            }

            try
            {
                XDocument xDoc = _ParseToXml(passCollection);
                xDoc?.Save(path);

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Exemplo n.º 9
0
        private void buttonOK_Click(object sender, EventArgs e)
        {
            // leave the app
            if (_plugins == null)
            {
                return;
            }

            try
            {
                foreach (PluginInfo pluginInfo in _plugins)
                {
                    pluginInfo.UpdateXElement();
                }
                _xDoc?.Save(_metaFile);
            }
            catch (Exception)
            {
                // just do nothing if anything bad happened
            }
            Application.Exit();
        }
Exemplo n.º 10
0
        public virtual Paragraph InsertParagraph(Paragraph p)
        {
            #region Styles
            XDocument style_document;

            if (p.styles.Count() > 0)
            {
                Uri style_package_uri = new Uri("/word/styles.xml", UriKind.Relative);
                if (!Document.package.PartExists(style_package_uri))
                {
                    PackagePart style_package = Document.package.CreatePart(style_package_uri, "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml", CompressionOption.Maximum);
                    using (TextWriter tw = new StreamWriter(style_package.GetStream()))
                    {
                        style_document = new XDocument
                                         (
                            new XDeclaration("1.0", "UTF-8", "yes"),
                            new XElement(XName.Get("styles", DocX.w.NamespaceName))
                                         );

                        style_document.Save(tw);
                    }
                }

                PackagePart styles_document = Document.package.GetPart(style_package_uri);
                using (TextReader tr = new StreamReader(styles_document.GetStream()))
                {
                    style_document = XDocument.Load(tr);
                    XElement styles_element = style_document.Element(XName.Get("styles", DocX.w.NamespaceName));

                    var ids = from d in styles_element.Descendants(XName.Get("style", DocX.w.NamespaceName))
                              let a = d.Attribute(XName.Get("styleId", DocX.w.NamespaceName))
                                      where a != null
                                      select a.Value;

                    foreach (XElement style in p.styles)
                    {
                        // If styles_element does not contain this element, then add it.

                        if (!ids.Contains(style.Attribute(XName.Get("styleId", DocX.w.NamespaceName)).Value))
                        {
                            styles_element.Add(style);
                        }
                    }
                }

                using (TextWriter tw = new StreamWriter(styles_document.GetStream()))
                    style_document.Save(tw);
            }
            #endregion

            XElement newXElement = new XElement(p.Xml);

            Xml.Add(newXElement);

            int index = 0;
            if (Document.paragraphLookup.Keys.Count() > 0)
            {
                index = Document.paragraphLookup.Last().Key;

                if (Document.paragraphLookup.Last().Value.Text.Length == 0)
                {
                    index++;
                }
                else
                {
                    index += Document.paragraphLookup.Last().Value.Text.Length;
                }
            }

            Paragraph newParagraph = new Paragraph(Document, newXElement, index);
            Document.paragraphLookup.Add(index, newParagraph);

            GetParent(newParagraph);

            return(newParagraph);
        }
Exemplo n.º 11
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            List <Room> rooms = new List <Room>();

            string[] roomList = new string[] {
                "../OgmoZelda/LoZ-1.oel",
                "../OgmoZelda/LoZ-2.oel",
                "../OgmoZelda/LoZ-3.oel",
                "../OgmoZelda/LoZ-4.oel",
                "../OgmoZelda/LoZ-5.oel",
                "../OgmoZelda/LoZ-6.oel",
                "../OgmoZelda/LoZ-7.oel",
                "../OgmoZelda/LoZ-8.oel",
                "../OgmoZelda/LoZ-9.oel",
                "../OgmoZelda/LoZ2-1.oel",
            };
            foreach (var room in roomList)
            {
                rooms.AddRange(readRooms(room, "../OgmoZelda/ZeldaRoom.oep", 16, 11, 12, 7));
            }

            roomList = new string[] {
                "../OgmoZelda/LttP1.oel", "../OgmoZelda/LttP10.oel", "../OgmoZelda/LttP11.oel", "../OgmoZelda/LttP12.oel",
                "../OgmoZelda/LttP13.oel", "../OgmoZelda/LttP14.oel", "../OgmoZelda/LttP15.oel", "../OgmoZelda/LttP16.oel",
                "../OgmoZelda/LttP17.oel", "../OgmoZelda/LttP18.oel", "../OgmoZelda/LttP19.oel", "../OgmoZelda/LttP2.oel",
                "../OgmoZelda/LttP20.oel", "../OgmoZelda/LttP21.oel", "../OgmoZelda/LttP22.oel", "../OgmoZelda/LttP3.oel",
                "../OgmoZelda/LttP4.oel", "../OgmoZelda/LttP5.oel", "../OgmoZelda/LttP6.oel", "../OgmoZelda/LttP7.oel",
                "../OgmoZelda/LttP8.oel", "../OgmoZelda/LttP9.oel",
            };
            foreach (var room in roomList)
            {
                rooms.AddRange(readRooms(room, "../OgmoZelda/ZeldaRoom.oep", 16, 16, 11, 10));
            }
            roomList = new string[] {
                "../OgmoZelda/LA1.oel", "../OgmoZelda/LA2.oel", "../OgmoZelda/LA3.oel",
                "../OgmoZelda/LA4.oel", "../OgmoZelda/LA5.oel", "../OgmoZelda/LA6.oel", "../OgmoZelda/LA7.oel",
                "../OgmoZelda/LA8.oel",
            };
            foreach (var room in roomList)
            {
                rooms.AddRange(readRooms(room, "../OgmoZelda/ZeldaRoom.oep", 10, 8, 8, 6));
            }

            int         ii      = 0;
            List <Room> flipped = new List <Room>();

            foreach (var room in rooms)
            {
                // room.toBitmap().Save("room" + ii + ".png");
                room.changeSize(12, 10);
                //  room.toBitmap().Save("room" + ii + "A.png");
                Room temp = room.FlipUpDown();
                flipped.Add(temp);
                flipped.Add(room.FlipLeftRight());
                flipped.Add(temp.FlipLeftRight());
                ii++;
            }
            rooms.AddRange(flipped);
            Console.WriteLine(rooms.Count);
            var output = Factorization.Factorize(rooms, 65);

            roomClusters = output.Item1;
            componentVec = output.Item2;

            foreach (var roomtype in roomClusters.Keys)
            {
                roomTypes.Add(roomtype);
            }
            roomTypes.Sort();
            listBox1.DataSource = roomTypes;
            XDocument componentDoc = new XDocument(new XElement("root"));

            foreach (var component in componentVec)
            {
                componentDoc.Root.Add(new XElement(component.Key, new XAttribute("dim1", component.Value.GetLength(0)), new XAttribute("dim2", component.Value.GetLength(1)), toString(component.Value)));
            }
            componentDoc.Save("components.xml");
            XDocument clusterDoc = new XDocument(new XElement("root"));

            foreach (var cluster in roomClusters)
            {
                foreach (var bunch in cluster.Value)
                {
                    var clusterBunch = new XElement("Cluster", new XAttribute("name", cluster.Key), new XAttribute("id", bunch.Key));
                    foreach (var room in bunch.Value)
                    {
                        clusterBunch.Add(room.toXML());
                    }
                    clusterDoc.Root.Add(clusterBunch);
                }
            }
            clusterDoc.Save("clusters.xml");
            XDocument noclusterDoc = new XDocument(new XElement("root"));

            foreach (var cluster in roomClusters)
            {
                var clusterBunch = new XElement("Cluster", new XAttribute("name", cluster.Key), new XAttribute("id", 0));
                foreach (var bunch in cluster.Value)
                {
                    foreach (var room in bunch.Value)
                    {
                        clusterBunch.Add(room.toXML());
                    }
                }
                noclusterDoc.Root.Add(clusterBunch);
            }
            noclusterDoc.Save("noclusters.xml");
        }
Exemplo n.º 12
0
 public void Save(string filePath) => _csproj.Save(filePath);
Exemplo n.º 13
0
 public void Save(XDocument doc, string filename)
 {
     doc.Save(filename);
 }
Exemplo n.º 14
0
        public bool Save()
        {
            lock (semaphore)
            {
                try
                {
                    // make bakup
                    if (File.Exists(path))
                    {
                        File.Copy(path, path + ".bak", true);
                    }

                    var doc = new XDocument(
                        new XElement("IPs",
                                     IPs
                                     //.ToArray()
                                     .Where(ip => ip != null)
                                     .Select(ip => {
                        if (ip.Attacks == null)
                        {
                            ip.Attacks = new HashSet <Attacks>();
                        }

                        //System.Console.WriteLine(ip.IP);

                        return(new XElement("IP",
                                            new XAttribute("Anonymous", ip.Anonymous),
                                            new XAttribute("Antivirus", ip.Antivirus),
                                            new XAttribute("Firewall", ip.Firewall),
                                            new XAttribute("Hostname", !string.IsNullOrEmpty(ip.Hostname) ? ip.Hostname : "unknown"),
                                            new XAttribute("IP", !string.IsNullOrEmpty(ip.IP) ? ip.IP : ""),
                                            new XAttribute("IPSpoofing", ip.IPSpoofing),
                                            new XAttribute("LastAttack", ip.LastAttack),
                                            new XAttribute("LastUpdate", ip.LastUpdate),
                                            new XAttribute("Money", ip.Money),
                                            new XAttribute("Name", ip.Name == null ? "" : ip.Name),
                                            new XAttribute("RepOnSuccess", ip.RepOnSuccess),
                                            new XAttribute("SDK", ip.SDK),
                                            new XAttribute("Spam", ip.Spam),
                                            new XAttribute("Spyware", ip.Spyware),
                                            new XAttribute("WinChance", ip.WinChance),
                                            new XElement("Attacks", ip.Attacks
                                                         .Select(att => new XElement("Attack",
                                                                                     new XAttribute("Dt", att.Dt == null ? vHackApi.IPs.MinDateTime : att.Dt),
                                                                                     new XAttribute("IP", att.IP == null ? "" : att.IP),
                                                                                     new XAttribute("MoneyOwned", att.MoneyOwned),
                                                                                     new XAttribute("MoneyWon", att.MoneyWon),
                                                                                     new XAttribute("RepWon", att.RepWon))))));
                    })));

                    doc.Save(path);

                    return(true);
                }
                catch (Exception e)
                {
                    System.Console.WriteLine(e.ToString());
                    return(false);
                }
            }
        }
Exemplo n.º 15
0
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try {
                Global.Debug = "start";
                SPWeb web = properties.Feature.Parent as SPWeb;
                if (web == null)
                {
                }


                SPList listKundkort = web.Lists.TryGetList("Kundkort");
                Global.Debug = "Kundkort";
                SPList listAktiviteter = web.Lists.TryGetList("Aktiviteter");
                Global.Debug = "Aktiviteter";

                if (!web.Properties.ContainsKey("activatedOnce"))
                {
                    web.Properties.Add("activatedOnce", "true");
                    web.Properties.Update();
                    Global.Debug = "set activatedOnce flag";

                    #region sätt default-kommun-värden
                    if (municipals.Count > 0)
                    {
                        Global.WriteLog("Kommuner existerar redan", EventLogEntryType.Information, 1000);
                    }
                    else
                    {
                        municipals.Add("uppsala", new Municipal {
                            AreaCode = "018", Name = "Uppsala", RegionLetter = "C"
                        });
                        municipals.Add("borlänge", new Municipal {
                            AreaCode = "0243", Name = "Borlänge", RegionLetter = "W"
                        });
                    }
                    Global.Debug = "added municipals";
                    #endregion

                    #region hämta listor
                    SPList listAgare = web.Lists.TryGetList("Ägare");
                    Global.Debug = "Ägare";
                    SPList listKontakter = web.Lists.TryGetList("Kontakter");
                    Global.Debug = "Kontakter";
                    SPList listAdresser = web.Lists.TryGetList("Adresser");
                    Global.Debug = "Adresser";
                    SPList listSidor = web.Lists.TryGetList("Webbplatssidor");
                    Global.Debug = "Webbplatssidor";
                    SPList listNyheter = web.Lists.TryGetList("Senaste nytt");
                    Global.Debug = "Senaste nytt";
                    //SPList listBlanketter = web.Lists.TryGetList("Blanketter");
                    SPList listGenvagar = web.Lists.TryGetList("Genvägar");
                    Global.Debug = "Genvägar";
                    SPList listGruppkopplingar = web.Lists.TryGetList("Gruppkopplingar");
                    Global.Debug = "Gruppkopplingar";

                    SPList[] lists = new SPList[] { listAgare, listKontakter, listAdresser, listSidor, listNyheter, listGenvagar, listGruppkopplingar };
                    int      i     = 0;
                    foreach (SPList list in lists)
                    {
                        i++;
                        if (list == null)
                        {
                            Global.WriteLog("Lista " + i.ToString() + " är null", EventLogEntryType.Error, 2000);
                        }
                    }
                    #endregion

                    if (listSidor != null)
                    {
                        #region startsida
                        string compoundUrl = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Start.aspx");

                        //* Define page payout
                        _wikiFullContent = FormatBasicWikiLayout();
                        Global.Debug     = "Skapa startsida";
                        SPFile startsida = listSidor.RootFolder.Files.Add(compoundUrl, SPTemplateFileType.WikiPage);

                        // Header
                        string relativeUrl = web.ServerRelativeUrl == "/" ? "" : web.ServerRelativeUrl;
                        _wikiFullContent = _wikiFullContent.Replace("[[HEADER]]", "<img alt=\"vinter\" src=\"" + relativeUrl + "/SiteAssets/profil_ettan_vinter_557x100.jpg\" style=\"margin: 5px;\"/><img alt=\"hj&auml;rta\" src=\"" + relativeUrl + "/SiteAssets/heart.gif\" style=\"margin: 5px;\"/>");

                        #region Nyheter
                        ListViewWebPart wpAnnouncements = new ListViewWebPart();
                        wpAnnouncements.ListName = listNyheter.ID.ToString("B").ToUpper();
                        //wpAnnouncements.ViewGuid = listNyheter.GetUncustomizedViewByBaseViewId(0).ID.ToString("B").ToUpper();
                        //wpAnnouncements.ViewGuid = listNyheter.DefaultView.ID.ToString("B").ToUpper();
                        wpAnnouncements.ViewGuid = string.Empty;
                        Guid wpAnnouncementsGuid = AddWebPartControlToPage(startsida, wpAnnouncements);
                        AddWebPartMarkUpToPage(wpAnnouncementsGuid, "[[COL1]]");
                        #endregion

                        #region Genvägar
                        ListViewWebPart wpLinks = new ListViewWebPart();
                        wpLinks.ListName = listGenvagar.ID.ToString("B").ToUpper();
                        //wpLinks.ViewGuid = listGenvagar.GetUncustomizedViewByBaseViewId(0).ID.ToString("B").ToUpper();
                        //wpLinks.ViewGuid = listGenvagar.DefaultView.ID.ToString("B").ToUpper();
                        wpLinks.ViewGuid = string.Empty;
                        Guid wpLinksGuid = AddWebPartControlToPage(startsida, wpLinks);
                        AddWebPartMarkUpToPage(wpLinksGuid, "[[COL2]]");
                        #endregion

                        startsida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent;
                        startsida.Item.UpdateOverwriteVersion();
                        Global.Debug = "Startsida skapad";
                        #endregion

                        #region lägg till försäljningsställe
                        string compoundUrl2 = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Lägg till försäljningsställe.aspx");

                        //* Define page payout
                        _wikiFullContent = FormatSimpleWikiLayout();
                        Global.Debug     = "Skapa nybutiksida";
                        SPFile nybutiksida = listSidor.RootFolder.Files.Add(compoundUrl2, SPTemplateFileType.WikiPage);

                        // Header
                        _wikiFullContent = _wikiFullContent.Replace("[[COL1]]",
                                                                    @"<h1>Sida för att lägga till nya försäljningsställen</h1>
<h2>STEG 1 - Lägg till ägare</h2>
[[WP1]]
<h2>STEG 2 - Lägg till adressuppgifter</h2>
[[WP2]]
<h2>STEG 3 - Lägg till kontaktperson</h2>
[[WP3]]
<h2>STEG&#160;4 - Lägg till försäljningsstället</h2>
[[WP4]]");

                        Global.Debug = "wpAgare";
                        XsltListViewWebPart wpAgare = new XsltListViewWebPart();
                        wpAgare.ChromeType = PartChromeType.None;
                        wpAgare.ListName   = listAgare.ID.ToString("B").ToUpper();
                        wpAgare.ViewGuid   = listAgare.Views["Tilläggsvy"].ID.ToString("B").ToUpper();
                        wpAgare.Toolbar    = "Standard";
                        Guid wpAgareGuid = AddWebPartControlToPage(nybutiksida, wpAgare);
                        AddWebPartMarkUpToPage(wpAgareGuid, "[[WP1]]");

                        Global.Debug = "wpAdresser";
                        XsltListViewWebPart wpAdresser = new XsltListViewWebPart();
                        wpAdresser.ChromeType = PartChromeType.None;
                        wpAdresser.ListName   = listAdresser.ID.ToString("B").ToUpper();
                        wpAdresser.ViewGuid   = listAdresser.Views["Tilläggsvy"].ID.ToString("B").ToUpper();
                        wpAdresser.Toolbar    = "Standard";
                        Guid wpAdresserGuid = AddWebPartControlToPage(nybutiksida, wpAdresser);
                        AddWebPartMarkUpToPage(wpAdresserGuid, "[[WP2]]");

                        Global.Debug = "wpKontakter";
                        XsltListViewWebPart wpKontakter = new XsltListViewWebPart();
                        wpKontakter.ChromeType = PartChromeType.None;
                        wpKontakter.ListName   = listKontakter.ID.ToString("B").ToUpper();
                        wpKontakter.ViewGuid   = listKontakter.Views["Tilläggsvy"].ID.ToString("B").ToUpper();
                        wpKontakter.Toolbar    = "Standard";
                        Guid wpKontakterGuid = AddWebPartControlToPage(nybutiksida, wpKontakter);
                        AddWebPartMarkUpToPage(wpKontakterGuid, "[[WP3]]");

                        Global.Debug = "wpKundkort";
                        XsltListViewWebPart wpKundkort = new XsltListViewWebPart();
                        wpKundkort.ChromeType = PartChromeType.None;
                        wpKundkort.ListName   = listKundkort.ID.ToString("B").ToUpper();
                        wpKundkort.ViewGuid   = listKundkort.Views["Tilläggsvy"].ID.ToString("B").ToUpper();
                        wpKundkort.Toolbar    = "Standard";
                        Guid wpKundkortGuid = AddWebPartControlToPage(nybutiksida, wpKundkort);
                        AddWebPartMarkUpToPage(wpKundkortGuid, "[[WP4]]");

                        nybutiksida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent;
                        nybutiksida.Item.UpdateOverwriteVersion();
                        Global.Debug = "Nybutiksida skapad";

                        #endregion

                        #region mitt försäljningsställe
                        string compoundUrl3 = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Mitt försäljningsställe.aspx");//* Define page payout
                        _wikiFullContent = FormatSimpleWikiLayout();
                        Global.Debug     = "Skapa minbutiksida";
                        SPFile minbutiksida = listSidor.RootFolder.Files.Add(compoundUrl3, SPTemplateFileType.WikiPage);

                        Global.Debug = "wpMinButik";
                        MinButikWP wpMinButik = new MinButikWP();
                        wpMinButik.ChromeType = PartChromeType.None;
                        wpMinButik.Adresser   = "Adresser";
                        wpMinButik.Agare      = "Ägare";
                        wpMinButik.Kontakter  = "Kontakter";
                        wpMinButik.Kundkort   = "Kundkort";
                        Guid wpMinButikGuid = AddWebPartControlToPage(minbutiksida, wpMinButik);
                        AddWebPartMarkUpToPage(wpMinButikGuid, "[[COL1]]");

                        minbutiksida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent;
                        minbutiksida.Item.UpdateOverwriteVersion();
                        Global.Debug = "Nybutiksida skapad";
                        #endregion

                        #region skapa tillsynsrapport
                        //string compoundUrl4 = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Skapa tillsynsrapport.aspx");//* Define page payout
                        //_wikiFullContent = FormatSimpleWikiLayout();
                        //Global.Debug = "Skapa tillsynsrapport";
                        //SPFile skapatillsynsida = listSidor.RootFolder.Files.Add(compoundUrl4, SPTemplateFileType.WikiPage);

                        //Global.Debug = "wpTillsyn";
                        //TillsynWP wpTillsyn = new TillsynWP();
                        //wpTillsyn.ChromeType = PartChromeType.None;
                        //Guid wpTillsynGuid = AddWebPartControlToPage(skapatillsynsida, wpTillsyn);
                        //AddWebPartMarkUpToPage(wpTillsynGuid, "[[COL1]]");

                        //skapatillsynsida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent;
                        //skapatillsynsida.Item.UpdateOverwriteVersion();
                        //Global.Debug = "Skapatillsynsida skapad";
                        #endregion

                        #region inställningar
                        string compoundUrl5 = string.Format("{0}/{1}", listSidor.RootFolder.ServerRelativeUrl, "Inställningar.aspx");//* Define page payout
                        _wikiFullContent = FormatSimpleWikiLayout();
                        Global.Debug     = "Inställningar";
                        SPFile installningarsida = listSidor.RootFolder.Files.Add(compoundUrl5, SPTemplateFileType.WikiPage);

                        Global.Debug = "wpSettings";
                        SettingsWP wpSettings = new SettingsWP();
                        wpSettings.ChromeType = PartChromeType.None;
                        Guid wpSettingsGuid = AddWebPartControlToPage(installningarsida, wpSettings);
                        AddWebPartMarkUpToPage(wpSettingsGuid, "[[COL1]]");

                        installningarsida.Item[SPBuiltInFieldId.WikiField] = _wikiFullContent;
                        installningarsida.Item.UpdateOverwriteVersion();
                        Global.Debug = "Installningarsida skapad";
                        #endregion
                    }

                    #region debugdata

                    Global.Debug = "ägare";
                    SPListItem item = listAgare.AddItem();
                    item["Title"] = "TESTÄGARE AB";
                    item.Update();

                    try {
                        Global.Debug      = "kontakt";
                        item              = listKontakter.AddItem();
                        item["Title"]     = "Testsson";
                        item["FirstName"] = "Test";
                        item["Email"]     = "*****@*****.**";
                        item.Update();

                        item              = listKontakter.AddItem();
                        item["Title"]     = "Jansson";
                        item["FirstName"] = "Peter";
                        item["Email"]     = "*****@*****.**";
                        item.Update();
                    }
                    catch (Exception ex) {
                        Global.WriteLog("Message:\r\n" + ex.Message + "\r\n\r\nStacktrace:\r\n" + ex.StackTrace, EventLogEntryType.Error, 2001);
                    }

                    Global.Debug  = "adress";
                    item          = listAdresser.AddItem();
                    item["Title"] = "Testgatan 13b";
                    item.Update();

                    #endregion

                    #region nyhet
                    Global.Debug  = "nyhet";
                    item          = listNyheter.AddItem();
                    item["Title"] = "Vår online plattform för tillsyn av tobak och folköl håller på att starta upp här";
                    item["Body"]  = @"Hej!

Nu har första stegen till en online plattform för tillsyn av tobak och folköl tagits. Här kan du som försäljningsställe ladda hem blanketter och ta del av utbildningsmaterial.

" + web.Title + " kommun";
                    item.Update();
                    #endregion

                    #region länkar
                    Global.Debug  = "länkar";
                    item          = listGenvagar.AddItem();
                    Global.Debug  = "Blanketter";
                    item["Title"] = "Blanketter";
                    item["URL"]   = web.ServerRelativeUrl + "/Blanketter, Blanketter";
                    item.Update();
                    item          = listGenvagar.AddItem();
                    Global.Debug  = "Utbildningsmaterial";
                    item["Title"] = "Utbildningsmaterial";
                    item["URL"]   = web.ServerRelativeUrl + "/Utbildningsmaterial, Utbildningsmaterial";
                    item.Update();
                    #endregion

                    #region sätt kundnummeregenskaper
                    Global.Debug = "löpnummer";
                    web.Properties.Add("lopnummer", "1000");
                    Global.Debug = "prefixformel";
                    web.Properties.Add("prefixFormula", "%B%R-%N");
                    Global.Debug = "listAdresserGUID";
                    web.Properties.Add("listAdresserGUID", listAdresser.ID.ToString());
                    Global.Debug = "listAgareGUID";
                    web.Properties.Add("listAgareGUID", listAgare.ID.ToString());
                    Global.Debug = "gruppkopplingar";
                    web.Properties.Add("listGruppkopplingarGUID", listGruppkopplingar.ID.ToString());
                    try {
                        Municipal m = municipals[web.Title.ToLower()];
                        web.Properties.Add("municipalAreaCode", m.AreaCode);
                        web.Properties.Add("municipalRegionLetter", m.RegionLetter);
                    }
                    catch { }
                    Global.Debug = "properties";
                    web.Properties.Update();
                    #endregion
                }
                else
                {
                    Global.WriteLog("Redan aktiverad", EventLogEntryType.Information, 1000);
                }

                #region modify template global
                Global.Debug = "ensure empty working directory";
                DirectoryInfo diFeature = new DirectoryInfo(@"C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\LAYOUTS\UPCOR.TillsynKommun");
                string        webid     = web.Url.Replace("http://", "").Replace('/', '_');
                string        dirname   = @"workdir_" + webid;
                Global.Debug = "dir: " + dirname;
                DirectoryInfo diWorkDir = diFeature.CreateSubdirectory(dirname);

                if (!diWorkDir.Exists)
                {
                    diWorkDir.Create();
                }

                XNamespace xsf  = "http://schemas.microsoft.com/office/infopath/2003/solutionDefinition";
                XNamespace xsf3 = "http://schemas.microsoft.com/office/infopath/2009/solutionDefinition/extensions";
                XNamespace xd   = "http://schemas.microsoft.com/office/infopath/2003";

                #endregion

                #region modify template tillsyn
                {
                    Global.Debug = "deleting files";
                    foreach (FileInfo fi in diWorkDir.GetFiles())
                    {
                        fi.Delete();
                    }

                    Global.Debug = "extract";
                    Process p = new Process();
                    p.StartInfo.RedirectStandardOutput = true;
                    p.StartInfo.UseShellExecute        = false;
                    p.StartInfo.FileName = @"C:\Program Files\7-Zip\7z.exe";
                    //string filename = diTillsyn.FullName + @"\75841904-0c67-4118-826f-b1319db35c6a.xsn";
                    string filename = diFeature.FullName + @"\4BEB6318-1CE0-47BE-92C2-E9815D312C1A.xsn";

                    p.StartInfo.Arguments = "e \"" + filename + "\" -y -o\"" + diWorkDir.FullName + "\"";
                    bool start = p.Start();
                    p.WaitForExit();
                    if (p.ExitCode != 0)
                    {
                        Global.WriteLog(string.Format("7z Error:\r\n{0}\r\n\r\nFilename:\r\n{1}", p.StandardOutput.ReadToEnd(), filename), EventLogEntryType.Error, 1000);
                    }

                    Global.Debug = "get content type";
                    SPContentType ctTillsyn = listAktiviteter.ContentTypes[_tillsynName];

                    Global.Debug = "modify manifest";
                    XDocument doc            = XDocument.Load(diWorkDir.FullName + @"\manifest.xsf");
                    var       xDocumentClass = doc.Element(xsf + "xDocumentClass");
                    var       q1             = from extension in xDocumentClass.Element(xsf + "extensions").Elements(xsf + "extension")
                                               where extension.Attribute("name").Value == "SolutionDefinitionExtensions"
                                               select extension;
                    var node1 = q1.First().Element(xsf3 + "solutionDefinition").Element(xsf3 + "baseUrl");
                    node1.Attribute("relativeUrlBase").Value = web.Url + "/Lists/Aktiviteter/Tillsyn/";
                    var q2 = from dataObject in xDocumentClass.Element(xsf + "dataObjects").Elements(xsf + "dataObject")
                             where dataObject.Attribute("name").Value == "Kundkort"
                             select dataObject;
                    var node2 = q2.First().Element(xsf + "query").Element(xsf + "sharepointListAdapterRW");
                    node2.Attribute("sharePointListID").Value = "{" + listKundkort.ID.ToString() + "}";
                    var node3 = xDocumentClass.Element(xsf + "query").Element(xsf + "sharepointListAdapterRW");
                    node3.Attribute("sharePointListID").Value = "{" + listAktiviteter.ID.ToString() + "}";
                    node3.Attribute("contentTypeID").Value    = ctTillsyn.Id.ToString();
                    doc.Save(diWorkDir.FullName + @"\manifest.xsf");

                    Global.Debug = "modify view1";
                    XDocument doc2 = XDocument.Load(diWorkDir.FullName + @"\view1.xsl");
                    foreach (var d in doc2.Descendants("object"))
                    {
                        d.Attribute(xd + "server").Value = web.Url + "/";
                    }
                    doc2.Save(diWorkDir.FullName + @"\view1.xsl");

                    Global.Debug = "repack";
                    string   directive    = "directives_inspection_" + webid + ".txt";
                    string   cabinet      = "template_inspection_" + webid + ".xsn";
                    FileInfo fiDirectives = new FileInfo(diFeature.FullName + '\\' + directive);
                    if (fiDirectives.Exists)
                    {
                        fiDirectives.Delete();
                    }
                    using (StreamWriter sw = fiDirectives.CreateText()) {
                        sw.WriteLine(".OPTION EXPLICIT");
                        sw.WriteLine(".set CabinetNameTemplate=" + cabinet);
                        sw.WriteLine(".set DiskDirectoryTemplate=\"" + diFeature.FullName + "\"");
                        sw.WriteLine(".set Cabinet=on");
                        sw.WriteLine(".set Compress=on");
                        foreach (FileInfo file in diWorkDir.GetFiles())
                        {
                            sw.WriteLine('"' + file.FullName + '"');
                        }
                    }
                    Process p2 = new Process();
                    p2.StartInfo.RedirectStandardOutput = true;
                    p2.StartInfo.UseShellExecute        = false;
                    //p2.StartInfo.FileName = diTillsyn.FullName + @"\makecab.exe";
                    p2.StartInfo.FileName         = @"c:\windows\system32\makecab.exe";
                    p2.StartInfo.WorkingDirectory = diFeature.FullName;
                    p2.StartInfo.Arguments        = "/f " + fiDirectives.Name;
                    bool start2 = p2.Start();
                    p2.WaitForExit();
                    if (p.ExitCode != 0)
                    {
                        Global.WriteLog(string.Format("makecab Error:\r\n{0}", p2.StandardOutput.ReadToEnd()), EventLogEntryType.Error, 1000);
                    }

                    Global.Debug = "upload";
                    FileInfo fiTemplate = new FileInfo(diFeature.FullName + '\\' + cabinet);
                    if (fiTemplate.Exists)
                    {
                        using (FileStream fs = fiTemplate.OpenRead()) {
                            byte[] data = new byte[fs.Length];
                            fs.Read(data, 0, (int)fs.Length);
                            SPFile file = listAktiviteter.RootFolder.Files.Add("Lists/Aktiviteter/Tillsyn/template.xsn", data);
                            Global.Debug = "set file properties";
                            //file.Properties["vti_contenttag"] = "{6908F1AD-3962-4293-98BB-0AA4FB54B9C9},3,1";
                            file.Properties["ipfs_streamhash"] = "0NJ+LASyxjJGhaIwPftKfwraa3YBBfJoNUPNA+oNYu4=";
                            file.Properties["ipfs_listform"]   = "true";
                            file.Update();
                        }
                        Global.Debug = "set folder properties";
                        SPFolder folder = listAktiviteter.RootFolder.SubFolders["Tillsyn"];
                        folder.Properties["_ipfs_solutionName"]    = "template.xsn";
                        folder.Properties["_ipfs_infopathenabled"] = "True";
                        folder.Update();
                    }
                    else
                    {
                        Global.WriteLog("template.xsn missing", EventLogEntryType.Error, 1000);
                    }

                    //Global.Debug = "set default forms";
                    //// create our own array since it will be modified (which would throw an exception)
                    //var forms = new SPForm[listAktiviteter.Forms.Count];
                    //int j = 0;
                    //foreach (SPForm form in listAktiviteter.Forms) {
                    //    forms[j] = form;
                    //    j++;
                    //}
                    //foreach (var form in forms) {
                    //    SPFile page = web.GetFile(form.Url);
                    //    SPLimitedWebPartManager limitedWebPartManager = page.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
                    //    foreach (System.Web.UI.WebControls.WebParts.WebPart wp in limitedWebPartManager.WebParts) {
                    //        if (wp is BrowserFormWebPart) {
                    //            BrowserFormWebPart bfwp = (BrowserFormWebPart)wp.WebBrowsableObject;
                    //            bfwp.FormLocation = bfwp.FormLocation.Replace("/Item/", "/Tillsyn/");
                    //            limitedWebPartManager.SaveChanges(bfwp);

                    //            switch (form.Type) {
                    //                case PAGETYPE.PAGE_NEWFORM:
                    //                    listAktiviteter.DefaultNewFormUrl = form.ServerRelativeUrl;
                    //                    break;
                    //                case PAGETYPE.PAGE_EDITFORM:
                    //                    listAktiviteter.DefaultEditFormUrl = form.ServerRelativeUrl;
                    //                    break;
                    //                case PAGETYPE.PAGE_DISPLAYFORM:
                    //                    listAktiviteter.DefaultDisplayFormUrl = form.ServerRelativeUrl;
                    //                    break;
                    //            }
                    //        }
                    //    }
                    //}
                }
                #endregion

                #region modify template permit
                {
                    Global.Debug = "delete";
                    foreach (FileInfo fi in diWorkDir.GetFiles())
                    {
                        fi.Delete();
                    }

                    Global.Debug = "extract";
                    Process p = new Process();
                    p.StartInfo.RedirectStandardOutput = true;
                    p.StartInfo.UseShellExecute        = false;
                    p.StartInfo.FileName = @"C:\Program Files\7-Zip\7z.exe";
                    string filename = diFeature.FullName + @"\givepermit.xsn";

                    p.StartInfo.Arguments = "e \"" + filename + "\" -y -o\"" + diWorkDir.FullName + "\"";
                    bool start = p.Start();
                    p.WaitForExit();
                    if (p.ExitCode != 0)
                    {
                        Global.WriteLog(string.Format("7z Error:\r\n{0}\r\n\r\nFilename:\r\n{1}", p.StandardOutput.ReadToEnd(), filename), EventLogEntryType.Error, 1000);
                    }

                    Global.Debug = "get content type";
                    SPContentType ctPermit = listAktiviteter.ContentTypes[_permitName];

                    Global.Debug = "modify manifest";
                    XDocument doc            = XDocument.Load(diWorkDir.FullName + @"\manifest.xsf");
                    var       xDocumentClass = doc.Element(xsf + "xDocumentClass");
                    var       q1             = from extension in xDocumentClass.Element(xsf + "extensions").Elements(xsf + "extension")
                                               where extension.Attribute("name").Value == "SolutionDefinitionExtensions"
                                               select extension;
                    var node1 = q1.First().Element(xsf3 + "solutionDefinition").Element(xsf3 + "baseUrl");
                    node1.Attribute("relativeUrlBase").Value = web.Url + "/Lists/Aktiviteter/Ge%20försäljningstillstånd/";
                    var q2 = from dataObject in xDocumentClass.Element(xsf + "dataObjects").Elements(xsf + "dataObject")
                             where dataObject.Attribute("name").Value == "Kundkort"
                             select dataObject;
                    var node2 = q2.First().Element(xsf + "query").Element(xsf + "sharepointListAdapterRW");
                    node2.Attribute("sharePointListID").Value = "{" + listKundkort.ID.ToString() + "}";
                    var node3 = xDocumentClass.Element(xsf + "query").Element(xsf + "sharepointListAdapterRW");
                    node3.Attribute("sharePointListID").Value = "{" + listAktiviteter.ID.ToString() + "}";
                    node3.Attribute("contentTypeID").Value    = ctPermit.Id.ToString();
                    doc.Save(diWorkDir.FullName + @"\manifest.xsf");

                    //Global.Debug = "modify view1";
                    //XDocument doc2 = XDocument.Load(diWorkDir.FullName + @"\view1.xsl");
                    //foreach (var d in doc2.Descendants("object")) {
                    //    d.Attribute(xd + "server").Value = web.Url + "/";
                    //}
                    //doc2.Save(diWorkDir.FullName + @"\view1.xsl");

                    Global.Debug = "repack";
                    string   directive    = "directives_permit_" + webid + ".txt";
                    string   cabinet      = "template_permit_" + webid + ".xsn";
                    FileInfo fiDirectives = new FileInfo(diFeature.FullName + '\\' + directive);
                    if (fiDirectives.Exists)
                    {
                        fiDirectives.Delete();
                    }
                    using (StreamWriter sw = fiDirectives.CreateText()) {
                        sw.WriteLine(".OPTION EXPLICIT");
                        sw.WriteLine(".set CabinetNameTemplate=" + cabinet);
                        sw.WriteLine(".set DiskDirectoryTemplate=\"" + diFeature.FullName + "\"");
                        sw.WriteLine(".set Cabinet=on");
                        sw.WriteLine(".set Compress=on");
                        foreach (FileInfo file in diWorkDir.GetFiles())
                        {
                            sw.WriteLine('"' + file.FullName + '"');
                        }
                    }
                    Process p2 = new Process();
                    p2.StartInfo.RedirectStandardOutput = true;
                    p2.StartInfo.UseShellExecute        = false;
                    //p2.StartInfo.FileName = diTillsyn.FullName + @"\makecab.exe";
                    p2.StartInfo.FileName         = @"c:\windows\system32\makecab.exe";
                    p2.StartInfo.WorkingDirectory = diFeature.FullName;
                    p2.StartInfo.Arguments        = "/f " + fiDirectives.Name;
                    bool start2 = p2.Start();
                    p2.WaitForExit();
                    if (p.ExitCode != 0)
                    {
                        Global.WriteLog(string.Format("makecab Error:\r\n{0}", p2.StandardOutput.ReadToEnd()), EventLogEntryType.Error, 1000);
                    }

                    Global.Debug = "upload";
                    FileInfo fiTemplate = new FileInfo(diFeature.FullName + '\\' + cabinet);
                    if (fiTemplate.Exists)
                    {
                        using (FileStream fs = fiTemplate.OpenRead()) {
                            byte[] data = new byte[fs.Length];
                            fs.Read(data, 0, (int)fs.Length);
                            SPFile file = listAktiviteter.RootFolder.Files.Add("Lists/Aktiviteter/Ge försäljningstillstånd/template.xsn", data);
                            Global.Debug = "set file properties";
                            //file.Properties["vti_contenttag"] = "{6908F1AD-3962-4293-98BB-0AA4FB54B9C9},3,1";
                            file.Properties["ipfs_streamhash"] = "0NJ+LASyxjJGhaIwPftKfwraa3YBBfJoNUPNA+oNYu4=";
                            file.Properties["ipfs_listform"]   = "true";
                            file.Update();
                        }
                        Global.Debug = "set folder properties";
                        SPFolder folder = listAktiviteter.RootFolder.SubFolders["Ge försäljningstillstånd"];
                        folder.Properties["_ipfs_solutionName"]    = "template.xsn";
                        folder.Properties["_ipfs_infopathenabled"] = "True";
                        folder.Update();
                    }
                    else
                    {
                        Global.WriteLog("template.xsn missing", EventLogEntryType.Error, 1000);
                    }
                }
                #endregion

                #region set default forms
                Global.Debug = "set default forms";
                foreach (SPContentType ct in listAktiviteter.ContentTypes)
                {
                    switch (ct.Name)
                    {
                    case "Tillsyn":
                    case "Ge försäljningstillstånd":
                        ct.DisplayFormUrl = "~list/" + ct.Name + "/displayifs.aspx";
                        ct.EditFormUrl    = "~list/" + ct.Name + "/editifs.aspx";
                        ct.NewFormUrl     = "~list/" + ct.Name + "/newifs.aspx";
                        ct.Update();
                        break;

                    default:
                        ct.DisplayFormUrl = ct.EditFormUrl = ct.NewFormUrl = string.Empty;
                        ct.Update();
                        break;
                    }
                }

                // create our own array since it will be modified (which would throw an exception)
                var forms = new SPForm[listAktiviteter.Forms.Count];
                int j     = 0;
                foreach (SPForm form in listAktiviteter.Forms)
                {
                    forms[j] = form;
                    j++;
                }
                foreach (var form in forms)
                {
                    SPFile page = web.GetFile(form.Url);
                    SPLimitedWebPartManager limitedWebPartManager = page.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
                    foreach (System.Web.UI.WebControls.WebParts.WebPart wp in limitedWebPartManager.WebParts)
                    {
                        if (wp is BrowserFormWebPart)
                        {
                            BrowserFormWebPart bfwp = (BrowserFormWebPart)wp.WebBrowsableObject;
                            //bfwp.FormLocation = bfwp.FormLocation.Replace("/Item/", "/Ge försäljningstillstånd/");
                            //limitedWebPartManager.SaveChanges(bfwp);
                            string[] aLocation   = form.Url.Split('/');
                            string   contenttype = aLocation[aLocation.Length - 2];
                            bfwp.FormLocation = "~list/" + contenttype + "/template.xsn";
                            limitedWebPartManager.SaveChanges(bfwp);

                            StringBuilder sb = new StringBuilder();
                            sb.AppendLine();
                            sb.Append("BrowserFormWebPart FormLocation: ");
                            sb.AppendLine(bfwp.FormLocation);
                            sb.Append("BrowserFormWebPart Title: ");
                            sb.AppendLine(bfwp.Title);
                            sb.Append("BrowserFormWebPart ID: ");
                            sb.AppendLine(bfwp.ID);
                            sb.Append("Form URL: ");
                            sb.AppendLine(form.Url);
                            sb.Append("Form TemplateName: ");
                            sb.AppendLine(form.TemplateName);
                            sb.Append("Form ID: ");
                            sb.AppendLine(form.ID.ToString());
                            sb.Append("Form ServerRelativeUrl: ");
                            sb.AppendLine(form.ServerRelativeUrl);
                            sb.AppendLine("BrowserFormWebPart Schema: ");
                            sb.AppendLine();
                            sb.AppendLine(form.SchemaXml);


                            Global.WriteLog(sb.ToString(), EventLogEntryType.Information, 1000);

                            //switch (form.Type) {
                            //    case PAGETYPE.PAGE_NEWFORM:
                            //        listAktiviteter.DefaultNewFormUrl = form.ServerRelativeUrl;
                            //        break;
                            //    case PAGETYPE.PAGE_EDITFORM:
                            //        listAktiviteter.DefaultEditFormUrl = form.ServerRelativeUrl;
                            //        break;
                            //    case PAGETYPE.PAGE_DISPLAYFORM:
                            //        listAktiviteter.DefaultDisplayFormUrl = form.ServerRelativeUrl;
                            //        break;
                            //}
                        }
                    }
                }

                #endregion

                #region cleanup

                Global.Debug = "cleanup";
                diWorkDir.Delete(true);
                foreach (FileInfo fi in diFeature.GetFiles("template*.xsn"))
                {
                    fi.Delete();
                }
                foreach (FileInfo fi in diFeature.GetFiles("directives*.xsn"))
                {
                    fi.Delete();
                }

                #endregion

                #region stäng av required på rubrik
                SPField title = listKundkort.Fields[new Guid("fa564e0f-0c70-4ab9-b863-0177e6ddd247")];
                Global.WriteLog("listKundkort Title - Required: " + title.Required.ToString() + ", ShowInNew: " + title.ShowInNewForm.ToString() + ", ShowInEdit: " + title.ShowInEditForm.ToString(), EventLogEntryType.Information, 1000);
                title.Required       = false;
                title.ShowInNewForm  = false;
                title.ShowInEditForm = false;
                title.Update();

                //title = listAktiviteter.Fields[new Guid("fa564e0f-0c70-4ab9-b863-0177e6ddd247")];
                //Global.WriteLog("listAktiviteter Title - Required: " + title.Required.ToString() + ", ShowInNew: " + title.ShowInNewForm.ToString() + ", ShowInEdit: " + title.ShowInEditForm.ToString(), EventLogEntryType.Information, 1000);
                //title.Required = false;
                //title.ShowInNewForm = false;
                //title.ShowInEditForm = false;
                //title.Update();

                foreach (SPContentType ct in listAktiviteter.ContentTypes)
                {
                    SPFieldLink flTitle = ct.FieldLinks[new Guid("fa564e0f-0c70-4ab9-b863-0177e6ddd247")];
                    flTitle.Required = false;
                    flTitle.Hidden   = true;
                    ct.Update();
                }
                #endregion

                Global.WriteLog("Feature Activated", EventLogEntryType.Information, 1001);
            }
            catch (Exception ex) {
                Global.WriteLog("Message:\r\n" + ex.Message + "\r\n\r\nStacktrace:\r\n" + ex.StackTrace, EventLogEntryType.Error, 2001);
            }
        } // feature activated
Exemplo n.º 16
0
        /// <summary>
        /// Loads the values from the xml file.
        /// </summary>
        void LoadValuesFromFile()
        {
            ResolutionComboBox.Items.Add("640x480");
            ResolutionComboBox.Items.Add("800x600");
            ResolutionComboBox.Items.Add("1024x768");

            // Fills the combo box.

            leftMovetxtbox.IsEnabled  = false;
            rightMovetxtbox.IsEnabled = false;
            pausetxtbox.IsEnabled     = false;
            firetxtbox.IsEnabled      = false;
            // Sets the enable fields of the textboxes.

            try
            {
                if (!File.Exists(@"..\..\Resources\OptionsSettings.xml"))
                {
                    XElement   mouseElement      = new XElement("mouse", "true");
                    XElement   keyboardElement   = new XElement("keyboard", "true");
                    XElement   soundElement      = new XElement("sound", "true");
                    XElement   resolutionElement = new XElement("resolution", "1024x768");
                    XElement   leftkeyElement    = new XElement("leftkey", "Left");
                    XElement   rightkeyElement   = new XElement("rightkey", "Right");
                    XElement   firekeyElement    = new XElement("firekey", "Space");
                    XElement   pausekeyElement   = new XElement("pausekey", "P");
                    XElement   difficultyElement = new XElement("difficulty", "1");
                    XElement   mapElement        = new XElement("map", "1");
                    XAttribute newAttribute      = new XAttribute("id", 1);
                    XElement   newElements       = new XElement("option", newAttribute, mouseElement, keyboardElement, soundElement, resolutionElement, leftkeyElement, rightkeyElement, firekeyElement, pausekeyElement, difficultyElement, mapElement);
                    XElement   newOptions        = new XElement("Options", newElements);
                    XDocument  newDocument       = new XDocument(newOptions);
                    newDocument.Save(@"..\..\Resources\OptionsSettings.xml");
                }
                // If the file doesn't exist, then create a new.

                XDocument settingsFromXml = XDocument.Load(@"..\..\Resources\OptionsSettings.xml");
                var       readDataFromXml = settingsFromXml.Descendants("option");
                var       fromXml         = from x in readDataFromXml
                                            select x;
                // Load the values stored in the xml.

                foreach (var oneElement in fromXml)
                {
                    optionsSettings.GraphicsResolution = (string)oneElement.Element("resolution");
                    optionsSettings.LeftKey            = (string)oneElement.Element("leftkey");
                    optionsSettings.RightKey           = (string)oneElement.Element("rightkey");
                    optionsSettings.PauseKey           = (string)oneElement.Element("pausekey");
                    optionsSettings.FireKey            = (string)oneElement.Element("firekey");
                    optionsSettings.DifficultyLevel    = (int)oneElement.Element("difficulty");
                    optionsSettings.MouseIsOn          = (bool)oneElement.Element("mouse");
                    optionsSettings.KeyboardIsOn       = (bool)oneElement.Element("keyboard");
                    optionsSettings.MapNumber          = (int)oneElement.Element("map");
                    optionsSettings.SoundIsOn          = (bool)oneElement.Element("sound");
                }
                // Gives the values from the xml to the OptionSettings object, thus sets the object with the default values.

                leftMovetxtbox.Text             = optionsSettings.LeftKey;
                rightMovetxtbox.Text            = optionsSettings.RightKey;
                pausetxtbox.Text                = optionsSettings.PauseKey;
                firetxtbox.Text                 = optionsSettings.FireKey;
                ResolutionComboBox.SelectedItem = optionsSettings.GraphicsResolution;
                mouseCheckBox.IsChecked         = optionsSettings.MouseIsOn;
                keyboardCheckBox.IsChecked      = optionsSettings.KeyboardIsOn;
                soundCheckBox.IsChecked         = optionsSettings.SoundIsOn;
                // Sets the default values to the GUI elements.
            }
            catch
            {
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Update xl/_rels/workbook.xml.rels file
        /// </summary>
        private void UpdateRelations(bool ensureStrings)
        {
            if (!(ensureStrings ||
                  (DeleteWorksheets != null && DeleteWorksheets.Any()) ||
                  (AddWorksheets != null && AddWorksheets.Any())))
            {
                // Nothing to update
                return;
            }

            using (Stream stream = Archive.GetEntry("xl/_rels/workbook.xml.rels").Open())
            {
                XDocument document = XDocument.Load(stream);

                if (document == null)
                {
                    //TODO error
                }
                bool update = false;

                List <XElement> relationshipElements = document.Descendants().Where(d => d.Name.LocalName == "Relationship").ToList();
                int             id = relationshipElements.Count;
                if (ensureStrings)
                {
                    //Ensure SharedStrings
                    XElement relationshipElement = (from element in relationshipElements
                                                    from attribute in element.Attributes()
                                                    where attribute.Name == "Target" && attribute.Value.Equals("sharedStrings.xml", StringComparison.OrdinalIgnoreCase)
                                                    select element).FirstOrDefault();

                    if (relationshipElement == null)
                    {
                        relationshipElement = new XElement(document.Root.GetDefaultNamespace() + "Relationship");
                        relationshipElement.Add(new XAttribute("Target", "sharedStrings.xml"));
                        relationshipElement.Add(new XAttribute("Type", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings"));
                        relationshipElement.Add(new XAttribute("Id", string.Format("rId{0}", ++id)));

                        document.Root.Add(relationshipElement);
                        update = true;
                    }
                }

                // Remove all references to sheets from this file as they are not requried
                if ((DeleteWorksheets != null && DeleteWorksheets.Any()) ||
                    (AddWorksheets != null && AddWorksheets.Any()))
                {
                    XElement[] worksheetElements = (from element in relationshipElements
                                                    from attribute in element.Attributes()
                                                    where attribute.Name == "Type" && attribute.Value == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet"
                                                    select element).ToArray();
                    for (int i = worksheetElements.Length - 1; i > 0; i--)
                    {
                        worksheetElements[i].Remove();
                        update = true;
                    }
                }

                if (update)
                {
                    // Set the stream to the start
                    stream.Position = 0;
                    // Clear the stream
                    stream.SetLength(0);

                    // Open the stream so we can override all content of the sheet
                    StreamWriter streamWriter = new StreamWriter(stream, Encoding.UTF8);
                    document.Save(streamWriter);
                    streamWriter.Flush();
                }
            }
        }
Exemplo n.º 18
0
 public void Save()
 {
     xSources.Save(XMLPath);
 }
Exemplo n.º 19
0
        static void Main(string[] args)
        {
            var input = new Dictionary <string, GlobalDecl>();

            for (int i = 0; i < args.Length / 2; i++)
            {
                var tag      = args[i * 2];
                var fileName = args[i * 2 + 1];
                Console.WriteLine("Reading " + fileName + " ...");
                var xml  = XDocument.Load(fileName);
                var decl = (GlobalDecl)SymbolDecl.Deserialize(xml.Root);
                decl.BuildSymbolTree(null, tag);
                input.Add(tag, decl);
            }

            Console.WriteLine("De-duplicating ...");
            var symbolGroup = new Dictionary <string, List <SymbolDecl> >();

            GroupSymbolsByOverloadKey(input.Values, symbolGroup);
            foreach (var pair in symbolGroup)
            {
                var groups = pair.Value
                             .GroupBy(x => x.ContentKey)
                             .ToArray();
                foreach (var group in groups)
                {
                    var decls = group.ToArray();
                    var tags  = decls
                                .Select(x => x.Tags)
                                .OrderBy(x => x)
                                .Aggregate((a, b) => a + ";" + b);
                    foreach (var decl in decls)
                    {
                        decl.Tags = tags;
                    }
                }
            }

            Console.WriteLine("Resolving Symbols ...");
            var symbolResolving = symbolGroup
                                  .SelectMany(x => x.Value)
                                  .ToArray();
            var environment = new ResolveEnvironment(input.Values);

            foreach (var symbol in symbolResolving)
            {
                symbol.Resolve(environment);
            }

            var output    = args[args.Length - 1];
            var xmlErrors = environment.Errors.Where(x => x.StartsWith("(Xml)")).ToArray();
            var warnings  = environment.Errors.Where(x => x.StartsWith("(Warning)")).ToArray();
            var errors    = environment.Errors.Where(x => x.StartsWith("(Error)")).ToArray();

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("Xml Errors: " + xmlErrors.Length);
            Console.WriteLine("Warnings: " + warnings.Length);
            Console.WriteLine("Errors: " + errors.Length);
            Console.ResetColor();

            using (var writer = new StreamWriter(output + ".errors.txt", false, Encoding.UTF8))
            {
                writer.WriteLine("=======================XML ERROR=======================");
                foreach (var message in xmlErrors)
                {
                    writer.WriteLine(message);
                }
                writer.WriteLine();

                writer.WriteLine("========================WARNING========================");
                foreach (var message in warnings)
                {
                    writer.WriteLine(message);
                }

                writer.WriteLine();
                writer.WriteLine("=========================ERROR=========================");
                foreach (var message in errors)
                {
                    writer.WriteLine(message);
                }
            }

            Console.WriteLine("Saving ...");
            var symbolSaving = symbolGroup
                               .ToDictionary(
                x => x.Key,
                x => x.Value
                .GroupBy(y => y.Tags)
                .Select(y => y.First())
                .Select(y =>
            {
                var templateDecl = y.Parent as TemplateDecl;
                return(templateDecl == null ? y : templateDecl);
            })
                .Where(y => y.Parent is NamespaceDecl || y.Parent is GlobalDecl)
                .ToArray()
                )
                               .Where(x => x.Value.Length > 0)
                               .GroupBy(x => x.Value.First().Parent)
                               .ToDictionary(
                x => x.Key,
                x => x.ToDictionary(
                    y => y.Key,
                    y => y.Value
                    )
                )
            ;
            var outputXml = new XDocument(
                new XElement("CppXmlDocument",
                             symbolSaving.Select(x => new XElement("Namespace",
                                                                   new XAttribute("Name", x.Key is GlobalDecl ? "" : (x.Key as NamespaceDecl).NameKey),
                                                                   x.Value.Select(y => new XElement("Symbol",
                                                                                                    new XAttribute("OverloadKey", y.Key),
                                                                                                    y.Value
                                                                                                    .Select(z => z.Parent is TemplateDecl ? z.Parent : z)
                                                                                                    .Select(z => z.Serialize())
                                                                                                    ))
                                                                   ))
                             )
                );

            outputXml.Save(output);
        }
Exemplo n.º 20
0
        // Create default config.xml file. Use in case file doesn't exist or corrupted
        private static void createDefaultConfig()
        {
            XDocument defaultValues = XDocument.Load(DefaultInfo.BuildsDefaultConfigFileLocation);

            defaultValues.Save(DefaultInfo.BuildsConfigLocation);
        }
Exemplo n.º 21
0
        private void WriteAndPatch(int appID)
        {
            richTextBox1.AppendText(Environment.NewLine);
            richTextBox1.AppendText("Searching DLC for: ");
            richTextBox1.AppendText(GameSelecForm.gameName, Color.White);
            richTextBox1.AppendText(Environment.NewLine);
            richTextBox1.AppendText("Accessing SteamDB.info with desired appid.");
            string steamDBURLDlc = "https://steamdb.info/app/" + appID.ToString() + "/dlc/";

            richTextBox1.AppendText(Environment.NewLine);
            richTextBox1.AppendText("URL read is: ");
            richTextBox1.AppendText(steamDBURLDlc);
            richTextBox1.AppendText(Environment.NewLine);
            richTextBox1.AppendText(Environment.NewLine);
            richTextBox1.AppendText("Gathering DLCs informations. This can take some time depending on your network connection and amount of DLC.");
            string statusCode = "";

            var tableDLC = GetDLCForSelectedAppIDAsync(appID, ref statusCode);

            if (statusCode == "tableDLCisnull")
            {
                richTextBox1.AppendText(Environment.NewLine);
                richTextBox1.AppendText(Environment.NewLine);
                richTextBox1.AppendText("There is NO DLC FOR THIS GAME, STOP BEING STUPID.", Color.Red);
                richTextBox1.AppendText(Environment.NewLine);
                richTextBox1.AppendText("Maybe you should close it and learn how to use your brain.", Color.Red);
                MessageBox.Show("No DLC was found.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                ArrayList dlcList = new ArrayList();
                richTextBox1.AppendText(Environment.NewLine);
                richTextBox1.AppendText(Environment.NewLine);
                richTextBox1.AppendText("Number of DLC found: ");
                richTextBox1.AppendText(tableDLC.Count.ToString(), Color.White);
                richTextBox1.AppendText(Environment.NewLine);
                for (int i = 0; i < tableDLC.Count; i++)
                {
                    dlcList.Add(new gameList(tableDLC[i][0], tableDLC[i][1]));
                    richTextBox1.AppendText(Environment.NewLine);
                    richTextBox1.AppendText("DLC ID:    ");
                    richTextBox1.AppendText(tableDLC[i][0], Color.White);
                    richTextBox1.AppendText(Environment.NewLine);
                    richTextBox1.AppendText("DLC Name:  ");
                    richTextBox1.AppendText(tableDLC[i][1], Color.White);
                    richTextBox1.AppendText(Environment.NewLine);
                    //  }
                }

                if (tableDLC.Count >= 50)
                {
                    richTextBox1.AppendText(Environment.NewLine);
                    richTextBox1.AppendText("SteamDB.info have issue with 50+ DLCs, it's due to Steam API limitation. You should " +
                                            "check it out on your own. More info will soon be found by looking on git page and README. But not know.", Color.Yellow);
                }
                bool justShowing = false;
                if (MessageBox.Show("Would you like to patch the game?", "Sure about patching?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    justShowing = false;
                }
                else
                {
                    justShowing = true;
                }

                if (!justShowing)
                {
                    richTextBox1.AppendText(Environment.NewLine);
                    richTextBox1.AppendText("The file will be saved on: ");
                    string gameDir;
                    byte   steam_api = 0;
                    if (!Program.useInstalledGame)
                    {
                        gameDir = Environment.CurrentDirectory.ToString() + "\\" + GameSelecForm.gameName + "\\";
                        if (!(Directory.Exists(gameDir)))
                        {
                            Directory.CreateDirectory(gameDir);
                        }
                    }
                    else
                    {
                        gameDir   = Program.gameDir + "\\";
                        steam_api = GetSteamPresence(gameDir);
                        if (steam_api == 0)
                        {
                            OpenFileDialog getSteamApiDllFile = new OpenFileDialog
                            {
                                InitialDirectory = gameDir,
                                Filter           = "steam_api(64).dll |steam_api.dll; steam_api64.dll"
                            };
                            if (getSteamApiDllFile.ShowDialog() == DialogResult.OK)
                            {
                                gameDir = getSteamApiDllFile.FileName.Replace(getSteamApiDllFile.SafeFileName, "");
                            }
                            else
                            {
                                MessageBox.Show("You're dumb!", "Stupid men ...", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                Application.Exit();
                            }
                            steam_api = GetSteamPresence(gameDir);
                        }
                    }
                    richTextBox1.AppendText(gameDir, Color.Yellow);
                    string capiFilesDir          = Environment.CurrentDirectory + "\\CreamAPI_" + Program.capiVersion + "\\";
                    bool   isCrackAlreadyPresent = false;
                    if (File.Exists(gameDir + "cream_api.ini"))
                    {
                        isCrackAlreadyPresent = true;
                    }
                    if (!isCrackAlreadyPresent)
                    {
                        if (steam_api == 1)
                        {
                            if (Program.useInstalledGame)
                            {
                                File.Move(gameDir + "steam_api.dll", gameDir + "steam_api_o.dll");
                            }
                            File.Copy(capiFilesDir + "steam_api.dll", gameDir + "steam_api.dll");
                        }
                        if (steam_api == 2)
                        {
                            if (Program.useInstalledGame)
                            {
                                File.Move(gameDir + "steam_api64.dll", gameDir + "steam_api64_o.dll");
                            }
                            File.Copy(capiFilesDir + "steam_api64.dll", gameDir + "steam_api64.dll");
                        }
                        if (steam_api == 3)
                        {
                            if (Program.useInstalledGame)
                            {
                                File.Move(gameDir + "steam_api.dll", gameDir + "steam_api_o.dll");
                                File.Move(gameDir + "steam_api64.dll", gameDir + "steam_api64_o.dll");
                            }
                            File.Copy(capiFilesDir + "steam_api.dll", gameDir + "steam_api.dll");
                            File.Copy(capiFilesDir + "steam_api64.dll", gameDir + "steam_api64.dll");
                        }
                        File.Copy(capiFilesDir + "cream_api.ini", gameDir + "cream_api.ini");
                    }
                    else
                    {
                        richTextBox1.AppendText(Environment.NewLine);
                        richTextBox1.AppendText(Environment.NewLine);
                        richTextBox1.AppendText("Existing DLCs info found!\n", Color.Yellow);
                        FileIniDataParser capiParser   = new FileIniDataParser();
                        var            temp1           = capiParser.ReadFile(gameDir + "cream_api.ini");
                        List <KeyData> localDLCKeyData = temp1.Sections["dlc"].ToList();
                        if (localDLCKeyData.Count == tableDLC.Count)
                        {
                            richTextBox1.AppendText("No new DLCs found for this game.\n", Color.Yellow);
                            tableDLC.Clear();
                        }
                        else
                        {
                            richTextBox1.AppendText($"{localDLCKeyData.Count} DLC(s) already activated!\n", Color.Yellow);
                            for (int i = 0; i < localDLCKeyData.Count; i++)
                            {
                                for (int j = 0; j < tableDLC.Count; j++)
                                {
                                    if ((localDLCKeyData[i].KeyName == tableDLC[j][0]) && (localDLCKeyData[i].Value == tableDLC[j][1]))
                                    {
                                        tableDLC.RemoveAt(j);
                                    }
                                }
                            }
                            richTextBox1.AppendText($"{tableDLC.Count} new DLC(s) will be added!\n", Color.Yellow);
                            for (int i = 0; i < tableDLC.Count; i++)
                            {
                                richTextBox1.AppendText("DLC Name:  ");
                                richTextBox1.AppendText(tableDLC[i][1], Color.White);
                                richTextBox1.AppendText(" newly added!\n");
                            }
                        }
                    }
                    CApiFileGest cApiFileGest = new CApiFileGest();
                    if (!isCrackAlreadyPresent)
                    {
                        cApiFileGest.CApiIniConfig(gameDir + "cream_api.ini");
                    }
                    cApiFileGest.CApiDlcWriter(gameDir + "cream_api.ini", appID, tableDLC);
                    richTextBox1.AppendText(Environment.NewLine);
                    richTextBox1.AppendText(Environment.NewLine);

                    string            strPathXML = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString() + "\\patchedCApiGames.xml";
                    GamePatchSaveMgmt saveMgmt   = new GamePatchSaveMgmt(strPathXML);

                    List <string> lsStrreadedGame = saveMgmt.ReadAppIDXml(appID.ToString());
                    List <string> lsStrGameInfo   = new List <string>
                    {
                        appID.ToString(),
                                  GameSelecForm.gameName,
                                  gameDir.ToString(),
                                  tableDLC.Count.ToString()
                    };
                    if (lsStrreadedGame.Count == 1)
                    {
                        if (lsStrreadedGame[0] == "no_file")
                        {
                            XDocument doc = new XDocument(
                                new XElement("crackedgame")
                                );
                            doc.Save(strPathXML);
                            bool boolWrite = saveMgmt.WriteToXML(lsStrGameInfo);
                        }
                        if (lsStrreadedGame[0] == "not_found")
                        {
                            bool boolWrite = saveMgmt.WriteToXML(lsStrGameInfo);
                        }
                    }
                    else
                    {
                        bool hasInfoChange = false;
                        for (int i = 0; i < lsStrreadedGame.Count; i++)
                        {
                            if (lsStrGameInfo[i] != lsStrreadedGame[i])
                            {
                                hasInfoChange = true;
                                break;
                            }
                        }
                        if (hasInfoChange)
                        {
                            bool bgitre = saveMgmt.UpdateXMLElement(lsStrGameInfo);
                            bgitre = saveMgmt.WriteToXML(lsStrGameInfo);
                        }
                    }

                    richTextBox1.AppendText("The game is now patched!", Color.Gray);
                    richTextBox1.AppendText(Environment.NewLine);
                    richTextBox1.AppendText("You can run it directly from Steam, or via exe's file.\n", Color.Gray);
                    richTextBox1.AppendText("Keep in mind this patch isn't universal, so it might not work\n", Color.Gray);
                    richTextBox1.AppendText("With various game.\n" +
                                            "Have fun.", Color.Gray);
                    richTextBox1.AppendText(Environment.NewLine);
                    richTextBox1.AppendText("BTw, press {enter} to leave.", Color.Gray);
                    Task.Factory.StartNew(() => richTextBox1.KeyPress += new KeyPressEventHandler(CheckEnter)).Wait(TimeSpan.FromSeconds(25.0));
                }
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Handles the Click event of the btnAppChng control witch saves the changes made in the options window.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
        private void btnAppChng_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                XDocument settingsFromXml = XDocument.Load(@"..\..\Resources\OptionsSettings.xml");
                var       readDataFromXml = settingsFromXml.Descendants("option");
                var       fromXml         = from x in readDataFromXml
                                            select x;
                // Load the values stored in the xml.

                if (fromXml.Single().Element("leftkey").Value != optionsSettings.LeftKey)
                {
                    fromXml.Single().Element("leftkey").Value = optionsSettings.LeftKey;
                    SettingsSaved.Content = "Settings has been updated!";
                }
                if (fromXml.Single().Element("rightkey").Value != optionsSettings.RightKey)
                {
                    fromXml.Single().Element("rightkey").Value = optionsSettings.RightKey;
                    SettingsSaved.Content = "Settings has been updated!";
                }
                if (fromXml.Single().Element("pausekey").Value != optionsSettings.PauseKey)
                {
                    fromXml.Single().Element("pausekey").Value = optionsSettings.PauseKey;
                    SettingsSaved.Content = "Settings has been updated!";
                }
                if (fromXml.Single().Element("resolution").Value != optionsSettings.GraphicsResolution)
                {
                    fromXml.Single().Element("resolution").Value = optionsSettings.GraphicsResolution;
                    SettingsSaved_Res.Content = "Settings has been updated!";
                }
                if (fromXml.Single().Element("firekey").Value != optionsSettings.FireKey)
                {
                    fromXml.Single().Element("firekey").Value = optionsSettings.FireKey;
                    SettingsSaved.Content = "Settings has been updated!";
                }
                if (fromXml.Single().Element("mouse").Value != optionsSettings.MouseIsOn.ToString())
                {
                    fromXml.Single().Element("mouse").Value = optionsSettings.MouseIsOn.ToString();
                    SettingsSaved.Content = "Settings has been updated!";
                }
                if (fromXml.Single().Element("keyboard").Value != optionsSettings.KeyboardIsOn.ToString())
                {
                    fromXml.Single().Element("keyboard").Value = optionsSettings.KeyboardIsOn.ToString();
                    SettingsSaved.Content = "Settings has been updated!";
                }
                if (fromXml.Single().Element("sound").Value != optionsSettings.SoundIsOn.ToString())
                {
                    fromXml.Single().Element("sound").Value = optionsSettings.SoundIsOn.ToString();
                    SettingsSaved.Content = "Settings has been updated!";
                }
                // If the values from the xml doesn't match the values from the OptionSettings object, than refresh the the xml values.

                settingsFromXml.Save(@"..\..\Resources\OptionsSettings.xml");
                // Save the changes in the values of the xml.

                LabelHide.Start();
                // Hides the label after the designated timespan.
            }
            catch
            {
            }
        }
Exemplo n.º 23
0
        /*public Boolean ReserveRoom(String r,int floor)
        {
           Boolean str= c.ReserveRoom(r,floor);
            return str;
        }
        */

        public int WriteHotelRooms(String room)
        {
            int floorno = 1;
            int roomno = 1;
            int roomlimit = 0;
            if (room.Equals("Standard"))
            {
                floorno = 1;
                roomno = 1;
                roomlimit = 10;
            }
            else if (room.Equals("Moderate"))
            {
                floorno = 1;
                roomno = 11;
                roomlimit = 20;
            }
            else if (room.Equals("Superior"))
            {
                floorno = 1;
                roomno = 21;
                roomlimit = 30;
            }
            else if (room.Equals("Junior Suite"))
            {
                floorno = 1;
                roomno = 31;
                roomlimit = 40;
            }
            else if (room.Equals("Suite"))
            {
                floorno = 1;
                roomno = 41;
                roomlimit = 50;
            }
            else
                return 0;
            String r = room + ".xml";
            Console.WriteLine(r);

            for (; floorno <= 5; floorno++)
            {
                for (; roomno <= roomlimit; roomno++)
                {
//                    Console.WriteLine("yes");

                    if (File.Exists(r) == false)
                    {
                        //                      Console.WriteLine("yesss");

                        XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
                        xmlWriterSettings.Indent = true;
                        xmlWriterSettings.NewLineOnAttributes = true;
                        using (XmlWriter xmlWriter = XmlWriter.Create(r, xmlWriterSettings))
                        {
//                            Console.WriteLine("ysss");

                            xmlWriter.WriteStartDocument();
                            xmlWriter.WriteStartElement("Hotel");

                            xmlWriter.WriteStartElement("Customer");
                            xmlWriter.WriteElementString("Name", "");
                            //xmlWriter.WriteElementString("Age", "");
                            //xmlWriter.WriteElementString("Gender", "");
                            xmlWriter.WriteElementString("IDCardNo", "");
                            //xmlWriter.WriteElementString("BalanceRs", "");
                            //xmlWriter.WriteElementString("DaysReserve", "");
                            xmlWriter.WriteElementString("FloorNo", floorno.ToString());
                            //xmlWriter.WriteElementString("RoomType", "Standard");
                            xmlWriter.WriteElementString("Roomno", roomno.ToString());
                            // xmlWriter.WriteElementString("CheckInTime", "");
                            // xmlWriter.WriteElementString("CheckOutTime", "");
                            // xmlWriter.WriteElementString("TimeRemaining", "");
                            xmlWriter.WriteElementString("Status", "notreserve");

                            xmlWriter.WriteEndElement();

                            xmlWriter.WriteEndElement();
                            xmlWriter.WriteEndDocument();
                            xmlWriter.Flush();
                            xmlWriter.Close();
                        }
                    }
                    else
                    {
                        XDocument xDocument = XDocument.Load(r);
                        XElement root = xDocument.Element("Hotel");
                        IEnumerable<XElement> rows = root.Descendants("Customer");
                        XElement firstRow = rows.First();
                        firstRow.AddBeforeSelf(
                            new XElement("Customer",
                                new XElement("Name", ""),
                                //new XElement("Age", ""),
                                //new XElement("Gender", ""),
                                new XElement("IDCardNo", ""),
                                //new XElement("BalanceRs", ""),
                                //new XElement("DaysReserve", ""),
              
                                new XElement("FloorNo", floorno.ToString()),
                                //new XElement("RoomType", "Standard"),
                                new XElement("Roomno", roomno.ToString()),
                                //new XElement("CheckInTime", ""),
                                //new XElement("CheckOutTime", ""),
                                //new XElement("TimeRemaining", ""),
                                new XElement("Status", "notreserve")));


                        xDocument.Save(r);
                    }
                }
                roomlimit = roomlimit + 10;
            }
            return 0;
        }
Exemplo n.º 24
0
        public static void AddCountToStatistic(string Statistic, string PluginName)
        {
            try
            {
                SimpleAES StringEncrypter = new SimpleAES();
                Directory.CreateDirectory(Directory.GetParent(StatisticsFilePath).FullName);
                if (!File.Exists(StatisticsFilePath))
                {
                    new XDocument(
                        new XElement("LSPDFRPlus")
                        )
                    .Save(StatisticsFilePath);
                }

                string pswd = Environment.UserName;

                string EncryptedStatistic = XmlConvert.EncodeName(StringEncrypter.EncryptToString(Statistic + PluginName + pswd));

                string EncryptedPlugin = XmlConvert.EncodeName(StringEncrypter.EncryptToString(PluginName + pswd));

                XDocument xdoc = XDocument.Load(StatisticsFilePath);
                char[]    trim = new char[] { '\'', '\"', ' ' };
                XElement  LSPDFRPlusElement;
                if (xdoc.Element("LSPDFRPlus") == null)
                {
                    LSPDFRPlusElement = new XElement("LSPDFRPlus");
                    xdoc.Add(LSPDFRPlusElement);
                }

                LSPDFRPlusElement = xdoc.Element("LSPDFRPlus");
                XElement StatisticElement;
                if (LSPDFRPlusElement.Elements(EncryptedStatistic).Where(x => (string)x.Attribute("Plugin") == EncryptedPlugin).ToList().Count == 0)
                {
                    //Game.LogTrivial("Creating new statistic entry.");
                    StatisticElement = new XElement(EncryptedStatistic);
                    StatisticElement.Add(new XAttribute("Plugin", EncryptedPlugin));
                    LSPDFRPlusElement.Add(StatisticElement);
                }
                StatisticElement = LSPDFRPlusElement.Elements(EncryptedStatistic).Where(x => (string)x.Attribute("Plugin") == EncryptedPlugin).FirstOrDefault();
                int StatisticCount;
                if (StatisticElement.IsEmpty)
                {
                    StatisticCount = 0;
                }
                else
                {
                    string DecryptedStatistic = StringEncrypter.DecryptString(XmlConvert.DecodeName(StatisticElement.Value));
                    //Game.LogTrivial("Decryptedstatistic: " + DecryptedStatistic);
                    int    index     = DecryptedStatistic.IndexOf(EncryptedStatistic);
                    string cleanPath = (index < 0)
                        ? "0"
                        : DecryptedStatistic.Remove(index, EncryptedStatistic.Length);
                    //if (cleanPath == "0") { Game.LogTrivial("Cleanpath debug 2"); }

                    index     = cleanPath.IndexOf(pswd);
                    cleanPath = (index < 0)
                        ? "0"
                        : cleanPath.Remove(index, pswd.Length);
                    //if (cleanPath == "0") { Game.LogTrivial("Cleanpath debug 1"); }
                    StatisticCount = int.Parse(cleanPath);
                }
                //Game.LogTrivial("Statisticscount: " + StatisticCount.ToString());
                StatisticCount++;
                string ValueToWrite    = StatisticCount.ToString() + pswd;
                int    indextoinsertat = LSPDFRPlusHandler.rnd.Next(ValueToWrite.Length);
                ValueToWrite = ValueToWrite.Substring(0, indextoinsertat) + EncryptedStatistic + ValueToWrite.Substring(indextoinsertat);
                //Game.LogTrivial("Valueotwrite: " + ValueToWrite);
                StatisticElement.Value = XmlConvert.EncodeName(StringEncrypter.EncryptToString(ValueToWrite));

                xdoc.Save(StatisticsFilePath);
            }
            catch (System.Threading.ThreadAbortException e) { }
            catch (Exception e)
            {
                Game.LogTrivial("LSPDFR+ encountered a statistics exception. It was: " + e.ToString());
                Game.DisplayNotification("~r~LSPDFR+: Statistics error.");
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Informs the screen manager to serialize its state to disk.
        /// </summary>
        public void Deactivate()
        {
            #if !WINDOWS_PHONE
            return;
            #else
            // Open up isolated storage
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // Create an XML document to hold the list of screen types currently in the stack
                XDocument doc = new XDocument();
                XElement root = new XElement("ScreenManager");
                doc.Add(root);

                // Make a copy of the master screen list, to avoid confusion if
                // the process of deactivating one screen adds or removes others.
                tempScreensList.Clear();
                foreach (GameScreen screen in screens)
                    tempScreensList.Add(screen);

                // Iterate the screens to store in our XML file and deactivate them
                foreach (GameScreen screen in tempScreensList)
                {
                    // Only add the screen to our XML if it is serializable
                    if (screen.IsSerializable)
                    {
                        // We store the screen's controlling player so we can rehydrate that value
                        string playerValue = screen.ControllingPlayer.HasValue
                            ? screen.ControllingPlayer.Value.ToString()
                            : "";

                        root.Add(new XElement(
                            "GameScreen",
                            new XAttribute("Type", screen.GetType().AssemblyQualifiedName),
                            new XAttribute("ControllingPlayer", playerValue)));
                    }

                    // Deactivate the screen regardless of whether we serialized it
                    screen.Deactivate();
                }

                // Save the document
                using (IsolatedStorageFileStream stream = storage.CreateFile(StateFilename))
                {
                    doc.Save(stream);
                }
            }
            #endif
        }
Exemplo n.º 26
0
        /// <summary>
        /// Update [Content_Types].xml file
        /// </summary>
        private void UpdateContentTypes(bool ensureStrings)
        {
            if (!(ensureStrings ||
                  (DeleteWorksheets != null && DeleteWorksheets.Any()) ||
                  (AddWorksheets != null && AddWorksheets.Any())))
            {
                // Nothing to update
                return;
            }

            using (Stream stream = Archive.GetEntry("[Content_Types].xml").Open())
            {
                XDocument document = XDocument.Load(stream);

                if (document == null)
                {
                    //TODO error
                }
                bool            update           = false;
                List <XElement> overrideElements = document.Descendants().Where(d => d.Name.LocalName == "Override").ToList();

                //Ensure SharedStrings
                if (ensureStrings)
                {
                    XElement overrideElement = (from element in overrideElements
                                                from attribute in element.Attributes()
                                                where attribute.Name == "PartName" && attribute.Value.Equals("/xl/sharedStrings.xml", StringComparison.OrdinalIgnoreCase)
                                                select element).FirstOrDefault();

                    if (overrideElement == null)
                    {
                        overrideElement = new XElement(document.Root.GetDefaultNamespace() + "Override");
                        overrideElement.Add(new XAttribute("ContentType", "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"));
                        overrideElement.Add(new XAttribute("PartName", "/xl/sharedStrings.xml"));

                        document.Root.Add(overrideElement);
                        update = true;
                    }
                }
                if (DeleteWorksheets != null && DeleteWorksheets.Any())
                {
                    foreach (var item in DeleteWorksheets)
                    {
                        // the file name is different for each xml file
                        string fileName = string.Format("/xl/worksheets/sheet{0}.xml", item);

                        XElement overrideElement = (from element in overrideElements
                                                    from attribute in element.Attributes()
                                                    where attribute.Name == "PartName" && attribute.Value == fileName
                                                    select element).FirstOrDefault();
                        if (overrideElement != null)
                        {
                            overrideElement.Remove();
                            update = true;
                        }
                    }
                }

                if (AddWorksheets != null && AddWorksheets.Any())
                {
                    foreach (var item in AddWorksheets)
                    {
                        // the file name is different for each xml file
                        string fileName = string.Format("/xl/worksheets/sheet{0}.xml", item.SheetId);

                        XElement overrideElement = new XElement(document.Root.GetDefaultNamespace() + "Override");
                        overrideElement.Add(new XAttribute("ContentType", "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"));
                        overrideElement.Add(new XAttribute("PartName", fileName));

                        document.Root.Add(overrideElement);
                        update = true;
                    }
                }

                if (update)
                {
                    // Set the stream to the start
                    stream.Position = 0;
                    // Clear the stream
                    stream.SetLength(0);

                    // Open the stream so we can override all content of the sheet
                    StreamWriter streamWriter = new StreamWriter(stream, Encoding.UTF8);
                    document.Save(streamWriter);
                    streamWriter.Flush();
                }
            }
        }
Exemplo n.º 27
0
 public void Save(XDocument doc)
 {
     doc.Save(XmlFilePath);
 }
        public void SerializeScadaModel(string serializationTarget = "ScadaModel.xml")
        {
            string target = Path.Combine(basePath, serializationTarget);

            XElement scadaModel = new XElement("ScadaModel");

            XElement rtus     = new XElement("RTUS");
            XElement digitals = new XElement("Digitals");
            XElement analogs  = new XElement("Analogs");
            XElement counters = new XElement("Counters");

            var rtusSnapshot = dbContext.Database.RTUs.ToArray();

            foreach (var rtu in rtusSnapshot)
            {
                XElement rtuEl = new XElement(
                    "RTU",
                    new XElement("Address", rtu.Value.Address),
                    new XElement("Name", rtu.Value.Name),
                    new XElement("FreeSpaceForDigitals", rtu.Value.FreeSpaceForDigitals),
                    new XElement("FreeSpaceForAnalogs", rtu.Value.FreeSpaceForAnalogs),
                    new XElement("Protocol", Enum.GetName(typeof(IndustryProtocols), rtu.Value.Protocol)),
                    new XElement("DigOutStartAddr", rtu.Value.DigOutStartAddr),
                    new XElement("DigInStartAddr", rtu.Value.DigInStartAddr),
                    new XElement("AnaOutStartAddr", rtu.Value.AnaOutStartAddr),
                    new XElement("AnaInStartAddr", rtu.Value.AnaInStartAddr),
                    new XElement("CounterStartAddr", rtu.Value.CounterStartAddr),
                    new XElement("DigOutCount", rtu.Value.DigOutCount),
                    new XElement("DigInCount", rtu.Value.DigInCount),
                    new XElement("AnaInCount", rtu.Value.AnaInCount),
                    new XElement("AnaOutCount", rtu.Value.AnaOutCount),
                    new XElement("CounterCount", rtu.Value.CounterCount),
                    new XElement("AnaInRawMin", rtu.Value.AnaInRawMin),
                    new XElement("AnaInRawMax", rtu.Value.AnaInRawMax),
                    new XElement("AnaOutRawMin", rtu.Value.AnaOutRawMin),
                    new XElement("AnaOutRawMax", rtu.Value.AnaOutRawMax)
                    );

                rtus.Add(rtuEl);
            }

            var pvsSnapshot = dbContext.Database.ProcessVariablesName.ToArray().OrderBy(pv => pv.Value.RelativeAddress);

            foreach (var pv in pvsSnapshot)
            {
                switch (pv.Value.Type)
                {
                case VariableTypes.DIGITAL:

                    Digital dig = pv.Value as Digital;

                    XElement validCommands = new XElement("ValidCommands");
                    XElement validStates   = new XElement("ValidStates");

                    foreach (var state in dig.ValidStates)
                    {
                        validStates.Add(new XElement("State", Enum.GetName(typeof(States), state)));
                    }

                    foreach (var command in dig.ValidCommands)
                    {
                        validCommands.Add(new XElement("Command", Enum.GetName(typeof(CommandTypes), command)));
                    }

                    XElement digEl = new XElement(
                        "Digital",
                        new XElement("Name", dig.Name),
                        new XElement("State", dig.State),
                        new XElement("Command", dig.Command),
                        new XElement("ProcContrName", dig.ProcContrName),
                        new XElement("RelativeAddress", dig.RelativeAddress),
                        new XElement("Class", Enum.GetName(typeof(DigitalDeviceClasses), dig.Class)),
                        validCommands,
                        validStates
                        );

                    digitals.Add(digEl);

                    break;

                case VariableTypes.ANALOG:
                    Analog analog = pv.Value as Analog;

                    XElement anEl = new XElement(
                        "Analog",
                        new XElement("Name", analog.Name),
                        new XElement("NumOfRegisters", analog.NumOfRegisters),
                        new XElement("AcqValue", analog.AcqValue),
                        new XElement("CommValue", analog.CommValue),
                        new XElement("MaxValue", analog.MaxValue),
                        new XElement("MinValue", analog.MinValue),
                        new XElement("ProcContrName", analog.ProcContrName),
                        new XElement("RelativeAddress", analog.RelativeAddress),
                        new XElement("UnitSymbol", Enum.GetName(typeof(UnitSymbol), analog.UnitSymbol))
                        );

                    analogs.Add(anEl);

                    break;
                }
            }

            scadaModel.Add(rtus);
            scadaModel.Add(digitals);
            scadaModel.Add(analogs);
            scadaModel.Add(counters);

            var xdocument = new XDocument(scadaModel);

            try
            {
                xdocument.Save(target);
                Console.WriteLine("Serializing ScadaModel succeed.");
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemplo n.º 29
0
 /// <summary>
 /// Persist changes of app.config to disk.
 /// </summary>
 public void WriteConfig()
 {
     xd.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile, SaveOptions.None);
     xd = XDocument.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
                         , LoadOptions.PreserveWhitespace);
 }
Exemplo n.º 30
0
        public ActionResult OldPost(string signature, string timestamp, string nonce, string echostr)
        {
            LocationService locationService = new LocationService();
            EventService    eventService    = new EventService();

            if (!CheckSignature.Check(signature, timestamp, nonce, Token))
            {
                return(Content("参数错误!"));
            }
            XDocument requestDoc = null;

            try
            {
                requestDoc = XDocument.Load(Request.InputStream);

                var requestMessage = RequestMessageFactory.GetRequestEntity(requestDoc);
                //如果不需要记录requestDoc,只需要:
                //var requestMessage = RequestMessageFactory.GetRequestEntity(Request.InputStream);

                requestDoc.Save(Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Request_" + requestMessage.FromUserName + ".txt"));//测试时可开启,帮助跟踪数据
                ResponseMessageBase responseMessage = null;
                switch (requestMessage.MsgType)
                {
                case RequestMsgType.Text:    //文字
                {
                    //TODO:交给Service处理具体信息,参考/Service/EventSercice.cs 及 /Service/LocationSercice.cs
                    var strongRequestMessage  = requestMessage as RequestMessageText;
                    var strongresponseMessage =
                        ResponseMessageBase.CreateFromRequestMessage(requestMessage, ResponseMsgType.Text) as
                        ResponseMessageText;
                    strongresponseMessage.Content =
                        string.Format(
                            "您刚才发送了文字信息:{0}\r\n您还可以发送【位置】【图片】【语音】等类型的信息,查看不同格式的回复。\r\nSDK官方地址:http://weixin.senparc.com",
                            strongRequestMessage.Content);
                    responseMessage = strongresponseMessage;
                    break;
                }

                case RequestMsgType.Location:    //位置
                {
                    responseMessage = locationService.GetResponseMessage(requestMessage as RequestMessageLocation);
                    break;
                }

                case RequestMsgType.Image:    //图片
                {
                    //TODO:交给Service处理具体信息
                    var strongRequestMessage  = requestMessage as RequestMessageImage;
                    var strongresponseMessage =
                        ResponseMessageBase.CreateFromRequestMessage(requestMessage, ResponseMsgType.News) as
                        ResponseMessageNews;
                    strongresponseMessage.Articles.Add(new Article()
                        {
                            Title       = "您刚才发送了图片信息",
                            Description = "您发送的图片将会显示在边上",
                            PicUrl      = strongRequestMessage.PicUrl,
                            Url         = "http://weixin.senparc.com"
                        });
                    strongresponseMessage.Articles.Add(new Article()
                        {
                            Title       = "第二条",
                            Description = "第二条带连接的内容",
                            PicUrl      = strongRequestMessage.PicUrl,
                            Url         = "http://weixin.senparc.com"
                        });
                    responseMessage = strongresponseMessage;
                    break;
                }

                case RequestMsgType.Voice:    //语音
                {
                    //TODO:交给Service处理具体信息
                    var strongRequestMessage  = requestMessage as RequestMessageVoice;
                    var strongresponseMessage =
                        ResponseMessageBase.CreateFromRequestMessage(requestMessage, ResponseMsgType.Music) as
                        ResponseMessageMusic;
                    strongresponseMessage.Music.MusicUrl = "http://weixin.senparc.com/Content/music1.mp3";
                    responseMessage = strongresponseMessage;
                    break;
                }

                case RequestMsgType.Event:    //事件
                {
                    responseMessage = eventService.GetResponseMessage(requestMessage as RequestMessageEventBase);
                    break;
                }

                default:
                    throw new ArgumentOutOfRangeException();
                }
                var responseDoc = MP.Helpers.EntityHelper.ConvertEntityToXml(responseMessage);
                responseDoc.Save(Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Response_" + responseMessage.ToUserName + ".txt"));//测试时可开启,帮助跟踪数据

                return(Content(responseDoc.ToString()));
                //如果不需要记录responseDoc,只需要:
                //return Content(responseMessage.ConvertEntityToXmlString());
            }
            catch (Exception ex)
            {
                using (
                    TextWriter tw = new StreamWriter(Server.MapPath("~/App_Data/Error_" + DateTime.Now.Ticks + ".txt")))
                {
                    tw.WriteLine(ex.Message);
                    tw.WriteLine(ex.InnerException.Message);
                    if (requestDoc != null)
                    {
                        tw.WriteLine(requestDoc.ToString());
                    }
                    tw.Flush();
                    tw.Close();
                }
                return(Content(""));
            }
        }
        public static void CreateNfoFile(SeriesInfo seriesInfo, EpisodeInfo episodeInfo, string folderPath, string fileName, TVRenameShow tvRenameShow)
        {
            // create document
            XDocument infoDoc  = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
            XElement  rootElem = new XElement("episodedetails");


            // populate with correct nodes from series info and episode info
            rootElem.Add(new XElement("title", episodeInfo.EpisodeName ?? string.Empty));
            rootElem.Add(new XElement("rating", episodeInfo.Rating > 0 ? episodeInfo.Rating.ToString() : string.Empty));
            rootElem.Add(new XElement("season", episodeInfo.SeasonNumber));
            if (tvRenameShow.UseDvdOrder)
            {
                rootElem.Add(new XElement("episode", episodeInfo.DvdEpisodeNumber));
            }
            else
            {
                rootElem.Add(new XElement("episode", episodeInfo.EpisodeNumber));
            }

            rootElem.Add(new XElement("plot", episodeInfo.Overview ?? string.Empty));
            rootElem.Add(new XElement("thumb", episodeInfo.ThumbnailUrl ?? string.Empty));
            rootElem.Add(new XElement("playcount", 0));
            rootElem.Add(new XElement("lastplayed", string.Empty));
            rootElem.Add(new XElement("credits", episodeInfo.Writer ?? string.Empty));
            rootElem.Add(new XElement("director", episodeInfo.Director ?? string.Empty));
            rootElem.Add(new XElement("aired", episodeInfo.FirstAired ?? string.Empty));
            //rootElem.Add(new XElement("premiered", episodeInfo.FirstAired ?? string.Empty));
            rootElem.Add(new XElement("mpaa", seriesInfo.MpaaClassification ?? string.Empty));
            rootElem.Add(new XElement("premiered", seriesInfo.DatePremiered ?? string.Empty));
            rootElem.Add(new XElement("studio", seriesInfo.Studio ?? string.Empty));

            // actors from series
            foreach (var actorInfo in seriesInfo.Actors)
            {
                XElement actorElem = new XElement("actor");
                actorElem.Add(new XElement("name", actorInfo.Name ?? string.Empty));
                actorElem.Add(new XElement("role", actorInfo.Role ?? string.Empty));
                actorElem.Add(new XElement("thumb", actorInfo.ThumbnailUrl ?? string.Empty));
                rootElem.Add(actorElem);
            }
            // actors from episode
            foreach (var actorInfo in episodeInfo.GuestActors)
            {
                XElement actorElem = new XElement("actor");
                actorElem.Add(new XElement("name", actorInfo.Name ?? string.Empty));
                actorElem.Add(new XElement("role", actorInfo.Role ?? string.Empty));
                actorElem.Add(new XElement("thumb", actorInfo.ThumbnailUrl ?? string.Empty));
                rootElem.Add(actorElem);
            }

            infoDoc.Add(rootElem);

            // write document out to correct directory
            ConsoleLogger.LogStart("Creating episode NFO file...");
            if (!CustomConfiguration.DisableAllFileSystemActions)
            {
                infoDoc.Save(folderPath + "\\" + fileName);
            }
            ConsoleLogger.LogEnd("done.");
        }
Exemplo n.º 32
0
        public void Deactivate()
        {
            #if !WINDOWS_PHONE
            return;
            #else

            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {

                XDocument doc = new XDocument();
                XElement root = new XElement("ScreenManager");
                doc.Add(root);

                tempScreensList.Clear();
                foreach (GameScreen screen in screens)
                    tempScreensList.Add(screen);

                foreach (GameScreen screen in tempScreensList)
                {

                    if (screen.IsSerializable)
                    {

                        string playerValue = screen.ControllingPlayer.HasValue
                            ? screen.ControllingPlayer.Value.ToString()
                            : "";

                        root.Add(new XElement(
                            "GameScreen",
                            new XAttribute("Type", screen.GetType().AssemblyQualifiedName),
                            new XAttribute("ControllingPlayer", playerValue)));
                    }

                    screen.Deactivate();
                }

                using (IsolatedStorageFileStream stream = storage.CreateFile(StateFilename))
                {
                    doc.Save(stream);
                }
            }
            #endif
        }