Exemple #1
0
 public void Error(Exception ex)
 {
     string str1 = this.formatMessage("error", ex.ToString());
     System.Threading.Monitor.Enter(lockObject);
     try
     {
         try
         {
             System.IO.TextWriter textwriter1 = new System.IO.StreamWriter(this.logFile, true);
             try
             {
                 textwriter1.WriteLine(str1);
             }
             finally
             {
                 if (textwriter1 != null)
                 {
                     textwriter1.Dispose();
                 }
             }
         }
         catch (Exception exception)
         {
             Exception exception1 = exception;
             Console.WriteLine("ERROR: Cannot write log to " + this.logFile + "." + exception1.ToString());
         }
     }
     finally
     {
         System.Threading.Monitor.Exit(lockObject);
     }
 }
Exemple #2
0
        // this code is modfied code from the following tutorial
        // http://blogs.msdn.com/b/mingfeis_code_block/archive/2010/10/03/windows-phone-7-how-to-store-data-and-pass-data-between-pages.aspx
        public void LoadClues()
        {
            EnterClues();
            string elementNumber;

            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                for (int i=0; i < noClues; i++)
                {
                    elementNumber = "number"+clueId[i].ToString();
                    XDocument _doc = new XDocument();
                    XElement _clue = new XElement(elementNumber);
                    XAttribute _clueId = new XAttribute("clueId", clueId[i]);
                    XAttribute _clueText = new XAttribute("clueText", clueText[i]);
                    XAttribute _barcodeRef = new XAttribute("barcodeRef", barcodeRef[i]);
                    XAttribute _location = new XAttribute("location", location[i]);
                    XAttribute _locInfo = new XAttribute("locInfo", locInfo[i]);
                    XAttribute _latitude = new XAttribute("latitude", latitude[i]);
                    XAttribute _longitude = new XAttribute("longitude", longitude[i]);

                    _clue.Add(_clueId, _clueText, _barcodeRef, _location, _locInfo, _latitude, _longitude);

                    _doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), _clue);
                    IsolatedStorageFileStream memory = new IsolatedStorageFileStream(elementNumber + ".clue", System.IO.FileMode.Create, storage);

                    System.IO.StreamWriter file = new System.IO.StreamWriter(memory);
                    _doc.Save(file);

                    file.Dispose();
                    memory.Dispose();
                }

            }
        }
Exemple #3
0
        private void TraceDispose()
        {
            lock (_streamLock)
            {
                try
                {
                    if (_traceStream == null)
                    {
                        return;
                    }

                    _traceStream.Close();
                    if (string.IsNullOrWhiteSpace(_directory))
                    {
                        _fileSystem.File.Delete(_traceFilePath);
                    }
                    else
                    {
                        _fileSystem.File.Move(_traceFilePath,
                                              _fileSystem.Path.Combine(_directory,
                                                                       _fileSystem.Path.GetFileNameWithoutExtension(_traceFilePath) + " final.csv"));
                    }
                }
                finally
                {
                    _traceStream?.Dispose();
                    _traceStream = null;
                }
            }
        }
Exemple #4
0
            public writeReadFile()
            {

                //Create a try catch block to make sure that that memory is recoverted. 
                try
                {
                    //Tell the user about writing a new file.
                    Console.WriteLine("Press any key to write a random double file to the same directory.");
                    Console.ReadKey();
                    using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter("fileOfGarbage.txt"))
                    {
                        //Create a new random double.
                        Random randGarbageDouble = new Random();
                        //Write random generated numbers to the text file
                        for (int countToGarbageTotalNumber = 0; countToGarbageTotalNumber < 10000000; countToGarbageTotalNumber++)
                        {
                            streamWriter.WriteLine((randGarbageDouble.NextDouble() * (99999999999.999999 - 1) + 1).ToString());
                        }
                        showMemoryUsage();
                        //Flush, dispose, and Close the stream writer.
                        streamWriter.Flush();
                        streamWriter.Dispose();
                        streamWriter.Close();
                        showMemoryUsage();
                    }
                    showMemoryUsage();
                    Console.WriteLine("Press any key to read the random double file in the same directory.");
                    Console.ReadKey();
                    //Create a new double to be collected.
                    double[] garbageArrayString = new double[10000000];
                    //Read everything that was written into an array.
                    using (System.IO.StreamReader streamReader = new System.IO.StreamReader("fileOfGarbage.txt"))
                    {
                        //Create a string to hold the line
                        string line;
                        //create an int to hold the linecount
                        int countOfGarbageLine = 0;
                        while ((line = streamReader.ReadLine()) != null)
                        {
                            garbageArrayString[countOfGarbageLine++] = double.Parse(line);
                        }
                        showMemoryUsage();
                        //Flush, dispose, and Close the stream writer.
                        streamReader.Dispose();
                        streamReader.Close();
                        //Nullify the garbage array string for collection.
                        garbageArrayString = null;
                        countOfGarbageLine = 0;
                        showMemoryUsage();
                    }
                }
                //Finally is not needed as variables are cleared in the using statements.
                finally
                {
                    //Run garbage collection to be sure.
                    GC.Collect();
                    showMemoryUsage();
                }
            }
Exemple #5
0
 public void Write() {
     using (var writer = new System.IO.StreamWriter(env.ROOT + "log", true)) {
         for (int i = 0; i < queue.Count; ++i)
             writer.Write(queue[i]);
         writer.Dispose();
     }
     queue.Clear();
 }
 private void addToFile(string ln)
 {
     System.IO.FileStream txt = new System.IO.FileStream("logsg.txt", System.IO.FileMode.Append);
     System.IO.StreamWriter trw = new System.IO.StreamWriter(txt);
     trw.WriteLine(ln);
     trw.Close();
     trw.Dispose();
 }
Exemple #7
0
 public static void PrintData(string path = "rf.dat")
 {
     System.IO.StreamWriter write = new System.IO.StreamWriter(path,false);
     foreach(string cmd in Commands)
     {
         write.WriteLine(cmd);
     }
     write.Dispose();
 }
Exemple #8
0
 static void logErr(string str)
 {
     string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
     string logPath = path + "\\Info-TC7.txt";
     System.IO.StreamWriter file = new System.IO.StreamWriter(logPath, true);
     file.WriteLine(str);
     file.Close();
     file.Dispose();
 }
Exemple #9
0
        static void Main(string[] args)
        {
            bool[] nullornot = new bool[10];
            // DefineTest.run();
            //Instruction ins = new Instruction(15, new string[] { "eax", "ecx" });
            //ins.printAssemblyInstruction();
            //ins.PrintBinaryInstruction();
            //Environment.Exit(0);
             //outloc = args[0] + ".lex";
            //Console.WriteLine(EnumKeywords.PUBLIC.ToString());
            //Console.ReadKey();
            //Environment.Exit(0);
            writer = new System.IO.StreamWriter(currentdir + args[0] + ".lex");
            lines = System.IO.File.ReadAllLines(currentdir + args[0]);
            //Console.WriteLine(operators.Count);
            //Console.WriteLine(keywords.Count);
            //Console.WriteLine(Convert.ToString((EnumOperator)1));
            for (int i = 0; i < lines.Length; i++)
            {
                //if(System.Text.RegularExpressions.Regex.IsMatch(lines[i], @"//.*|/\*([~/]|\*[~/])*\*+/"));
                //{
                //    continue;
                //}
                if (lines[i].StartsWith("//"))
                {
                    continue;
                }
                Console.WriteLine(lines[i]);
                Lexer.Start(ref lines, ref i,writer);
            }

            writer.Flush();
            writer.Close();
            writer.Dispose();
            Console.WriteLine("Lexical Analasis Complete");
            for (int i = 0; i < Lexer.pubtokenslist.Count; i++ )
            {
                for (int j = 0; j < Lexer.pubtokenslist.ElementAt<string[]>(i).Length; j++ )
                {
                    if (Lexer.pubtokenslist.ElementAt<string[]>(i)[j] == null)
                    {
                        nullornot[j] = true;
                    }
                }
                if (checknull(nullornot))
                {
                    continue;
                }
                AST<dynamic, dynamic, dynamic, dynamic> tokentree = new AST<dynamic, dynamic, dynamic, dynamic>(Lexer.pubtokenslist.ElementAt<string[]>(i));
                Parser parse = new Parser(tokentree,ref i);
            }

            Console.WriteLine("Compilation Complete");
            Console.WriteLine("Press Any Key To Exit");
            Console.ReadKey();
        }
