Flush() public method

public Flush ( ) : void
return void
        //OnWriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext)
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            string uri = HttpContext.Current.Request.Url.Query;
            string method = HttpContext.Current.Request.HttpMethod;
            if(HttpContext.Current.Request.HttpMethod =="GET")
            {

                return Task.Factory.StartNew(() =>
                {
                    var writer = new StreamWriter(writeStream);
                    var query = HttpUtility.ParseQueryString(uri);
                    string callback = query[CallbackQueryParameter];
                    writer.Write(callback + "(");
                    writer.Flush();

                    base.WriteToStreamAsync(type, value, writeStream, content, transportContext).Wait();

                    writer.Write(")");
                    writer.Flush();
                });
            }
            else
            {
                return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
            }
        }
Example #2
0
        public static void Connect_Server()
        {
            //connection setup
            ircconnect = new TcpClient(SetupClass.Server, SetupClass.port);
            ircstream = ircconnect.GetStream();
            PingClass ping = new PingClass();
            ping.Start();
            reader = new StreamReader(ircstream);
            writer = new StreamWriter(ircstream);

            writer.WriteLine("PING " + "irc.freenode.net");
            writer.Flush();
            writer.WriteLine("USER WPChat 8 * : WrongPlanet IRC Client");
            writer.Flush();
            writer.WriteLine("NICK " + SetupClass.Nick);
            writer.Flush();
            writer.WriteLine("JOIN " + "#wrongplanet");
            writer.Flush();

            while (true)
            {

                //if (reader.ReadLine() != null)
                {
                    System.Messaging.MessageQueue queue = new System.Messaging.MessageQueue(@".\Private$\ServerQueue");
                    queue.Send(reader.ReadLine());
                }

            }
        }
Example #3
0
        public void comprobarGanador(StreamWriter sw)
        {
            // Resolvemos la jugada

            if ((jugada1 == "piedra" && jugada2 == "piedra") ||
                (jugada1 == "papel" && jugada2 == "papel") ||
                (jugada1 == "tijera" && jugada2 == "tijera"))
            {
                sw.WriteLine("#OK#empate#");
                sw.Flush();
            }
            else if ((jugada1 == "piedra" && jugada2 == "tijera") ||
                (jugada1 == "tijera" && jugada2 == "papel") ||
                (jugada1 == "papel" && jugada2 == "piedra"))
            {
                sw.WriteLine("#OK#ganador:" + jugador1 + "#");
                puntos1++;
                sw.Flush();
            }
            else if ((jugada2 == "piedra" && jugada1 == "tijera") ||
                (jugada2 == "tijera" && jugada1 == "papel") ||
                (jugada2 == "papel" && jugada1 == "piedra"))
            {
                sw.WriteLine("#OK#ganador:" + jugador2 + "#");
                puntos2++;
                sw.Flush();
            }

            //dormimos el thread 1 segundo para que de tiempo a que el otro jugador analice el resultado
            //antes de borrar las jugadas
            Thread.Sleep(1000);
            jugada1 = "";
            jugada2 = "";
        }
Example #4
0
        public string GetUploadResponse(string url, UploadData upload)
        {
            string boundary = Guid.NewGuid().ToString().Replace("-", "");
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); 
            request.Method = "POST";
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:15.0) Gecko/20100101 Firefox/15.0.1";
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Proxy = null;

            MemoryStream PostData = new MemoryStream();
            StreamWriter writer = new StreamWriter(PostData);
            writer.Write("--" + boundary + "\n");
            writer.Write("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"{2}", upload.fieldName, upload.fileName, "\n");
            writer.Write(("Content-Type: " + GetContentType(upload.fileName) + "\n") + "\n");
            writer.Flush();
            writer.Write("\n");
            writer.Write("--{0}--{1}", boundary, "\n");
            PostData.Write(upload.content, 0, upload.content.Length);
            writer.Flush();
          
            request.ContentLength = PostData.Length;
            using (Stream s = request.GetRequestStream())
            {
                PostData.WriteTo(s);
            }
            PostData.Close();

            return new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd();
        }
Example #5
0
 public static void Merge(string targetPath, string[] sourcePaths, Action<string> logMessage)
 {
     const int bufferSize = 512;
     byte[] buffer = new byte[bufferSize];
     int bytesRead;
     //Use a target stream
     using (FileStream ts = new FileStream(targetPath, FileMode.Create, FileAccess.Write, FileShare.None))
     using (StreamWriter sw = new StreamWriter(ts))
     {
         sw.WriteLine("//-- GENERATED BY PxCoco -merge --//");
         sw.WriteLine("//-- make sure to modify the source files instead of this one! --//");
         foreach (string sourcePath in sourcePaths)
         {
             if (!File.Exists(sourcePath))
             {
                 Console.WriteLine("Source file " + sourcePath + " does not exist.");
                 continue;
             }
             string sourceName = Path.GetFileName(sourcePath);
             logMessage.Invoke(String.Format("Adding {0} to {1}.", sourceName, Path.GetFileName(targetPath)));
             //Use a source stream
             using (FileStream ss = new FileStream(sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read))
             {
                 sw.WriteLine("\n#file:" + Path.GetFullPath(sourcePath) + "#");
                 sw.Flush();
                 while((bytesRead = ss.Read(buffer, 0, bufferSize)) > 0)
                     ts.Write(buffer, 0, bytesRead);                        
             }
             
         }
         //Switch line processing back to normal, in case the user wants to add stuff here
         sw.WriteLine("#file:default#");
         sw.Flush();
     }
 }
Example #6
0
 public static string Encrypt(string originalString, byte[] key)
 {
     try
     {
         if (String.IsNullOrEmpty(originalString))
         {
             throw new ArgumentNullException
                    ("The string which needs to be encrypted can not be null.");
         }
         DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
         cryptoProvider.Mode = CipherMode.ECB;
         cryptoProvider.Padding = PaddingMode.Zeros;
         MemoryStream memoryStream = new MemoryStream();
         CryptoStream cryptoStream = new CryptoStream(memoryStream,
             cryptoProvider.CreateEncryptor(key, key), CryptoStreamMode.Write);
         StreamWriter writer = new StreamWriter(cryptoStream);
         writer.Write(originalString);
         writer.Flush();
         cryptoStream.FlushFinalBlock();
         writer.Flush();
         return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
     }
     catch (Exception e)
     {
         return null;
     }
 }
