Exemplo n.º 1
0
        public MainForm()
        {
            InitializeComponent();

            fileSystemWatcher1.EnableRaisingEvents = false;

            // For convenience.
            charts.Add(HeatersChart);
            charts.Add(RFChart);
            charts.Add(CavityChart);
            charts.Add(PowerInputChart);
            charts.Add(PowerSuppliesChart);
            charts.Add(HydrogenChart);
            charts.Add(IonPumpsChart);
            charts.Add(PllChart);
            charts.Add(TemperatureChart);

            foreach (Chart c in charts)
            {
                //c.ChartAreas[0].CursorX.LineColor = Color.Red;
                c.ChartAreas[0].CursorX.SelectionColor         = Color.Red;
                c.ChartAreas[0].CursorX.IsUserEnabled          = true;
                c.ChartAreas[0].CursorX.IsUserSelectionEnabled = true;
                c.ChartAreas[0].CursorX.IntervalType           = DateTimeIntervalType.Hours;
                c.ChartAreas[0].AxisX.ScaleView.Zoomable       = false;

                c.SelectionRangeChanged += C_SelectionRangeChanged;

                for (int i = 0; i < c.Series.Count; i++)
                {
                    c.Series[i].Color = palette[i];
                    // Below - test
                    c.Series[i].IsVisibleInLegend = false;

                    LegendItem l = new LegendItem(c.Series[i].Name, c.Series[i].Color, "");
                    l.Cells.Add(new LegendCell(LegendCellType.SeriesSymbol, ""));
                    LegendCell lc = new LegendCell(LegendCellType.Text, c.Series[i].Name);
                    lc.Font = c.Legends[0].Font;
                    l.Cells.Add(lc);

                    l.ImageStyle = LegendImageStyle.Line;
                    c.Legends[0].CustomItems.Add(l);
                }
            }

            statusLabel.Text = string.Format("Updated {0}", DateTime.UtcNow.ToLongTimeString());

            var     parser  = new FileIniDataParser();
            IniData iniData = parser.ReadFile("EFOS.ini");

            plotPath            = iniData["EfosView"]["plot-path"];
            logPath             = iniData["EfosMon"]["data-path"];
            logfilePrefix       = iniData["EfosMon"]["filename-prefix"];
            exportPlots         = bool.Parse(iniData["EfosView"]["export-plots"]);
            exportHistoricPlots = bool.Parse(iniData["EfosView"]["export-historic-plots"]);

            d           = new DataLoader(logPath);
            d.filenames = String.Format("{0} 20*.csv", logfilePrefix);

            // Run exportcharts in the background
            //if (exportPlots) {
            //    Task.Run(() => ExportCharts());

            //    // Wait untill ExportCharts has copied the charts
            //    doneCopyingCharts.WaitOne();
            //}

            var data = GetData(DateTime.UtcNow.AddHours(-span), DateTime.UtcNow, true);

            BindData(data, true);

            fileSystemWatcher1.Path   = logPath;
            fileSystemWatcher1.Filter = d.filenames;
            fileSystemWatcher1.EnableRaisingEvents = true;
        }
Exemplo n.º 2
0
        static ScanCodeMapper()
        {
            FileIniDataParser parser = new FileIniDataParser();

            data = parser.ReadFile("keyboard.ini");
        }
Exemplo n.º 3
0
        public SettingsForm(Form main, TableLayoutPanel headers, TableLayoutPanelArray playerControlArray, CurrentGameData currentGameData)
        {
            _header = headers;

            fonts = new Fonts(main);

            InitializeComponent();
            this.btnSettingsApply.Click += new System.EventHandler((sender, e) => BtnSettingsApply_Click(this, e, playerControlArray, currentGameData));
            this.btnSettingsOK.Click    += new System.EventHandler((sender, e) => BtnSettingsOK_Click(this, e, playerControlArray, currentGameData));

            settings = fileIniData.ReadFile(Settings.Default.IniFile);

            switch (Int32.Parse(settings[Settings.Default.IniSection]["Bounties"]))
            {
            case 0:
                rbNone.Checked = true;
                HideBountyColumn(_header, playerControlArray);
                break;

            case 1:
                rbOnRebuy.Checked = true;
                ShowBountyColumn(_header, playerControlArray);
                break;

            case 2:
                rbOnElimination.Checked = true;
                ShowBountyColumn(_header, playerControlArray);
                break;

            default:
                break;
            }

            switch (Int32.Parse(settings[Settings.Default.IniSection]["Blinds"]))
            {
            case 0:
                rbPDC.Checked = true;
                break;

            case 1:
                rbAVISTA.Checked = true;
                break;

            case 2:
                rbCustom.Checked = true;
                break;

            default:
                break;
            }

            if (bool.Parse(settings[Settings.Default.IniSection]["TimeIsPerPlayer"]))
            {
                rbPerPlayer.Checked = true;
            }
            else
            {
                rbPerRound.Checked = true;
            }

            nudRoundLength.Value    = (Int32.Parse(settings[Settings.Default.IniSection]["SecondsPerPlayer"]) / 60);
            nudMaxRoundLength.Value = (Int32.Parse(settings[Settings.Default.IniSection]["MaxSecondsPerRound"]) / 60);
            nudStartingChips.Value  = Int32.Parse(settings[Settings.Default.IniSection]["StartingChips"]);
            nudBuyinCost.Value      = Int32.Parse(settings[Settings.Default.IniSection]["BuyinCost"]);
            nudLastRebuyRound.Value = Int32.Parse(settings[Settings.Default.IniSection]["LastRebuyRound"]);

            List <string> existingLocations = settings[Settings.Default.IniSection]["ExistingLocations"].Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries).ToList();

            foreach (string location in existingLocations)
            {
                lbExistingLocations.Items.Add(location);
            }

            tbSaveFolder.Text = settings[Settings.Default.IniSection]["ResultsFolder"];
        }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            // creating a var to hold the location of our test files
            //
            string myFileLoc = @"C:\Users\thede\source\repos\GHNotesOnCSharp-001\GHNotesOnCSharp-001\";

            // reads a file, places each line as an array element
            //

            // Before I forget, do make a json file called: myTempFile.json

            /* Now, place these three lines into it:
             *
             *      {"Account":"myKitchen","Character":"stove","Password":"******"}
             *      {"Account":"myCat","Character":"kittens","Password":"******"}
             *      {"Account":"myFrog","Character":"poliwogs","Password":"******"}
             */

            List <string> lines = File.ReadAllLines(myFileLoc + "myTempFile.json").ToList();


            // output the number of elements in the lines array
            //
            Console.WriteLine("To grab the number of elements in the array that was created by the List object...");
            Console.WriteLine(lines.Capacity + "\n");

            // output one of the array elements
            //
            Console.WriteLine("Outputting one element of the array that was created...");
            Console.WriteLine(lines[0]);
            Console.ReadLine();             // a placeholder call for waiting for the user to hit enter before continuing

            // foreach loop: loops through an array & temporarily places an element value into line
            //
            Console.WriteLine("A foreach loop to output all of the elements of the array...");
            foreach (string line in lines)
            {
                Console.WriteLine(line);
            }
            Console.ReadLine();

            // for loop which outputs all of the elements of the array
            //
            Console.WriteLine("A for loop which outputs all of the elements of the array that had been created...");
            for (int i = 0; i < lines.Capacity; i++)
            {
                Console.WriteLine(lines[i]);
            }
            Console.ReadLine();


            // ** Works up to here! **
            Console.WriteLine("/n/n** THE CODE WORKS THIS FAR! **");
            Console.ReadLine();
            Console.Clear(); // clears the Console screen


            // --------------------------------------------------------
            //  Arithmetic operators:
            //                          + - * / % ++ --

            // --------------------------------------------------------
            //  Assignment operators:
            //                          = += -= /= %= &= |= ^= >>= <<=

            // --------------------------------------------------------
            //  Comparison operators:
            //                          == != > < >= <=

            // --------------------------------------------------------
            //  Logical operators:
            //                          && || !

            // Serializing the json file's values into a C# class object
            // We'll need to add Newtonsoft.Json to the list of using namespaces for the next example
            // In the properties window: rightClick the namespace, in this case it is: GHNotesOnCSharp-001
            //      Manage NuGet Packages > Browse > install Newtonsoft.Json
            //
            // Now, we'll need to make a class for holding our getters & setters
            // In the properties window: rightClick the namespace, in this case it is: GHNotesOnCSharp-001
            //      Add > Class > name it: PetAccount

            // Place these getters & setters into the body of the new class:

            /*
             *      class PetAccount
             *      {
             *          // serialized object from a json file:
             *          public string Account { get; set; }
             *          public string Character { get; set; }
             *          public string Password { get; set; }
             *      }
             */
            /*  Notes on the class objects:
             *      It is important to use the appropriate data type for the obj variables.
             *      If not, the serializing and deserializing of a Json or of an object will not match the original
             */


            // Necessary variable
            int profileMenu = 1;    // for selecting which object of the element of the array to output from the simpleTestFile.json file

            // Let's deserialize:
            // **Note**: the following will work for a single line of a json file
            //
            //List<string> linesB = File.ReadAllLines(myFileLoc + "myTempFile.json").ToList();
            string     jsonTemp    = lines[profileMenu];
            PetAccount petAccounts = JsonConvert.DeserializeObject <PetAccount>(jsonTemp);

            Console.WriteLine("Outputting one of the object values from our petAccounts object...");
            Console.WriteLine($"Account: {petAccounts.Account}");
            Console.ReadLine();

            // Let's serialize.
            // First, we'll change the values of one of the ojects:
            Console.WriteLine("Changing some of the object values from our petAccounts object...");
            petAccounts.Account   = "myGoat";
            petAccounts.Character = "kids";
            petAccounts.Password  = "******";

            // Since we changed an object's values, we now need to serialize the object

            string petAccountsTemp = JsonConvert.SerializeObject(petAccounts, Formatting.None);

            Console.WriteLine(petAccountsTemp);
            Console.ReadLine();

            lines[profileMenu] = petAccountsTemp;

            Console.WriteLine("A foreach loop to output each of the elements of the altered array...");
            foreach (string line in lines)
            {
                Console.WriteLine(line);
            }
            Console.ReadLine();

            // Now, and to save the newly altered and serialzed json lines we need to merge them...
            //

            string LinesTemp = lines[0];    // this initiates the temp var for the numerous json lines

            for (int i = 1; i < lines.Capacity; i++)
            {
                LinesTemp += ("\n" + lines[i]);
            }
            Console.WriteLine("Now, we'll see the json lines all stacked one on top of the other...");
            Console.WriteLine(LinesTemp);
            Console.ReadLine();

            Console.WriteLine("Now, it will save a new json file called myTempFile2.json");
            File.WriteAllText(myFileLoc + "myTempFile2.json", LinesTemp);
            Console.ReadLine();


            //  Working with ini files using ini-parser
            //

            // using an example ini:

            /*  myTestIni.ini:
             *      [settings]
             *      UserProfileEnabled=true
             *      ExitOnCompletion=true
             *
             */
            var     parser = new FileIniDataParser();
            IniData data   = parser.ReadFile("myTestIni.ini");

            // string UserProfileEnabled = data["settings"]["UserProfileEnabled"];
            // UseProfileScript contains "true"
            // bool UseProfileEnbld = bool.Parse(UserProfileEnabled);

            data["settings"]["UserProfileEnabled"] = "false";
            parser.WriteFile("myTestIni.ini", data);
Exemplo n.º 5
0
        public KeyManager()
        {
            var parser = new FileIniDataParser();

            data = parser.ReadFile(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "keys.ini");
        }
Exemplo n.º 6
0
        private void SetScreenSizeInPrefs()
        {
            if (SystemParameters == null)
            {
                throw new ArgumentNullException("System Parameters was null.  Cannot set screen size prefs");
            }
            var config = new IniParserConfiguration {
                AllowDuplicateKeys = true, AllowDuplicateSections = true
            };
            var oblivionPath = (RelativePath)"Oblivion.ini";

            foreach (var file in OutputFolder.Combine("profiles").EnumerateFiles()
                     .Where(f => ((string)f.FileName).EndsWith("refs.ini") || f.FileName == oblivionPath))
            {
                try
                {
                    var  parser   = new FileIniDataParser(new IniDataParser(config));
                    var  data     = parser.ReadFile((string)file);
                    bool modified = false;
                    if (data.Sections["Display"] != null)
                    {
                        if (data.Sections["Display"]["iSize W"] != null && data.Sections["Display"]["iSize H"] != null)
                        {
                            data.Sections["Display"]["iSize W"] =
                                SystemParameters.ScreenWidth.ToString(CultureInfo.CurrentCulture);
                            data.Sections["Display"]["iSize H"] =
                                SystemParameters.ScreenHeight.ToString(CultureInfo.CurrentCulture);
                            modified = true;
                        }
                    }
                    if (data.Sections["MEMORY"] != null)
                    {
                        if (data.Sections["MEMORY"]["VideoMemorySizeMb"] != null)
                        {
                            data.Sections["MEMORY"]["VideoMemorySizeMb"] =
                                SystemParameters.EnbLEVRAMSize.ToString(CultureInfo.CurrentCulture);
                            modified = true;
                        }
                    }

                    if (modified)
                    {
                        parser.WriteFile((string)file, data);
                    }
                }
                catch (Exception)
                {
                    Utils.Log($"Skipping screen size remap for {file} due to parse error.");
                }
            }

            var tweaksPath = (RelativePath)"SSEDisplayTweaks.ini";

            foreach (var file in OutputFolder.EnumerateFiles()
                     .Where(f => f.FileName == tweaksPath))
            {
                try
                {
                    var  parser   = new FileIniDataParser(new IniDataParser(config));
                    var  data     = parser.ReadFile((string)file);
                    bool modified = false;
                    if (data.Sections["Render"] != null)
                    {
                        if (data.Sections["Render"]["Resolution"] != null)
                        {
                            data.Sections["Render"]["Resolution"] =
                                $"{SystemParameters.ScreenWidth.ToString(CultureInfo.CurrentCulture)}x{SystemParameters.ScreenHeight.ToString(CultureInfo.CurrentCulture)}";
                            modified = true;
                        }
                    }

                    if (modified)
                    {
                        parser.WriteFile((string)file, data);
                    }
                }
                catch (Exception)
                {
                    Utils.Log($"Skipping screen size remap for {file} due to parse error.");
                }
            }
        }
