Ejemplo n.º 1
0
        public override IData GetMessagesData(IList<Message> messages)
        {
            IData data = null;
            byte[] buffer;
            long index = 0;
            using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
            {
                foreach (Message message in messages)
                {
                    stream.Write(new byte[4], 0, 4);
                    short typevalue = TypeMapper.GetValue(message.Type);
                    if (typevalue == 0)
						throw new Exception (string.Format ("{0} type value not registed", message.Type));
                      
                    byte[] typedata = BitConverter.GetBytes(typevalue);
                    stream.Write(typedata, 0, typedata.Length);
                    if (message.Value != null)
                        ProtoBuf.Meta.RuntimeTypeModel.Default.Serialize(stream, message.Value);
                    buffer = stream.GetBuffer();
                    BitConverter.GetBytes((int)stream.Length - 4 - (int)index).CopyTo(buffer, index);
                    index = stream.Position;
                }
                byte[] array = stream.ToArray();
                data = new Data(array,0, array.Length);
             

            }
            return data;
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Expands the specified info.
        /// </summary>
        /// <param name="info">optional context and application specific information (can be a zero-length string)</param>
        /// <param name="l">length of output keying material in octets (&lt;= 255*HashLen)</param>
        /// <returns>OKM (output keying material) of L octets</returns>
        public byte[] Expand(byte[] info, int l)
        {
            if (info == null) info = new byte[0];

            hmac.Key = this.prk;

            var n = (int) System.Math.Ceiling(l * 1f / hashLength);
            var t = new byte[n * hashLength];

            using (var ms = new System.IO.MemoryStream())
            {
                var prev = new byte[0];

                for (var i = 1; i <= n; i++)
                {
                    ms.Write(prev, 0, prev.Length);
                    if (info.Length > 0) ms.Write(info, 0, info.Length);
                    ms.WriteByte((byte)(0x01 * i));

                    prev = hmac.ComputeHash(ms.ToArray());

                    Array.Copy(prev, 0, t, (i - 1) * hashLength, hashLength);

                    ms.SetLength(0); //reset
                }
            }

            var okm = new byte[l];
            Array.Copy(t, okm, okm.Length);

            return okm;
        }
Ejemplo n.º 3
0
		void FillInternal (DataRow row,IDataItem item)
		{
			if (item != null)
			{
				BaseImageItem bi = item as BaseImageItem;
				if (bi != null) {
					using (System.IO.MemoryStream memStream = new System.IO.MemoryStream()){
						Byte[] val = row[bi.ColumnName] as Byte[];
						if (val != null) {
							if ((val[78] == 66) && (val[79] == 77)){
								memStream.Write(val, 78, val.Length - 78);
							} else {
								memStream.Write(val, 0, val.Length);
							}
							System.Drawing.Image image = System.Drawing.Image.FromStream(memStream);
							bi.Image = image;
						}
					}
				}
				else
				{
					var dataItem = item as BaseDataItem;
					if (dataItem != null) {
						dataItem.DBValue = ExtractDBValue(row,dataItem).ToString();
					}
					return;
				}
			}
		}
Ejemplo n.º 4
0
        public static Icon PngIconFromImage(Image img, int size = 16)
        {
            using (var bmp = new Bitmap(img, new Size(size, size)))
            {
                byte[] png;
                using (var fs = new System.IO.MemoryStream())
                {
                    bmp.Save(fs, System.Drawing.Imaging.ImageFormat.Png);
                    fs.Position = 0;
                    png = fs.ToArray();
                }

                using (var fs = new System.IO.MemoryStream())
                {
                    if (size >= 256) size = 0;
                    Pngiconheader[6] = (byte)size;
                    Pngiconheader[7] = (byte)size;
                    Pngiconheader[14] = (byte)(png.Length & 255);
                    Pngiconheader[15] = (byte)(png.Length / 256);
                    Pngiconheader[18] = (byte)(Pngiconheader.Length);

                    fs.Write(Pngiconheader, 0, Pngiconheader.Length);
                    fs.Write(png, 0, png.Length);
                    fs.Position = 0;
                    return new Icon(fs);
                }
            }
        }
Ejemplo n.º 5
0
        public override IData GetMessageData(IList<Message> messages)
        {
            Beetle.Express.IData data = null;
            byte[] buffer;
            long index = 0;
            using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
            {
                foreach (Message message in messages)
                {
                    stream.Write(new byte[4], 0, 4);
                    short typevalue = TypeMapper.GetValue(message.Type);
                    if (typevalue == 0)
                        "{0} type value not registed".ThrowError<Exception>(message.Type);
                    byte[] typedata = BitConverter.GetBytes(typevalue);
                    stream.Write(typedata, 0, typedata.Length);
                    if (message.Value != null)
                    {
                        var serializer = SerializationContext.Default.GetSerializer(message.Type);
                        serializer.Pack(stream, message.Value);
                    }
                    buffer = stream.GetBuffer();
                    BitConverter.GetBytes((int)stream.Length - 4 - (int)index).CopyTo(buffer, index);
                    index = stream.Position;
                }
                byte[] array = stream.ToArray();
                data = new Data(array, array.Length);
                data.Tag = messages;

            }
            return data;
        }
Ejemplo n.º 6
0
        public override IData GetMessageData(IList<Message> messages)
        {
            Beetle.Express.IData data = null;
            byte[] buffer;
            long index = 0;
            using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
            {
                foreach (Message message in messages)
                {

                    stream.Write(new byte[4], 0, 4);
                    byte[] typedata = MessageCenter.GetMessageTypeData(message.Type);
                    stream.Write(typedata, 0, typedata.Length);
                    if (message.Value != null)
                    {
                        var serializer = SerializationContext.Default.GetSerializer(message.Type);
                        serializer.Pack(stream, message.Value);
                    }
                    buffer = stream.GetBuffer();
                    BitConverter.GetBytes((int)stream.Length - 4 - (int)index).CopyTo(buffer, index);
                    index = stream.Position;
                }

                data = new Data(stream.GetBuffer(), (int)stream.Length);
                data.Tag = messages;

            }
            return data;
        }
Ejemplo n.º 7
0
 public byte[] appendBytes(byte[] original, string salt)
 {
     byte[] saltBytes = System.Text.Encoding.UTF8.GetBytes(salt);
     var contentVar = new System.IO.MemoryStream();
     contentVar.Write(original, 0, original.Length);
     contentVar.Write(saltBytes, 0, saltBytes.Length);
     return contentVar.ToArray();
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Converts the <see cref="T:System.Data.IEnumerable"/> data source into CSV formatted data and returns that data as a <see cref="T:System.IO.MemoryStream"/> stream.
        /// </summary>
        /// <param name="data">The <see cref="T:System.Linq.IQueryable"/> object containing the data to be parsed.</param>
        /// <param name="skipColumns">A <see cref="T:System.String[]"/> array indicating the names of columns that should not be included in the output.</param>
        /// <param name="columnHeaders">A value of type <see cref="T:System.Boolean"/> indicating true if the resulting CSV file should include column headers. Otherwise, false.</param>
        /// <returns>A <see cref="T:System.IO.MemoryStream"/> containing the resulting CSV file's binary data.</returns>
        public static System.IO.MemoryStream CreateCSV(IEnumerable data, bool columnHeaders, params string[] skipColumns)
        {
            List<int> skipColIdx = new List<int>();
            System.IO.MemoryStream strm = new System.IO.MemoryStream();
            {
                int rowNum = 0;
                foreach (var d in data)
                {
                    Type dType = d.GetType();
                    PropertyInfo[] props = dType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public);

                    // First, we're going to identify any columns we don't want to output (if any are specified).
                    if (rowNum == 0 && skipColumns.Length > 0)
                        for (int i = 0; i < props.Length; i++)
                            if (skipColumns.Contains(props[i].Name))
                                skipColIdx.Add(i);

                    // Now we're going to create the column headers, if we haven't done that already.
                    if (++rowNum == 1 && columnHeaders)
                    {
                        StringBuilder sbHdr = new StringBuilder();
                        for (int i = 0; i < props.Length; i++)
                            if (!props[i].PropertyType.Name.StartsWith("EntitySet") && !skipColIdx.Contains(i))
                            {
                                string colHdrName = props[i].Name;
                                if (colHdrName.Contains(',') || colHdrName.StartsWith(" ") || colHdrName.EndsWith(" "))
                                    sbHdr.AppendFormat(",\"{0}\"", colHdrName);
                                else
                                    sbHdr.Append("," + props[i].Name);
                            }
                        byte[] bufferHdr = System.Text.Encoding.UTF8.GetBytes(sbHdr.ToString().TrimStart(',') + "\r\n");
                        strm.Write(bufferHdr, 0, bufferHdr.Length);
                    }


                    StringBuilder sbRow = new StringBuilder();
                    for (int i = 0; i < props.Length; i++)
                    {
                        if (props[i].PropertyType.Name.StartsWith("EntitySet") || skipColIdx.Contains(i))
                            continue;

                        sbRow.Append(",");
                        object objfieldVal = props[i].GetValue(d, null);
                        string fieldVal = (objfieldVal != null) ? objfieldVal.ToString() : string.Empty;
                        if (fieldVal.Contains(',') || fieldVal.StartsWith(" ") || fieldVal.EndsWith(" "))
                            sbRow.AppendFormat("\"{0}\"", fieldVal);
                        else
                            sbRow.Append(fieldVal);
                    }

                    byte[] bufferRow = System.Text.Encoding.UTF8.GetBytes(sbRow.ToString().TrimStart(',') + "\r\n");
                    strm.Write(bufferRow, 0, bufferRow.Length);
                }
            }
            return strm;
        }
Ejemplo n.º 9
0
 public string recv()
 {
     System.Text.Encoding enc = System.Text.Encoding.UTF8;
     //サーバーから送られたデータを受信する
     System.IO.MemoryStream ms = new System.IO.MemoryStream();
     byte[] resBytes = new byte[1];
     int resSize;
     ns.ReadTimeout = 100;
     do
     {
         //データの一部を受信する
         resSize = ns.Read(resBytes,0,1);
         //Readが0を返した時はサーバーが切断したと判断
         if (resSize == 0)
         {
             Console.WriteLine("サーバーが切断しました。");
             return "";
         }
         if (resBytes[0] == ';')
         {
             break;
         }
         //受信したデータを蓄積する
         ms.Write(resBytes, 0,1);
         
     } while (ns.DataAvailable);
     //受信したデータを文字列に変換
     string resMsg = enc.GetString(ms.ToArray());
     ms.Close();
     Console.WriteLine(resMsg);
     return resMsg;
 }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            Sodao.FastSocket.SocketBase.Log.Trace.EnableConsole();
            Sodao.FastSocket.SocketBase.Log.Trace.EnableDiagnostic();

            var client = new Sodao.FastSocket.Client.AsyncBinarySocketClient(8192, 8192, 3000, 3000);
            //注册服务器节点,这里可注册多个(name不能重复)
            client.RegisterServerNode("127.0.0.1:8401", new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), 8401));
            //client.RegisterServerNode("127.0.0.1:8402", new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.2"), 8401));

            //组织sum参数, 格式为<<i:32-limit-endian,....N>>
            //这里的参数其实也可以使用thrift, protobuf, bson, json等进行序列化,
            byte[] bytes = null;
            using (var ms = new System.IO.MemoryStream())
            {
                for (int i = 1; i <= 1000; i++) ms.Write(BitConverter.GetBytes(i), 0, 4);
                bytes = ms.ToArray();
            }
            //发送sum命令
            client.Send("sum", bytes, res => BitConverter.ToInt32(res.Buffer, 0)).ContinueWith(c =>
            {
                if (c.IsFaulted)
                {
                    // Console.WriteLine(c.Exception.ToString());
                    return;
                }
                // Console.WriteLine(c.Result);
            });

            Console.ReadLine();
        }