Example #7
0
        public void write(string word)
        {
            StreamWriter sr;
             if (File.Exists(str+"\\load.txt")) //如果文件存在,则创建File.AppendText对象
             {
                 sr = File.AppendText(str+"\\load.txt");
             }
             else   //如果文件不存在,则创建File.CreateText对象
             {
                 sr = File.CreateText(str+"\\load.txt");
             }
            // sr.WriteLine(str);
             sr.Close();
               //创建一个文件流,用以写入或者创建一个StreamWriter
            FileStream fs = new FileStream(str+"\\load.txt", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter m_streamWriter = new StreamWriter(fs);
            m_streamWriter.Flush();
            // 使用StreamWriter来往文件中写入内容
            m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
            m_streamWriter.Write(word+"\r\n\r\n\r\n");

            //关闭此文件
            m_streamWriter.Flush();
            m_streamWriter.Close();
        }
Example #8
0
		public void Run ()
		{
			StreamReader sr = new StreamReader (conn.Transport.Stream, Encoding.ASCII);
			StreamWriter sw = new StreamWriter (conn.Transport.Stream, Encoding.ASCII);

			sw.NewLine = "\r\n";

			string str = conn.Transport.AuthString ();
			byte[] bs = Encoding.ASCII.GetBytes (str);

			string authStr = ToHex (bs);

			sw.WriteLine ("AUTH EXTERNAL {0}", authStr);
			sw.Flush ();

			string ok_rep = sr.ReadLine ();

			string[] parts;
			parts = ok_rep.Split (' ');

			if (parts.Length < 1 || parts[0] != "OK")
				throw new Exception ("Authentication error: AUTH EXTERNAL was not OK: \"" + ok_rep + "\"");

			/*
			string guid = parts[1];
			byte[] guidData = FromHex (guid);
			uint unixTime = BitConverter.ToUInt32 (guidData, 0);
			Console.Error.WriteLine ("guid: " + guid + ", " + "unixTime: " + unixTime + " (" + UnixToDateTime (unixTime) + ")");
			*/

			sw.WriteLine ("BEGIN");
			sw.Flush ();
		}
        public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
        {
            MemoryStream outStream = new MemoryStream();
            StreamWriter writer = new StreamWriter(outStream);
            writer.WriteLine("--" + Boundary);
            writer.WriteLine("Content-Disposition: form-data; name=\"torrent_file\"; filename=\"foo.torrent\"");
            writer.WriteLine("Content-Type: ");
            writer.WriteLine();
            writer.Flush();
            (parameters[0] as Stream).CopyTo(outStream);
            writer.WriteLine();
            writer.WriteLine("--" + Boundary + "--");
            writer.Flush();

            outStream.Seek(0, SeekOrigin.Begin);
            parameters[0] = outStream;

            Message request = this.originalFormatter.SerializeRequest(messageVersion, parameters);

            if (!request.Properties.ContainsKey(HttpRequestMessageProperty.Name))
            {
                request.Properties[HttpRequestMessageProperty.Name] = new HttpRequestMessageProperty();
            }

            HttpRequestMessageProperty http = request.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
            http.Headers.Set(HttpRequestHeader.ContentType, "multipart/form-data; boundary=" + Boundary);
            http.Headers.Remove(HttpRequestHeader.Expect);

            return request;
        }
Example #10
0
        public static string EncryptStringForMapServer(string text)
        {
            string RetVal;
            DESCryptoServiceProvider CryptoProvider;
            MemoryStream MemoryStream;
            CryptoStream CryptoStream;
            StreamWriter Writer;
            byte[] Bytes;

            RetVal = string.Empty;

            if (!string.IsNullOrEmpty(text))
            {
                Bytes = ASCIIEncoding.ASCII.GetBytes(DIMapServer.EncryptionKey);
                CryptoProvider = new DESCryptoServiceProvider();
                MemoryStream = new MemoryStream(Bytes.Length);
                CryptoStream = new CryptoStream(MemoryStream, CryptoProvider.CreateEncryptor(Bytes, Bytes), CryptoStreamMode.Write);
                Writer = new StreamWriter(CryptoStream);
                Writer.Write(text);
                Writer.Flush();
                CryptoStream.FlushFinalBlock();
                Writer.Flush();

                RetVal = Convert.ToBase64String(MemoryStream.GetBuffer(), 0, (int)MemoryStream.Length);
            }

            return RetVal;
        }
        public string EncryptField(string fieldValue)
        {
            string result = string.Empty;

            if (!string.IsNullOrEmpty(fieldValue)) {
                try {
                    DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();

                    MemoryStream memoryStream = new MemoryStream();

                    CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(this.key, this.key), CryptoStreamMode.Write);

                    StreamWriter writer = new StreamWriter(cryptoStream);

                    writer.Write(fieldValue);

                    writer.Flush();

                    cryptoStream.FlushFinalBlock();

                    writer.Flush();

                    result = Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
                } catch (Exception ex) {
                    /*LogManager.GetCurrentClassLogger().Error(
                        errorMessage => errorMessage("Could not encrypt value: {0}", fieldValue), ex);*/

                    throw new ApplicationException("Could not encrypt value: " + fieldValue, ex);
                }
            }

            return result;
        }
        public void BeginPostCallback(IAsyncResult result)
        {
            HttpWebRequest request = result.AsyncState as HttpWebRequest;
            Stream requestStream = request.EndGetRequestStream(result);
            StreamWriter writer = new StreamWriter(requestStream);

            byte[] ba = new byte[_imageStream.Length];
            _imageStream.Read(ba, 0, (int)_imageStream.Length);

            writer.Write("--");
            writer.WriteLine(boundary);
            writer.WriteLine(@"Content-Disposition: form-data; name=""userfile[]""; filename=""WP7Upload.jpg""");
            writer.WriteLine(@"Content-Type: image/jpeg");
            writer.WriteLine(@"Content-Length: " + ba.Length);
            writer.WriteLine();
            writer.Flush();
            Stream output = writer.BaseStream;

            output.Write(ba, 0, ba.Length);
            output.Flush();
            writer.WriteLine();

            writer.Write("--");
            writer.Write(boundary);
            writer.WriteLine("--");
            writer.Flush();
            writer.Close();

            request.BeginGetResponse(new AsyncCallback(ResponseCallback), request);
        }
Example #13
0
        private void Parse()
        {
            TcpClient tcpclient = new TcpClient(); // create an instance of TcpClient
            tcpclient.Connect("pop.mail.ru", 995); // HOST NAME POP SERVER and gmail uses port number 995 for POP
            System.Net.Security.SslStream sslstream = new SslStream(tcpclient.GetStream()); // This is Secure Stream // opened the connection between client and POP Server
            sslstream.AuthenticateAsClient("pop.mail.ru"); // authenticate as client
            //bool flag = sslstream.IsAuthenticated; // check flag
            System.IO.StreamWriter sw = new StreamWriter(sslstream); // Asssigned the writer to stream
            System.IO.StreamReader reader = new StreamReader(sslstream); // Assigned reader to stream
            sw.WriteLine("USER [email protected]"); // refer POP rfc command, there very few around 6-9 command
            sw.Flush(); // sent to server
            sw.WriteLine("PASS utybfkmyjcnm321");
            sw.Flush();
            sw.WriteLine("RETR 5");
            sw.Flush();
            sw.WriteLine("Quit "); // close the connection
            sw.Flush();
            string str = string.Empty;
            string strTemp = string.Empty;

            while ((strTemp = reader.ReadLine()) != null)
            {
                if (".".Equals(strTemp))
                {
                    break;
                }
                if (strTemp.IndexOf("-ERR") != -1)
                {
                    break;
                }
                str += strTemp;
            }

            MessageBox.Show(str);
        }
Example #14
0
 /// <summary>
 /// 在指定文件中写入指定的内容
 /// </summary>
 ///  <param name="strPathName">需要写入的文本名称</param>
 ///  <param name="strContent">写入的内容</param>
 /// <returns></returns>
 public static bool WriteContentToText(string strPathName, string strContent)
 {
     try
     {
         if (strPathName == null || strPathName == String.Empty)
             return false;
         if (!File.Exists(strPathName))
         {
             File.CreateText(strPathName);
         }
         FileStream fs = new FileStream(strPathName, FileMode.Open, FileAccess.Write);
         StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.GetEncoding("GB2312"));//通过指定字符编码方式可以实现对汉字的支持,否则在用记事本打开查看会出现乱码
         sw.Flush();
         sw.BaseStream.Seek(0, SeekOrigin.End);   //从哪里开始写入.
         sw.WriteLine(strContent);
         sw.Flush();
         sw.Close();
         fs.Close();
         return true;
     }
     catch
     {
         return false;
     }
 }
Example #15
0
        public static void Connect(Server serverInfo)
        {
            try {

                  TcpClient ircConnection = new TcpClient(serverInfo.Hostname, serverInfo.Port);
                  NetworkStream ircStream = ircConnection.GetStream();
                  StreamReader ircReader = new StreamReader(ircStream);
                  StreamWriter ircWriter = new StreamWriter(ircStream);

                  Ping.loadGlobals(ircWriter, serverInfo);

                  ircWriter.WriteLine("NICK " + serverInfo.Nickname);
                  ircWriter.Flush();
                  ircWriter.WriteLine("USER " + serverInfo.User);
                  ircWriter.Flush();

                  Ping ping = new Ping();
                  ping.Start();

                  StreamReceiver.Initialize(ircReader, ircWriter, serverInfo);

                  ircWriter.Close();
                  ircReader.Close();
                  ircStream.Close();
              }

              catch (Exception e) {

                  Console.WriteLine(e.ToString());
                  Console.WriteLine("Hit the anykey to quit.");
                  Console.ReadLine();

              }
        }
