Пример #1
0
 public void reClient()
 {
     string listenerIp = WebService.ContentValue("Listener", "ListenerIp", WebService.WASConfigPath);//监听的IP地址
     string listenerPort = WebService.ContentValue("Listener", "ListenerPort", WebService.WASConfigPath);//监听的端口号
     string DataSourceIpOrPortA = WebService.ContentValue("DataSourceA", "DataServiceA", WebService.WASConfigPath);//数据源的IP和端口A
     string DataSourceIpOrPortB = WebService.ContentValue("DataSourceB", "DataServiceB", WebService.WASConfigPath);//数据源的IP和端口B
     using (System.IO.StreamWriter sws = new System.IO.StreamWriter("C:\\KIOSKlog2.txt", true))
     {
         sws.WriteLine(DataSourceIpOrPortA);
         sws.WriteLine(DataSourceIpOrPortB);
     }
     IPAddress ip = IPAddress.Parse(listenerIp);//IP地址
     listener = new TcpListener(ip, Convert.ToInt32(listenerPort));//使用本机Ip地址和端口号创建一个System.Net.Sockets.TcpListener的实例
     try
     {
         listener.Start(); ////监听客户端的请求:开始侦听
     }
     catch (Exception)
     {
         return;
     }
     try
     {
         while (true) //接收多个客户端
         {
             client = listener.AcceptTcpClient();//获取单一客户端连接
             agent = new Agent(client, client.GetStream(), DataSourceIpOrPortA, DataSourceIpOrPortB);
             ziThread = new Thread(agent.dele);//单一客户端可以发送多条请求
             ziThread.Start(null);
         }
     }
     catch (SocketException)
     {
     }
 }
Пример #2
0
        static void Main(string[] args)
        {
            double start = -4;
            double end = 6;
            double factor = 65535 / Math.Exp(end);
            int steps = 100;
            double step = (end - start) / (steps - 1);
            int i;
            int value;

            System.IO.StreamWriter file = new System.IO.StreamWriter(@"logvec.h");
            System.IO.StreamWriter file2 = new System.IO.StreamWriter(@"logvec.txt");

            file.Write("static const int logvec[] = { 0x0000,");
            for (i = 0; i < 100; i++)
            {
                if ((i % 10) == 0)
                {
                    file.WriteLine();
                    file.Write("\t");
                }
                value = (int)Math.Floor(Math.Exp(start) * factor);
                start += step;
                file2.Write("{0}, ", value);
                file.Write ("0x{0:X4}, ", value);
            }
            file.WriteLine();
            file.WriteLine("};");

            file.Close();
            file2.Close();
        }
Пример #3
0
        public void Run()
        {
            var ext = System.IO.Path.GetExtension(m_targetpath);
            var module = m_options.CompressionModule;

            if (ext != module)
                m_targetpath = m_targetpath + "." + module;

            if (System.IO.File.Exists(m_targetpath))
                throw new Exception(string.Format("Output file already exists, not overwriting: {0}", m_targetpath));

            if (!System.IO.File.Exists(m_options.Dbpath))
                throw new Exception(string.Format("Database file does not exist: {0}", m_options.Dbpath));

            m_result.AddMessage("Scrubbing filenames from database, this may take a while, please wait");

            using(var tmp = new Library.Utility.TempFile())
            {
                System.IO.File.Copy(m_options.Dbpath, tmp, true);
                using(var db = new LocalBugReportDatabase(tmp))
                {
                    m_result.SetDatabase(db);
                    db.Fix();
                }

                using(var cm = DynamicLoader.CompressionLoader.GetModule(module, m_targetpath, m_options.RawOptions))
                {
                    using(var cs = cm.CreateFile("log-database.sqlite", Duplicati.Library.Interface.CompressionHint.Compressible, DateTime.UtcNow))
                    using(var fs = System.IO.File.Open(tmp, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
                        Library.Utility.Utility.CopyStream(fs, cs);

                    using(var cs = new System.IO.StreamWriter(cm.CreateFile("system-info.txt", Duplicati.Library.Interface.CompressionHint.Compressible, DateTime.UtcNow)))
                    {
                        cs.WriteLine("Duplicati: {0} ({1})", System.Reflection.Assembly.GetEntryAssembly().FullName, System.Reflection.Assembly.GetExecutingAssembly().FullName);
                        cs.WriteLine("OS: {0}", Environment.OSVersion);
                        cs.WriteLine("Uname: {0}", Duplicati.Library.Utility.Utility.UnameAll);

                        cs.WriteLine("64bit: {0} ({1})", Environment.Is64BitOperatingSystem, Environment.Is64BitProcess);
                        cs.WriteLine("Machinename: {0}", Environment.MachineName);
                        cs.WriteLine("Processors: {0}", Environment.ProcessorCount);
                        cs.WriteLine(".Net Version: {0}", Environment.Version);
                        cs.WriteLine("Mono: {0} ({1}) ({2})", Duplicati.Library.Utility.Utility.IsMono, Duplicati.Library.Utility.Utility.MonoVersion, Duplicati.Library.Utility.Utility.MonoDisplayVersion);

                        Type sqlite = null;
                        string sqliteversion = "";

                        try { sqlite = Duplicati.Library.SQLiteHelper.SQLiteLoader.SQLiteConnectionType; }
                        catch { }

                        if (sqlite != null)
                        {
                            try { sqliteversion = (string)sqlite.GetProperty("SQLiteVersion").GetValue(null, null); }
                            catch { }

                            cs.WriteLine("SQLite: {0} - {1}", sqliteversion, sqlite.FullName);
                        }
                    }
                }
            }
        }
 public static void WriteLog(Exception ex)
 {
     //just in case: we protect code with try.
     try
     {
         string filename = m_baseDir
             + GetFilenameYYYMMDD("_LOG", ".log");
         System.IO.StreamWriter sw = new System.IO.StreamWriter(filename, true);
     //				XElement xmlEntry = new XElement("logEntry",
     //				                                 new XElement("Date", System.DateTime.Now.ToString()),
     //				                                 new XElement("Exception",
     //				             new XElement("Source", ex.Source),
     //				             new XElement("Message", ex.Message),
     //				             new XElement("Stack", ex.StackTrace)
     //				             )//end exception
     //				                                 );
         sw.WriteLine(string.Format("{0} {1} {2}\r\n{3}",System.DateTime.Now.ToString(), ex.Source, ex.Message, ex.StackTrace));
         //has inner exception?
         if (ex.InnerException != null)
         {
     //					xmlEntry.Element("Exception").Add(
     //					                                  new XElement("InnerException",
     //					             new XElement("Source", ex.InnerException.Source),
     //					             new XElement("Message", ex.InnerException.Message),
     //					             new XElement("Stack", ex.InnerException.StackTrace))
     //					                                  );
             sw.WriteLine(string.Format("{0} {1} {2}\r\n{3}",System.DateTime.Now.ToString(),
                 ex.InnerException.Source, ex.InnerException.Message, ex.InnerException.StackTrace));
         }
         //sw.WriteLine(xmlEntry);
         sw.Close();
     } catch (Exception) {}
 }
Пример #5
0
        public void SauvegarderCarte(List<Tuile>[,] tuileArray, String asset)
        {
            ecrireCarte = new System.IO.StreamWriter(asset);

            int width = tuileArray.GetLength(0);
            int height = tuileArray.GetLength(1);

            ecrireCarte.WriteLine(width);
            ecrireCarte.WriteLine(height);

            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    string str = "";

                    foreach (Tuile tuile in tuileArray[x, y])
                    {
                        str += tuile.type;
                        if (tuile.hauteur < 10)
                            str += "0";
                        str += tuile.hauteur;
                    }

                    ecrireCarte.WriteLine(str);

                }
            }

            ecrireCarte.Close();

            Console.WriteLine("CARTE SAUVEGARDEE");
        }
Пример #6
0
        MakePackage()
        {
            var packageDir = Graph.Instance.ProcessState.WorkingDirectory;
            var bamDir = System.IO.Path.Combine(packageDir, BamSubFolder);
            if (System.IO.Directory.Exists(bamDir))
            {
                throw new Exception("A Bam package already exists at {0}", packageDir);
            }

            var packageNameArgument = new Options.PackageName();
            var packageName = CommandLineProcessor.Evaluate(packageNameArgument);
            if (null == packageName)
            {
                throw new Exception("No name was defined. Use {0} on the command line to specify it.", (packageNameArgument as ICommandLineArgument).LongName);
            }

            var packageVersion = CommandLineProcessor.Evaluate(new Options.PackageVersion());
            var definition = new PackageDefinition(bamDir, packageName, packageVersion);

            System.IO.Directory.CreateDirectory(bamDir);
            definition.Write();

            var scriptsDir = System.IO.Path.Combine(bamDir, ScriptsSubFolder);
            System.IO.Directory.CreateDirectory(scriptsDir);

            var initialScriptFile = System.IO.Path.Combine(scriptsDir, packageName) + ".cs";
            using (System.IO.TextWriter writer = new System.IO.StreamWriter(initialScriptFile))
            {
                writer.WriteLine("using Bam.Core;");
                writer.WriteLine("namespace {0}", packageName);
                writer.WriteLine("{");
                writer.WriteLine("    // write modules here ...");
                writer.WriteLine("}");
            }
        }
Пример #7
0
        public static bool endCurrentPeriod(string username, string name)
        {
            try
            {
                string clean = "";
                string[] lines;

                lines = System.IO.File.ReadAllLines("Data\\" + username + ".current");
                int mlz = 0;
                int exp = 0;
                for (int i = 0; i < lines.Length; i++)
                {
                    if (i % 2 == 0)
                    {
                        if (lines[i].StartsWith("$"))
                            exp += Int16.Parse(lines[i].TrimStart('$'));
                        else
                            mlz += Int16.Parse(lines[i]);
                    }
                }
                clean += "$" + exp + ", " + mlz + " mi.";

                System.IO.StreamWriter file = new System.IO.StreamWriter("Data\\" + username + ".archive", true);
                file.WriteLine(clean);
                file.WriteLine(name);
                file.Close();
                file = new System.IO.StreamWriter("Data\\" + username + ".current", false);
                file.Close();
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }
Пример #8
0
        public static void Main(string[] args)
        {
            Defrag.IFileSystem fileSystem = new Defrag.Win32FileSystem("C:");
            Defrag.Optimizer optimizer = new Defrag.Optimizer(fileSystem);

            Defrag.Win32ChangeWatcher watcher = new Defrag.Win32ChangeWatcher("C:\\");
            System.IO.TextWriter log = new System.IO.StreamWriter(System.Console.OpenStandardOutput());

            while (true)
            {
                String path = watcher.NextFile();
                if (path != null)
                {
                    try
                    {
                        optimizer.DefragFile(path, log);
                    }
                    catch (Win32Exception ex)
                    {
                        log.WriteLine(ex.Message);
                        log.WriteLine("* * Failed! * *");
                    }
                    finally
                    {
                        log.WriteLine();
                        log.Flush();
                    }
                }
                else
                {
                    Thread.Sleep(500);
                }
            }
        }
Пример #9
0
        static void Main(string[] args)
        {
            BcsDefinitionFile document;

            using (var bcsHandler = new BcsFileHandler())
            {
                bcsHandler.ProcessDefinitionFile("yamada.txt");
                document = bcsHandler.DefinitionFile;
            }

            //categorize
            var malformedLines = document.Entities.SelectMany(e => e.MalformedLines).Concat(document.Rules.SelectMany(r => r.MalformedLines));
            var equations = document.Rules.Select(r => r.Equation);

            //write debug output
            using (var writer = new System.IO.StreamWriter("eq.txt"))
            {
                foreach (var equation in equations)
                {
                    writer.WriteLine(equation.SourceText);

                    var stringifiedTokens = equation.SourceTokens.Select(token => $"[{token.Type.GetDescription()}]");

                    writer.WriteLine(string.Join("", stringifiedTokens));
                }
                writer.Close();
            }
        }
Пример #10
0
        /// <summary>
        /// ExportCentroidsDict2TXT
        /// </summary>
        /// <param name="dictionary"></param>
        /// <param name="exportFileName"></param>
        public void ExportCentroidsDict2TXT(Dictionary<string, string> dictionary, 
            string exportFileName,
            Engine.AppEngine.ProjectionUnits projUnits,
            Boolean includeAreaPerimeter)
        {
            System.IO.TextWriter textWriter = new System.IO.StreamWriter(exportFileName);

              if (projUnits == Engine.AppEngine.ProjectionUnits.Geometric){
            if (includeAreaPerimeter == true)
            {
              textWriter.WriteLine("AreaId,CoordX,CoordY,Area,Perimeter");
            }
            else
            {
              textWriter.WriteLine("AreaId,CoordX,CoordY");
            }
              }
              else {
            if (includeAreaPerimeter == true)
            {
              textWriter.WriteLine("AreaId,Lat,Lon,Area,Perimeter");
            }
            else
            {
              textWriter.WriteLine("AreaId,Lat,Lon");
            }
              } // End if

              foreach (var dictItem in dictionary)
              {
            textWriter.WriteLine(dictItem.Value);
              } //End Foreach

              textWriter.Close();
        }
Пример #11
0
        static void Main(string[] args)
        {
            System.IO.StreamWriter outputFile = new System.IO.StreamWriter(@"c:\VisualStudioOhjelmointi\tv.txt");

            TV tv1 = new TV { ShowName = "Uutiset", Channel = "Yle TV1", StartTime = "20.30", EndTime = "20.50", Info = "Illan uutislähetys" };
            outputFile.WriteLine(tv1);

            TV tv2 = new TV { ShowName = "Kymmenen uutiset", Channel = "MTV3", StartTime = "22.00", EndTime = "22.20", Info = "Illan pääuutislähetys" };
            outputFile.WriteLine(tv2);

            TV tv3 = new TV { ShowName = "Urheilua", Channel = "Yle TV2", StartTime = "14.30", EndTime = "16.50", Info = "Urheilua suorana lähetyksenä" };
            outputFile.WriteLine(tv3);

            outputFile.Close();

            try
            {
                string tvshows = System.IO.File.ReadAllText(@"c:\VisualStudioOhjelmointi\tv.txt");
                Console.WriteLine(tvshows);
            }
            catch (System.IO.FileNotFoundException)
            {
                Console.WriteLine("File not found!!!");
            }
        }
Пример #12
0
        static void Main(string[] args)
        {
            Console.WriteLine("Лабораторная работа по численным методам №6. Формула Гаусса");
            Console.WriteLine("Задача №8.5: [1.2;2](x-0.5)dx/((x^2-1)^1/2)\n");
            double Integral = 0;
            double a = 1.2, b = 2;
            double[,] AandT = new double[2,5];
            AandT[0, 0] = 0.236927;
            AandT[0, 1] = 0.478629;
            AandT[0, 2] = 0.568889;
            AandT[0, 3] = 0.478629;
            AandT[0, 4] = 0.236927;
            AandT[1, 0] = -0.906180;
            AandT[1, 1] = -0.538459;
            AandT[1, 2] = 0;
            AandT[1, 3] = 0.538469;
            AandT[1, 4] = 0.906180;

            System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Lab6.txt");
            for (int i = 0; i < 5; ++i)
            {
                Integral += AandT[0, i] * f(((a + b) / 2) + ((b - a) / 2) * AandT[1, i]);
                Console.WriteLine("t{0} = {1:0.000000}, A{0} = {2:0.000000}, Summ(I){0} = {3:0.00000}", i + 1, AandT[1, i], AandT[0, i], Integral);
                file.WriteLine("t{0} = {1:0.000000}, A{0} = {2:0.000000}, Summ(I){0} = {3:0.00000}", i + 1, AandT[1, i], AandT[0, i], Integral);
            }
            Integral *= (b - a) / 2;
            file.WriteLine("Ответ: " + Integral);
            Console.WriteLine("\nПриближенное значение интеграла I = {0:0.00000}",Integral);
            file.Close();
        }
Пример #13
0
 public static void LogPublicElements()
 {
     using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"API.csv"))
     {
         foreach (Type type in Assembly.GetAssembly(typeof(World)).GetTypes().Where(t => t.IsPublic))
         {
             if (!type.GetMembers(BindingFlags.Public
                                 | BindingFlags.Instance
                                 | BindingFlags.DeclaredOnly
                                 | BindingFlags.InvokeMethod).Any())
                 continue;
             file.WriteLine(type.Name);
             foreach (ConstructorInfo member in type.GetConstructors())
                 file.WriteLine(";Constructor"+"(" + (member.GetParameters().Any() ? string.Join(", ", member.GetParameters().Select(p => p.ParameterType.Name)) : "")+")");
             foreach (MethodInfo member in type.GetMethods())
             {
                 if (!(new[] { "ToString", "GetHashCode", "Equals", "GetType" }).Contains(member.Name))
                 {
                     if (member.DeclaringType != null && member.DeclaringType.IsInterface)
                     {
                         if(!member.DeclaringType.IsPublic)
                             continue;
                     }
                     var toBeDeleted = new[] { "System.", "Collections.Generic.", "`1", "`2", "Alpha.Core.Realms.", "Alpha.Core.Provinces.", "Alpha.Core.Fleets.", "Alpha.Core.Commands.", "Alpha.Core.Calendars.", "Alpha.Toolkit.Math." };
                     string name = member.ToString();
                     name = toBeDeleted.Aggregate(name, (current, value) => current.Replace(value, string.Empty));
                     name = name.Replace(" ", ";");
                     file.WriteLine(name);
                 }
             }
             file.WriteLine();
         }
     }
 }
Пример #14
0
        public static void chatResult(System.Collections.Hashtable raceStat, string datFile, string raceDir, infoRace currInfoRace, string chatInX)
        {
            // add InRace and InQual then deside!
            System.IO.StreamWriter sw = new System.IO.StreamWriter(raceDir + "/" + datFile + "_chat_" + chatInX + ".html");
            System.IO.StreamReader sr = new System.IO.StreamReader("./templates/html_chat.tpl");
            string readLine;
            combinedSplit = 0;

            while (true)
            {
                readLine = sr.ReadLine();
                if (readLine == null)
                    break;
                if (readLine.IndexOf("{IngameChatLog}") !=-1 )
                {
                    readLine = readLine.Replace("{IngameChatLog}","|" );
                    string [] str = readLine.Split('|');
                    sw.WriteLine(str[0]);
                    for (int i = 0; i < currInfoRace.chat.Count; i++)
                        sw.WriteLine(currInfoRace.chat[i] + "<BR>");
                    sw.WriteLine(str[1]);
                }
                else
                {
                    readLine = updateGlob(readLine, datFile, currInfoRace, chatInX);
                    sw.WriteLine(readLine);
                }
            }
            sw.Close();
            sr.Close();
        }
