Flush() public method

public Flush ( ) : void
return void
        public override byte[] GetEncoding()
        {
            try
            {
                MemoryStream outputStream = new MemoryStream();
                BinaryWriter binaryWriter = new BinaryWriter(new BufferedStream(outputStream));

                MessagesEncodingUtil.WriteMessageType(binaryWriter, this);

                if (PeerAddress.PrivateEndPoint == null)
                    MessagesEncodingUtil.WriteString(binaryWriter, "null");
                else
                    MessagesEncodingUtil.WriteString(binaryWriter, PeerAddress.PrivateEndPoint.ToString());

                if (PeerAddress.PublicEndPoint == null)
                    MessagesEncodingUtil.WriteString(binaryWriter, "null");
                else
                    MessagesEncodingUtil.WriteString(binaryWriter, PeerAddress.PublicEndPoint.ToString());

                binaryWriter.Flush();

                byte[] buffer = outputStream.ToArray();

                if (buffer.Length <= EncodingConstants.MAX_MESSAGE_LENGTH)
                    return outputStream.ToArray();
                else
                    throw new BinaryEncodingException();
            }
            catch (Exception)
            {
                throw new BinaryEncodingException("Decode");
            }
        }
 public void TestIncompleteRewind()
 {
     MemoryStream ms = new MemoryStream();
     BinaryWriter bw = new BinaryWriter(ms);
     bw.Write(1);
     bw.Write(2);
     bw.Write(3);
     bw.Write(4);
     bw.Write(5);
     bw.Write(6);
     bw.Write(7);
     bw.Flush();
     ms.Position = 0;
     RewindableStream stream = new RewindableStream(ms);
     stream.StartRecording();
     BinaryReader br = new BinaryReader(stream);
     Assert.AreEqual(br.ReadInt32(), 1);
     Assert.AreEqual(br.ReadInt32(), 2);
     Assert.AreEqual(br.ReadInt32(), 3);
     Assert.AreEqual(br.ReadInt32(), 4);
     stream.Rewind(true);
     Assert.AreEqual(br.ReadInt32(), 1);
     Assert.AreEqual(br.ReadInt32(), 2);
     stream.StartRecording();
     Assert.AreEqual(br.ReadInt32(), 3);
     Assert.AreEqual(br.ReadInt32(), 4);
     Assert.AreEqual(br.ReadInt32(), 5);
     stream.Rewind(true);
     Assert.AreEqual(br.ReadInt32(), 3);
     Assert.AreEqual(br.ReadInt32(), 4);
     Assert.AreEqual(br.ReadInt32(), 5);
     Assert.AreEqual(br.ReadInt32(), 6);
     Assert.AreEqual(br.ReadInt32(), 7);
 }
Esempio n. 3
0
        public void FlushAndWriteCatalogs(BinaryWriter writer)
        {
            writer.Write((uint)m_stringsDict.Count);
            writer.Flush();
            m_stringsCatalogWriter.Flush();
            m_stringsCatalogStream.WriteTo(writer.BaseStream);

            writer.Write((uint)m_typeNameTagsDict.Count);
            writer.Flush();
            m_typeNameCatalogWriter.Flush();
            m_typeNameCatalogStream.WriteTo(writer.BaseStream);

            writer.Write((uint)m_typeSpecTagsDict.Count);
            writer.Flush();
            m_typeCatalogWriter.Flush();
            m_typeCatalogStream.WriteTo(writer.BaseStream);

            writer.Write((uint)m_methodSignaturesDict.Count);
            writer.Flush();
            m_methodSignatureCatalogWriter.Flush();
            m_methodSignatureCatalogStream.WriteTo(writer.BaseStream);

            writer.Write((uint)m_methodDeclTagsDict.Count);
            writer.Flush();
            m_methodDeclCatalogWriter.Flush();
            m_methodDeclCatalogStream.WriteTo(writer.BaseStream);

            writer.Write((uint)m_methodSpecDict.Count);
            writer.Flush();
            m_methodSpecCatalogWriter.Flush();
            m_methodSpecCatalogStream.WriteTo(writer.BaseStream);
        }
Esempio n. 4
0
        public static void writeVectorToFile(MathNet.Numerics.LinearAlgebra.Double.DenseVector vector, string file, System.Windows.Forms.RichTextBox tb1, MainForm frm)
        {
            System.IO.Stream       fileStream = new System.IO.FileStream(file, System.IO.FileMode.Create);
            System.IO.BinaryWriter bw         = new System.IO.BinaryWriter(fileStream, System.Text.Encoding.Default);
            double[]             arr          = vector.Values;
            System.IO.TextWriter tr           = new System.IO.StreamWriter(file + ".metainfo");
            tr.WriteLine("Items count");
            tr.WriteLine(vector.Count);
            tr.Flush();
            tr.Close();
            int len = arr.Length;

            vector = null;
            int index = 0;

            byte[] bytes = new byte[arr.Length * 8];
            foreach (double item in arr)
            {
                BitConverter.GetBytes(item).CopyTo(bytes, index);
                if (index / 8 / 500D == Math.Round(index / 8 / 500D))
                {
                    tb1.BeginInvoke(new MainForm.setProgressDel(frm.addVal), new object[] { (int)index / 8, len, "Записано" });
                }
                index += 8;
            }
            bw.Write(bytes);
            bw.Flush();
            tb1.BeginInvoke(new MainForm.setProgressDel(frm.addVal), new object[] { (int)0, len, "" });
            bw.Flush();
            bw.Close();
            fileStream.Close();
        }
Esempio n. 5
0
File: NDS.cs Progetto: MetLob/tinke
        public static void EscribirBanner(string salida, Estructuras.Banner banner)
        {
            BinaryWriter bw = new BinaryWriter(new FileStream(salida, FileMode.Create));
            Console.Write("Banner...");

            bw.Write(banner.version);
            bw.Write(banner.CRC16);
            bw.Write(banner.reserved);
            bw.Write(banner.tileData);
            bw.Write(banner.palette);
            bw.Write(StringToTitle(banner.japaneseTitle));
            bw.Write(StringToTitle(banner.englishTitle));
            bw.Write(StringToTitle(banner.frenchTitle));
            bw.Write(StringToTitle(banner.germanTitle));
            bw.Write(StringToTitle(banner.italianTitle));
            bw.Write(StringToTitle(banner.spanishTitle));
            bw.Flush();

            int rem = (int)bw.BaseStream.Position % 0x200;
            if (rem != 0)
            {
                while (rem < 0x200)
                {
                    bw.Write((byte)0xFF);
                    rem++;
                }
            }
            bw.Flush();

            Console.WriteLine(Tools.Helper.GetTranslation("Messages", "S09"), bw.BaseStream.Length);
            bw.Close();
        }
        /// <summary>
        /// Writes a packet's header and encrypts the contents of the packet (not the header).
        /// </summary>
        /// <param name="PacketID">The ID of the packet.</param>
        /// <param name="PacketData">The packet's contents.</param>
        /// <returns>The finalized packet!</returns>
        private static byte[] FinalizePacket(byte PacketID, DESCryptoServiceProvider CryptoService, byte[] PacketData)
        {
            MemoryStream FinalizedPacket = new MemoryStream();
            BinaryWriter PacketWriter = new BinaryWriter(FinalizedPacket);

            PasswordDeriveBytes Pwd = new PasswordDeriveBytes(Encoding.ASCII.GetBytes(PlayerAccount.Client.Password),
                Encoding.ASCII.GetBytes("SALT"), "SHA1", 10);

            MemoryStream TempStream = new MemoryStream();
            CryptoStream EncryptedStream = new CryptoStream(TempStream,
                CryptoService.CreateEncryptor(PlayerAccount.EncKey, Encoding.ASCII.GetBytes("@1B2c3D4e5F6g7H8")),
                CryptoStreamMode.Write);
            EncryptedStream.Write(PacketData, 0, PacketData.Length);
            EncryptedStream.FlushFinalBlock();

            PacketWriter.Write(PacketID);
            //The length of the encrypted data can be longer or smaller than the original length,
            //so write the length of the encrypted data.
            PacketWriter.Write((byte)(3 + TempStream.Length));
            PacketWriter.Flush();
            //Also write the length of the unencrypted data.
            PacketWriter.Write((byte)PacketData.Length);
            PacketWriter.Flush();

            PacketWriter.Write(TempStream.ToArray());
            PacketWriter.Flush();

            byte[] ReturnPacket = FinalizedPacket.ToArray();

            PacketWriter.Close();

            return ReturnPacket;
        }