Exemplo n.º 7
0
        private static bool FindEmuMMC(DriveInfo drive)
        {
            DirectoryInfo root      = drive.RootDirectory;
            FileInfo      emummcIni = root.GetFile("emuMMC/emummc.ini");

            if (emummcIni.Exists)
            {
                // find the DiskDrive associated with this drive letter
                VolumeInfo volume = AllVolumes
                                    .Where(x => x.Caption == drive.Name).FirstOrDefault();

                LogicalDiskInfo logicalDisk = AllLogicalDisks
                                              .Where(x => x.DeviceID == volume.DriveLetter).FirstOrDefault();

                IEnumerable <PartitionInfo> partitionsFromLogicalDisk = ToDiskPartitions(logicalDisk);
                if (!partitionsFromLogicalDisk.Any())
                {
                    return(false);
                }

                DiskInfo disk = AllDisks.Where(x => x.Index == partitionsFromLogicalDisk.First().DiskIndex).FirstOrDefault();

                IEnumerable <PartitionInfo> partitions = AllPartitions.Where(x => x.DiskIndex == disk.Index);

                // parse ini
                FileIniDataParser parser = new FileIniDataParser();

                IniData ini = parser.ReadFile(emummcIni.FullName);
                ini.SectionKeySeparator = '/';

                if (!ini.TryGetKey("emummc/sector", out string sectorStr))
                {
                    return(false);
                }

                ulong sector = ulong.Parse(sectorStr.Replace("0x", ""), System.Globalization.NumberStyles.HexNumber);

                PartitionInfo partition = partitions.Where(x =>
                                                           (sector * x.BlockSize)
                                                           - 0x1000000 /* hekate's 16MB padding to protect the emuMMC */

                                                           == x.StartingOffset).FirstOrDefault();

                bool usingEmummc = partition != null;
                if (usingEmummc)
                {
                    MessageBoxResult r = MessageBox.Show("emuMMC was detected on this SD card. Do you want to open that instead of sysMMC content?", "emuMMC", MessageBoxButton.YesNo);
                    if (r == MessageBoxResult.No)
                    {
                        usingEmummc = false;
                    }
                }

                if (usingEmummc)
                {
                    DeviceStream stream      = new DeviceStream(disk.PhysicalName, disk.Length);
                    IStorage     diskStorage = new CachedStorage(stream.AsStorage().AsReadOnly(), disk.SectorSize * 100, 4, true);
                    long         offset      = (long)partition.StartingOffset;
                    offset += 0x1000000; // account for hekate's padding
                    offset += 0x400000;  // BOOT0
                    offset += 0x400000;  // BOOT1


                    NANDService.InsertNAND(diskStorage.Slice(offset, (long)partition.Size), false);
                }

                return(usingEmummc);
            }

            return(false);
        }
        /*private static void ProvisionMissingApps()
         * {
         *  string SourceEdition = "Professional";
         *  string TargetEdition = "PPIPro";
         *  string UUPPath = @"C:\Users\Gus\Downloads\19635.1_amd64_en-us_multi_6d892fb5\UUPs";
         *
         *  CompDBXmlClass.CompDB neutralCompDB = null;
         *
         *  if (Directory.EnumerateFiles(UUPPath, "*aggregatedmetadata*").Count() > 0)
         *  {
         *      using (CabinetHandler cabinet = new CabinetHandler(File.OpenRead(Directory.EnumerateFiles(UUPPath, "*aggregatedmetadata*").First())))
         *      {
         *          IEnumerable<string> potentialNeutralFiles = cabinet.Files.Where(x =>
         *          x.ToLower().Contains($"desktoptargetcompdb_neutral"));
         *
         *          if (potentialNeutralFiles.Count() == 0)
         *              goto exit;
         *
         *          using (CabinetHandler cabinet2 = new CabinetHandler(cabinet.OpenFile(potentialNeutralFiles.First())))
         *          {
         *              string xmlfile = cabinet2.Files.First();
         *              using (Stream xmlstream = cabinet2.OpenFile(xmlfile))
         *              {
         *                  neutralCompDB = CompDBXmlClass.DeserializeCompDB(xmlstream);
         *              }
         *          }
         *      }
         *  }
         *  else
         *  {
         *      IEnumerable<string> files = Directory.EnumerateFiles(UUPPath).Select(x => Path.GetFileName(x));
         *
         *      IEnumerable<string> potentialNeutralFiles = files.Where(x =>
         *             x.ToLower().Contains($"desktoptargetcompdb_neutral"));
         *
         *      if (potentialNeutralFiles.Count() == 0)
         *          goto exit;
         *
         *      using (CabinetHandler cabinet2 = new CabinetHandler(File.OpenRead(Path.Combine(UUPPath, potentialNeutralFiles.First()))))
         *      {
         *          string xmlfile = cabinet2.Files.First();
         *          using (Stream xmlstream = cabinet2.OpenFile(xmlfile))
         *          {
         *              neutralCompDB = CompDBXmlClass.DeserializeCompDB(xmlstream);
         *          }
         *      }
         *  }
         *
         *  var apppackages = neutralCompDB.Features.Feature.First(x => x.FeatureID == "BaseNeutral").Packages.Package.Select(x => x.ID.Split('_').Last()).Where(x => x.StartsWith("Microsoft.ModernApps.", StringComparison.InvariantCultureIgnoreCase));
         *
         *  bool sourceneedsclientpack = !SourceEdition.StartsWith("enterpriseg", StringComparison.InvariantCultureIgnoreCase) && !SourceEdition.StartsWith("ppipro", StringComparison.InvariantCultureIgnoreCase);
         *  bool sourceneedsclientnpack = SourceEdition.EndsWith("n", StringComparison.InvariantCultureIgnoreCase) || SourceEdition.EndsWith("neval", StringComparison.InvariantCultureIgnoreCase);
         *
         *  bool targetneedsclientpack = !TargetEdition.StartsWith("enterpriseg", StringComparison.InvariantCultureIgnoreCase) && !SourceEdition.StartsWith("ppipro", StringComparison.InvariantCultureIgnoreCase);
         *  bool targetneedsclientnpack = TargetEdition.EndsWith("n", StringComparison.InvariantCultureIgnoreCase) || TargetEdition.EndsWith("neval", StringComparison.InvariantCultureIgnoreCase);
         *
         *  List<string> SourceEditionApps = new List<string>();
         *  List<string> TargetEditionApps = new List<string>();
         *
         *  var potentialSourceEditionAppPackages = apppackages.Where(x => x.ToLower().Contains(SourceEdition.ToLower().TrimEnd('n')));
         *  if (potentialSourceEditionAppPackages.Count() > 0)
         *  {
         *      var apppackage = potentialSourceEditionAppPackages.First();
         *      string[] entries;
         *      imagingInterface.EnumerateFiles(Path.Combine(UUPPath, apppackage + ".esd"), 1, "", out entries);
         *      foreach (var entry in entries)
         *      {
         *          if (entry.ToLower() != "$filehashes$.dat")
         *          {
         *              string[] entries2;
         *              imagingInterface.EnumerateFiles(Path.Combine(UUPPath, apppackage + ".esd"), 1, entry, out entries2);
         *              var pkg = entries2.Where(x => x.ToLower() != "appxsignature.p7x" && x.ToLower() != "appxblockmap.xml" && x.ToLower() != "appxmetadata").First();
         *              var newpkg = pkg.Split('_')[0] + "_" + pkg.Split('_')[1] + "_neutral_~_" + pkg.Split('_')[4];
         *              bool isbundle = entries2.Any(x => x.ToLower() == "appxmetadata");
         *              SourceEditionApps.Add($"{entry}|{pkg}|{pkg.Split('_')[0]}|{newpkg}|{isbundle}");
         *          }
         *      }
         *  }
         *
         *  if (sourceneedsclientpack)
         *  {
         *      string package = "microsoft.modernapps.client.all.esd";
         *      if (sourceneedsclientnpack)
         *      {
         *          package = "microsoft.modernapps.clientn.all.esd";
         *      }
         *
         *      string[] entries;
         *      imagingInterface.EnumerateFiles(Path.Combine(UUPPath, package), 1, "", out entries);
         *      foreach (var entry in entries)
         *      {
         *          if (entry.ToLower() != "$filehashes$.dat")
         *          {
         *              string[] entries2;
         *              imagingInterface.EnumerateFiles(Path.Combine(UUPPath, package), 1, entry, out entries2);
         *              var pkg = entries2.Where(x => x.ToLower() != "appxsignature.p7x" && x.ToLower() != "appxblockmap.xml" && x.ToLower() != "appxmetadata").First();
         *              var newpkg = pkg.Split('_')[0] + "_" + pkg.Split('_')[1] + "_neutral_~_" + pkg.Split('_')[4];
         *              bool isbundle = entries2.Any(x => x.ToLower() == "appxmetadata");
         *              SourceEditionApps.Add($"{entry}|{pkg}|{pkg.Split('_')[0]}|{newpkg}|{isbundle}");
         *          }
         *      }
         *  }
         *
         *  var potentialTargetEditionAppPackages = apppackages.Where(x => x.ToLower().Contains(TargetEdition.ToLower().TrimEnd('n')));
         *  if (potentialTargetEditionAppPackages.Count() > 0)
         *  {
         *      var apppackage = potentialTargetEditionAppPackages.First();
         *      string[] entries;
         *      imagingInterface.EnumerateFiles(Path.Combine(UUPPath, apppackage + ".esd"), 1, "", out entries);
         *      foreach (var entry in entries)
         *      {
         *          if (entry.ToLower() != "$filehashes$.dat")
         *          {
         *              string[] entries2;
         *              imagingInterface.EnumerateFiles(Path.Combine(UUPPath, apppackage + ".esd"), 1, entry, out entries2);
         *              var pkg = entries2.Where(x => x.ToLower() != "appxsignature.p7x" && x.ToLower() != "appxblockmap.xml" && x.ToLower() != "appxmetadata").First();
         *              var newpkg = pkg.Split('_')[0] + "_" + pkg.Split('_')[1] + "_neutral_~_" + pkg.Split('_')[4];
         *              bool isbundle = entries2.Any(x => x.ToLower() == "appxmetadata");
         *              TargetEditionApps.Add($"{entry}|{pkg}|{pkg.Split('_')[0]}|{newpkg}|{isbundle}");
         *          }
         *      }
         *  }
         *
         *  if (targetneedsclientpack)
         *  {
         *      string package = "microsoft.modernapps.client.all.esd";
         *      if (targetneedsclientnpack)
         *      {
         *          package = "microsoft.modernapps.clientn.all.esd";
         *      }
         *
         *      string[] entries;
         *      imagingInterface.EnumerateFiles(Path.Combine(UUPPath, package), 1, "", out entries);
         *      foreach (var entry in entries)
         *      {
         *          if (entry.ToLower() != "$filehashes$.dat")
         *          {
         *              string[] entries2;
         *              imagingInterface.EnumerateFiles(Path.Combine(UUPPath, package), 1, entry, out entries2);
         *              var pkg = entries2.Where(x => x.ToLower() != "appxsignature.p7x" && x.ToLower() != "appxblockmap.xml" && x.ToLower() != "appxmetadata").First();
         *              var newpkg = pkg.Split('_')[0] + "_" + pkg.Split('_')[1] + "_neutral_~_" + pkg.Split('_')[4];
         *              bool isbundle = entries2.Any(x => x.ToLower() == "appxmetadata");
         *              TargetEditionApps.Add($"{entry}|{pkg}|{pkg.Split('_')[0]}|{newpkg}|{isbundle}");
         *          }
         *      }
         *  }
         *
         *  SourceEditionApps.Sort();
         *  TargetEditionApps.Sort();
         *
         *  Console.WriteLine("Source apps (" + SourceEdition + ")");
         *  foreach (var app in SourceEditionApps)
         *  {
         *      Console.WriteLine(app);
         *  }
         *  Console.WriteLine();
         *
         *  Console.WriteLine("Target apps (" + TargetEdition + ")");
         *  foreach (var app in TargetEditionApps)
         *  {
         *      Console.WriteLine(app);
         *  }
         *  Console.WriteLine();
         *
         *  var common = TargetEditionApps.Intersect(SourceEditionApps);
         *
         *  Console.WriteLine("The following apps must be uninstalled");
         *  foreach (var app in SourceEditionApps.Except(common))
         *  {
         *      Console.WriteLine(app);
         *  }
         *  Console.WriteLine();
         *
         *  Console.WriteLine("The following apps must be installed");
         *  foreach (var app in TargetEditionApps.Except(common))
         *  {
         *      Console.WriteLine(app);
         *  }
         *  Console.WriteLine();
         *
         * exit:
         *  return;
         * }*/

        public static bool CreateHackedEditionFromMountedImage(
            string UUPPath,
            string MediaPath,
            string MountedImagePath,
            string EditionID,
            string OutputInstallImage,
            Common.CompressionType CompressionType,
            ProgressCallback progressCallback = null)
        {
            bool result = true;

            progressCallback?.Invoke(Common.ProcessPhase.ApplyingImage, true, 0, "Applying " + EditionID + " - Package Swap");

            progressCallback?.Invoke(Common.ProcessPhase.ApplyingImage, true, 0, "Getting serial for " + EditionID);
            string productinifilepath = Path.Combine(MediaPath, "sources", "product.ini");

            var     parser = new FileIniDataParser();
            IniData data   = parser.ReadFile(productinifilepath);

            string serial = data["cmi"].First(x => x.KeyName.ToLower() == EditionID.ToLower()).Value;

            progressCallback?.Invoke(Common.ProcessPhase.ApplyingImage, true, 0, "Serial: " + serial);

            progressCallback?.Invoke(Common.ProcessPhase.ApplyingImage, true, 0, "Getting current edition");
            string SourceEdition = DismOperations.GetCurrentEdition(MountedImagePath);

            progressCallback?.Invoke(Common.ProcessPhase.ApplyingImage, true, 0, "Current edition is: " + SourceEdition);

            progressCallback?.Invoke(Common.ProcessPhase.ApplyingImage, true, 0, "Getting wim info for: " + OutputInstallImage);
            WIMInformationXML.WIM wiminfo;
            result = imagingInterface.GetWIMInformation(OutputInstallImage, out wiminfo);
            if (!result)
            {
                goto exit;
            }

            progressCallback?.Invoke(Common.ProcessPhase.ApplyingImage, true, 0, "Searching index for : " + SourceEdition);
            var srcimage = wiminfo.IMAGE.First(x =>
            {
                var img = x;
                var win = img.WINDOWS;
                var ed  = win.EDITIONID;
                return(ed.Equals(SourceEdition, StringComparison.InvariantCultureIgnoreCase));
            });
            var index        = int.Parse(srcimage.INDEX);
            var languagecode = srcimage.WINDOWS.LANGUAGES.DEFAULT;

            progressCallback?.Invoke(Common.ProcessPhase.ApplyingImage, true, 0, "Source index: " + index);
            progressCallback?.Invoke(Common.ProcessPhase.ApplyingImage, true, 0, "Source language: " + languagecode);

            WimCompressionType compression = WimCompressionType.None;

            switch (CompressionType)
            {
            case Common.CompressionType.LZMS:
                compression = WimCompressionType.Lzms;
                break;

            case Common.CompressionType.LZX:
                compression = WimCompressionType.Lzx;
                break;

            case Common.CompressionType.XPRESS:
                compression = WimCompressionType.Xpress;
                break;
            }

            //
            // Perform edition hack
            //
            string servicingPath = Path.Combine(MountedImagePath, "Windows", "servicing", "Packages");
            string manifest      = $"Microsoft-Windows-{SourceEdition}Edition~31bf3856ad364e35~*~~10.0.*.*.mum";
            string catalog       = $"Microsoft-Windows-{SourceEdition}Edition~31bf3856ad364e35~*~~10.0.*.*.cat";
            string manifestPath  = Directory.EnumerateFiles(servicingPath, manifest).First();
            string catalogPath   = Directory.EnumerateFiles(servicingPath, catalog).First();

            bool LTSB = false;

            if (EditionID.ToLower().StartsWith("enterpriseg") ||
                EditionID.ToLower().StartsWith("enterprises") ||
                EditionID.ToLower().StartsWith("iotenterprises"))
            {
                LTSB = true;
            }

            bool HasEditionPack = Directory.EnumerateFiles(UUPPath, "*.esd", SearchOption.AllDirectories).Any(x =>
                                                                                                              Path.GetFileName(x).Equals($"microsoft-windows-editionpack-{EditionID}-package.esd", StringComparison.InvariantCultureIgnoreCase)
                                                                                                              );

            progressCallback?.Invoke(Common.ProcessPhase.ApplyingImage, true, 0, "Has edition pack: " + HasEditionPack);

            string TemporaryFolder = Path.GetTempFileName();

            File.Delete(TemporaryFolder);
            Directory.CreateDirectory(TemporaryFolder);

            string SxSFolder = Path.Combine(TemporaryFolder, "SxS");

            Directory.CreateDirectory(SxSFolder);

            //
            // Build reconstructed edition xml
            //
            progressCallback?.Invoke(Common.ProcessPhase.ApplyingImage, true, 0, "Generating edition manifest");
            string packageFilter = $"microsoft-windows-edition*{EditionID}-*.esd";
            var    packages      = Directory.EnumerateFiles(UUPPath, packageFilter, SearchOption.AllDirectories);

            string manifestFileName = Path.GetFileName(manifestPath).Replace(SourceEdition, EditionID);
            string catalogFileName  = Path.GetFileName(catalogPath).Replace(SourceEdition, EditionID);

            string newManifestPath = Path.Combine(SxSFolder, manifestFileName);
            string newCatalogPath  = Path.Combine(SxSFolder, catalogFileName);

            File.Copy(manifestPath, newManifestPath);
            File.Copy(catalogPath, newCatalogPath);

            string ManifestContent = File.ReadAllText(newManifestPath);

            ManifestContent = ManifestContent.Replace($"EditionSpecific-{SourceEdition}", $"EditionSpecific-{EditionID}").Replace($"Windows {SourceEdition} Edition", $"Windows {EditionID} Edition").Replace($"Microsoft-Windows-{SourceEdition}Edition", $"Microsoft-Windows-{EditionID}Edition");

            if (HasEditionPack)
            {
                ManifestContent = ManifestContent.Replace($"EditionPack-{SourceEdition}", $"EditionPack-{EditionID}");
            }

            File.WriteAllText(newManifestPath, ManifestContent);

            if (LTSB)
            {
                AssemblyManifestHandler.RemoveNonLTSBPackages(newManifestPath);
            }

            // Cleanup WOW64
            if (!packages.Any(x => x.Equals($"microsoft-windows-editionspecific-{EditionID}-wow64-package.esd", StringComparison.InvariantCultureIgnoreCase)))
            {
                progressCallback?.Invoke(Common.ProcessPhase.ApplyingImage, true, 0, "Cleaning up WOW64");
                AssemblyManifestHandler.RemoveWOW64Package(newManifestPath, $"microsoft-windows-editionspecific-{EditionID}-wow64-package");
            }

            //
            // Expand LP to folder
            //
            if (LPFolder == null)
            {
                LPFolder = Path.GetTempFileName();
                File.Delete(LPFolder);
                Directory.CreateDirectory(LPFolder);

                string lpfilter1 = $"*fre_client_{languagecode}_lp.cab";
                var    paths     = Directory.EnumerateFiles(UUPPath, lpfilter1, SearchOption.AllDirectories);
                if (paths.Count() > 0)
                {
                    string lppackage = paths.First();
                    void ProgressCallback(int percent, string file)
                    {
                        progressCallback?.Invoke(Common.ProcessPhase.PreparingFiles, false, percent, "Unpacking " + file + "...");
                    };

                    CabinetHandler.ExpandFiles(lppackage, LPFolder, ProgressCallback);
                }
                else
                {
                    string lpfilter2 = $"microsoft-windows-client-languagepack-package_{languagecode}-*-{languagecode}.esd";
                    string lppackage = "";
                    if (Directory.EnumerateFiles(UUPPath, lpfilter2, SearchOption.AllDirectories).Count() > 0)
                    {
                        lppackage = Directory.EnumerateFiles(UUPPath, lpfilter2, SearchOption.AllDirectories).First();
                    }
                    else
                    {
                        lpfilter2 = $"microsoft-windows-client-languagepack-package_{languagecode}~*~{languagecode}~.esd";
                        lppackage = Directory.EnumerateFiles(UUPPath, lpfilter2, SearchOption.AllDirectories).First();
                    }

                    result = imagingInterface.ApplyImage(lppackage, 1, LPFolder, PreserveACL: false, progressCallback: callback2);
                    if (!result)
                    {
                        goto exit;
                    }
                }
            }

            //
            // Expand Edition related packages to SxS folder
            //
            foreach (var package in packages)
            {
                result = imagingInterface.ApplyImage(package, 1, SxSFolder, PreserveACL: false, progressCallback: callback2);
                if (!result)
                {
                    goto exit;
                }

                if (File.Exists(Path.Combine(SxSFolder, "update.mum")))
                {
                    var    assembly = AssemblyManifestHandler.Deserialize(File.ReadAllText(Path.Combine(SxSFolder, "update.mum")));
                    string cbsKey   = assembly.AssemblyIdentity.Name + "~" + assembly.AssemblyIdentity.PublicKeyToken + "~" + assembly.AssemblyIdentity.ProcessorArchitecture + "~" + (assembly.AssemblyIdentity.Language.ToLower() == "neutral" ? "" : assembly.AssemblyIdentity.Language) + "~" + assembly.AssemblyIdentity.Version;
                    if (!File.Exists(Path.Combine(SxSFolder, cbsKey + ".mum")))
                    {
                        File.Move(Path.Combine(SxSFolder, "update.mum"), Path.Combine(SxSFolder, cbsKey + ".mum"));
                    }
                    else
                    {
                        File.Delete(Path.Combine(SxSFolder, "update.mum"));
                    }

                    if (File.Exists(Path.Combine(SxSFolder, "update.cat")))
                    {
                        if (!File.Exists(Path.Combine(SxSFolder, cbsKey + ".cat")))
                        {
                            File.Move(Path.Combine(SxSFolder, "update.cat"), Path.Combine(SxSFolder, cbsKey + ".cat"));
                        }
                        else
                        {
                            File.Delete(Path.Combine(SxSFolder, "update.cat"));
                        }
                    }
                }
                File.Delete(Path.Combine(SxSFolder, "$filehashes$.dat"));
            }

            //
            // Generate unattend
            //
            progressCallback?.Invoke(Common.ProcessPhase.ApplyingImage, true, 0, "Generating unattend");
            string arch = manifestFileName.Split('~')[2];
            string ver  = manifestFileName.Split('~')[4].Replace(".mum", "");

            bool removeogedition = true;

            // TODO: get these from matrix
            //
            if (SourceEdition.Equals("core", StringComparison.InvariantCultureIgnoreCase))
            {
                if (EditionID.Equals("corecountryspecific", StringComparison.InvariantCultureIgnoreCase))
                {
                    removeogedition = false;
                }
            }
            if (SourceEdition.Equals("professional", StringComparison.InvariantCultureIgnoreCase))
            {
                if (EditionID.Equals("core", StringComparison.InvariantCultureIgnoreCase))
                {
                    removeogedition = false;
                }
            }
            if (SourceEdition.Equals("professionaln", StringComparison.InvariantCultureIgnoreCase))
            {
                if (EditionID.Equals("coren", StringComparison.InvariantCultureIgnoreCase))
                {
                    removeogedition = false;
                }
            }
            if (SourceEdition.Equals("core", StringComparison.InvariantCultureIgnoreCase))
            {
                if (EditionID.Equals("starter", StringComparison.InvariantCultureIgnoreCase))
                {
                    removeogedition = false;
                }
            }
            if (SourceEdition.Equals("coren", StringComparison.InvariantCultureIgnoreCase))
            {
                if (EditionID.Equals("startern", StringComparison.InvariantCultureIgnoreCase))
                {
                    removeogedition = false;
                }
            }

            string unattend = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                              "<unattend xmlns=\"urn:schemas-microsoft-com:unattend\">\n" +
                              "    <servicing>\n";

            if (!removeogedition)
            {
                unattend +=
                    "        <package action=\"stage\">\n" +
                    $"            <assemblyIdentity name=\"Microsoft-Windows-{SourceEdition}Edition\" version=\"{ver}\" processorArchitecture=\"{arch}\" publicKeyToken=\"31bf3856ad364e35\" language=\"neutral\" />\n" +
                    "        </package>\n";
            }

            unattend +=
                "        <package action=\"stage\">\n" +
                $"            <assemblyIdentity name=\"Microsoft-Windows-{EditionID}Edition\" version=\"{ver}\" processorArchitecture=\"{arch}\" publicKeyToken=\"31bf3856ad364e35\" language=\"neutral\" />\n" +
                $"            <source location=\"{newManifestPath}\" />\n" +
                "        </package>\n";

            if (removeogedition)
            {
                unattend +=
                    "        <package action=\"remove\">\n" +
                    $"            <assemblyIdentity name=\"Microsoft-Windows-{SourceEdition}Edition\" version=\"{ver}\" processorArchitecture=\"{arch}\" publicKeyToken=\"31bf3856ad364e35\" language=\"neutral\" />\n" +
                    "        </package>\n";
            }

            unattend +=
                "        <package action=\"install\">\n" +
                $"            <assemblyIdentity name=\"Microsoft-Windows-{EditionID}Edition\" version=\"{ver}\" processorArchitecture=\"{arch}\" publicKeyToken=\"31bf3856ad364e35\" language=\"neutral\" />\n" +
                "        </package>\n" +
                "        <package action=\"install\">\n" +
                $"            <assemblyIdentity name=\"Microsoft-Windows-Client-LanguagePack-Package\" version=\"{ver}\" processorArchitecture=\"{arch}\" publicKeyToken=\"31bf3856ad364e35\" language=\"{languagecode}\" />\n" +
                $"            <source location=\"{LPFolder}\\update.mum\" />\n" +
                "        </package>\n" +
                "    </servicing>\n" +
                "</unattend>";

            string unattendPath = Path.Combine(TemporaryFolder, "unattend.xml");

            File.WriteAllText(unattendPath, unattend);

            //
            // Backup OEMDefaultAssociations
            //
            progressCallback?.Invoke(Common.ProcessPhase.ApplyingImage, true, 0, "Backing up OEMDefaultAssociations");

            bool HandleOEMDefaultAssociationsXml = File.Exists(Path.Combine(MountedImagePath, "Windows", "System32", "OEMDefaultAssociations.xml"));
            bool HandleOEMDefaultAssociationsDll = File.Exists(Path.Combine(MountedImagePath, "Windows", "System32", "OEMDefaultAssociations.dll"));

            string OEMDefaultAssociationsXml = Path.GetTempFileName();
            string OEMDefaultAssociationsDll = Path.GetTempFileName();

            File.Delete(OEMDefaultAssociationsXml);
            File.Delete(OEMDefaultAssociationsDll);

            string OEMDefaultAssociationsXmlInImage = Path.Combine(MountedImagePath, "Windows", "System32", "OEMDefaultAssociations.xml");
            string OEMDefaultAssociationsDllInImage = Path.Combine(MountedImagePath, "Windows", "System32", "OEMDefaultAssociations.dll");

            if (HandleOEMDefaultAssociationsXml)
            {
                File.Copy(OEMDefaultAssociationsXmlInImage, OEMDefaultAssociationsXml);
            }

            if (HandleOEMDefaultAssociationsDll)
            {
                File.Copy(OEMDefaultAssociationsDllInImage, OEMDefaultAssociationsDll);
            }

            //
            // Apply unattend
            //
            progressCallback?.Invoke(Common.ProcessPhase.ApplyingImage, true, 0, "Applying unattend");
            DismOperations.ApplyUnattend(MountedImagePath, unattendPath);

            //
            // Restore OEMDefaultAssociations
            //
            progressCallback?.Invoke(Common.ProcessPhase.ApplyingImage, true, 0, "Restoring up OEMDefaultAssociations");

            if (HandleOEMDefaultAssociationsXml)
            {
                if (!File.Exists(OEMDefaultAssociationsXmlInImage))
                {
                    File.Move(OEMDefaultAssociationsXml, OEMDefaultAssociationsXmlInImage);
                }
            }

            if (HandleOEMDefaultAssociationsDll)
            {
                if (!File.Exists(OEMDefaultAssociationsDllInImage))
                {
                    File.Move(OEMDefaultAssociationsDll, OEMDefaultAssociationsDllInImage);
                }
            }

            //
            // Copy edition xml
            //
            progressCallback?.Invoke(Common.ProcessPhase.ApplyingImage, true, 0, "Handling Edition Unattend XML");
            string editionXml            = Path.Combine(MountedImagePath, "Windows", "servicing", "Editions", $"{EditionID}Edition.xml");
            string desintationEditionXml = Path.Combine(MountedImagePath, "Windows", $"{EditionID}.xml");

            File.Copy(editionXml, desintationEditionXml);

            //
            // Delete old edition xml
            //
            File.Delete(Path.Combine(MountedImagePath, "Windows", $"{SourceEdition}.xml"));

            //
            // Apply edition xml as unattend
            //
            progressCallback?.Invoke(Common.ProcessPhase.ApplyingImage, true, 0, "Applying Edition Unattend XML");
            DismOperations.ApplyUnattend(MountedImagePath, desintationEditionXml);

            //
            // Install correct product key
            //
            progressCallback?.Invoke(Common.ProcessPhase.ApplyingImage, true, 0, "Installing product key");

            DismOperations.SetProductKey(MountedImagePath, serial);

            //
            // Application handling
            //
            progressCallback?.Invoke(Common.ProcessPhase.ApplyingImage, true, 0, "Installing apps");

            //////////////////////// TODO ////////////////////////

            //
            // Cleanup
            //
            progressCallback?.Invoke(Common.ProcessPhase.ApplyingImage, true, 0, "Cleaning up");
            Directory.Delete(TemporaryFolder, true);
            CleanupLanguagePackFolderIfRequired();

            void callback2(string Operation, int ProgressPercentage, bool IsIndeterminate)
            {
                progressCallback?.Invoke(Common.ProcessPhase.CapturingImage, IsIndeterminate, ProgressPercentage, Operation);
            };

            string name = $"Windows 10 {EditionID}";

            if (Constants.FriendlyEditionNames.Any(x => x.Key.Equals(EditionID, StringComparison.InvariantCultureIgnoreCase)))
            {
                name = Constants.FriendlyEditionNames.First(x => x.Key.Equals(EditionID, StringComparison.InvariantCultureIgnoreCase)).Value;
            }

            result = imagingInterface.CaptureImage(
                OutputInstallImage,
                name,
                name,
                EditionID,
                MountedImagePath,
                name,
                name,
                compression,
                progressCallback: callback2,
                UpdateFrom: index);

            if (!result)
            {
                goto exit;
            }

            WIMInformationXML.IMAGE tmpImageInfo;
            result = imagingInterface.GetWIMImageInformation(OutputInstallImage, wiminfo.IMAGE.Count + 1, out tmpImageInfo);
            if (!result)
            {
                goto exit;
            }

            var sku = tmpImageInfo.WINDOWS.EDITIONID;

            tmpImageInfo.WINDOWS           = srcimage.WINDOWS;
            tmpImageInfo.WINDOWS.EDITIONID = sku;
            tmpImageInfo.FLAGS             = sku;
            tmpImageInfo.NAME               = name;
            tmpImageInfo.DESCRIPTION        = name;
            tmpImageInfo.DISPLAYNAME        = name;
            tmpImageInfo.DISPLAYDESCRIPTION = name;

            result = imagingInterface.SetWIMImageInformation(OutputInstallImage, wiminfo.IMAGE.Count + 1, tmpImageInfo);
            if (!result)
            {
                goto exit;
            }

exit:
            return(result);
        }