Example #16
0
 static void Main(string[] args)
 {
     Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9000);
     s.Bind(iep);
     s.Listen(10);
     Console.WriteLine("Waiting Client...");
     Socket sc = s.Accept();
     NetworkStream ns = new NetworkStream(sc);
     StreamReader sr = new StreamReader(ns);
     StreamWriter sw = new StreamWriter(ns);
     sw.WriteLine("Chao Client");
     sw.Flush();
     while (true)
     {
         string st;
         st = sr.ReadLine();
         Console.WriteLine("Client gui len:{0}",st);
         if (st.ToUpper().Equals("QUIT"))
             break;
         st = st.ToUpper();
         sw.WriteLine(st);
         sw.Flush();
     }
     sw.Close();
     sr.Close();
     ns.Close();
     sc.Close();
     s.Close();
 }
        public void Blah()
        {
            using( var stream = new MemoryStream() )
            using( var reader = new StreamReader( stream ) )
            using( var writer = new StreamWriter( stream ) )
            using( var csv = new CsvReader( reader ) )
            {
                writer.WriteLine( "Id,Name" );
                writer.WriteLine( "1,one" );
                writer.Flush();
                stream.Position = 0;

                var records = csv.GetRecords<Test>().ToList();

                var position = stream.Position;
                writer.WriteLine( "2,two" );
                writer.Flush();
                stream.Position = position;

                records = csv.GetRecords<Test>().ToList();

                writer.WriteLine( "2,two" );
                writer.Flush();
                stream.Position = position;

                Assert.AreEqual( 1, records.Count );
                Assert.AreEqual( 2, records[0].Id );
                Assert.AreEqual( "two", records[0].Name );
            }
        }
Example #18
0
        public static string Encode(string data)
        {
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

            string encodeString = string.Empty;
            using (DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider())
            {
                int i = cryptoProvider.KeySize;
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write))
                    {
                        using (StreamWriter sw = new StreamWriter(cst))
                        {
                            sw.Write(data);
                            sw.Flush();
                            cst.FlushFinalBlock();
                            sw.Flush();
                            encodeString = Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
                        }
                    }
                }
            }

            return encodeString;
        }
Example #19
0
        public void Start()
        {
            DateTime dt = System.DateTime.Now;
            bool exists = Directory.Exists("./log");
            if (!exists)
                Directory.CreateDirectory("./log");
            fileName = string.Format("./log/psd{0:D4}{1:D2}{2:D2}-{3:D2}{4:D2}{5:D2}.log",
                dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second);
            var ass = System.Reflection.Assembly.GetExecutingAssembly().GetName();
            int version = ass.Version.Revision;

            queue = new BlockingCollection<string>(new ConcurrentQueue<string>());
            Task.Factory.StartNew(() =>
            {
                using (StreamWriter sw = new StreamWriter(fileName, true))
                {
                    sw.WriteLine("VERSION={0} ISSV=1", version);
                    sw.Flush();
                    Stop = false;
                    while (!Stop)
                    {
                        string line = queue.Take();
                        if (!string.IsNullOrEmpty(line))
                        {
                            string eline = Base.LogES.DESEncrypt(line, "AKB48Show!",
                                (version * version).ToString());
                            sw.WriteLine(eline);
                            sw.Flush();
                        }
                    }
                }
            });
        }
Example #20
0
        public ServerConnection(string host, int port, string username, string password)
        {
            Host = host;
            Port = port;
            Username = username;
            _currentConnection = this;

            try
            {
                Client = new TcpClient(host, port);
                Reader = new StreamReader(Client.GetStream());
                Writer = new StreamWriter(Client.GetStream());

                if (password.Equals(""))
                {
                    Writer.WriteLine("M:/name " + username);
                } else
                {
                    Writer.WriteLine("M:/auth " + username + " " + password);
                }
                Writer.Flush();

                Writer.WriteLine("S:Client");
                Writer.Flush();
                Writer.WriteLine("S:Account");
                Writer.Flush();
                Writer.WriteLine("S:ChannelClientList");
                Writer.Flush();
            } catch
            {
                Client = null;
            }
        }
 public void ConstructorTest2_FromEnd()
 {
     var path = Path.GetTempFileName();
     try
     {
         using (Stream ofs = new FileStream(path, FileMode.Open, FileAccess.Write, FileShare.Read))
         using (TextWriter writer = new StreamWriter(ofs))
         {
             writer.WriteLine("こんにちは");
             writer.Flush();
             using (Stream ifs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite))
             using (TailFollowStream tail = new TailFollowStream(ifs, true))
             using (TextReader reader = new StreamReader(tail))
             {
                 var job = Task<bool>.Factory.StartNew(() =>
                 {
                     Assert.AreEqual("さようなら", reader.ReadLine());
                     return true;
                 });
                 writer.WriteLine("さようなら");
                 writer.Flush();
                 job.Wait();
                 Assert.True(job.Result);
             }
         }
     }
     finally
     {
         File.Delete(path);
     }
 }
Example #22
0
        protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream,
                                               HttpContentHeaders contentHeaders,
                                               FormatterContext formatterContext,
                                               TransportContext transportContext)
        {
            string callback;

               if (IsJsonpRequest(formatterContext.Response.RequestMessage, out callback))
               {
            return Task.Factory.StartNew(() =>
            {
             var writer = new StreamWriter(stream);
             writer.Write(callback + "(");
             writer.Flush();

             base.OnWriteToStreamAsync(type, value, stream, contentHeaders,
                             formatterContext, transportContext).Wait();

             writer.Write(")");
             writer.Flush();
            });
               }
               else
               {
            return base.OnWriteToStreamAsync(type, value, stream, contentHeaders, formatterContext, transportContext);
               }
        }
Example #23
0
        private void ok_Button_Click(object sender, RoutedEventArgs e)
        {
            if (hotKey1_ComboBox.SelectedIndex < 0 || hotKey2_ComboBox.SelectedIndex<0)
            {
                MessageBox.Show("信息选择不完全!","提醒",MessageBoxButton.OK,MessageBoxImage.Warning);
                return;
            }
            HotKey.KeyFlags control=HotKey.KeyFlags.MOD_ALT;
            int index = 0;
            switch (hotKey1_ComboBox.SelectedIndex)
            {
                case 0: control = HotKey.KeyFlags.MOD_ALT; break;
                case 1: control = HotKey.KeyFlags.MOD_CONTROL; index = 1; break;
                case 2: control = HotKey.KeyFlags.MOD_SHIFT; index = 2; break;
                case 3: control = HotKey.KeyFlags.MOD_WIN; index = 3; break;
            }

            //撤销先前的热键
            HotKeyFactory.UnregisterHotKey();
            //注册新的热键
            HotKeyFactory.RegisterHotKey(control,(System.Windows.Forms.Keys)hotKey2_ComboBox.SelectedItem);

            if (HotKeyFactory.hotKey.IRightRegistered)
            {
                MessageBox.Show("热键注册成功!");
                FileStream fs = new FileStream(HotKeyFactory.path, FileMode.Create, FileAccess.Write);
                StreamWriter streamWriter = new StreamWriter(fs);
                streamWriter.Flush();
                streamWriter.WriteLine(index.ToString()+":"+hotKey2_ComboBox.SelectedItem.ToString());
                streamWriter.Flush();
                streamWriter.Close();
            }
            else
                MessageBox.Show("热键注册失败!");
        }
Example #24
0
 protected override void ProcessLogQueue(ConcurrentQueue<LogEvent> logQueue, LogEventDispatcher dispatcher)
 {
     // Open a buffered stream writer to the console standard out
     LogEvent logEvent;
     using (var writer = new StreamWriter(new BufferedStream(Console.OpenStandardOutput())))
     {
         // Pull all of the log events from the queue and write them to the buffered writer
         while (logQueue.IsEmpty == false)
         {
             if (logQueue.TryDequeue(out logEvent))
             {
                 try
                 {
                     writer.Write(Layout.FormatLogEvent(logEvent));
                 }
                 catch (Exception e)
                 {
                     try
                     {
                         writer.Flush();
                     }
                     finally
                     {
                         if (dispatcher != null)
                             dispatcher.HandleException(e, logEvent);
                         else
                             throw e;
                     }
                 }
             }
         }
         writer.Flush();
     }
 }