Exemple #10
0
 public static void writedebuglog(string dblog) {
     System.IO.StreamWriter sw = new System.IO.StreamWriter("uwizard_debuglog.txt", true);
     sw.WriteLine("This debug log was generated by Uwizard " + getVerText(myversion) + " :");
     sw.WriteLine();
     sw.WriteLine(dblog);
     sw.WriteLine();
     sw.WriteLine();
     sw.Close();
     sw.Dispose();
 }
 private void button2_Click(object sender, EventArgs e)
 {
     System.IO.FileStream objfile;
     saveFileDialog1.ShowDialog();
     objfile = System.IO.File.Create(@saveFileDialog1.FileName);
     objfile.Close();
     objfile.Dispose();
     System.IO.StreamWriter objfil = new System.IO.StreamWriter(@saveFileDialog1.FileName);
     objfil.Write(textBox1.Text);
     objfil.Close();
     objfil.Dispose();
 }
Exemple #12
0
        ///
        /// <summary>
        /// Closes the log file
        /// </summary>
        ///
        public void Close()
        {
            if (m_file != null)
            {
                m_file.Flush();
#if DOTNET5_4
                m_file.Dispose();
#else
                m_file.Close();
#endif
            }
        }
        public static void SplitCsv_byitemcount(string file, string prefix, int itemcount)
        {
            // Read lines from source file
            string strDir = System.IO.Path.GetDirectoryName(file);
            string[] arr = System.IO.File.ReadAllLines(file);

            string headerrow = string.Empty;

            if (arr.LongLength > 0)
            {
                headerrow = arr[0];
            }

            int total = 0;
            int num = 0;
            var writer = new System.IO.StreamWriter(System.IO.Path.Combine(strDir, GetFileName(prefix, num)),true, System.Text.Encoding.UTF8);
            writer.WriteLine(headerrow);

            //Having Content in Array since first row is header
            if (arr.LongLength > 1)
            {
                for (int i = 1; i < arr.Length; i++)
                {

                    // Current line
                    string line = arr[i];
                    // Length of current line
                    int currentItemCount = i;

                    // See if adding this line would exceed the size threshold
                    if (total >= itemcount)
                    {
                        // Create a new file
                        num++;
                        total = 0;
                        writer.Dispose();
                        writer = new System.IO.StreamWriter(System.IO.Path.Combine(strDir, GetFileName(prefix, num)), true, System.Text.Encoding.UTF8);
                        writer.WriteLine(headerrow);
                    }
                    // Write the line to the current file
                    writer.WriteLine(line);

                    // Add item count
                    total += 1;

                }

            }
            // Loop through all source lines

            writer.Dispose();
        }
        public void ScoreRangeCalculator()
        {
            int simulationCount = 500000;
            var scoreResults    = new Dictionary <int, IList <double> >();
            var scoreRanges     = new List <ScoreRange>();

            var deck  = new Deck();
            var cards = new List <Card>();
            var hand  = new List <Card>();

            for (int i = 3; i < 4; i++)
            {
                var numberOfCards = i + 2;
                scoreResults.Add(numberOfCards, new List <double>());

                for (int u = 0; u < simulationCount; u++)
                {
                    deck.Regroup();
                    deck.Shuffle();

                    cards.Clear();
                    hand.Clear();
                    for (int j = 0; j < numberOfCards; j++)
                    {
                        cards.Add(deck.Draw());
                    }

                    var cardCombination = _combinationEvaluator.EvaluateCards(cards);



                    scoreResults[numberOfCards].Add(cardCombination.Score);
                }
            }

            var str = String.Join("\n", scoreResults.Values.First().ToList().OrderBy(v => v).Select(v => v.ToString()));


            //foreach (var keyValuePair in scoreResults.ToList())
            //{
            //    var max = keyValuePair.Value.OrderByDescending(v => v).First();
            //    var min = keyValuePair.Value.OrderByDescending(v => v).Last();
            //    scoreRanges.Add(new ScoreRange(keyValuePair.Key, min, max));
            //}

            var logPath   = System.IO.Path.GetTempFileName();
            var logFile   = System.IO.File.Create(logPath);
            var logWriter = new System.IO.StreamWriter(logFile);

            logWriter.WriteLine(str);
            logWriter.Dispose();
        }