Exemplo n.º 9
0
        public static void Init()
        {
            if (dict.Count > 0 && rdict.Count > 0)
            {
                return;
            }

            dict.Add("A0", "UserDefinedMetric (1189.00 x 841.00毫米)");
            dict.Add("A01", "UserDefinedMetric (1486.00 x 841.00毫米)");
            dict.Add("A02", "UserDefinedMetric (1784.00 x 841.00毫米)");
            dict.Add("A03", "UserDefinedMetric (2081.00 x 841.00毫米)");
            dict.Add("A04", "UserDefinedMetric (2378.00 x 841.00毫米)");

            dict.Add("A1", "ISO_full_bleed_A1_(841.00_x_594.00_MM)");
            dict.Add("A11", "UserDefinedMetric (1051.00 x 594.00毫米)");
            dict.Add("A12", "UserDefinedMetric (1262.00 x 594.00毫米)");
            dict.Add("A13", "UserDefinedMetric (1472.00 x 594.00毫米)");
            dict.Add("A14", "UserDefinedMetric (1682.00 x 594.00毫米)");
            dict.Add("A2", "ISO_full_bleed_A2_(594.00_x_420.00_MM)");
            dict.Add("A21", "UserDefinedMetric (743.00 x 420.00毫米)");
            dict.Add("A22", "UserDefinedMetric (891.00 x 420.00毫米)");
            dict.Add("A23", "UserDefinedMetric (1040.00 x 420.00毫米)");
            dict.Add("A24", "UserDefinedMetric (1188.00 x 420.00毫米)");



            rdict.Add("A0", "ISO_A0_(841.00_x_1189.00_MM)");
            rdict.Add("A01", "UserDefinedMetric (841.00 x 1486.00毫米)");
            rdict.Add("A02", "UserDefinedMetric (841.00 x 1784.00毫米)");
            rdict.Add("A03", "UserDefinedMetric (841.00 x 2081.00毫米)");
            rdict.Add("A04", "UserDefinedMetric (841.00 x 2378.00毫米)");

            rdict.Add("A1", "ISO_full_bleed_A1_(594.00_x_841.00_MM)");

            rdict.Add("A11", "UserDefinedMetric (594.00 x 1051.00毫米)");
            rdict.Add("A12", "UserDefinedMetric (594.00 x 1262.00毫米)");
            rdict.Add("A13", "UserDefinedMetric (594.00 x 1472.00毫米)");
            rdict.Add("A14", "UserDefinedMetric (594.00 x 1682.00毫米)");
            rdict.Add("A2", "ISO_full_bleed_A2_(420.00_x_594.00_MM)");
            rdict.Add("A21", "UserDefinedMetric (420.00 x 743.00毫米)");
            rdict.Add("A22", "UserDefinedMetric (420.00 x 891.00毫米)");
            rdict.Add("A23", "UserDefinedMetric (420.00 x 1040.00毫米)");
            rdict.Add("A24", "UserDefinedMetric (420.00 x 1188.00毫米)");

            fileIniData = new FileIniDataParser();
            fileIniData.Parser.Configuration.CommentString = "#";

            string ddd = System.Environment.CurrentDirectory;
            string eee = System.IO.Directory.GetCurrentDirectory();

            try
            {
                parsedData = fileIniData.ReadFile(getCfgPath() + "\\BatchPlotPdf.ini");
            }
            catch (Exception)
            {
                PdfUtil.setXs(50);
                PdfUtil.setYs(100);
                PdfUtil.setRxs(300);
                PdfUtil.setRys(400);
                PdfUtil.setSmaxy(0.1);
                PdfUtil.setSmaxx(0.02);
            }
        }
Exemplo n.º 10
0
        public static Config LoadMacrosFromConfig(string configFilePath)
        {
            var parser = new FileIniDataParser();

            if (!File.Exists(configFilePath))
            {
                CreateSampleConfig(configFilePath);
            }

            // Load file
            IniData iniConfig;

            try
            {
                iniConfig = parser.ReadFile(configFilePath, Encoding.UTF8);
            }
            catch (ParsingException)
            {
                // Errors thrown inside ini-parser library
                throw new ConfigException("Could not parse configuration file. Make sure the syntax is correct.");
            }
            catch (Exception e)
            {
                throw new ConfigException(e.Message);
            }

            // Parse macro definitions
            List <MacroCommand> macros;

            try
            {
                macros = ParseMacroConfig(iniConfig);
            }
            catch (InvalidMacroDefinition e)
            {
                throw new ConfigException(e.Message);
            }
            catch (Exception e)
            {
                throw new ConfigException(e.Message);
            }

            // Parse menu toggling shortcut
            var menuKey = KeyCode.None;

            if (iniConfig.Global.ContainsKey("toggle_menu_shortcut"))
            {
                var toggleMenuKeyStr = iniConfig.Global.GetKeyData("toggle_menu_shortcut").Value;

                try
                {
                    menuKey = (KeyCode)Enum.Parse(typeof(KeyCode), toggleMenuKeyStr, false);
                }
                catch (Exception)
                {
                    throw new ConfigException("Menu toggle shortcut must be a known KeyCode. See: https://docs.unity3d.com/ScriptReference/KeyCode.html");
                }
            }

            return(new Config(macros, menuKey));
        }