Пример #15
0
        // Save people from text file
        public bool SavePeople()
        {
            System.IO.TextWriter textOut = null;
            try
            {
                System.IO.File.WriteAllText(filename, string.Empty);
                textOut = new System.IO.StreamWriter(filename);
                textOut.WriteLine(TopFivePeople.Count());
                foreach (PersonDetails People in TopFivePeople) // Save all the people
                {
                    textOut.WriteLine(People.NameGetSet);
                    textOut.WriteLine(People.ScoreGetSet);
                }

            }
            catch
            {
                return false;
            }
            finally
            {
                if (textOut != null) textOut.Close();
            }

            return true;
        }
Пример #16
0
        public static void UpdateCache(string folderPath, Dictionary<string, PMetaData> datas)
        {
            if (datas.Count > 0)
            {                
                System.IO.FileInfo info;
                if (System.IO.File.Exists(folderPath + @"\" + GENTLE_FILE))
                {
                    info = new System.IO.FileInfo(folderPath + @"\" + GENTLE_FILE);
                    info.Attributes = System.IO.FileAttributes.Normal;
                }

                using (System.IO.StreamWriter writer = new System.IO.StreamWriter(folderPath + @"\"  + GENTLE_FILE))
                {
                    foreach (var item in datas)
                    {
                        writer.WriteLine(string.Format("[{0}]", System.IO.Path.GetFileName(item.Key)));
                        writer.WriteLine(string.Format("hash={0}", item.Value.Hash));
                        writer.WriteLine(string.Format("keywords={0}", string.Join(",", item.Value.Keywords.ToArray())));                        
                        writer.WriteLine(string.Format("updated={0}", item.Value.Updated));                       
                    }
                }

                info = new System.IO.FileInfo(folderPath + @"\" + GENTLE_FILE);
                info.Attributes = System.IO.FileAttributes.Hidden;
            }
        }
Пример #17
0
        public void OpenFile(string path)
        {
            // at least on 64bit windows - critical to use no byte order mark;
            System.Text.Encoding Enc = new System.Text.UTF8Encoding(false, true);
            //System.Text.Encoding Enc = new System.Text.ASCIIEncoding()

            DotFile = new System.IO.StreamWriter(path, false, Enc);
            DotFile.WriteLine("digraph G {");
            switch (directionMode)
            {
                    // remember we draw arrows backwards, DIR=BACK
                case graphDirection.UP: DotFile.WriteLine("rankdir=\"UD\";"); break;
                case graphDirection.DOWN : DotFile.WriteLine("rankdir=\"DU\";"); break;
                case graphDirection.LEFT : DotFile.WriteLine("rankdir=\"LR\";"); break;
                case graphDirection.RIGHT : DotFile.WriteLine("rankdir=\"RL\";"); break;
            }

            DotFile.WriteLine("ratio=\"compress\";");
            DotFile.WriteLine("nodesep=0.1;");
            //DotFile.Write(@"imagepath=C:\temp\");

            if (false)
            {
                //for twopi:
                DotFile.WriteLine("size = \"20\" ;");
                DotFile.WriteLine("overlap = \"false\" ;");
                DotFile.WriteLine("fontname = \"Arial\" ;");
                DotFile.WriteLine("ranksep = \"0.5\" ;");
                DotFile.WriteLine("ratio = \"auto\" ;");
                DotFile.WriteLine("root = \"{}\" ;");
            }
        }
Пример #18
0
        static void Main(string[] args)
        {
            var rand = new Random();
            //changing eps
            
            System.IO.StreamWriter file = new System.IO.StreamWriter("d:\\test.txt");
            file.WriteLine("changing eps");
            file.WriteLine("n eps time");
          
            for (int i = 100; i < 30000; i += 5000)
            {
                int[] t = new int[i];
                for (int k = 0; k < i; k++)
                {
                    t[k] = rand.Next(100);
                }
                for (double j = 0.5; j >= 0.05; j -= 0.05)
                {
                    Console.WriteLine(string.Format("{0} {1}", i, j));
                    var ptas = new PTAS.Repo.Ptas(t, j);
                    long time = 0;
                    for (int p = 0; p < 3; p++)
                    {
                        time += ptas.ptasFunction();
                    }
                    file.WriteLine(string.Format("{0} {1} {2}", i, j, time/3.0));
                }
            }

            file.Close();            
        }
Пример #19
0
 public void Save(string filename)
 {
     var cols = columns.OrderBy(kv => kv.Value).Select(kv => kv.Key).ToList();
     using (var o = new System.IO.StreamWriter(filename))
     {
         // write header
         {
             var header = "";
             var mid = "";
             foreach (var col in cols)
             {
                 header += mid+Escape(col);
                 mid = ";";
             }
             o.WriteLine(header);
         }
         // then rows
         foreach (var row in rows)
         {
             var line = "";
             var mid = "";
             foreach (var col in cols)
             {
                 var val = "";
                 if (row.ContainsKey(col)) val = row[col].ToString();
                 line += mid + Escape(val);
                 mid = ";";
             }
             o.WriteLine(line);
         }
         o.Flush();
         o.Close();
     }
 }
Пример #20
0
        /// <summary>
        /// Creates a new empty Lua script in the specified project, in the specified folder.
        /// </summary>
        /// <param name="data">The solution creation data, usually derived from the user's input in a NewSolutionForm.</param>
        /// <returns>A new solution that can be loaded.</returns>
        public override Moai.Platform.Management.File Create(string name, Project project, Folder folder)
        {
            File f = null;

            // Determine where to place the file.
            if (folder == null)
            {
                // Place the file in the root of the project
                f = new File(project, project.ProjectInfo.DirectoryName, name);
                project.AddFile(f);
            }
            else
            {
                // Place the file in the specified folder
                f = new File(project, project.ProjectInfo.DirectoryName, System.IO.Path.Combine(folder.FolderInfo.Name, name));
                folder.Add(f);
            }

            // Write the contents of the data into the file.
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(f.FileInfo.FullName))
            {
                writer.WriteLine("-- An empty script file.");
                writer.WriteLine();
            }

            return f;
        }
Пример #21
0
 private void button1_Click(object sender, EventArgs e)
 {
     System.IO.StreamWriter sw = new System.IO.StreamWriter("nastr.txt");
     sw.WriteLine(textBox1.Text);
     sw.WriteLine(textBox2.Text);
     sw.Close();
 }
Пример #22
0
        static void Main(string[] args)
        {
            Console.WriteLine("Лабораторная работа по численным методам №3. Метод простой итерации");
            Console.WriteLine("Задача №3.11: sin(x+1)-y=1; 2*x+cos(y)=2");

            double epsilon = 0.0001, x0 = 5, y, x;
            Console.WriteLine("Поиск корней на промежутке Xn < {0}", x0);

            x = x0;
            while (true)
            {
                y = f1(x);
                x0 = x;
                x = f2(y);
                Console.WriteLine("Значение Xn: {0}", x0);
                Console.WriteLine("Значение Xn+1: {0}", x);
                Console.WriteLine("Значение Yn: {0}", y);
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\WriteLines2.txt", true))
                {
                    file.WriteLine("Значение Xn: {0}", x0);
                    file.WriteLine("Значение Xn+1: {0}", x);
                    file.WriteLine("Значение Yn: {0}", y);
                }
                if(Math.Abs(x-x0)<=epsilon) break;

            }
            Console.WriteLine("Корень найден, X={0}, Y={2}, точность - {1}", x, epsilon,y);
        }
    private void yesButton_Click(object sender, EventArgs e)
    {
      using (SaveFileDialog save = new SaveFileDialog())
      {
        save.DefaultExt = "sql";
        save.OverwritePrompt = true;
        save.Filter = "SQL Script Files (*.sql)|*.sql|All Files (*.*)|*.*";
        save.FileName = String.Format(CultureInfo.InvariantCulture, "{0}.sql", _tableName);
        save.Title = "Save SQLite Change Script";

        DialogResult = save.ShowDialog(this);

        if (DialogResult == DialogResult.OK)
        {
          _defaultSave = _saveOrig.Checked;

          using (System.IO.StreamWriter writer = new System.IO.StreamWriter(save.FileName, false, Encoding.UTF8))
          {
            if ((_show.Visible == true && _saveOrig.Checked == true) || (_show.Visible == false && _splitter.Panel2Collapsed == true))
            {
              if (_show.Visible == true) writer.WriteLine("/*");
              writer.WriteLine(_original.Text.Replace("\r", "").TrimEnd('\n').Replace("\n", "\r\n"));
              if (_show.Visible == true) writer.WriteLine("*/");
            }
            if (_show.Visible == true || _splitter.Panel2Collapsed == false) 
              writer.WriteLine(_script.Text.Replace("\r", "").TrimEnd('\n').Replace("\n", "\r\n"));
          }
        }
      }
      Close();
    }
        private void btnExport_Click(object sender, EventArgs e)
        {
            SaveFileDialog svD = new SaveFileDialog();
            svD.Filter = "CSV|*.csv";
            svD.AddExtension = true;
            svD.Title = "Export Data To";
            if (svD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                using (System.IO.StreamWriter wr = new System.IO.StreamWriter(svD.FileName))
                {
                    wr.WriteLine("Series,XValues,YValues");
                    for (int i = 0; i < chrHistogram.Series.Count; i++)
                    {
                        System.Windows.Forms.DataVisualization.Charting.Series chS = chrHistogram.Series[i];
                        string sName = chS.Name;
                        for (int j = 0; j < chS.Points.Count; j++)
                        {
                            System.Windows.Forms.DataVisualization.Charting.DataPoint chDp = chS.Points[j];
                            string xVl = chDp.XValue.ToString();
                            string[] yVlArr = (from double d in chDp.YValues select d.ToString()).ToArray();
                            string yVl = String.Join(";", yVlArr);
                            string ln = sName + "," + xVl + "," + yVl;
                            wr.WriteLine(ln);
                        }

                    }
                    wr.Close();
                }
            }
            MessageBox.Show("Finished writing data");
        }
Пример #25
0
 public void save()
 {
     System.IO.StreamWriter m_stwSave = new System.IO.StreamWriter(".\\CCDate.dat", false);
     m_stwSave.WriteLine(strCCKey);
     m_stwSave.WriteLine(strSaveKey);
     m_stwSave.Close();
 }
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            RadioButton rbFullScreen = UIHelpers.FindChild<RadioButton>(this, "rbFullScreen");

            if (rbFullScreen.IsChecked.Value)
            {
                Settings.GetInstance().Mode = Settings.ScreenMode.Fullscreen;
                PageNavigator.MainWindow.WindowStyle = WindowStyle.None;
                PageNavigator.MainWindow.WindowState = WindowState.Maximized;
                PageNavigator.MainWindow.Focus();
            }
            else
            {
                Settings.GetInstance().Mode = Settings.ScreenMode.Windowed;
            }

            ComboBox cbLanguage = UIHelpers.FindChild<ComboBox>(this, "cbLanguage");
            AppSettings.GetInstance().setLanguage((Language)cbLanguage.SelectedItem);

            System.IO.StreamWriter file = new System.IO.StreamWriter(AppSettings.getCommonApplicationDataPath() + "\\game.settings");
            file.WriteLine(AppSettings.GetInstance().getLanguage().Name);
            file.WriteLine(Settings.GetInstance().Mode);
            file.Close();

            //PageNavigator.NavigateTo(new PageStartMenu());
        }
Пример #27
0
        public static void UpdateCache(string folderPath, Dictionary<string, PMetaData> data)
        {
            if(data.Count > 0) 
            {
                System.IO.FileInfo info;
                if (System.IO.File.Exists(folderPath + @"\" + PICASA_FILE))
                {
                    info = new System.IO.FileInfo(folderPath + @"\" +PICASA_FILE);
                    info.Attributes = System.IO.FileAttributes.Normal;
                }

                using (System.IO.StreamWriter writer = new System.IO.StreamWriter(folderPath + @"\" + PICASA_FILE))
                {
                    foreach (var item in data)
                    {
                        if (item.Value.Keywords.Count > 0 || item.Value.RawData.Count > 0)
                        {
                            writer.WriteLine(string.Format("[{0}]", System.IO.Path.GetFileName(item.Key)));                            
                            string tags = string.Join(",", item.Value.Keywords.ToArray());

                            writer.WriteLine(string.Format("keywords={0}", tags));

                            foreach (var raw in item.Value.RawData)
                                writer.WriteLine(string.Format("{0}={1}", raw.Key, raw.Value));
                        }
                    }
                }
                info = new System.IO.FileInfo(folderPath + @"\" + PICASA_FILE);
                info.Attributes = System.IO.FileAttributes.Hidden;
            }
        }
Пример #28
0
        public void logPoints(Shape currentShape, bool success, int curSet, int curSeq, int shapeInd)
        {
            // Append new text to an existing file.
            // The using statement automatically flushes AND CLOSES the stream and calls
            // IDisposable.Dispose on the stream object.
            Console.WriteLine("Logging points...");

            using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileName, true))
            {
                file.WriteLine("Intended Shape: {0}", currentShape.name);
                if (success)
                {
                    file.WriteLine("Success");
                }
                else
                {
                    file.WriteLine("Failure");
                }
                file.WriteLine(points.Count);
                for (int i = 0; i < points.Count; i++)
                {
                    file.WriteLine("{0},{1},{2},{3},{4},{5},{6},{7},{8}", i, points[i].X, points[i].Y, points[i].stroke, points[i].time, points[i].pressure,curSet,curSeq,shapeInd);
                }
            }
            Console.WriteLine("Done logging points.");
        }
Пример #29
0
 private void WriteLog (Exception e)
 {
     var ws = new System.IO.StreamWriter("error.log",true );
     ws.WriteLine(e);
     ws.WriteLine("");
     ws.Close();
 }
        public static void FlowStatics()
        {
            System.IO.StreamWriter sw = new System.IO.StreamWriter("log.txt", false);
            DataClasses1DataContext mydb = new DataClasses1DataContext(common.connString);
            var message = mydb.LA_update1.Select(e => e.ip_version_MsgType).Distinct();
            Dictionary<string, int> myDic = new Dictionary<string, int>();
            foreach (string m in message)
            {
                myDic.Add(m, 0);
                Console.Write(m + "--------------------");
                Console.WriteLine(0);

                sw.Write(m + "--------------------");
                sw.WriteLine(0);

            }
            sw.Flush();

            List<string> startmessage = new List<string>();
            startmessage.Add("DTAP MM.Location Updating Request");
            startmessage.Add("DTAP MM.CM Service Request");
            startmessage.Add("DTAP RR.Paging Response");
            startmessage.Add("BSSMAP.Handover Request");


            foreach (var start in startmessage)
            {
                Dictionary<string, int> newDic = new Dictionary<string, int>();
                foreach (KeyValuePair<string, int> pair in myDic)
                    newDic.Add(pair.Key, 0);

                var a = from p in mydb.LA_update1
                        where p.ip_version_MsgType == start
                        select p.opcdpcsccp;

                foreach (var b in a)
                {
                    foreach (KeyValuePair<string, int> kvp in myDic)
                    {
                        var c = mydb.LA_update1.Where(e => e.opcdpcsccp == b).Where(e => e.ip_version_MsgType == kvp.Key).FirstOrDefault();
                        if (c != null)
                            newDic[kvp.Key] = newDic[kvp.Key] + 1;
                    }
                }

                foreach (var m in newDic.OrderByDescending(e => e.Value))
                {
                    Console.Write(m.Key+"--------------------");
                    Console.WriteLine(m.Value);

                    sw.Write(m.Key + "--------------------");
                    sw.WriteLine(m.Value);
                }

                sw.Flush();
                
            }
            sw.Close();
        }
Пример #31
0
 public void WriteLine(string line)
 {
     lock (s_lock)
     {
         _logFile?.WriteLine(line);
         _logFile?.Flush();
         LogCallback?.Invoke(line);
     }
 }
Пример #32
0
        public string GetMessageFromKey(string message)
        {
            string resourceMessage = _manager != null && message != null?_manager.GetString(message, _resourceCulture) : string.Empty;

            if (string.IsNullOrEmpty(resourceMessage))
            {
                _streamWriter?.WriteLine(message);
                return($"#<{message}>");
            }

            return(resourceMessage);
        }
Пример #33
0
        void OnDisable()
        {
            if (Application.isPlaying)
            {
                Application.logMessageReceived -= HandleLog;
            }
            switch (fileType)
            {
            case FileType.JSON:
                fileWriter?.WriteLine("\n]");
                break;

            case FileType.CSV:
            case FileType.TSV:
            default:
                break;
            }

            fileWriter?.Close();
        }
Пример #34
0
        private void buttonSaveLog_Click(object sender, EventArgs e)
        {
#if LOGGING_ON
            if (LogData == null || LogData.Count == 0)
            {
                return;
            }

            string name = "";

            ClientCommonAPI.LoggingType[] lt = (LoggingType0 < LoggingType1) ?
                                               new ClientCommonAPI.LoggingType[2] {
                LoggingType0, LoggingType1
            } :
            new ClientCommonAPI.LoggingType[2] {
                LoggingType1, LoggingType0
            };
            string[] posName = new string[2] {
                "", ""
            };
            double[] factor = new double[2] {
                1.0, 1.0
            };
            for (int i = 0; i < 2; ++i)
            {
                switch (lt[i])
                {
                default: name += "UNKN_"; posName[i] = ""; break;

                case ClientCommonAPI.LoggingType.M_POS: name += "MPOS_"; posName[i] = "MPOS"; break;

                case ClientCommonAPI.LoggingType.M_LOG: name += "MLOG_"; posName[i] = "MLOG"; break;

                case ClientCommonAPI.LoggingType.M_SPD: name += "MSPD_"; posName[i] = "MSPD(u/s)"; factor[i] = 1000.0 / MSPEED_SCALE; break;

                case ClientCommonAPI.LoggingType.M_ERR: name += "MERR_"; posName[i] = "MERR"; break;

                case ClientCommonAPI.LoggingType.A_POS: name += "APOS_"; posName[i] = "APOS"; break;

                case ClientCommonAPI.LoggingType.A_LOG: name += "ALOG_"; posName[i] = "ALOG"; break;

                case ClientCommonAPI.LoggingType.A_SPD: name += "ASPD_"; posName[i] = "ASPD(u/s)"; factor[i] = 1000.0 / ASPEED_SCALE; break;

                case ClientCommonAPI.LoggingType.A_ERR: name += "AERR_"; posName[i] = "AERR"; break;
                }
            }
            if (LoggingChannel == ClientCommonAPI.LoggingChannel.AZM)
            {
                name += "Client_AZM_";
            }
            else
            {
                name += "Client_ALT_";
            }
            string header = "Time(s)," + posName[0] + ",diff0,," + posName[1] + ",diff1";

            SaveFileDialog savefile = new SaveFileDialog();
            DateTime       dt       = DateTime.Now;
            savefile.FileName = String.Format("{6}{0}-{1}-{2}_{3}-{4}-{5}.csv",
                                              dt.Year.ToString("D4"), dt.Month.ToString("D2"), dt.Day.ToString("D2"), dt.Hour.ToString("D2"), dt.Minute.ToString("D2"), dt.Second.ToString("D2"), name);
            savefile.Filter = "CSV files (*.csv)|*.csv|All files (*.*)|*.*";

            try
            {
                DialogResult res = savefile.ShowDialog();
                if (res != DialogResult.OK)
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

            try
            {
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(savefile.FileName))
                {
                    sw.WriteLine(header);
                    double   startTs = (double)LogData[0] / 1000.0;
                    double[] prev    = new double[2] {
                        0.0, 0.0
                    };
                    for (int i = 0; i < LogData.Count; i += 3)
                    {
                        string s = ((double)LogData[i] / 1000.0 - startTs).ToString("F3");
                        double x = LogData[i + 1] * factor[0];
                        s      += "," + x.ToString();
                        s      += "," + (i == 0 ? 0 : x - prev[0]).ToString("F3");
                        prev[0] = x;

                        s += ",";

                        x       = LogData[i + 2] * factor[1];
                        s      += "," + x.ToString();
                        s      += "," + (i == 0 ? 0 : x - prev[1]).ToString("F3");
                        prev[1] = x;

                        sw.WriteLine(s);
                    }
                }
                LogData = new List <int>();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
#endif
        }
Пример #35
0
        // 정리된 데이터 분석 및 통계 처리
        void DataParse()
        {
            lock ( thread )
            {
                System.Threading.Thread.Sleep(100);

                string [] dirs = new string[Form2.parselist.Count];
                int       i    = 0;

                foreach (System.Collections.DictionaryEntry d in Form2.parselist)
                {
                    dirs[i] = "HackUser\\" + d.Key;
                    i++;
                }


                //string [] dirs = System.IO.Directory.GetDirectories("HackUser\\","*");
                foreach (string dir in dirs)
                {
                    //string []str = Form1.FolderPath.Split('\\');
                    string [] str     = dir.Split('\\');
                    string    version = str[str.Length - 1];

                    string [] dirs2 = System.IO.Directory.GetDirectories(dir, "*");


                    progressBar1.Maximum = dirs2.Length;
                    progressBar1.Minimum = 0;
                    progressBar1.Value   = 0;


                    foreach (string dir2 in dirs2)
                    {
                        label3.Text = dir2 + "\\dmp.html";

                        // 1. 덤프 로그 분석
                        ParsDmpLog(dir2 + "\\dmp.html");
                        progressBar1.Value++;
                    }

                    int nFindHack = 0;
                    System.IO.StreamWriter writer = new System.IO.StreamWriter("report\\" + version + "_dmp.html");
                    writer.WriteLine("<body link=darkgreen vlink=lightgreen><font size=2><p> <b> Total {0} HackUser files</b>", dirs2.Length);

                    System.Collections.ArrayList fileList = new ArrayList();
                    fileList.Clear();

                    while (dmp.Count != 0)
                    {
                        int    max = 0;
                        string key = "";

                        foreach (System.Collections.DictionaryEntry d in dmp)
                        {
                            if (((ArrayList)d.Value).Count > max)
                            {
                                key = (string)d.Key;
                                max = (int)((ArrayList)d.Value).Count;
                            }
                        }

                        writer.WriteLine("</p><p> <font size=3>");

                        foreach (string filename in (ArrayList)dmp[key])
                        {
                            bool bFindHack = CheckHackList(System.Windows.Forms.Application.StartupPath + "\\" + filename);

                            if (bFindHack)
                            {
                                writer.WriteLine("[<a href='..\\" + filename + "'>" + filename.Split('\\')[2] + "</a>] <font size=2 color=red>Find Hack!!</font>");
                                ++nFindHack;
                            }
                            else
                            {
                                writer.WriteLine("[<a href='..\\" + filename + "'>" + filename.Split('\\')[2] + "</a>]");
                            }

                            System.IO.StreamReader reader = new System.IO.StreamReader(System.Windows.Forms.Application.StartupPath + "\\" + filename, System.Text.Encoding.Default);

                            fileList.Add(reader);
                        }
                        writer.WriteLine("</font>");

                        dmp.Remove(key);
                    }

                    writer.WriteLine("<body link=darkgreen vlink=lightgreen><font size=2 color = red><p> <b> Find {0} HackUser!</b>", nFindHack);

/*
 *                  System.IO.StreamWriter writerXls = new System.IO.StreamWriter( "report\\"+version+".xls" );
 *                  for(int index=0; i<1024; ++i)
 *                  {
 *                      foreach(System.IO.StreamReader reader in fileList)
 *                      {
 *
 *                          if(reader.Peek() > 0)
 *                          {
 *                              string strData = reader.ReadLine();
 *
 *                              if(strData.Equals("") == true)
 *                                  writerXls.Write( "\t" );
 *                              else
 *                              {
 *
 *                                  strData = strData.Replace("<body link=darkgreen vlink=lightgreen><font size=4></font><font size=3><pre>","");
 *                                  strData = strData.Replace("</pre>", "");
 *
 *                                  if(strData.IndexOf("color=red") >= 0)
 *                                  {
 *                                      strData = strData.Replace("<font size=2 color=black>","");
 *                                      strData = strData.Replace("<font size=2 color=red>","");
 *                                      strData = strData.Replace("</font>", "");
 *                                      strData = "<body link=darkgreen vlink=lightgreen><font size=4></font><font size=3><pre><font size=2 color=red>" + strData + "</font></pre></body>";
 *                                  }
 *                                  else
 *                                  {
 *                                      strData = strData.Replace("<font size=2 color=black>","");
 *                                      strData = strData.Replace("<font size=2 color=red>","");
 *                                      strData = strData.Replace("</font>", "");
 *                                  }
 *
 *                                  writerXls.Write( strData + "\t" );
 *                              }
 *                          }
 *                      }
 *                      writerXls.Write("\r\n");
 *                  }
 *                  writerXls.Close();
 *
 *
 *                  foreach(System.IO.StreamReader reader in fileList)
 *                  {
 *                      reader.Close();
 *                  }
 */
                    writer.Close();
                }
                thread = null;
            }
            this.Close();
        }
Пример #36
0
        private void CalculatePositions()
        {
            using (System.IO.StreamWriter filein =
                       new System.IO.StreamWriter(Globals.MapOutputTotalDir + "map\\positions.txt", false, Encoding.GetEncoding(1252)))
            {
                foreach (var provinceDetailse in provinces)
                {
                    Point min = provinceDetailse.min;
                    Point max = provinceDetailse.max;
                    Point c   = new Point(max.X - min.X, max.Y - min.Y);
                    min.X += c.X / 3;
                    min.Y += c.Y / 3;
                    max.X -= c.X / 3;
                    max.Y -= c.Y / 3;
                    Rectangle rect   = new Rectangle(min.X, min.Y, max.X - min.X, max.Y - min.Y);
                    var       centre = provinceDetailse.points.Where(p => rect.Contains(p)).ToList();
                    if (centre.Count == 0)
                    {
                        centre.AddRange(provinceDetailse.points);
                    }
                    var town        = centre.OrderBy(p => Rand.Next(10000000)).First();
                    var army        = centre.OrderBy(p => Rand.Next(10000000)).First();
                    var councillers = centre.OrderBy(p => Rand.Next(10000000)).First();
                    var ports       = provinceDetailse.coast.OrderBy(p => Rand.Next(10000000));
                    var port        = town;
                    if (ports.Count() > 0)
                    {
                        port = ports.OrderBy(p => Rand.Next(10000000)).First();
                    }
                    var text = centre.OrderBy(p => Rand.Next(10000000)).First();
                    //provinceDetailse.points.Remove(provinceDetailse.border);

                    town.Y        = Bitmap.Height - town.Y - 1;
                    army.Y        = Bitmap.Height - army.Y - 1;
                    councillers.Y = Bitmap.Height - councillers.Y - 1;
                    port.Y        = Bitmap.Height - port.Y - 1;
                    text.Y        = Bitmap.Height - text.Y - 1;

                    filein.WriteLine(provinceDetailse.ID + "=");
                    filein.WriteLine("{");
                    filein.WriteLine("position=");
                    filein.WriteLine("{");
                    filein.WriteLine(town.X + ".000 " + town.Y + ".000 " + army.X + ".000 " + army.Y + ".000 " + councillers.X + ".000 " + councillers.Y + ".000 " + text.X + ".000 " + text.Y + ".000 " + port.X + ".000 " + port.Y + ".000");
                    filein.WriteLine("}");
                    filein.WriteLine("rotation=");
                    filein.WriteLine("{");
                    filein.WriteLine("0.000 0.000 0.000 0.000 0.000");
                    filein.WriteLine("}");
                    filein.WriteLine("height=");
                    filein.WriteLine("{");
                    filein.WriteLine("0.000 0.000 0.000 20.000 0.000");
                    filein.WriteLine("}");
                    filein.WriteLine("}");
                }
            }
        }
Пример #37
0
        public static async Task Run([TimerTrigger("%CronTimerInterval%")] TimerInfo myTimer, ILogger log)
        {
            InitializeFunctionParameters();

            System.IO.MemoryStream ms     = new System.IO.MemoryStream();
            System.IO.StreamWriter writer = new System.IO.StreamWriter(ms);

            log.LogInformation("Retrieving secrets from keyvault");

            await RetrieveSecretsAsync();

            log.LogInformation("Checking if alert condition is met");
            using (NpgsqlConnection conn = new NpgsqlConnection(connectionString))
            {
                log.LogInformation("Opening connection");
                conn.Open();

                using (NpgsqlCommand cmd = new NpgsqlCommand(alertCondition, conn))
                {
                    var result = await cmd.ExecuteReaderAsync();

                    if (!result.HasRows)
                    {
                        log.LogInformation("Alert condition is not met");
                        return;
                    }
                    log.LogInformation("Alert condition is met");

                    writer.WriteLine($"Alert condition is met for : {alertCondition}\n");

                    writer.WriteLine(BuildStringFromStream(result));
                }
            }

            foreach (var qry in supportingDataQueries)
            {
                //need to dispose the connection for each query. Otherwise, we get "an operation is already in progress error"
                using (NpgsqlConnection conn = new NpgsqlConnection(connectionString))
                {
                    log.LogInformation("Opening connection");
                    conn.Open();

                    using (NpgsqlCommand cmd = new NpgsqlCommand(qry.Value, conn))
                    {
                        // Execute the command and log the # rows affected.
                        var rows = await cmd.ExecuteReaderAsync();

                        if (rows.HasRows)
                        {
                            log.LogInformation($"Reading {qry.Key}");
                            writer.WriteLine("============================================================================================\n");
                            writer.WriteLine($"Begin: {qry.Key}\n");
                            writer.WriteLine(BuildStringFromStream(rows));
                            writer.WriteLine($"End: {qry.Key}\n");
                            writer.WriteLine("============================================================================================\n");

                            log.LogInformation($"Processed: {qry.Key}");
                        }
                    }
                }
            }

            writer.Flush();
            ms.Position = 0;

            log.LogInformation("Sending mail");
            SendMail(mailTo, ms);

            writer.Dispose();
            ms.Close();
        }
Пример #38
0
        public static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
            List <Citizen> Citis            = new List <Citizen>();
            List <Scooter> Scoots           = new List <Scooter>();
            int            numberOfCitizens = 10;
            int            numberOfScooters = 20;
            double         ScoVelocity      = 0.0076;
            double         CitVelocity      = 0.001559;

            //area of interest, rad.10km, square
            city.max_x = 0.08983 * 10 + city.lng;
            city.min_x = city.lng - 0.08983 * 10;
            city.max_y = 0.08983 * 10 + city.lati;
            city.min_y = city.lati - 0.08983 * 10;
            //1degree=111.196672km
            //10km=0.08983degree
            //creating 10 citizens
            Random rand = new Random();

            //initialising citizens
            for (int i = 0; i < 10; i++)
            {
                Citizen Cit = new Citizen();
                Cit.pos_x = rand.NextDouble() * (city.max_x - city.min_x) + city.min_x;
                //Citis[i] = new Citizen();

                Cit.pos_y = rand.NextDouble() * (city.max_y - city.min_y) + city.min_y;

                Cit.dest_x = rand.NextDouble() * (city.max_x - city.min_x) + city.min_x;

                Cit.dest_y     = rand.NextDouble() * (city.max_y - city.min_y) + city.min_y;
                Cit.status     = "walking";
                Cit.timeToWait = 0;
                Cit.velocity   = CitVelocity;//10m jump per iteration
                Cit.stepInd    = 0;
                Citis.Add(Cit);

                //Citis.Insert(1, Cit);
            }
            //initialising scooters
            for (int i = 0; i < 20; i++)
            {
                Scooter Sco = new Scooter();
                Sco.pos_x = rand.NextDouble() * (city.max_x - city.min_x) + city.min_x;

                Sco.pos_y    = rand.NextDouble() * (city.max_y - city.min_y) + city.min_y;
                Sco.idle     = true;
                Sco.velocity = 0;
                Scoots.Add(Sco);
            }
            string Orig;
            string dest;
            double ScootsDist      = 90000000000000;
            int    closestScootInd = 55;
            string export;
            var    g = new Coding();

            //!!!!!!!!!!!!paste your own Google Api Key here:
            g.Key = "";
            System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\ositions1.txt");

            //while (true)
            for (int kj = 0; kj < 5000; kj++)
            {
                for (int i = 0; i < numberOfCitizens; i++)
                {
                    if (Citis[i].timeToWait == 0)
                    {
                        Orig = Convert.ToString(Citis[i].pos_x) + "," + Convert.ToString(Citis[i].pos_y);

                        //finding closest scooter
                        if (Citis[i].status == "walking")
                        {
                            //1st case scenario
                            //finding route
                            if (Citis[i].stepsToDir == null)
                            {
                                Citis[i].stepInd = 0;
                                closestScootInd  = 0;
                                for (int j = 0; j < numberOfScooters; j++)
                                {
                                    if (Scoots[j].idle && (Math.Pow(Citis[i].pos_x - Scoots[j].pos_x, 2) + Math.Pow(Citis[i].pos_y - Scoots[j].pos_y, 2) < ScootsDist))
                                    {
                                        closestScootInd = j;
                                    }

                                    ScootsDist = (Math.Pow(Citis[i].pos_x - Scoots[j].pos_x, 2) + Math.Pow(Citis[i].pos_y - Scoots[j].pos_y, 2));
                                }
                                Citis[i].CitsScooter = closestScootInd;

                                dest = Convert.ToString(Scoots[Citis[i].CitsScooter].pos_x) + "," + Convert.ToString(Scoots[Citis[i].CitsScooter].pos_y);
                                var r_cit = g.DirInfo(new DirParameters {
                                    Origin = Orig, Destination = dest, Mode = Citis[i].status, Units = "metric", Avoid = "highways"
                                });

                                Citis[i].stepCount  = r_cit.routes[0].Legs[0].Steps.Length;
                                Citis[i].stepsToDir = new Location[Citis[i].stepCount];

                                for (int j1 = 0; j1 < r_cit.routes[0].Legs[0].Steps.Length; j1++)
                                {
                                    Citis[i].stepsToDir[j1] = r_cit.routes[0].Legs[0].Steps[j1].EndLocation;
                                }
                                //making 1st step
                                Citis[i].movCit();
                                //if 1st step made:
                                if (Math.Abs(Citis[i].pos_x - Citis[i].stepsToDir[0].Lat) < 0.00001 && Math.Abs(Citis[i].pos_y - Citis[i].stepsToDir[0].Long) < 0.00001)
                                {
                                    Citis[i].stepInd = 1;
                                }
                            }
                            //2nd,3rd and 4th cases scenarios
                            //if route known
                            else
                            {
                                //if at dest (scoot's pos)
                                if (Citis[i].stepInd >= Citis[i].stepCount)
                                {
                                    //4th case scenario
                                    if (Scoots[Citis[i].CitsScooter].idle)
                                    {
                                        //start a scooter
                                        Citis[i].drive(ScoVelocity);
                                        Scoots[Citis[i].CitsScooter].idle = false;
                                    }
                                    //3rd case scenario
                                    //find another scooter
                                    else
                                    {
                                        Citis[i].stepsToDir = null;
                                    }
                                }
                                //2nd case scenario
                                else
                                {
                                    Citis[i].movCit();
                                    //if step done:
                                    if (Math.Abs(Citis[i].pos_x - Citis[i].stepsToDir[Citis[i].stepInd].Lat) < 0.0001 && Math.Abs(Citis[i].pos_y - Citis[i].stepsToDir[Citis[i].stepInd].Long) < 0.0001)
                                    {
                                        Citis[i].stepInd++;
                                    }
                                }
                            }
                        }
                        //when driving
                        if (Citis[i].status == "driving")
                        {
                            //5th case scenario
                            if (Citis[i].stepsToDir == null)
                            {
                                dest = Convert.ToString(Citis[i].dest_x) + "," + Convert.ToString(Citis[i].dest_y);
                                var r_scoot = g.DirInfo(new DirParameters {
                                    Origin = Orig, Destination = dest, Mode = Citis[i].status, Units = "metric", Avoid = "highways"
                                });
                                Citis[i].stepCount  = r_scoot.routes[0].Legs[0].Steps.Length;
                                Citis[i].stepsToDir = new Location[Citis[i].stepCount];
                                for (int j1 = 0; j1 < r_scoot.routes[0].Legs[0].Steps.Length; j1++)
                                {
                                    Citis[i].stepsToDir[j1] = r_scoot.routes[0].Legs[0].Steps[j1].EndLocation;
                                }
                                //making 1st step
                                Citis[i].stepInd = 0;
                                Citis[i].movCit();
                                Scoots[Citis[i].CitsScooter].MovScoot(Citis[i].pos_x, Citis[i].pos_y);
                                //if 1st step made:
                                if (Math.Abs(Citis[i].pos_x - Citis[i].stepsToDir[0].Lat) < 0.00001 && Math.Abs(Citis[i].pos_y - Citis[i].stepsToDir[0].Long) < 0.00001)
                                {
                                    Citis[i].stepInd = 1;
                                }
                            }
                            //6th and 7th case scenarios
                            else
                            {
                                //7th case scenario
                                if (Citis[i].stepInd == Citis[i].stepCount)
                                {
                                    Scoots[Citis[i].CitsScooter].idle = true;
                                    Citis[i].pos_x = Citis[i].dest_x;
                                    Citis[i].pos_y = Citis[i].dest_y;
                                    Citis[i].arrived(rand, CitVelocity);
                                }
                                //6th case scenario
                                else
                                {
                                    Citis[i].movCit();
                                    Scoots[Citis[i].CitsScooter].MovScoot(Citis[i].pos_x, Citis[i].pos_y);


                                    //if step done:
                                    if (Math.Abs(Citis[i].pos_x - Citis[i].stepsToDir[Citis[i].stepInd].Lat) < 0.0001 && Math.Abs(Citis[i].pos_y - Citis[i].stepsToDir[Citis[i].stepInd].Long) < 0.0001)
                                    {
                                        Citis[i].stepInd++;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        Citis[i].timeToWait = Citis[i].timeToWait - 1;
                    }
                    export = i + ".  " + Citis[i].pos_x + ", " + Citis[i].pos_y + ", " + Citis[i].stepInd + "  " + Citis[i].status + "  " + Citis[i].CitsScooter + "\n";

                    file.WriteLine(export);
                }
            }
            file.Close();
        }
Пример #39
0
        static public void SupportControlAgk()
        {
            var ListAgk = Site.GetAllAGK();

            try
            {
                DateTime dateEnd = DateTime.Now;
                DateTime dateBgn = dateEnd.AddDays(-7);

                var theHydro = new HydroService.HydroServiceClient();
                // 2 - ГП
                // 6 - АГК


                foreach (var site in ListAgk)
                {
                    try
                    {
                        System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\HydroDataCenterAgkControl\\" + site.Code.ToString() + "-" + site.Name.Replace("/", "-") + ".txt");

                        string line = site.Name;

                        file.WriteLine(line);

                        var ListResultAgk = theHydro.GetDataValues(site.ExtID, dateBgn, dateEnd, 2, null, null, null);

                        var theHydroPost        = Site.GetByCode(Convert.ToInt32(site.Code), 2 /*ГП*/);
                        var ListResultHydroPost = theHydro.GetDataValues(theHydroPost.ExtID, dateBgn, dateEnd, 2, null, null, null);

                        int CountValue          = 0;
                        int SummaControlProcent = 0;

                        foreach (var value_hydropost in ListResultHydroPost)
                        {
                            #region stat
                            if (value_hydropost.Date.Hour == 8 || value_hydropost.Date.Hour == 20)
                            {
                                line  = value_hydropost.Date.ToString();
                                line += "\t";
                                line += value_hydropost.Value.ToString();

                                string agk_value = "";
                                if (ListResultAgk == null)
                                {
                                    agk_value = "AGK not found";

                                    line += "\t";
                                    line += agk_value;
                                    file.WriteLine(line);
                                    continue;
                                }
                                var value_agk_list = ListResultAgk.Where(x => x.Date.Year == value_hydropost.Date.Year && x.Date.Month == value_hydropost.Date.Month && x.Date.Day == value_hydropost.Date.Day && x.Date.Hour == value_hydropost.Date.Hour).ToList();

                                if (value_agk_list == null || value_agk_list.Count() == 0)
                                {
                                    agk_value = "AGK not data";

                                    line += "\t";
                                    line += agk_value;
                                    file.WriteLine(line);
                                    continue;
                                }

                                var value_agk = value_agk_list.Last();


                                agk_value = value_agk.Value.ToString();

                                if (value_agk != null)
                                {
                                    CountValue++;
                                    float value_control = Math.Abs(value_hydropost.Value - value_agk.Value);
                                    int   coeff         = 0;
                                    if (value_control < 1)
                                    {
                                        coeff = 100;
                                        SummaControlProcent += coeff;
                                    }
                                    else
                                    {
                                        if (value_control < 3)
                                        {
                                            coeff = 75;
                                            SummaControlProcent += coeff;
                                        }
                                        else
                                        if (value_control < 4)
                                        {
                                            coeff = 50;
                                            SummaControlProcent += coeff;
                                        }
                                        else
                                        {
                                            coeff = 0;
                                            SummaControlProcent += coeff;
                                        }
                                    }


                                    line += "\t";
                                    line += agk_value;

                                    line += "\t";
                                    line += value_control.ToString();

                                    line += "\t";
                                    line += coeff.ToString();
                                    file.WriteLine(line);
                                }
                            }
                            #endregion
                        }



                        if (CountValue == 0)
                        {
                            continue;
                        }

                        site.ControlProcent = SummaControlProcent / CountValue;

                        site.Update();

                        line = site.ControlProcent.ToString();
                        file.WriteLine("{0} / {1} = {2}", SummaControlProcent, CountValue, line);

                        file.Close();
                    }
                    catch
                    {
                        site.ControlProcent = -999;
                    }
                }
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                if (ex.InnerException != null)
                {
                    err += "\n\r" + ex.InnerException.Message;
                }
                Console.WriteLine(err);
            }
        }
Пример #40
0
 internal static void  debug(System.String s)
 {
     err.WriteLine(">>> " + NAME + ": " + s);
 }
Пример #41
0
        private void Button_Click_add(object sender, RoutedEventArgs e)
        {
            String        nazwa  = nick.Text;
            String        log    = login.Text;
            String        haslo  = password.Password.ToString();
            String        Phaslo = Cpassword.Password.ToString();
            List <String> lista  = new List <string>();
            String        line;

            String[] words;
            int      flag = 0;

            System.IO.StreamReader file3 = new System.IO.StreamReader("users.txt");
            while ((line = file3.ReadLine()) != null)
            {
                words = line.Split(' ');
                lista.Add(words[0]);
            }
            file3.Close();

            if (nazwa == "" || log == "" || haslo == "" || Phaslo == "")
            {
                MessageBox.Show("Fields cannot be empty", "Dicc - new account create failure");
                password.Clear();
                Cpassword.Clear();
                flag = 1;
            }
            else if ((string.IsNullOrEmpty(nazwa)) || (string.IsNullOrEmpty(log)) || (string.IsNullOrWhiteSpace(haslo)) || (string.IsNullOrWhiteSpace(Phaslo)) || (string.IsNullOrEmpty(haslo)) || (string.IsNullOrEmpty(Phaslo)) || (string.IsNullOrWhiteSpace(nazwa)) || (string.IsNullOrWhiteSpace(log)) || nazwa.Contains(" ") || log.Contains(" ") || haslo.Contains(" ") || Phaslo.Contains(" "))
            {
                MessageBox.Show("Fields cannot contain spaces", "Dicc - new account create failure");
                password.Clear();
                Cpassword.Clear();
                login.Clear();
                nick.Clear();
                flag = 1;
            }
            else if (haslo != Phaslo)
            {
                MessageBox.Show("Password and its confirmation are different", "Dicc - new account create failure");
                password.Clear();
                Cpassword.Clear();
                flag = 2;
            }
            for (int i = 0; i < lista.Count; i++)
            {
                if (lista[i] == log)
                {
                    MessageBox.Show("Login already exists in system", "Dicc - new account create failure");
                    password.Clear();
                    Cpassword.Clear();
                    flag = 3;
                }
            }

            if (flag == 0)
            {
                System.IO.StreamWriter file2 = new System.IO.StreamWriter("users.txt", append: true);
                nazwa = nazwa.Replace("\n", ""); nazwa = nazwa.Replace("\r", ""); nazwa = nazwa.Replace("\t", "");
                log   = log.Replace("\r", "");     log = log.Replace("\n", "");     log = log.Replace("\t", "");
                haslo = haslo.Replace("\t", ""); haslo = haslo.Replace("\r", ""); haslo = haslo.Replace("\n", "");
                file2.WriteLine(log + " " + haslo + " " + nazwa);
                file2.Close();
                System.IO.StreamWriter file = new System.IO.StreamWriter(log + ".txt");
                file.Close();

                Logged x = new Logged(log, nazwa);
                x.Show();
                Window parentWindow = Window.GetWindow(this);
                parentWindow.Close();
            }
        }
Пример #42
0
        public static void GenerateBindingCode(List <Type> types, string outputPath, HashSet <MethodBase> excludes = null)
        {
            if (!System.IO.Directory.Exists(outputPath))
            {
                System.IO.Directory.CreateDirectory(outputPath);
            }
            string[] oldFiles = System.IO.Directory.GetFiles(outputPath, "*.cs");
            foreach (var i in oldFiles)
            {
                System.IO.File.Delete(i);
            }
            List <string> clsNames = new List <string>();

            foreach (var i in types)
            {
                string clsName, realClsName;
                bool   isByRef;
                if (i.GetCustomAttributes(typeof(ObsoleteAttribute), true).Length > 0)
                {
                    continue;
                }
                GetClassName(i, out clsName, out realClsName, out isByRef);
                clsNames.Add(clsName);
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputPath + "/" + clsName + ".cs", false, Encoding.UTF8))
                {
                    sw.Write(@"using System;
using System.Collections.Generic;
using System.Reflection;

using ILRuntime.CLR.TypeSystem;
using ILRuntime.CLR.Method;
using ILRuntime.Runtime.Enviorment;
using ILRuntime.Runtime.Intepreter;
using ILRuntime.Runtime.Stack;
using ILRuntime.Reflection;
using ILRuntime.CLR.Utils;

namespace ILRuntime.Runtime.Generated
{
    unsafe class ");
                    sw.WriteLine(clsName);
                    sw.Write(@"    {
        public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app)
        {
            BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
            MethodBase method;
            Type[] args;
            Type type = typeof(");
                    sw.Write(realClsName);
                    sw.WriteLine(");");
                    MethodInfo[]      methods          = i.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);
                    string            registerCode     = GenerateRegisterCode(i, methods, excludes);
                    string            commonCode       = GenerateCommonCode(i, realClsName);
                    ConstructorInfo[] ctors            = i.GetConstructors(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);
                    string            ctorRegisterCode = GenerateConstructorRegisterCode(i, ctors, excludes);
                    string            wraperCode       = GenerateWraperCode(i, methods, realClsName, excludes);
                    string            ctorWraperCode   = GenerateConstructorWraperCode(i, ctors, realClsName, excludes);
                    sw.WriteLine(registerCode);
                    sw.WriteLine(ctorRegisterCode);
                    sw.WriteLine("        }");
                    sw.WriteLine();
                    sw.WriteLine(commonCode);
                    sw.WriteLine(wraperCode);
                    sw.WriteLine(ctorWraperCode);
                    sw.WriteLine("    }");
                    sw.WriteLine("}");
                    sw.Flush();
                }
            }

            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputPath + "/CLRBindings.cs", false, Encoding.UTF8))
            {
                sw.WriteLine(@"using System;
using System.Collections.Generic;
using System.Reflection;

namespace ILRuntime.Runtime.Generated
{
    class CLRBindings
    {
        /// <summary>
        /// Initialize the CLR binding, please invoke this AFTER CLR Redirection registration
        /// </summary>
        public static void Initialize(ILRuntime.Runtime.Enviorment.AppDomain app)
        {");
                foreach (var i in clsNames)
                {
                    sw.Write("            ");
                    sw.Write(i);
                    sw.WriteLine(".Register(app);");
                }

                sw.WriteLine(@"        }
    }
}");
            }
        }
Пример #43
0
        static void Main(string[] args)
        {
            string filename = "/var/log/secure";

            if (args.Length != 0)
            {
                filename = args[0];
            }


            System.IO.StreamReader   sr        = new System.IO.StreamReader(filename);
            Dictionary <string, int> host_list = new Dictionary <string, int>();
            Dictionary <string, int> user_list = new Dictionary <string, int>();

            string st;

            while ((st = sr.ReadLine()) != null)
            {
                if (st.IndexOf("rhost") > 0)
                {
                    string[] temp = st.Split(' ');
                    foreach (string s in temp)
                    {
                        if (s.IndexOf("ruser") > -1)
                        {
                            string[] split = s.Split('=');
                            // キーの存在チェック
                            if (!user_list.ContainsKey(split[1]))
                            {
                                // 存在しない場合
                                user_list[split[1]] = 1;
                            }
                            else
                            {
                                user_list[split[1]]++;
                            }
                        }
                        if (s.IndexOf("rhost") > -1)
                        {
                            string[] split = s.Split('=');
                            // キーの存在チェック
                            if (!host_list.ContainsKey(split[1]))
                            {
                                // 存在しない場合
                                host_list[split[1]] = 1;
                            }
                            else
                            {
                                host_list[split[1]]++;
                            }
                        }
                    }
                }
            }
            sr.Close();

            System.IO.StreamWriter sw = new System.IO.StreamWriter("host_list.txt");

            foreach (KeyValuePair <string, int> kvp in host_list)
            {
                Console.WriteLine("{0} : {1}", kvp.Key, kvp.Value);
                sw.WriteLine("{0} : {1}", kvp.Key, kvp.Value);
            }
            sw.Close();

            sw = new System.IO.StreamWriter("user_list.txt");
            foreach (KeyValuePair <string, int> kvp in user_list)
            {
                Console.WriteLine("{0} : {1}", kvp.Key, kvp.Value);
                sw.WriteLine("{0} : {1}", kvp.Key, kvp.Value);
            }
            sw.Close();
        }
Пример #44
0
 private static void WriteResultsToCSV(List <CustomerModel> customerModels, string state, System.IO.StreamWriter writer)
 {
     customerModels.ToList().ForEach(cm => writer.WriteLine($"{cm.Name},{cm.Email},{cm.Password}, {state}"));
 }
Пример #45
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            //string ss = "Don�tfoovar??"; // "foo�bar"; // "’";
            //string tt = FixEncoding(ss);
            //Console.WriteLine("[" + tt + "]");

            Console.WriteLine("Creating and starting task...");
            //Task t = new Task(DownloadPageAsync);
            //t.Start();
            //Console.WriteLine("Waiting...");
            //t.Wait();

            Console.WriteLine("Creating, starting and waiting...");
            DownloadPageAsync().Wait();

            //Console.WriteLine(pagecontents);

            // Create a new parser front-end (can be re-used)
            var parser = new HtmlParser();

            //Just get the DOM representation
            var document = parser.Parse(pagecontents);

            //var mainSections = document.QuerySelectorAll("section");
            //foreach(var s in mainSections)
            //{
            //    Console.WriteLine("NodeName:\t'" + s.NodeName);
            //    Console.WriteLine("TagName:\t'" + s.TagName);
            //    foreach (var attr in s.Attributes)
            //    {
            //        Console.WriteLine("Attribute:\t'" + attr.Name + "=" + attr.Value);
            //    }
            //}

            //Console.WriteLine("Principle Sections:");
            //foreach (var s in mainSections)
            //{
            //    if (String.IsNullOrEmpty(s.GetAttribute("id")) ? false : s.GetAttribute("id").StartsWith("Principle"))
            //    {
            //        Console.WriteLine("NodeName:\t'" + s.NodeName);
            //        Console.WriteLine("TagName:\t'" + s.TagName);
            //        Console.WriteLine("ClassName:\t'" + s.ClassName);
            //        foreach (var attr in s.Attributes)
            //        {
            //            Console.WriteLine("Attribute:\t'" + attr.Name + "=" + attr.Value);
            //        }
            //    }
            //}

            bool doMakeKeywordPhrases = true;

            bool       haveTopicTitle = false;
            bool       isAfterFirstPrincipleNumber = false;
            bool       isAfterFirstPrincipleTitle  = false;
            string     childPrincipleNumber        = "0"; // to get the initial Publication number correct (and not SNULL)
            string     parentPrincipleNumber       = "0";
            string     topicNumber             = "NULL";
            string     principleNumber         = "NULL";
            string     subprincipleNumber      = "NULL";
            EntityType entityType              = EntityType.Unknown_Principles_RayDalio_ModelMate;
            string     topicText               = "NULL";
            string     sectionPrincipleNumber  = "S0"; // format Snnn
            string     sectionTitle            = "NULL";
            string     principleTitle          = "NULL";
            string     principleText           = "NULL";
            string     principleCommentaryText = "NULL";
            string     principleQuestionText   = "NULL";
            string     principleLetterText     = "NULL";
            string     principleBulletText     = "NULL";
            string     principleNumberText     = "NULL";
            string     principleImageUrl       = "NULL";
            string     principleFigureText     = "NULL";
            int        entityOrder             = 0;

            var principleSections = document.All.Where(m =>
                                                       (m.LocalName == "div" && !String.IsNullOrEmpty(m.ClassName) && m.ClassName.Contains("section__title")) ||
                                                       (m.LocalName == "section" && !String.IsNullOrEmpty(m.ClassName) && m.ClassName == "topic") ||
                                                       (m.LocalName == "div" && !String.IsNullOrEmpty(m.ClassName) && m.ClassName.Contains("topic__number")) ||
                                                       //(m.LocalName == "div" && !String.IsNullOrEmpty(m.ClassName)&& m.ClassName.Contains("topic__title")) ||
                                                       (m.LocalName == "div" && !String.IsNullOrEmpty(m.ClassName) && m.ClassName.Contains("topic__text")) ||
                                                       (m.LocalName == "div" && !String.IsNullOrEmpty(m.ClassName) && m.ClassName == "principle") ||
                                                       (m.LocalName == "span" && !String.IsNullOrEmpty(m.ClassName) && m.ClassName.Contains("principle__number")) ||
                                                       (m.LocalName == "h2" && !String.IsNullOrEmpty(m.ClassName) && m.ClassName.Contains("principle__title")) ||
                                                       (m.LocalName == "div" && !String.IsNullOrEmpty(m.ClassName) && m.ClassName == "subprinciple") ||
                                                       (m.LocalName == "span" && !String.IsNullOrEmpty(m.ClassName) && m.ClassName.Contains("subprinciple__number")) ||
                                                       (m.LocalName == "h3" && !String.IsNullOrEmpty(m.ClassName) && m.ClassName.Contains("subprinciple__title")) ||
                                                       (m.LocalName == "p" && !String.IsNullOrEmpty(m.ClassName) && m.ClassName.Contains("commentary")) ||
                                                       (m.LocalName == "p" && !String.IsNullOrEmpty(m.ClassName) && m.ClassName.Contains("question")) ||
                                                       (m.LocalName == "p" && !String.IsNullOrEmpty(m.ClassName) && m.ClassName.Contains("bullet")) ||
                                                       (m.LocalName == "p" && !String.IsNullOrEmpty(m.ClassName) && m.ClassName.Contains("number")) ||
                                                       (m.LocalName == "p" && !String.IsNullOrEmpty(m.ClassName) && m.ClassName.Contains("letter")) ||
                                                       (m.LocalName == "figure" && !String.IsNullOrEmpty(m.ClassName) && !m.ClassName.Contains("image")) ||
                                                       (m.LocalName == "img")
                                                       );

            List <String> corpus = new List <string>();
            // 0            1                       2                        3           4                5            6        7
            // entityorder, child principle number, parent principle number, entitytype, principle title, contenttype, content, keyphases
            string csvformat = "\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\"";

            using (System.IO.StreamWriter _File = new System.IO.StreamWriter(@"HTMLScanner-RayDalioPrinciples.csv", false, Encoding.UTF8))
            {
                _File.WriteLine(csvformat,
                                "EntityOrder", "ChildPrincipleNumber", "ParentPrincipleNumber", "EntityType", "PrincipleTitle", "ContentType", "Content", "KeyPhrases");
                _File.WriteLine(csvformat,
                                "0", "0", "-1", "Publication_Principles_RayDalio_ModelMate", "PRINCIPLES BY RAY DALIO", "BaseEntity_Principles_RayDalio_ModelMate", "0. PRINCIPLES BY RAY DALIO", "principles,Ray Dalio");

                Console.WriteLine("Principle Sections 2:");
                foreach (var docPart in principleSections)
                {
                    //if (String.IsNullOrEmpty(s.GetAttribute("id")) ? false : s.GetAttribute("id").StartsWith("Principle"))
                    //{
                    Console.WriteLine("LocalName:\t'" + docPart.LocalName + "'");
                    Console.WriteLine("NodeName:\t'" + docPart.NodeName + "'");
                    Console.WriteLine("TagName:\t'" + docPart.TagName + "'");
                    Console.WriteLine("ClassName:\t'" + docPart.ClassName + "'");
                    foreach (var attr in docPart.Attributes)
                    {
                        Console.WriteLine("Attribute:\t'" + attr.Name + "=" + attr.Value + "'");
                    }
                    //}

                    //if (s.LocalName == "figure") System.Diagnostics.Debugger.Break(); // ’


                    if (docPart.ClassName.Contains("section__title"))
                    {
                        parentPrincipleNumber  = "0";
                        childPrincipleNumber   = "S" + childPrincipleNumber.ToString();
                        sectionPrincipleNumber = childPrincipleNumber;

                        sectionTitle = Regex.Replace(FixEncoding(docPart.TextContent), @"\s+", " ").Replace("“", "&quote;").Replace("”", "&quote;").Replace("\"", "&quote;").Trim();
                        entityType   = MapEnitityType("section");
                        corpus.Add(sectionTitle);

                        Console.WriteLine("principleNumber:\t'" + childPrincipleNumber + "' parent:" + parentPrincipleNumber + " entityType: " + entityType.ToString() + " insideSectionTitle: " + haveTopicTitle.ToString());
                        Console.WriteLine("sectionTitle:\t'" + sectionTitle + "'");

                        if (doMakeKeywordPhrases && !String.IsNullOrEmpty(sectionTitle))
                        {
                            List <String> response = new List <string>();
                            response.Add(sectionTitle);
                            string request = AzureTextAnalytics.FormatRequestJSON(response);
                            AzureTextAnalytics.MakeKeyPhrasesRequest(request).Wait();
                        }
                        else
                        {
                            AzureTextAnalytics.Response = "NULL";
                        }
                        string keyphases = AzureTextAnalytics.Response;

                        if (String.IsNullOrEmpty(sectionTitle))
                        {
                            sectionTitle = "NULL";
                        }

                        _File.WriteLine(csvformat,
                                        ++entityOrder, childPrincipleNumber, parentPrincipleNumber, entityType.ToString(), sectionTitle, ContentTypes.BaseEntity_Principles_RayDalio_ModelMate.ToString(), childPrincipleNumber + ". " + sectionTitle, keyphases);

                        parentPrincipleNumber = childPrincipleNumber;
                    }
                    else if (docPart.ClassName.Contains("topic__number"))
                    {
                        childPrincipleNumber        = Regex.Replace(FixEncoding(docPart.TextContent), @"\s+", " ").Replace("“", "&quote;").Replace("”", "&quote;").Replace("\"", "&quote;").Trim();
                        isAfterFirstPrincipleNumber = true;

                        parentPrincipleNumber = sectionPrincipleNumber;
                        topicNumber           = childPrincipleNumber;
                        entityType            = MapEnitityType(docPart.ClassName);
                        corpus.Add(sectionTitle);

                        Console.WriteLine("principleNumber:\t'" + childPrincipleNumber + "' parent:" + parentPrincipleNumber + " entityType: " + entityType.ToString() + " insideSectionTitle: " + haveTopicTitle.ToString());
                        Console.WriteLine("childPrincipleNumber:\t'" + childPrincipleNumber + "'");
                    }
                    else if (docPart.ClassName.Contains("topic__text"))
                    {
                        topicText = Regex.Replace(FixEncoding(docPart.TextContent), @"\s+", " ").Replace("“", "&quote;").Replace("”", "&quote;").Replace("\"", "&quote;").Trim();
                        isAfterFirstPrincipleTitle = true;
                        corpus.Add(topicText);

                        Console.WriteLine("principleNumber:\t'" + childPrincipleNumber + "' parent:" + parentPrincipleNumber + " entityType: " + entityType.ToString() + " insideSectionTitle: " + haveTopicTitle.ToString());
                        Console.WriteLine("topicText:\t'" + topicText + "'");

                        if (doMakeKeywordPhrases && !String.IsNullOrEmpty(topicText))
                        {
                            List <String> response = new List <string>();
                            response.Add(topicText);
                            string request = AzureTextAnalytics.FormatRequestJSON(response);
                            AzureTextAnalytics.MakeKeyPhrasesRequest(request).Wait();
                        }
                        else
                        {
                            AzureTextAnalytics.Response = "NULL";
                        }
                        string keyphases = AzureTextAnalytics.Response;

                        if (String.IsNullOrEmpty(topicText))
                        {
                            topicText = "NULL";
                        }

                        _File.WriteLine(csvformat,
                                        ++entityOrder, childPrincipleNumber, parentPrincipleNumber, entityType.ToString(), topicText, ContentTypes.BaseEntity_Principles_RayDalio_ModelMate.ToString(), childPrincipleNumber + ". " + topicText, keyphases);

                        parentPrincipleNumber = childPrincipleNumber;

                        _File.WriteLine(csvformat,
                                        ++entityOrder, childPrincipleNumber, parentPrincipleNumber, entityType.ToString(), topicText, ContentTypes.TopicText_Principles_RayDalio_ModelMate.ToString(), topicText, keyphases); // link TopicText to BaseEntity

                        parentPrincipleNumber = childPrincipleNumber;
                    }
                    else if (docPart.ClassName.Contains("_number"))
                    {
                        childPrincipleNumber        = Regex.Replace(FixEncoding(docPart.TextContent), @"\s+", " ").Replace("“", "&quote;").Replace("”", "&quote;").Replace("\"", "&quote;").Trim();
                        isAfterFirstPrincipleNumber = true;

                        switch (docPart.ClassName)
                        {
                        case "topic__number":
                        {
                            throw new ArgumentOutOfRangeException("topic__number");         // processed above
                            break;
                        }

                        case "principle__number":
                        {
                            parentPrincipleNumber = topicNumber;         // set above
                            principleNumber       = childPrincipleNumber;
                            entityType            = MapEnitityType(docPart.ClassName);
                            break;
                        }

                        case "subprinciple__number":
                        {
                            parentPrincipleNumber = principleNumber;
                            subprincipleNumber    = childPrincipleNumber;
                            entityType            = MapEnitityType(docPart.ClassName);
                            break;
                        }

                        default:
                        {
                            throw new NotImplementedException("s.ClassName: " + docPart.ClassName);
                        }
                        }

                        Console.WriteLine("principleNumber:\t'" + childPrincipleNumber + "' parent:" + parentPrincipleNumber + " entityType: " + entityType.ToString() + " insideSectionTitle: " + haveTopicTitle.ToString());
                        Console.WriteLine("childPrincipleNumber:\t'" + childPrincipleNumber + "'");
                    }
                    else if (docPart.ClassName.Contains("_title"))
                    {
                        principleTitle             = Regex.Replace(FixEncoding(docPart.TextContent), @"\s+", " ").Replace("“", "&quote;").Replace("”", "&quote;").Replace("\"", "&quote;").Trim();
                        isAfterFirstPrincipleTitle = true;
                        corpus.Add(principleTitle);

                        Console.WriteLine("principleNumber:\t'" + childPrincipleNumber + "' parent:" + parentPrincipleNumber + " entityType: " + entityType.ToString() + " insideSectionTitle: " + haveTopicTitle.ToString());
                        Console.WriteLine("principleTitle:\t'" + principleTitle + "'");

                        if (doMakeKeywordPhrases && !String.IsNullOrEmpty(principleTitle))
                        {
                            List <String> response = new List <string>();
                            response.Add(principleTitle);
                            string request = AzureTextAnalytics.FormatRequestJSON(response);
                            AzureTextAnalytics.MakeKeyPhrasesRequest(request).Wait();
                        }
                        else
                        {
                            AzureTextAnalytics.Response = "NULL";
                        }
                        string keyphases = AzureTextAnalytics.Response;

                        if (String.IsNullOrEmpty(principleTitle))
                        {
                            principleTitle = "NULL";
                        }

                        _File.WriteLine(csvformat,
                                        ++entityOrder, childPrincipleNumber, parentPrincipleNumber, entityType.ToString(), principleTitle, ContentTypes.BaseEntity_Principles_RayDalio_ModelMate.ToString(), childPrincipleNumber + ". " + principleTitle, keyphases);

                        parentPrincipleNumber = childPrincipleNumber;
                    }
                    else if (docPart.ClassName == "commentary" && isAfterFirstPrincipleNumber && isAfterFirstPrincipleTitle)
                    {
                        principleCommentaryText = Regex.Replace(FixEncoding(docPart.TextContent), @"\s+", " ").Replace("“", "&quote;").Replace("”", "&quote;").Replace("\"", "&quote;").Trim();
                        corpus.Add(principleCommentaryText);

                        Console.WriteLine("principleNumber:\t'" + childPrincipleNumber + "': '" + principleTitle + "' parent:" + parentPrincipleNumber + " entityType: " + entityType.ToString());
                        Console.WriteLine("principleCommentaryText:\t'" + principleCommentaryText + "'");

                        if (doMakeKeywordPhrases && !String.IsNullOrEmpty(principleCommentaryText))
                        {
                            List <String> response = new List <string>();
                            response.Add(principleCommentaryText);
                            string request = AzureTextAnalytics.FormatRequestJSON(response);
                            AzureTextAnalytics.MakeKeyPhrasesRequest(request).Wait();
                        }
                        else
                        {
                            AzureTextAnalytics.Response = "NULL";
                        }
                        string keyphases = AzureTextAnalytics.Response;

                        if (String.IsNullOrEmpty(principleCommentaryText))
                        {
                            principleCommentaryText = "NULL";
                        }

                        _File.WriteLine(csvformat,
                                        ++entityOrder, childPrincipleNumber, parentPrincipleNumber, entityType.ToString(), principleTitle, ContentTypes.CommentaryText_Principles_RayDalio_ModelMate.ToString(), principleCommentaryText, keyphases);
                    }
                    else if (docPart.ClassName == "question" && isAfterFirstPrincipleNumber && isAfterFirstPrincipleTitle)
                    {
                        principleQuestionText = Regex.Replace(FixEncoding(docPart.TextContent), @"\s+", " ").Replace("“", "&quote;").Replace("”", "&quote;").Replace("\"", "&quote;").Trim();
                        corpus.Add(principleQuestionText);

                        Console.WriteLine("principleNumber:\t'" + childPrincipleNumber + "': '" + principleTitle + "' parent:" + parentPrincipleNumber + " entityType: " + entityType.ToString());
                        Console.WriteLine("principleQuestion:\t'" + principleQuestionText + "'");

                        if (doMakeKeywordPhrases && !String.IsNullOrEmpty(principleQuestionText))
                        {
                            List <String> response = new List <string>();
                            response.Add(principleQuestionText);
                            string request = AzureTextAnalytics.FormatRequestJSON(response);
                            AzureTextAnalytics.MakeKeyPhrasesRequest(request).Wait();
                        }
                        else
                        {
                            AzureTextAnalytics.Response = "NULL";
                        }
                        string keyphases = AzureTextAnalytics.Response;

                        if (String.IsNullOrEmpty(principleQuestionText))
                        {
                            principleQuestionText = "NULL";
                        }

                        _File.WriteLine(csvformat,
                                        ++entityOrder, childPrincipleNumber, parentPrincipleNumber, entityType.ToString(), principleTitle, ContentTypes.QuestionText_Principles_RayDalio_ModelMate.ToString(), principleQuestionText, keyphases);
                    }
                    else if (docPart.ClassName == "letter" && isAfterFirstPrincipleNumber && isAfterFirstPrincipleTitle)
                    {
                        principleLetterText = Regex.Replace(FixEncoding(docPart.TextContent), @"\s+", " ").Replace("“", "&quote;").Replace("”", "&quote;").Replace("\"", "&quote;").Trim();
                        corpus.Add(principleLetterText);

                        Console.WriteLine("principleNumber:\t'" + childPrincipleNumber + "': '" + principleTitle + "' parent:" + parentPrincipleNumber + " entityType: " + entityType.ToString());
                        Console.WriteLine("principleLetterText:\t'" + principleLetterText + "'");

                        if (doMakeKeywordPhrases && !String.IsNullOrEmpty(principleLetterText))
                        {
                            List <String> response = new List <string>();
                            response.Add(principleLetterText);
                            string request = AzureTextAnalytics.FormatRequestJSON(response);
                            AzureTextAnalytics.MakeKeyPhrasesRequest(request).Wait();
                        }
                        else
                        {
                            AzureTextAnalytics.Response = "NULL";
                        }
                        string keyphases = AzureTextAnalytics.Response;

                        if (String.IsNullOrEmpty(principleLetterText))
                        {
                            principleLetterText = "NULL";
                        }

                        _File.WriteLine(csvformat,
                                        ++entityOrder, childPrincipleNumber, parentPrincipleNumber, entityType.ToString(), principleTitle, ContentTypes.LetterText_Principles_RayDalio_ModelMate.ToString(), principleLetterText, keyphases);
                    }
                    else if (docPart.ClassName == "bullet" && isAfterFirstPrincipleNumber && isAfterFirstPrincipleTitle)
                    {
                        principleBulletText = Regex.Replace(FixEncoding(docPart.TextContent), @"\s+", " ").Replace("“", "&quote;").Replace("”", "&quote;").Replace("\"", "&quote;").Trim();
                        corpus.Add(principleBulletText);

                        Console.WriteLine("principleNumber:\t'" + childPrincipleNumber + "': '" + principleTitle + "' parent:" + parentPrincipleNumber + " entityType: " + entityType.ToString());
                        Console.WriteLine("principleBulletText:\t'" + principleBulletText + "'");

                        if (doMakeKeywordPhrases && !String.IsNullOrEmpty(principleBulletText))
                        {
                            List <String> response = new List <string>();
                            response.Add(principleBulletText);
                            string request = AzureTextAnalytics.FormatRequestJSON(response);
                            AzureTextAnalytics.MakeKeyPhrasesRequest(request).Wait();
                        }
                        else
                        {
                            AzureTextAnalytics.Response = "NULL";
                        }
                        string keyphases = AzureTextAnalytics.Response;

                        if (String.IsNullOrEmpty(principleBulletText))
                        {
                            principleBulletText = "NULL";
                        }

                        _File.WriteLine(csvformat,
                                        ++entityOrder, childPrincipleNumber, parentPrincipleNumber, entityType.ToString(), principleTitle, ContentTypes.BulletText_Principles_RayDalio_ModelMate.ToString(), principleBulletText, keyphases);
                    }
                    else if (docPart.ClassName == "number" && isAfterFirstPrincipleNumber && isAfterFirstPrincipleTitle)
                    {
                        principleNumberText = Regex.Replace(FixEncoding(docPart.TextContent), @"\s+", " ").Replace("“", "&quote;").Replace("”", "&quote;").Replace("\"", "&quote;").Trim();
                        corpus.Add(principleNumberText);

                        Console.WriteLine("principleNumber:\t'" + childPrincipleNumber + "': '" + principleTitle + "' parent:" + parentPrincipleNumber + " entityType: " + entityType.ToString());
                        Console.WriteLine("principleNumberText:\t'" + principleNumberText + "'");

                        if (doMakeKeywordPhrases && !String.IsNullOrEmpty(principleNumberText))
                        {
                            List <String> response = new List <string>();
                            response.Add(principleNumberText);
                            string request = AzureTextAnalytics.FormatRequestJSON(response);
                            AzureTextAnalytics.MakeKeyPhrasesRequest(request).Wait();
                        }
                        else
                        {
                            AzureTextAnalytics.Response = "NULL";
                        }
                        string keyphases = AzureTextAnalytics.Response;

                        if (String.IsNullOrEmpty(principleNumberText))
                        {
                            principleNumberText = "NULL";
                        }

                        _File.WriteLine(csvformat,
                                        ++entityOrder, childPrincipleNumber, parentPrincipleNumber, entityType.ToString(), principleTitle, ContentTypes.NumberText_Principles_RayDalio_ModelMate.ToString(), principleNumberText, keyphases);
                    }
                    else if (docPart.LocalName == "img" && isAfterFirstPrincipleNumber && isAfterFirstPrincipleTitle)
                    {
                        principleImageUrl = docPart.GetAttribute("src");
                        //corpus.Add(principleImageUrl);

                        Console.WriteLine("principleNumber:\t'" + childPrincipleNumber + "': '" + principleTitle + "' parent:" + parentPrincipleNumber + " entityType: " + entityType.ToString());
                        Console.WriteLine("principleImageUrl:\t'" + principleImageUrl + "'");

                        if (doMakeKeywordPhrases && !String.IsNullOrEmpty(principleImageUrl))
                        {
                            List <String> response = new List <string>();
                            response.Add(principleImageUrl);
                            string request = AzureTextAnalytics.FormatRequestJSON(response);
                            AzureTextAnalytics.MakeKeyPhrasesRequest(request).Wait();
                        }
                        else
                        {
                            AzureTextAnalytics.Response = "NULL";
                        }
                        string keyphases = AzureTextAnalytics.Response;

                        if (String.IsNullOrEmpty(principleImageUrl))
                        {
                            principleImageUrl = "NULL";
                        }

                        _File.WriteLine(csvformat,
                                        ++entityOrder, childPrincipleNumber, parentPrincipleNumber, entityType.ToString(), principleTitle, ContentTypes.ImageUrl_Principles_RayDalio_ModelMate.ToString(), principleImageUrl, keyphases);
                    }
                    else if (docPart.LocalName == "figure" && isAfterFirstPrincipleNumber && isAfterFirstPrincipleTitle && !docPart.ClassName.Contains("image"))
                    {
                        principleFigureText = Regex.Replace(FixEncoding(docPart.TextContent), @"\s+", " ").Replace("“", "&quote;").Replace("”", "&quote;").Replace("\"", "&quote;").Trim();
                        corpus.Add(principleFigureText);

                        Console.WriteLine("principleNumber:\t'" + childPrincipleNumber + "': '" + principleTitle + "' parent:" + parentPrincipleNumber + " entityType: " + entityType.ToString());
                        Console.WriteLine("principleFigureText:\t'" + principleFigureText + "'");

                        if (doMakeKeywordPhrases && !String.IsNullOrEmpty(principleFigureText))
                        {
                            List <String> response = new List <string>();
                            response.Add(principleFigureText);
                            string request = AzureTextAnalytics.FormatRequestJSON(response);
                            AzureTextAnalytics.MakeKeyPhrasesRequest(request).Wait();
                        }
                        else
                        {
                            AzureTextAnalytics.Response = "NULL";
                        }
                        string keyphases = AzureTextAnalytics.Response;

                        if (String.IsNullOrEmpty(principleFigureText))
                        {
                            principleFigureText = "NULL";
                        }

                        _File.WriteLine(csvformat,
                                        ++entityOrder, childPrincipleNumber, parentPrincipleNumber, entityType.ToString(), principleTitle, ContentTypes.FigureText_Principles_RayDalio_ModelMate.ToString(), principleFigureText, keyphases);
                    }

                    _File.Flush();
                }
            }

            string request2 = AzureTextAnalytics.FormatRequestJSON(corpus);

            AzureTextAnalytics.MakeTopicsRequest(request2).Wait();
            string response2 = AzureTextAnalytics.Response;
            string location2 = AzureTextAnalytics.Location;

            string[] parts       = location2.Split('/');
            string   operationId = parts[parts.Length - 1];
            string   response3   = "\"Running\"";

            while (response3.Contains("\"Running\""))
            {
                Console.WriteLine("Waiting...");
                System.Threading.Thread.Sleep(60 * 1000);
                AzureTextAnalytics.GetTopicsResults(operationId).Wait();
                response3 = AzureTextAnalytics.Response;
                Console.WriteLine(response3);
            }

            using (System.IO.StreamWriter _File = new System.IO.StreamWriter(@"HTMLScanner-RayDalioPrinciples.json"))
            {
                _File.WriteLine(response3);
            }

            ////Serialize it back to the console
            //Console.WriteLine(document.DocumentElement.OuterHtml);

            Console.WriteLine("Press enter to exit...");
            Console.ReadLine();
        }
Пример #46
0
        /// <summary>
        /// Write An .ini file value of a key inside a given section
        /// </summary>
        /// <param name="filePath">The path to the .ini file</param>
        /// <param name="section">The desired section</param>
        /// <param name="key">The desired key inside the given section</param>
        /// <param name="value">The value to write.</param>
        /// <returns>true in case of success, false otherwise</returns>
        ///<exception cref="System.ArgumentNullException">either section / key are null</exception>
        /// <exception cref="Parsers.FileHandlingException">Any exception thrown by file handling methods.</exception>
        public static bool WriteValue(string filePath, string section, string key, string value)
        {
            string line, rawLine;
            string currentSection = null;
            bool   updated        = false;
            string tempFile       = System.IO.Path.GetFileName(filePath);

            if (section == null || key == null)
            {
                throw new ArgumentNullException("Section or key are null");
            }
            key     = key.Trim();
            section = section.Trim().TrimStart('[').TrimEnd(']');
            string[] keyValue;
            try
            {
                using (var sr = new System.IO.StreamReader(filePath))
                {
                    using (var sw = new System.IO.StreamWriter(System.IO.File.Create(tempFile)))
                    {
                        while (!sr.EndOfStream)
                        {
                            rawLine = sr.ReadLine();
                            if (updated)
                            {
                                sw.WriteLine(rawLine); continue;
                            }
                            line = rawLine.TrimStart();
                            if (line.Length == 0)
                            {
                                sw.WriteLine(rawLine); continue;
                            }
                            if (line.StartsWith(";"))
                            {
                                sw.WriteLine(rawLine); continue;
                            }
                            if (line.StartsWith("[")) //section
                            {
                                line = line.TrimStart('[');
                                try { line = line.Remove(line.IndexOf(']')); }
                                catch { }
                                currentSection = line;
                                sw.WriteLine(rawLine);
                                continue;
                            }
                            if (currentSection == null || currentSection != section)
                            {
                                sw.WriteLine(rawLine); continue;
                            }
                            keyValue = line.Split(new char[] { '=' }, 2);
                            if (keyValue == null || keyValue.Length != 2)
                            {
                                sw.WriteLine(rawLine); continue;
                            }
                            keyValue[0] = keyValue[0].Trim();
                            if (keyValue[1].Contains(';'))
                            {
                                keyValue[1] = keyValue[1].Remove(keyValue[1].IndexOf(';'));
                            }
                            keyValue[1] = keyValue[1].Trim();
                            if (keyValue[0] == key)
                            {
                                updated = true;
                                rawLine = rawLine.Replace(keyValue[1], value);
                            }
                            sw.WriteLine(rawLine);
                        }
                    }
                }
                if (updated)
                {
                    System.IO.File.Copy(tempFile, filePath, true);
                }
                else
                {
                    System.IO.File.Delete(tempFile);
                }
            }
            catch (Exception e) { throw new FileHandlingException(e.Message); }
            return(updated);
        }
Пример #47
0
        private void button_Click(object sender, RoutedEventArgs e)
        {
            if (textBox.Text != "")
            {
                System.IO.StreamWriter sw = new System.IO.StreamWriter(
                    Hensu.ProjectPath + @"\source\" + textBox.Text + ".cs",
                    false,
                    System.Text.Encoding.GetEncoding("shift_jis"));
                sw.WriteLine("using System;");
                sw.WriteLine("using System.CodeDom;");
                sw.WriteLine("using System.CodeDom.Compiler;");
                sw.WriteLine("using System.Reflection;");
                sw.WriteLine("using System.Windows.Forms;");
                sw.WriteLine("using System.Drawing;");
                sw.WriteLine("namespace " + Hensu.ProjectName);
                sw.WriteLine("{");
                sw.WriteLine("        public partial class " + textBox.Text + "");
                sw.WriteLine("        {");

                sw.WriteLine("        }");
                sw.WriteLine("}");
                //閉じる
                sw.Close();

                this.Close();
            }
            else
            {
                MessageBox.Show("正しい値を入力してください。", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
Пример #48
0
        private static void Main(string[] args)
        {
            try {
                AuthenticationManager.Authenticate();
            } catch (Exception) {
                MessageBox.Show("Ошибка авторизации!");
                return;
            }

            TechModel model;

            try {
                model = TechModel.Load("d:\\structure.vtp");
            } catch (Exception) {
                AuthenticationManager.Deauthenticate();
                MessageBox.Show("Ошибка загрузки модели!");
                return;
            }

            System.IO.StreamWriter logFile;
            try {
                logFile = new System.IO.StreamWriter(@"D:\namelist.txt");
            } catch (Exception) {
                model.Close();
                AuthenticationManager.Deauthenticate();
                MessageBox.Show("Ошибка создания файла!");
                return;
            }

            foreach (TechClass cls in model.Classes)
            {
                if (cls.DisplayName != String.Empty)
                {
                    logFile.WriteLine("    " + cls.Name + "(Экранное имя): " + cls.DisplayName);
                }
                if (cls.Description != String.Empty)
                {
                    logFile.WriteLine("    " + cls.Name + "(Комментарий): " + cls.Description);
                }
                foreach (var group in cls.Appearance.AttributesGroups)
                {
                    if (group.Name != String.Empty)
                    {
                        logFile.WriteLine("    " + cls.Name + "(Группа): " + group.Name);
                    }
                }

                foreach (TechClassMember mbr in cls.Members)
                {
                    if (mbr.Description != String.Empty)
                    {
                        logFile.WriteLine("    " + cls.Name + "." + mbr.Name + "(Экранное имя): " + mbr.DisplayName);
                    }
                    if (mbr.Description != String.Empty)
                    {
                        logFile.WriteLine("    " + cls.Name + "." + mbr.Name + "(Комментарий): " + mbr.Description);
                    }
                }
            }

            foreach (var flt in model.Filters)
            {
                if (flt.DisplayName != String.Empty)
                {
                    logFile.WriteLine("    " + flt.Name + "(Экранное имя): " + flt.DisplayName);
                }
                if (flt.Description != String.Empty)
                {
                    logFile.WriteLine("    " + flt.Name + "(Комментарий): " + flt.Description);
                }
            }

            foreach (var func in model.Functions)
            {
                if (func.DisplayName != String.Empty)
                {
                    logFile.WriteLine("    " + func.Name + "(Экранное имя): " + func.DisplayName);
                }
                if (func.Description != String.Empty)
                {
                    logFile.WriteLine("    " + func.Name + "(Комментарий): " + func.Description);
                }
            }

            foreach (var num in model.Numerators)
            {
                if (num.DisplayName != String.Empty)
                {
                    logFile.WriteLine("    " + num.Name + "(Экранное имя): " + num.DisplayName);
                }
                if (num.Description != String.Empty)
                {
                    logFile.WriteLine("    " + num.Name + "(Комментарий): " + num.Description);
                }
            }

            foreach (var marker in model.Markers)
            {
                if (marker.DisplayName != String.Empty)
                {
                    logFile.WriteLine("    " + marker.Name + "(Экранное имя): " + marker.DisplayName);
                }
                if (marker.Description != String.Empty)
                {
                    logFile.WriteLine("    " + marker.Name + "(Комментарий): " + marker.Description);
                }
            }

            foreach (var tree in model.Presentations)
            {
                if (tree.DisplayName != String.Empty)
                {
                    logFile.WriteLine("    " + tree.Name + "(Экранное имя): " + tree.DisplayName);
                }
                if (tree.Description != String.Empty)
                {
                    logFile.WriteLine("    " + tree.Name + "(Комментарий): " + tree.Description);
                }
            }

            model.Close();
            AuthenticationManager.Deauthenticate();
            logFile.Close();
            MessageBox.Show("Выполнено!");
        }
Пример #49
0
        }/* script_close */

        /*
         * script_new_line
         *
         * Write a newline to the transscript file.
         *
         */

        internal static void ScriptNewLine()
        {
            Sfp?.WriteLine();

            ScriptWidth = 0;
        }/* script_new_line */
Пример #50
0
 public void WriteLine(string str)
 {
     _sw.WriteLine(str);
 }
Пример #51
0
        private string ProccessProviderFile(string FilePath, string ErrorFilePath, string CustomerPublicId)
        {
            //get excel rows
            LinqToExcel.ExcelQueryFactory XlsInfo = new LinqToExcel.ExcelQueryFactory(FilePath);

            List <ExcelProviderModel> oPrvToProcess =
                (from x in XlsInfo.Worksheet <ExcelProviderModel>(0)
                 select x).ToList();

            List <ExcelProviderResultModel> oPrvToProcessResult = new List <ExcelProviderResultModel>();

            //process Provider
            oPrvToProcess.Where(prv => !string.IsNullOrEmpty(prv.NumeroIdentificacion)).All(prv =>
            {
                try
                {
                    #region Operation
                    //Validar el provider
                    ProviderModel Provider = new ProviderModel();

                    ProviderModel oResultValidate = new ProviderModel();
                    ProviderModel oInfoValidate   = new ProviderModel();
                    oResultValidate = DocumentManagement.Provider.Controller.Provider.ProviderGetByIdentification(prv.NumeroIdentificacion, Convert.ToInt32(prv.TipoIdentificacion), CustomerPublicId);

                    //Create ProviderCustomerInfo
                    List <ProviderInfoModel> ListCustomerProviderInfo = new List <ProviderInfoModel>();
                    ProviderInfoModel CustomerProviderInfo            = new ProviderInfoModel();
                    if (oResultValidate == null)
                    {
                        CustomerProviderInfo.ProviderInfoType = new CatalogModel()
                        {
                            ItemId = 401
                        };
                        CustomerProviderInfo.Value = "201";
                        ListCustomerProviderInfo.Add(CustomerProviderInfo);
                    }

                    CustomerProviderInfo = new ProviderInfoModel();
                    CustomerProviderInfo.ProviderInfoId = oResultValidate != null ?
                                                          oResultValidate.RelatedProviderCustomerInfo.Where(x => x.ProviderInfoType.ItemId == 378).
                                                          Select(x => x.ProviderInfoId).FirstOrDefault() : 0;
                    CustomerProviderInfo.ProviderInfoType = new CatalogModel()
                    {
                        ItemId = 378
                    };
                    CustomerProviderInfo.Value = prv.DigitoVerificacion;
                    ListCustomerProviderInfo.Add(CustomerProviderInfo);


                    //Create Provider
                    ProviderModel ProviderToCreate = new ProviderModel()
                    {
                        CustomerPublicId   = CustomerPublicId,
                        Name               = prv.RazonSocial,
                        IdentificationType = new Provider.Models.Util.CatalogModel()
                        {
                            ItemId = Convert.ToInt32(prv.TipoIdentificacion)
                        },
                        IdentificationNumber = prv.NumeroIdentificacion,
                        Email = prv.Email,
                        RelatedProviderCustomerInfo = ListCustomerProviderInfo
                    };
                    if (oResultValidate == null)
                    {
                        DocumentManagement.Provider.Controller.Provider.ProviderUpsert(ProviderToCreate);

                        ProviderToCreate.CustomerPublicId = DocumentManagement.Models.General.InternalSettings.Instance[DocumentManagement.Models.General.Constants.C_Settings_PublicId_Publicar].Value;
                        ListCustomerProviderInfo.All(x =>
                        {
                            x.ProviderInfoId = 0;
                            return(true);
                        });

                        DocumentManagement.Provider.Controller.Provider.ProviderCustomerInfoUpsert(ProviderToCreate);
                    }
                    else
                    {
                        ProviderToCreate.ProviderPublicId = oResultValidate.ProviderPublicId;
                        DocumentManagement.Provider.Controller.Provider.ProviderCustomerInfoUpsert(ProviderToCreate);
                    }


                    oPrvToProcessResult.Add(new ExcelProviderResultModel()
                    {
                        PrvModel = prv,
                        Success  = true,
                        Error    = "Se ha creado el Proveedor '" + ProviderToCreate.ProviderPublicId + "'",
                    });
                    #endregion
                }
                catch (Exception err)
                {
                    oPrvToProcessResult.Add(new ExcelProviderResultModel()
                    {
                        PrvModel = prv,
                        Success  = false,
                        Error    = "Error :: " + err.Message + " :: " +
                                   err.StackTrace +
                                   (err.InnerException == null ? string.Empty :
                                    " :: " + err.InnerException.Message + " :: " +
                                    err.InnerException.StackTrace),
                    });
                }
                return(true);
            });

            //save log file
            #region Error log file
            try
            {
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(ErrorFilePath))
                {
                    string strSep = ";";

                    sw.WriteLine
                        ("\"RazonSocial\"" + strSep +
                        "\"TipoIdentificacion\"" + strSep +
                        "\"NumeroIdentificaion\"" + strSep +
                        "\"DigitoVerificacion\"" + strSep +
                        "\"Email\"" + strSep +
                        "\"CampanaSalesforce\"" + strSep +

                        "\"PublicIdPublicar\"" + DocumentManagement.Models.General.Constants.C_Settings_PublicId_Publicar.ToString() +
                        "\"Success\"" + strSep +
                        "\"Error\"");

                    oPrvToProcessResult.All(lg =>
                    {
                        sw.WriteLine
                            ("\"" + lg.PrvModel.RazonSocial + "\"" + strSep +
                            "\"" + lg.PrvModel.TipoIdentificacion + "\"" + strSep +
                            "\"" + lg.PrvModel.NumeroIdentificacion + "\"" + strSep +
                            "\"" + lg.PrvModel.DigitoVerificacion + "\"" + strSep +
                            "\"" + lg.PrvModel.Email + "\"" + strSep +
                            "\"" + lg.PrvModel.CampanaSalesforce + "\"" + strSep +

                            "\"" + lg.Success + "\"" + strSep +
                            "\"" + lg.Error + "\"");

                        return(true);
                    });

                    sw.Flush();
                    sw.Close();
                }

                //load file to s3
                string strRemoteFile = ProveedoresOnLine.FileManager.FileController.LoadFile
                                           (ErrorFilePath,
                                           DocumentManagement.Models.General.InternalSettings.Instance[DocumentManagement.Models.General.Constants.C_Settings_File_ExcelDirectory].Value);
                //remove temporal file
                if (System.IO.File.Exists(ErrorFilePath))
                {
                    System.IO.File.Delete(ErrorFilePath);
                }

                return(strRemoteFile);
            }
            catch { }

            return(null);

            #endregion
        }
Пример #52
0
        public static void Main(string [] args)
        {
            Random rnd = new Random();

            System.IO.StreamWriter file1 = new System.IO.StreamWriter(@"file1.txt");
            System.IO.StreamWriter file2 = new System.IO.StreamWriter(@"file2.txt");

            for (int i = 0; i < 1000; i++)
            {
                try
                {
                    int a = rnd.Next(10);
                    int b = rnd.Next(10);
                    int c = rnd.Next(10);
                    int d = rnd.Next(10);

                    try
                    {
                        switch (rnd.Next(3))
                        {
                        case 0:
                            new Triangle(a, b, c);
                            break;

                        case 1:
                            new Quadrangle(a, b, c, d);
                            break;

                        case 2:
                            new Circle(a);
                            break;
                        }
                    }
                    catch (TriangleException e)
                    {
                        string str = "Triangle";
                        foreach (int j in e.Parametrs)
                        {
                            str += (":" + j.ToString());
                        }
                        file1.WriteLine(str);

                        Console.WriteLine(str);
                        throw;
                    }
                    catch (QuadrangleException e)
                    {
                        string str = "Quadrangle";
                        foreach (int j in e.Parametrs)
                        {
                            str += (":" + j.ToString());
                        }
                        file1.WriteLine(str);

                        Console.WriteLine(str);
                        throw;
                    }
                }
                catch (GeometryException e)
                {
                    string str;
                    switch (e.Parametrs.Length)
                    {
                    case 1:
                        str = "Circle";
                        break;

                    case 3:
                        str = "Triangle";
                        break;

                    case 4:
                        str = "Quadrangle";
                        break;

                    default:
                        str = "Figure";
                        break;
                    }

                    foreach (int j in e.Parametrs)
                    {
                        str += (":" + j.ToString());
                    }
                    file2.WriteLine(str);
                    Console.WriteLine(str);
                }
            }
            file1.Close();
            file2.Close();
            Console.ReadLine();
        }
Пример #53
0
        public Presentation()
        {
            if (System.IO.File.Exists(SlidesFile))
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader(SlidesFile))
                {
                    while (!sr.EndOfStream)
                    {
                        slides.Add(sr.ReadLine());
                    }
                }
            }

            List <string> slidesInAssembly = new List <string>();

            Assembly asm = Assembly.GetExecutingAssembly();

            using (ResourceReader reader = new ResourceReader(asm.GetManifestResourceStream(asm.GetName().Name + ".g.resources")))
            {
                foreach (DictionaryEntry entry in reader)
                {
                    if (entry.Key is string)
                    {
                        string s = ((string)entry.Key);
                        if (s.StartsWith("slides/") && s.EndsWith(".baml"))
                        {
                            slidesInAssembly.Add(s.Replace(".baml", ".xaml"));
                        }
                    }
                }
            }

            /*foreach (Type t in this.GetType().Assembly.GetTypes())
             * {
             *  if (t.Namespace == "WPFPresenter.Slides" && t.IsSubclassOf(typeof(Page)))
             *  {
             *      string s = @"Slides\" + t.Name.Substring(1) + ".xaml";
             *      slidesInAssembly.Add(s);
             *  }
             * }*/

            slidesInAssembly.Sort();

            slidesInAssembly.ForEach(s => { if (!slides.Contains(s))
                                            {
                                                slides.Add(s);
                                            }
                                     });

            foreach (string s in slides.ToArray())
            {
                if (!slidesInAssembly.Contains(s))
                {
                    slides.Remove(s);
                }
            }

            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(SlidesFile))
            {
                slides.ForEach(f => sw.WriteLine(f));
            }
        }
Пример #54
0
 public static void Write(int line)
 {
     file.WriteLine(line);
 }
Пример #55
0
        public static void checkEnvironment(System.IO.StreamWriter file)
        {
            foreach (var drive in System.IO.DriveInfo.GetDrives())
            {
                try
                {
                    double freeSpace   = drive.TotalFreeSpace;
                    double totalSpace  = drive.TotalSize;
                    double percentFree = (freeSpace / totalSpace) * 100;
                    float  num         = (float)percentFree;

                    file.WriteLine(DateTime.Now);
                    file.WriteLine(drive.Name);
                    file.WriteLine(Environment.UserName);
                    file.WriteLine("Drive:{0} With {1} % free", drive.Name, num);
                    file.WriteLine("Space Remaining:{0}", drive.AvailableFreeSpace);
                    file.WriteLine("Percent Free Space:{0}", percentFree);
                    file.WriteLine("Space used:{0}", drive.TotalSize);
                    file.WriteLine("Type: {0}", drive.DriveType);

                    Console.WriteLine(Environment.UserName);
                    Console.WriteLine(DateTime.Now);
                    Console.WriteLine(drive.Name);
                    Console.WriteLine("Drive:{0} With {1} % free", drive.Name, num);
                    Console.WriteLine("Space Remaining:{0}", drive.AvailableFreeSpace);
                    Console.WriteLine("Percent Free Space:{0}", percentFree);
                    Console.WriteLine("Space used:{0}", drive.TotalSize);
                    Console.WriteLine("Type: {0}", drive.DriveType);
                    try
                    {
                        string[] filePaths = System.IO.Directory.GetFiles(@drive.Name);
                        foreach (string arquivo in filePaths)
                        {
                            Console.WriteLine("Arquivo: " + arquivo);
                            file.WriteLine("Arquivo: " + arquivo);
                        }
                        string[] dirpaths = System.IO.Directory.GetDirectories(@drive.Name);
                        foreach (string diretorio in dirpaths)
                        {
                            Console.WriteLine("Diretório: " + diretorio);
                            file.WriteLine("Diretório: " + diretorio);
                        }
                    }
                    catch (System.ArgumentException e)
                    {
                        Console.WriteLine("erro " + e);
                        file.WriteLine("erro " + e);
                    }
                }
                catch (System.IO.IOException e)
                {
                    Console.WriteLine("Erro " + e);
                    file.WriteLine("Erro " + e);
                }
            }
        }
Пример #56
0
        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                //  Read File
                List <string> lines;
                if (!Helpers.ReadInfFile(filePath, out lines))
                {
                    return;
                }
                // Find Manufacturer Section to Find OS Speciefic Sections
                for (int i = 0; i < lines.Count; i++)
                {
                    if (lines[i].Trim().Equals("[Manufacturer]"))
                    {
                        listSectionNames = Helpers.getControlSections(lines[i + 1]);
                        break;
                    }
                }
                //
                foreach (string fullsectionname in listSectionNames)
                {
                    bool inSection = false;
                    for (int i = 0; i < lines.Count; i++)
                    {
                        if (lines[i].Trim().ToLower().Equals(fullsectionname.ToLower()) && !inSection)
                        {
                            inSection = true;
                            listSections.Add(new List <Section>());
                            i++;
                        }

                        if (inSection)
                        {
                            Section x = new Section(lines[i]);
                            if (x.Valid())
                            {
                                lines[i] = string.Empty;
                                listSections[listSections.Count - 1].Add(x);
                            }
                            else if (lines[i].StartsWith("["))
                            {
                                break;
                            }
                        }
                    }
                }

                // ### Alle validen Elemente in 'allSections' schreiben
                List <Section> allSections     = listSections.SelectMany(listSec => listSec).ToList();
                List <string>  allSectionLines = new List <string>();
                foreach (Section section in allSections)
                {
                    allSectionLines.Add(section.GetLine());
                }
                allSectionLines = allSectionLines.Distinct().ToList();


                using (System.IO.StreamWriter file = new System.IO.StreamWriter(filePath))
                {
                    int currentSectionnr = -1;

                    foreach (string line in lines)
                    {
                        if (listSectionNames.Contains(line))
                        {
                            currentSectionnr++;
                            file.WriteLine(listSectionNames[currentSectionnr]);
                            foreach (string x in allSectionLines)
                            {
                                file.WriteLine(x);
                            }
                        }
                        else
                        {
                            if (line.Length > 0)
                            {
                                file.WriteLine(line);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                ok = false;
            }
        }
Пример #57
0
        public void CalculateClimate(LockBitmap heatMap)
        {
            var provinces = new List <Province>(this.ProvinceLand);

            this.heat = heatMap;
            heatMap.LockBits();
            using (System.IO.StreamWriter filein =
                       new System.IO.StreamWriter(Globals.MapOutputTotalDir + "map\\climate.txt", false,
                                                  Encoding.GetEncoding(1252)))
            {
                provinces.Sort(SortByHeat);

                int numHeavy  = provinces.Count / 7;
                int numNormal = provinces.Count / 6;
                int numLight  = provinces.Count / 5;
                if (Globals.Climate == 3)
                {
                    numHeavy  /= 2;
                    numNormal /= 2;
                    numHeavy  /= 2;
                }
                if (Globals.Climate == 4)
                {
                    numHeavy  = 0;
                    numNormal = 0;
                    numHeavy  = 0;
                }

                numNormal += numHeavy;
                numLight  += numNormal;
                List <Province> heavy  = new List <Province>();
                List <Province> normal = new List <Province>();
                List <Province> light  = new List <Province>();
                int             c      = 1;
                String          h      = "";
                String          n      = "";
                String          l      = "";
                for (int x = 0; x < provinces.Count; x++)
                {
                    var p = provinces[x];

                    if (c < numHeavy)
                    {
                        heavy.Add(p);
                        h = h + " " + p.ID;
                    }
                    else if (c < numNormal)
                    {
                        normal.Add(p);
                        n = n + " " + p.ID;
                    }
                    else if (c < numLight)
                    {
                        light.Add(p);
                        l = l + " " + p.ID;
                    }
                    c++;
                }

                filein.WriteLine("mild_winter = {");
                filein.WriteLine(l);
                filein.WriteLine("}");
                filein.WriteLine("normal_winter = {");
                filein.WriteLine(n);
                filein.WriteLine("}");
                filein.WriteLine("severe_winter = {");
                filein.WriteLine(h);
                filein.WriteLine("}");
            }

            heatMap.UnlockBits();
            foreach (var value in colorProvinceMap.Values)
            {
                value.points.Clear();
                value.border.Clear();
                value.coast.Clear();
                value.adjacent.Clear();
            }
            this.provinces.Clear();
            ProvinceSea.Clear();
            ProvinceLand.Clear();
            OceanZones.Clear();
            SeaZones.Clear();
        }
Пример #58
0
        public void DoProcessIat()
        {
            PrinterDir        print       = new PrinterDir();
            List <PrinterDir> printerList = print.printerList();

            if (printerList.Count == 0)
            {
                MessageBox.Show(@"No hay impresoras configuradas, se usará DefaultPrinter");
            }

            int i = 0;
            int j = 0;


            while (!_shouldStop)
            {
                Console.WriteLine("ProcessIat thread: working...");

                Thread.Sleep(5000);

                i++;

                String paquete        = String.Empty;
                String dirCurrentFile = String.Empty;
                String Impresora      = String.Empty;

                // instancia fileadmin, para tener las herramientas para mover archivos
                fileAdmin fileAdm = new fileAdmin();

                // inatancia txt_reader
                TxtReader lec = new TxtReader();

                Documento        docLectura = new Documento();
                FuncionesComunes fc         = new FuncionesComunes();

                if (printerList.Count == 0)
                {
                    dirCurrentFile = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file";
                    Impresora      = fc.GetDefaultPrinter();
                }
                else
                {
                    PrinterDir printDir = printerList.ElementAt(j);
                    dirCurrentFile = printDir.directory;
                    Impresora      = printDir.printerName;
                }
                Console.WriteLine("Buscando Json en " + dirCurrentFile);
                j++;


                // Ejecuta metodo de txt_reader que llena y obtienen Clase Documento
                docLectura = lec.lectura("", false, dirCurrentFile);

                // Proceso de validación de Folio, si este proceso no tiene exito se dejará el json en directorio errorFolio
                // se dejará el objeto docLectura para que no sea procesado
                // ************************************************
                // Obtener folioSiguiente

                /*   Folio folio = new Folio();
                 * folio = folio.getFolio(docLectura.TipoDTE, docLectura.RUTEmisor);
                 *
                 *
                 * // comparar folio siguiente con docLectura.folio
                 * if (folio.folioSgte == docLectura.Folio)
                 * {
                 *     // Si son iguales
                 *     //      Continuar con el proceso normal
                 * }
                 * else
                 * {
                 *     // Si no son iguales
                 *     //      Verificar que quedan folios
                 *     if (folio.folioSgte > folio.folioFin)
                 *     {
                 *         //      si quedan folios
                 *         //          Avisar a Cajero
                 *         SocketClient sc = new SocketClient();
                 *         sc.StartClient("El Folio "+docLectura.Folio+" ha cambiado por el "+folio.folioSgte);
                 *         //          docLectura.Folio = FolioSiguiente
                 *         docLectura.Folio = folio.folioSgte;
                 *         // TO DO; UpdatearADM
                 *
                 *     }
                 *     else
                 *     {
                 *         //      si no quedan folios
                 *         //          Mover el Json a directorio errorFolio
                 *         fileAdm.mvFile(docLectura.fileName, dirCurrentFile, @""+Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString()+":\IatFiles\errorFolio\");
                 *         //          dejar docLectura en Null para que no se imprima
                 *         docLectura = null;
                 *     }
                 * }
                 */

                //*************************************************

                // instancia XML_admin
                xmlPaquete xml = new xmlPaquete();

                List <int> tipos = new List <int>();

                DateTime thisDay = DateTime.Now;
                String   fch     = String.Format("{0:yyyy-MM-ddTHH:mm:ss}", thisDay);
                String   fchName = String.Format("{0:yyyyMMddTHHmmss}", thisDay);

                Log log = new Log();

                String firsRut = String.Empty;
                empresa = empresa.getEmpresa();
                if (docLectura != null)
                {
                    // Proceso de ReImpresión
                    // ir a directorio procesados y buscar el archivo docLectura.filename
                    if (System.IO.File.Exists(@"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/fileprocess/" + docLectura.fileName)) // si ya existe, reimprimir
                    {
                        if (empresa.PrnThermal == "True")
                        {
                            String    fileNameXML = @"DTE_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + "_";
                            fileAdmin f           = new fileAdmin();

                            String fileXml = f.fileAprox(fileNameXML, @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/xml/", "*.xml");

                            if (fileXml != null)
                            {
                                new ReimpThermal().reimp(docLectura, fileXml, Impresora);
                            }
                        }
                        else
                        {
                            String fileNamePDFRePrint = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/pdf/PRINT_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + ".pdf";

                            if (System.IO.File.Exists(fileNamePDFRePrint))
                            {
                                fc.printPdf(fileNamePDFRePrint, Impresora);
                            }
                        }
                        fileAdm.mvFile(docLectura.fileName, dirCurrentFile, @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/fileprocess/");
                    }
                    else // si no procesar
                    {
                        fileAdm.mvFile(docLectura.fileName, dirCurrentFile, @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/fileprocess/");

                        log.addLog("Inicio proceso TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK");
                        tipos.Add(docLectura.TipoDTE);

                        String TimbreElec = xml.ted_to_xmlSii(docLectura, fch);
                        log.addLog("Crea Timbre TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK");

                        String docXmlSign = xml.doc_to_xmlSii(docLectura, TimbreElec, fch);
                        log.addLog("Crea XML Envio TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK");

                        // Guarda DTE xml
                        String DTE         = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n" + docXmlSign;
                        String fileNameXML = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/xml/DTE_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + "_" + fchName + ".xml";
                        using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileNameXML, false, Encoding.GetEncoding("ISO-8859-1")))
                        {
                            file.WriteLine(docXmlSign);
                        }

                        //si es digitalTerminal abrir Pdf
                        if (empresa.VistaPrevia == "True")
                        {
                            Pdf docpdf = new Pdf();

                            String fileNamePDF = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/pdf/DTE_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + "_" + fchName + ".pdf";
                            docpdf.OpenPdf(TimbreElec, docLectura, fileNamePDF, " ");
                            log.addLog("Crea PDF Trib TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK");

                            String fileNamePDFCed = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/pdf/DTE_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + "_" + fchName + "CEDIBLE.pdf";

                            if (docLectura.TipoDTE == 33 || docLectura.TipoDTE == 34)
                            {
                                docpdf.OpenPdf(TimbreElec, docLectura, fileNamePDFCed, "CEDIBLE");
                            }

                            if (docLectura.TipoDTE == 52)
                            {
                                docpdf.OpenPdf(TimbreElec, docLectura, fileNamePDFCed, "CEDIBLE CON SU FACTURA");
                            }
                            log.addLog("Crea PDF C TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK");
                            log.addLog("IMPRIME TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK");

                            String fileNamePDFPrint = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/pdf/PRINT_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + ".pdf";
                            docpdf.OpenPdfPrint(TimbreElec, docLectura, fileNamePDFPrint);
                            log.addLog("Crea PDF PRINT TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK");

                            // Agrega el DTE timbrado al paquete

                            paquete = paquete + docXmlSign;

                            //Estrae el rut del emisor de la primera factura del paquete
                            if (i == 0)
                            {
                                firsRut = docLectura.RUTEmisor;
                            }
                            i++;



                            // Firma POaquete unitario
                            String envioCliente = xml.creaEnvio(paquete, docLectura.RUTEmisor, docLectura.RUTRecep, tipos, docLectura.RutEnvia, docLectura.FchResol, docLectura.RUTRecep, docLectura.NumResol);

                            String envioSII = xml.creaEnvio(paquete, docLectura.RUTEmisor, docLectura.RUTRecep, tipos, docLectura.RutEnvia, docLectura.FchResol, "", docLectura.NumResol);

                            X509Certificate2 cert = FuncionesComunes.obtenerCertificado(docLectura.NombreCertificado);

                            String enviox509SII     = xml.firmarDocumento(envioSII, cert);
                            String enviox509Cliente = xml.firmarDocumento(envioCliente, cert);

                            log.addLog("FIRMA ENVIO TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK");

                            enviox509SII     = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n" + enviox509SII;
                            enviox509Cliente = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n" + enviox509Cliente;


                            String fileNameEnvioSII = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/xml/enviounitario/EnvioUnit_" + docLectura.RUTEmisor + "_" + docLectura.Folio + "_" + fchName + ".xml";

                            String fileNameEnvioCliente = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/xml/enviounitario/EnvioUnitCliente_" + docLectura.RUTEmisor + "_" + docLectura.Folio + "_" + fchName + ".xml";

                            using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileNameEnvioSII, false, Encoding.GetEncoding("ISO-8859-1")))
                            {
                                file.WriteLine(enviox509SII);
                            }

                            using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileNameEnvioCliente, false, Encoding.GetEncoding("ISO-8859-1")))
                            {
                                file.WriteLine(enviox509Cliente);
                            }

                            System.Diagnostics.Process.Start(fileNamePDFPrint);
                        }
                        else
                        {
                            //-----------------------------------------------------------------THERMAL--------------------------------------------------------------

                            if (empresa.PrnThermal == "True")
                            {
                                try
                                {
                                    for (int copies = 0; copies < 3; copies++)
                                    {
                                        Thermal thermal = new Thermal();
                                        thermal.doc    = docLectura;
                                        thermal.dd     = TimbreElec;
                                        thermal.copias = copies;
                                        if (docLectura.PrnTwoCopy == "True")
                                        {
                                            copies = 1;
                                        }
                                        docLectura.PrnTwoCopy = "False";
                                        if (copies == 2)
                                        {
                                            if (docLectura.TipoDTE == 33 || docLectura.TipoDTE == 34)
                                            {
                                                thermal.tipoCopia = "CEDIBLE";
                                            }
                                            if (docLectura.TipoDTE == 52)
                                            {
                                                thermal.tipoCopia = "CEDIBLE CON SU FACTURA";
                                            }

                                            if (docLectura.TipoDTE == 61)
                                            {
                                                break;
                                            }
                                        }
                                        //
                                        PrintDocument pd = new PrintDocument();
                                        pd.DefaultPageSettings.PaperSize = new PaperSize("", 284, 1800);
                                        pd.PrintPage += new PrintPageEventHandler(thermal.OpenThermal);
                                        pd.PrinterSettings.PrinterName = Impresora;
                                        Console.WriteLine(pd.ToString());
                                        pd.Print();
                                    }

                                    Pdf docpdf = new Pdf();

                                    String fileNamePDF = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/pdf/DTE_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + "_" + fchName + ".pdf";
                                    docpdf.OpenPdf(TimbreElec, docLectura, fileNamePDF, " ");
                                    log.addLog("Crea PDF Trib TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK");

                                    String fileNamePDFCed = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/pdf/DTE_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + "_" + fchName + "CEDIBLE.pdf";

                                    if (docLectura.TipoDTE == 33 || docLectura.TipoDTE == 34)
                                    {
                                        docpdf.OpenPdf(TimbreElec, docLectura, fileNamePDFCed, "CEDIBLE");
                                    }

                                    if (docLectura.TipoDTE == 52)
                                    {
                                        docpdf.OpenPdf(TimbreElec, docLectura, fileNamePDFCed, "CEDIBLE CON SU FACTURA");
                                    }
                                    log.addLog("Crea PDF C TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK");
                                    log.addLog("IMPRIME TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK");

                                    // Agrega el DTE timbrado al paquete

                                    paquete = paquete + docXmlSign;

                                    //Estrae el rut del emisor de la primera factura del paquete
                                    if (i == 0)
                                    {
                                        firsRut = docLectura.RUTEmisor;
                                    }
                                    i++;



                                    // Firma POaquete unitario
                                    String envioCliente = xml.creaEnvio(paquete, docLectura.RUTEmisor, docLectura.RUTRecep, tipos, docLectura.RutEnvia, docLectura.FchResol, docLectura.RUTRecep, docLectura.NumResol);

                                    String envioSII = xml.creaEnvio(paquete, docLectura.RUTEmisor, docLectura.RUTRecep, tipos, docLectura.RutEnvia, docLectura.FchResol, "", docLectura.NumResol);

                                    X509Certificate2 cert = FuncionesComunes.obtenerCertificado(docLectura.NombreCertificado);

                                    String enviox509SII     = xml.firmarDocumento(envioSII, cert);
                                    String enviox509Cliente = xml.firmarDocumento(envioCliente, cert);

                                    log.addLog("FIRMA ENVIO TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK");

                                    enviox509SII     = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n" + enviox509SII;
                                    enviox509Cliente = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n" + enviox509Cliente;


                                    String fileNameEnvioSII = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/xml/enviounitario/EnvioUnit_" + docLectura.RUTEmisor + "_" + docLectura.Folio + "_" + fchName + ".xml";

                                    String fileNameEnvioCliente = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/xml/enviounitario/EnvioUnitCliente_" + docLectura.RUTEmisor + "_" + docLectura.Folio + "_" + fchName + ".xml";

                                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileNameEnvioSII, false, Encoding.GetEncoding("ISO-8859-1")))
                                    {
                                        file.WriteLine(enviox509SII);
                                    }

                                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileNameEnvioCliente, false, Encoding.GetEncoding("ISO-8859-1")))
                                    {
                                        file.WriteLine(enviox509Cliente);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show("" + ex);
                                }
                                finally
                                {
                                }
                            }
                            else
                            {
                                Pdf docpdf = new Pdf();

                                String fileNamePDF = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/pdf/DTE_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + "_" + fchName + ".pdf";
                                docpdf.OpenPdf(TimbreElec, docLectura, fileNamePDF, " ");
                                log.addLog("Crea PDF Trib TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK");

                                String fileNamePDFCed = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/pdf/DTE_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + "_" + fchName + "CEDIBLE.pdf";

                                if (docLectura.TipoDTE == 33 || docLectura.TipoDTE == 34)
                                {
                                    docpdf.OpenPdf(TimbreElec, docLectura, fileNamePDFCed, "CEDIBLE");
                                }

                                if (docLectura.TipoDTE == 52)
                                {
                                    docpdf.OpenPdf(TimbreElec, docLectura, fileNamePDFCed, "CEDIBLE CON SU FACTURA");
                                }
                                log.addLog("Crea PDF C TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK");

                                // para otro tipo de impresion
                                // FuncionesComunes f = new FuncionesComunes();
                                // f.PrintDocument(@"CutePDF Writer", @""+Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString()+":/IatFiles/file/pdf/DTE_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + "_" + fchName + ".pdf");

                                //Imprime pdf

                                String fileNamePDFPrint = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/pdf/PRINT_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + ".pdf";
                                docpdf.OpenPdfPrint(TimbreElec, docLectura, fileNamePDFPrint);
                                log.addLog("Crea PDF PRINT TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK");



                                fc.printPdf(fileNamePDFPrint, Impresora);

                                log.addLog("IMPRIME TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK");

                                // Agrega el DTE timbrado al paquete

                                paquete = paquete + docXmlSign;

                                //Estrae el rut del emisor de la primera factura del paquete
                                if (i == 0)
                                {
                                    firsRut = docLectura.RUTEmisor;
                                }
                                i++;



                                // Firma POaquete unitario
                                String envioCliente = xml.creaEnvio(paquete, docLectura.RUTEmisor, docLectura.RUTRecep, tipos, docLectura.RutEnvia, docLectura.FchResol, docLectura.RUTRecep, docLectura.NumResol);

                                String envioSII = xml.creaEnvio(paquete, docLectura.RUTEmisor, docLectura.RUTRecep, tipos, docLectura.RutEnvia, docLectura.FchResol, "", docLectura.NumResol);

                                X509Certificate2 cert = FuncionesComunes.obtenerCertificado(docLectura.NombreCertificado);

                                String enviox509SII     = xml.firmarDocumento(envioSII, cert);
                                String enviox509Cliente = xml.firmarDocumento(envioCliente, cert);

                                log.addLog("FIRMA ENVIO TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK");

                                enviox509SII     = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n" + enviox509SII;
                                enviox509Cliente = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n" + enviox509Cliente;


                                String fileNameEnvioSII = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/xml/enviounitario/EnvioUnit_" + docLectura.RUTEmisor + "_" + docLectura.Folio + "_" + fchName + ".xml";

                                String fileNameEnvioCliente = @"" + Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Iat", "unidadIat", null).ToString() + ":/IatFiles/file/xml/enviounitario/EnvioUnitCliente_" + docLectura.RUTEmisor + "_" + docLectura.Folio + "_" + fchName + ".xml";

                                using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileNameEnvioSII, false, Encoding.GetEncoding("ISO-8859-1")))
                                {
                                    file.WriteLine(enviox509SII);
                                }

                                using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileNameEnvioCliente, false, Encoding.GetEncoding("ISO-8859-1")))
                                {
                                    file.WriteLine(enviox509Cliente);
                                }
                            }
                        }

                        // *************  Envía json a server
                        Connect conn = new Connect();
                        String  trib = @"DTE_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + "_" + fchName + ".pdf";
                        String  envU = @"EnvioUnit_" + docLectura.RUTEmisor + "_" + docLectura.Folio + "_" + fchName + ".xml";
                        String  envC = @"EnvioUnitCliente_" + docLectura.RUTEmisor + "_" + docLectura.Folio + "_" + fchName + ".xml";
                        String  envF = @"DTE_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + "_" + fchName + ".xml";
                        String  ced  = String.Empty;
                        if (docLectura.TipoDTE != 61 && docLectura.TipoDTE != 56)
                        {
                            ced = @"DTE_" + docLectura.RUTEmisor + "_" + docLectura.TipoDTE + "_" + docLectura.Folio + "_" + fchName + "CEDIBLE.pdf";
                        }


                        //envia documentos al core
                        conn.sendInvoice(docLectura, trib, ced, envU, envC, envF, "S");
                        // *************  Envía json a server
                        log.addLog("Envia CORE TipoDTE :" + docLectura.TipoDTE + " Folio :" + docLectura.Folio, "OK");
                        // ************  Crea regsitro del ultimo dte
                        UltimoDteSql uDTE = new UltimoDteSql();
                        uDTE.addUltmoDte(docLectura);
                    }
                }
                if (j == printerList.Count())
                {
                    j = 0;
                }
            }
            Console.WriteLine("ProcessIat thread: terminating gracefully.");
        }
Пример #59
0
        /// <summary>
        /// Write property
        /// </summary>
        /// <param name="writer">Stream to write</param>
        public void Write(System.IO.StreamWriter writer)
        {
            CommentWriter.Write(writer, Comment);
            if (Multiline)
            {
                writer.WriteLine(string.Format("{0} {1} {2} {3} {4}", Modifier.ToString().ToLower(),
                                               IsStatic ? "static" : string.Empty,
                                               (SubMethod != SubMethod.None) ? SubMethod.ToString().ToLower() : string.Empty,
                                               Type, GetName(Name)));
                writer.WriteLine("{");

                writer.WriteLine("get");
                writer.WriteLine("{");
                writer.WriteLine(_Get);
                writer.WriteLine("}");

                if (HasSet)
                {
                    writer.WriteLine("set");
                    writer.WriteLine("{");
                    writer.WriteLine(_Set);
                    writer.WriteLine("}");
                }

                writer.WriteLine("}");
            }
            else
            {
                if (HasSet)
                {
                    writer.WriteLine(string.Format("{0} {1} {2} {3} {4} {{ get {{ {5} }} set {{ {6} }} }}", Modifier.ToString().ToLower(),
                                                   IsStatic ? "static" : string.Empty,
                                                   (SubMethod != SubMethod.None) ? SubMethod.ToString().ToLower() : string.Empty,
                                                   Type, GetName(Name), _Get, _Set));
                }
                else
                {
                    writer.WriteLine(string.Format("{0} {1} {2} {3} {4} {{ get {{ {5} }} }}", Modifier.ToString().ToLower(),
                                                   IsStatic ? "static" : string.Empty,
                                                   (SubMethod != SubMethod.None) ? SubMethod.ToString().ToLower() : string.Empty,
                                                   Type, GetName(Name), _Get));
                }
            }
        }
Пример #60
0
        public static void WriteScorecard()
        {
            // This code to find the mobile Download folder is used in several places - perhaps extract to a utility method, and also perhaps think about making the location configurable.
            string filename         = Match.HomeTeam + "v" + Match.AwayTeam + DateTime.Today.ToString("dd-MM-yyyy") + ".html";
            var    pathFile         = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads);
            string fileNameWithPath = Path.Combine(pathFile.ToString(), filename);

            System.IO.StreamWriter file = new System.IO.StreamWriter(fileNameWithPath);

            file.WriteLine("<html>");
            file.WriteLine("<body>");

            file.WriteLine("<pre>");
            file.WriteLine(Match.Venue);
            // Use HTML <table> with large width for player name and dismissal data, then narrow columns for runs, 4, 6, balls.
            file.WriteLine("<table>");
            file.WriteLine("<tr>");
            file.WriteLine("<th width = 50%>Name</th><th>Runs</th><th>4s</th><th>6s</th><th>Balls</th>");
            file.WriteLine("</tr>");
            // file.WriteLine("Name", "Runs", "4s", "6s", "Balls");
            for (int i = 0; i < Teams.teamOnePlayers.Count; i++)
            {
                file.WriteLine("<tr>");
                if (Teams.teamOnePlayers[i].IsOut)
                {
                    file.WriteLine("<td width=50%>{0}</td><TD>Bowled</TD><TD>{1}</td>,<TD>{2}</td>,<TD>{3}</td>,<TD>{4}</td>,<TD>{5}</td>",
                                   Teams.teamOnePlayers[i].Name, Teams.teamTwoPlayers[Teams.teamOnePlayers[i].DismissingBowler].Name,
                                   Teams.teamOnePlayers[i].RunsScored, Teams.teamOnePlayers[i].NumberOfFoursScored,
                                   Teams.teamOnePlayers[i].NumberOfSixesScored, Teams.teamOnePlayers[i].DeliveriesFaced);
                    //file.WriteLine("{0}, Bowled {1}, {2}, {3}, {4}, {5}",
                }

                else
                {
                    file.WriteLine("<td width=50%>{0}</td><TD>Not Out</tD><TD>{1}</td>,<TD>{2}</td>,<TD>{3}</td>,<TD>{4}</td>", Teams.teamOnePlayers[i].Name,
                                   Teams.teamOnePlayers[i].RunsScored, Teams.teamOnePlayers[i].NumberOfFoursScored,
                                   Teams.teamOnePlayers[i].NumberOfSixesScored, Teams.teamOnePlayers[i].DeliveriesFaced);
                    //    file.WriteLine("{0}, Not Out {1}, {2}, {3}, {4}",
                }
                file.WriteLine("</tr>");
            }
            file.WriteLine("</table>");
            // Need a fall of wicket section (Innings class needs new members to store that data)
            file.WriteLine("Fall of wicket"); // Needs not out batsman score

            file.WriteLine("<table>");
            file.WriteLine("<tr>");
            file.WriteLine("<th width = 50%>Name</th><th>Overs</th><th>Maidens</th><th>Runs</th><th>Wickets</th>");
            file.WriteLine("</tr>");
            // file.WriteLine("Name", "Overs", "Maidens", "Runs", "Wickets");
            // Bowling analysis - need another member on player to determine the bowling order
            for (int i = 0; i < Teams.teamTwoPlayers.Count; i++)
            {
                file.WriteLine("<tr>");
                if (Teams.teamTwoPlayers[i].NumberOfOversBowled > 0)
                {
                    file.WriteLine("<td width=50%>{0}</td>Not Out<TD>{1}</td>,<TD>{2}</td>,<TD>{3}</td>,<TD>{4}</td>", Teams.teamTwoPlayers[i].Name, Teams.teamTwoPlayers[i].NumberOfOversBowled,
                                   Teams.teamTwoPlayers[i].NumberOfMaidensBowled, Teams.teamTwoPlayers[i].RunsConceded,
                                   Teams.teamTwoPlayers[i].NumberOfWicketsTaken);
                    //file.WriteLine("{0}, Bowled {1} - {2} - {3} - {4}"
                }
                file.WriteLine("</tr>");
            }
            file.WriteLine("</table>");

            file.WriteLine("<table>");
            file.WriteLine("<tr>");
            file.WriteLine("<th>Byes</th><th>Legbyes</th><th>Wides</th><th>Noballs</th><th>Total</th>");
            file.WriteLine("</tr>");
            // file.WriteLine("Byes", "Legbyes", "Wides", "Noballs", "Total");
            file.WriteLine("<tr>");
            file.WriteLine("<td width=50%>{0}</td>Not Out<TD>{1}</td>,<TD>{2}</td>,<TD>{3}</td>,<TD>{4}</td>", Innings.Byes, Innings.LegByes, Innings.Wides, Innings.NoBalls,
                           (Innings.Byes + Innings.LegByes + Innings.Wides + Innings.NoBalls));
            //file.WriteLine("Extras b({0}),lb ({1}),w ({2}),nb ({3}),   {4}"
            file.WriteLine("</tr>");
            file.WriteLine("</table>");

            file.WriteLine("Total  {0}", Innings.Runs);
            file.WriteLine("</pre>");

            file.WriteLine("</body>");
            file.WriteLine("</html>");

            file.Close();

            return;
        }