Exemple #15
0
        static void Main(string[] args)
        {
            string file1 = System.IO.File.ReadAllText(@"/Users/michaelsilberstein/launch_academy/output_file.txt");

            string[] file2 = System.IO.File.ReadAllLines(@"/Users/michaelsilberstein/launch_academy/output_file2.txt");
            Console.WriteLine(file1);

            foreach (var line in file2)
            {
                Console.WriteLine(line);
            }

            string text = "This is the new information";

            System.IO.File.WriteAllText(@"/Users/michaelsilberstein/launch_academy/output_file3.txt", text);

            string[] lines = { "This is line1", "This is line2", "This is line3" };

            System.IO.File.WriteAllLines(@"/Users/michaelsilberstein/launch_academy/output_file4.txt", lines);

            //           using(System.IO.StreamWriter writer =  new System.IO.StreamWriter(@"/Users/michaelsilberstein/launch_academy/output_file5.txt"))
            //          {
            //               foreach (var line in lines)
            //               {
            //                   writer.WriteLine(line);
            //                   writer.Dispose();
            //               }
            //           }


            System.IO.StreamWriter writer = null;
            try
            {
                writer = new System.IO.StreamWriter(@"/Users/michaelsilberstein/launch_academy/");
                foreach (var line in lines)
                {
                    writer.WriteLine(line);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            finally
            {
                if (writer != null)
                {
                    writer.Dispose();
                }
            }
        }
Exemple #16
0
        private void Save_selected_windows()
        {
            SaveFileDialog save = new SaveFileDialog()
            {
                Title = "Save fittng data", FileName = Form2.file_name, Filter = "Data Files (*.wf)|*.wf", DefaultExt = "wf", OverwritePrompt = true, AddExtension = true
            };

            //save.InitialDirectory = Application.StartupPath + "\\Data";
            //DirectoryInfo di = new DirectoryInfo(save.InitialDirectory);
            //if (di.Exists != true) di.Create();

            if (save.ShowDialog() == DialogResult.OK)
            {
                System.IO.StreamWriter file = new System.IO.StreamWriter(save.OpenFile());  // Create the path and filename.

                file.WriteLine("Mode:\texternal data");
                file.WriteLine("AA Sequence:\t" + Form2.Peptide);
                file.WriteLine("Fitted isotopes:\t" + Form2.candidate_fragments.ToString());
                file.WriteLine("m/z[Da]\tIntensity");
                file.WriteLine();
                file.WriteLine("Name:\tExp");
                foreach (double[] p in Form2.selected_all_data[0])
                {
                    file.WriteLine(p[0] + "\t" + p[1]);
                }
                file.WriteLine();
                foreach (int w in selected_windows_to_save.OrderBy(p => p).ToList())
                {
                    file.WriteLine("Window:\t" + Form2.windowList[w].Code.ToString().ToString());
                    file.WriteLine("Starting:\t" + Form2.windowList[w].Starting);
                    file.WriteLine("Ending:\t" + Form2.windowList[w].Ending);
                    for (int i = 0; i < Form2.windowList[w].Mono_fragments.Count; i++)
                    {
                        int indexS = Form2.windowList[w].Mono_fragments[i];
                        file.WriteLine("Name:\t" + Form2.Fragments2[indexS - 1].Name);
                        file.WriteLine("Factor:\t" + Form2.Fragments2[indexS - 1].Factor);
                        file.WriteLine("Fix:\t" + Form2.Fragments2[indexS - 1].Fix);
                        file.WriteLine("Centroid:\t" + Form2.Fragments2[indexS - 1].Centroid[0].X + "\t" + Form2.Fragments2[indexS - 1].Centroid[0].Y);
                        file.WriteLine("ListViewItems:\t" + Form2.Fragments2[indexS - 1].ListName[0].ToString() + "\t" + Form2.Fragments2[indexS - 1].ListName[1].ToString() + "\t" + Form2.Fragments2[indexS - 1].ListName[2].ToString() + "\t" + Form2.Fragments2[indexS - 1].ListName[3].ToString());
                        file.WriteLine("Selected:\t" + Form2.Fragments2[indexS - 1].To_plot.ToString());
                        file.WriteLine("Color:\t" + Form2.Fragments2[indexS - 1].Color.ToColor().ToArgb());
                        foreach (double[] p in Form2.all_data[indexS])
                        {
                            file.WriteLine(p[0] + "\t" + p[1]);
                        }
                        file.WriteLine();
                    }
                }

                file.Flush(); file.Close(); file.Dispose();
            }
        }
Exemple #17
0
        public static void SplitCsv_byitemcount(string file, string prefix, int itemcount)
        {
            // Read lines from source file
            string strDir = System.IO.Path.GetDirectoryName(file);

            string[] arr = System.IO.File.ReadAllLines(file);


            string headerrow = string.Empty;

            if (arr.LongLength > 0)
            {
                headerrow = arr[0];
            }

            int total  = 0;
            int num    = 0;
            var writer = new System.IO.StreamWriter(System.IO.Path.Combine(strDir, GetFileName(prefix, num)), true, System.Text.Encoding.UTF8);

            writer.WriteLine(headerrow);

            //Having Content in Array since first row is header
            if (arr.LongLength > 1)
            {
                for (int i = 1; i < arr.Length; i++)
                {
                    // Current line
                    string line = arr[i];
                    // Length of current line
                    int currentItemCount = i;

                    // See if adding this line would exceed the size threshold
                    if (total >= itemcount)
                    {
                        // Create a new file
                        num++;
                        total = 0;
                        writer.Dispose();
                        writer = new System.IO.StreamWriter(System.IO.Path.Combine(strDir, GetFileName(prefix, num)), true, System.Text.Encoding.UTF8);
                        writer.WriteLine(headerrow);
                    }
                    // Write the line to the current file
                    writer.WriteLine(line);

                    // Add item count
                    total += 1;
                }
            }
            // Loop through all source lines

            writer.Dispose();
        }
Exemple #18
0
        public override void DoEvent(FileManager fm)
        {
            var x = fm.GetPathEnd(this.Path).Result;

            x.GetInfoFile().GetItem(this.GroupPath).ChangeInfoBySyncString(Value, Time);
            var w = new System.IO.StreamWriter(FileManager.PathToHFOFolder + x.GetInfoFilePath());

            try
            {
                x.GetInfoFile().RewriteFile(w);
            }
            finally { w.Dispose(); }
        }
Exemple #19
0
        /// <summary>
        /// write / over write the settings.ini file
        /// </summary>
        public void WriteSettings()
        {
            System.IO.TextWriter WriteSettings = new System.IO.StreamWriter(".\\settings.ini");

            WriteSettings.WriteLine("Settings: with great powers comes with great responsibility");
            WriteSettings.WriteLine(string.Format("{0}", IgnoreEmptyTranslation_));
            WriteSettings.WriteLine(string.Format("{0}", IgnoreLineNumberCheck_));
            WriteSettings.WriteLine(string.Format("{0}", IgnoreEmptyLyrics_));
            WriteSettings.WriteLine(string.Format("{0}", WrapTranslation_));
            WriteSettings.WriteLine(string.Format("{0}", Wrapper_.ToString()));

            WriteSettings.Close(); WriteSettings.Dispose();
        }
        /// <summary>
        /// 添加文本日志记录
        /// </summary>
        /// <param name="message"></param>
        public static void AddLogInfo(string message)
        {
            var logPath = System.IO.Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "log.txt");

            if (!System.IO.File.Exists(logPath))
            {
                System.IO.File.Create(logPath);
            }
            System.IO.StreamWriter sw = new System.IO.StreamWriter(logPath, true);
            sw.WriteLine(message);
            sw.Close();
            sw.Dispose();
        }
Exemple #21
0
 public static void WriteFile(string Path, string Strings)
 {
     if (!System.IO.File.Exists(Path))
     {
         System.IO.FileStream f = System.IO.File.Create(Path);
         f.Close();
         f.Dispose();
     }
     System.IO.StreamWriter f2 = new System.IO.StreamWriter(Path, true, System.Text.Encoding.UTF8);
     f2.WriteLine(Strings);
     f2.Close();
     f2.Dispose();
 }
Exemple #22
0
        public bool SaveOrder(Order order)
        {
            System.IO.StreamWriter sw
                = new System.IO.StreamWriter(@"c:\test\orders.csv", true);

            sw.WriteLine($"Order,{order.CustomerName}" +
                         $",{order.EmployeeName},{order.TotalPrice}");

            sw.Close();
            sw.Dispose();

            return(true);
        }
 public static void DumpObject(MapObject mo, int zone)
 {
     try {
         System.IO.StreamWriter s = System.IO.File.AppendText("LostObjects.txt");
         s.WriteLine("zone= \"" + zone.ToString() + "\"; name=\"" + mo.strName + "\"; x=\"" + mo.BasePoint.x + "\"; y=\"" + mo.BasePoint.y + "\"");
         s.Flush();
         s.Close();
         s.Dispose();
     }
     catch (Exception e) {
         throw new Exception("error writing lost objects file", e);
     }
 }
        public static void AddWord(string path, string word)
        {
            var _writeStream = new System.IO.FileStream(path,
                                                        System.IO.FileMode.Append,
                                                        System.IO.FileAccess.Write,
                                                        System.IO.FileShare.ReadWrite);
            var _writer = new System.IO.StreamWriter(_writeStream, System.Text.Encoding.UTF8, 128);

            _writer.WriteLine(word);

            _writer.Dispose();
            _writeStream.Dispose();
        }
 public void Complete()
 {
     if (currentNamespace != null)
     {
         //close the last namespace section
         WriteLine("}</pre>", 0);
         WriteLine("Generated with (.NET Object Model Diagram Generator)[https://github.com/dotMorten/DotNetOMDGenerator]", 0);
         sw.Flush();
     }
     sw.Flush();
     sw.Close();
     sw.Dispose();
 }
 public static void Write_File(string path, string Write, bool GhiTiepVaoFile, ref List <string> Output)
 {
     Check_Exits(path);
     try
     {
         System.IO.StreamWriter GhiFile = new System.IO.StreamWriter(path, GhiTiepVaoFile, System.Text.Encoding.Unicode);
         GhiFile.WriteLine(Write);
         GhiFile.Close();
         GhiFile.Dispose();
         Output.Add(Write);
     }
     catch { }
 }
Exemple #27
0
        private void saveFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            saveFileDialog.Title  = "Save an Output File";
            //
            if (saveVertices.Count != 0)
            {
                this.dataNumber++;
                Voronoi       voronoi        = new Voronoi(saveVertices.Count);
                List <Vertex> sortedVertices = saveVertices.OrderBy(o => o.x).ToList();
                sortedVertices = voronoi.y_sorting(sortedVertices);
                for (int i = 0; i < sortedVertices.Count; i++)
                {
                    voronoi.setVertex(sortedVertices[i].x, sortedVertices[i].y);
                }
                this.voronoiList.Add(voronoi);
            }

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                System.IO.StreamWriter writer = new System.IO.StreamWriter(saveFileDialog.OpenFile());
                for (int j = 0; j < voronoiList[dataNumber].Num; j++)
                {
                    writer.WriteLine("P " + voronoiList[dataNumber].getVertex(j).x + " " + voronoiList[dataNumber].getVertex(j).y);
                }
                if (voronoiList[dataNumber].HPs.Count != 0)
                {
                    for (int j = 0; j < voronoiList[dataNumber].HPs.Count; j++)
                    {
                        if (voronoiList[dataNumber].HPs[j].is_line)
                        {
                            writer.WriteLine("E " + voronoiList[dataNumber].HPs[j].start_vertex.x + " " + voronoiList[dataNumber].HPs[j].start_vertex.y + " " + voronoiList[dataNumber].HPs[j].end_vertex.x + " " + voronoiList[dataNumber].HPs[j].end_vertex.y);
                        }
                        if (voronoiList[dataNumber].HPs[j].start_vertex.infinity && voronoiList[dataNumber].HPs[j].end_vertex.infinity)
                        {
                            continue;
                        }
                        writer.WriteLine("E " + voronoiList[dataNumber].HPs[j].start_vertex.x + " " + voronoiList[dataNumber].HPs[j].start_vertex.y + " " + voronoiList[dataNumber].HPs[j].end_vertex.x + " " + voronoiList[dataNumber].HPs[j].end_vertex.y);
                    }
                }
                writer.Dispose();
                writer.Close();
            }
            canvas.Clear(Color.White);
            saveVertices.Clear();
            voronoiList.Clear();
            Es.Clear();
            Ps.Clear();
        }