Ejemplo n.º 11
0
 public byte[] GetHash()
 {
     System.IO.MemoryStream MS = new System.IO.MemoryStream ();
     foreach (Column c in columns)
         MS.Write (c.ID.ToByteArray (), 0, 16);
     return System.Security.Cryptography.SHA256.Create ().ComputeHash (MS.ToArray ());
 }
Ejemplo n.º 12
0
        public override DecodedObject<object> decodeAny(DecodedObject<object> decodedTag, System.Type objectClass, ElementInfo elementInfo, System.IO.Stream stream)
        {
            int bufSize = elementInfo.MaxAvailableLen;
            if (bufSize == 0)
                return null;
            System.IO.MemoryStream anyStream = new System.IO.MemoryStream(1024);
            /*int tagValue = (int)decodedTag.Value;
            for (int i = 0; i < decodedTag.Size; i++)
            {
                anyStream.WriteByte((byte)tagValue);
                tagValue = tagValue >> 8;
            }*/

            if(bufSize<0)
                bufSize = 1024;
            int len = 0;
            if (bufSize > 0)
            {
                byte[] buffer = new byte[bufSize];
                int readed = stream.Read(buffer, 0, buffer.Length);
                while (readed > 0)
                {
                    anyStream.Write(buffer, 0, readed);
                    len += readed;
                    if (elementInfo.MaxAvailableLen > 0)
                        break;
                    readed = stream.Read(buffer, 0, buffer.Length);
                }
            }
            CoderUtils.checkConstraints(len, elementInfo);
            return new DecodedObject<object>(anyStream.ToArray(), len);
        }
        public void TestParse()
        {
            var saxHandler = new Mock<ISaxHandler>();

              using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
              {
            memoryStream.Write(new System.Text.UTF8Encoding().GetBytes(_xmlToParse), 0, _xmlToParse.Length);
            memoryStream.Position = 0;

            SaxReaderImpl saxReaderImpl = new SaxReaderImpl();
            saxReaderImpl.Parse(new System.IO.StreamReader(memoryStream), saxHandler.Object);
              }

              AttributeCollection element3Attributes = new AttributeCollection();
              Attribute attr1Attribute = new Attribute();
              attr1Attribute.LocalName = "attr1";
              attr1Attribute.QName = "attr1";
              attr1Attribute.Uri = string.Empty;
              attr1Attribute.Value = "val1";
              element3Attributes.Add("attr1", attr1Attribute);

              saxHandler.Verify(c => c.StartDocument(), Times.Exactly(1));
              saxHandler.Verify(c => c.EndDocument(), Times.Exactly(1));
              saxHandler.Verify(c => c.StartElement(string.Empty, "root", "root", new AttributeCollection()));
              saxHandler.Verify(c => c.StartElement(string.Empty, "element1", "element1", new AttributeCollection()));
              saxHandler.Verify(c => c.StartElement(string.Empty, "element2", "element2", new AttributeCollection()));
              saxHandler.Verify(c => c.StartElement(string.Empty, "element3", "element3", element3Attributes));
              saxHandler.Verify(c => c.EndElement(string.Empty, "root", "root"));
              saxHandler.Verify(c => c.EndElement(string.Empty, "element1", "element1"));
              saxHandler.Verify(c => c.EndElement(string.Empty, "element2", "element2"));
              saxHandler.Verify(c => c.EndElement(string.Empty, "element3", "element3"));
              saxHandler.Verify(c => c.Characters(It.IsAny<char[]>(), It.IsAny<int>(), It.IsAny<int>()));
        }