Example #25
0
        public static string Encrypt(string originalString)
        {
            if (String.IsNullOrEmpty(originalString))
            {
                return string.Empty;
            }
            try
            {
                DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
                MemoryStream memoryStream = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(bytes, bytes), CryptoStreamMode.Write);

                StreamWriter writer = new StreamWriter(cryptoStream);
                writer.Write(originalString);
                writer.Flush();
                cryptoStream.FlushFinalBlock();
                writer.Flush();

                return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public void Typical ()
        {
            using (var ms = new MemoryStream ())
            using (var sw = new StreamWriter (ms))
            {
                XDocument doc;
                XmlNamespaceManager namespaceManager;
                using (var stream = AssemblyExtensions.OpenScopedResourceStream<Program> ("Template.cxml"))
                using (var reader = XmlReader.Create (stream))
                {
                    doc = XDocument.Load (reader);
                    namespaceManager = new XmlNamespaceManager (reader.NameTable);
                    namespaceManager.AddNamespace ("c", Program.CollectionNamespace.NamespaceName);
                }

                using (var cw = new CollectionWriter (ms, Program.WriterSettings, futureCw => 
                    {
                        futureCw.Flush ();
                        sw.Write (ProgramTest.ExpectedAnsweredAndAccepted);
                        sw.Flush ();
                    })
                )
                {
                    doc.Save (cw);
                }

                sw.Flush ();
                ProgramTest.AssertStreamsAreEqual<CollectionWriterTest> ("CollectionWithInjectedItems.cxml", ms);
            }
        }
Example #27
0
        public static string SerializeToText(System.Type ObjectType, Object Object)
        {
            string RetVal;
            StreamWriter Writer;
            StreamReader Reader;
            MemoryStream Stream;

            RetVal = string.Empty;
            Stream = new MemoryStream();
            Reader = new StreamReader(Stream);
            Writer = new StreamWriter(Stream);

            try
            {
                if (Object != null && ObjectType != null)
                {
                    Serialize(Writer, ObjectType, Object);
                    Stream.Position = 0;
                    RetVal = Reader.ReadToEnd();

                    Writer.Flush();
                    Writer.Close();
                    Reader.Close();
                }
            }
            catch (Exception ex)
            {
                Writer.Flush();
                Writer.Close();
                Reader.Close();
                throw ex;
            }
            return RetVal;
        }
Example #28
0
        public IRC()
        {
            //"https://api.twitch.tv/kraken/oauth2/authorize?response_type=token&client_id=" + ConfigurationManager.AppSettings["client_id"] + "&redirect_uri=http://localhost&scope=channel_read+channel_editor+channel_commercial+channel_subscriptions+channel_check_subscription
            
            Client = new TcpClient("irc.twitch.tv", 6667);
            NwStream = Client.GetStream();
            Reader = new StreamReader(NwStream, Encoding.GetEncoding("iso8859-1"));
            Writer = new StreamWriter(NwStream, Encoding.GetEncoding("iso8859-1"));
            botUsername = ConfigurationManager.AppSettings["username"];
            channel = ConfigurationManager.AppSettings["channel"];
            timeoutList = sql.readSQLite("timeoutWords", "name", "duration");
            banList = sql.readSQLite("bannedwords", "name");
            commandList = sql.readSQLite("commands", "command", "response");


            listen = new Thread(new ThreadStart(Listen));
            listen.Start();



            Writer.WriteLine("PASS " + ConfigurationManager.AppSettings["password"]);
            Writer.Flush();
            Writer.WriteLine("NICK " + botUsername);
            Writer.Flush();
            Writer.WriteLine("USER " + botUsername + "8 * :" + botUsername);
            Writer.Flush();
            Writer.WriteLine("JOIN #" + channel + "\n");
            Writer.Flush();

        }
Example #29
0
        public static void DumpArray(Stream outputStream, byte[] array)
        {
            TextWriter tw = new StreamWriter( outputStream, Encoding.GetEncoding( 866 ) );
            bool isEnd = false;
            int i = 0x0000;

            tw.WriteLine( "-------------------------------Begin Dump--------------------------------" );
            while ( i < array.Length ) {
                tw.Write( "{0,8:X4}: ", i );

                for( int j=0; j<16; j++) {
                    if( i+j == array.Length) {
                        isEnd = true;
                        break;
                    }
                    tw.Write( "{0,2:X2} ", array[i + j] );
                    if( j % 4 == 3 ) {
                        tw.Write( "| " );
                    }
                }
                tw.Write( "\n" );
                if ( isEnd ) { break; }

                tw.Flush();

                i+=16;
            }
            tw.WriteLine( "--------------------------------End Dump---------------------------------" );
            tw.Flush();
        }
Example #30
0
        public bool SavePersonalData(string pathToSave, out string message)
        {
            message = string.Empty;

            if (string.IsNullOrEmpty(NameObject.GetNameRaw.Trim()) ||
                string.IsNullOrEmpty(NameObject.GetSurnameRaw.Trim()))
            {
                message = "Can't save without name and surname!";
                return(false);
            }

            if (string.IsNullOrEmpty(NameObject.GetLifeWayNumberString) ||
                string.IsNullOrEmpty(NameObject.GetVowelsOfNameAndSurnameString) ||
                string.IsNullOrEmpty(NameObject.GetConsonantsOfNameAndSurnameString) ||
                string.IsNullOrEmpty(NameObject.GetVowelsAndConsonantsOfNameAndSurnameString) ||
                string.IsNullOrEmpty(NameObject.GetVowelsAndConsonantsOfNameAndSurnameAndlifeWayNumberString))
            {
                message = "Important personal numbers are not initialized. operation aborted!";
                return(false);
            }

            var comparisonObject = new Comparison();

            comparisonObject.Language = NameObject.GetLanguageString;

            comparisonObject.Name       = NameObject.GetNameRaw;
            comparisonObject.Surname    = NameObject.GetSurnameRaw;
            comparisonObject.Fathername = NameObject.GetfathersnameRaw;

            comparisonObject.DOB = DOBObject.DOB;

            comparisonObject.LifeWayNumber            = int.Parse(NameObject.GetLifeWayNumberString);
            comparisonObject.SoulNumber               = int.Parse(NameObject.GetVowelsOfNameAndSurnameString);
            comparisonObject.PersonalityNumber        = int.Parse(NameObject.GetConsonantsOfNameAndSurnameString);
            comparisonObject.DestinyNumber            = int.Parse(NameObject.GetVowelsAndConsonantsOfNameAndSurnameString);
            comparisonObject.PowerNumber              = int.Parse(NameObject.GetVowelsAndConsonantsOfNameAndSurnameAndlifeWayNumberString);
            comparisonObject.Peaks                    = DOBObject.Peaks;
            comparisonObject.EveryDayStabilityNumber  = DOBObject.GetEveryDayStabilityNumber;
            comparisonObject.SpiritualStabilityNumber = DOBObject.GetSpiritualStabilityNumber;

            var fileName = GetFileName(comparisonObject);

            using (var writer = new System.IO.StreamWriter(Path.Combine(pathToSave, fileName)))
            {
                var serializer = new XmlSerializer(typeof(Comparison), new[] { typeof(List <PeakObject>), typeof(PeakObject) });
                serializer.Serialize(writer, comparisonObject);
                writer.Flush();
            }

            return(true);
        }
Example #31
0
        private static void UpdateMonoConfiguration()
        {
            //create fast-cgi mono webapp config
            var webappConfig = new System.IO.StreamWriter("tripthru.webapp");
            webappConfig.WriteLine("<apps>");
            webappConfig.Flush();

            webappConfig.WriteLine(@"<web-application>
                                    <name>TripThru.TripThruGateway</name>
                                    <vhost>*</vhost>
                                    <vport>80</vport>
                                    <vpath>/TripThru.TripThruGateway</vpath>
                                    <path>/var/www/ServiceStack.TripThruGateway/Web</path>
                                 </web-application>"
                );
            webappConfig.Flush();

            foreach (var config in partnerConfigurations)
            {
                webappConfig.WriteLine(@"<web-application>
                                    <name>TripThru.{0}</name>
                                    <vhost>*</vhost>
                                    <vport>80</vport>
                                    <vpath>/TripThru.{0}</vpath>
                                    <path>/var/www/ServiceStack.{0}/Web</path>
                                 </web-application>", config.Partner.Name.Replace(" ", "")
                );
                webappConfig.Flush();
            }

            webappConfig.WriteLine("</apps>");
            webappConfig.Flush();
            webappConfig.Close();

            Console.WriteLine("Updating mono webapp config");
            ssh.RunCommand("rm /etc/rc.d/init.d/mono-fastcgi/tripthru.webapp");
            sftpBase.Put("tripthru.webapp", "/etc/rc.d/init.d/mono-fastcgi/tripthru.webapp");
        }
Example #32
0
        public static void saveJoints(string filename, List <Body> bodies)
        {
            FileStream fileStream = File.Open(filename, FileMode.Create);

            System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(fileStream);

            //PLY file header is written here.
            streamWriter.WriteLine("{[");
            streamWriter.Flush();

            for (int bodyIdx = 0; bodyIdx < bodies.Count; bodyIdx++)
            {
                if (bodies[bodyIdx].bTracked == false)
                {
                    continue;
                }
                string body_s = "\"body_" + bodyIdx.ToString(CultureInfo.InvariantCulture) + "\":{";
                streamWriter.WriteLine(body_s);
                streamWriter.WriteLine("\"joints\": [");
                for (int j = 0; j < bodies[bodyIdx].lJoints.Count; j++)
                {
                    streamWriter.WriteLine("\"" +
                                           bodies[bodyIdx].lJoints[j].jointType.ToString(CultureInfo.InvariantCulture) +
                                           "\":" +
                                           "[" + bodies[bodyIdx].lJoints[j].position.X.ToString(CultureInfo.InvariantCulture) + "," +
                                           bodies[bodyIdx].lJoints[j].position.Y.ToString(CultureInfo.InvariantCulture) + "," +
                                           bodies[bodyIdx].lJoints[j].position.Z.ToString(CultureInfo.InvariantCulture) +
                                           "]" + ","
                                           );
                }
                streamWriter.WriteLine("]");
                streamWriter.WriteLine("},");
            }

            streamWriter.WriteLine("]}");
            streamWriter.Flush();
            fileStream.Close();
        }
Example #33
0
        public void Save(List <TimeModel> items)
        {
            if (items == null)
            {
                return;
            }

            using (var writer = new System.IO.StreamWriter(FilePath))
            {
                var serializer = new XmlSerializer(typeof(List <TimeModel>));
                serializer.Serialize(writer, items);
                writer.Flush();
            }
        }
Example #34
0
        static private void write_to_file(string logstr)
        {
            DateTime dt = DateTime.Now;

            if (sw_ == null)
            {
                int    pid      = Process.GetCurrentProcess().Id;
                string str      = pid.ToString() + "_" + dt.ToString("yyyy-MM-dd");
                string log_path = log_path_ + str + ".txt";
                sw_ = System.IO.File.AppendText(log_path);
            }
            sw_.WriteLine(dt.ToString("HH:mm:ss ") + logstr);
            sw_.Flush();
        }
    byte[] myBuffer = new byte[1024 * 1024]; // 1 1MB
    IEnumerator SendWebRequestAsync()
    {
        tc = new TcpClient();

        tc.Connect(ipCamera, 8080);
        ns = tc.GetStream();

        var sw = new System.IO.StreamWriter(ns);

        //using (var sr = new System.IO.StreamReader(ns))
        //{
        string DigestAnswer = d.GrabResponse("/stream/video/mjpeg");

        Debug.Log("Got digest:\n" + DigestAnswer);

        Debug.Log("Sending request...");
        string req = Request2_WithAuth.Replace("{0}", DigestAnswer);// String.Format(Request2_WithAuth, DigestAnswer);

        sw.Write(req);
        sw.Flush();

        Debug.Log("Getting Response...");

        // Read main headers:
        string allHeaders = readUntilEndHeaders(ns);

        Debug.Log("[*] Main Headers:\n" + allHeaders);

        string myBoundary = "--" + findBetween(allHeaders, "=", "--") + "--";


        // Read each FRAME:
        while (true)
        {
            readUntilBuffer(ns, myBoundary);

            string allMySubHeaders = readUntilEndHeaders(ns);
            //Debug.Log("************ JPEG Headers:\n\n" + allMySubHeaders);

            // Analyze JPEG:
            int length =
                int.Parse(
                    findBetween(allMySubHeaders, "Content-Length: ", "\r\n")
                    );

            getJPEG(ns, length);

            yield return(new WaitForEndOfFrame());
        }
    }
Example #36
0
        /// <summary>
        /// Saves to an xml file
        /// </summary>
        public void Save()
        {
            Directory.CreateDirectory(Path.GetDirectoryName(AppPaths.SettingsPath));
            // Directory.CreateDirectory(NaturalGroundingFolder);

            using (var writer = new System.IO.StreamWriter(AppPaths.SettingsPath)) {
                var serializer             = new XmlSerializer(typeof(SettingsFile));
                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add("", "");
                serializer.Serialize(writer, this, ns);
                writer.Flush();
            }
            Settings.RaiseSettingsChanged();
        }
Example #37
0
        //保存DOS执行日志到txt
        public void WriteCmdLog()
        {
            string txt = "[" + GetMachineName() + "]" + "\r\n\r\n" + textBox1.Text;

            logfilename = @"" + diskname.Trim() + filesavefolder + "\\" + "catchloglist_" + currentdate + ".log";
            //if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            //{
            //    filename = saveFileDialog1.FileName;
            //}
            System.IO.StreamWriter sw = new System.IO.StreamWriter(logfilename);
            sw.Write(txt);
            sw.Flush();
            sw.Close();
        }
    /// <summary>
    /// Writes
    /// </summary>
    /// <param name="debug">If set to <c>true</c>, write all recorded </param>
    public void WriteToFile(bool debug = false)
    {
        TrainingPair trainingPair = new TrainingPair(this.goal);

        trainingPair.InitializeFromGame(this.self, this.self.transform.FindChild("FirstPersonCharacter").gameObject);

        // write to file with features and target movements
        if (debug)
        {
            //debug.Log (trainingPair.ToString ());
        }
        file.WriteLine(trainingPair.ToString());
        file.Flush();
    }
Example #39
0
        private Task _client_ReactionAdded(Cacheable<IUserMessage, ulong> arg1, ISocketMessageChannel arg2, SocketReaction arg3)
        {
            if (arg3.UserId.ToString() == ownerId && Messages.ContainsKey(arg1.Id))
            {
                System.IO.StreamWriter file = new System.IO.StreamWriter(Detector.DataPath, true);
                string msg = Messages[arg1.Id];
                List<string> messagesMutated = new List<string>();
                messagesMutated.Add(msg);
                for (var k = 0; k < 5; k++)
                {
                    string tmpMessage = msg;
                    for (var i = 0; i < msg.Length / 5; i++)
                    {
                        tmpMessage = tmpMessage.RemoveAt(rnd.Next(0, tmpMessage.Length));
                    }
                    messagesMutated.Add(tmpMessage);
                    tmpMessage = msg;
                    for (var i = 0; i < 1; i++)
                    {
                        tmpMessage = tmpMessage.RemoveAt(rnd.Next(0, tmpMessage.Length));
                    }
                    messagesMutated.Add(tmpMessage);
                }

                if (arg3.Emote.Name == "👍")
                {
                    foreach (var item in messagesMutated.Distinct())
                    {
                        if (item.Length > 3)
                        {
                            file.WriteLine($"1\t{item}");
                        }
                    }
                }
                if (arg3.Emote.Name == "👎")
                {
                    foreach (var item in messagesMutated.Distinct())
                    {
                        if (item.Length > 3)
                        {
                            file.WriteLine($"0\t{item}");
                        }
                    }
                }

                file.Flush();
                file.Close();
            }
            return Task.CompletedTask;
        }
Example #40
0
        private void mnuSave_Click(object sender, EventArgs e)
        {
            SaveFileDialog ofd = new SaveFileDialog();

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                using (System.IO.TextWriter tw = new System.IO.StreamWriter(ofd.FileName))
                {
                    tw.WriteLine(textBox1.Text);
                    tw.Flush();
                }
                MessageBox.Show("File saved to " + ofd.FileName);
            }
        }