Exemple #28
0
 public static void WriteTextLog(string LogStr)
 {
     try
     {
         var Writer = new System.IO.StreamWriter(@"c:\ITXProjectGovernanceReport.txt", true);
         Writer.WriteLine(LogStr);
         Writer.Close();
         Writer.Dispose();
     }
     catch
     {
         return;
     }
 }
Exemple #29
0
        static PathSettings CreateInstance()
        {
            string src = "using System;\n";

            src += "using System.ComponentModel;\n";
            src += "namespace SimPe{\n";
            src += "public class RuntimePathSettings : PathSettings { \n";

            src += "\tpublic RuntimePathSettings() : base(Helper.WindowsRegistry){\n";
            src += "\t}\n\n\n";

            foreach (ExpansionItem ei in PathProvider.Global.Expansions)
            {
                src += "\t[Category(\"" + ei.Flag.Class + "\"), System.ComponentModel.Editor(typeof(SimPe.SelectSimFolderUITypeEditor), typeof(System.Drawing.Design.UITypeEditor)),\n";
                src += "\tDescription(\"" + SimPe.Localization.GetString("[Description:]").Replace("{LongName}", ei.Name).Trim().Replace(Helper.lbr, "\\n") + "\"), ";
                src += "DisplayName(\"" + ei.NameSortNumber + ": " + ei.NameShorter + "\")]\n";
                src += "\tpublic string " + ei.ShortId + "Path\n";
                src += "\t{\n";
                src += "\t\tget {\n";
                src += "\t\t\treturn GetPath(PathProvider.Global.GetExpansion(" + ei.Version + "));\n";
                src += "\t\t}\n";
                src += "\t\tset {PathProvider.Global.GetExpansion(" + ei.Version + ").InstallFolder = value;}\n";
                src += "\t}\n\n";
            }

            src += "}}\n";

            try
            {
                System.Reflection.Assembly a = SimPe.RuntimeCompiler.Compile(src, new string[] {
                    System.IO.Path.Combine(Helper.SimPePath, "simpe.helper.dll"),
                    "system.drawing.dll"
                });
                return((PathSettings)SimPe.RuntimeCompiler.CreateInstance(a, "SimPe.RuntimePathSettings", new object[0]));
            }
            catch (Exception ex)
            {
                if (Helper.DebugMode || Helper.QARelease)
                {
                    System.IO.StreamWriter sw = new System.IO.StreamWriter(System.IO.Path.Combine(Helper.SimPePath, "RuntimePathSettings.cs"));
                    sw.Write(src);
                    sw.Close();
                    sw.Dispose();
                    sw = null;

                    Helper.ExceptionMessage(ex);
                }
                return(null);
            }
        }
Exemple #30
0
 private static void WriteTextLog(string LogStr)
 {
     try
     {
         var Writer = new System.IO.StreamWriter(@"c:\CIMBTimeSheet.txt", true);
         Writer.WriteLine(LogStr);
         Writer.Close();
         Writer.Dispose();
     }
     catch (Exception)
     {
         return;
     }
 }
Exemple #31
0
 static void SaveTutorials(string cont)
 {
     System.IO.StreamWriter sw = System.IO.File.CreateText(TutorialTempFile);
     try
     {
         sw.Write(cont);
     }
     finally
     {
         sw.Close();
         sw.Dispose();
         sw = null;
     }
 }
Exemple #32
0
 private void BtnConn_Click_1(object sender, EventArgs e)
 {
     try
     {
         if (cbPorts.Text != "")
         {
             if (cbBaud.Text != "")
             {
                 serialPort1.PortName      = cbPorts.Text;
                 serialPort1.BaudRate      = Convert.ToInt32(cbBaud.Text);
                 serialPort1.Parity        = (Parity)Enum.Parse(typeof(Parity), cbParity.Text);
                 serialPort1.StopBits      = (StopBits)Enum.Parse(typeof(StopBits), cbStopbits.Text);
                 serialPort1.DataBits      = Convert.ToInt32(cbDatabits.Text);
                 serialPort1.Handshake     = Handshake.None;
                 serialPort1.RtsEnable     = true;
                 serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
                 if (serialPort1.IsOpen)
                 {
                     return;
                 }
                 serialPort1.Open();
                 btnConn.Enabled    = false;
                 btnDisConn.Enabled = true;
                 //
                 cbBaud.Enabled     = false;
                 cbPorts.Enabled    = false;
                 cbDatabits.Enabled = false;
                 cbStopbits.Enabled = false;
                 cbParity.Enabled   = false;
                 if (datalogger_checkbox.Checked)
                 {
                     try { out_file.Dispose(); }
                     catch { /*ignore*/ }
                 }
             }
             else
             {
                 return;
             }
         }
         else
         {
             return;
         }
     }
     catch
     {
         return;
     }
 }
Exemple #33
0
 private void mOptionSqlMonitor_Click(object sender, RoutedEventArgs e)
 {
     if (swSqlWriter == null)
     {
         swSqlWriter = SqlMonitor.OpenSqlFile();
     }
     else
     {
         swSqlWriter.Close();
         swSqlWriter.Dispose();
         swSqlWriter = null;
         MessageBox.Show("已停止监视。", "消息", MessageBoxButton.OK, MessageBoxImage.Information);
     }
 }
Exemple #34
0
 public void CheckTimeLog(string txt)
 {
     try
     {
         string filePath           = "c:\\time_log.txt";
         System.IO.StreamWriter wr = new System.IO.StreamWriter(filePath, true);
         wr.WriteLine(string.Format("[{0}] {1}", DateTime.Now.ToString("dd/MM/yy HH:mm:ss:fff"), txt));
         wr.Dispose();
         wr.Close();
     }
     catch (Exception)
     {
     }
 }
        // 儲存 shapes information 成 json file
        private void SaveFile(List <Shape> shapes, string directory)
        {
            ShapesConverter converter = new ShapesConverter();

            converter.ConvertToText(shapes);
            string text             = converter.Text;
            string currentDirectory = directory;
            string filePath         = Constant.FILE_NAME;

            System.IO.StreamWriter file = new System.IO.StreamWriter(filePath, false);
            file.Write(text);
            file.Close();
            file.Dispose();
        }
Exemple #36
0
        /// <summary>
        /// Returns the effective Transformation, that is described by the CresHirarchy
        /// </summary>
        /// <returns></returns>
        public VectorTransformation GetEffectiveTransformation()
        {
            VectorTransformations list = GetHirarchyTransformations();
            VectorTransformation  v    = new VectorTransformation();

#if DEBUG
            System.IO.StreamWriter sw = System.IO.File.CreateText(@"G:\effect.txt");
#endif
            try
            {
#if DEBUG
                sw.WriteLine("-----------------------------------");
                sw.WriteLine("    " + v.ToString());
#endif


                VectorTransformation l = null;
                for (int i = list.Length - 1; i >= 0; i--)
                {
                    VectorTransformation t = list[i];
                    t.Rotation.MakeUnitQuaternion();



                    v.Rotation    = v.Rotation * t.Rotation;
                    v.Translation = t.Rotation.Rotate((v.Translation)) - t.Rotation.Rotate((t.Translation));
                    //v.Rotation.MakeUnitQuaternion();


#if DEBUG
                    sw.WriteLine("++++" + t.ToString() + " " + t.Name);
                    sw.WriteLine("    " + v.ToString());
#endif



                    l = t;
                }
            }
            finally
            {
#if DEBUG
                sw.Close();
                sw.Dispose();
                sw = null;
#endif
            }

            return(v);
        }
Exemple #37
0
 protected virtual void Dispose(bool disposing)
 {
     if (!m_Disposed)
     {
         if (fileStream != null)
         {
             if (disposing)
             {
                 fileStream.Dispose();
             }
         }
         m_Disposed = true;
     }
 }
Exemple #38
0
        public String SavaProcess(string data)
        {
            String FilePath = "I:\\c#项目\\BookMannage\\BookMannage\\BookFile.txt";

            //文件覆盖方式添加内容
            System.IO.StreamWriter file = new System.IO.StreamWriter(FilePath, false);
            //保存数据到文件
            file.Write(data);

            file.Close();
            file.Dispose();

            return(FilePath);
        }