Exemplo n.º 11
0
        protected override void OnStart(string[] args)
        {
            FileIniDataParser parser = new FileIniDataParser();

            config = parser.ReadFile(AppDomain.CurrentDomain.BaseDirectory + "config.ini", System.Text.Encoding.UTF8);

            int portPointer = 5410;

            http                  = new HttpServer();
            http.EndPoint         = new IPEndPoint(IPAddress.Loopback, portPointer);
            http.RequestReceived += HTTPRequest;
            http.Start();

            foreach (SectionData section in config.Sections)
            {
                portPointer++;
                string ip   = section.SectionName;
                int    port = portPointer;
                if (ProxiesConfig.ContainsKey(ip))
                {
                    continue;
                }

                bool failed = false;
                for (int retry = 0; retry <= 1; retry++)
                {
                    failed = false;

                    try {
                        ProxyServer proxy = new ProxyServer();
                        proxy.AddEndPoint(new ExplicitProxyEndPoint(IPAddress.Loopback, port, false));
                        proxy.UpStreamEndPoint = new IPEndPoint(IPAddress.Parse(ip), 0);
                        proxy.Start();

                        Proxies.Add(ip, proxy);
                        ProxiesConfig.Add(ip, new Dictionary <string, dynamic>());
                    } catch {
                        failed = true;
                        continue;
                    }

                    break;
                }

                if (failed)
                {
                    continue;
                }


                ProxiesConfig[ip].Add("ip", ip);
                ProxiesConfig[ip].Add("port", port);

                foreach (KeyData key in section.Keys)
                {
                    if (ProxiesConfig[ip].ContainsKey(key.KeyName.ToLower()))
                    {
                        continue;
                    }
                    ProxiesConfig[ip].Add(key.KeyName.ToLower(), key.Value);
                }
            }
        }
Exemplo n.º 12
0
 public void Init()
 {
     iniData = iniFile.ReadFile(filename);
 }
Exemplo n.º 13
0
        private static void RegisterURLHandler_Linux()
        {
            var     parser = new FileIniDataParser();
            IniData data;

            log.InfoFormat("Trying to register URL handler");

            try
            {
                data = parser.ReadFile(MimeAppsListPath);
            }
            catch (DirectoryNotFoundException ex)
            {
                log.InfoFormat("Skipping URL handler: {0}", ex.Message);
                return;
            }
            catch (FileNotFoundException ex)
            {
                log.InfoFormat("Skipping URL handler: {0}", ex.Message);
                return;
            }
            catch (ParsingException ex)
            {
                log.InfoFormat("Skipping URL handler: {0}", ex.Message);
                return;
            }

            data["Added Associations"].RemoveKey("x-scheme-handler/ckan");
            data["Added Associations"].AddKey("x-scheme-handler/ckan", HandlerFileName);

            parser.WriteFile(MimeAppsListPath, data);

            var handlerPath      = Path.Combine(ApplicationsPath, HandlerFileName);
            var handlerDirectory = Path.GetDirectoryName(handlerPath);

            if (handlerDirectory == null || !Directory.Exists(handlerDirectory))
            {
                log.ErrorFormat("Error: {0} doesn't exist", handlerDirectory);
                return;
            }

            if (File.Exists(handlerPath))
            {
                File.Delete(handlerPath);
            }

            File.WriteAllText(handlerPath, "");
            data = parser.ReadFile(handlerPath);
            data.Sections.AddSection("Desktop Entry");
            data["Desktop Entry"].AddKey("Version", "1.0");
            data["Desktop Entry"].AddKey("Type", "Application");
            data["Desktop Entry"].AddKey("Exec", System.Reflection.Assembly.GetExecutingAssembly().Location + " gui %u");
            data["Desktop Entry"].AddKey("Icon", "ckan");
            data["Desktop Entry"].AddKey("StartupNotify", "true");
            data["Desktop Entry"].AddKey("Terminal", "false");
            data["Desktop Entry"].AddKey("Categories", "Utility");
            data["Desktop Entry"].AddKey("MimeType", "x-scheme-handler/ckan");
            data["Desktop Entry"].AddKey("Name", "CKAN Launcher");
            data["Desktop Entry"].AddKey("Comment", "Launch CKAN");

            parser.WriteFile(handlerPath, data);
        }
Exemplo n.º 14
0
        private void cbZone_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                var dataParser = new IniDataParser();
                dataParser.Configuration.CommentString = "//";
                var     parser   = new FileIniDataParser(dataParser);
                IniData data     = parser.ReadFile("Zones\\" + cbZone.SelectedValue + ".ini");
                string  clientIp = data["NETWORK"]["IP"];
                if (clientIp != null)
                {
                    tbClientIp.Text = clientIp;
                }
                string clientPort = data["NETWORK"]["PORT"];
                if (clientPort != null)
                {
                    tbClientPort.Text = clientPort;
                }
                string baud = data["DIRECT"]["BAUD"];
                if (baud != null)
                {
                    int baudrate = Int32.Parse(baud);
                    for (int i = 0; i < BAUD_RATE.Length; i++)
                    {
                        if (baudrate == BAUD_RATE[i])
                        {
                            cbBaudrate.SelectedIndex = i;
                            break;
                        }
                    }
                }

                parameters.PwdOffset    = ushort.Parse(data["OFFSETS"]["PASSWORD"], System.Globalization.NumberStyles.HexNumber);
                parameters.SeedOffset   = byte.Parse(data["OFFSETS"]["SEED"], System.Globalization.NumberStyles.HexNumber);
                parameters.TimeoutMs    = int.Parse(data["TIMER_INTERVAL"]["TIMEOUT"]);
                parameters.PollMs       = int.Parse(data["TIMER_INTERVAL"]["POLL"]);
                parameters.BroadcastIds = new List <byte>();
                string broadcast = data["BROADCAST"]["ID"];
                if (broadcast == null)
                {
                    broadcast = "0";
                }
                string[] b_ids = broadcast.Split(',');
                foreach (var id in b_ids)
                {
                    byte k = byte.Parse(id);
                    if (parameters.BroadcastIds.Contains(k))
                    {
                        throw new Exception();
                    }
                    parameters.BroadcastIds.Add(k);
                }
                rbCom.IsChecked     = true;
                tbConnect.IsEnabled = true;
            }
            catch
            {
                tbConnect.IsEnabled = false;
                MessageBox.Show("Parameters in Zone ini file error");
            }
        }
Exemplo n.º 15
0
        static void Main(string[] args)
        {
            Options options = new Options();

            FileIniDataParser parser = new FileIniDataParser();

            IniData data = null;

            string fullPath = String.Format("{0}/Configuration.ini", Directory.GetCurrentDirectory());

            if (File.Exists(fullPath))
            {
                data = parser.ReadFile(fullPath);
            }

            bool confReceived = false;

            if (data != null)
            {
                PropertyInfo[] propInfos = options.GetType().GetProperties();

                foreach (KeyData keyData in data.Global)
                {
                    string key = keyData.KeyName.ToLower();

                    foreach (PropertyInfo propInfo in propInfos)
                    {
                        if (propInfo.Name.ToLower() == key)
                        {
                            if (propInfo.PropertyType == typeof(String))
                            {
                                propInfo.SetValue(options, keyData.Value);
                            }
                            else if (propInfo.PropertyType == typeof(int))
                            {
                                int value = 0;
                                if (int.TryParse(keyData.Value, out value))
                                {
                                    propInfo.SetValue(options, value);
                                }
                            }
                            else if (propInfo.PropertyType == typeof(bool))
                            {
                                bool value = false;
                                if (bool.TryParse(keyData.Value, out value))
                                {
                                    propInfo.SetValue(options, value);
                                }
                            }
                        }
                    }
                }
                confReceived = !String.IsNullOrEmpty(options.VoiceName) && options.BitRate > 0 && options.SampleRate > 0 && CommandLine.Parser.Default.ParseArguments(args, options);
            }
            else
            {
                confReceived = CommandLine.Parser.Default.ParseArguments(args, options);
            }

            confReceived = confReceived && ((!String.IsNullOrEmpty(options.Path) && (!String.IsNullOrEmpty(options.InputFile) || !String.IsNullOrEmpty(options.Text))) || options.VoicesList);

            bool result = true;

            if (confReceived)
            {
                if (options.VoicesList)
                {
                    DisplayVoicesList();
                }
                else
                {
                    result = GenerateFile(options);
                }
                if (!result)
                {
                    Console.WriteLine("An error has occurred");
                    Environment.Exit(1);
                }
            }
            else
            {
                Console.WriteLine("Options error");
                Environment.Exit(1);
            }
        }
Exemplo n.º 16
0
        private void InitAppConfig(string configFile)
        {
            var parser = new FileIniDataParser();

            Data = parser.ReadFile(Environment.CurrentDirectory + "/" + configFile);
        }
        static void Main()
        {
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
            clients  = new List <Ts3FullClient>();
            channels = File.ReadAllLines(chanfile);
            var parser = new FileIniDataParser();

            cfg = parser.ReadFile(cfgfile);
            RandomNick rndnick = new RandomNick();

            rndnick.Init();
            TSSettings.OpenDB();
            Console.CancelKeyPress += (s, e) => {
                if (e.SpecialKey == ConsoleSpecialKey.ControlC)
                {
                    e.Cancel = true;
                    Dispose();
                    Environment.Exit(0);
                }
            };
            con.Address  = cfg["general"]["Address"];
            con.Password = cfg["general"]["ServerPassword"];
            ownerUID     = cfg["general"]["OwnerUID"];

            /*
             * adminCGID = uint.Parse(cfg["general"]["adminCGID"]);
             * modCGID = uint.Parse(cfg["general"]["modCGID"]);
             * banCGID = uint.Parse(cfg["general"]["banCGID"]);
             */
            if (!File.Exists(idfile))
            {
                using (File.Create(idfile)) { }
            }
            ids = File.ReadAllLines(idfile);
            for (int i = 0; i < channels.Length; i++)
            {
                if (isExit)
                {
                    return;
                }
                con.Username = rndnick.GetRandomNick();                 //cfg["general"]["Nickname"];
                var client = new Ts3FullClient(EventDispatchType.DoubleThread);
                client.OnConnected           += OnConnected;
                client.OnDisconnected        += OnDisconnected;
                client.OnErrorEvent          += OnErrorEvent;
                client.OnTextMessageReceived += OnTextMessageReceived;
                client.OnClientMoved         += OnClientMoved;
                client.OnClientEnterView     += OnClientEnterView;
                var          _identity = ids.Select(x => x.Split(',')).ToList();
                IdentityData ID;
                try {
                    ID = Ts3Crypt.LoadIdentity(_identity[i][0], ulong.Parse(_identity[i][1]));
                    if (i > 0)
                    {
                        Thread.Sleep(int.Parse(cfg["general"]["ConnectSleepMS"]));
                    }
                } catch (Exception) {
                    ID = Ts3Crypt.GenerateNewIdentity(int.Parse(cfg["general"]["MinLVL"]));
                    File.AppendAllText(idfile, ID.PrivateKeyString + "," + ID.ValidKeyOffset + "\r\n");
                }
                Console.WriteLine("#" + i + " UID: " + ID.ClientUid);
                con.Identity = ID;
                //Array values = Enum.GetValues(typeof(VersionSign));
                //Random random = new Random();
                //con.VersionSign = (VersionSign)values.GetValue(random.Next(values.Length));
                //var t = typeof(VersionSign).GetFields();
                con.VersionSign = VersionSign.VER_WIN_3_UNKNOWN;
                //con.VersionSign = new VersionSign("YaTQA-3.9pre [Build: 32503680000]", "ServerQuery", String.Empty);
                con.HWID = $"{Clientlib.RandomString(32)},{Clientlib.RandomString(32)}";
                Console.WriteLine("#" + i + " HWID: " + con.HWID);
                client.Connect(con);
                clients.Add(client);
            }
            AntiAFK = new Timer(OnTick, "on", 114 * 10000, 114 * 10000);
            Console.WriteLine("End");
            Console.ReadLine();
            Dispose();
        }
Exemplo n.º 18
0
        public List <uint> reimport(string file)
        {
            var     parser = new FileIniDataParser();
            IniData data   = parser.ReadFile(file);

            List <uint> segments     = new List <uint>();
            List <uint> moveSegments = new List <uint>();
            List <MusicPlaylistObject_Transition>      transitions       = new List <MusicPlaylistObject_Transition>();
            List <MusicPlaylistObject_PlaylistElement> playlist_elements = new List <MusicPlaylistObject_PlaylistElement>();

            foreach (var s in data.Sections)
            {
                if (s.SectionName == "SEGMENTS")
                {
                    foreach (KeyData k in s.Keys)
                    {
                        uint s_id = 0;
                        if (uint.TryParse(k.Value, out s_id))
                        {
                            segments.Add(s_id);
                        }
                    }
                }
                else if (s.SectionName == "MOVE SEGMENTS")
                {
                    // store move segment
                    foreach (KeyData k in s.Keys)
                    {
                        uint m_id = 0;
                        if (uint.TryParse(k.Value, out m_id))
                        {
                            moveSegments.Add(m_id);
                        }
                    }
                }
                else if (s.SectionName.StartsWith("TRANSITION"))
                {
                    MusicPlaylistObject_Transition t = new MusicPlaylistObject_Transition();
                    uint.TryParse(s.Keys["source_id"], out t._source_id);
                    uint.TryParse(s.Keys["dest_id"], out t._dest_id);
                    int.TryParse(s.Keys["source_fadeout"], out t._source_fadeout);
                    uint.TryParse(s.Keys["source_shape_curve_fadeout"], out t._source_shape_curve_fadeout);
                    int.TryParse(s.Keys["source_fadeout_offset"], out t._source_fadeout_offset);
                    uint.TryParse(s.Keys["unk_field32_1"], out t._unk_field32_1);
                    uint.TryParse(s.Keys["unk_field32_2"], out t._unk_field32_2);
                    uint.TryParse(s.Keys["unk_field32_3"], out t._unk_field32_3);
                    byte.TryParse(s.Keys["src_type"], out t._src_type);
                    int.TryParse(s.Keys["dest_fadein"], out t._dest_fadein);
                    uint.TryParse(s.Keys["dest_shape_curve_fadein"], out t._dest_shape_curve_fadein);
                    int.TryParse(s.Keys["dest_fadein_offset"], out t._dest_fadein_offset);
                    uint.TryParse(s.Keys["unk_field32_4"], out t._unk_field32_4);
                    uint.TryParse(s.Keys["unk_field32_5"], out t._unk_field32_5);
                    ushort.TryParse(s.Keys["unk_field16_1"], out t._unk_field16_1);
                    byte.TryParse(s.Keys["dest_type"], out t._dest_type);
                    byte.TryParse(s.Keys["unk_field8_1"], out t._unk_field8_1);
                    bool.TryParse(s.Keys["has_segment"], out t._has_segment);
                    uint.TryParse(s.Keys["trans_segment_id"], out t._trans_segment_id);
                    int.TryParse(s.Keys["trans_fadein"], out t._trans_fadein);
                    uint.TryParse(s.Keys["trans_shape_curve_fadein"], out t._trans_shape_curve_fadein);
                    int.TryParse(s.Keys["trans_fadein_offset"], out t._trans_fadein_offset);
                    int.TryParse(s.Keys["trans_fadeout"], out t._trans_fadeout);
                    uint.TryParse(s.Keys["trans_shape_curve_fadeout"], out t._trans_shape_curve_fadeout);
                    int.TryParse(s.Keys["trans_fadeout_offset"], out t._trans_fadeout_offset);
                    byte.TryParse(s.Keys["trans_fadein_type"], out t._trans_fadein_type);
                    byte.TryParse(s.Keys["trans_fadeout_type"], out t._trans_fadeout_type);

                    transitions.Add(t);
                }
                else if (s.SectionName.StartsWith("PLAYLIST ELEMENT"))
                {
                    MusicPlaylistObject_PlaylistElement p = new MusicPlaylistObject_PlaylistElement();
                    if (s.Keys["id"] == "<NEW ID>")
                    {
                        p._id = getNewElementId();
                    }
                    else
                    {
                        uint.TryParse(s.Keys["id"], out p._id);
                    }
                    uint.TryParse(s.Keys["child_elements"], out p._child_elements);
                    int.TryParse(s.Keys["playlist_type"], out p._playlist_type);
                    ushort.TryParse(s.Keys["loop_count"], out p._loop_count);
                    uint.TryParse(s.Keys["weight"], out p._weight);
                    ushort.TryParse(s.Keys["times_in_row"], out p._times_in_row);
                    byte.TryParse(s.Keys["unk_field8_1"], out p._unk_field8_1);
                    byte.TryParse(s.Keys["random_type"], out p._random_type);
                    playlist_elements.Add(p);
                }

                if (segments.Count > 0)
                {
                    _segment_ids = segments;
                    _segments    = (uint)segments.Count;
                }

                if (transitions.Count > 0)
                {
                    _transitions      = transitions;
                    _transition_count = (uint)transitions.Count;
                }

                if (playlist_elements.Count > 0)
                {
                    _playlist_elements       = playlist_elements;
                    _playlist_elements_count = (uint)playlist_elements.Count;
                }
            }


            if (segments.Count > 0)
            {
                _segment_ids = segments;
                _segments    = (uint)segments.Count;
            }
            if (transitions.Count > 0)
            {
                _transitions      = transitions;
                _transition_count = (uint)transitions.Count;
            }
            if (playlist_elements.Count > 0)
            {
                _playlist_elements       = playlist_elements;
                _playlist_elements_count = (uint)playlist_elements.Count;
            }
            return(moveSegments);
        }