Esempio n. 7
0
        public override byte[] FinalizePacket(byte PacketID, byte[] PacketData)
        {
            MemoryStream FinalizedPacket = new MemoryStream();
            BinaryWriter PacketWriter = new BinaryWriter(FinalizedPacket);

            MemoryStream TempStream = new MemoryStream();
            CryptoStream EncryptedStream = new CryptoStream(TempStream,
                m_EncryptTransformer, CryptoStreamMode.Write);
            EncryptedStream.Write(PacketData, 0, PacketData.Length);
            EncryptedStream.FlushFinalBlock();

            PacketWriter.Write(PacketID);
            //The length of the encrypted data can be longer or smaller than the original length,
            //so write the length of the encrypted data.
            PacketWriter.Write((ushort)((long)PacketHeaders.ENCRYPTED + TempStream.Length));
            //Also write the length of the unencrypted data.
            PacketWriter.Write((ushort)PacketData.Length);
            PacketWriter.Flush();

            PacketWriter.Write(TempStream.ToArray());
            PacketWriter.Flush();

            byte[] ReturnPacket = FinalizedPacket.ToArray();

            PacketWriter.Close();

            return ReturnPacket;
        }
Esempio n. 8
0
        public static void ProcessRequest(ClientWebRequest equest)
        {
            lock(syncobj) {
            if(db == null) {
            db = new PubKeyDatabase("default",File.Open("OpenNetDB_client",FileMode.OpenOrCreate));

            }
            if(db.Length == 0) {
            db.AddPublicKey(db.GenPublicPrivateKey(2048));
            db.GetPublicKeyOnly(db[0]);
            }
            Uri url = new Uri("http:/"+equest.UnsanitizedRelativeURI.Replace("idw.local.ids","127.0.0.1"));
            if(!drivers.ContainsKey(url.Host)) {
            Console.WriteLine("Connecting to "+url.Host);
                HttpWebRequest request = HttpWebRequest.Create("http://"+url.Host+"/OpenNetProvider") as HttpWebRequest;
            request.AllowWriteStreamBuffering = false;
            Stream receiver = new TrashyStream(request.GetResponse().GetResponseStream());
            BinaryReader mreader = new BinaryReader(receiver);
            byte[] guid = mreader.ReadBytes(16);
            Console.WriteLine(BitConverter.ToString(guid));
            request = HttpWebRequest.Create("http://"+url.Host+"/OpenNetProvider") as HttpWebRequest;
            request.Method = "POST";
            request.ContentLength = 9999999999;
            request.AllowWriteStreamBuffering = false;
            Stream sender = new TrashyStream(request.GetRequestStream());
            BinaryWriter mwriter = new BinaryWriter(sender);
            mwriter.Write(guid);
            mwriter.Flush();
            byte[] theirpubkey = mreader.ReadBytes(mreader.ReadInt32());
            Stream dbStr = File.Open("keyDB.db", FileMode.OpenOrCreate);

            byte[] ourpublickey = db.GetPublicKeyOnly(db[0]);
            byte[] ourprivatekey = db[0];
            mwriter.Write(ourpublickey.Length);
            mwriter.Write(ourpublickey);
            mwriter.Flush();
            db.AddPublicKey(theirpubkey);
            Stream securedStream = new TrashyStream(db.CreateAuthenticatedStream(ourprivatekey, new DualStream(sender, receiver), 32));

            Console.WriteLine("Secure stream negotiated");

            driver = new OpenNetProtocolDriver(securedStream);
            drivers.Add(url.Host,driver);
                Console.WriteLine("Driver initialized");

            }
                mvent.Reset();
            currentRequest = equest;
                currentURL = url;
                driver = drivers[url.Host];
                drivers[url.Host].onConnectionEstablished += HandleonConnectionEstablished;

                drivers[url.Host].OpenStream();

                mvent.WaitOne();

            }
        }
Esempio n. 9
0
  private void WriteFramesToFfmpeg() {
    Bytable curFrame = null;
    byte[] buf = null;
    System.IO.BinaryWriter dataPipe = m_dataWriter;

    try {
      while (!m_shouldExit) {
        while (!m_shouldPause) {
          // Wait for the next frame to arrive.
          m_frameReady.WaitOne();
          m_frameWritten.Reset();

          // Grab the frame.
          curFrame = Interlocked.Exchange(ref m_frame, curFrame);

          if (curFrame == null || curFrame.Length == 0) {
            // This really shouldn't happen.
            UnityEngine.Debug.LogWarning("FfmpegPipe recieved invalid frame");
            m_frameWritten.Set();
            continue;
          }

          curFrame.ToBytes(ref buf);
          dataPipe.Write(buf);

          if (ReleaseFrame != null) {
            ReleaseFrame(curFrame);
          }

          m_frameCount++;

          m_frameWritten.Set();

          // It's safe to throw this memory away, because Unity is transferring ownership.
          curFrame = null;
        }

        // Wait for the next frame
        m_ready.WaitOne();
      }

      dataPipe.Flush();
      dataPipe.Close();

    } catch (System.Threading.ThreadInterruptedException) {
      // This is fine, the render thread sent an interrupt.
      dataPipe.Flush();
      dataPipe.Close();
    } catch (System.Exception e) {
      UnityEngine.Debug.LogWarning(m_outputFile);
      UnityEngine.Debug.LogException(e);
    }
  }
Esempio n. 10
0
        public void getBlob(int parent_refno)
        {
            string connStr = "Data Source=192.168.45.17;Initial Catalog=NLS;User Id=gvandell;Password=$#Escher1;";
            string sPath = null;
            int bufferSize = 100;
            byte[] outbyte = new byte[bufferSize];
            SqlConnection CN = new SqlConnection();
            SqlCommand CM = new SqlCommand();
            FileStream FS = null;
            BinaryWriter BW = null;
            long retVal;
            int StartIndex;
            string strSQL = "select VerificationDocsID, DocumentBIN from GlobalVerificationDocs where VerificationDocsID in (select top 1 VerificationDocsID from vw_doc_packets where parent_refno = " + parent_refno + " and grouping_name = '" + "Unsecured Doc Packet" + "' order by VerificationDocsID desc)";

            CN.ConnectionString = connStr;
            CN.Open();

            CM.Connection = CN;
            CM.CommandType = CommandType.Text;
            CM.CommandText = strSQL;

            SqlDataReader sqlDR = CM.ExecuteReader(CommandBehavior.SequentialAccess);
            while (sqlDR.Read())
            {
                sPath = HttpContext.Current.Server.MapPath(@"/docs/");
                FS = new FileStream(HttpContext.Current.Server.MapPath(@"/docs/SFC_" + DateTime.Today.Year + DateTime.Today.Month + DateTime.Today.Day + ".zip"), FileMode.OpenOrCreate, FileAccess.Write);

                BW = new BinaryWriter(FS);

                StartIndex = 0;
                retVal = sqlDR.GetBytes(1, StartIndex, outbyte, 0, bufferSize);

                while (retVal == bufferSize)
                {
                    BW.Write(outbyte, 0, (int)retVal);
                    BW.Flush();

                    StartIndex += bufferSize;
                    retVal = sqlDR.GetBytes(1, StartIndex, outbyte, 0, bufferSize);

                }

                BW.Write(outbyte, 0, (int)retVal);
                BW.Flush();

                BW.Close();
                FS.Close();
            }

            sqlDR.Close();
            CN.Close();
        }