Ejemplo n.º 14
0
		private async Task<string> DecodeResponse(HttpWebResponse response)
		{
			foreach (System.Net.Cookie cookie in response.Cookies)
			{
				_cookies.Add(new Uri(response.ResponseUri.GetLeftPart(UriPartial.Authority)), cookie);
			}

			if (response.StatusCode == HttpStatusCode.Redirect)
			{
				var location = response.Headers[HttpResponseHeader.Location];
				if (!string.IsNullOrEmpty(location))
					return await Get(new Uri(location));
			}	
			
			var stream = response.GetResponseStream();
			var buffer = new System.IO.MemoryStream();
			var block = new byte[65536];
			var blockLength = 0;
			do{
				blockLength = stream.Read(block, 0, block.Length);
				buffer.Write(block, 0, blockLength);
			}
			while(blockLength == block.Length);

			return Encoding.UTF8.GetString(buffer.GetBuffer());
		}
Ejemplo n.º 15
0
        /// <summary>
        /// Creates a byte array from the hexadecimal string. Each two characters are combined
        /// to create one byte. First two hexadecimal characters become first byte in returned array.
        /// Non-hexadecimal characters are ignored. 
        /// </summary>
        /// <param name="hexString">string to convert to byte array</param>
        /// <param name="discarded">number of characters in string ignored</param>
        /// <returns>byte array, in the same left-to-right order as the hexString</returns>
        public static byte[] GetBytes(string hexString, out int discarded)
        {
            discarded = 0;

            // XML Reader/Writer is highly optimized for BinHex conversions
            // use instead of byte/character replacement for performance on
            // arrays larger than a few dozen elements

            hexString = "<node>" + hexString + "</node>";

            System.Xml.XmlTextReader tr = new System.Xml.XmlTextReader(
                hexString,
                System.Xml.XmlNodeType.Element,
                null);

            tr.Read();

            System.IO.MemoryStream ms = new System.IO.MemoryStream();

            int bufLen = 1024;
            int cap = 0;
            byte[] buf = new byte[bufLen];

            do
            {
                cap = tr.ReadBinHex(buf, 0, bufLen);
                ms.Write(buf, 0, cap);
            } while (cap == bufLen);

            return ms.ToArray();
        }
        public string recive()
        {
            System.Text.Encoding enc = System.Text.Encoding.UTF8;
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            byte[] resBytes = new byte[256];
            int resSize = 0;

            if (ns.DataAvailable)
            {

                do
                {
                    //データの一部を受信する
                    resSize = ns.Read(resBytes, 0, resBytes.Length);

                    //受信したデータを蓄積する
                    ms.Write(resBytes, 0, resSize);

                    // 受信を続ける
                } while (ns.DataAvailable || resBytes[resSize - 1] != '\n');

                //受信したデータを文字列に変換
                string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length);
                ms.Close();
                //末尾の\nを削除
                resMsg = resMsg.TrimEnd('\n');

                return resMsg;
            }
            else
            {
                return "0";
            }
        }
Ejemplo n.º 17
0
		/// <summary>Compresses the specified byte range using the
		/// specified compressionLevel (constants are defined in
		/// java.util.zip.Deflater). 
		/// </summary>
		public static byte[] Compress(byte[] value_Renamed, int offset, int length, int compressionLevel)
		{
			/* Create an expandable byte array to hold the compressed data.
			* You cannot use an array that's the same size as the orginal because
			* there is no guarantee that the compressed data will be smaller than
			* the uncompressed data. */
			System.IO.MemoryStream bos = new System.IO.MemoryStream(length);

            SupportClass.SharpZipLib.Deflater compressor = SupportClass.SharpZipLib.CreateDeflater();
			
			try
			{
				compressor.SetLevel(compressionLevel);
				compressor.SetInput(value_Renamed, offset, length);
				compressor.Finish();
				
				// Compress the data
				byte[] buf = new byte[1024];
				while (!compressor.IsFinished)
				{
					int count = compressor.Deflate(buf);
					bos.Write(buf, 0, count);
				}
			}
			finally
			{
			}
			
			return bos.ToArray();
		}
Ejemplo n.º 18
0
        public void CSVAttributeNoHeaderTest()
        {
            var stream = new System.IO.MemoryStream();
            var text = "A,B\r\nD,E";
            var bytes = System.Text.Encoding.UTF8.GetBytes(text);
            stream.Write(bytes, 0, bytes.Length);
            stream.Position = 0;
            var target = new CSVSource<TestClass>(stream, System.Text.Encoding.UTF8);

            var firstLine = target.ReadNext();
            Assert.AreEqual("A", firstLine.Col1);
            Assert.AreEqual("B", firstLine.Col2);

            //Without Index
            stream = new System.IO.MemoryStream();
            text = "A,B\r\nD,E";
            bytes = System.Text.Encoding.UTF8.GetBytes(text);
            stream.Write(bytes, 0, bytes.Length);
            stream.Position = 0;
            var target2 = new CSVSource<TestClass2>(stream, System.Text.Encoding.UTF8);

            var firstLine2 = target2.ReadNext();
            Assert.IsNull(firstLine2.Col1);
            Assert.IsNull(firstLine2.Col2);
        }
Ejemplo n.º 19
0
        public ReaderVO(string BAR)
        {
            var dbr = new DBReader();
            DataRow reader = dbr.GetReaderByBAR(BAR);
            if (reader == null) return;
            this.ID = (int)reader["NumberReader"];
            this.Family = reader["FamilyName"].ToString();
            this.Father = reader["FatherName"].ToString();
            this.Name = reader["Name"].ToString();
            this.FIO = this.Family + " " + this.Name + " " + this.Father;
            if (reader["fotka"].GetType() != typeof(System.DBNull))
            {
                object o = reader["fotka"];
                byte[] data = (byte[])reader["fotka"];

                if (data != null)
                {
                    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                    {
                        ms.Write(data, 0, data.Length);
                        ms.Position = 0L;

                        this.Photo = new Bitmap(ms);
                    }
                }
            }
            else
            {
                this.Photo = Properties.Resources.nofoto;
            }
        }
Ejemplo n.º 20
0
 public WordprocessingDocument GetWordprocessingDocument()
 {
     var mem = new MemoryStream();
     mem.Write(this.DocumentByteArray, 0, this.DocumentByteArray.Length);
     WordprocessingDocument doc = WordprocessingDocument.Open(mem, true);
     return doc;
 }
Ejemplo n.º 21
0
 public static object Deserialize(byte[] data)
 {
     var tempStream = new System.IO.MemoryStream();
     tempStream.Write(data, 0, data.Length);
     tempStream.Seek(0, System.IO.SeekOrigin.Begin);
     return formatter.Deserialize(tempStream);
 }