Exemplo n.º 19
0
 public void InitializeData()
 {
     Parser = new FileIniDataParser();
     Data   = Parser.ReadFile(ConfigPath);
 }
Exemplo n.º 20
0
        private List <BackupAction> ReadConfigurationFromFile(Options options)
        {
            IniData data;

            try
            {
                var parser = new FileIniDataParser();
                data = parser.ReadFile(options.Configuration);
            }
            catch (Exception e)
            {
                Console.Error.Write(e);
                throw new ArgumentException("Configuration file does not exist or invalid format! /n Check the example ");
            }
            var     flags      = data["Flags"];
            var     files      = data["Files"];
            string  actionName = flags["profile"];
            IBackup mode;

            switch (flags["mode"])
            {
            case "database": mode = new DatabaseBackup(); break;

            case "simple": mode = new FileBackup(); break;

            default: throw new ArgumentException("Invalid value in 'mode' setting!");
            }
            IComparator comparator;

            switch (flags["compare"])
            {
            case "bydate": comparator = new HashComparator(); break;

            case "byhash": comparator = new DateComparator(); break;

            default: throw new ArgumentException("Invalid value in 'compare' setting!");
            }

            int    copies   = Convert.ToInt32(flags["history"]);
            bool   archive  = (flags["archive"] == "yes" || flags["archive"] == "true") ? true : false;
            string password = flags["password"];

            string[] sources     = files["sources"].Replace("\"", "").Split(",");
            string[] destination = files["destinations"].Replace("\"", "").Split(",");


            List <BackupAction> backupActionList = new List <BackupAction>();

            if (destination.Length == 1)
            {
                for (int i = 0; i < sources.Length; i++)
                {
                    backupActionList.Add(new BackupAction(actionName, sources[i], destination[0] + "/" + Path.GetFileName(sources[i]) + "/", mode, comparator, copies, archive, password));
                }
            }
            else if (sources.Length == destination.Length)
            {
                for (int i = 0; i < sources.Length; i++)
                {
                    backupActionList.Add(new BackupAction(actionName, sources[i], destination[i], mode, comparator, copies, archive, password));
                }
            }
            else
            {
                throw new ArgumentException("The number of destinations must be equal to 1 or the number of sources!");
            }
            return(backupActionList);
        }
Exemplo n.º 21
0
        private void Main2_Load(object sender, EventArgs e)
        {
            string version = System.Windows.Forms.Application.ProductVersion;

            this.Text = String.Format("Excel add image by command line (version {0})", version);

            outputExcelFileName.Text = "";
            openExcel.Visible        = false;

            if (!(args.Length == 8))
            {
                string msg = @"
EXAMPLE:
    ExcelAddImage.exe ""D:\te\source_excel"" ""D:\te\output_excel"" Y B C Y 1 80

    parameter 1 : Source excel file (excluded .xlsx)
    parameter 2 : Destination excel file (excluded .xlsx)
    parameter 3 : Y or N, Show the SaveAs Dialog Box
    parameter 4 : Image path column from source excel file
    parameter 5 : Add image column from source excel file
    parameter 6 : Y or N, Insert a blank column to add image
    parameter 7 : 1 or 2 (PCX or JPG), Get image priority
    parameter 8 : Image range of height from 30 to 100
";
                Fun.showMessageBox(msg, "Error : Incorrect number of parameter");
                Application.Exit();
            }

            // 檢查圖片高度參數範圍,超過範圍跳出訊息並關閉程式
            if (Int32.Parse(args[7]) != Fun.imageHeightRange(Int32.Parse(args[7])))
            {
                Fun.showMessageBox(
                    String.Format("Check image range of height from 30 to 100"), "Error");
                Application.Exit();
            }

            sourceFile = new FileInfo2(string.Format("{0}.xlsx", args[0]));
            saveAsFile = new FileInfo2(string.Format("{0}.xlsx", args[1]));

            if (!sourceFile.isFileExists())
            {
                Fun.showMessageBox(
                    String.Format("\"{0}\" source excel does not exist.",
                                  sourceFile.getFullName()), "SaveAs error");
                Application.Exit();
            }

            // 程式執行路徑
            string executingDirectory = Fun.getExecutingDirectory();

            // 讀取ini
            var     parser = new FileIniDataParser();
            IniData data   = parser.ReadFile(String.Format(@"{0}\{1}", executingDirectory, "Config.ini"));

            imageDirectory = data["ExcelAddImage"]["ImageDirectory"];
            imagePriority  = data["ExcelAddImage"]["ImagePriority"];

            // 檢查圖片路徑存在否
            if (!Directory.Exists(imageDirectory))
            {
                Fun.showMessageBox(String.Format("\"{0}\" does not exist.", imageDirectory), "Error");
            }

            // 顯示SaveAs Dialog Box
            if (args[2].ToUpper().Equals("Y"))
            {
                showSaveAsDialogBox = true;
            }
            else
            {
                showSaveAsDialogBox = false;
            }

            // Excel新增圖片的column是否要insert一欄
            if (args[5].ToUpper().Equals("Y"))
            {
                excelColumnInsert = true;
            }
            else
            {
                excelColumnInsert = false;
            }

            // BwGenExcel參數Object
            bwGenExcelArgs = new BwGenExcelArgs
            {
                sourceFile = sourceFile.getFullName(),
                outputFile = saveAsFile.getFullName(),
                excelImagePathColumnIdx = Fun.GetNumberFromExcelColumn(args[3]),
                imageHeight             = Int32.Parse(args[7]),
                imagePriorityList       = Fun.getExtPriorityList(Int32.Parse(args[6])),
                imageDirectory          = imageDirectory,
                excelAddImageColumnIdx  = Fun.GetNumberFromExcelColumn(args[4]),
                excelColumnInsert       = excelColumnInsert
            };

            // 線程產生Excel
            BwGenExcel bw_DoWork = new BwGenExcel(bwGenExcelArgs);

            bw = new BackgroundWorker();
            bw.WorkerReportsProgress      = true;
            bw.WorkerSupportsCancellation = true;
            bw.DoWork             += new DoWorkEventHandler(bw_DoWork.DoWork);
            bw.ProgressChanged    += new ProgressChangedEventHandler(bw_ProgressChanged);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            bw.RunWorkerAsync();
        }
Exemplo n.º 22
0
        private static void RegisterURLHandler_Linux()
        {
            var parser = new FileIniDataParser();

            // Yes, 'Assigment' is the spelling used by the library.
            parser.Parser.Configuration.AssigmentSpacer = "";
            IniData data;

            log.InfoFormat("Trying to register URL handler");

            if (!File.Exists(MimeAppsListPath))
            {
                log.InfoFormat("{0} does not exist, trying to create it", MimeAppsListPath);
                File.WriteAllLines(MimeAppsListPath, new string[] { "[Default Applications]" });
            }

            try
            {
                data = parser.ReadFile(MimeAppsListPath);
            }
            catch (DirectoryNotFoundException ex)
            {
                log.InfoFormat("Skipping URL handler: {0}", ex.Message);
                return;
            }
            catch (FileNotFoundException ex)
            {
                log.InfoFormat("Skipping URL handler: {0}", ex.Message);
                return;
            }
            catch (ParsingException ex)
            {
                log.InfoFormat("Skipping URL handler: {0}", ex.Message);
                return;
            }

            if (data["Added Associations"] == null)
            {
                data.Sections.AddSection("Added Associations");
            }
            data["Added Associations"].RemoveKey("x-scheme-handler/ckan");
            data["Added Associations"].AddKey("x-scheme-handler/ckan", HandlerFileName);

            parser.WriteFile(MimeAppsListPath, data);

            var handlerPath      = Path.Combine(ApplicationsPath, HandlerFileName);
            var handlerDirectory = Path.GetDirectoryName(handlerPath);

            if (handlerDirectory == null || !Directory.Exists(handlerDirectory))
            {
                log.ErrorFormat("Error: {0} doesn't exist", handlerDirectory);
                return;
            }

            if (File.Exists(handlerPath))
            {
                File.Delete(handlerPath);
            }

            File.WriteAllText(handlerPath, "");
            data = parser.ReadFile(handlerPath);
            data.Sections.AddSection("Desktop Entry");
            data["Desktop Entry"].AddKey("Version", "1.0");
            data["Desktop Entry"].AddKey("Type", "Application");
            data["Desktop Entry"].AddKey("Exec", "mono \"" + System.Reflection.Assembly.GetExecutingAssembly().Location + "\" gui %u");
            data["Desktop Entry"].AddKey("Icon", "ckan");
            data["Desktop Entry"].AddKey("StartupNotify", "true");
            data["Desktop Entry"].AddKey("NoDisplay", "true");
            data["Desktop Entry"].AddKey("Terminal", "false");
            data["Desktop Entry"].AddKey("Categories", "Utility");
            data["Desktop Entry"].AddKey("MimeType", "x-scheme-handler/ckan");
            data["Desktop Entry"].AddKey("Name", "CKAN Launcher");
            data["Desktop Entry"].AddKey("Comment", "Launch CKAN");

            parser.WriteFile(handlerPath, data);
            AutoUpdate.SetExecutable(handlerPath);
        }
Exemplo n.º 23
0
 static Config()
 {
     // Setup the ini config
     var parser = new FileIniDataParser();
     ConfigFile = parser.ReadFile("cfg.ini");
 }       
Exemplo n.º 24
0
        private void ValidSettingsCheck()
        {
            if (bedrockServers.Count() < 1)
            {
                throw new Exception("No Servers Configured");
            }
            else
            {
                var exeLocations = bedrockServers.GroupBy(t => t.ServerConfig.BedrockServerExeLocation);
                if (exeLocations.Count() != bedrockServers.Count())
                {
                    throw new Exception("Duplicate Server Paths defined");
                }
                foreach (var server in bedrockServers)
                {
                    if (!File.Exists(server.ServerConfig.BedrockServerExeLocation))
                    {
                        throw new FileNotFoundException("The bedrock server file is not accessible or does not exist", server.ServerConfig.BedrockServerExeLocation);
                    }
                    else
                    {
                        FileInfo inf        = new FileInfo(server.ServerConfig.BedrockServerExeLocation);
                        FileInfo configfile = inf.Directory.GetFiles(serverProperties).ToList().Single();

                        IniDataParser parser = new IniDataParser();
                        parser.Configuration.AllowKeysWithoutSection = true;
                        parser.Configuration.CommentString           = "#";

                        FileIniDataParser fp = new FileIniDataParser(parser);

                        IniData data = fp.ReadFile(configfile.FullName);

                        server.ServerConfig.ServerName  = data.GetKey(serverName);
                        server.ServerConfig.ServerPort4 = data.GetKey(ipv4port);
                        server.ServerConfig.ServerPort6 = data.GetKey(ipv6port);
                    }
                }

                var duplicateV4 = bedrockServers.GroupBy(x => x.ServerConfig.ServerPort4)
                                  .Where(g => g.Count() > 1)
                                  .Select(y => new ServerConfig()
                {
                    ServerPort4 = y.Key
                })
                                  .ToList();
                var duplicateV4Servers = bedrockServers.Where(t => duplicateV4.Select(r => r.ServerPort4).Contains(t.ServerConfig.ServerPort4)).ToList();
                if (duplicateV4Servers.Count() > 0)
                {
                    throw new Exception("Duplicate server IPv4 ports detected for: " + string.Join(", ", duplicateV4Servers.Select(t => t.ServerConfig.BedrockServerExeLocation)));
                }
                var duplicateV6 = bedrockServers.GroupBy(x => x.ServerConfig.ServerPort6)
                                  .Where(g => g.Count() > 1)
                                  .Select(y => new ServerConfig()
                {
                    ServerPort6 = y.Key
                })
                                  .ToList();
                var duplicateV6Servers = bedrockServers.Where(t => duplicateV6.Select(r => r.ServerPort6).Contains(t.ServerConfig.ServerPort6)).ToList();
                if (duplicateV6Servers.Count() > 0)
                {
                    throw new Exception("Duplicate server IPv6 ports detected for: " + string.Join(", ", duplicateV6Servers.Select(t => t.ServerConfig.BedrockServerExeLocation)));
                }
                var duplicateName = bedrockServers.GroupBy(x => x.ServerConfig.ServerName)
                                    .Where(g => g.Count() > 1)
                                    .Select(y => new ServerConfig()
                {
                    ServerName = y.Key
                })
                                    .ToList();
                var duplicateNameServers = bedrockServers.Where(t => duplicateName.Select(r => r.ServerName).Contains(t.ServerConfig.ServerName)).ToList();
                if (duplicateNameServers.Count() > 0)
                {
                    throw new Exception("Duplicate server names detected for: " + string.Join(", ", duplicateV6Servers.Select(t => t.ServerConfig.BedrockServerExeLocation)));
                }
                if (bedrockServers.Count > 1)
                {
                    if (!bedrockServers.Exists(t => t.ServerConfig.ServerPort4 == primaryipv4port && t.ServerConfig.ServerPort6 == primaryipv6port))
                    {
                        throw new Exception("No server defined with default ports " + primaryipv4port + " and " + primaryipv6port);
                    }
                    bedrockServers.Single(t => t.ServerConfig.ServerPort4 == primaryipv4port && t.ServerConfig.ServerPort6 == primaryipv6port).ServerConfig.Primary = true;
                }
                else
                {
                    bedrockServers.ForEach(t => t.ServerConfig.Primary = true);
                }
            }
        }