Esempio n. 11
0
File: LINK.cs Progetto: MetLob/tinke
        public static void Pack(string fileIn, string fileOut, ref sFolder unpacked)
        {
            BinaryReader br = new BinaryReader(File.OpenRead(fileIn));
            br.BaseStream.Position = 0x08;
            uint block_size = br.ReadUInt32();
            br.Close();

            BinaryWriter bw = new BinaryWriter(File.OpenWrite(fileOut));

            bw.Write(new char[] { 'L', 'I', 'N', 'K' });
            bw.Write(unpacked.files.Count);
            bw.Write(block_size);
            bw.Write(0x00);

            unpacked.files.Sort(SortFiles);

            uint offset = block_size;
            List<byte> buffer = new List<byte>();
            for (int i = 0; i < unpacked.files.Count; i++)
            {
                br = new BinaryReader(File.OpenRead(unpacked.files[i].path));
                br.BaseStream.Position = unpacked.files[i].offset;
                buffer.AddRange(br.ReadBytes((int)unpacked.files[i].size));
                while (buffer.Count % block_size != 0)
                    buffer.Add(0x00);
                br.Close();

                bw.Write(offset / block_size);
                bw.Write(unpacked.files[i].size);

                sFile upFile = unpacked.files[i];
                upFile.offset = offset;
                upFile.path = fileOut;
                unpacked.files[i] = upFile;

                offset += unpacked.files[i].size;
                if (offset % block_size != 0)  // Padding
                    offset += (block_size - (offset % block_size));
            }
            byte[] rem = new byte[0];
            if (bw.BaseStream.Position % block_size != 0)
                rem = new byte[block_size - (bw.BaseStream.Position % block_size)];
            bw.Write(rem);
            bw.Flush();

            bw.Write(buffer.ToArray());
            bw.Flush();

            bw.Close();
        }
Esempio n. 12
0
    static void WriteToFile(string str)
    {
        if (logfile != null)
        {
#if ENCRYPT_LOG
            byte[] encrypted = XOREncrypter.EncryptToBytes(str);
            logfile.Write(encrypted.Length);
            logfile.Write(encrypted, 0, encrypted.Length);
            logfile.Flush();
#else
            logfile.Write(str);
            logfile.Flush();
#endif
        }
    }
Esempio n. 13
0
        public static void Append(ref BinaryWriter bw, ref BinaryReader br)
        {
            const int block_size = 0x80000; // 512 KB
            int size = (int)br.BaseStream.Length;

            while (br.BaseStream.Position + block_size < size)
            {
                bw.Write(br.ReadBytes(block_size));
                bw.Flush();
            }

            int rest = size - (int)br.BaseStream.Position;
            bw.Write(br.ReadBytes(rest));
            bw.Flush();
        }
Esempio n. 14
0
        private void buttonGenerate_Click(object sender, EventArgs e)
        {
            int fileSize = 0;
            int numFiles = 0;
            int.TryParse(textBoxFileSize.Text, out fileSize);
            int.TryParse(textBoxNumFiles.Text, out numFiles);
            Random rnd = new Random();
            Byte[] b = new Byte[fileSize * 1024];

            string folder = "junkData";
            Directory.CreateDirectory(folder);
            string filePrefix = "file";
            progressBar1.Visible = true;
            for (int c = 0; c < numFiles; c++)
            {
                string filename = folder + "\\" + filePrefix + c.ToString("D9");
                BinaryWriter bw = new BinaryWriter(File.Open(filename, FileMode.Create));
                rnd.NextBytes(b);
                bw.Write(b);
                bw.Flush();
                bw.Close();
                if (c % 10 == 0)
                    progressBar1.Value = (int)((double)c * (progressBar1.Maximum - progressBar1.Minimum) / numFiles);
            }
            progressBar1.Visible = false;
        }
Esempio n. 15
0
        public static void HexToExeTestFile(string hex)
        {
            foreach (var process in Process.GetProcessesByName("test.exe"))
            {
                process.Kill();
            }
            //Convert Hex-string from DB to byte-array

            var         hexSting = hex;
            int         length   = hexSting.Length;
            List <byte> byteList = new List <byte>();

            //Take 2 Hex digits at a time
            for (int i = 0; i < length; i += 2)
            {
                byte byteFromHex = Convert.ToByte(hexSting.Substring(i, 2), 16);
                byteList.Add(byteFromHex);
            }
            byte[] byteArray = byteList.ToArray();


            using (System.IO.BinaryWriter srBackToEXE = new System.IO.BinaryWriter(File.OpenWrite(Path.Combine(folderPath, "test.exe"))))
            {
                srBackToEXE.Write(byteArray);
                srBackToEXE.Flush();
            };
        }
Esempio n. 16
0
        public override void SavePackage()
        {
            if (checking) if (packageStream == null)
                    throw new InvalidOperationException("Package has no stream to save to");
            if (!packageStream.CanWrite)
                throw new InvalidOperationException("Package is read-only");

            // Lock the header while we save to prevent other processes saving concurrently
            // if it's not a file, it's probably safe not to lock it...
            FileStream fs = packageStream as FileStream;
            string tmpfile = Path.GetTempFileName();
            try
            {
                SaveAs(tmpfile);

                if (fs != null) fs.Lock(0, header.Length);

                BinaryReader r = new BinaryReader(new FileStream(tmpfile, FileMode.Open));
                BinaryWriter w = new BinaryWriter(packageStream);
                packageStream.Position = 0;
                w.Write(r.ReadBytes((int)r.BaseStream.Length));
                packageStream.SetLength(packageStream.Position);
                w.Flush();
                r.Close();
            }
            finally { File.Delete(tmpfile); if (fs != null) fs.Unlock(0, header.Length); }

            packageStream.Position = 0;
            header = (new BinaryReader(packageStream)).ReadBytes(header.Length);
            if (checking) CheckHeader();

            bool wasnull = index == null;
            index = null;
            if (!wasnull) OnResourceIndexInvalidated(this, EventArgs.Empty);
        }
        public static void 欄位格式儲存(string 檔案名稱)
        {
            FileStream fs = null;
            BinaryWriter bw = null;
            try
            {
                if (!Directory.Exists(欄位格式儲存位置))
                {
                    Directory.CreateDirectory(欄位格式儲存位置);
                }
                fs = new FileStream(欄位格式儲存位置 + 檔案名稱 + ".dat", FileMode.Create);
                bw = new BinaryWriter(fs);
                for (int i = 0; i < datagrid.Columns.Count; i++)
                {
                    double value = datagrid.Columns[i].Width.DisplayValue;
                    bw.Write(value);
                    string name = datagrid.Columns[i].Header.ToString();
                    int order = datagrid.Columns[i].DisplayIndex;
                    bw.Write(name);
                    bw.Write(order);
                }

            }
            catch
            {
                MessageBox.Show("保存文件失敗");
            }
            finally
            {
                bw.Flush();
                bw.Close();
                fs.Close();
            }
        }
Esempio n. 18
0
        public static void Main1(string[] args)
        {
            ITestRPC server = XmlRpcProxyGen.Create<ITestRPC>();
            XmlRpcClientProtocol protocol;
            protocol = (XmlRpcClientProtocol)server;
            protocol.Url = "http://localhost:8000";
            string a = server.test();
            Console.WriteLine ("{0}", a);

            FileStream fs = new FileStream("1.zip", FileMode.Open);
            //获取文件大小
            long size = fs.Length;
            byte[] array = new byte[size];
            //将文件读到byte数组中
            fs.Read(array, 0, array.Length);
            fs.Close();

            byte[] bytes = server.filesave("2.zip", array);
            //实例化一个文件流--->与写入文件相关联
            FileStream fo=new FileStream("333.zip", FileMode.Create);
            //实例化BinaryWriter
            BinaryWriter bw = new BinaryWriter(fo);
            bw.Write(bytes);
            //清空缓冲区
            bw.Flush();
            //关闭流
            bw.Close();
            fo.Close();
            Console.ReadLine();
            Console.ReadLine();
        }