Ejemplo n.º 22
0
        private static void OtherWaysToGetReport()
        {
            string report = @"d:\bla.rdl";

            // string lalal = System.IO.File.ReadAllText(report);
            // byte[] foo = System.Text.Encoding.UTF8.GetBytes(lalal);
            // byte[] foo = System.IO.File.ReadAllBytes(report);

            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {

                using (System.IO.FileStream file = new System.IO.FileStream(report, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                {
                    byte[] bytes = new byte[file.Length];
                    file.Read(bytes, 0, (int)file.Length);
                    ms.Write(bytes, 0, (int)file.Length);
                    ms.Flush();
                    ms.Position = 0;
                }

                using (System.IO.Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("resource"))
                {
                    using (System.IO.TextReader reader = new System.IO.StreamReader(ms))
                    {
                        // rv.LocalReport.LoadReportDefinition(reader);
                    }
                }

                using (System.IO.TextReader reader = System.IO.File.OpenText(report))
                {
                    // rv.LocalReport.LoadReportDefinition(reader);
                }

            }
        }
Ejemplo n.º 23
0
        public override void Splash()
        {
            byte[] imageBytes = null;

            using (var imageStream = new System.IO.MemoryStream())
            {
                imageStream.Write(imageBytes, 0, imageBytes.Length);

                using (var image = Image.FromStream(imageStream))
                using (var displayForm = new Form
                {
                    Width = 500,
                    Height = 340,
                    TopMost = true,
                    BackColor = Color.Black,
                    StartPosition = FormStartPosition.CenterParent,
                    FormBorderStyle = FormBorderStyle.FixedToolWindow,
                    BackgroundImage = image,
                    BackgroundImageLayout = ImageLayout.None,
                    Text = @"ReplaceMe1"
                })
                {
                    displayForm.ShowDialog();
                }
            }
        }
Ejemplo n.º 24
0
		public static void DeserializeVoxelAreaData (byte[] bytes, VoxelArea target) {
#if !ASTAR_RECAST_CLASS_BASED_LINKED_LIST
			Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile();
			System.IO.MemoryStream stream = new System.IO.MemoryStream();
			stream.Write(bytes,0,bytes.Length);
			stream.Position = 0;
			zip = Ionic.Zip.ZipFile.Read(stream);
			System.IO.MemoryStream stream2 = new System.IO.MemoryStream();
			
			zip["data"].Extract (stream2);
			stream2.Position = 0;
			System.IO.BinaryReader reader = new System.IO.BinaryReader(stream2);
			
			int width = reader.ReadInt32();
			int depth = reader.ReadInt32();
			if (target.width != width) throw new System.ArgumentException ("target VoxelArea has a different width than the data ("+target.width + " != " + width + ")");
			if (target.depth != depth) throw new System.ArgumentException ("target VoxelArea has a different depth than the data ("+target.depth + " != " + depth + ")");
			LinkedVoxelSpan[] spans = new LinkedVoxelSpan[reader.ReadInt32()];
			
			for (int i=0;i<spans.Length;i++) {
				spans[i].area = reader.ReadInt32();
				spans[i].bottom = reader.ReadUInt32();
				spans[i].next = reader.ReadInt32();
				spans[i].top = reader.ReadUInt32();
			}
			target.linkedSpans = spans;
#else
			throw new System.NotImplementedException ("This method only works with !ASTAR_RECAST_CLASS_BASED_LINKED_LIST");
#endif
		}
        public override byte[] EncodeValue(ScalarValue v)
        {
            if (v == ScalarValue.NULL)
            {
                return NULL_VALUE_ENCODING;
            }

            var buffer = new System.IO.MemoryStream();
            var value_Renamed = (DecimalValue) v;

            try
            {
                if (Math.Abs(value_Renamed.exponent) > 63)
                {
                    Global.HandleError(Error.FastConstants.R1_LARGE_DECIMAL, "Encountered exponent of size " + value_Renamed.exponent);
                }

                byte[] temp_byteArray = INTEGER.Encode(new IntegerValue(value_Renamed.exponent));
                buffer.Write(temp_byteArray, 0, temp_byteArray.Length);
                byte[] temp_byteArray2 = INTEGER.Encode(new LongValue(value_Renamed.mantissa));
                buffer.Write(temp_byteArray2, 0, temp_byteArray2.Length);
            }
            catch (System.IO.IOException e)
            {
                throw new RuntimeException(e);
            }

            return buffer.ToArray();
        }
        /// <summary>
        /// Get EditorsTable from server response.
        /// </summary>
        /// <param name="subResponse">The sub response from server.</param>
        /// <param name="site">Transfer ITestSite into this operation, for this operation to use ITestSite's function.</param>
        /// <returns>The instance of EditorsTable.</returns>
        public static EditorsTable GetEditorsTableFromResponse(FsshttpbResponse subResponse, ITestSite site)
        {
            if (subResponse == null || subResponse.DataElementPackage == null || subResponse.DataElementPackage.DataElements == null)
            {
                site.Assert.Fail("The parameter CellResponse is not valid, check whether the CellResponse::DataElementPackage or CellResponse::DataElementPackage::DataElements is null.");
            }

            foreach (DataElement de in subResponse.DataElementPackage.DataElements)
            {
                if (de.Data.GetType() == typeof(ObjectGroupDataElementData))
                {
                    ObjectGroupDataElementData ogde = de.Data as ObjectGroupDataElementData;

                    if (ogde.ObjectGroupData == null || ogde.ObjectGroupData.ObjectGroupObjectDataList.Count == 0)
                    {
                        continue;
                    }

                    for (int i = 0; i < ogde.ObjectGroupData.ObjectGroupObjectDataList.Count; i++)
                    {
                        if (IsEditorsTableHeader(ogde.ObjectGroupData.ObjectGroupObjectDataList[i].Data.Content.ToArray()))
                        {
                            string editorsTableXml = null;

                            // If the current object group object data is the header byte array 0x1a, 0x5a, 0x3a, 0x30, 0, 0, 0, 0, then the immediate following object group object data will contain the Editor table xml. 
                            byte[] buffer = ogde.ObjectGroupData.ObjectGroupObjectDataList[i + 1].Data.Content.ToArray();
                            System.IO.MemoryStream ms = null;
                            try
                            {
                                ms = new System.IO.MemoryStream();
                                ms.Write(buffer, 0, buffer.Length);
                                ms.Position = 0;
                                using (DeflateStream stream = new DeflateStream(ms, CompressionMode.Decompress))
                                {
                                    stream.Flush();
                                    byte[] decompressBuffer = new byte[buffer.Length * 3];
                                    stream.Read(decompressBuffer, 0, buffer.Length * 3);
                                    stream.Close();
                                    editorsTableXml = System.Text.Encoding.UTF8.GetString(decompressBuffer);
                                }

                                ms.Close();
                            }
                            finally
                            {
                                if (ms != null)
                                {
                                    ms.Dispose();
                                }
                            }

                            return GetEditorsTable(editorsTableXml);
                        }
                    }
                }
            }

            throw new InvalidOperationException("Cannot find any data group object data contain editor tables information.");
        }
 public async Task<string> GetNextSorterOps(string sourceId, string set, string sorters)
 {
     EntitySetType type;
     if (Enum.TryParse<EntitySetType>(set, out type))
     {
         switch (type)
         {
             case EntitySetType.User:
                 {
                     DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(List<QToken>));
                     DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(TokenOptions));
                     System.IO.MemoryStream strm = new System.IO.MemoryStream();
                     byte[] sbf = System.Text.Encoding.UTF8.GetBytes(sorters);
                     strm.Write(sbf, 0, sbf.Length);
                     strm.Position = 0;
                     var _sorters = ser1.ReadObject(strm) as List<QToken>;
                     UserServiceProxy svc = new UserServiceProxy();
                     var result = await svc.GetNextSorterOpsAsync(ApplicationContext.ClientContext, _sorters);
                     strm = new System.IO.MemoryStream();
                     ser2.WriteObject(strm, result);
                     string json = System.Text.Encoding.UTF8.GetString(strm.ToArray());
                     return json;
                 }
             case EntitySetType.Role:
                 {
                     DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(List<QToken>));
                     DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(TokenOptions));
                     System.IO.MemoryStream strm = new System.IO.MemoryStream();
                     byte[] sbf = System.Text.Encoding.UTF8.GetBytes(sorters);
                     strm.Write(sbf, 0, sbf.Length);
                     strm.Position = 0;
                     var _sorters = ser1.ReadObject(strm) as List<QToken>;
                     RoleServiceProxy svc = new RoleServiceProxy();
                     var result = await svc.GetNextSorterOpsAsync(ApplicationContext.ClientContext, _sorters);
                     strm = new System.IO.MemoryStream();
                     ser2.WriteObject(strm, result);
                     string json = System.Text.Encoding.UTF8.GetString(strm.ToArray());
                     return json;
                 }
             case EntitySetType.MemberNotification:
                 {
                     DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(List<QToken>));
                     DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(TokenOptions));
                     System.IO.MemoryStream strm = new System.IO.MemoryStream();
                     byte[] sbf = System.Text.Encoding.UTF8.GetBytes(sorters);
                     strm.Write(sbf, 0, sbf.Length);
                     strm.Position = 0;
                     var _sorters = ser1.ReadObject(strm) as List<QToken>;
                     MemberNotificationServiceProxy svc = new MemberNotificationServiceProxy();
                     var result = await svc.GetNextSorterOpsAsync(ApplicationContext.ClientContext, _sorters);
                     strm = new System.IO.MemoryStream();
                     ser2.WriteObject(strm, result);
                     string json = System.Text.Encoding.UTF8.GetString(strm.ToArray());
                     return json;
                 }
         }
     }
     return null;
 }