Exemplo n.º 25
0
        static void Main(string[] args)
        {
            //lists to store Country code, PI code & Programme Service name from Lookup table.
            List <string> Master_List = new List <string> ();
            List <string> list_CC     = new List <string> ();
            List <string> list_ECC    = new List <string> ();
            List <string> list_PI     = new List <string> ();
            List <string> list_PSN    = new List <string> ();

            //filtered PI & PSN containing only information related to country selected by the user.
            List <string> firstFewPI  = new List <string> ();
            List <string> firstFewPSN = new List <string> ();
            List <string> firstFewECC = new List <string> ();

            /*
             * foreach (var a in args) {
             *  Console.WriteLine ("Arguments to print are: ", a + System.Environment.NewLine);
             * }*/

            double start_freq      = Convert.ToDouble(args[0]);
            int    stations2create = Int32.Parse(args[1]);
            string region          = args[2];

            if ((start_freq > 108.0) || (start_freq < 88.0))
            {
                // The user wants to exit the application. Close everything down.
                Console.WriteLine("Invalid start frequency ! only 88-108MHz is accepted ! Exiting...");
                Environment.Exit(-1);
            }

            //lists to hold 34 frequencies from 88-107.8 MHz.
            List <string> list_random_FMfreq = new List <string> ();
            int           i_count            = 0;

            //for loop runs until the end of frequency is reached and then is reset back to start.
            //use mod operator "%" if needed to create a station of more than 34 list size.
            for (double i_loop = start_freq; i_loop <= Constants.end_freq; i_loop += Constants.freq_increment)
            {
                //convert double var to single decimal point var and copy to string of lists.
                i_loop = Math.Round(i_loop, 1);
                string str = i_loop.ToString(CultureInfo.GetCultureInfo("en-GB"));
                list_random_FMfreq.Add(str);
                i_count++;
            }

            if (i_count < stations2create)
            {
                for (double i_loop = start_freq; i_count <= stations2create; i_loop += Constants.freq_increment)
                {
                    //convert double var to single decimal point var and copy to string of lists.
                    if (i_loop >= Constants.end_freq)
                    {
                        i_loop = start_freq;
                    }
                    i_loop = Math.Round(i_loop, 1);
                    string str = i_loop.ToString(CultureInfo.GetCultureInfo("en-GB"));
                    list_random_FMfreq.Add(str);
                    i_count++;
                }
            }

            using (var reader = new StreamReader(@"LUT.csv")) {
                //read 1 time outside the while loop to skip reading the heading row !
                reader.ReadLine();
                while (!reader.EndOfStream)
                {
                    var line = reader.ReadLine();
                    Master_List.Add(line);
                }
            }
            IListExtensions.Shuffle(Master_List);
            foreach (var item in Master_List)
            {
                var values = item.Split(',');

                list_CC.Add(values[0]);
                list_ECC.Add(values[1]);
                list_PI.Add(values[2]);
                list_PSN.Add(values[3]);
            }

            /*
             *  //disabled routine to extract the distinct countries used in LUT table and construct windows form.
             *  // Get distinct Country Code and convert into a list again.
             *  List<string> list_Distinct_CC = new List<string>();
             *
             *  //lists to be available as input to the user in drop-down box.
             *  list_Distinct_CC = list_CC.Distinct().ToList();
             *
             *  foreach(var item in list_Distinct_CC)
             *  {
             *      string pre = "\"";
             *      string post = "\",";
             *      string merge = string.Concat(pre,item,post);
             *
             *      Console.WriteLine(item);
             *  } */
            var search_CC_List = list_CC
                                 .Select((v, i) => new { Index = i, Value = v })
                                 .Where(x => x.Value == region)
                                 .Select(x => x.Index)
                                 .ToList();

            //skip few random stations within first 50 items and take as many stations as requested by the user.
            Random rnd = new Random();

            if ((search_CC_List.Count > 50) && (search_CC_List.Count > stations2create))
            {
                if (region == "DE")
                {
                    foreach (var item in search_CC_List)
                    {
                        int temp    = Convert.ToInt32(list_PI[item], 16);
                        int DE_code = 0xD000;
                        int count   = 0;
                        if ((temp & DE_code) == DE_code)
                        {
                            if (count <= stations2create)
                            {
                                firstFewECC.Add(list_ECC[item]);
                                firstFewPI.Add(list_PI[item]);
                                firstFewPSN.Add(list_PSN[item]);
                                count++;
                            }
                        }
                    }
                }
                else
                {
                    foreach (var item in search_CC_List.Skip(rnd.Next(1, 50)).Take(stations2create))
                    {
                        firstFewECC.Add(list_ECC[item]);
                        firstFewPI.Add(list_PI[item]);
                        firstFewPSN.Add(list_PSN[item]);
                    }
                }
            }
            else
            {
                if (search_CC_List.Count < stations2create)
                {
                    stations2create = search_CC_List.Count;
                }
                foreach (var item in search_CC_List.Take(stations2create))
                {
                    firstFewECC.Add(list_ECC[item]);
                    firstFewPI.Add(list_PI[item]);
                    firstFewPSN.Add(list_PSN[item]);
                }
            }

            string builder_channel = File.ReadAllText(@"builder_channel.txt", Encoding.UTF8);
            string builder_rds     = File.ReadAllText(@"builder_rds.txt", Encoding.UTF8);
            string audio_file      = File.ReadAllText(@"audio_playlist.txt", Encoding.UTF8);

            var    parser   = new FileIniDataParser();
            string fileName = string.Concat("parser_", DateTime.Now.ToString("HHmmss") + ".ini");

            using (File.Create(fileName)) { }

            IniData data = parser.ReadFile(fileName);

            foreach (var i in Enumerable.Range(1, stations2create))
            {
                string channel = String.Concat("channel.", i);
                data.Sections.AddSection(channel);

                string rds = String.Concat("rds.", i);
                data.Sections.AddSection(rds);
            }

            //routine to append channel & rds parameter text to parser ini file
            using (File.Create(@"merge_content.ini")) { }
            using (var write = File.CreateText(@"merge_content.ini")) {
                write.WriteLine(audio_file);
                foreach (var i in Enumerable.Range(1, stations2create))
                {
                    string channel = String.Concat("[channel.", i, "]");
                    string rds     = String.Concat("[rds.", i, "]");

                    write.WriteLine(channel);
                    write.WriteLine(builder_channel);

                    write.WriteLine(rds);
                    write.WriteLine(builder_rds);
                }
            }

            foreach (var i in Enumerable.Range(1, stations2create))
            {
                string channel = String.Concat("channel.", i);
                string rds     = String.Concat("rds.", i);

                data[channel]["freq"]  = list_random_FMfreq[i - 1];
                data[channel]["idrds"] = i.ToString();

                data[rds]["name"] = String.Concat("RDS_", i);
                long   Dec       = Int32.Parse(firstFewECC[i - 1], System.Globalization.NumberStyles.HexNumber);
                string DecString = String.Format("{0:0}", Dec);
                data[rds]["slow"] = DecString;
                data[rds]["ps"]   = firstFewPSN[i - 1];
                data[rds]["pi"]   = firstFewPI[i - 1];
            }

            var merge_parser = new IniParser.Parser.IniDataParser();

            IniData user_config = merge_parser.Parse(File.ReadAllText("merge_content.ini"));

            data.Merge(user_config);

            //Save the file
            parser.WriteFile(fileName, data);
            File.Copy(fileName, Path.ChangeExtension(fileName, ".fm"));
        }