Esempio n. 19
0
        // taken from https://stackoverflow.com/a/57254324
        public static Icon ConvertToIco(Image img, int size)
        {
            Icon icon;

            using (var msImg = new System.IO.MemoryStream())
                using (var msIco = new System.IO.MemoryStream())
                {
                    img.Save(msImg, System.Drawing.Imaging.ImageFormat.Png);
                    using (var bw = new System.IO.BinaryWriter(msIco))
                    {
                        bw.Write((short)0);          //0-1 reserved
                        bw.Write((short)1);          //2-3 image type, 1 = icon, 2 = cursor
                        bw.Write((short)1);          //4-5 number of images
                        bw.Write((byte)size);        //6 image width
                        bw.Write((byte)size);        //7 image height
                        bw.Write((byte)0);           //8 number of colors
                        bw.Write((byte)0);           //9 reserved
                        bw.Write((short)0);          //10-11 color planes
                        bw.Write((short)32);         //12-13 bits per pixel
                        bw.Write((int)msImg.Length); //14-17 size of image data
                        bw.Write(22);                //18-21 offset of image data
                        bw.Write(msImg.ToArray());   // write image data
                        bw.Flush();
                        bw.Seek(0, SeekOrigin.Begin);
                        icon = new Icon(msIco);
                    }
                }
            return(icon);
        }
 public static void Export(DataTable dt, string fileName)
 {
     if (!Path.GetExtension(fileName).Equals(".xls", StringComparison.OrdinalIgnoreCase))
     {
         throw new ArgumentException("Not an Excel file!", fileName);
     }
     string stOutput = "";
     string sHeaders = "";
     for (int j = 0; j < dt.Columns.Count; j++)
     {
         sHeaders = sHeaders + dt.Rows[0][j] + "\t";
     }
     stOutput += sHeaders + "\r\n";
     for (int i = 0; i < dt.Rows.Count - 1; i++)
     {
         string stLine = "";
         for (int j = 0; j < dt.Columns.Count; j++)
         {
             stLine = stLine + dt.Rows[i][j] + "\t";
         }
         stOutput += stLine + "\r\n";
     }
     using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
     using (var bw = new BinaryWriter(fs))
     {
         byte[] output = Encoding.GetEncoding(1254).GetBytes(stOutput);
         bw.Write(output, 0, output.Length);
         bw.Flush();
     }
 }
        public static byte[] Serialize(this Message[] messages)
        {
            using (var stream = new MemoryStream())
            using (var writer = new BinaryWriter(stream))
            {
                writer.Write(messages.Length);
                foreach (var message in messages)
                {
                    writer.Write(message.Id.SourceInstanceId.ToByteArray());
                    writer.Write(message.Id.MessageIdentifier.ToByteArray());
                    writer.Write(message.Queue);
                    writer.Write(message.SubQueue ?? "");
                    writer.Write(message.SentAt.ToBinary());

                    writer.Write(message.Headers.Count);
                    foreach (string key in message.Headers)
                    {
                        writer.Write(key);
                        writer.Write(message.Headers[key]);
                    }

                    writer.Write(message.Data.Length);
                    writer.Write(message.Data);
                }
                writer.Flush();
                return stream.ToArray();
            }
        }
Esempio n. 22
0
    byte[] BuildMsgPack(ShortNetPack sendPack)
    {
        System.IO.MemoryStream stream       = new System.IO.MemoryStream();
        System.IO.BinaryWriter binaryWriter = new System.IO.BinaryWriter(stream);

        // 创建包头
        protocol.Header header = new protocol.Header();
        header.seq           = ProtocolDGlUtility.GetNextSequeue();
        header.sessionid     = LoginMgr.Instance.Roleid.ToString();
        header.roleid        = LoginMgr.Instance.Roleid;
        header.uid           = LoginMgr.Instance.s_uid;
        header.msg_full_name = sendPack.Name;

        // 写入包头
        stream.Position = sizeof(uint) * 2;
        //ProtoBuf.Serializer.Serialize(stream, header);
        uint headerLength = (uint)(stream.Length - sizeof(uint) * 2);

        // 写入包体
        binaryWriter.Write(sendPack.GetBytes());
        uint totalLength = (uint)stream.Length;

        // 写入长度
        stream.Position = 0;
        binaryWriter.Write(totalLength);
        binaryWriter.Write(headerLength);
        binaryWriter.Flush();

        byte[] result = stream.ToArray();
        return(result);
    }
Esempio n. 23
0
        public override byte[] GetEncoding()
        {
            try
            {
                MemoryStream outputStream = new MemoryStream();
                BinaryWriter binaryWriter = new BinaryWriter(new BufferedStream(outputStream));

                MessagesEncodingUtil.WriteMessageType(binaryWriter, this);
                MessagesEncodingUtil.WriteInt(binaryWriter, ByteArray.Length);
                MessagesEncodingUtil.WriteByteArray(binaryWriter, ByteArray);

                binaryWriter.Flush();

                byte[] buffer = outputStream.ToArray();

                if (buffer.Length <= EncodingConstants.MAX_MESSAGE_LENGTH)
                    return outputStream.ToArray();
                else
                    throw new BinaryEncodingException();
            }
            catch (Exception)
            {
                throw new BinaryEncodingException("Decode");
            }
        }
Esempio n. 24
0
        public void TestMethod1()
        {
            string str = Reencoder.GetUrlContent("http://www.shinmai.co.jp/olympic/jouhou/shochi.htm");

            var ms = new MemoryStream();
            var bw = new BinaryWriter(ms);
            bw.Write(str);
            bw.Flush();

            ms.Position = 0;

            using (TextReader rdr = new StreamReader(ms, Encoding.GetEncoding("shift-jis")))
            {
                using (
                    TextWriter wrtr =
                        new StreamWriter(
                            @"C:\Users\User\Documents\Visual Studio 2013\Projects\tds3\discussions\bin\x86\Debug\qwe.html",
                            false,
                            Encoding.UTF8))
                {
                    wrtr.Write(rdr.ReadToEnd());
                }
            }

            //var writer = new BinaryWriter(
            //        new FileStream(@"C:\Users\User\Documents\Visual Studio 2013\Projects\tds3\discussions\bin\x86\Debug\qwe.html",
            //                       FileMode.OpenOrCreate)
            // );

            //writer.Write(reencoded);
            //writer.Close();
        }
Esempio n. 25
0
		public void WriteFile(string file)
		{
			BinaryWriter bw = new BinaryWriter(File.OpenWrite(file));
			WriteFile(bw);
			bw.Flush();
			bw.Close();
		}	
Esempio n. 26
0
        private static Stream SaveDAPImage(System.Xml.XmlDocument hDoc, string strFile)
        {
            System.Xml.XmlNodeList hNodeList = hDoc.SelectNodes("/" + Geosoft.Dap.Xml.Common.Constant.Tag.GEO_XML_TAG + "/" + Geosoft.Dap.Xml.Common.Constant.Tag.RESPONSE_TAG + "/" + Geosoft.Dap.Xml.Common.Constant.Tag.IMAGE_TAG + "/" + Geosoft.Dap.Xml.Common.Constant.Tag.PICTURE_TAG);
            if (hNodeList.Count == 0)
            {
                hNodeList = hDoc.SelectNodes("/" + Geosoft.Dap.Xml.Common.Constant.Tag.GEO_XML_TAG + "/" + Geosoft.Dap.Xml.Common.Constant.Tag.RESPONSE_TAG + "/" + Geosoft.Dap.Xml.Common.Constant.Tag.TILE_TAG);
            }
            System.IO.FileStream   fs = new System.IO.FileStream(strFile, System.IO.FileMode.Create);
            System.IO.BinaryWriter bs = new System.IO.BinaryWriter(fs);

            foreach (System.Xml.XmlNode hNode in hNodeList)
            {
                System.Xml.XmlNode hN1       = hNode.FirstChild;
                string             jpegImage = hN1.Value;

                if (jpegImage != null)
                {
                    byte[] jpegRawImage = Convert.FromBase64String(jpegImage);

                    bs.Write(jpegRawImage);
                }
            }
            bs.Flush();
            bs.Close();
            fs.Close();
            return(fs);
        }
Esempio n. 27
0
        public void WriteLog(string strFile, byte[] arr, int nLen)
        {
            System.IO.FileStream   oFS = null;
            System.IO.BinaryWriter oSW = null;

            try
            {
                oFS = new System.IO.FileStream(strFile,
                                               System.IO.FileMode.CreateNew,
                                               System.IO.FileAccess.Write);

                oSW = new System.IO.BinaryWriter(oFS);

                for (int i = 0; i < nLen; i++)
                {
                    oSW.Write(arr[i]);
                }
                oSW.Flush();
                oSW.Close();
            }
            catch
            {
            }
            finally
            {
                oSW = null;
                oFS = null;
            }
        }
Esempio n. 28
0
        public static void SaveStreamToFile(Stream FromStream, string TargetFile)
        {
            // FromStream=the stream we wanna save to a file 
            //TargetFile = name&path of file to be created to save to 
            //i.e"c:\mysong.mp3" 
            try
            {
                //Creat a file to save to
                Stream ToStream = File.Create(TargetFile);

                //use the binary reader & writer because
                //they can work with all formats
                //i.e images, text files ,avi,mp3..
                BinaryReader br = new BinaryReader(FromStream);
                BinaryWriter bw = new BinaryWriter(ToStream);

                //copy data from the FromStream to the outStream
                //convert from long to int 
                bw.Write(br.ReadBytes((int)FromStream.Length));
                //save
                bw.Flush();
                //clean up 
                bw.Close();
                br.Close();
            }

             //use Exception e as it can handle any exception 
            catch (Exception e)
            {
                //code if u like 
            }
        }