Exemple #39
0
        /// <summary>
        /// 保存数据data到文件处理过程,返回值为保存的文件名
        /// </summary>
        private static void SaveFile(String data, String filePath)
        {
            //string CurDir = System.AppDomain.CurrentDomain.BaseDirectory + @"SaveDir\";    //设置当前目录
            //if (!System.IO.Directory.Exists(CurDir)) System.IO.Directory.CreateDirectory(CurDir);   //该路径不存在时,在当前文件目录下创建文件夹"导出.."

            ////不存在该文件时先创建
            //String filePath = CurDir + name + ".txt";
            System.IO.StreamWriter file1 = new System.IO.StreamWriter(filePath, false);     //文件已覆盖方式添加内容

            file1.Write(data);                                                              //保存数据到文件

            file1.Close();                                                                  //关闭文件
            file1.Dispose();                                                                //释放对象
        }
Exemple #40
0
 public void ClearLogFile()
 {
     if (System.IO.File.Exists(settingsFile))
     {
         try
         {
             System.IO.StreamWriter fileWriter = new System.IO.StreamWriter(System.IO.Path.GetDirectoryName(executableURL) + "\\MomentumStrategyModule.log", false);
             fileWriter.WriteLine("");
             fileWriter.Dispose();
             fileWriter.Close();
         }
         finally {}
     }
 }
Exemple #41
0
        public async Task Post([FromBody] string value)
        {
            value = value.ToHtml();
            var logPath   = $@"C:\Gangstabit\{DateTime.UtcNow.Ticks}.html";
            var logFile   = System.IO.File.Create(logPath);
            var logWriter = new System.IO.StreamWriter(logFile);

            logWriter.WriteLine(value);
            logWriter.Dispose();

            value = HttpUtility.HtmlDecode(value);
            var game = _gameInterpretor.InterpreteGameFromHtml(value, logPath);
            await _gameRepository.SaveGameAsync(game).ConfigureAwait(false);
        }
Exemple #42
0
        static FrameIDFactory()
        {
            CreateEntries();
            #if generate
            var writer = new System.IO.StreamWriter(@"C:\Temp\table.txt");
            _entries = new List<ID3v2FrameEntry>();

            var elements = Enum.GetNames(typeof(ID3v2FrameID));
            foreach (var element in elements)
            {
                var id = Enum.Parse(typeof(ID3v2FrameID), element);
                var id3v4ID = ID3v2FrameIDFactory.GetID((ID3v2FrameID)id, ID3Version.ID3v2_4);
                string id3v3ID;
                try
                {
                    id3v3ID = ID3v2FrameIDFactory.GetID((ID3v2FrameID)id, ID3Version.ID3v2_3);
                }
                catch (Exception)
                {
                    id3v3ID = null;
                }
                string id3v2ID;
                try
                {
                    id3v2ID = ID3v2FrameIDFactory.GetID((ID3v2FrameID)id, ID3Version.ID3v2_2);
                }
                catch (Exception)
                {
                    id3v2ID = null;
                }

                StringBuilder builder = new StringBuilder();
                builder.AppendLine("                entry = new ID3v2FrameEntry()");
                builder.AppendLine("                {");
                builder.AppendLine(String.Format("                    ID = ID3v2FrameID.{0},", ((ID3v2FrameID)id).ToString()));
                builder.AppendLine(String.Format("                    ID3v4ID = {0},", id3v4ID == null ? "null" : "\"" + id3v4ID + "\""));
                builder.AppendLine(String.Format("                    ID3v3ID = {0},", id3v3ID == null ? "null" : "\"" + id3v3ID + "\""));
                builder.AppendLine(String.Format("                    ID3v2ID = {0},", id3v2ID == null ? "null" : "\"" + id3v2ID + "\""));
                builder.AppendLine(String.Format("                    Desc = \"{0}\"", element));
                builder.AppendLine("                };");
                builder.AppendLine("                _entries.Add(entry);");
                writer.WriteLine(builder.ToString());
                writer.WriteLine();
                writer.WriteLine();
            }
            writer.Flush();
            writer.Dispose();
            #endif
        }
Exemple #43
0
 public void SaveArrayToFile()
 {
     int count;
     var writer = new System.IO.StreamWriter("C:/calc/calculations.txt", false);
     for (count = 0; count <= Results.Length - 1; count++)
     {
         if (Results[count] == 0)
         {
             continue;
         }
         writer.Write(Results[count]);
         writer.WriteLine();
     }
     writer.Dispose();
 }
Exemple #44
0
        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="path"></param>
        /// <param name="append"></param>
        /// <param name="ErrStr"></param>
        public static void WriteLog(string path, bool append, string ErrStr)
        {
            if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(path)))
            {
                System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path));
            }
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(path, append))
            {
                writer.WriteLine(ErrStr);

                writer.Flush();

                writer.Dispose();
            }
        }
Exemple #45
0
        protected void Application_Error(object sender, EventArgs e)
        {
            string strPath = "";
            string strPathName = "";
            string strErrorMessage = "";

            if ((Server != null) && (Server.GetLastError() != null) && (Server.GetLastError().GetBaseException() != null))
            {
                System.Exception ex = Server.GetLastError().GetBaseException();

                strErrorMessage = "'<b>" + ex.Message + "'</b> Occured on " + System.DateTime.Now.ToString("yyyy/mm/dd - hh:mm:ss");
                strErrorMessage += "<br />Error Message: " + strErrorMessage;
                strErrorMessage += "<br />User IP: " + Request.UserHostAddress;
                strErrorMessage += "<br />Physical Path: " + Request.PhysicalPath;

                //Server.ClearError();

                Response.Write("<br />" + strErrorMessage + "<br /><br />");
            }

            System.IO.StreamWriter sw = null;
            strPath = Server.MapPath("~/bin/");
            strPathName = strPath + "\\ApplicationError.log";

            Application.Lock();

            try
            {
                sw = new System.IO.StreamWriter(strPathName, true, System.Text.Encoding.UTF8);
                sw.Write("Application Error:\r\n" + strErrorMessage.Replace("<br />", "\r\n") + "\r\n");
                sw.Close();
            }
            catch (Exception ex)
            {
                Response.Write("<br />" + ex.Message);
            }
            finally
            {
                if (sw != null)
                {
                    sw.Dispose();
                    sw = null;
                }
            }

            Application.UnLock();
        }
        protected void Application_Error(object sender, EventArgs e)
        {
            System.IO.StreamWriter sw = new System.IO.StreamWriter(HttpContext.Current.Request.PhysicalApplicationPath + "\\errlog.txt", true, System.Text.Encoding.UTF8);

            Exception objErr = Server.GetLastError().GetBaseException();
            string error = "发生异常页: " + Request.Url.ToString() + "\n";
            error += "异常信息: " + objErr.Message + "\n";
            error += objErr.StackTrace + "\n";

            if (error.IndexOf("文件不存在") < 0)
            {
                sw.WriteLine(DateTime.Now.ToString());
                sw.WriteLine(error); ;
            }
            sw.Close();
            sw.Dispose();
        }
Exemple #47
0
        private static void Main(string[] args)
        {
            
            //outloc = args[0] + ".lex";
            //Console.WriteLine(EnumKeywords.PUBLIC.ToString());
            //Console.ReadKey();
            //Environment.Exit(0);
            writer = new System.IO.StreamWriter(args[0] + ".lex");
            lines = System.IO.File.ReadAllLines(args[0]);
            Console.WriteLine(operators.Count);
            Console.WriteLine(keywords.Count);
            //Console.WriteLine(Convert.ToString((EnumOperator)1));
            for (int i = 0; i < lines.Length; i++)
            {
                //if(System.Text.RegularExpressions.Regex.IsMatch(lines[i], @"//.*|/\*([~/]|\*[~/])*\*+/"));
                //{
                //    continue;
                //}
                if (lines[i].Contains("//"))
                {
                    continue;
                }
                Console.WriteLine(lines[i]);
                if (!checkkeywords(ref i) || !checkoperators(ref i) || !checktypes(ref i))
                {
                    Console.Error.Write("Invalid Input");

                }
                System.Threading.Thread.Sleep(100);
                Console.WriteLine(checkkeywords(ref i));
                System.Threading.Thread.Sleep(100);
                Console.WriteLine(checkoperators(ref i));
                System.Threading.Thread.Sleep(100);
               
                printTokens(lhs);
                writer.WriteLine();
                
                
            }
            writer.Flush();
            writer.Close();
            writer.Dispose();
            Console.WriteLine("Lexical Analasis Complete");
            Console.ReadKey();

        }
 private void LogToFile(string message)
 {
     System.IO.StreamWriter sw = null;
     try
     {
         sw = new System.IO.StreamWriter(Server.MapPath("~/log.txt"), true, encoding: Encoding.UTF8);
         sw.WriteLine(message);
     }
     catch (Exception) { }
     finally
     {
         if (sw != null)
         {
             sw.Close();
             sw.Dispose();
         }
     }
 }