Example #41
0
        private void ProcessDFNFile(UOXData.Script.Script myFile, string sName)
        {
            // In each section, check for any SCRIPT tags
            // If we find any, and they're of the format [[x]], replace the x
            // with the valid script number found in the earlier lookup
            foreach (UOXData.Script.ScriptSection mSect in myFile.Sections)
            {
                UOXData.Script.TagDataPair mPair = mSect.GetDataPair("SCRIPT");
                if (mPair != null)
                {
                    if (mPair.Data.Value.Trim().StartsWith("[["))
                    {                           // we have to do the lookup/replacement here ... what fun!
                        string mValue   = mPair.Data.Value;
                        int    startIdx = mValue.LastIndexOf("[");
                        int    endIdx   = mValue.IndexOf("]");
                        int    toLookup = UOXData.Conversion.ToInt32(mValue.Substring(startIdx + 1, endIdx - (startIdx + 1)));
                        mPair.Data.Value = pkgConfig.GetTranslatedNumber(toLookup).ToString();
                    }
                }
            }
            // OK, we've updated our scripts, isn't this wonderful?
            // Create a new text file with the appropriate name
            // and then pass the stream to myFile.Save()

            string dfnPath  = pkgConfig.DFNPath + pkgConfig.GetDFNSection(sName.Replace("\\", "/")) + pkgConfig.DirPath;
            string filePath = GetPath(sName.Replace("\\", "/"));

            string [] paths        = filePath.Split('/');
            string    buildingPath = dfnPath;

            if (!Directory.Exists(dfnPath))
            {
                Directory.CreateDirectory(dfnPath);
            }
            if (paths.Length > 1)
            {
                for (int i = 0; i < paths.Length; ++i)
                {
                    buildingPath += "/" + paths[i];
                    if (!Directory.Exists(buildingPath))
                    {
                        Directory.CreateDirectory(buildingPath);
                    }
                }
            }
            System.IO.StreamWriter ioStream = File.CreateText(buildingPath + GetFile(sName));
            myFile.Save(ioStream);
            ioStream.Flush();
            ioStream.Close();
        }