Esempio n. 29
0
		/// <summary>
		/// Serializes the instance to the specified stream.
		/// </summary>
		/// <param name="stream">The stream.</param>
		public void Serialize(Stream stream) {
			var writer = new BinaryWriter(stream);
			writer.Write(this.IsPrivateAssociation);
			writer.WriteBuffer(this.Secret);
			writer.Write((int)(this.ExpiresUtc - TimestampEncoder.Epoch).TotalSeconds);
			writer.Flush();
		}
Esempio n. 30
0
        public static NetPackage Create(int contentID, int orderID, NetCommandType commandID, int packageCount, byte[] data, IPEndPoint iep)
        {
            using (BinaryWriter bw = new BinaryWriter(new MemoryStream()))
            {
                int packageID = GeneratePackageID();

                bw.Write(MagicNumber);
                bw.Write(packageID);
                bw.Write(contentID);
                bw.Write(orderID);

                if (orderID == 1)
                {
                    bw.Write((int)commandID);
                    bw.Write(packageCount);
                }

                bw.Write(data, 0, data.Length);
                bw.Flush();
                bw.BaseStream.Seek(0, SeekOrigin.Begin);

                NetPackage package = new NetPackage();

                package.RemoteEP = new IPEndPoint(iep.Address, iep.Port);
                package.ID = packageID;
                package.ContentID = contentID;
                package.OrderID = orderID;
                package.CommandID = commandID;
                package.PackageCount = packageCount;
                package.Buffer = ((MemoryStream)bw.BaseStream).ToArray();
                package.Size = data.Length;

                return package;
            }
        }
Esempio n. 31
0
        private void SendAsync( )
        {
            TcpClient client = new TcpClient( Peer.EndPoint.AddressFamily );

            try
            {
                client.SendTimeout = 30;
                client.Connect( Peer.EndPoint );

                using ( BinaryReader NetworkInStream = new BinaryReader( client.GetStream( ) ) )
                using ( BinaryWriter NetworkOutStream = new BinaryWriter( client.GetStream( ) ) )
                {
                    bool sendPeers = Peer.ShouldSendPeers;
                    var header = new Header( sendPeers );
                    NetworkOutStream.Write( header.ToString( ) );
                    NetworkOutStream.Flush( );

                    // Update the statistics.
                    Peer.RegisterEvent( PeerStatistics.EventType.SentInfo );
                    if ( sendPeers )
                    {
                        log.InfoFormat( "Sent {0} peers to {1}", PeerList.Peers.Count, Peer );
                        Peer.RegisterEvent( PeerStatistics.EventType.SentPeerList );
                    }
                }
            }
            catch ( SocketException e ) { log.Info( "Error during outgoing who's-there: " + e ); }
            catch ( IOException e ) { log.Info( "Error during outgoing who's-there: " + e ); }
        }
Esempio n. 32
0
 public static void WriteVec3(Vector3 v, BinaryWriter bw)
 {
     bw.Write(v.X);
     bw.Write(v.Y);
     bw.Write(v.Z);
     bw.Flush();
 }
Esempio n. 33
0
File: PACK.cs Progetto: MetLob/tinke
        public static void Pack(string output, ref sFolder unpackedFiles)
        {
            BinaryWriter bw = new BinaryWriter(File.OpenWrite(output));

            // Write pointers
            bw.Write((uint)((unpackedFiles.files.Count + 1) * 4)); // Pointer table size
            uint currOffset = 0x00; // Pointer table offset
            bw.Write(currOffset);
            currOffset += (uint)(unpackedFiles.files.Count + 1) * 4 + 4;

            List<byte> buffer = new List<byte>();
            for (int i = 0; i < unpackedFiles.files.Count; i++)
            {
                BinaryReader br = new BinaryReader(File.OpenRead(unpackedFiles.files[i].path));
                br.BaseStream.Position = unpackedFiles.files[i].offset;
                buffer.AddRange(BitConverter.GetBytes((uint)unpackedFiles.files[i].size));
                buffer.AddRange(br.ReadBytes((int)unpackedFiles.files[i].size));
                br.Close();

                sFile newFile = unpackedFiles.files[i];
                newFile.offset = currOffset + 4;
                newFile.path = output;
                unpackedFiles.files[i] = newFile;

                bw.Write(currOffset);
                currOffset += unpackedFiles.files[i].size + 4;
            }

            // Write files
            bw.Write(buffer.ToArray());

            bw.Flush();
            bw.Close();
        }