Exemple #49
0
 static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
 {
     try
     {
         Exception ex = (Exception)e.ExceptionObject;
         System.IO.StreamWriter io = new System.IO.StreamWriter(FormMain.Instance.CurrentFolder + System.IO.Path.DirectorySeparatorChar + "Logs" + System.IO.Path.DirectorySeparatorChar + "exception.log", true);
         io.WriteLine(DateTime.Now.ToString() + "-" + ex.Message + ":" + ex.StackTrace);
         io.WriteLine();
         io.Flush();
         io.Close();
         io.Dispose();
         MessageBox.Show("Monody 9 Unhandled Exception Error\n\n" + ex.Message + ex.StackTrace, "Fatal Error - Written to Exception.log", MessageBoxButtons.OK, MessageBoxIcon.Stop);
     }
     finally
     {
         //Application.Exit();
     }
 }
Exemple #50
0
        /// <summary>
        /// ExportContiguitiesDict2TXT
        /// </summary>
        /// <param name="dictionary"></param>
        /// <param name="exportFileName"></param>
        /// <param name="enumVal"></param>
        public void ExportContiguitiesDict2TXT(Dictionary<string, string> dictionary,
            string exportFileName,
            Engine.AppEngine.ExportMode enumVal)
        {
            System.IO.TextWriter textWriter = new System.IO.StreamWriter(exportFileName);

              if (enumVal == Engine.AppEngine.ExportMode.Pairs)
              {
            textWriter.WriteLine("AreaId,NeigId");
              } // End if

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

              textWriter.Close();
              textWriter.Dispose();
        }
Exemple #51
0
 public static bool decompress(string infile, string outfile)
 {
     try {
         System.IO.StreamWriter sw = new System.IO.StreamWriter(outfile);
         System.IO.StreamReader sr = new System.IO.StreamReader(infile);
         System.IO.Compression.GZipStream gzs = new System.IO.Compression.GZipStream(sr.BaseStream, System.IO.Compression.CompressionMode.Decompress);
         int lbyte = gzs.ReadByte();
         while (lbyte != -1) {
             sw.BaseStream.WriteByte((byte) lbyte);
             lbyte = gzs.ReadByte();
         }
         gzs.Close();
         gzs.Dispose();
         sw.Close();
         sw.Dispose();
     } catch (System.Exception ex) {
         lerror = ex.Message;
         return false;
     }
     return true;
 }
Exemple #52
0
        static void Readfile(string loc , string loc2)
        {
            //System.IO.StreamWriter writer = new System.IO.StreamWriter(loc,true);
            string[] lines = System.IO.File.ReadAllLines(loc);
            foreach (string line in lines)
            {
                if (line.StartsWith("#"))
                {
                    splitstring = line.Split(new char[]{ ' ' });
                    for (int i = 0; i < splitstring.Length; i++)
                    {
                        Console.WriteLine(splitstring[i]);
                        if (splitstring[i].EndsWith(".js"))
                        {
                            System.IO.StreamWriter writer = new System.IO.StreamWriter(loc2, true);
                            string[] includelines = System.IO.File.ReadAllLines(Environment.CurrentDirectory + @"\" + splitstring[i]);
                            foreach (string pline in includelines)
                            {
                                Console.WriteLine(pline);
                                writer.WriteLine(pline);

                            }
                            writer.Flush();
                            writer.Close();
                            writer.Dispose();
                        }
                    }
                }
                else
                {
                    System.IO.StreamWriter writer2 = new System.IO.StreamWriter(loc2, true);
                    writer2.WriteLine(line);
                    writer2.Flush();
                    writer2.Close();
                    writer2.Dispose();
                }
            }
            Console.WriteLine("Preprocessing is Complete");
            return;
        }
Exemple #53
0
        //处理各项命令
        public void DealWithCommand()
        {
            switch (Option.Command)
            {
                case Menu_Command.Start:
                    _system.ChangeState("Stage1");
                    soundmanager.Stop("victor01");
                    break;
                case Menu_Command.OptionChanged:
                    System.IO.StreamWriter writer = new System.IO.StreamWriter("opst.dat");
                    writer.WriteLine("$volume#" + (soundmanager.Volume+1).ToString());
                    writer.Dispose();
                    break;
                case Menu_Command.CharactorSelect:

                    break;
                case Menu_Command.Quit:
                    if(form!=null)
                       form.Close();
                    break;
            }
            Option.Command = Menu_Command.None;
        }
 private void GeneratePlaylist(string filename)
 {
     System.IO.TextWriter writer = new System.IO.StreamWriter(filename);
     StringBuilder s = new StringBuilder();
     foreach (Tag t in _tags.Where(t => t.IsChecked))
     {
         if (s.Length == 0)
         {
             s.Append("# ");
             s.Append(t.Name);
         }
         else
         {
             s.Append(", ");
             s.Append(t.Name);
         }
     }
     writer.WriteLine(s.ToString());
     foreach (AudioFile f in _filteredAudioFiles)
     {
         writer.WriteLine(f.Location);
     }
     writer.Dispose();
 }
Exemple #55
0
        public static void section_data_1min_task()
        {
            WriteLine("section_data_1min_task started!");

            while (true)
            {
                try
                {
                    System.Net.WebRequest req = System.Net.HttpWebRequest.Create(QYTask.Settings1.Default.TIMCC_uri);

                    System.IO.Stream stream = req.GetResponse().GetResponseStream();
                    System.IO.TextReader rd = new System.IO.StreamReader(stream);
                    System.IO.TextWriter wr = new System.IO.StreamWriter(Util.CPath(AppDomain.CurrentDomain.BaseDirectory + "tmp.xml"));
                    wr.Write(rd.ReadToEnd());
                    wr.Flush();
                    wr.Close();
                    rd.Close();
                    stream.Close();
                    wr.Dispose();
                    rd.Dispose();
                    stream.Dispose();

                    Ds ds = five_min_section_parser(Util.CPath(AppDomain.CurrentDomain.BaseDirectory + "tmp.xml"));
                    // Curr5minSecDs.Dispose();
                    Curr5minSecDs = ds;

                    string dest;
                    if ((dest = getSaveDirFileName(ds.tblFileAttr[0].time)) != "")   // new 5 min data
                    {
                        WriteLine("section_data_1min_task: new section data->" + ds.tblFileAttr[0][0].ToString());

                        System.IO.File.Copy(Util.CPath(AppDomain.CurrentDomain.BaseDirectory + "tmp.xml"), dest);
                        if (OnNewTravelData != null)
                        {
                            // QYTask.Ds ds1 = new QYTask.Ds();
                            calcuate_travel_time();
                            ////ds1.Merge(RGSConfDs.tblRGSMain);
                            ////ds1.Merge(RGSConfDs.tblRGS_Config);
                            OnNewTravelData(RGSConfDs);
                            try
                            {
                                NotifyDisplayTask();
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("section_data_1min_task:" + ex.Message);
                            }
                        }

                    }

                }
                catch (Exception ex)
                {
                    WriteLine("section_data_1min_task:" + ex.Message + ex.StackTrace);

                    try
                    {
                        if (Curr5minSecDs == null || System.Math.Abs(((TimeSpan)(System.DateTime.Now - Curr5minSecDs.tblFileAttr[0].time)).Minutes) >= 20)
                        {
                            lock (RGSConfDs.tblRGS_Config)
                            {
                                foreach (QYTask.Ds.tblRGS_ConfigRow r in RGSConfDs.tblRGS_Config.Rows)
                                {
                                    r.RowError = "Timcc 連線資料異常!";
                                    r.mode = 1; //手動
                                    Console.WriteLine("寫入 RowErr");

                                }
                                if (OnNewTravelData != null)
                                {

                                    try
                                    {
                                        DataSet ds1 = new DataSet();

                                        ds1.Tables.Add(Util.getPureDataTable(RGSConfDs.tblRGS_Config));
                                        OnNewTravelData(ds1);
                                        NotifyDisplayTask();
                                    }
                                    catch (Exception ex1)
                                    {
                                        Console.WriteLine("section_data_1min_task:" + ex1.StackTrace);
                                    }
                                }
                            }
                            System.Console.WriteLine("Timcc 連線異常!");
                        }
                    }
                    catch (Exception ex1)
                    {
                        Console.WriteLine(ex1.Message);
                    }

                }

                Util.GC();

                System.Threading.Thread.Sleep(60 * 1000);
            }
        }
        /// <summary>
        /// 保存设置
        /// </summary>
        /// <param name="firstrun"></param>
        private void SaveSettings(bool firstrun = false)
        {
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                XDocument _doc = new XDocument();

                // root
                XElement _root = new XElement("Settings");

                // general and livetiles
                XElement _general = new XElement("General");
                XElement _livetiles = new XElement("LiveTiles");

                // general items
                XElement _autoclean;

                // live tiles items
                XElement _flip;

                if (firstrun)
                {
                    _autoclean = new XElement("AutoClean", "False");
                    _flip = new XElement("Flip", "False");
                }
                else
                {
                    _autoclean = new XElement("AutoClean", autoclean.ToString());
                    _flip = new XElement("Flip", flip.ToString());
                }

                _general.Add(_autoclean/*, _theme*/);
                _livetiles.Add(_flip);

                _root.Add(_general, _livetiles);

                _doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), _root);

                IsolatedStorageFileStream location = new IsolatedStorageFileStream("Settings.xml",
                    System.IO.FileMode.Create,
                    System.IO.FileAccess.ReadWrite,
                    System.IO.FileShare.Read,
                    storage);

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

                _doc.Save(file);
                file.Dispose();
                location.Dispose();
            }
        }
        /// <summary>
        /// 保存数据
        /// </summary>
        private void SaveData()
        {
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                XDocument _doc = new XDocument();

                // root
                XElement _root = new XElement("Ido");

                // today and future
                XElement _today = new XElement("Today");

                AddItems(_today);

                _root.Add(_today);

                _doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), _root);

                IsolatedStorageFileStream location = new IsolatedStorageFileStream("Content.xml",
                    System.IO.FileMode.Create,
                    System.IO.FileAccess.ReadWrite,
                    System.IO.FileShare.Read,
                    storage);

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

                _doc.Save(file);
                file.Dispose();
                location.Dispose();
            }
        }