Example #42
0
        public static string saveEmail(Rfc822Message msg, long issueId, long acctId, string uid)
        {
            string filename = "";

            if ((GlobalShared.mailInDir != null) & !string.IsNullOrEmpty(GlobalShared.mailInDir.Trim()))
            {
                filename = string.Format(GlobalShared.popFilename, GlobalShared.mailInDir, acctId, issueId, DateTime.Now, uid, "txt");
                System.IO.StreamWriter sw = new System.IO.StreamWriter(filename, false);
                sw.Write(messageFormat(msg));
                sw.Flush();
                sw.Close();
            }
            return(filename);
        }
Example #43
0
        private void saveFileXML()
        {
            if (xml_fileNameOUT.Length == 0)
            {
                return;
            }

            using (System.IO.StreamWriter file =
                       new System.IO.StreamWriter(xml_fileNameOUT))
            {
                file.Write(xml_data);
                file.Flush();
            }
        }
Example #44
0
        public void ImplicitSubReturnTypes()
        {
            var stream    = new System.IO.MemoryStream();
            var writer    = new System.IO.StreamWriter(stream);
            var generator = new CSharpGenerator(writer);
            var root      = new ApisRoot
            {
                ApiGroups = new List <ApiGroup>()
                {
                    new ApiGroup
                    {
                        Name        = "g",
                        Methods     = new List <ApiMethod>(),
                        ReturnTypes = new List <ReturnType>()
                        {
                            new ReturnType
                            {
                                Name   = "r1",
                                Fields = new List <Field>()
                                {
                                    new Field
                                    {
                                        Name = "f1",
                                    },
                                    new Field
                                    {
                                        Name = "f2:(r2:(name))",
                                    },
                                },
                            },
                        },
                    },
                },
            };
            var builder = new ServiceDefinitionBuilder();

            builder.AppendServiceDefinition(new ServiceDefinition(root));
            generator.Run(builder.Definition);

            writer.Flush();
            stream.Seek(0L, System.IO.SeekOrigin.Begin);
            var result = new StreamReader(stream).ReadToEnd();

            Assert.IsFalse(string.IsNullOrEmpty(result));
            Assert.IsTrue(result.Contains("public class R1"));
            Assert.IsTrue(result.Contains("public class F2"));
            Assert.IsTrue(result.Contains("public string F1"));
            Assert.IsTrue(result.Contains("public F2 F2"));
            Assert.IsTrue(result.Contains("public string Name"));
        }
Example #45
0
        public void Flush(Agent pAgent)
        {
#if !BEHAVIAC_RELEASE
            if (Config.IsLogging)
            {
                System.IO.StreamWriter fp = GetFile(pAgent);

                lock (fp)
                {
                    fp.Flush();
                }
            }
#endif
        }
        protected void btnlaunch_Click(object sender, EventArgs e)
        {
            string strFileName = Request.PhysicalApplicationPath + @"launch.txt";

            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(strFileName, false))
            {
                string strErrorString = txtpromo.Text.Trim();
                sw.Write(strErrorString);
                sw.Flush();
                sw.Close();
            }
            homepagecontent.Style["display"] = "block";
            Response.Redirect(Request.Url.AbsoluteUri);
        }
Example #47
0
    public static void CollectAllResources()
    {
        List <string> res = BuildProjectExWizard.GetAllResources();

        System.IO.FileStream   fs = System.IO.File.Open("AllResources.txt", System.IO.FileMode.OpenOrCreate);
        System.IO.StreamWriter sw = new System.IO.StreamWriter(fs);
        foreach (string r in res)
        {
            sw.WriteLine(r);
        }
        sw.Flush();
        sw.Close();
        fs.Close();
    }
Example #48
0
        /// <summary>
        /// Renders the dot content to a new image file (in the temporary directory) and returns the file path.
        /// </summary>
        /// <param name="dotContent"></param>
        /// <param name="imageExtension"></param>
        /// <returns></returns>
        public static string RenderImage(string dotContent, string imageExtension)
        {
            if (String.IsNullOrEmpty(imageExtension))
            {
                throw new ArgumentNullException("imageExtension");
            }

            string dotEngine = ResolveDotEnginePath();

            string imageTempFilePath = Path.GetTempFileName() + "." + imageExtension;
            string extension         = imageExtension.Trim(' ', '.').ToLowerInvariant();
            string dotContentPath    = imageTempFilePath + ".dotcontent";

            try
            {
                // Write the dot content to a file.
                using (var sw = new System.IO.StreamWriter(File.Open(dotContentPath, FileMode.OpenOrCreate), Encoding.GetEncoding("iso-8859-1")))
                {
                    sw.Write(dotContent);
                    sw.Flush();
                }

                System.Diagnostics.Process process = new System.Diagnostics.Process();

                // Stop the process from opening a new window
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.UseShellExecute        = false;
                process.StartInfo.CreateNoWindow         = true;

                // Setup executable and parameters
                process.StartInfo.FileName  = dotEngine;
                process.StartInfo.Arguments = String.Format("\"{0}\" -T{1} -o \"{2}\" -Gdpi=72 -Gsize=\"6, 8.5\"", dotContentPath, extension, imageTempFilePath);

                // Go
                process.Start();

                // and wait dot.exe to complete and exit
                process.WaitForExit();
            }
            finally
            {
                // Remove the temp file again
                if (!String.IsNullOrEmpty(dotContentPath) && File.Exists(dotContentPath))
                {
                    File.Delete(dotContentPath);
                }
            }

            return(imageTempFilePath);
        }
Example #49
0
        public bool Store(string path)
        {
            System.IO.FileStream   stream = new System.IO.FileStream(path, System.IO.FileMode.Create);
            System.IO.StreamWriter writer = new System.IO.StreamWriter(stream, System.Text.Encoding.UTF8);

            //シリアライズ
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(Project));
            serializer.Serialize(writer, this);

            writer.Flush();
            writer.Close();

            return(true);
        }