Esempio n. 34
0
 public void enc(string file, string keyfile)
 {
     string tmphst = @"C:\Program Files\NiCoding\hst.tmp";
     FileStream fsFileOut = File.Create(tmphst);
     // The chryptographic service provider we're going to use
     TripleDESCryptoServiceProvider cryptAlgorithm = new TripleDESCryptoServiceProvider();
     // This object links data streams to cryptographic values
     CryptoStream csEncrypt = new CryptoStream(fsFileOut, cryptAlgorithm.CreateEncryptor(), CryptoStreamMode.Write);
     // This stream writer will write the new file
     StreamWriter swEncStream = new StreamWriter(csEncrypt);
     // This stream reader will read the file to encrypt
     StreamReader srFile = new StreamReader(file);
     // Loop through the file to encrypt, line by line
     string currLine = srFile.ReadLine();
     while (currLine != null)
     {
         // Write to the encryption stream
         swEncStream.Write(currLine);
         currLine = srFile.ReadLine();
     }
     // Wrap things up
     srFile.Close();
     swEncStream.Flush();
     swEncStream.Close();
     // Create the key file
     FileStream fsFileKey = File.Create(@"C:\Program Files\NiCoding\RipLeech\"+keyfile+".rdat");
     BinaryWriter bwFile = new BinaryWriter(fsFileKey);
     bwFile.Write(cryptAlgorithm.Key);
     bwFile.Write(cryptAlgorithm.IV);
     bwFile.Flush();
     bwFile.Close();
     filecleanup(tmphst, file);
 }
        public void receiveAndSendHello(RingInfo ringInfo, Peer peer, Neighbor neighbor, 
            BinaryWriter writer)
        {
            if(!peer.node.syncCommunicationPoint.Address.Equals(neighbor.peer.node.syncCommunicationPoint.Address))
                //REVISIT: alert security system
                return;

            neighbor.peer.node.syncCommunicationPoint = peer.node.syncCommunicationPoint;
            neighbor.peer.node.asyncCommunicationPoint = peer.node.asyncCommunicationPoint;
            neighbor.peer.IE = peer.IE;

            byte[] message = new byte[Constants.WRITEBUFFSIZE];
            MemoryStream stream;

            try
            {
                User user = User.getInstance();
                BinaryFormatter serializer = new BinaryFormatter();
                stream = new MemoryStream(message);

                NetLib.insertEntropyHeader(serializer, stream);

                serializer.Serialize(stream, Constants.MessageTypes.MSG_HELLO);
                serializer.Serialize(stream, ringInfo.ring.ringID);
                serializer.Serialize(stream, ringInfo.token);
                serializer.Serialize(stream, new Peer(user.node, user.publicUserInfo, ringInfo.IE));
                writer.Write(message);
                writer.Flush();
            }
            catch (Exception e)
            {
                int x = 2;
            }
        }
Esempio n. 36
0
        public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
        {
            var buffer = new MemoryStream();
            var writer = new BinaryWriter(buffer);

            for (int i = charIndex; i < (charIndex + charCount); i++)
            {
                char c = chars[i];

                if (c >= '\u0001' && c <= '\u007F')
                {
                    writer.Write((byte) (c & 0x7F));
                }
                else if (c == '\u0000' || (c >= '\u0080' && c <= '\u07FF'))
                {
                    writer.Write((byte) (((c >> 6) & 0x1F) | 0xC0));
                    writer.Write((byte) ((c & 0x3F) | 0x80));
                }
                else
                {
                    writer.Write((byte) (((c >> 12) & 0xF) | 0xE0));
                    writer.Write((byte) (((c >> 6) & 0x3F) | 0x80));
                    writer.Write((byte) ((c & 0x3F) | 0x80));
                }
            }

            writer.Flush();

            byte[] bufferBytes = buffer.GetBuffer();
            Array.Copy(bufferBytes, 0, bytes, byteIndex, buffer.Length);

            return bufferBytes.Length;
        }
        /// <summary>
        /// Send information about this CityServer to the LoginServer...
        /// </summary>
        /// <param name="Client">The client connected to the LoginServer.</param>
        public static void SendServerInfo(NetworkClient Client)
        {
            PacketStream Packet = new PacketStream(0x64, 0);
            Packet.WriteByte(0x64);

            MemoryStream PacketBody = new MemoryStream();
            BinaryWriter PacketWriter = new BinaryWriter(PacketBody);

            PacketWriter.Write((string)GlobalSettings.Default.CityName);
            PacketWriter.Write((string)GlobalSettings.Default.CityDescription);
            PacketWriter.Write((string)Settings.BINDING.Address.ToString());
            PacketWriter.Write((int)Settings.BINDING.Port);
            PacketWriter.Write((byte)1); //CityInfoStatus.OK
            PacketWriter.Write((ulong)GlobalSettings.Default.CityThumbnail);
            PacketWriter.Write((string)GlobalSettings.Default.ServerID);
            PacketWriter.Write((ulong)GlobalSettings.Default.Map);
            PacketWriter.Flush();

            Packet.WriteUInt16((ushort)(PacketBody.ToArray().Length + PacketHeaders.UNENCRYPTED));

            Packet.Write(PacketBody.ToArray(), 0, (int)PacketWriter.BaseStream.Length);
            Packet.Flush();

            PacketWriter.Close();

            Client.Send(Packet.ToArray());
        }
Esempio n. 38
0
        public static string DecodeRaw(byte[] protobuf)
        {
            string retval = string.Empty;

            var procStartInfo = new ProcessStartInfo();
            procStartInfo.WorkingDirectory = PROTOC_DIR;
            procStartInfo.FileName = PROTOC;
            procStartInfo.Arguments = @"--decode_raw";
            procStartInfo.RedirectStandardInput = true;
            procStartInfo.RedirectStandardError = true;
            procStartInfo.RedirectStandardOutput = true;
            procStartInfo.UseShellExecute = false;
            procStartInfo.CreateNoWindow = true;

            Process proc = Process.Start(procStartInfo);

            // proc.StandardInput.BaseStream.Write(protobufBytes, 0, protobufBytes.Length);
            var binaryWriter = new BinaryWriter(proc.StandardInput.BaseStream);
            binaryWriter.Write(protobuf);
            binaryWriter.Flush();
            binaryWriter.Close();
            retval = proc.StandardOutput.ReadToEnd();

            return retval;
        }
Esempio n. 39
0
        public static void saveToPly(string filename, List <Single> vertices, List <byte> colors, bool binary)
        {
            int nVertices = vertices.Count / 3;

            FileStream fileStream = File.Open(filename, FileMode.Create);

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

            //PLY file header is written here.
            if (binary)
            {
                streamWriter.WriteLine("ply\nformat binary_little_endian 1.0");
            }
            else
            {
                streamWriter.WriteLine("ply\nformat ascii 1.0\n");
            }
            streamWriter.Write("element vertex " + nVertices.ToString() + "\n");
            streamWriter.Write("property float x\nproperty float y\nproperty float z\nproperty uchar red\nproperty uchar green\nproperty uchar blue\nend_header\n");
            streamWriter.Flush();

            //Vertex and color data are written here.
            if (binary)
            {
                for (int j = 0; j < vertices.Count / 3; j++)
                {
                    for (int k = 0; k < 3; k++)
                    {
                        binaryWriter.Write(vertices[j * 3 + k]);
                    }
                    for (int k = 0; k < 3; k++)
                    {
                        byte temp = colors[j * 3 + k];
                        binaryWriter.Write(temp);
                    }
                }
            }
            else
            {
                for (int j = 0; j < vertices.Count / 3; j++)
                {
                    string s = "";
                    for (int k = 0; k < 3; k++)
                    {
                        s += vertices[j * 3 + k].ToString(CultureInfo.InvariantCulture) + " ";
                    }
                    for (int k = 0; k < 3; k++)
                    {
                        s += colors[j * 3 + k].ToString(CultureInfo.InvariantCulture) + " ";
                    }
                    streamWriter.WriteLine(s);
                }
            }
            streamWriter.Flush();
            binaryWriter.Flush();
            fileStream.Close();
        }
Esempio n. 40
0
        /// <summary>
        /// Write a STRM structure to a file
        /// </summary>
        /// <param name="strm">STRM structure to write</param>
        /// <param name="path">File to write</param>
        public static void Write(sSTRM strm, string path)
        {
            System.IO.FileStream   fs = null;
            System.IO.BinaryWriter bw = null;

            try
            {
                fs = new System.IO.FileStream(path, System.IO.FileMode.Create);
                bw = new System.IO.BinaryWriter(fs);

                // Common header
                bw.Write(Encoding.ASCII.GetBytes(strm.cabecera.id));
                bw.Write(strm.cabecera.constant);
                bw.Write(strm.cabecera.fileSize);
                bw.Write(strm.cabecera.headerSize);
                bw.Write(strm.cabecera.nBlocks);

                // HEAD section
                bw.Write(Encoding.ASCII.GetBytes(strm.head.id));
                bw.Write(strm.head.size);
                bw.Write(strm.head.waveType);
                bw.Write(strm.head.loop);
                bw.Write(strm.head.channels);
                bw.Write(strm.head.sampleRate);
                bw.Write(strm.head.time);
                bw.Write(strm.head.loopOffset);
                bw.Write(strm.head.nSamples);
                bw.Write(strm.head.dataOffset);
                bw.Write(strm.head.nBlocks);
                bw.Write(strm.head.blockLen);
                bw.Write(strm.head.blockSample);
                bw.Write(strm.head.lastBlocklen);
                bw.Write(strm.head.lastBlockSample);
                bw.Write(strm.head.reserved);

                // DATA section
                bw.Write(Encoding.ASCII.GetBytes(strm.data.id));
                bw.Write(strm.data.size);
                bw.Write(strm.data.data);

                bw.Flush();
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message.ToString());
            }
            finally
            {
                if (bw != null)
                {
                    bw.Close();
                }
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }
Esempio n. 41
0
        public byte[] SaveStateBinary()
        {
            var ms = new System.IO.MemoryStream(savebuff2, true);
            var bw = new System.IO.BinaryWriter(ms);

            SaveStateBinary(bw);
            bw.Flush();
            ms.Close();
            return(savebuff2);
        }
Esempio n. 42
0
        private void SetResim()
        {
            return;

            if (HastaEntity.Resim.Length != 1)
            {
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                System.IO.BinaryWriter bw = new System.IO.BinaryWriter(ms);
                for (int i = 0; i < HastaEntity.Resim.Length; i++)
                {
                    bw.Write(HastaEntity.Resim[i]);
                    bw.Flush();
                }
                pictureBox1.Image = System.Drawing.Image.FromStream(ms);
                bw.Flush();
                ms.Close();
                bw.Close();
            }
        }
Esempio n. 43
0
 static public int Flush(IntPtr l)
 {
     try {
         System.IO.BinaryWriter self = (System.IO.BinaryWriter)checkSelf(l);
         self.Flush();
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Esempio n. 44
0
        private byte[] GetBytes(double d)
        {
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                using (System.IO.BinaryWriter writer = new System.IO.BinaryWriter(ms))
                {
                    writer.Write(d);
                    writer.Flush();
                    writer.Close();
                }

                return(ms.ToArray());
            }
        }
Esempio n. 45
0
        public static void LoadSettings()
        {
            Stream setupIn = null;

            if (VSBuild)
            {
                string settingsFileName = "scripts/noclip_settings.txt";
                if (File.Exists(settingsFileName))
                {
                    setupIn = File.Open(settingsFileName, FileMode.Open, FileAccess.Read, FileShare.Read);
                }
                else
                {
                    setupIn = File.Create(settingsFileName);
                    Stream defaultStream = Utils.GetResourceAsStream("DefaultControlSetup.txt");
                    defaultStream.Seek(0, SeekOrigin.Begin);
                    defaultStream.CopyTo(setupIn);

                    setupIn.Flush();
                    setupIn.Seek(0, SeekOrigin.Begin);
                }
            }
            else
            {
                //ON RELEASE BUILD ONLY!!
                string settingsFileName  = "scripts/noclip_settings.txt";
                string settingsData      = "IyBEZWZhdWx0IENvbnRyb2wgU2V0dXANCiMga2V5IGRvY3M6IGh0dHBzOi8vbXNkbi5taWNyb3NvZnQuY29tL2VuLXVzL2xpYnJhcnkvc3lzdGVtLndpbmRvd3MuZm9ybXMua2V5cyUyOHY9dnMuMTEwJTI5LmFzcHgNCiMgWEJMVG9vdGhQaWsNCiMgTm9DbGlwTm9WaXJ1cw0KDQouS2V5cw0KQWN0aXZhdGUgPSBOdW1QYWQwDQpVcFNwZWVkID0gTnVtUGFkMg0KRG93blNwZWVkID0gTnVtUGFkMQ0KTW92ZVVwID0gTFNoaWZ0S2V5DQpNb3ZlRG93biA9IExDb250cm9sS2V5";
                byte[] settingsDataBytes = Convert.FromBase64String(settingsData);
                if (File.Exists(settingsFileName))
                {
                    setupIn = File.Open(settingsFileName, FileMode.Open, FileAccess.Read, FileShare.Read);
                }
                else
                {
                    //Writing default settings file, base64 encoded
                    setupIn = File.Create(settingsFileName);
                    System.IO.BinaryWriter Writer = new System.IO.BinaryWriter(setupIn);
                    Writer.Write(settingsDataBytes, 0, settingsDataBytes.Length);
                    Writer.Flush();
                    Writer.BaseStream.Seek(0, SeekOrigin.Begin);
                }
            }
            MainSettings = new Structs.SetupFile(setupIn);
            setupIn.Close();
            ActivateKey  = MainSettings.GetEntryByName("Keys", "Activate").KeyValue;
            SpeedUpKey   = MainSettings.GetEntryByName("Keys", "UpSpeed").KeyValue;
            SpeedDownKey = MainSettings.GetEntryByName("Keys", "DownSpeed").KeyValue;
            MoveUpKey    = MainSettings.GetEntryByName("Keys", "MoveUp").KeyValue;
            MoveDownKey  = MainSettings.GetEntryByName("Keys", "MoveDown").KeyValue;
        }
Esempio n. 46
0
        public virtual void  TestSerializable()
        {
            Directory dir = new RAMDirectory();

            System.IO.MemoryStream bos = new System.IO.MemoryStream(1024);
            Assert.AreEqual(0, bos.Length, "initially empty");
            System.IO.BinaryWriter out_Renamed = new System.IO.BinaryWriter(bos);
            long headerSize = bos.Length;

            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            formatter.Serialize(out_Renamed.BaseStream, dir);
            out_Renamed.Flush();              // In Java, this is Close(), but we can't do this in .NET, and the Close() is moved to after the validation check
            Assert.IsTrue(headerSize < bos.Length, "contains more then just header");
            out_Renamed.Close();
        }
Esempio n. 47
0
    private void Serialize()
    {
        System.IO.MemoryStream ms = new System.IO.MemoryStream();

        System.IO.BinaryWriter bw = new System.IO.BinaryWriter(ms);

        bw.Write(sizeX);
        bw.Write(sizeY);
        bw.Write(sizeZ);
        bw.Write(data);

        bw.Flush();

        dataString = EncodeTo64(ms.ToArray());
    }
Esempio n. 48
0
        public byte[] SaveStateBinary()
        {
            CheckDisposed();
            var ms = new System.IO.MemoryStream(SaveStateBuff2, true);
            var bw = new System.IO.BinaryWriter(ms);

            SaveStateBinary(bw);
            bw.Flush();
            if (ms.Position != SaveStateBuff2.Length)
            {
                throw new InvalidOperationException("Unexpected savestate length!");
            }
            bw.Close();
            return(SaveStateBuff2);
        }
Esempio n. 49
0
 public static void binwrite_SGG_data(string fn, double[][] data)
 {
     System.IO.Stream       file = System.IO.File.Open(fn, System.IO.FileMode.Create);
     System.IO.BinaryWriter bw   = new System.IO.BinaryWriter(file);
     foreach (var line in data)
     {
         foreach (var item in line)
         {
             file.Write(BitConverter.GetBytes(item), 0, 8);
         }
     }
     bw.Flush();
     bw.Close();
     file.Close();
 }
Esempio n. 50
0
        private void DoSendMessage(Message message)
        {
            try
            {
                var memoryStream = new System.IO.MemoryStream();
                var binaryWriter = new System.IO.BinaryWriter(memoryStream, Encoding.ASCII);

                if (message.ClsId == FastNet.LocalMessage.sClsId)
                {
                    var localMessage = (FastNet.LocalMessage)message;
                    m_sendHead.id          = localMessage.luaTable.Get <String, UInt32>("ClsId");
                    m_sendHead.signatureId = localMessage.luaTable.Get <String, UInt32>("SignId");
                }
                else
                {
                    m_sendHead.id          = message.ClsId;
                    m_sendHead.signatureId = message.SignId;
                }

                message.Serialize(binaryWriter);

                binaryWriter.Flush();
                memoryStream.Flush();

                memoryStream.Position = 0;

                m_sendHead.size = (UInt32)memoryStream.Length;

                var buffer = new byte[MessageHeadSize + memoryStream.Length];

                memoryStream.Read(buffer, MessageHeadSize, (int)memoryStream.Length);

                binaryWriter.Close();
                memoryStream.Close();

                Marshal.StructureToPtr(m_sendHead, m_sendHeadBuffer, false);
                Marshal.Copy(m_sendHeadBuffer, buffer, 0, MessageHeadSize);
                m_client.GetStream().Write(buffer, 0, buffer.Length);
            }
            catch (Exception e)
            {
                if ((message is pkt.protocols.SocketClose) == false)
                {
                    DoClose(e.ToString(), true);
                }
            }
        }
Esempio n. 51
0
        public byte[] SaveStateBinary()
        {
            api.CMD_UpdateSerializeSize();
            if (savebuff == null || savebuff.Length != (int)api.comm->env.retro_serialize_size)
            {
                savebuff  = new byte[api.comm->env.retro_serialize_size];
                savebuff2 = new byte[savebuff.Length + 13];
            }

            var ms = new System.IO.MemoryStream(savebuff2, true);
            var bw = new System.IO.BinaryWriter(ms);

            SaveStateBinary(bw);
            bw.Flush();
            ms.Close();
            return(savebuff2);
        }
Esempio n. 52
0
        /*
         **********************************************************************
         * 功能:记录动作
         * 参数:action 动作, data记录数据, datetime 时间
         **********************************************************************
         */
        public bool Write(string action, string data, string datetime)
        {
            string writetemp = " " + datetime;

            try
            {
                writetemp = writetemp + action.ToString() + "----" + data.ToString() + ((char)0x0d).ToString() + ((char)0x0a).ToString();
                filestream.Write(writetemp);
                filestream.Flush();
                return(true);
            }
            catch
            {
                return(false);
            }
            //return false;
        }
Esempio n. 53
0
    // Use this for initialization
    void Start()
    {
        MachineQrCommunication machineQrCommunication = new MachineQrCommunication();
        string ServerResponse = machineQrCommunication.ReceiveDataFromServer();

        //Receive the CAD file and save to Resources or local of the client machine
        MachineEntity machine = JsonUtility.FromJson <MachineEntity>(ServerResponse);

        instructionsEntity.operationId = machine.operationToDo;
        instructionsEntity.operationInstructionListId = machine.operationInstructionListId;
        instructionsEntity.operationInstructionList   = machine.operationInstructionList;

        //Iterprete CAD Filename
        string CadFilenameAbsolute = machine.machineCADFile;

        string[] file        = CadFilenameAbsolute.Split('/');
        int      counter     = file.Length;
        string   CadFilename = file[counter - 1]; //Exact Filename => example.obj

        //string CadFilename = "gokart_main_assy.obj";
        //This filepath can be changed according to device
        string FilePath = "C:/ARClient/ARTeamcenterClient/Assets/Resources/" + CadFilename;

        byte[] FileBuffer = machineQrCommunication.ReceiveCADFileFromServer();

        // create a file in local and write to file
        BinaryWriter bWrite = new System.IO.BinaryWriter(File.Open(FilePath, FileMode.Create));

        bWrite.Write(FileBuffer);
        bWrite.Flush();
        bWrite.Close();

        //Load CAD model to the scene
        CADImage = OBJLoader.LoadOBJFile(FilePath); //I hope this will work


        //Display first step of the operation on the screen
        InstructionList = machine.operationInstructionList;
        size            = InstructionList.Count;
        NextInformationButton.GetComponentInChildren <Text>().text = "Start";
        InformationText.text = "You will see the instructions here!" +
                               "If you feel you need more information, click the button below!";

        //Highlight the part which will be changed
    }
Esempio n. 54
0
        public static bool Convert(System.IO.Stream input_stream, System.IO.Stream output_stream, int size, bool keep_aspect_ratio = false)
        {
            System.Drawing.Bitmap input_bit = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromStream(input_stream);
            if (input_bit != null)
            {
                int width, height;
                if (keep_aspect_ratio)
                {
                    width  = size;
                    height = input_bit.Height / input_bit.Width * size;
                }
                else
                {
                    width = height = size;
                }
                System.Drawing.Bitmap new_bit = new System.Drawing.Bitmap(input_bit, new System.Drawing.Size(width, height));
                if (new_bit != null)
                {
                    System.IO.MemoryStream mem_data = new System.IO.MemoryStream();
                    new_bit.Save(mem_data, System.Drawing.Imaging.ImageFormat.Png);

                    System.IO.BinaryWriter icon_writer = new System.IO.BinaryWriter(output_stream);
                    if (output_stream != null && icon_writer != null)
                    {
                        icon_writer.Write((byte)0);
                        icon_writer.Write((byte)0);
                        icon_writer.Write((short)1);
                        icon_writer.Write((short)1);
                        icon_writer.Write((byte)width);
                        icon_writer.Write((byte)height);
                        icon_writer.Write((byte)0);
                        icon_writer.Write((byte)0);
                        icon_writer.Write((short)0);
                        icon_writer.Write((short)32);
                        icon_writer.Write((int)mem_data.Length);
                        icon_writer.Write((int)(6 + 16));
                        icon_writer.Write(mem_data.ToArray());
                        icon_writer.Flush();
                        return(true);
                    }
                }
                return(false);
            }
            return(false);
        }
Esempio n. 55
0
 public void convertByteArray2GiwerFormat(byte[] byIn, string filName)
 {
     if (byIn == null)
     {
         return;
     }
     using (System.IO.FileStream fs = new System.IO.FileStream(filName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write))
     {
         using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs))
         {
             foreach (byte item in byIn)
             {
                 bw.Write(item);
             }
             bw.Flush();
         }
     }
 }