Exemple #58
0
        /// <summary>
        /// Sends processing information to output (screen, file, etc)
        /// </summary>
        /// <param name="Message">Text to output</param>
        /// <param name="Method">Current executing method</param>
        /// <param name="ExtendedLogInfo">Indicates if this extended Debug info</param>
        private static void LogOutput(string Message, string Method, bool ExtendedLogInfo)
        {
            // Open the StreamWriter to write to the file
            System.IO.StreamWriter logfile = new System.IO.StreamWriter(LogFile, true);

            // Check if we are in Debug mode or not
            switch (ConfigDebug)
            {
                case true:
                    // Full debug...This dumps timing information, executing module, and some message about what we are doing
                    string strOutput = System.DateTime.Now.ToString("hh:mm:ss.ffffff") + "\tCURRENT MODULE: " + Method + "\tMESSAGE: " + Message;
                    Console.WriteLine(strOutput);
                    logfile.WriteLine(strOutput);
                    break;
                default:
                    // Basic logging...just dump basic info
                    if (!ExtendedLogInfo)
                    {
                        Console.WriteLine(Message);
                        logfile.WriteLine(Message);
                    }
                    break;
            }

            logfile.Flush();
            logfile.Close();
            logfile.Dispose();
        }
Exemple #59
0
        /// <summary>
        /// Creates the weekly output report using the supplied project list
        /// </summary>
        /// <param name="projects">Project list, with calculations, to use for report</param>
        /// <param name="RptDate">Date to use for calculating Sunday/Saturday end dates</param>
        private static void CreateWeeklyReport(List<Project> projects, DateTime RptDate)
        {
            string strOutLine = "";
            bool bDBConnected = false;

            // Create the SQL Server database connection
            SqlConnection sqlDatabase = new SqlConnection("Data Source=" + ConfigDBServer +
                                                            ";Initial Catalog=" + ConfigDBName +
                                                            ";User ID=" + ConfigDBUID +
                                                            ";Password="******"Error connecting to SQL Server:" + ex.Message, "CreateWeeklyReport", false);
                bDBConnected = false;
            }

            // Write the string to a file.
            ReportFile = ConfigReportPath + "\\" + System.DateTime.Now.ToString("ddMMMyyyy") + "-" + System.DateTime.Now.ToString("HHmm") + "_WeeklyReport.txt";
            System.IO.StreamWriter reportfile = new System.IO.StreamWriter(ReportFile);

            // Write the header line
            reportfile.WriteLine("*********************************");
            reportfile.WriteLine("Weekly report for " + RptDate.ToString("ddMMMyyyy"));
            reportfile.WriteLine("*********************************\r\n");
            strOutLine = "Intiative\tProject Name\tOpp Amount\tOwner\tPlanned Start Date\tPlanned End Date\tActual End Date\t";
            strOutLine = strOutLine + "Expedite\tState\tCancel Reason\tEpicID\tEpic\tEpic State\tDefect Hours Est\tDefect Hours To Do\tDefect Hours Actual\t";
            strOutLine = strOutLine + "Story Hours Est\tStory Hours To Do\tStory Hours Actual\tUpdate Owner\tStatus Update\tReport Date";
            reportfile.WriteLine(strOutLine);
            foreach (Project proj in projects)
            {
                foreach (Epic epic in proj.Epics)
                {
                    strOutLine = proj.Initiative + "\t" + proj.Name + "\t" + proj.OpportunityAmount.ToString("$ 0,000,000") + "\t" + proj.Owner + "\t";
                    strOutLine = strOutLine + proj.PlannedStartDate.ToString("ddMMMyyyy") + "\t" + proj.PlannedEndDate.ToString("ddMMMyyyy") + "\t";
                    strOutLine = strOutLine + proj.ActualEndDate.ToString("ddMMMyyyy") + "\t";
                    if (proj.Expedite)
                    {
                        strOutLine = strOutLine + "Yes\t";
                    }
                    else
                    {
                        strOutLine = strOutLine + "No\t";
                    }
                    strOutLine = strOutLine + proj.State + "\t" + proj.RevokedReason + "\t" + epic.FormattedID + "\t" + epic.Name + "\t" + epic.State + "\t" + epic.DefectEstimate.ToString("0.0") + "\t";
                    strOutLine = strOutLine + epic.DefectToDo.ToString("0.0") + "\t" + epic.DefectActual.ToString("0.0") + "\t" + epic.StoryEstimate.ToString("0.0") + "\t";
                    strOutLine = strOutLine + epic.StoryToDo.ToString("0.0") + "\t" + epic.StoryActual.ToString("0.0") + "\t" + proj.UpdateOwner + "\t";
                    strOutLine = strOutLine + proj.StatusUpdate + "\t" + DateTime.Now.ToString("ddMMMyyyy") + "\n";
                    reportfile.WriteLine(strOutLine);

                    if (bDBConnected)
                    {
                        SqlCommand sqlCmd = new SqlCommand("INSERT INTO dbo.WeeklyStats VALUES(@Initiative, @ProjectName, @OppAmount, @Owner, @PlannedStartDate, " +
                                "@PlannedEndDate, @ActualEndDate, @Expedite, @State, @CancelledReason, @EpicID, @Epic, @EpicState, @EpicDefectsEst, @EpicDefectsToDo," +
                                 "@EpicDefectsActual, @EpicStoryEst, @EpicStoryToDo, @EpicStoryActual, @UpdateOwner, @ProjectUpdate, @ReportDate, @CreateDate)", sqlDatabase);
                        sqlCmd.Parameters.Add(new SqlParameter("Initiative", proj.Initiative));
                        sqlCmd.Parameters.Add(new SqlParameter("ProjectName", proj.Name));
                        sqlCmd.Parameters.Add(new SqlParameter("OppAmount", proj.OpportunityAmount));
                        sqlCmd.Parameters.Add(new SqlParameter("Owner", proj.Owner));
                        // Check to make sure that PlannedStartDate is within date limits for SQL Server
                        if (proj.PlannedStartDate < Convert.ToDateTime("1/1/2010") || proj.PlannedStartDate > Convert.ToDateTime("1/1/2099"))
                        {
                            sqlCmd.Parameters.Add(new SqlParameter("PlannedStartDate", System.Data.SqlTypes.SqlDateTime.MinValue));
                        }
                        else
                        {
                            sqlCmd.Parameters.Add(new SqlParameter("PlannedStartDate", proj.PlannedStartDate));
                        }
                        // Check to make sure that PlannedEndDate is within date limits for SQL Server
                        if (proj.PlannedEndDate < Convert.ToDateTime("1/1/2010") || proj.PlannedEndDate > Convert.ToDateTime("1/1/2099"))
                        {
                            sqlCmd.Parameters.Add(new SqlParameter("PlannedEndDate", System.Data.SqlTypes.SqlDateTime.MinValue));
                        }
                        else
                        {
                            sqlCmd.Parameters.Add(new SqlParameter("PlannedEndDate", proj.PlannedEndDate));
                        }
                        // Check to make sure that ActualEndDate is within date limits for SQL Server
                        if (proj.ActualEndDate < Convert.ToDateTime("1/1/2010") || proj.ActualEndDate > Convert.ToDateTime("1/1/2099"))
                        {
                            sqlCmd.Parameters.Add(new SqlParameter("ActualEndDate", System.Data.SqlTypes.SqlDateTime.MinValue));
                        }
                        else
                        {
                            sqlCmd.Parameters.Add(new SqlParameter("ActualEndDate", proj.ActualEndDate));
                        }
                        if (proj.Expedite)
                        {
                            sqlCmd.Parameters.Add(new SqlParameter("Expedite", "Y"));
                        }
                        else
                        {
                            sqlCmd.Parameters.Add(new SqlParameter("Expedite", "N"));
                        }
                        sqlCmd.Parameters.Add(new SqlParameter("State", proj.State));
                        sqlCmd.Parameters.Add(new SqlParameter("CancelledReason", proj.RevokedReason));
                        sqlCmd.Parameters.Add(new SqlParameter("EpicID", epic.FormattedID));
                        sqlCmd.Parameters.Add(new SqlParameter("Epic", epic.Name));
                        sqlCmd.Parameters.Add(new SqlParameter("EpicState", epic.State));
                        sqlCmd.Parameters.Add(new SqlParameter("EpicDefectsEst", epic.DefectEstimate));
                        sqlCmd.Parameters.Add(new SqlParameter("EpicDefectsToDo", epic.DefectToDo));
                        sqlCmd.Parameters.Add(new SqlParameter("EpicDefectsActual", epic.DefectActual));
                        sqlCmd.Parameters.Add(new SqlParameter("EpicStoryEst", epic.StoryEstimate));
                        sqlCmd.Parameters.Add(new SqlParameter("EpicStoryToDo", epic.StoryToDo));
                        sqlCmd.Parameters.Add(new SqlParameter("EpicStoryActual", epic.StoryActual));
                        sqlCmd.Parameters.Add(new SqlParameter("UpdateOwner", proj.UpdateOwner));
                        sqlCmd.Parameters.Add(new SqlParameter("ProjectUpdate", proj.StatusUpdate));
                        sqlCmd.Parameters.Add(new SqlParameter("ReportDate", RptDate));
                        sqlCmd.Parameters.Add(new SqlParameter("CreateDate", System.DateTime.Now));
                        try
                        {
                            sqlCmd.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {
                            LogOutput("Error on insert to SQL Server:" + ex.Message, "CreateWeeklyReport", false);
                        }
                        sqlCmd.Dispose();
                    }
                }
                strOutLine = strOutLine + " ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + "\n";
            }

            // Close the file
            reportfile.Flush();
            reportfile.Close();
            reportfile.Dispose();

            // Close the database
            sqlDatabase.Close();
            sqlDatabase.Dispose();
        }