Ejemplo n.º 28
0
 public FilelistXmlBz2(byte[] content, bool isBz2)
     : base(null)
 {
     xmlBaseStream = new System.IO.MemoryStream();
     xmlBaseStream.Write(content, 0, content.Length);
     Bz2 = isBz2;
     fromXml = true;
 }
Ejemplo n.º 29
0
        /// <summary>
        /// <para>Represents the Header2 section of the EWF file.</para>
        /// <para>Holds various meta-data about the acquisition.</para>
        /// </summary>
        /// <param name="bytes">The bytes that make up the Header2 section.</param>
        public Header2(byte[] bytes)
        {
            string header = null; // Will eventually hold the decompressed Header2 info
            #region Decompress zlib'd data
            {
                byte[] buff = new byte[1024];
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes))
                {
                    using (Compression.ZlibStream zs = new Compression.ZlibStream(ms, System.IO.Compression.CompressionMode.Decompress, false))
                    {
                        using (System.IO.MemoryStream decomp = new System.IO.MemoryStream())
                        {
                            int n;
                            while ((n = zs.Read(buff, 0, buff.Length)) != 0)
                            {
                                decomp.Write(buff, 0, n);
                            }
                            decomp.Seek(0, System.IO.SeekOrigin.Begin);
                            System.IO.StreamReader sr = new System.IO.StreamReader(decomp, System.Text.Encoding.UTF8);
                            header = sr.ReadToEnd();
                        }
                    }
                }
            }
            #endregion

            string[] parts = header.Split(new char[] { (char)0x0A });

            int catsCount = int.Parse(parts[0]);
            Categories = new List<Header2Category>(catsCount);

            if (catsCount == 1) // EnCase 4
            {
                for (int i = 0; i < parts.Length; i++) // Header seems to have 0x0A on the end
                    parts[i] = parts[i].TrimEnd('\r');
                if (parts[1] != "main")
                    throw new ArgumentException(string.Format("unexpected category: {0}", parts[1]));
                Categories.Add(new Header2Category("main", parts[2], parts[3]));
            }
            else if (catsCount == 3) // EnCase 5-7
            {
                if (parts[1] != "main")
                    throw new ArgumentException(string.Format("unexpected category: {0}", parts[1]));
                Categories.Add(new Header2Category("main", parts[2], parts[3]));

                if (parts[5] != "srce")
                    throw new ArgumentException(string.Format("unexpected category: {0}", parts[5]));
                Categories.Add(new Header2Category("srce", parts[7], parts[9]));

                if (parts[11] != "sub")
                    throw new ArgumentException(string.Format("unexpected category: {0}", parts[13]));
                Categories.Add(new Header2Category("sub", parts[13], parts[15]));
            }
            else
            {
                throw new ArgumentException(string.Format("unknown category layout ({0} categories)", catsCount));
            }
        }
 public void ReadAllBinary2()
 {
     using (System.IO.MemoryStream Test = new System.IO.MemoryStream())
     {
         Test.Write("This is a test".ToByteArray(), 0, "This is a test".Length);
         byte[] Content = Test.ReadAllBinary();
         Assert.Equal("This is a test", System.Text.Encoding.ASCII.GetString(Content, 0, Content.Length));
     }
 }
Ejemplo n.º 31
0
        //public bool IsConnected { get; set; }


        ////Getting the IP Address of the device fro Android.


        //public string getIPAddress()
        //{
        //    string ipaddress = "";

        //    IPHostEntry ipentry = Dns.GetHostEntry(Dns.GetHostName());

        //    foreach (IPAddress ip in ipentry.AddressList)
        //    {
        //        if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
        //        {
        //            ipaddress = ip.ToString();
        //            break;
        //        }
        //    }
        //    return ipaddress;
        //}



        public async Task ServerConnect()
        {
            int port = 3333;
            //ListenするIPアドレス
            string ipString = "127.0.0.1";

            System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(ipString);

            //ホスト名からIPアドレスを取得する時は、次のようにする
            //string host = "localhost";
            //System.Net.IPAddress ipAdd =
            //    System.Net.Dns.GetHostEntry(host).AddressList[0];
            //.NET Framework 1.1以前では、以下のようにする
            //System.Net.IPAddress ipAdd =
            //    System.Net.Dns.Resolve(host).AddressList[0];

            //Listenするポート番号
            //int port = 2001;

            //TcpListenerオブジェクトを作成する
            System.Net.Sockets.TcpListener listener = await Task.Run(() => new System.Net.Sockets.TcpListener(ipAdd, port));

            //Listenを開始する
            listener.Start();
            System.Console.WriteLine("Listenを開始しました({0}:{1})。", ((System.Net.IPEndPoint)listener.LocalEndpoint).Address, ((System.Net.IPEndPoint)listener.LocalEndpoint).Port);

            //接続要求があったら受け入れる
            System.Net.Sockets.TcpClient client = listener.AcceptTcpClient(); System.Console.WriteLine("クライアント({0}:{1})と接続しました。",
                                                                                                       ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Address,
                                                                                                       ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Port);

            //NetworkStreamを取得
            System.Net.Sockets.NetworkStream ns = client.GetStream();

            //読み取り、書き込みのタイムアウトを10秒にする
            //デフォルトはInfiniteで、タイムアウトしない
            //(.NET Framework 2.0以上が必要)
            ns.ReadTimeout  = 10000;
            ns.WriteTimeout = 10000;

            //クライアントから送られたデータを受信する
            System.Text.Encoding enc = System.Text.Encoding.UTF8;
            bool disconnected        = false;

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            byte[] resBytes           = new byte[256];
            int    resSize            = 0;

            do
            {
                //データの一部を受信する
                resSize = ns.Read(resBytes, 0, resBytes.Length);
                //Readが0を返した時はクライアントが切断したと判断
                if (resSize == 0)
                {
                    disconnected = true;
                    System.Console.WriteLine("クライアントが切断しました。");
                    break;
                }
                //受信したデータを蓄積する
                ms.Write(resBytes, 0, resSize);
                //まだ読み取れるデータがあるか、データの最後が\nでない時は、
                // 受信を続ける
            } while (ns.DataAvailable || resBytes[resSize - 1] != '\n');
            //受信したデータを文字列に変換
            string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length);

            ms.Close();
            //末尾の\nを削除
            resMsg = resMsg.TrimEnd('\n');
            System.Console.WriteLine(resMsg);

            if (!disconnected)
            {
                //クライアントにデータを送信する
                //クライアントに送信する文字列を作成
                string sendMsg = resMsg.Length.ToString();
                //文字列をByte型配列に変換
                byte[] sendBytes = enc.GetBytes(sendMsg + '\n');
                //データを送信する
                ns.Write(sendBytes, 0, sendBytes.Length);
                System.Console.WriteLine(sendMsg);
            }

            //閉じる
            ns.Close();
            client.Close();
            System.Console.WriteLine("クライアントとの接続を閉じました。");

            //リスナを閉じる
            listener.Stop();
            System.Console.WriteLine("Listenerを閉じました。");

            System.Console.ReadLine();
        }