Example #50
0
        private string CreateDailySales(DateTime pvtProcessDate, Data.TerminalReportDetails pvtTerminalReportDetails, decimal decSeniorCitizenDiscount, long lngSeniorCitizenDiscountCount)
        {
            string strRetValue = "";

            try
            {
                string stDailyTableName = mclsFSIDetails.OutputDirectory + "\\S" + mclsFSIDetails.TenantName.Substring(0, 4) + pvtTerminalReportDetails.TerminalNo + pvtTerminalReportDetails.BatchCounter.ToString() + "." + pvtTerminalReportDetails.DateLastInitializedToDisplay.ToString("MM").Replace("10", "A").Replace("11", "B").Replace("12", "C").Replace("0", "") + pvtTerminalReportDetails.DateLastInitializedToDisplay.ToString("dd");
                if (File.Exists(stDailyTableName))
                {
                    File.Delete(stDailyTableName);
                }

                long    lngDiscountCountNetOfSeniorCitizen = pvtTerminalReportDetails.NoOfDiscountedTransactions - lngSeniorCitizenDiscountCount;
                decimal decDiscountNetOfSeniorCitizen      = pvtTerminalReportDetails.TotalDiscount - decSeniorCitizenDiscount;

                writer = File.AppendText(stDailyTableName);
                writer.WriteLine("01{0}", mclsFSIDetails.TenantCode);
                writer.WriteLine("02{0}", pvtTerminalReportDetails.TerminalNo);
                writer.WriteLine("03{0}", pvtTerminalReportDetails.DateLastInitializedToDisplay.ToString("MMddyyyy"));
                writer.WriteLine("04{0}", pvtTerminalReportDetails.OldGrandTotal.ToString("####.#0").Replace(".", ""));
                writer.WriteLine("05{0}", pvtTerminalReportDetails.NewGrandTotal.ToString("####.#0").Replace(".", ""));
                writer.WriteLine("06{0}", Convert.ToDecimal(pvtTerminalReportDetails.DailySales + pvtTerminalReportDetails.VAT).ToString("####.#0").Replace(".", ""));
                writer.WriteLine("07{0}", pvtTerminalReportDetails.NonVATableAmount.ToString("####.#0").Replace(".", ""));
                writer.WriteLine("08{0}", decSeniorCitizenDiscount.ToString("####.#0").Replace(".", ""));
                writer.WriteLine("09{0}", "0");
                writer.WriteLine("10{0}", decDiscountNetOfSeniorCitizen.ToString("####.#0").Replace(".", ""));
                writer.WriteLine("11{0}", pvtTerminalReportDetails.RefundSales.ToString("####.#0").Replace(".", ""));
                writer.WriteLine("12{0}", pvtTerminalReportDetails.VoidSales.ToString("####.#0").Replace(".", ""));
                writer.WriteLine("13{0}", pvtTerminalReportDetails.ZReadCount.ToString("####.#0").Replace(".", ""));
                writer.WriteLine("14{0}", pvtTerminalReportDetails.NoOfClosedTransactions.ToString("####"));
                writer.WriteLine("15{0}", pvtTerminalReportDetails.NoOfTotalTransactions.ToString("####"));
                writer.WriteLine("16{0}", mclsFSIDetails.SalesTypeCode);
                writer.WriteLine("17{0}", pvtTerminalReportDetails.DailySales.ToString("####.#0").Replace(".", ""));
                decimal decVAT = pvtTerminalReportDetails.DailySales * decimal.Parse("0.12");
                writer.WriteLine("18{0}", decVAT.ToString("####.#0").Replace(".", ""));
                writer.WriteLine("19{0}", pvtTerminalReportDetails.TotalCharge.ToString("####.#0").Replace(".", ""));
                writer.WriteLine("20{0}", "0"); //adjustment

                writer.Flush();
                writer.Close();

                strRetValue = stDailyTableName;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(strRetValue);
        }
Example #51
0
        private void simpleButton6_Click(object sender, EventArgs e)
        {
            var    web2       = new HtmlWeb();
            string currentUri = @"https://ru.mouser.com/ProductDetail/TE-Connectivity/M85049-93-16?qs=2WXlatMagcH45qgLJ7jojA%3D%3D";
            var    doc2       = web2.LoadFromBrowser(HttpUtility.HtmlDecode(currentUri), o =>
            {
                WebBrowser webBrowser = (WebBrowser)o;
                // WAIT until the dynamic text is set
                return(!string.IsNullOrEmpty(webBrowser.Document.GetElementById("mlnkMailTo").InnerText));
            });

            int sds = 3;

            return;

            try
            {
                Console.WriteLine(String.Format("*** Begin Request ***"));
                var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://api.PhantomJScloud.com/api/browser/v2/a-demo-key-with-low-quota-per-ip-address/");
                request.ContentType = "application/json";
                request.Method      = "POST";
                request.Timeout     = 45000; //45 seconds
                request.KeepAlive   = false;
                request.MediaType   = "application/json";
                request.ServicePoint.Expect100Continue = false; //REQUIRED! or you will get 502 Bad Gateway errors
                using (var streamWriter = new System.IO.StreamWriter(request.GetRequestStream()))
                {
                    //you should look at the HTTP Endpoint docs, section about "userRequest" and "pageRequest"
                    //for a listing of all the parameters you can pass via the "pageRequestJson" variable.
                    string pageRequestJson = @"{'url':'https://ru.mouser.com/ProductDetail/TE-Connectivity/M85049-93-16?qs=2WXlatMagcH45qgLJ7jojA%3D%3D','renderType':'plainText','outputAsJson':true }";
                    streamWriter.Write(pageRequestJson);
                    streamWriter.Flush();
                    streamWriter.Close();
                }
                var response = (System.Net.HttpWebResponse)request.GetResponse();
                Console.WriteLine(String.Format("HttpWebResponse.StatusDescription: {0}", response.StatusDescription));
                using (var streamReader = new System.IO.StreamReader(response.GetResponseStream()))
                {
                    string server_reply = streamReader.ReadToEnd();
                    Console.WriteLine(String.Format("Server Response content: {0}", server_reply));
                }
                response.Close();
            }
            catch (Exception Ex)
            {
                Console.WriteLine("*** HTTP Request Error ***");
                Console.WriteLine(Ex.Message);
            }
        }
Example #52
0
        public void BackUp(string binDir, string backupDir, string host, int port
                           , string dbname, string username, string password, bool visible)
        {
            if (!Directory.Exists(binDir))
            {
                throw new Exception("Не е намерена директория '" + binDir + "'");
            }
            if (!Directory.Exists(backupDir))
            {
                throw new Exception("Не е намерена директория '" + backupDir + "' за бекъп");
            }

            string batFile = Path.Combine(backupDir, "backup.bat");

            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(batFile))
            {
                sw.WriteLine("@echo off");
                sw.WriteLine("SET PGPASSWORD="******"echo on");

                string dumpFile   = System.IO.Path.Combine(binDir, "pg_dump.exe");
                string backupFile = System.IO.Path.Combine(backupDir, dbname + "_" + DateTime.Now.ToString("yyyy.MM.dd_HHmmss") + ".backup");

                sw.WriteLine("\"" + dumpFile + "\" -i -h " + host +
                             " -p " + port.ToString() +
                             " -U " + username +
                             " -F c -b -v -f \"" + backupFile + "\" " + dbname);

                sw.WriteLine("del \"" + batFile + "\"");
                sw.Flush();
                sw.Close();
            }

            using (System.Diagnostics.Process processBackup = new System.Diagnostics.Process())
            {
                processBackup.StartInfo.FileName       = batFile;
                processBackup.StartInfo.CreateNoWindow = true;
                if (visible)
                {
                    processBackup.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                }
                else
                {
                    processBackup.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                }
                //processBackup.StartInfo.Verb = "print";
                processBackup.Start();
            }
        }
Example #53
0
        public void ExportAnimation()
        {
            using (System.Windows.Forms.SaveFileDialog a = new System.Windows.Forms.SaveFileDialog
            {
                FileName = ActionName + ".saanim",
                Filter = "SAModel Animations|*.saanim|JSON|*.json|C structs|*.c"
            })
            {
                if (a.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    switch (System.IO.Path.GetExtension(a.FileName).ToLowerInvariant())
                    {
                    case ".c":
                    case ".txt":
                        using (System.IO.StreamWriter sw = System.IO.File.CreateText(a.FileName))
                        {
                            sw.WriteLine("/* NINJA Motion");
                            sw.WriteLine(" * ");
                            sw.WriteLine(" * Generated by DataToolbox");
                            sw.WriteLine(" * ");
                            sw.WriteLine(" */");
                            sw.WriteLine();
                            GeoAnim.Animation.ToStructVariables(sw);
                            sw.Flush();
                            sw.Close();
                        }
                        break;

                    case ".json":
                        Newtonsoft.Json.JsonSerializer js = new Newtonsoft.Json.JsonSerializer()
                        {
                            Culture = System.Globalization.CultureInfo.InvariantCulture
                        };
                        using (TextWriter tw = File.CreateText(a.FileName))
                            using (JsonTextWriter jtw = new JsonTextWriter(tw)
                            {
                                Formatting = Formatting.Indented
                            })
                                js.Serialize(jtw, GeoAnim.Animation);
                        break;

                    case ".saanim":
                    default:
                        GeoAnim.Animation.Save(a.FileName);
                        break;
                    }
                }
            }
        }