Exemple #60
0
        /// <summary>
        /// Creates the weekly output report using the supplied project list
        /// </summary>
        /// <param name="projects">Project list, with calculations, to use for report</param>
        /// <param name="RptMonth">Month to run report for</param>
        private static void CreateMonthlyReport(List<Project> projects, int RptMonth)
        {
            string strOutLine = "";
            bool bDBConnected = false;

            // Create the SQL Server database connection
            SqlConnection sqlDatabase = new SqlConnection("Data Source=" + ConfigDBServer +
                                                            ";Initial Catalog=" + ConfigDBName +
                                                            ";User ID=" + ConfigDBUID +
                                                            ";Password="******"Error connecting to SQL Server:" + ex.Message, "CreateMonthlyReport", false);
                bDBConnected = false;
            }

            // Write the string to a file.
            ReportFile = ConfigReportPath + "\\" + System.DateTime.Now.ToString("ddMMMyyyy") + "-" + System.DateTime.Now.ToString("HHmm") + "_MonthlyReport.txt";
            System.IO.StreamWriter reportfile = new System.IO.StreamWriter(ReportFile);

            // Write the header line
            reportfile.WriteLine("*********************************");
            reportfile.WriteLine("Monthly report for " + MonthName(RptMonth));
            reportfile.WriteLine("*********************************\r\n");
            reportfile.WriteLine("Initiative\tProject Name\tOpportunity Amount\tState\tPlanned Start Date\tPlanned End Date\t" +
                "Actual End Date\tOwner\tReport Date\tCreate Date\r\n");
            foreach (Project proj in projects)
            {
                strOutLine = proj.Initiative + "\t" + proj.Name + "\t" + proj.OpportunityAmount + "\t" + proj.State + "\t";
                strOutLine = strOutLine + proj.PlannedStartDate + "\t" + proj.PlannedEndDate + "\t" + proj.ActualEndDate + "\t";
                strOutLine = strOutLine + proj.Owner + "\t" + MonthName(RptMonth) + "\t" + DateTime.Now + "\n";
                reportfile.WriteLine(strOutLine);

                if (bDBConnected)
                {
                    SqlCommand sqlCmd = new SqlCommand("INSERT INTO dbo.MonthlyStats VALUES(@Initiative, @ProjectName, @OppAmount, @State, " +
                        "@PlannedStartDate, @PlannedEndDate, @ActualEndDate, @Owner, @ReportDate, @CreateDate)", sqlDatabase);
                    sqlCmd.Parameters.Add(new SqlParameter("Initiative", proj.Initiative));
                    sqlCmd.Parameters.Add(new SqlParameter("ProjectName", proj.Name));
                    sqlCmd.Parameters.Add(new SqlParameter("OppAmount", proj.OpportunityAmount));
                    sqlCmd.Parameters.Add(new SqlParameter("State", proj.State));
                    // Check to make sure that PlannedStartDate is within date limits for SQL Server
                    if (proj.PlannedStartDate < Convert.ToDateTime("1/1/2010") || proj.PlannedStartDate > Convert.ToDateTime("1/1/2099"))
                    {
                        sqlCmd.Parameters.Add(new SqlParameter("PlannedStartDate", System.Data.SqlTypes.SqlDateTime.MinValue));
                    }
                    else
                    {
                        sqlCmd.Parameters.Add(new SqlParameter("PlannedStartDate", proj.PlannedStartDate));
                    }
                    // Check to make sure that PlannedEndDate is within date limits for SQL Server
                    if (proj.PlannedEndDate < Convert.ToDateTime("1/1/2010") || proj.PlannedEndDate > Convert.ToDateTime("1/1/2099"))
                    {
                        sqlCmd.Parameters.Add(new SqlParameter("PlannedEndDate", System.Data.SqlTypes.SqlDateTime.MinValue));
                    }
                    else
                    {
                        sqlCmd.Parameters.Add(new SqlParameter("PlannedEndDate", proj.PlannedEndDate));
                    }
                    // Check to make sure that ActualEndDate is within date limits for SQL Server
                    if (proj.ActualEndDate < Convert.ToDateTime("1/1/2010") || proj.ActualEndDate > Convert.ToDateTime("1/1/2099"))
                    {
                        sqlCmd.Parameters.Add(new SqlParameter("ActualEndDate", System.Data.SqlTypes.SqlDateTime.MinValue));
                    }
                    else
                    {
                        sqlCmd.Parameters.Add(new SqlParameter("ActualEndDate", proj.ActualEndDate));
                    }
                    sqlCmd.Parameters.Add(new SqlParameter("Owner", proj.Owner));
                    sqlCmd.Parameters.Add(new SqlParameter("ReportDate", MonthName(RptMonth)));
                    sqlCmd.Parameters.Add(new SqlParameter("CreateDate", DateTime.Now));
                    try
                    {
                        sqlCmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        LogOutput("Error on insert to SQL Server:" + ex.Message, "CreateMonthlyReport", false);
                    }
                    sqlCmd.Dispose();
                }
            }

            // Close the file
            reportfile.Flush();
            reportfile.Close();
            reportfile.Dispose();

            // Close the database
            sqlDatabase.Close();
            sqlDatabase.Dispose();
        }