Ejemplo n.º 32
0
        public override bool Render(int components, System.IO.MemoryStream bw, out int w, out int h, bool bRorate90)
        {
            w = this.width;
            h = this.height;
            var _pixels = this.pixels;
            {
                var bheader = new DcmBITMAPFILEHEADER();
                bheader.bfOffBits   = 54;
                bheader.bfReserved1 = 0;
                bheader.bfReserved2 = 0;
                bheader.bfSize      = (uint)(54 + _pixels.ByteSize);
                bheader.bfType      = 19778;

                var binfo = new DcmBITMAPINFOHEADER();
                binfo.biBitCount     = 32;
                binfo.biClrImportant = 0;
                binfo.biClrUsed      = 0;
                binfo.biCompression  = DcmBitmapCompressionMode.BI_RGB;
                if (bRorate90)
                {
                    //----旋转90度, 其它参数不变
                    h = this.width;
                    w = this.height;
                }
                else
                {
                    w = this.width;
                    h = this.height;
                }

                binfo.biPlanes        = 1;
                binfo.biSize          = 40;
                binfo.biSizeImage     = 0;
                binfo.biXPelsPerMeter = 3978;
                binfo.biYPelsPerMeter = 3978;
                var hd = DcmStructToBytes(bheader);
                var bd = DcmStructToBytes(binfo);

                bw.Write(hd, 0, hd.Length);
                bw.Write(bd, 0, bd.Length);



                if (false == bRorate90)
                {
                    for (int i = this.height; i > 0; i--)
                    {
                        //int[] rawData = new int[ScaledData.Width];
                        //Buffer.BlockCopy(_pixels.Data, (i - 1) * ScaledData.Width, rawData, 0, ScaledData.Width);
                        for (int j = 0; j < this.width; j++)
                        {
                            int    ax = _pixels[(i - 1) * this.width + j];
                            byte[] ar = BitConverter.GetBytes(ax);
                            bw.Write(ar, 0, 3);
                        }
                    }
                }
                else
                {
                    for (int i = 0; i < this.width; i++)
                    {
                        for (int j = 0; j < this.height; j++)
                        {
                            int    aw = _pixels[j * this.width + i];
                            byte[] ar = BitConverter.GetBytes(aw);
                            bw.Write(ar, 0, 3);
                        }
                    }
                }
                bw.Flush();

                return(true);
            }
        }
Ejemplo n.º 33
0
        public void POST(string key, RequestInfo info)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                var target = info.Request.Param["target"].Value;
                if (string.IsNullOrWhiteSpace(target))
                {
                    info.ReportClientError("Missing target parameter");
                    return;
                }

                var answer = CaptchaUtil.CreateRandomAnswer(minlength: 6, maxlength: 6);
                var nonce  = Guid.NewGuid().ToString();

                string token;
                using (var ms = new System.IO.MemoryStream())
                {
                    var bytes = System.Text.Encoding.UTF8.GetBytes(answer + nonce);
                    ms.Write(bytes, 0, bytes.Length);
                    ms.Position = 0;
                    token       = Library.Utility.Utility.Base64PlainToBase64Url(Library.Utility.Utility.CalculateHash(ms));
                }

                lock (m_lock)
                {
                    var expired = m_captchas.Where(x => x.Value.Expires < DateTime.Now).Select(x => x.Key).ToArray();
                    foreach (var x in expired)
                    {
                        m_captchas.Remove(x);
                    }

                    if (m_captchas.Count > 3)
                    {
                        info.ReportClientError("Too many captchas, wait 2 minutes and try again", System.Net.HttpStatusCode.ServiceUnavailable);
                        return;
                    }

                    m_captchas[token] = new CaptchaEntry(answer, target);
                }

                info.OutputOK(new
                {
                    token = token
                });
            }
            else
            {
                var answer = info.Request.Param["answer"].Value;
                var target = info.Request.Param["target"].Value;
                if (string.IsNullOrWhiteSpace(answer))
                {
                    info.ReportClientError("Missing answer parameter");
                    return;
                }
                if (string.IsNullOrWhiteSpace(target))
                {
                    info.ReportClientError("Missing target parameter");
                    return;
                }

                if (SolvedCaptcha(key, target, answer))
                {
                    info.OutputOK();
                }
                else
                {
                    info.ReportClientError("Incorrect");
                }
            }
        }
Ejemplo n.º 34
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="ia"></param>
        private void BeginReceiveCallback(IAsyncResult ia)
        {
            Socket sck = ia.AsyncState as Socket;
            int    n   = 0;

            try
            {
                n = sck.EndReceive(ia);
            }
            catch (ObjectDisposedException odEx)
            {
                OnException(odEx);
                return;
            }
            catch (SocketException sckEx)
            {
                OnException(sckEx);
                this.CloseHelper();
                return;
            }
            catch
            {
                throw;
            }
            log.Debug("Received bytes length: " + n);

            if (n > 0)
            {
                _memoryStream.Write(_receBuffer, 0, n);
                if (this.IsOccupy)
                {
                    // do nothing
                }
                else
                {
                    FireReceivedEvent(EventArgs.Empty);
                }

                try
                {
                    BeginReceiveHelper();
                }
                catch (ObjectDisposedException odEx)
                {
                    OnException(odEx);
                    return;
                }
                catch (SocketException sckEx)
                {
                    OnException(sckEx);
                    this.CloseHelper();
                    return;
                }
                catch
                {
                    throw;
                }
            }
            else
            {
                CloseHelper();
            }
        }