Example #54
0
        private void Complete_Btn_Click(object sender, EventArgs e)
        {
            float[] tmp1 = new float[resListView.Items.Count];
            float[] tmp2 = new float[resListView.Items.Count];

            try
            {
                for (int c = 0; c < resListView.Items.Count; c++)
                {
                    tmp1[c] = float.Parse(resListView.Items[c].SubItems[0].Text, CultureInfo.InvariantCulture.NumberFormat);
                    tmp2[c] = float.Parse(resListView.Items[c].SubItems[1].Text, CultureInfo.InvariantCulture.NumberFormat);
                }
                Array.Sort(tmp1, tmp2);
            }
            catch { MessageBox.Show("Error in input values! Please try again.", "Error!"); return; }

            if (changed)
            {
                SaveFileDialog save = new SaveFileDialog()
                {
                    Title = "Save 'Custom Resolution' data", FileName = "Custom" + machine_enum.ToString(), Filter = "Data Files (*.cr)|*.cr", DefaultExt = "cr", OverwritePrompt = true, AddExtension = true
                };

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

                    file.WriteLine("Mode:\tCustom Resolution");
                    for (int r = 0; r < tmp1.Count(); r++)
                    {
                        file.WriteLine(tmp1[r] + "\t" + tmp2[r]);
                    }
                    new_machine = Path.GetFileNameWithoutExtension(save.FileName);
                    file.Flush(); file.Close(); file.Dispose();
                    Resolution_List.L.Add(new_machine, new Resolution_List.MachineR(tmp1, tmp2));
                    active = false;
                    this.Close();
                }
            }
            else
            {
                //var result = tmp2.Select(n => n * 1.5f);
                //tmp2 = result.ToArray();
                new_machine = loaded_res_name;
                Resolution_List.L.Add(new_machine, new Resolution_List.MachineR(tmp1, tmp2));
                active = false;
                this.Close();
            }
        }
Example #55
0
        private void SaveFile(string path, List <TeaCertificate> failList)
        {
            try
            {
                List <TeaViewModel> teaViewModelList = failList.Select(g => new TeaViewModel()
                {
                    TeacherName = g.Name, Area = GetAreaStr(g.Province, g.City), Category = g.Category, Gender = g.Gender, Number = g.Number, Level = g.Level
                }).ToList();

                List <ExcelHeaderColumn> excelList = new List <ExcelHeaderColumn>()
                {
                    new ExcelHeaderColumn()
                    {
                        DisplayName = "教师姓名", Name = "TeacherName"
                    },
                    new ExcelHeaderColumn()
                    {
                        DisplayName = "性别", Name = "GenderName"
                    },
                    new ExcelHeaderColumn()
                    {
                        DisplayName = "教师级别", Name = "LevelName"
                    },
                    new ExcelHeaderColumn()
                    {
                        DisplayName = "证书编号", Name = "Number"
                    },
                    new ExcelHeaderColumn()
                    {
                        DisplayName = "所在地区", Name = "Area"
                    },
                    new ExcelHeaderColumn()
                    {
                        DisplayName = "证书类型", Name = "CategoryName"
                    },
                };

                byte[] bytes = ExcelHelper.ExportCsvByte(teaViewModelList, excelList);

                System.IO.StreamWriter stream = new System.IO.StreamWriter(path, false, Encoding.UTF8);
                stream.Write(Encoding.Default.GetString(bytes));
                stream.Flush();
                stream.Close();
                stream.Dispose();
            }
            catch
            {
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["download"] != null)
            {
                string         id         = Request.QueryString["download"];
                DataCollection collection = BaseObject.GetById <DataCollection>(new Guid(id));
                string         fileName   = collection.Name + ".csv";


                System.IO.MemoryStream stream = new System.IO.MemoryStream();
                System.IO.StreamWriter writer = new System.IO.StreamWriter(stream, System.Text.Encoding.Unicode);

                //if (webshopMode)
                //{
                //    ((WebshopDataCollection)dataModule.ConvertToType()).MakeDownload(writer);
                //}
                //else
                //{
                //collection.MakeDownload(writer);
                //}

                writer.Flush();
                // Convert the memory stream to an array of bytes.
                byte[] byteArray = stream.ToArray();

                // Send the file to the web browser for download.
                Response.Clear();
                Response.AppendHeader("Content-Disposition", "filename=" + fileName);
                Response.AppendHeader("Content-Length", byteArray.Length.ToString());
                Response.ContentType = "application/octet-stream";
                Response.ContentType = "";
                Response.BinaryWrite(byteArray);
                writer.Close();
            }
            else
            {
                HttpFileCollection files = Request.Files;

                string[] arr1 = files.AllKeys;  // This will get names of all files into a string array.
                for (int loop1 = 0; loop1 < arr1.Length; loop1++)
                {
                    DataCollectionService.fileToImport = files[loop1];
                }

                Response.Write("File: " + Server.HtmlEncode(DataCollectionService.fileToImport.FileName) + "<br />");
                Response.Write("  size: " + DataCollectionService.fileToImport.ContentLength + "<br />");
                Response.Write("<br />");
            }
        }
Example #57
0
        public void saveMDFile(KonfigurationOneNote onenoteConf)
        {
            System.IO.Directory.CreateDirectory(this.getPagePath(onenoteConf));
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(this.getPagePath(onenoteConf) + @"README.md"))
            {
                file.WriteLine("# " + this.name);
                file.WriteLine("");
                foreach (Paragraph paragraph in paragraphs)
                {
                    String renderedText = paragraph.render(onenoteConf);

                    renderedText = this.RenderInternalLinks(renderedText);

                    file.WriteLine(renderedText);
                }

                file.Flush();
                file.Close();
            }

            foreach (Page page in childPages)
            {
                page.saveMDFile(onenoteConf);
            }

            foreach (ContentImage image in images)
            {
                image.saveImage(onenoteConf);
            }

            // rename thumbnail image as "icon.png"
            if (thumbnail != null)
            {
                thumbnail.renameToIcon();
                thumbnail.saveImage(onenoteConf);
            }

            try
            {
                this.readImages(onenoteConf);
            }
            catch (Exception e)
            {
                Debug.WriteLine("ERROR: reading images failed " + e.Message);
            }


            Debug.WriteLine("Finished page");
        }
Example #58
0
        public override void RunTests(System.IO.StreamWriter writer)
        {
            if (writer == null)
            {
                throw new ArgumentNullException(nameof(writer));
            }
            var testResults = string.Empty;

            using (var op = _connection.OperationStarting(null, null)) {
                testResults = _connection
                              .ExecuteCommandsWithManagedConnection <string>(x => f(x));
            }
            writer.WriteLine(testResults);
            writer.Flush();
        }
Example #59
0
        public static void Log(string msg)
        {
            var debugMode = ConfigurationManager.AppSettings["DebugMode"].ToBool();

            if (debugMode == true)
            {
                var appDir   = AppRootDirectory();
                var fileName = string.Format("{0}\\Doku4Signatures.log", appDir);
                using (var sw = new System.IO.StreamWriter(fileName, true))
                {
                    sw.Write(string.Format("{0} - {1}\n", DateTime.Now, msg));
                    sw.Flush();
                }
            }
        }
Example #60
-1
        /// <summary>
        /// Serializes all of the data in <paramref name="settings"/> and writes the data to the file
        /// specified in the <see cref="Path"/>.
        /// </summary>
        /// <param name="settings">The collection of settings to serialize.</param>
        public void Save(Dictionary<string, object> settings)
        {
            try
            {
                // try to serialize first, before we overwrite the file
                string data = SerializeObject(settings);

                FileStream stream = new FileStream(this.path, FileMode.Create, FileAccess.Write);
                using (stream)
                {
                    StreamWriter writer = new StreamWriter(stream);
                    using (writer)
                    {
                        writer.Flush();
                        writer.BaseStream.Seek(0, SeekOrigin.Begin);
                        writer.Write(data);
                        writer.Flush();
                        writer.Close();
                    }
                    stream.Close();
                }
            }
            catch
            {
                throw;
            }
        }