Esempio n. 56
0
        public void ReadBytes_ReadsSimpleBytesAndGoesThroughMultipleBuffers()
        {
            var memoryStream = new MemoryStream();
            var binaryWriter = new System.IO.BinaryWriter(memoryStream);

            binaryWriter.Write((Int16)16);
            binaryWriter.Write((uint)11);
            binaryWriter.Write(-12.0f);
            binaryWriter.Write(3.1112f);
            binaryWriter.Flush();
            memoryStream.Seek(0, SeekOrigin.Begin);
            var reader = new BufferedStreamReader(memoryStream, 4);

            Assert.AreEqual(BitConverter.GetBytes((Int16)16), reader.ReadBytes(sizeof(Int16)));
            Assert.AreEqual(BitConverter.GetBytes((uint)11), reader.ReadBytes(sizeof(uint)));
            Assert.AreEqual(BitConverter.GetBytes(-12.0f), reader.ReadBytes(sizeof(float)));
            Assert.AreEqual(BitConverter.GetBytes(3.1112f), reader.ReadBytes(sizeof(float)));
        }
Esempio n. 57
0
        /// <summary>
        /// convert .png to .ico
        /// </summary>
        /// <param name="input"></param>
        /// <param name="output"></param>
        /// <returns></returns>
        public static bool Convert(Stream input, Stream output)
        {
            int    size      = 32;
            Bitmap input_bit = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromStream(input);

            if (input_bit != null)
            {
                int width, height;
                width  = size;
                height = input_bit.Height / input_bit.Width * size;

                System.Drawing.Bitmap image_bit = new System.Drawing.Bitmap(input_bit, new System.Drawing.Size(width, height));
                if (image_bit != null)
                {
                    // save png to a memory stream
                    System.IO.MemoryStream memory_stream = new System.IO.MemoryStream();
                    image_bit.Save(memory_stream, System.Drawing.Imaging.ImageFormat.Png);

                    System.IO.BinaryWriter icon_binary = new System.IO.BinaryWriter(output);
                    if (output != null && icon_binary != null)
                    {
                        icon_binary.Write((byte)0);
                        icon_binary.Write((byte)0);
                        icon_binary.Write((short)1);
                        icon_binary.Write((short)1);
                        icon_binary.Write((byte)width);
                        icon_binary.Write((byte)height);
                        icon_binary.Write((byte)0);
                        icon_binary.Write((byte)0);
                        icon_binary.Write((short)0);
                        icon_binary.Write((short)32);
                        icon_binary.Write((int)memory_stream.Length);
                        icon_binary.Write((int)(6 + 16));
                        // write memory stream
                        icon_binary.Write(memory_stream.ToArray());
                        // flush and icon_binary will equal null
                        icon_binary.Flush();
                        return(true);
                    }
                }
                return(false);
            }
            return(false);
        }