Ejemplo n.º 35
0
        public async Task ClientConnect()
        {
            //サーバーに送信するデータを入力してもらう
            //System.Console.WriteLine("文字列を入力し、Enterキーを押してください。");
            string sendMsg = System.Console.ReadLine();

            //何も入力されなかった時は終了
            //if (sendMsg == null || sendMsg.Length == 0)
            //{
            //    return "";
            //}


            try
            {
                //TcpClientを作成し、サーバーと接続する
                tcp = await Task.Run(() => new System.Net.Sockets.TcpClient(HOST, port));

                System.Console.WriteLine("サーバー({0}:{1})と接続しました({2}:{3})。",
                                         ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Address,
                                         ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Port,
                                         ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Address,
                                         ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Port);


                a = new string[] { ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Address.ToString(), ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Port.ToString(),
                                   ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Address.ToString(), ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Port.ToString() };
            }
            catch (IOException e)
            {
                System.Console.WriteLine("文字列を入力し、Enterキーを押してください。" + e);
            }

            //catch (IOException e)
            //{
            //    System.Console.WriteLine("文字列を入力し、Enterキーを押してください。"+e);
            //}



            //NetworkStreamを取得する
            System.Net.Sockets.NetworkStream ns = tcp.GetStream();

            //読み取り、書き込みのタイムアウトを10秒にする
            //デフォルトはInfiniteで、タイムアウトしない
            //(.NET Framework 2.0以上が必要)
            ns.ReadTimeout  = 10000;
            ns.WriteTimeout = 10000;

            //サーバーにデータを送信する
            //文字列をByte型配列に変換
            System.Text.Encoding enc = System.Text.Encoding.UTF8;
            byte[] sendBytes         = enc.GetBytes(sendMsg + '\n');
            //データを送信する
            ns.Write(sendBytes, 0, sendBytes.Length);
            System.Console.WriteLine(sendMsg);

            //サーバーから送られたデータを受信する
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            byte[] resBytes           = new byte[256];
            int    resSize            = 0;

            do
            {
                //データの一部を受信する
                resSize = ns.Read(resBytes, 0, resBytes.Length);
                //Readが0を返した時はサーバーが切断したと判断
                if (resSize == 0)
                {
                    System.Console.WriteLine("サーバーが切断しました。");
                    break;
                }
                //受信したデータを蓄積する
                ms.Write(resBytes, 0, resSize);
                //まだ読み取れるデータがあるか、データの最後が\nでない時は、
                // 受信を続ける
            } while (ns.DataAvailable || resBytes[resSize - 1] != '\n');
            //受信したデータを文字列に変換
            string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length);

            ms.Close();
            //末尾の\nを削除
            resMsg = resMsg.TrimEnd('\n');
            System.Console.WriteLine(resMsg);

            //閉じる
            ns.Close();
            tcp.Close();
            System.Console.WriteLine("切断しました。");

            System.Console.ReadLine();
            //return resMsg.ToString();
            Ans = resMsg;
        }
Ejemplo n.º 36
0
        public void Connect(string ip, int port)
        {
            if (socket != null)
            {
                DisConnect();
            }

            this.socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
            this.socket.Connect(new IPEndPoint(IPAddress.Parse(ip), port));

            if (this.watchLoop == null)
            {
                this.watchLoop = Task.Run(() =>
                {
                    isStop = false;
                    while (!isStop)
                    {
                        this.socket.Send(this.sendMessage);

                        int receiveLength = socket.Receive(this.resBuffer);
                        flexData resData  = null;

                        using (var ms = new System.IO.MemoryStream())
                        {
                            try
                            {
                                var length = ParseHeader(this.resBuffer, 0);
                                //System.Diagnostics.Debug.WriteLine(length);
                                ms.Write(this.resBuffer, 8, length);
                                ms.Position = 0;

                                if (length == 0)
                                {
                                    continue;
                                }

                                resData = (flexData)serializer.Deserialize(ms);

                                if (resData.notifications != null)
                                {
                                    //resData.notifications.ToList().ForEach(n =>
                                    //{
                                    //    Console.Error.WriteLine($"{n.code}: {n.message}");
                                    //});

                                    //Thread.Sleep(1000);
                                    continue;
                                }


                                var updateData = resData.dataExchange.dataUpdate[0].data[0].r;

                                var info = new RobotInfo
                                {
                                    Tcp = new Position
                                    {
                                        X     = (float)updateData[0],
                                        Y     = (float)updateData[1],
                                        Z     = (float)updateData[2],
                                        Role  = (float)updateData[3],
                                        Pitch = (float)updateData[4],
                                        Yaw   = (float)updateData[5],
                                    },
                                    Time = DateTime.Now.ToFileTime(),
                                };
                                this.RobotInfoUpdated?.Invoke(info);

                                Thread.Sleep(1);
                            }
                            catch (System.Exception err)
                            {
                                Console.WriteLine(err.ToString());
                                Thread.Sleep(5000);
                                return;
                            }
                            finally
                            {
                                ms.Dispose();
                            }
                        }
                    }
                });

                IsLogging = true;
            }
        }
Ejemplo n.º 37
0
        ///////////////////////////
        //receive byte Array via XModem using either Checksum or CRC error detection
        /// ///////////////////////
        public byte[] XModemReceive(bool useCRC)
        {
            //since we don't know how many bytes we receive it's the
            //best solution to use a MemoryStream
            System.IO.MemoryStream buf = new System.IO.MemoryStream();

            int    packetno = 1;
            int    retry = 0;
            int    i, c;
            double kb = 0;

            if (useCRC) // send and use CRC
            {
                this.writeByte(C);
            }
            else //send and don't use CRC
            {
                this.writeByte(NAK);
            }

            while (retry < 16)
            {
                try { c = port.ReadByte(); }
                catch { c = 0x00; }

                if (c == SOH || c == STX)
                {
                    #region SOH/STX

                    retry = 0;
                    bufsz = 128; // default buffer size
                    if (c == STX)
                    {
                        bufsz = 1024; // buffer size for Xmodem1K
                    }
                    #region fill packet with datastream

                    xbuff[0] = (byte)c;
                    for (i = 0; i < (bufsz + (useCRC ? 1 : 0) + 3); i++)
                    {
                        xbuff[i + 1] = (byte)this.port.ReadByte();
                    }

                    #endregion

                    if (xbuff[1] == (byte)(~xbuff[2]) && xbuff[1] == packetno && check(useCRC, xbuff, 3, bufsz))
                    {
                        //add buffer to memory stream
                        buf.Write(xbuff, 3, bufsz);
                        this.writeByte(ACK);

                        #region fire event & increment packet number

                        //128 or 1024 Byte per package
                        double d = bufsz;
                        d  = d / 1024;
                        kb = (kb + d);

                        if (this.PacketReceived != null)
                        {
                            PacketReceived(this, null);
                        }

                        packetno++;
                        if (packetno >= 256)
                        {
                            packetno = 0;
                        }

                        #endregion
                    }
                    else
                    {
                        this.writeByte(NAK);
                    }

                    #endregion
                }
                else if (c == EOT)
                {
                    #region EOT

                    port.DiscardInBuffer();
                    this.writeByte(ACK);
                    //convert from memory stream to byte[]
                    return(buf.ToArray());

                    #endregion
                }
                else if (c == CAN)
                {
                    #region CAN

                    if (port.ReadByte() == CAN)
                    {
                        port.DiscardInBuffer();
                        this.writeByte(ACK);
                        return(null); //canceled by remote
                    }

                    #endregion
                }
                else
                {
                    retry++;
                    port.DiscardInBuffer();
                    this.writeByte(NAK);
                }
            }//while()

            //timeout
            this.writeByte(CAN);
            this.writeByte(CAN);
            this.writeByte(CAN);
            port.DiscardInBuffer();

            return(null);
        }