Exemplo n.º 26
0
        /// <summary>
        /// Load settings from IniData.
        /// This will be read from the ini file on disk the first time.
        /// </summary>
        private void LoadSettings()
        {
            // Read file
            if (data == null)
            {
                data = parser.ReadFile(path);
                ModSettingsReader.UpdateSettings(ref data, defaultSettings, Mod);
                config = ModSettingsReader.GetConfig(Mod);
            }

            // Read settings
            foreach (SectionData section in data.Sections.Where(x => x.SectionName != ModSettingsReader.internalSection))
            {
                // Section label
                TextLabel textLabel = new TextLabel();
                textLabel.Text                = section.SectionName;
                textLabel.TextColor           = sectionTitleColor;
                textLabel.Position            = new Vector2(x, y);
                textLabel.HorizontalAlignment = HorizontalAlignment.None;
                currentPanel.Components.Add(textLabel);
                MovePosition(spacing + 4);
                List <string> comments = section.Comments;
                int           comment  = 0;

                foreach (KeyData key in section.Keys)
                {
                    // Setting label
                    TextLabel settingName = new TextLabel();
                    settingName.Text                = key.KeyName;
                    settingName.Position            = new Vector2(x, y);
                    settingName.HorizontalAlignment = HorizontalAlignment.None;
                    if (comment < comments.Count)
                    {
                        settingName.ToolTip     = defaultToolTip;
                        settingName.ToolTipText = comments[comment];
                        comment++;
                    }
                    currentPanel.Components.Add(settingName);

                    // Setting field
                    ModSettingsKey configKey;
                    if (config && config.Key(section.SectionName, key.KeyName, out configKey))
                    {
                        settingName.ToolTipText = configKey.description;

                        // Use config file
                        switch (configKey.type)
                        {
                        case ModSettingsKey.KeyType.Toggle:
                            AddCheckBox(key.Value == "True");
                            break;

                        case ModSettingsKey.KeyType.Slider:
                            var slider = configKey.slider;
                            int startValue;
                            if (!int.TryParse(key.Value, out startValue))
                            {
                                startValue = 0;
                            }
                            AddSlider(slider.min, slider.max, startValue, key.KeyName);
                            break;

                        case ModSettingsKey.KeyType.FloatSlider:
                            var   floatSlider = configKey.floatSlider;
                            float floatStartValue;
                            if (!float.TryParse(key.Value, out floatStartValue))
                            {
                                floatStartValue = 0;
                            }
                            AddSlider(floatSlider.min, floatSlider.max, floatStartValue, key.KeyName);
                            break;

                        case ModSettingsKey.KeyType.Tuple:
                        case ModSettingsKey.KeyType.FloatTuple:
                            int index  = key.Value.IndexOf(ModSettingsReader.tupleDelimiterChar);
                            var first  = GetTextbox(95, 19.6f, key.Value.Substring(0, index));
                            var second = GetTextbox(116, 19.6f, key.Value.Substring(index + ModSettingsReader.tupleDelimiterChar.Length));
                            modTuples.Add(new Tuple <TextBox, TextBox>(first, second));
                            break;

                        case ModSettingsKey.KeyType.Text:
                        case ModSettingsKey.KeyType.MultipleChoice:     //TODO
                            TextBox textBox = GetTextbox(95, 40, key.Value);
                            modTextBoxes.Add(textBox);
                            break;

                        case ModSettingsKey.KeyType.Color:
                            TextBox colorBox = GetTextbox(95, 40, key.Value);
                            modTextBoxes.Add(colorBox);
                            int hexColor;
                            if (colorBox.DefaultText.Length != 8 || !int.TryParse(colorBox.DefaultText, System.Globalization.NumberStyles.HexNumber,
                                                                                  System.Globalization.CultureInfo.InvariantCulture, out hexColor))
                            {
                                colorBox.DefaultText = "FFFFFFFF";
                            }
                            // Use box background as a preview of the color
                            Color32 color = ModSettingsReader.ColorFromString(colorBox.DefaultText);
                            colorBox.BackgroundColor = color;
                            colorBox.ToolTip         = defaultToolTip;
                            colorBox.ToolTipText     = color.ToString();
                            break;
                        }
                    }
                    else
                    {
                        // Legacy support
                        if (key.Value == "True")
                        {
                            AddCheckBox(true);
                        }
                        else if (key.Value == "False")
                        {
                            AddCheckBox(false);
                        }
                        else if (key.Value.Contains(ModSettingsReader.tupleDelimiterChar)) // Tuple
                        {
                            int index  = key.Value.IndexOf(ModSettingsReader.tupleDelimiterChar);
                            var first  = GetTextbox(95, 19.6f, key.Value.Substring(0, index));
                            var second = GetTextbox(116, 19.6f, key.Value.Substring(index + ModSettingsReader.tupleDelimiterChar.Length));
                            modTuples.Add(new Tuple <TextBox, TextBox>(first, second));
                        }
                        else
                        {
                            TextBox textBox = GetTextbox(95, 40, key.Value);
                            modTextBoxes.Add(textBox);

                            // Color
                            if (textBox.DefaultText.Length == 8)
                            {
                                // Check if is a hex number or just a string with lenght eight
                                int hexColor;
                                if (int.TryParse(textBox.DefaultText, System.Globalization.NumberStyles.HexNumber,
                                                 System.Globalization.CultureInfo.InvariantCulture, out hexColor))
                                {
                                    // Use box background as a preview of the color
                                    Color32 color = ModSettingsReader.ColorFromString(textBox.DefaultText);
                                    textBox.BackgroundColor = color;
                                    textBox.ToolTip         = defaultToolTip;
                                    textBox.ToolTipText     = color.ToString();
                                }
                            }
                        }
                    }

                    MovePosition(spacing);
                }
            }
        }
        /// <summary>
        /// Loads the given config file, and adds all of the entries within to this <see cref="UMFGadgetConfigMenu"/>
        /// </summary>
        protected virtual void LoadConfigFile(string configFilePath, string section, params string[] readonlyEntries)
        {
            if (!File.Exists(configFilePath))
            {
                AddComponent(new GadgetConfigLabelComponent(this, "No Config File", "This mod had no config file when this menu was generated."));
                AddComponent(new GadgetConfigLabelComponent(this, "No Config File", "Perhaps it was just installed?"));
                AddComponent(new GadgetConfigLabelComponent(this, "No Config File", "Click the button to reload this config menu."));
                AddComponent(new GadgetConfigSpacerComponent(this, "Spacer"));
                AddComponent(new GadgetConfigButtonComponent(this, null, "Refresh Config File", () =>
                {
                    Reset();
                }, 0.25f));
                return;
            }
            ConfigFilePath    = configFilePath;
            ConfigFileSection = section;
            ReadonlyEntries   = readonlyEntries;
            IniParser         = new FileIniDataParser();
            Ini = IniParser.ReadFile(configFilePath);
            Ini.Configuration.SkipInvalidLines = true;
            Ini.Configuration.AssigmentSpacer  = "";
            if (section == null || !Ini.Sections.ContainsSection(section))
            {
                section = Path.GetFileNameWithoutExtension(configFilePath);
                if (!Ini.Sections.ContainsSection(section))
                {
                    throw new InvalidOperationException(NO_CONFIGURABLE_DATA);
                }
            }
            AddComponent(new GadgetConfigLabelComponent(this, "ConfigVersion", "Config Version (not to be confused with mod version): " + Ini["uModFramework"]["ConfigVersion"]), GadgetConfigComponentAlignment.HEADER);
            bool firstStandard = true, firstHeader = false, firstFooter = true;

            foreach (KeyData keyData in Ini[section])
            {
                if (keyData == null)
                {
                    continue;
                }
                GadgetConfigComponentAlignment alignment = default;
                bool seperatorMade = false, commentsMade = false;
                try
                {
                    string dataTypeString  = keyData.Comments.SingleOrDefault((x) => x.StartsWith("[Type:"));
                    string dataRangeString = null;
                    if (!string.IsNullOrEmpty(dataTypeString))
                    {
                        string[] dataTypeStrings = dataTypeString.Split('|');
                        dataTypeString = dataTypeStrings[0];
                        if (dataTypeStrings.Length > 1)
                        {
                            dataRangeString = dataTypeStrings[1].Substring(8, dataTypeStrings[1].Length - 9);
                        }
                        dataTypeString = dataTypeString.Substring(7, dataTypeString.Length - 8);
                    }
                    else
                    {
                        dataTypeString = "String";
                    }
                    string defaultValueString = keyData.Comments.SingleOrDefault((x) => x.StartsWith("[Default(s):"));
                    string vanillaValueString = keyData.Comments.SingleOrDefault((x) => x.StartsWith("[Vanilla:"));
                    if (!string.IsNullOrEmpty(defaultValueString) && defaultValueString != "[Default(s): n/a]")
                    {
                        string[] defaultValueStrings = defaultValueString.Split('|');
                        defaultValueString = defaultValueStrings[0];
                        if (defaultValueStrings.Length > 1)
                        {
                            vanillaValueString = defaultValueStrings[1].Substring(10, defaultValueStrings[1].Length - 11);
                        }
                        defaultValueString = defaultValueString.Substring(13, defaultValueString.Length - 14);
                    }
                    else if (!string.IsNullOrEmpty(vanillaValueString) && vanillaValueString != "[Vanilla: n/a]")
                    {
                        vanillaValueString = vanillaValueString.Substring(10, vanillaValueString.Length - 11);
                    }
                    else
                    {
                        defaultValueString = null;
                    }
                    string allowedValuesString = keyData.Comments.SingleOrDefault((x) => x.StartsWith("[Allowed:"));
                    if (!string.IsNullOrEmpty(allowedValuesString))
                    {
                        allowedValuesString = allowedValuesString.Substring(10, allowedValuesString.Length - 11);
                    }
                    else
                    {
                        allowedValuesString = null;
                    }
                    string requiresRestartString = keyData.Comments.SingleOrDefault((x) => x.StartsWith("[Restart:"));
                    if (!string.IsNullOrEmpty(requiresRestartString))
                    {
                        requiresRestartString = requiresRestartString.Substring(10, requiresRestartString.Length - 11);
                    }
                    else
                    {
                        requiresRestartString = null;
                    }
                    bool requiresRestart = requiresRestartString != null?bool.Parse(requiresRestartString) : false;

                    GadgetConfigComponentAlignment?nullableAlignment = AlignConfigEntry(keyData.KeyName);
                    if (nullableAlignment == null)
                    {
                        continue;
                    }
                    alignment = (GadgetConfigComponentAlignment)nullableAlignment;
                    if ((alignment == GadgetConfigComponentAlignment.STANDARD && firstStandard == true) || (alignment == GadgetConfigComponentAlignment.HEADER && firstHeader == true) || (alignment == GadgetConfigComponentAlignment.FOOTER && firstFooter == true))
                    {
                        switch (alignment)
                        {
                        case GadgetConfigComponentAlignment.STANDARD:
                            firstStandard = false;
                            break;

                        case GadgetConfigComponentAlignment.HEADER:
                            firstHeader = false;
                            break;

                        case GadgetConfigComponentAlignment.FOOTER:
                            firstFooter = false;
                            break;
                        }
                    }
                    else
                    {
                        AddComponent(new GadgetConfigSeparatorComponent(this, "Seperator"), alignment);
                    }
                    seperatorMade = true;
                    foreach (string comment in keyData.Comments)
                    {
                        if (!string.IsNullOrEmpty(comment) && comment[0] != '[')
                        {
                            AddComponent(new GadgetConfigLabelComponent(this, "Comment For: " + keyData.KeyName, comment, 0.05f, true), alignment);
                        }
                    }
                    commentsMade = true;
                    switch (dataTypeString)
                    {
                    case "Boolean":
                        bool boolValue        = bool.Parse(keyData.Value);
                        bool?boolDefaultValue = defaultValueString != null ? (bool?)bool.Parse(defaultValueString) : null;
                        bool?boolVanillaValue = vanillaValueString != null ? (bool?)bool.Parse(vanillaValueString) : null;
                        AddComponent(new GadgetConfigBoolComponent(this, keyData.KeyName, boolValue, (b) => SetConfigValue(section, keyData.KeyName, b.ToString()), readonlyEntries.Contains(keyData.KeyName), boolDefaultValue, boolVanillaValue), alignment);
                        break;

                    case "Int32":
                        int   intValue = int.Parse(keyData.Value);
                        int[] intRange = dataRangeString?.Split(',').Select(x => int.Parse(x)).ToArray();
                        if (intRange != null && intRange.Length != 2)
                        {
                            throw new InvalidDataException("The range '" + dataRangeString + "' is not valid!");
                        }
                        int?intDefaultValue = defaultValueString != null ? (int?)int.Parse(defaultValueString) : null;
                        int?intVanillaValue = vanillaValueString != null ? (int?)int.Parse(vanillaValueString) : null;
                        AddComponent(new GadgetConfigIntComponent(this, keyData.KeyName, intValue, (s) => SetConfigValue(section, keyData.KeyName, s.ToString()), intRange != null ? intRange[0] : 0, intRange != null ? intRange[1] : 0, readonlyEntries.Contains(keyData.KeyName), intDefaultValue, intVanillaValue), alignment);
                        break;

                    case "Single":
                        float   floatValue = float.Parse(keyData.Value);
                        float[] floatRange = dataRangeString?.Split(',').Select(x => float.Parse(x)).ToArray();
                        if (floatRange != null && floatRange.Length != 2 && floatRange.Length != 3)
                        {
                            throw new InvalidDataException("The range '" + dataRangeString + "' is not valid!");
                        }
                        float?floatDefaultValue = defaultValueString != null ? (float?)float.Parse(defaultValueString) : null;
                        float?floatVanillaValue = vanillaValueString != null ? (float?)float.Parse(vanillaValueString) : null;
                        AddComponent(new GadgetConfigFloatComponent(this, keyData.KeyName, floatValue, (s) => SetConfigValue(section, keyData.KeyName, s.ToString()), floatRange != null ? floatRange[0] : 0, floatRange != null ? floatRange[1] : 0, floatRange != null && floatRange.Length == 3 ? (int)floatRange[2] : -1, readonlyEntries.Contains(keyData.KeyName), floatDefaultValue, floatVanillaValue), alignment);
                        break;

                    case "Double":
                        double   doubleValue = double.Parse(keyData.Value);
                        double[] doubleRange = dataRangeString?.Split(',').Select(x => double.Parse(x)).ToArray();
                        if (doubleRange != null && doubleRange.Length != 2 && doubleRange.Length != 3)
                        {
                            throw new InvalidDataException("The range '" + dataRangeString + "' is not valid!");
                        }
                        double?doubleDefaultValue = defaultValueString != null ? (double?)double.Parse(defaultValueString) : null;
                        double?doubleVanillaValue = vanillaValueString != null ? (double?)double.Parse(vanillaValueString) : null;
                        AddComponent(new GadgetConfigDoubleComponent(this, keyData.KeyName, doubleValue, (s) => SetConfigValue(section, keyData.KeyName, s.ToString()), doubleRange != null ? doubleRange[0] : 0, doubleRange != null ? doubleRange[1] : 0, doubleRange != null && doubleRange.Length == 3 ? (int)doubleRange[2] : -1, readonlyEntries.Contains(keyData.KeyName), doubleDefaultValue, doubleVanillaValue), alignment);
                        break;

                    case "String":
                        string stringValue        = keyData.Value;
                        string stringDefaultValue = defaultValueString;
                        string stringVanillaValue = vanillaValueString;
                        if (keyData.Comments.Contains("[IsKeyBind: True]"))
                        {
                            AddComponent(new GadgetConfigKeybindComponent(this, keyData.KeyName, stringValue, (s) => SetConfigValue(section, keyData.KeyName, s), true, readonlyEntries.Contains(keyData.KeyName), stringDefaultValue, stringVanillaValue), alignment);
                        }
                        else
                        {
                            AddComponent(new GadgetConfigStringComponent(this, keyData.KeyName, stringValue, (s) => SetConfigValue(section, keyData.KeyName, s), readonlyEntries.Contains(keyData.KeyName), stringDefaultValue, stringVanillaValue), alignment);
                        }
                        break;

                    case "String[]":
                        string[] stringArrayValue        = keyData.Value.Split(',');
                        string[] stringArrayDefaultValue = defaultValueString?.Split(',');
                        string[] stringArrayVanillaValue = vanillaValueString?.Split(',');
                        if (keyData.Comments.Contains("[IsKeyBind: True]"))
                        {
                            AddComponent(new GadgetConfigMultiKeybindComponent(this, keyData.KeyName, stringArrayValue, (s) => SetConfigValue(section, keyData.KeyName, s?.Aggregate(new StringBuilder(), (x, y) => { if (x.Length > 0)
                                                                                                                                                                                                                      {
                                                                                                                                                                                                                          x.Append(',');
                                                                                                                                                                                                                      }
                                                                                                                                                                                                                      x.Append(y); return(x); })?.ToString()), true, readonlyEntries.Contains(keyData.KeyName), stringArrayDefaultValue, stringArrayVanillaValue), alignment);
                        }
                        else
                        {
                            AddComponent(new GadgetConfigMultiStringComponent(this, keyData.KeyName, stringArrayValue, (s) => SetConfigValue(section, keyData.KeyName, s?.Aggregate(new StringBuilder(), (x, y) => { if (x.Length > 0)
                                                                                                                                                                                                                     {
                                                                                                                                                                                                                         x.Append(',');
                                                                                                                                                                                                                     }
                                                                                                                                                                                                                     x.Append(y); return(x); })?.ToString()), readonlyEntries.Contains(keyData.KeyName), stringArrayDefaultValue, stringArrayVanillaValue), alignment);
                        }
                        break;

                    case "KeyCode":
                        string keyCodeValue        = keyData.Value;
                        string keyCodeDefaultValue = defaultValueString;
                        string keyCodeVanillaValue = vanillaValueString;
                        AddComponent(new GadgetConfigKeybindComponent(this, keyData.KeyName, keyCodeValue, (s) => SetConfigValue(section, keyData.KeyName, s), false, readonlyEntries.Contains(keyData.KeyName), keyCodeDefaultValue, keyCodeVanillaValue), alignment);
                        break;

                    default: continue;
                    }
                }
                catch (Exception e)
                {
                    GadgetCore.Log("WARNING: Exception parsing config entry '" + keyData.KeyName + "' with value '" + keyData.Value + "': " + e);
                    try
                    {
                        if (!seperatorMade)
                        {
                            GadgetConfigComponentAlignment?nullableAlignment = AlignConfigEntry(keyData.KeyName);
                            if (nullableAlignment == null)
                            {
                                continue;
                            }
                            alignment = (GadgetConfigComponentAlignment)nullableAlignment;
                            if ((alignment == GadgetConfigComponentAlignment.STANDARD && firstStandard == true) || (alignment == GadgetConfigComponentAlignment.HEADER && firstHeader == true) || (alignment == GadgetConfigComponentAlignment.FOOTER && firstFooter == true))
                            {
                                switch (alignment)
                                {
                                case GadgetConfigComponentAlignment.STANDARD:
                                    firstStandard = false;
                                    break;

                                case GadgetConfigComponentAlignment.HEADER:
                                    firstHeader = false;
                                    break;

                                case GadgetConfigComponentAlignment.FOOTER:
                                    firstFooter = false;
                                    break;
                                }
                            }
                            else
                            {
                                AddComponent(new GadgetConfigSeparatorComponent(this, "Seperator"), alignment);
                            }
                            seperatorMade = true;
                        }
                        if (!commentsMade)
                        {
                            foreach (string comment in keyData.Comments)
                            {
                                if (!string.IsNullOrEmpty(comment) && comment[0] != '[')
                                {
                                    AddComponent(new GadgetConfigLabelComponent(this, "Comment For: " + keyData.KeyName, comment, 0.05f, true), alignment);
                                }
                            }
                            commentsMade = true;
                        }
                        AddComponent(new GadgetConfigSpacerComponent(this, "Parsing Error Spacer for: " + keyData.KeyName));
                        AddComponent(new GadgetConfigLabelComponent(this, "Parsing Error Label for: " + keyData.KeyName, "An error occured parsing the following config entry: " + keyData.KeyName, 0.05f, true), alignment);
                        AddComponent(new GadgetConfigLabelComponent(this, "Parsing Error Label for: " + keyData.KeyName, "As such, a raw-text editor is being provided as a fallback.", 0.05f, true), alignment);
                        AddComponent(new GadgetConfigLabelComponent(this, "Parsing Error Label for: " + keyData.KeyName, "Additionally, the entry's meta-comments are being displayed.", 0.05f, true), alignment);
                        AddComponent(new GadgetConfigSpacerComponent(this, "Parsing Error Spacer for: " + keyData.KeyName));
                        foreach (string comment in keyData.Comments)
                        {
                            if (!string.IsNullOrEmpty(comment) && comment[0] == '[')
                            {
                                AddComponent(new GadgetConfigLabelComponent(this, "Meta-Comment For: " + keyData.KeyName, comment, 0.05f, true), alignment);
                            }
                        }
                        AddComponent(new GadgetConfigStringComponent(this, keyData.KeyName, keyData.Value, (s) => SetConfigValue(section, keyData.KeyName, s), readonlyEntries.Contains(keyData.KeyName)), alignment);
                    }
                    catch (Exception ee)
                    {
                        GadgetCore.Log("WARNING: Failed fallback parsing of config entry '" + keyData.KeyName + "' with value '" + keyData.Value + "': " + ee);
                        try
                        {
                            if (!seperatorMade)
                            {
                                try
                                {
                                    GadgetConfigComponentAlignment?nullableAlignment = AlignConfigEntry(keyData.KeyName);
                                    if (nullableAlignment == null)
                                    {
                                        continue;
                                    }
                                    alignment = (GadgetConfigComponentAlignment)nullableAlignment;
                                    if ((alignment == GadgetConfigComponentAlignment.STANDARD && firstStandard == true) || (alignment == GadgetConfigComponentAlignment.HEADER && firstHeader == true) || (alignment == GadgetConfigComponentAlignment.FOOTER && firstFooter == true))
                                    {
                                        switch (alignment)
                                        {
                                        case GadgetConfigComponentAlignment.STANDARD:
                                            firstStandard = false;
                                            break;

                                        case GadgetConfigComponentAlignment.HEADER:
                                            firstHeader = false;
                                            break;

                                        case GadgetConfigComponentAlignment.FOOTER:
                                            firstFooter = false;
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        AddComponent(new GadgetConfigSeparatorComponent(this, "Seperator"), alignment);
                                    }
                                    seperatorMade = true;
                                }
                                catch (Exception se)
                                {
                                    GadgetCore.Log("WARNING: Failed creating seperator for failed config entry '" + keyData.KeyName + "': " + se);
                                }
                            }
                            AddComponent(new GadgetConfigLabelComponent(this, "Fatal Error Name Label for: " + keyData.KeyName, "A FATAL ERROR OCCURED PROCESSING THE FOLLOWING CONFIG ENTRY: " + keyData.KeyName, 0.05f, true), alignment);
                            AddComponent(new GadgetConfigLabelComponent(this, "Fatal Error Value Label for: " + keyData.KeyName, "THE VALUE OF THE CONFIG ENTRY IS: " + keyData.Value, 0.05f, true), alignment);
                        }
                        catch (Exception fe)
                        {
                            GadgetCore.Log("WARNING: Failed creating label for failed config entry '" + keyData.KeyName + "': " + fe);
                        }
                    }
                }
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// 读取流媒体配置文件中关键信息
        /// </summary>
        private static void getMediaServerConfig()
        {
            string iniPath = checkMediaServerConfig();

            processZLMediaKitConfigFile(iniPath); //处理FileIniDataParser碰到#开头的行,解析错误的问题
            var parser = new FileIniDataParser();

            IniData data    = parser.ReadFile(iniPath);
            var     _tmpStr = data["general"]["mediaServerId"];

            if (!string.IsNullOrEmpty(_tmpStr))
            {
                MediaServerId = _tmpStr.Trim();
            }
            else
            {
                //生成一个id
                data["general"]["mediaServerId"] = generalGuid();
                MediaServerId = data["general"]["mediaServerId"];
                parser.WriteFile(iniPath, data);
            }

            _tmpStr = data["http"]["port"];
            if (string.IsNullOrEmpty(_tmpStr))
            {
                data["http"]["port"] = "8818";
                MediaServerHttpPort  = 8818;
                parser.WriteFile(iniPath, data);
            }
            else
            {
                MediaServerHttpPort = ushort.Parse(_tmpStr);
            }

            _tmpStr = data["api"]["secret"];
            if (!string.IsNullOrEmpty(_tmpStr))
            {
                Secret = _tmpStr;
            }
            else
            {
                throw new DataException();
            }

            Uri streamNodeUri = new Uri(StreamNodeServerUrl);

            data["hook"]["enable"]         = "1";
            data["hook"]["on_flow_report"] =
                "http://" + streamNodeUri.Host + ":" + streamNodeUri.Port +
                "/WebHook/OnStop";                                                                           //流量统计,断开连接时超过flowThreshold值时会触发
            data["hook"]["on_http_access"] = "";                                                             //http事件,不作支持
            data["hook"]["on_play"]        =
                "http://" + streamNodeUri.Host + ":" + streamNodeUri.Port + "/WebHook/OnPlay";               //有流被客户端播放时
            data["hook"]["on_publish"] =
                "http://" + streamNodeUri.Host + ":" + streamNodeUri.Port + "/WebHook/OnPublish";            //有流发布时
            data["hook"]["on_record_mp4"] =
                "http://" + streamNodeUri.Host + ":" + streamNodeUri.Port + "/WebHook/OnRecordMp4Completed"; //当录制mp4完成时
            data["hook"]["on_record_ts"] =
                "http://" + streamNodeUri.Host + ":" + streamNodeUri.Port + "/WebHook/OnRecordTsCompleted";  //当录制ts完成时
            data["hook"]["on_rtsp_auth"]      = "";                                                          //rtsp鉴权,不作支持
            data["hook"]["on_rtsp_realm"]     = "";                                                          //rtsp专用鉴权,不作支持
            data["hook"]["on_shell_login"]    = "";                                                          //shell鉴权,不作支持
            data["hook"]["on_stream_changed"] =
                "http://" + streamNodeUri.Host + ":" + streamNodeUri.Port + "/WebHook/OnStreamChange";       //流注册或注销时
            data["hook"]["on_stream_none_reader"] =
                "http://" + streamNodeUri.Host + ":" + streamNodeUri.Port + "/WebHook/OnStreamNoneReader";   //流无人观看时
            data["hook"]["on_stream_not_found"] = "";                                                        //请求没有找到对应流的时候,不作支持
            data["hook"]["on_server_started"]   = "http://" + streamNodeUri.Host + ":" + streamNodeUri.Port +
                                                  "/WebHook/OnMediaServerStart";                             //当流媒体启动时
            data["hook"]["timeoutSec"]       = "5";                                                          //httpclient超时时间5秒
            data["general"]["flowThreshold"] = "1";                                                          //当用户超过1byte流量时,将触发on_flow_report的webhook(/WebHook/OnStop)

            parser.WriteFile(iniPath, data);
        }
Exemplo n.º 29
0
        public static dynamic FromFile(string filename)
        {
            var fi = new FileIniDataParser();

            return(new DynamicIniData(fi.ReadFile(filename)));
        }
Exemplo n.º 30
0
        private void btn_Generate_Click(object sender, EventArgs e)
        {
            if (!Directory.Exists(@"bin\lib"))
            {
                MessageBox.Show(this, "\"bin\\lib\" is not found.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            if (!Directory.Exists(@"bin"))
            {
                MessageBox.Show(this, "\"bin\" is not found.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            DateTime actualProcessSrat = DateTime.Now;

            richConsole.Clear();
            int error_Count  = 0;
            int Chargable    = 0;
            int nonChargable = 0;

            this.progressBar1.Visible = true;

            string       fileName = txt_FilePath.Text;
            string       log      = @"log/" + Application.ProductName + ".log";
            StreamWriter file     = new StreamWriter(log, false);


            // Load INI file from path, Stream or TextReader.
            var parser = new FileIniDataParser();


            // is also the default comment string, you need to change it
            parser.Parser.Configuration.CommentString = "//";

            IniData data = parser.ReadFile(@"bin/PDFAnalyzer_Map.ini");


            // INI Sections Assign, Separater is mid dash "|"
            var iniBlankText = data["Non-Chargable"]["BlankPage"].Split('|');
            var iniWmText    = data["Non-Chargable"]["Watermark"].Split('|');


            //Log Create
            if (!File.Exists(log))
            {
                File.Create(log);
                file.WriteLine("-------------------------------------------");
                file.WriteLine("     	  "+ Application.ProductName + " (" + Application.ProductVersion + ")");
                file.WriteLine("-------------------------------------------");

                richConsole.AppendText("-------------------------------------------\n");
                richConsole.AppendText("    " + Application.ProductName + " (" + Application.ProductVersion + ")\n");
                richConsole.AppendText("-------------------------------------------\n");
                richConsole.ScrollToCaret();

                //file.Close();
            }
            else
            {
                file.Flush();
                file.WriteLine("-------------------------------------------");
                file.WriteLine("     	  "+ Application.ProductName + " (" + Application.ProductVersion + ")");
                file.WriteLine("-------------------------------------------");

                richConsole.AppendText("-------------------------------------------\n");
                richConsole.AppendText("   " + Application.ProductName + " (" + Application.ProductVersion + ")\n");
                richConsole.AppendText("-------------------------------------------\n");
                richConsole.ScrollToCaret();
                //file.Close();
            }


            /* Validate Excel */

            if (String.IsNullOrEmpty(fileName))
            {
                error_Count++;
                MessageBox.Show(this, "Invalid Path.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                file.WriteLine("[ERROR]: Invalid path.");
                file.WriteLine("------------------ END --------------------");
                file.Close();

                richConsole.AppendText("[ERROR]: Invalid path.\n");
                richConsole.AppendText("----------------- END -----------------");
                richConsole.ScrollToCaret();

                return;
            }

            if (!File.Exists(fileName))
            {
                error_Count++;
                MessageBox.Show(this, "Invalid Path.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                file.WriteLine("[ERROR]: Path \"" + fileName + "\" is not found.");
                file.WriteLine("------------------ END --------------------");
                file.Close();


                richConsole.AppendText("[ERROR]: Path \"" + fileName + "\" is not found.\n");
                richConsole.AppendText("----------------- END -----------------");
                richConsole.ScrollToCaret();

                return;
            }

            /* Start Process */
            var workbook = new XLWorkbook(fileName);
            var ws1      = workbook.Worksheet(1);

            //Remove header from template
            int skipCells = 1;                                                        // Skip top header names
            int totalRows = ws1.Range("B2:B1048576").CellsUsed().Count() + skipCells; //Modify cell range what you want to start loop

            //MessageBox.Show(this, totalRows.ToString(), "ROW_Count", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.progressBar1.Maximum = totalRows;

            progressLabel.Visible = true;
            richConsole.AppendText("[STATUS]: Please wait, until extracting PDF files...\n");
            richConsole.ScrollToCaret();
            DateTime startTime = DateTime.Now;

            progressLabel.Text = "Extracting PDF files...";

            /* docpub application run*/
            Process ExternalProcess = new Process();

            ExternalProcess.StartInfo.FileName    = @"bin\docpubxsp_XPS.bat";
            ExternalProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            ExternalProcess.Start();
            ExternalProcess.WaitForExit();

            if (ExternalProcess.HasExited)
            {
                // ... This is case-insensitive.
                string[] zipFiles = Directory.GetFiles(@"temp/", "*.zip");


                foreach (string zipfilename in zipFiles)
                {
                    string fl             = zipfilename.Replace(@"temp/", "");
                    string filen          = fl.Replace(".zip", "");
                    string actualFilePath = @"temp/" + filen;

                    richConsole.AppendText("[STATUS]: Extracting file: " + filen + "\n");
                    richConsole.ScrollToCaret();

                    try
                    {
                        using (var zip = Ionic.Zip.ZipFile.Read(zipfilename))
                        {
                            zip.ExtractAll(actualFilePath,
                                           ExtractExistingFileAction.OverwriteSilently);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (ex.HResult == -2146233088)
                        {
                            System.IO.Compression.ZipFile.ExtractToDirectory(zipfilename, actualFilePath);
                        }
                    }

                    File.Delete(zipfilename);
                }
            }

            progressLabel.Visible = false;
            DateTime endTime = DateTime.Now;

            richConsole.AppendText("[STATUS]: PDF files extracted... (Process Time: " + (endTime - startTime) + ")\n");

            for (int i = (1 + skipCells); i <= totalRows; i++)
            {
                //Progessbar
                progressBar1.Value += 1;

                //Initialize row
                var  row   = ws1.Row(i);
                bool empty = row.IsEmpty();

                var    cell     = row.Cell(2);
                var    cellSkip = row.Cell(1);
                string value    = cell.GetValue <string>();
                //string value = valuepdf.Replace("-primary.pdf", "");
                string valueSkip = cellSkip.GetValue <string>();

                if (valueSkip == "The following pages are non-chargeable")
                {
                    break;
                }



                /*5-9*/
                if (!empty)
                {
                    richConsole.AppendText(value + "\n");
                    richConsole.ScrollToCaret();

                    string ppath = value;

                    var inputDirectory = Directory.EnumerateFiles(@"input\");
                    var pdfFile        = inputDirectory.FirstOrDefault(PDFfile => PDFfile.Contains(ppath));
                    var pdfFileExists  = pdfFile != null;

                    if (pdfFileExists)
                    {
                        string getPath0          = pdfFile.Replace(@"input\", "");
                        string getPath1          = getPath0.Replace(".pdf", "");
                        string tempZipFolder     = @"temp/" + getPath1;
                        bool   additionalRemarks = false;
                        bool   IsOCR             = false;

                        //int TOCPage = 0;
                        List <int> FrontPageNumbers = new List <int>();
                        int        frontMaxPage     = 0;
                        int        backMaxPage      = 0;
                        int        chkWMPage        = 0;
                        int        chkOCR           = 0;

                        List <string> WMPages    = new List <string>();
                        List <string> BlankPages = new List <string>();

                        PdfReader pdfReader     = new PdfReader(pdfFile);
                        int       numberOfPages = pdfReader.NumberOfPages;
                        Chargable = numberOfPages;
                        var Info = pdfReader.PdfVersion;

                        ws1.Cell(i, 6).DataType = XLDataType.Number;
                        ws1.Cell(i, 6).Value    = (numberOfPages);

                        var xmlDoc = new XmlDocument();
                        //int isTOCFound = 0;
                        //const int blankPdfsize = 20;
                        var raf = new RandomAccessFileOrArray(pdfFile);


                        //if (File.Exists(tempZipFolder + @"/Documents/1/Structure/DocStruct.struct"))
                        //{

                        //    // content is your XML as string
                        //    xmlDoc.Load(tempZipFolder + @"/Documents/1/Structure/DocStruct.struct");

                        //    XmlNodeList elemList = xmlDoc.GetElementsByTagName("OutlineEntry");
                        //    for (int s = 0; s < elemList.Count; s++)
                        //    {

                        //        string DescriptionVal = elemList[s].Attributes["Description"].Value;

                        //        /*Table of Contents Checking*/
                        //        bool TOC = DescriptionVal.Contains("CONTENTS") || DescriptionVal.Contains("Table of Contents") || DescriptionVal.Contains("Contents");

                        //        /*Preface Checking*/
                        //        bool Preface = DescriptionVal.Contains("PREFACE") || DescriptionVal.Contains("Preface");

                        //        /*Foreward Checking*/
                        //        bool Foreward = DescriptionVal.Contains("FOREWORD") || DescriptionVal.Contains("Foreword");

                        //        /*Introduction Checking*/
                        //        bool Intro = DescriptionVal.Contains("INTRODUCTION") || DescriptionVal.Contains("Introduction");

                        //        if (TOC)
                        //        {

                        //            TOCPage = int.Parse(elemList[s + 1].Attributes["OutlineTarget"].Value.Replace("/FixedDocumentSequence.fdseq#", ""));
                        //            //FrontPageNumbers.Add(TOCPage - 1);

                        //            isTOCFound = TOCPage;

                        //        }

                        //    }

                        //    //if (FrontPageNumbers.Count > 0)
                        //    //{
                        //    //    frontMaxPage = FrontPageNumbers.Max();
                        //    //}
                        //    //else
                        //    //{
                        //    //    frontMaxPage = 0;
                        //    //}

                        //}

                        List <List <string> > groups  = new List <List <string> >();
                        List <string>         current = null;

                        /*Read Each Page*/
                        for (int j = 1; j <= numberOfPages; j++)
                        {
                            foreach (var line in File.ReadAllLines(tempZipFolder + @"\Documents\1\Pages\" + (j) + ".fpage"))
                            {
                                //if ((line.Contains("UnicodeString=\"NOTES ") || line.Contains("UnicodeString=\"Notes ") || line.Contains("UnicodeString=\"NOTES\"")) && current == null)
                                //{
                                //    nonChargable += 1;

                                //}
                                //else if ((line.Contains("UnicodeString=\"Intentionally Blank ") || line.Contains("UnicodeString=\"INTENTIONALLY BLANK ") || line.Contains("UnicodeString=\"INTENTIONALLY BLANK\"")) && current == null)
                                //{
                                //    nonChargable += 1;

                                //}

                                if ((line.Contains("&lt;FrontMatter&gt;")) && current == null)
                                {
                                    frontMaxPage = j - 1;
                                }

                                if ((line.Contains("&lt;/FrontMatter&gt;")) && current == null)
                                {
                                    backMaxPage = numberOfPages - j;
                                }

                                //Watermark
                                if ((line.Contains("&lt;WATERMARKED&gt;")) && current == null)
                                {
                                    WMPages.Add(j.ToString());
                                    additionalRemarks = true;
                                }
                                //BlankPages
                                if ((line.Contains("&lt;SA_BLANK_PAGE&gt;")) && current == null)
                                {
                                    nonChargable += 1;
                                    BlankPages.Add(j.ToString());
                                }

                                //Match m = Regex.Match(line, "<Path Data=\".*Z \"");
                                //if (m.Success && m.Length > 10440 && (!line.Contains("StrokeMiterLimit")) && current == null || (line.Contains("UnicodeString=\"Internal Use Only")))
                                //{

                                //    WMPages.Add(j.ToString());
                                //    additionalRemarks = true;
                                //}
                                //else
                                //{

                                //    //FindWatermark
                                //    foreach (String key in iniWmText)
                                //    {
                                //        if ((line.Contains("UnicodeString=\"" + key.ToString() + "\"")) && current == null)
                                //        {
                                //            WMPages.Add(j.ToString());
                                //            additionalRemarks = true;
                                //        }
                                //    }

                                //}
                            }
                        }



                        //loop through each page and if the bs is larger than 20 than we know it is not blank.
                        //if it is less than 20 than we don't include that blank page.
                        //for (var page = frontMaxPage + 1; page < numberOfPages - backMaxPage; page++)
                        //{
                        //    if (frontMaxPage > 0)
                        //    {
                        //        string text = string.Empty;

                        //        text += PdfTextExtractor.GetTextFromPage(pdfReader, page);

                        //        // get the page content
                        //        byte[] bContent = pdfReader.GetPageContent(page, raf);
                        //        var bs = new MemoryStream();
                        //        bs.Write(bContent, 0, bContent.Length);



                        //        ////FindBlanks
                        //        //foreach (String key in iniBlankText)
                        //        //{

                        //        //    if (text == key.ToString() || text == key.ToString() + " ")
                        //        //    {
                        //        //        nonChargable += 1;
                        //        //        BlankPages.Add(page.ToString());
                        //        //    }

                        //        //    if (string.IsNullOrEmpty(text) || text== "<FrontMatter>" || text == "</FrontMatter>" && bs.Length < 150)
                        //        //    {
                        //        //        chkOCR++;
                        //        //    }

                        //        //}

                        //        //if (string.IsNullOrEmpty(text) && bs.Length > blankPdfsize)
                        //        //{
                        //        //    nonChargable += 1;
                        //        //    BlankPages.Add(page.ToString());
                        //        //}

                        //    }
                        //}

                        //OCR identify
                        if (chkOCR > numberOfPages / 2)
                        {
                            IsOCR = true;
                        }

                        //Chargeble Page Count
                        ws1.Cell(i, 7).DataType = XLDataType.Number;
                        ws1.Cell(i, 7).Value    = ((numberOfPages) - (frontMaxPage + backMaxPage + nonChargable));
                        //nonChargable = 0;

                        //BlankPages
                        ws1.Cell(i, 12).DataType = XLDataType.Number;
                        ws1.Cell(i, 12).Value    = (nonChargable);
                        ws1.Cell(i, 12).Style.Fill.BackgroundColor = XLColor.LightGray;
                        if (BlankPages.Count != 0)
                        {
                            error_Count++;
                            richConsole.AppendText("[INFO]: " + value + ", blank detected between bodymatter in page(s) " + string.Join(",", BlankPages.Distinct()) + "\n");
                            //richConsole.ScrollToCaret();
                            file.WriteLine("[INFO]: " + value + ", blank detected between bodymatter in page(s) " + string.Join(",", BlankPages.Distinct()));

                            ws1.Cell(i, 13).Value = ("Blank detected between bodymatter in page(s) " + string.Join(",", BlankPages.Distinct()) + ".");
                        }

                        nonChargable = 0;

                        //Additional Remarks
                        ws1.Cell(i, 13).DataType = XLDataType.Text;

                        if (BlankPages.Count != 0 && additionalRemarks)
                        {
                            ws1.Cell(i, 13).Value = ("1. blank detected between bodymatter in page(s) " + string.Join(",", BlankPages.Distinct()) + ".\n2. Please verify if this file included with watermark page(s)\n");
                            additionalRemarks     = false;
                            IsOCR  = false;
                            chkOCR = 0;
                        }
                        else if (chkOCR > 0 && additionalRemarks)
                        {
                            ws1.Cell(i, 13).Value = ("1. This file may be Scanned PDF, please manually check this again.\n2. Please verify if this file included with watermark page(s)\n");
                            additionalRemarks     = false;
                            IsOCR  = false;
                            chkOCR = 0;
                        }
                        else if (IsOCR)
                        {
                            ws1.Cell(i, 13).Value = ("This file may be Scanned PDF, please manually check this again.\n");
                            IsOCR  = false;
                            chkOCR = 0;
                        }
                        else if (BlankPages.Count == 0 && additionalRemarks)
                        {
                            ws1.Cell(i, 13).Value = ("Please verify if this file included with watermark page(s)\n");
                            additionalRemarks     = false;
                        }

                        ws1.Cell(i, 13).Style.Fill.BackgroundColor = XLColor.LightGray;
                        additionalRemarks = false;


                        //check WaterMark Count
                        if (WMPages.Count != 0)
                        {
                            error_Count++;
                            richConsole.AppendText("[WARRNING]: " + value + ", watermarks found in page(s) " + string.Join(",", WMPages.Distinct()) + "\n");
                            //richConsole.ScrollToCaret();

                            file.WriteLine("[WARRNING]: " + value + ", watermarks found in page(s) " + string.Join(",", WMPages.Distinct()));

                            ws1.Cell(i, 8).DataType = XLDataType.Text;
                            ws1.Cell(i, 8).Value    = ("YES");
                            ws1.Cell(i, 8).Style.Fill.BackgroundColor = XLColor.Yellow;
                            chkWMPage = 0;
                        }
                        else
                        {
                            chkWMPage = 0;
                        }



                        //nonChargableBeforeFront
                        ws1.Cell(i, 9).DataType = XLDataType.Number;
                        ws1.Cell(i, 9).Value    = (frontMaxPage);
                        frontMaxPage            = 0;

                        //nonChargableAfterback
                        ws1.Cell(i, 10).DataType = XLDataType.Number;
                        ws1.Cell(i, 10).Value    = (backMaxPage);
                        backMaxPage = 0;

                        /*ReSet*/
                        //isTOCFound = 0;
                        //isPrefaceFound = 0;
                        //isForwardFound = 0;
                        //isIntroFound = 0;

                        ////If All Done
                        Directory.Delete(tempZipFolder, true);
                    }
                    else
                    {
                        ws1.Cell(i, 6).DataType = XLDataType.Text;
                        ws1.Cell(i, 6).Style.Fill.BackgroundColor = XLColor.Yellow;
                        ws1.Cell(i, 6).Value = ("NOT FOUND");
                    }
                }
            }

            /* End Process*/

            //BlankPages
            ws1.Cell(1, 12).DataType = XLDataType.Text;
            ws1.Cell(1, 12).Value    = ("Blank Pages Count - Between Content");
            ws1.Cell(1, 12).Style.Fill.BackgroundColor = XLColor.LightGray;
            nonChargable = 0;

            //Additional Remarks
            ws1.Cell(1, 13).DataType = XLDataType.Text;
            ws1.Cell(1, 13).Value    = ("Additional Remarks");
            ws1.Cell(1, 13).Style.Fill.BackgroundColor = XLColor.LightGray;

            DateTime actualProcessEnd = DateTime.Now;

            /*Log file Close*/
            richConsole.AppendText("[STATUS]: Total Process Time - " + (actualProcessEnd - actualProcessSrat).ToString() + "\n");
            richConsole.ScrollToCaret();
            file.WriteLine("------------------ END --------------------");
            file.Close();

            richConsole.AppendText("----------------- END -----------------");
            richConsole.ScrollToCaret();

            workbook.SaveAs(@"output/Catalogue v1" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xlsx");

            this.progressBar1.Visible = false;
            progressBar1.Value        = 1;
            MessageBox.Show(this, "Precess Completed.", "Done!", MessageBoxButtons.OK, MessageBoxIcon.Information);

            /* Automatically open log file */
            if (error_Count > 0)
            {
                Process.Start("notepad.exe", log);
            }
        }