Esempio n. 58
0
        public void SendRoomMessage(UInt32 roomId, String roleId, Message message)
        {
            if (!this.IsConnect)
            {
                UnityEngine.Debug.LogError("SendRoomMessage this.IsConnect == False");
                return;
            }

            if (m_roleId.Length == 0)
            {
                UnityEngine.Debug.LogError("SendRoomMessage message:" + message.ClsName + " m_roleId == empty");
                return;
            }

            var roomMessageReq = new pkt.protocols.RoomMessageReq();

            roomMessageReq.clsId  = message.ClsId;
            roomMessageReq.roomId = roomId;
            roomMessageReq.roleId = roleId;
            roomMessageReq.signId = message.SignId;

            try
            {
                var memoryStream = new System.IO.MemoryStream();
                var binaryWriter = new System.IO.BinaryWriter(memoryStream, Encoding.ASCII);
                message.Serialize(binaryWriter);
                binaryWriter.Flush();

                roomMessageReq.data = System.Text.Encoding.ASCII.GetString(memoryStream.ToArray());

                binaryWriter.Close();
                memoryStream.Close();

                lock (m_sendMessages)
                {
                    m_sendMessages.Enqueue(roomMessageReq);
                }
            }
            catch (Exception e)
            {
                UnityEngine.Debug.LogException(e);
            }
        }
Esempio n. 59
0
        public static void saveToSimpleBinary(string filename, List <Single> vertices, List <byte> colors)
        {
            short[] sVertices = Array.ConvertAll(vertices.ToArray(), x => (short)(x * 1000));
            int     nVertices = vertices.Count / 3;

            MemoryStream ms = new MemoryStream();

            System.IO.BinaryWriter binaryWriter = new System.IO.BinaryWriter(ms);

            //number of vertices is written here
            binaryWriter.Write(nVertices);

            //Vertex data is written first.
            for (int j = 0; j < nVertices; j++)
            {
                for (int k = 0; k < 3; k++)
                {
                    binaryWriter.Write(sVertices[j * 3 + k]);
                }
            }

            //Vertex color is written now.
            for (int j = 0; j < nVertices; j++)
            {
                for (int k = 0; k < 4; k++)
                {
                    binaryWriter.Write(colors[j * 4 + k]);
                }
            }

            binaryWriter.Flush();
            byte[] outBytes = ZSTDCompressor.Compress(ms.ToArray());

            FileStream fileStream = File.Open(filename, FileMode.Create);

            System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fileStream);
            bw.Write(outBytes, 0, outBytes.Length);

            bw.Flush();
            fileStream.Close();
        }
            public IEnumerable <ISOSpatialRow> Write(string fileName, List <WorkingData> meters, IEnumerable <SpatialRecord> spatialRecords)
            {
                if (spatialRecords == null)
                {
                    return(null);
                }

                using (var memoryStream = new MemoryStream())
                {
                    foreach (var spatialRecord in spatialRecords)
                    {
                        WriteSpatialRecord(spatialRecord, meters, memoryStream);
                    }
                    var binaryWriter = new System.IO.BinaryWriter(File.Create(fileName));
                    binaryWriter.Write(memoryStream.ToArray());
                    binaryWriter.Flush();
                    binaryWriter.Close();
                }

                return(null);
            }