Ejemplo n.º 38
0
 public ByteBuffer put(byte[] src, int offset, int length)
 {
     stream.Write(src, offset, length);
     return(this);
 }
Ejemplo n.º 39
0
            public async Task SendJsonMessage(string messageBody)
            {
                if (ShouldRenewAuthHeader())
                {
                    SetAuthHeader();
                }

                using (var ms = new System.IO.MemoryStream())
                {
                    var bytes = System.Text.UTF8Encoding.UTF8.GetBytes(messageBody);

                    if (_UseCompression)
                    {
                        using (var cs = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, true))
                        {
                            cs.Write(bytes, 0, bytes.Length);
                            cs.Flush();
                        }
                    }
                    else
                    {
                        ms.Write(bytes, 0, bytes.Length);
                    }

                    int retries = 0, maxRetries = 5;
                    while (retries < maxRetries)
                    {
                        ms.Seek(0, System.IO.SeekOrigin.Begin);

                        using (var content = new StreamContent(ms))
                        {
                            if (_UseCompression)
                            {
                                content.Headers.ContentEncoding.Add("gzip");
                            }

                            var result = await _HttpClient.PostAsync(_ConnectionString.EventHubUrl + "/" + _ConnectionString.EventHubPath + "/messages", content).ConfigureAwait(false);

                            if (((int)result.StatusCode >= 500 && (int)result.StatusCode < 600) || (int)result.StatusCode == 429)
                            {
                                retries++;
                                if (retries < maxRetries)
                                {
#if SUPPORTS_TASKEX
                                    await TaskEx.Delay(250 *(retries + 1)).ConfigureAwait(false);
#else
                                    await Task.Delay(250 *(retries + 1)).ConfigureAwait(false);
#endif
                                    continue;
                                }
                            }

                            try
                            {
                                result.EnsureSuccessStatusCode();
                                break;
                            }
                            catch (HttpRequestException hrex)
                            {
                                hrex.Data.Add("StatusCode", result.StatusCode);
                                throw;
                            }
                        }
                    }
                }
            }
Ejemplo n.º 40
0
        /// <summary>
        /// <para>Represents the Header2 section of the EWF file.</para>
        /// <para>Holds various meta-data about the acquisition.</para>
        /// </summary>
        /// <param name="bytes">The bytes that make up the Header2 section.</param>
        public Header2(byte[] bytes)
        {
            string header = null; // Will eventually hold the decompressed Header2 info

            #region Decompress zlib'd data
            {
                byte[] buff = new byte[1024];
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes))
                {
                    using (Compression.ZlibStream zs = new Compression.ZlibStream(ms, System.IO.Compression.CompressionMode.Decompress, false))
                    {
                        using (System.IO.MemoryStream decomp = new System.IO.MemoryStream())
                        {
                            int n;
                            while ((n = zs.Read(buff, 0, buff.Length)) != 0)
                            {
                                decomp.Write(buff, 0, n);
                            }
                            decomp.Seek(0, System.IO.SeekOrigin.Begin);
                            System.IO.StreamReader sr = new System.IO.StreamReader(decomp, System.Text.Encoding.UTF8);
                            header = sr.ReadToEnd();
                        }
                    }
                }
            }
            #endregion

            string[] parts = header.Split(new char[] { (char)0x0A });

            int catsCount = int.Parse(parts[0]);
            Categories = new List <Header2Category>(catsCount);

            if (catsCount == 1)                        // EnCase 4
            {
                for (int i = 0; i < parts.Length; i++) // Header seems to have 0x0A on the end
                {
                    parts[i] = parts[i].TrimEnd('\r');
                }
                if (parts[1] != "main")
                {
                    throw new ArgumentException(string.Format("unexpected category: {0}", parts[1]));
                }
                Categories.Add(new Header2Category("main", parts[2], parts[3]));
            }
            else if (catsCount == 3) // EnCase 5-7
            {
                if (parts[1] != "main")
                {
                    throw new ArgumentException(string.Format("unexpected category: {0}", parts[1]));
                }
                Categories.Add(new Header2Category("main", parts[2], parts[3]));

                if (parts[5] != "srce")
                {
                    throw new ArgumentException(string.Format("unexpected category: {0}", parts[5]));
                }
                Categories.Add(new Header2Category("srce", parts[7], parts[9]));

                if (parts[11] != "sub")
                {
                    throw new ArgumentException(string.Format("unexpected category: {0}", parts[13]));
                }
                Categories.Add(new Header2Category("sub", parts[13], parts[15]));
            }
            else
            {
                throw new ArgumentException(string.Format("unknown category layout ({0} categories)", catsCount));
            }
        }
Ejemplo n.º 41
0
        /// <summary>
        /// 生成读取直接节点数据信息的内容
        /// </summary>
        /// <param name="cips">cip指令内容</param>
        /// <returns>最终的指令值</returns>
        public static byte[] PackCommandSpecificData(params byte[][] cips)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream( );
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            ms.WriteByte(0x01);       // 超时
            ms.WriteByte(0x00);
            ms.WriteByte(0x02);       // 项数
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);       // 连接的地址项
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);       // 长度
            ms.WriteByte(0x00);
            ms.WriteByte(0xB2);       // 连接的项数
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);       // 后面数据包的长度,等全部生成后在赋值
            ms.WriteByte(0x00);

            ms.WriteByte(0x52);       // 服务
            ms.WriteByte(0x02);       // 请求路径大小
            ms.WriteByte(0x20);       // 请求路径
            ms.WriteByte(0x06);
            ms.WriteByte(0x24);
            ms.WriteByte(0x01);
            ms.WriteByte(0x0A);       // 超时时间
            ms.WriteByte(0xF0);
            ms.WriteByte(0x00);       // CIP指令长度
            ms.WriteByte(0x00);

            int count = 0;

            if (cips.Length == 1)
            {
                ms.Write(cips[0], 0, cips[0].Length);
                count += cips[0].Length;
            }
            else
            {
                ms.WriteByte(0x0A);     // 固定
                ms.WriteByte(0x02);
                ms.WriteByte(0x20);
                ms.WriteByte(0x02);
                ms.WriteByte(0x24);
                ms.WriteByte(0x01);
                count += 8;

                ms.Write(BitConverter.GetBytes((ushort)cips.Length), 0, 2);      // 写入项数
                ushort offect = (ushort)(0x02 + 2 * cips.Length);
                count += 2 * cips.Length;

                for (int i = 0; i < cips.Length; i++)
                {
                    ms.Write(BitConverter.GetBytes(offect), 0, 2);
                    offect = (ushort)(offect + cips[i].Length);
                }

                for (int i = 0; i < cips.Length; i++)
                {
                    ms.Write(cips[i], 0, cips[i].Length);
                    count += cips[i].Length;
                }
            }
            ms.WriteByte(0x01);       // Path Size
            ms.WriteByte(0x00);
            ms.WriteByte(0x01);       // port
            ms.WriteByte(0x00);

            byte[] data = ms.ToArray( );

            BitConverter.GetBytes((short)count).CopyTo(data, 24);
            data[14] = BitConverter.GetBytes((short)(data.Length - 16))[0];
            data[15] = BitConverter.GetBytes((short)(data.Length - 16))[1];
            return(data);
        }