SetLength() public method

public SetLength ( long value ) : void
value long
return void
Ejemplo n.º 1
0
        public async Task<Message> ReceiveAsync(CancellationToken cancellationToken = default(CancellationToken)) {
            const int blockSize = 0x10000;
            var buffer = new MemoryStream(blockSize);

            while (true) {
                cancellationToken.ThrowIfCancellationRequested();

                int index = (int)buffer.Length;
                buffer.SetLength(index + blockSize);

                await _receiveLock.WaitAsync(cancellationToken);
                WebSocketReceiveResult wsrr;
                try {
                    wsrr = await _socket.ReceiveAsync(new ArraySegment<byte>(buffer.GetBuffer(), index, blockSize), cancellationToken);
                } catch (Exception ex) when(IsTransportException(ex)) {
                    throw new MessageTransportException(ex);
                } finally {
                    _receiveLock.Release();
                }

                buffer.SetLength(index + wsrr.Count);

                if (wsrr.CloseStatus != null) {
                    return null;
                }

                if (wsrr.EndOfMessage) {
                    return Message.Parse(buffer.ToArray());
                }
            }
        }
Ejemplo n.º 2
0
 public void AddBytes(byte[] bytes)
 {
     if (bytes == null)
     {
         return;
     }
     if (bytes.Length == 8)
     {
         if (bytes[0] == 240 && bytes[7] == 254)
         {
             _SplitData(bytes);
             return;
         }
     }
     try
     {
         men.Write(bytes, 0, bytes.Length);
         Split();
     }
     catch
     {
         men.SetLength(0);   // 当发生异常时要初始化基础缓存
         this.是否规则转化 = false;
     }
 }
Ejemplo n.º 3
0
        // decodes a quoted-printable encoded string
        public static string UrlDecode(string s, Encoding e)
        {
            if (null == s)
                return null;

            if (s.IndexOf ('%') == -1 && s.IndexOf ('+') == -1)
                return s;

            if (e == null)
                e = Encoding.UTF8;

            StringBuilder output = new StringBuilder ();
            long len = s.Length;
            MemoryStream bytes = new MemoryStream ();
            int xchar;

            for (int i = 0; i < len; i++) {
                if (s [i] == '%' && i + 2 < len && s [i + 1] != '%') {
                    if (s [i + 1] == 'u' && i + 5 < len) {
                        if (bytes.Length > 0) {
                            output.Append (GetChars (bytes, e));
                            bytes.SetLength (0);
                        }

                        xchar = GetChar (s, i + 2, 4);
                        if (xchar != -1) {
                            output.Append ((char) xchar);
                            i += 5;
                        } else {
                            output.Append ('%');
                        }
                    } else if ((xchar = GetChar (s, i + 1, 2)) != -1) {
                        bytes.WriteByte ((byte) xchar);
                        i += 2;
                    } else {
                        output.Append ('%');
                    }
                    continue;
                }

                if (bytes.Length > 0) {
                    output.Append (GetChars (bytes, e));
                    bytes.SetLength (0);
                }

                if (s [i] == '+') {
                    output.Append (' ');
                } else {
                    output.Append (s [i]);
                }
             }

            if (bytes.Length > 0) {
                output.Append (GetChars (bytes, e));
            }

            bytes = null;
            return output.ToString ();
        }
Ejemplo n.º 4
0
		public static string UrlDecode (string s, Encoding e)
		{
			if (null == s) 
				return null;

			if (s.IndexOf ('%') == -1 && s.IndexOf ('+') == -1)
				return s;

			if (e == null)
				e = Encoding.GetEncoding (28591);
	
			StringBuilder output = new StringBuilder ();
			long len = s.Length;
			NumberStyles hexa = NumberStyles.HexNumber;
			MemoryStream bytes = new MemoryStream ();
	
			for (int i = 0; i < len; i++) {
				if (s [i] == '%' && i + 2 < len) {
					if (s [i + 1] == 'u' && i + 5 < len) {
						if (bytes.Length > 0) {
							output.Append (GetChars (bytes, e));
							bytes.SetLength (0);
						}
						output.Append ((char) Int32.Parse (s.Substring (i + 2, 4), hexa));
						i += 5;
					} else {
						bytes.WriteByte ((byte) Int32.Parse (s.Substring (i + 1, 2), hexa));
						i += 2;
					}
					continue;
				}

				if (bytes.Length > 0) {
					output.Append (GetChars (bytes, e));
					bytes.SetLength (0);
				}

				if (s [i] == '+') {
					output.Append (' ');
				} else {
					output.Append (s [i]);
				}
	         	}
	
			if (bytes.Length > 0) {
				output.Append (GetChars (bytes, e));
			}

			bytes = null;
			return output.ToString ();
		}
Ejemplo n.º 5
0
        private static void RunTestIssue103(int loop, TypeA typeA, TypeB typeB, TypeModel model, string caption)
        {
            // for JIT and preallocation
            MemoryStream ms = new MemoryStream();
            ms.SetLength(0);
            model.Serialize(ms, typeA);
            ms.Position = 0;
            model.Deserialize(ms, null, typeof(TypeA));

            Stopwatch typeASer = Stopwatch.StartNew();
            for (int i = 0; i < loop; i++)
            {
                ms.SetLength(0);
                model.Serialize(ms, typeA);
            }
            typeASer.Stop();
            Stopwatch typeADeser = Stopwatch.StartNew();
            for (int i = 0; i < loop; i++)
            {
                ms.Position = 0;
                model.Deserialize(ms, null, typeof(TypeA));
            }
            typeADeser.Stop();

            ms.SetLength(0);
            model.Serialize(ms, typeB);
            ms.Position = 0;
            TypeB clone = (TypeB)model.Deserialize(ms, null, typeof(TypeB));
            Assert.AreEqual(typeB.containedType.Count, clone.containedType.Count);

            Stopwatch typeBSer = Stopwatch.StartNew();
            for (int i = 0; i < loop; i++)
            {
                ms.SetLength(0);
                model.Serialize(ms, typeB);
            }
            typeBSer.Stop();
            Stopwatch typeBDeser = Stopwatch.StartNew();
            for (int i = 0; i < loop; i++)
            {
                ms.Position = 0;
                model.Deserialize(ms, null, typeof(TypeB));
            }
            typeBDeser.Stop();

            Console.WriteLine(caption + " A/ser\t" + (typeASer.ElapsedMilliseconds * 1000 / loop) + " μs/item");
            Console.WriteLine(caption + " A/deser\t" + (typeADeser.ElapsedMilliseconds * 1000 / loop) + " μs/item");
            Console.WriteLine(caption + " B/ser\t" + (typeBSer.ElapsedMilliseconds * 1000 / loop) + " μs/item");
            Console.WriteLine(caption + " B/deser\t" + (typeBDeser.ElapsedMilliseconds * 1000 / loop) + " μs/item");
        }
Ejemplo n.º 6
0
        public void Write(Message message, object obj)
        {
            if (mStream == null)
            {
                mStream = new MemoryStream(4096);
            }
            mStream.Position = 0;
            mStream.SetLength(4095);
            string value = JsonConvert.SerializeObject(obj);
            int    count = Encoding.UTF8.GetBytes(value, 0, value.Length, mStream.GetBuffer(), 0);

            mStream.SetLength(count);
            message.BodyStream = mStream;
        }
		public static MulticlientConfiguration LoadConfiguration(string password)
		{
			try
			{
				EncryptHelper.DecryptFile(AppDataFolderHelper.GetMulticlientFile(), AppDataFolderHelper.GetTempMulticlientFile(), password);
			}
			catch (System.Security.Cryptography.CryptographicException)
			{
				return null;
			}
			try
			{
				var memoryStream = new MemoryStream();
				using (var fileStream = new FileStream(AppDataFolderHelper.GetTempMulticlientFile(), FileMode.Open))
				{
					memoryStream.SetLength(fileStream.Length);
					fileStream.Read(memoryStream.GetBuffer(), 0, (int)fileStream.Length);
				}
				File.Delete(AppDataFolderHelper.GetTempMulticlientFile());
				var dataContractSerializer = new DataContractSerializer(typeof(MulticlientConfiguration));
				var configuration = (MulticlientConfiguration)dataContractSerializer.ReadObject(memoryStream);
				return configuration;
			}
			catch (Exception e)
			{
				Logger.Error(e, "MulticlientConfigurationHelper.LoadConfiguration");
			}
			return null;
		}
Ejemplo n.º 8
0
        public void TestMbr()
        {
            MemoryStream ms = new MemoryStream();
            ms.SetLength(1024 * 1024);

            byte[] newMbr = new byte[512];
            for (int i = 0; i < 512; i++)
            {
                newMbr[i] = (byte)i;
            }

            Raw.Disk rawDisk = new DiscUtils.Raw.Disk(ms, Ownership.Dispose);
            rawDisk.SetMasterBootRecord(newMbr);

            byte[] readMbr = rawDisk.GetMasterBootRecord();
            Assert.AreEqual(512, readMbr.Length);

            for (int i = 0; i < 512; i++)
            {
                if (readMbr[i] != (byte)i)
                {
                    Assert.Fail("Mismatch on byte {0}, expected {1} was {2}", i, (byte)i, readMbr[i]);
                }
            }
        }
        private BufferSlice EncodeMessage(Message msg)
        {
            if (msg.Body.Length != 0)
                msg.Headers["Content-Length"] = msg.Body.Length.ToString();

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


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

            var tmp = Encoding.ASCII.GetString(buffer, 0, (int) length);
            return new BufferSlice(buffer, 0, (int) length, (int) length);
        }
Ejemplo n.º 10
0
        public static Stream ReadPersianNumber(int number, string tempDirectory)
        {
            if (number > 99 || number < 1)
                return
                    Assembly.GetExecutingAssembly().GetManifestResourceStream(
                        "Fardis.Audio.Wave.Invalid.wav");

            var reminder = number % 10;

            if (number <= 20 || reminder == 0)
                return PrepareSingle(number, tempDirectory);

            int quotient = number / 10;
            var firstPart = quotient * 10;

            var fileName = Concatenate(new[]
                {
                    Assembly.GetExecutingAssembly().GetManifestResourceStream(
                    string.Format("Fardis.Audio.Wave.{0}.wav", firstPart)),
                    Assembly.GetExecutingAssembly().GetManifestResourceStream(
                    "Fardis.Audio.Wave.And.wav"),
                    Assembly.GetExecutingAssembly().GetManifestResourceStream(
                    string.Format("Fardis.Audio.Wave.{0}.wav", reminder)),
                }, tempDirectory);

            var memStream = new MemoryStream();
            using (var fileStream = File.OpenRead(fileName))
            {
                memStream.SetLength(fileStream.Length);
                fileStream.Read(memStream.GetBuffer(), 0, (int)fileStream.Length);
            }

            return memStream;
        }
Ejemplo n.º 11
0
        /**
         * Finds next Nth H.264 bitstream NAL unit (0x00000001) and returns the data
         * that preceeds it as a System.IO.MemoryStream slice
         *
         * Segment byte order is always little endian
         *
         * TODO: emulation prevention
         *
         * @param buf
         * @return
         */
        public static System.IO.MemoryStream gotoNALUnit(System.IO.MemoryStream buf)
        {
            if (buf.Position >= buf.Length)
            {
                return(null);
            }

            long from = buf.Position;

            byte[] temp = new byte[buf.Length - buf.Position];

            buf.Read(temp, 0, (int)(buf.Length - buf.Position));

            System.IO.MemoryStream result = new System.IO.MemoryStream(temp);
            //result.order(ByteOrder.BIG_ENDIAN);

            long val = 0xffffffff;

            while (buf.Position < buf.Length)
            {
                val <<= 8;
                val  |= (buf.ReadByte() & 0xff);
                if ((val & 0xffffff) == 1)
                {
                    buf.Position = buf.Position - (val == 1 ? 4 : 3);
                    result.SetLength(buf.Position - from);
                    break;
                }
            }
            return(result);
        }
Ejemplo n.º 12
0
        public static object deepCopyFromFileToObject(string fileName)
        {
            FileStream inStream = File.OpenRead(fileName);
            MemoryStream memoryStream = new MemoryStream();

            memoryStream.SetLength(inStream.Length);
            inStream.Read(memoryStream.GetBuffer(), 0, (int)inStream.Length);

            memoryStream.Flush();
            memoryStream.Position = 0;
            inStream.Close();

            object deserializedObject = null;

            try
            {
                BinaryFormatter serializer = new BinaryFormatter();
                deserializedObject = serializer.Deserialize(memoryStream);
            }
            finally
            {
                if (memoryStream != null)
                    memoryStream.Close();
            }
            return deserializedObject;
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Reads byte[] line from stream. NOTE: Returns null if end of stream reached.
        /// </summary>
        /// <returns>Return null if end of stream reached.</returns>
        public byte[] ReadLine()
        {
            MemoryStream strmLineBuf = new MemoryStream();
            byte      prevByte = 0;

            int currByteInt = m_StrmSource.ReadByte();
            while(currByteInt > -1){
                strmLineBuf.WriteByte((byte)currByteInt);

                // Line found
                if((prevByte == (byte)'\r' && (byte)currByteInt == (byte)'\n')){
                    strmLineBuf.SetLength(strmLineBuf.Length - 2); // Remove <CRLF>

                    return strmLineBuf.ToArray();
                }

                // Store byte
                prevByte = (byte)currByteInt;

                // Read next byte
                currByteInt = m_StrmSource.ReadByte();
            }

            // Line isn't terminated with <CRLF> and has some bytes left, return them.
            if(strmLineBuf.Length > 0){
                return strmLineBuf.ToArray();
            }

            return null;
        }
Ejemplo n.º 14
0
 /// <summary>
 /// 解密
 /// </summary>
 /// <param name="encryptedText"></param>
 /// <param name="key"></param>
 /// <param name="encoding"></param>
 /// <returns></returns>
 public string DoDecrypt(string encryptedText, string key, Encoding encoding)
 {
     try
     {
         desKey = Encoding.Unicode.GetBytes(key);
         encryptedText = encryptedText.Replace("{z1}", "=");
         encryptedText = encryptedText.Replace("{z2}", "&");
         MemoryStream stream = new MemoryStream(200);
         stream.SetLength(0L);
         byte[] buffer = Convert.FromBase64String(encryptedText);
         Rijndael rijndael = new RijndaelManaged();
         rijndael.KeySize = 0x100;
         CryptoStream stream2 = new CryptoStream(stream, rijndael.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write);
         stream2.Write(buffer, 0, buffer.Length);
         stream2.FlushFinalBlock();
         stream.Flush();
         stream.Seek(0L, SeekOrigin.Begin);
         byte[] buffer2 = new byte[stream.Length];
         stream.Read(buffer2, 0, buffer2.Length);
         stream2.Close();
         stream.Close();
         return Encoding.Unicode.GetString(buffer2);
     }
     catch (Exception ex)
     {
         return "";
     }
 }
Ejemplo n.º 15
0
        public static void unescapeNAL(System.IO.MemoryStream _buf)
        {
            if (_buf.Position - _buf.Length < 2)
            {
                return;
            }
            System.IO.MemoryStream inb  = new System.IO.MemoryStream(_buf.ToArray());
            System.IO.MemoryStream outb = new System.IO.MemoryStream(_buf.ToArray());
            byte p1 = (byte)inb.ReadByte();

            outb.WriteByte(p1);
            byte p2 = (byte)inb.ReadByte();

            outb.WriteByte(p2);
            while (inb.Position < inb.Length)
            {
                byte b = (byte)inb.ReadByte();
                if (p1 != 0 || p2 != 0 || b != 3)
                {
                    outb.WriteByte(b);
                }
                p1 = p2;
                p2 = b;
            }
            _buf.SetLength(outb.Position);
        }
Ejemplo n.º 16
0
 public byte[] SubByte(byte[] srcBytes, int startIndex, int length)
 {
     try {
         System.IO.MemoryStream bufferStream = new System.IO.MemoryStream();
         byte[] returnByte = new byte[] { };
         if (srcBytes == null)
         {
             return(returnByte);
         }
         if (startIndex < 0)
         {
             startIndex = 0;
         }
         if (startIndex < srcBytes.Length)
         {
             if (length < 1 || length > srcBytes.Length - startIndex)
             {
                 length = srcBytes.Length - startIndex;
             }
             bufferStream.Write(srcBytes, startIndex, length);
             returnByte = bufferStream.ToArray();
             bufferStream.SetLength(0);
             bufferStream.Position = 0;
         }
         bufferStream.Close();
         bufferStream.Dispose();
         return(returnByte);
     }
     catch (Exception error) {
         WriteMessage("BasicSocketClass->SubByte:" + error.Message);
         return(new byte[0]);
     }
 }
Ejemplo n.º 17
0
		/// <summary>
		/// Wraps a byte array into a buffer.
		/// The new buffer will be backed by the given byte array; that is, modifications 
		/// to the buffer will cause the array to be modified and vice versa. 
		/// The new buffer's capacity will be array.length, its position will be offset, 
		/// its limit will be offset + length, and its mark will be undefined.
		/// </summary>
		/// <param name="array">Byte array to wrap.</param>
		/// <param name="offset">Offset in the byte array.</param>
		/// <param name="length"></param>
		/// <returns></returns>
		public static ByteBuffer Wrap(byte[] array, int offset, int length) {
			MemoryStream ms = new MemoryStream(array, offset, length, true, true);
			ms.Capacity = array.Length;
			ms.SetLength(offset + length);
			ms.Position = offset;
			return new ByteBuffer(ms);
		}
Ejemplo n.º 18
0
 public NetworkBuffer()
 {
     mStream = new MemoryStream();
     mStream.SetLength(mInitialialSize);
     mReadOffset = 0;
     mWriteOffset = 0;
 }
Ejemplo n.º 19
0
        public static IObservable<byte[]> MinimumBuffer(this IObservable<byte[]> input, int minimumBufSize)
        {
            return Observable.Create<byte[]>(observer =>
            {
                MemoryStream memStream = new MemoryStream();

                return input.Subscribe(
                    bytes =>
                    {
                        memStream.Write(bytes, 0, bytes.Length);
                        if (memStream.Length >= minimumBufSize)
                        {
                            Debug.Assert(memStream.Position == memStream.Length);
                            observer.OnNext(memStream.ToArray());

                            memStream.SetLength(0);// truncate the stream
                            memStream.Position = 0;
                        }
                    },
                    observer.OnError,
                    () =>
                    {
                        if (memStream.Length > 0)
                            observer.OnNext(memStream.ToArray());
                        observer.OnCompleted();
                    }
                    );
            });
        }
Ejemplo n.º 20
0
		public static void Serve(string filePath, HttpContext context, string contentType)
		{
			CachePrep(ref filePath);
			lock (GetImageLock(filePath))
			{
				try
				{
					using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
					{
						using (MemoryStream memoryStream = new MemoryStream())
						{
							memoryStream.SetLength(fileStream.Length);
							fileStream.Read(memoryStream.GetBuffer(), 0, (int)fileStream.Length);
							memoryStream.WriteTo(context.Response.OutputStream);
							context.Response.ContentType = contentType;
						}
					}
				}
				catch (Exception ex)
				{
					ex.GetType();
					//The requested resource doesn't exist. Return HTTP status code 404.
					context.Response.StatusCode = (int)HttpStatusCode.NotFound;
					context.Response.StatusDescription = "Resource not found.";
				}

				RemoveImageLock(filePath);
			}
		}
Ejemplo n.º 21
0
        static void Main(string[] args)
        {
            const string releaseDir = @"";
            var assemblyPath = Path.Combine(Path.Combine(Environment.CurrentDirectory, releaseDir), "LINQPadLog4jDriver.dll");
            var assembly = Assembly.LoadFile(assemblyPath);
            var version = assembly.GetName().Version;

            using (var ms = new MemoryStream())
            using (var releaseZip = new ZipFile())
            using (var lpx45 = new ZipFile())
            {
                var releaseZipPath = Path.Combine(releaseDir, string.Format("Log4jLinqpadDriver {0}.zip", version));
                lpx45.AddFile(Path.Combine(Environment.CurrentDirectory, "LINQPadLog4jDriver.dll"), "");
                lpx45.AddFile(Path.Combine(Environment.CurrentDirectory, "header.xml"), "");
                lpx45.Save(ms);
                ms.Seek(0, SeekOrigin.Begin);
                releaseZip.AddEntry("Log4jLinqpadDriver.lpx", ms);

                releaseZip.Save(releaseZipPath);
                ms.SetLength(0);

                // readme
                releaseZip.AddFile(Path.Combine(releaseDir, "readme.txt"), "");
                releaseZip.Save(releaseZipPath);
            }

            // open
            Process.Start(Environment.CurrentDirectory);
        }
        public async Task StringTestAsync()
        {
            MemoryStream memStream = new MemoryStream();
            BigEndianStream bigEndianStream = new BigEndianStream(memStream);

            string testString = "Hello, World!";

            await bigEndianStream.WriteAsync(testString);

            memStream.Seek(0, SeekOrigin.Begin);

            var result = await bigEndianStream.ReadString16Async();

            Assert.AreEqual(testString, result);

            Assert.AreEqual(memStream.Position, memStream.Length);


            memStream.SetLength(0);

            bigEndianStream.Write8(testString);

            memStream.Seek(0, SeekOrigin.Begin);

            result = await bigEndianStream.ReadString8Async();

            Assert.AreEqual(testString, result);

            Assert.AreEqual(memStream.Position, memStream.Length);
        }
		private static int ReadInputLine(
			MemoryStream	bOut,
			int				lookAhead,
			Stream			fIn)
		{
			bOut.SetLength(0);

			int ch = lookAhead;

			do
			{
				bOut.WriteByte((byte) ch);
				if (ch == '\r' || ch == '\n')
				{
					lookAhead = ReadPassedEol(bOut, ch, fIn);
					break;
				}
			}
			while ((ch = fIn.ReadByte()) >= 0);

			if (ch < 0)
			{
				lookAhead = -1;
			}

			return lookAhead;
		}
        public void StringTest()
        {
            MemoryStream memStream = new MemoryStream();
            BigEndianStream bigEndianStream = new BigEndianStream(memStream);

            string testString = "Hello, World!";

            bigEndianStream.Write(testString);

            memStream.Seek(0, SeekOrigin.Begin);

            var result = bigEndianStream.ReadString16();

            Assert.AreEqual(testString, result);

            Assert.AreEqual(memStream.Position, memStream.Length);


            memStream.SetLength(0);

            bigEndianStream.Write8(testString);

            memStream.Seek(0, SeekOrigin.Begin);

            result = bigEndianStream.ReadString8();

            Assert.AreEqual(testString, result);

            Assert.AreEqual(memStream.Position, memStream.Length);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Post processes the image.
        /// </summary>
        /// <param name="stream">The source image stream.</param>
        /// <param name="extension">The image extension.</param>
        /// <returns>
        /// The <see cref="MemoryStream"/>.
        /// </returns>
        public static MemoryStream PostProcessImage(MemoryStream stream, string extension)
        {
            // Create a source temporary file with the correct extension.
            long length = stream.Length;
            string tempFile = Path.GetTempFileName();
            string sourceFile = Path.ChangeExtension(tempFile, extension);
            File.Move(tempFile, sourceFile);

            // Save the input stream to a temp file for post processing.
            using (FileStream fileStream = File.Create(sourceFile))
            {
                stream.CopyTo(fileStream);
            }

            PostProcessingResultEventArgs result = RunProcess(sourceFile, length);

            if (result != null && result.Saving > 0)
            {
                using (FileStream fileStream = File.OpenRead(sourceFile))
                {
                    // Replace stream contents.
                    stream.SetLength(0);
                    fileStream.CopyTo(stream);
                }
            }

            // Cleanup
            File.Delete(sourceFile);

            stream.Position = 0;

            return stream;
        }
		private async void StartReceiving()
		{
			var buffer = new byte[8192];
			var segment = new ArraySegment<byte>(buffer, 0, buffer.Length);
			using (var ms = new MemoryStream())
			{
				try
				{
					do
					{
						if (_socket.State != WebSocketState.Open)
						{
							await Task.Delay(10);
							continue;
						}
						var result = await _socket.ReceiveAsync(segment, _tokenSource.Token);
						if (result.CloseStatus != null && result.CloseStatus != WebSocketCloseStatus.Empty)
							break;
						if (result.Count > 0)
							ms.Write(segment.Array, segment.Offset, result.Count);
						if (result.EndOfMessage)
						{
							var data = new ArraySegment<byte>(ms.GetBuffer(), 0, (int) ms.Length);
							var args = new DataReceivedArgs { Data = data, SessionID = _socket };
							Received.Invoke(this, args); // assuming synchronous usage of the data: that may not be correct
							ms.SetLength(0);
						}
					} while (!_tokenSource.IsCancellationRequested);
				}
				catch (OperationCanceledException)
				{
					// exit without propagating the exception
				}
			}
		}
 public ByteBuffer(int length)
 {
     this._memoryStream = new MemoryStream();
     _memoryStream.SetLength(length);
     _memoryStream.Capacity = length;
     _limit = length;
 }
Ejemplo n.º 28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="HttpMessageEncoder"/> class.
 /// </summary>
 public HttpEncoder(BufferManager bufferManager)
 {
     _bufferManager = bufferManager;
     _headerStream = new MemoryStream(_buffer);
     _headerStream.SetLength(0);
     _writer = new StreamWriter(_headerStream);
 }
Ejemplo n.º 29
0
 /// <summary>
 /// 截取字节数组
 /// </summary>
 /// <param name="srcBytes">要截取的字节数组</param>
 /// <param name="startIndex">开始截取位置的索引</param>
 /// <param name="length">要截取的字节长度</param>
 /// <returns>截取后的字节数组</returns>
 public static byte[] SubByte(byte[] srcBytes, int startIndex, int length)
 {
     byte[] returnByte = null;
     using (System.IO.MemoryStream bufferStream = new System.IO.MemoryStream())
     {
         if (srcBytes == null)
         {
             return(returnByte);
         }
         if (startIndex < 0)
         {
             startIndex = 0;
         }
         if (startIndex < srcBytes.Length)
         {
             if (length < 1 || length > srcBytes.Length - startIndex)
             {
                 length = srcBytes.Length - startIndex;
             }
             bufferStream.Write(srcBytes, startIndex, length);
             returnByte = bufferStream.ToArray();
             bufferStream.SetLength(0);
             bufferStream.Position = 0;
         }
         bufferStream.Close();
         bufferStream.Dispose();
     }
     return(returnByte);
 }
Ejemplo n.º 30
0
 static ByteString EncodeObject (object value, Type type, MemoryStream buffer, CodedOutputStream stream)
 {
     buffer.SetLength (0);
     if (value != null && !type.IsInstanceOfType (value))
         throw new ArgumentException ("Value of type " + value.GetType () + " cannot be encoded to type " + type);
     if (value == null && !type.IsSubclassOf (typeof(RemoteObject)) && !IsACollectionType (type))
         throw new ArgumentException ("null cannot be encoded to type " + type);
     if (value == null)
         stream.WriteUInt64 (0);
     else if (value is Enum)
         stream.WriteInt32 ((int)value);
     else {
         switch (Type.GetTypeCode (type)) {
         case TypeCode.Int32:
             stream.WriteInt32 ((int)value);
             break;
         case TypeCode.Int64:
             stream.WriteInt64 ((long)value);
             break;
         case TypeCode.UInt32:
             stream.WriteUInt32 ((uint)value);
             break;
         case TypeCode.UInt64:
             stream.WriteUInt64 ((ulong)value);
             break;
         case TypeCode.Single:
             stream.WriteFloat ((float)value);
             break;
         case TypeCode.Double:
             stream.WriteDouble ((double)value);
             break;
         case TypeCode.Boolean:
             stream.WriteBool ((bool)value);
             break;
         case TypeCode.String:
             stream.WriteString ((string)value);
             break;
         default:
             if (type.Equals (typeof(byte[])))
                 stream.WriteBytes (ByteString.CopyFrom ((byte[])value));
             else if (IsAClassType (type))
                 stream.WriteUInt64 (((RemoteObject)value).id);
             else if (IsAMessageType (type))
                 ((IMessage)value).WriteTo (buffer);
             else if (IsAListType (type))
                 WriteList (value, type, buffer);
             else if (IsADictionaryType (type))
                 WriteDictionary (value, type, buffer);
             else if (IsASetType (type))
                 WriteSet (value, type, buffer);
             else if (IsATupleType (type))
                 WriteTuple (value, type, buffer);
             else
                 throw new ArgumentException (type + " is not a serializable type");
             break;
         }
     }
     stream.Flush ();
     return ByteString.CopyFrom (buffer.GetBuffer (), 0, (int)buffer.Length);
 }
Ejemplo n.º 31
0
        private bool sendEmail()
        {
            List<string> MyEmailList = new List<string>();
            MyEmailList.Add(tbEmailAddress.Text);
            EmailAttachment MyEmailAttachment = new EmailAttachment();

            using (FileStream fileStream = File.OpenRead(Server.MapPath("/AttachmentExample.txt")))
            {
                MemoryStream memStream = new MemoryStream();
                memStream.SetLength(fileStream.Length);
                fileStream.Read(memStream.GetBuffer(), 0, (int)fileStream.Length);
                MyEmailAttachment.AttachmentMemoryStream = memStream;
                MyEmailAttachment.AttachmentFileInfo = new FileInfo(Server.MapPath("/AttachmentExample.txt"));
            }

            List<EmailAttachment> MyEmailAttachmentList = new List<EmailAttachment>();
            MyEmailAttachmentList.Add(MyEmailAttachment);

            Email MyEmail = new Email(MyEmailList, MyEmailAttachmentList, "Test subject", "Test body", null, ConfigurationManager.AppSettings["EmailFrom"]);
            if (!MyEmail.SendEmail())
            {
                ErrorMessage = MyEmail.ErrorMessage;
                return false;
            }
            return true;
        }
Ejemplo n.º 32
0
        public void Flush()
        {
            _bufferSize = 0;

            using (var tx = _storageEnvironment.NewTransaction(TransactionFlags.ReadWrite))
            {
                foreach (var kvp in _buffer)
                {
                    var data = _storageEnvironment.CreateTree(tx, "channel:" + kvp.Key);
                    var buffer = new byte[16];
                    var key = new Slice(buffer);
                    var ms = new MemoryStream();
                    var bw = new BinaryWriter(ms);
                    foreach (var item in kvp.Value)
                    {
                        var date = item.Timestamp;
                        EndianBitConverter.Big.CopyBytes(date.Ticks, buffer, 0);
                        EndianBitConverter.Big.CopyBytes(_last++, buffer, 8);
                        ms.SetLength(0);
                        bw.Write(item.Value);
                        ms.Position = 0;

                        data.Add(tx, key, ms);
                    }
                }

                tx.State.Root.Add(tx, _lastKey, new MemoryStream(BitConverter.GetBytes(_last)));
                tx.Commit();
            }
            _buffer.Clear();
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Do Encry for plainString.
        /// </summary>
        /// <param name="plainString">Plain string.</param>
        /// <returns>Encrypted string as base64.</returns>
        public string Encrypt(string plainString)
        {
            // Create the file streams to handle the input and output files.
            MemoryStream fout = new MemoryStream(200);
            fout.SetLength(0);

            // Create variables to help with read and write.
            byte[] bin = System.Text.Encoding.Unicode.GetBytes(plainString);
            DES des = new DESCryptoServiceProvider();

            // des.KeySize=64;
            CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);
            encStream.Write(bin, 0, bin.Length);
            encStream.FlushFinalBlock();

            fout.Flush();
            fout.Seek(0, SeekOrigin.Begin);

            // read all string
            byte[] bout = new byte[fout.Length];
            fout.Read(bout, 0, bout.Length);
            encStream.Close();
            fout.Close();

            return Convert.ToBase64String(bout, 0, bout.Length);
        }
Ejemplo n.º 34
0
 public void TestPerfermence(string path)
 {
     int num;
     byte[] buffer = File.ReadAllBytes(path);
     Stopwatch stopwatch = Stopwatch.StartNew();
     MemoryStream targetStream = new MemoryStream();
     for (num = 0; num < 10; num++)
     {
         targetStream.SetLength(0L);
         Lz4CompressStream stream2 = new Lz4CompressStream(targetStream);
         stream2.Write(buffer, 0, buffer.Length);
         stream2.Close();
     }
     Console.WriteLine("compress total {0} ms, {1}MB/S", stopwatch.ElapsedMilliseconds,
         (buffer.Length * 10 / stopwatch.ElapsedMilliseconds) / 0x400L);
     stopwatch.Restart();
     for (num = 0; num < 10; num++)
     {
         targetStream.Position = 0L;
         Lz4DecompressStream stream3 = new Lz4DecompressStream(targetStream);
         Assert.That(stream3.Read(buffer, 0, buffer.Length), Is.EqualTo(buffer.Length));
     }
     Console.WriteLine("decompress total {0} ms, {1}MB/S", stopwatch.ElapsedMilliseconds,
         (buffer.Length * 10 / stopwatch.ElapsedMilliseconds) / 0x400L);
 }
Ejemplo n.º 35
0
 public NewByteBuffer flip()
 {
     mode = Mode.Read;
     stream.SetLength(stream.Position);
     stream.Position = 0;
     return(this);
 }
Ejemplo n.º 36
0
        public void IsAssembly_WhenStreamDoesNotContainPEHeaderSignature_ReturnsFalse()
        {
            var stream = new MemoryStream();
            stream.SetLength(1024); // only contains nulls

            Assert.IsFalse(AssemblyUtils.IsAssembly(stream));
        }
Ejemplo n.º 37
0
        private byte[] SubByte(byte[] srcBytes, int startIndex, int length)
        {
            System.IO.MemoryStream bufferStream = new System.IO.MemoryStream();

            // Console.WriteLine("srcbyte length = {0}\n", srcBytes.Length);

            byte[] returnByte = new byte[] { };
            if (srcBytes == null)
            {
                return(returnByte);
            }
            if (startIndex < 0)
            {
                startIndex = 0;
            }
            if (startIndex < srcBytes.Length)
            {
                if (length < 1 || length > srcBytes.Length - startIndex)
                {
                    length = srcBytes.Length - startIndex;
                }
                bufferStream.Write(srcBytes, startIndex, length);
                returnByte = bufferStream.ToArray();
                bufferStream.SetLength(0);
                bufferStream.Position = 0;
            }
            bufferStream.Close();
            bufferStream.Dispose();
            return(returnByte);
        }
        public static Stream Convert(Stream originalStream)
        {
            var copyData = new byte[originalStream.Length];
            originalStream.Read(copyData, 0, copyData.Length);
            var copyStream = new MemoryStream(copyData);

            var encoding = DetectEncoding(copyData);

            if (encoding == null)
                return copyStream;

            var utf8Suffix = new byte[] { 0xC2 };

            if (encoding == Encoding.UTF8 && IsDataSuffixed(copyData, utf8Suffix))
                copyStream.SetLength(copyStream.Length - utf8Suffix.Length);

            using (var copyReader = new StreamReader(copyStream, encoding))
            {
                var originalText = copyReader.ReadToEnd();
                var asciiData = Encoding.ASCII.GetBytes(originalText);
                var asciiText = Encoding.ASCII.GetString(asciiData);

                if (originalText == asciiText)
                    return new MemoryStream(asciiData);

                return CreateSuffixedStream(originalText, Encoding.UTF8, utf8Suffix);
            }
        }
Ejemplo n.º 39
0
 public static void MemoryStreamClear()
 {
     if (_ms == null)
     {
         return;
     }
     _ms.Position = 0;
     _ms.SetLength(0);
 }
Ejemplo n.º 40
0
        private byte[] Decompress(byte[] data, int offset, int count)
        {
            if (decompressorInputStream == null)
            {
                decompressorInputStream = new MemoryStream(count);
            }

            decompressorInputStream.Write(data, offset, count);

            // http://tools.ietf.org/html/rfc7692#section-7.2.2
            // Append 4 octets of 0x00 0x00 0xff 0xff to the tail end of the payload of the message.
            //decompressorInputStream.Write(PerMessageCompression.Trailer, 0, PerMessageCompression.Trailer.Length);

            decompressorInputStream.Position = 0;

            if (decompressorGZipStream == null)
            {
                decompressorGZipStream = new Decompression.Zlib.GZipStream(decompressorInputStream,
                                                                           Decompression.Zlib.CompressionMode.Decompress,
                                                                           Decompression.Zlib.CompressionLevel.Default,
                                                                           true);
                decompressorGZipStream.FlushMode = Decompression.Zlib.FlushType.Sync;
            }

            if (decompressorOutputStream == null)
            {
                decompressorOutputStream = new System.IO.MemoryStream();
            }
            decompressorOutputStream.SetLength(0);

            if (copyBuffer == null)
            {
                copyBuffer = new byte[1024];
            }

            int readCount;

            while ((readCount = decompressorGZipStream.Read(copyBuffer, 0, copyBuffer.Length)) != 0)
            {
                decompressorOutputStream.Write(copyBuffer, 0, readCount);
            }

            decompressorGZipStream.SetLength(0);

            byte[] result = decompressorOutputStream.ToArray();

            /*if (this.ServerNoContextTakeover)
             * {
             *  decompressorDeflateStream.Dispose();
             *  decompressorDeflateStream = null;
             * }*/

            return(result);
        }
Ejemplo n.º 41
0
        // 收到数据,解析并读取数据
        public void OnDataReceived()
        {
            int curPos = 0;

            while (mRecvPos - curPos >= 8)
            {
                // 数据长度
                int len = BitConverter.ToInt32(mRecvBuffer, curPos);  // 将数组中指定位置的四个字节转换为Int32
                // 数据类型
                int type = BitConverter.ToInt32(mRecvBuffer, curPos + 4);
                if (len > mRecvBuffer.Length)
                {
                    DebugEx.LogError("can't parse message" + "type=" + type + "len=" + len);
                    break;
                }
                if (len > mRecvPos - curPos)
                {
                    break; //wait net recv more buffer to parse.
                }
                //获取stream
                System.IO.MemoryStream tempStream = null;
                if (mReceiveStreamsPool.Count > 0)
                {
                    tempStream = mReceiveStreamsPool[0];
                    tempStream.SetLength(0);
                    tempStream.Position = 0;
                    mReceiveStreamsPool.RemoveAt(0);
                }
                else
                {
                    tempStream = new System.IO.MemoryStream();
                }
                //往stream填充网络数据
                tempStream.Write(mRecvBuffer, curPos + 8, len - 8);
                tempStream.Position = 0;
                curPos += len;
                mMessageQueue.Enqueue(new KeyValuePair <int, MemoryStream>(type, tempStream));
            }
            if (curPos > 0)         // 读取了大小为curPos数据
            {
                mRecvPos -= curPos; // 剩下未读取的数据量

                if (mRecvPos < 0)
                {
                    DebugEx.LogError("mRecvPos < 0");
                }

                if (mRecvPos > 0)
                {
                    // 将剩下未读取的数据移动到mRecvBuffer的头部
                    Buffer.BlockCopy(mRecvBuffer, curPos, mRecvBuffer, 0, mRecvPos);
                }
            }
        }
Ejemplo n.º 42
0
    /// <summary>
    /// 把接收到的消息解析出来
    /// </summary>
    public void ParseReceivedData()
    {
        int m_CurPos = 0;

        while (receive_pos - m_CurPos >= 8)                                //表示消息超过消息头(是否接收消息超过消息头的大小,如果比消息头都小,表示消息还没有接收完毕,继续接收)
        {
            int len  = BitConverter.ToInt32(receive_buffer, m_CurPos);     //总长度
            int type = BitConverter.ToInt32(receive_buffer, m_CurPos + 4); //消息id
            if (len > receive_buffer.Length)                               //解析出消息的长度len和id
            {
                Debug.LogError("can't pause message" + "type=" + type + "len=" + len);
                break;
            }

            //这个判断和上面有点类似,但是有点不一样,上面的只能判断一条消息的时候,这个可以假如一次收到的是两条消息
            //那么m_CurPos指针会偏移,那么是不是可以判断第二条消息是否出错
            if (len > receive_pos - m_CurPos) //如果接收的消息本来是len这么长度,过这个判断,发现收到的竟然少了,说明出现错误
            {
                break;                        //wait net recv more buffer to parse.
            }
            //获取stream (这里搞了一个stream对象池,为什么要用对象池,因为消息不断发送过来,你的stream是要不断地new,很耗内存,所以这里搞了个stream对象池存stream,需要的时候直接取)
            System.IO.MemoryStream tempStream = null;
            if (receive_streams_pool.Count > 0)
            {
                tempStream = receive_streams_pool[0];
                tempStream.SetLength(0);
                tempStream.Position = 0;
                receive_streams_pool.RemoveAt(0);
            }
            else
            {
                tempStream = new System.IO.MemoryStream();
            }
            //往stream填充网络数据
            tempStream.Write(receive_buffer, m_CurPos + 8, len - 8);
            tempStream.Position = 0;
            m_CurPos           += len; //偏移指针,到下条消息开始处
            receive_Msg_IDs.Add(type);
            receive_streams.Add(tempStream);
        }
        if (m_CurPos > 0) //当你解析出所有消息后,判断指针是否移动到缓存数组的最后(正常的话.是为0)
        {
            receive_pos = receive_pos - m_CurPos;
            if (receive_pos < 0)
            {
                Debug.LogError("m_RecvPos < 0");
            }
            if (receive_pos > 0)
            {
                Buffer.BlockCopy(receive_buffer, m_CurPos, receive_buffer, 0, receive_pos);
            }
        }
    }
Ejemplo n.º 43
0
    protected virtual void OnButtonClearSendAreaClicked(object sender, System.EventArgs e)
    {
//				textviewTextS.Buffer.Clear ();
//				textviewHexS.Buffer.Clear ();
//				textviewDecS.Buffer.Clear ();
        moverTextS.Clear();
        moverHexS.Clear();
        moverDecS.Clear();

        SendStream.SetLength(0);
        labelTx.Text = ReceiveStream.Length.ToString();
    }
Ejemplo n.º 44
0
        private byte[] Decompress(byte[] data, int offset, int count, bool forceDecompress = false)
        {
            if (decompressorInputStream == null)
            {
                decompressorInputStream = new MemoryStream(count);
            }

            if (data != null)
            {
                decompressorInputStream.Write(data, offset, count);
            }

            if (!forceDecompress && decompressorInputStream.Length < MinLengthToDecompress)
            {
                return(null);
            }

            decompressorInputStream.Position = 0;

            if (decompressorGZipStream == null)
            {
                decompressorGZipStream = new Decompression.Zlib.GZipStream(decompressorInputStream,
                                                                           Decompression.Zlib.CompressionMode.Decompress,
                                                                           Decompression.Zlib.CompressionLevel.Default,
                                                                           true);
                decompressorGZipStream.FlushMode = Decompression.Zlib.FlushType.Sync;
            }

            if (decompressorOutputStream == null)
            {
                decompressorOutputStream = new System.IO.MemoryStream();
            }
            decompressorOutputStream.SetLength(0);

            if (copyBuffer == null)
            {
                copyBuffer = new byte[1024];
            }

            int readCount;

            while ((readCount = decompressorGZipStream.Read(copyBuffer, 0, copyBuffer.Length)) != 0)
            {
                decompressorOutputStream.Write(copyBuffer, 0, readCount);
            }

            decompressorGZipStream.SetLength(0);

            byte[] result = decompressorOutputStream.ToArray();

            return(result);
        }
Ejemplo n.º 45
0
        private async void getResult()
        {
            string strRequestUri = "http://www.sczg.unizg.hr/prehrana/restorani/zuk-borongaj/";
            string strResult     = string.Empty;
            string websource1    = string.Empty;

            try
            {
                HttpClient httpClient = new HttpClient();
                websource1 = httpClient.BaseAddress;

                try
                {
                    // GetStringAsync
                    strResult = await httpClient.GetStringAsync(strRequestUri);

                    // GetByteArrayAsync
                }
                catch (Exception ex)
                {
                    strResult = ex.Message;
                }
            }
            catch (Exception ex)
            {
                strResult = ex.Message;
            }
            finally
            {
                // Show the result.


                Dispatcher.BeginInvoke(delegate()
                {
                    Stream repo = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(strResult));
                    Generiraj_menu("MENU-MESNI:", listbox1, "MENU-VEGETARIJANSKI", repo, 1);
                    repo.SetLength(0);

                    repo = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(strResult));
                    Generiraj_menu("MENU-VEGETARIJANSKI", listbox2, "GLAVNA JELA", repo, 2);
                    repo.SetLength(0);

                    repo = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(strResult));
                    Generiraj_menu("GLAVNA JELA", listbox3, "PRILO", repo, 3);
                    repo.SetLength(0);

                    repo = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(strResult));
                    Generiraj_menu("PRILO", listbox4, "Normativ", repo, 4);
                    repo.SetLength(0);
                });
            }
        }
Ejemplo n.º 46
0
    /// <summary>
    /// 发送消息
    /// </summary>
    /// <param name="pMsg"></param>
    /// <param name="MsgID"></param>
    public void SendMessage(LuaByteBuffer data, Int32 MsgID)
    {
        if (client != null)
        {
            //清除stream (可见,我们要发送消息,一定要有发送消息发送流)
            send_streams.SetLength(0);
            send_streams.Position = 0;

            //添加到send_streams里面
            send_streams.Write(data.buffer, 0, data.buffer.Length);
            CMsg sendMessage = new CMsg((int)send_streams.Length);    //添加消息头部
            sendMessage.SetProtocalID(MsgID);
            sendMessage.Add(send_streams.ToArray(), 0, (int)send_streams.Length);
            //发送消息的最重要的代码,将网络数据流发送到指定服务器流中
            client.GetStream().Write(sendMessage.GetMsgBuffer(), 0, (int)sendMessage.GetMsgSize());
        }
    }
Ejemplo n.º 47
0
 private void m_Camera_OnFrameCaptrue(Bitmap bitmap)
 {
     System.Windows.Media.Imaging.BitmapImage m_Frame = new System.Windows.Media.Imaging.BitmapImage();
     using (var stream = new System.IO.MemoryStream())
     {
         bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
         stream.Seek(0, System.IO.SeekOrigin.Begin);
         m_Frame.BeginInit();
         m_Frame.CacheOption  = System.Windows.Media.Imaging.BitmapCacheOption.OnLoad;
         m_Frame.StreamSource = stream;
         m_Frame.EndInit();
         stream.SetLength(0);
         stream.Capacity = 0;
         stream.Dispose();
     }
     m_Frame.Freeze();
     m_ControlWindow.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.SystemIdle, m_Refresh, m_Frame);
 }
Ejemplo n.º 48
0
    protected virtual void OnButtonClearReceiveAreaClicked(object sender, System.EventArgs e)
    {
//				textviewText.Buffer.Clear ();
//				textviewHex.Buffer.Clear ();
//				textviewDec.Buffer.Clear ();

        moverText.Clear();
        moverHex.Clear();
        moverDec.Clear();

        ReceiveStream.SetLength(0);
        labelRx.Text = ReceiveStream.Length.ToString();
//				textviewTextString = "";
//				textviewHexString = "";
//				textviewDecString = "";
//
//				textviewHexOffset = 0;
//				textviewTextOffset = 0;
//				textviewDecOffset = 0;
    }
Ejemplo n.º 49
0
        /// <summary>
        /// MD5加密字符串
        /// </summary>
        /// <param name="sourceStr">要加密的字符串</param>
        /// <returns>MD5加密后的字符串</returns>
        public static string MD5(string sourceStr)
        {
            string sRet = string.Empty;

            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5CryptoServiceProvider.Create();
            byte[] btRet;
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            System.IO.StreamWriter sw = new System.IO.StreamWriter(ms);
            System.IO.StreamReader sr = new System.IO.StreamReader(ms);

            if (sourceStr == null)
            {
                sourceStr = string.Empty;
            }

            sw.Write(sourceStr);
            sw.Flush();
            ms.Seek(0, System.IO.SeekOrigin.Begin);

            btRet = md5.ComputeHash(ms);
            ms.SetLength(0);
            sw.Flush();

            for (int i = 0; i < btRet.Length; i++)
            {
                sw.Write("{0:X2}", btRet[i]);
            }
            sw.Flush();
            ms.Seek(0, System.IO.SeekOrigin.Begin);
            sRet = sr.ReadToEnd();

            sw.Close();
            sw.Dispose();
            sr.Close();
            sr.Dispose();
            ms.Close();
            ms.Dispose();

            return(sRet);
        }
Ejemplo n.º 50
0
 private byte[] packFrame(int cmdGlobalCipher, byte[] payload)
 {
     try
     {
         if (parameters.securityType != SecurityType.NONE)
         {
             System.IO.MemoryStream stream = new System.IO.MemoryStream();
             byte[] data = Security.authenticatedEncryption(parameters, payload);
             stream.SetLength(0);
             stream.WriteByte((byte)cmdGlobalCipher);
             //Array.Reverse(getSizeBytes(data.Length));
             stream.Write(getSizeBytes(data.Length), 0, getSizeBytes(data.Length).Length);
             //Array.Reverse(data);
             stream.Write(data, 0, data.Length);
             return(stream.ToArray());
         }
         return(payload);
     }
     catch (IOException)
     {
         throw new DlmsException(DlmsException.DlmsExceptionReason.INTERNAL_ERROR);
     }
 }
Ejemplo n.º 51
0
    public static byte[] YahooCrypt(string key, string salt)
    {
        const string md5SaltPrefix = "$1$";

        byte[] byteSaltPrefix = ASCIIEncoding.ASCII.GetBytes(md5SaltPrefix);
        byte[] byteKey        = ASCIIEncoding.ASCII.GetBytes(key);
        byte[] byteSalt       = ASCIIEncoding.ASCII.GetBytes(salt);

        // create a memory stream for the result
        IO.MemoryStream result = new IO.MemoryStream();

        result.Write(byteKey, 0, byteKey.Length);
        result.Write(byteSaltPrefix, 0, byteSaltPrefix.Length);
        result.Write(byteSalt, 0, byteSalt.Length);

        // create an alternate string for encyption
        IO.MemoryStream altResult = new IO.MemoryStream();

        altResult.Write(byteKey, 0, byteKey.Length);
        altResult.Write(byteSalt, 0, byteSalt.Length);
        altResult.Write(byteKey, 0, byteKey.Length);

        // encrypt alternate result
        Crypto.MD5CryptoServiceProvider md5 = new Crypto.MD5CryptoServiceProvider();
        byte[] altResultHash = md5.ComputeHash(altResult.ToArray());

        // Add for any character in the key one byte of the alternate sum.
        int cnt;

        for (cnt = byteKey.Length; cnt > 16; cnt -= 16)
        {
            result.Write(altResultHash, 0, 16);
        }
        result.Write(altResultHash, 0, cnt);

        /* For the following code we need a NUL byte.  */
        altResultHash[0] = 0;

        /* The original implementation now does something weird: for every 1
         *       bit in the key the first 0 is added to the buffer, for every 0
         *       bit the first character of the key.  This does not seem to be
         *       what was intended but we have to follow this to be compatible.  */
        for (cnt = key.Length; cnt > 0; cnt >>= 1)
        {
            result.Write(((cnt & 1) != 0 ? altResultHash : byteKey), 0, 1);
        }

        // create intermediate result
        altResultHash = md5.ComputeHash(result.ToArray());

        /* Now comes another weirdness.  In fear of password crackers here
         *       comes a quite long loop which just processes the output of the
         *       previous round again.  We cannot ignore this here.  */
        for (cnt = 0; cnt < 1000; ++cnt)
        {
            result.Seek(0, IO.SeekOrigin.Begin);
            result.SetLength(0);

            /* Add key or last result.  */
            if ((cnt & 1) != 0)
            {
                result.Write(byteKey, 0, byteKey.Length);
            }
            else
            {
                result.Write(altResultHash, 0, 16);
            }

            /* Add salt for numbers not divisible by 3.  */
            if (cnt % 3 != 0)
            {
                result.Write(byteSalt, 0, byteSalt.Length);
            }

            /* Add key for numbers not divisible by 7.  */
            if (cnt % 7 != 0)
            {
                result.Write(byteKey, 0, byteKey.Length);
            }

            /* Add key or last result.  */
            if ((cnt & 1) != 0)
            {
                result.Write(altResultHash, 0, 16);
            }
            else
            {
                result.Write(byteKey, 0, byteKey.Length);
            }

            /* Create intermediate result.  */
            altResultHash = md5.ComputeHash(result.ToArray());
        }

        /* Now we can construct the result string.  It consists of three
         *               parts.  */

        // start with the salt prefix
        IO.MemoryStream finalResult = new IO.MemoryStream();

        finalResult.Write(byteSaltPrefix, 0, byteSaltPrefix.Length);
        finalResult.Write(byteSalt, 0, byteSalt.Length);
        finalResult.WriteByte((byte)'$');

        b64_from_24bit(altResultHash[0], altResultHash[6], altResultHash[12], 4, finalResult);
        b64_from_24bit(altResultHash[1], altResultHash[7], altResultHash[13], 4, finalResult);
        b64_from_24bit(altResultHash[2], altResultHash[8], altResultHash[14], 4, finalResult);
        b64_from_24bit(altResultHash[3], altResultHash[9], altResultHash[15], 4, finalResult);
        b64_from_24bit(altResultHash[4], altResultHash[10], altResultHash[5], 4, finalResult);
        b64_from_24bit(0, 0, altResultHash[11], 2, finalResult);

        result.Close();
        altResult.Close();

        byte[] done = finalResult.ToArray();

        finalResult.Close();

        return(done);
    }
Ejemplo n.º 52
0
        /// <summary> This method writes the new codestream to the file.
        ///
        /// </summary>
        /// <param name="fi">The file to write the new codestream to
        ///
        /// </param>
        /// <exception cref="IOException">If an I/O error ocurred.
        ///
        /// </exception>
        private void  writeNewCodestream(BufferedRandomAccessFile fi)
        {
            int t, p, tp;             // i removed
            int numTiles = tileParts.Length;

            int[][] packetHeaderLengths = new int[numTiles][];
            for (int i2 = 0; i2 < numTiles; i2++)
            {
                packetHeaderLengths[i2] = new int[maxtp];
            }
            byte[] temp;
            int    length;

            // Write main header up to SOT marker
            fi.write(mainHeader, 0, mainHeader.Length);

            // If PPM used write all packet headers in PPM markers
            if (ppmUsed)
            {
                System.IO.MemoryStream ppmMarkerSegment = new System.IO.MemoryStream();
                int   numPackets;
                int   totNumPackets;
                int   ppmIndex = 0;
                int   ppmLength;
                int   pStart, pStop;
                int[] prem = new int[numTiles];

                // Set number of remaining packets
                for (t = 0; t < numTiles; t++)
                {
                    prem[t] = packetHeaders[t].Length;
                }

                // Calculate Nppm values
                for (tp = 0; tp < maxtp; tp++)
                {
                    for (t = 0; t < numTiles; t++)
                    {
                        if (tileParts[t].Length > tp)
                        {
                            totNumPackets = packetHeaders[t].Length;
                            // Calculate number of packets in this tilepart
                            numPackets = (tp == tileParts[t].Length - 1)?prem[t]:pptp;

                            pStart = totNumPackets - prem[t];
                            pStop  = pStart + numPackets;

                            // Calculate number of packet header bytes for this
                            // tile part
                            for (p = pStart; p < pStop; p++)
                            {
                                packetHeaderLengths[t][tp] += packetHeaders[t][p].Length;
                            }

                            prem[t] -= numPackets;
                        }
                    }
                }

                // Write first PPM marker
                ppmMarkerSegment.WriteByte((System.Byte)SupportClass.URShift(CSJ2K.j2k.codestream.Markers.PPM, 8));
                ppmMarkerSegment.WriteByte((System.Byte)(CSJ2K.j2k.codestream.Markers.PPM & 0x00FF));
                ppmMarkerSegment.WriteByte((System.Byte) 0);                 // Temporary Lppm value
                ppmMarkerSegment.WriteByte((System.Byte) 0);                 // Temporary Lppm value
                ppmMarkerSegment.WriteByte((System.Byte) 0);                 // zppm
                ppmLength = 3;
                ppmIndex++;

                // Set number of remaining packets
                for (t = 0; t < numTiles; t++)
                {
                    prem[t] = packetHeaders[t].Length;
                }

                // Write all PPM markers and information
                for (tp = 0; tp < maxtp; tp++)
                {
                    for (t = 0; t < numTiles; t++)
                    {
                        if (tileParts[t].Length > tp)
                        {
                            totNumPackets = packetHeaders[t].Length;

                            // Calculate number of packets in this tilepart
                            numPackets = (tp == tileParts[t].Length - 1)?prem[t]:pptp;

                            pStart = totNumPackets - prem[t];
                            pStop  = pStart + numPackets;

                            // If Nppm value wont fit in current PPM marker segment
                            // write current PPM marker segment and start new
                            if (ppmLength + 4 > CSJ2K.j2k.codestream.Markers.MAX_LPPM)
                            {
                                // Write current PPM marker
                                temp    = ppmMarkerSegment.ToArray();
                                length  = temp.Length - 2;
                                temp[2] = (byte)(SupportClass.URShift(length, 8));
                                temp[3] = (byte)length;
                                fi.write(temp, 0, length + 2);

                                // Start new PPM marker segment
                                //UPGRADE_ISSUE: Method 'java.io.ByteArrayOutputStream.reset' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaioByteArrayOutputStreamreset'"
                                //ppmMarkerSegment.reset();
                                ppmMarkerSegment.SetLength(0);
                                ppmMarkerSegment.WriteByte((System.Byte)SupportClass.URShift(CSJ2K.j2k.codestream.Markers.PPM, 8));
                                ppmMarkerSegment.WriteByte((System.Byte)(CSJ2K.j2k.codestream.Markers.PPM & 0x00FF));
                                ppmMarkerSegment.WriteByte((System.Byte) 0);                                 // Temporary Lppm value
                                ppmMarkerSegment.WriteByte((System.Byte) 0);                                 // Temporary Lppm value
                                ppmMarkerSegment.WriteByte((System.Byte)ppmIndex++);                         // zppm
                                ppmLength = 3;
                            }

                            // Write Nppm value
                            length = packetHeaderLengths[t][tp];
                            ppmMarkerSegment.WriteByte((System.Byte)SupportClass.URShift(length, 24));
                            ppmMarkerSegment.WriteByte((System.Byte)SupportClass.URShift(length, 16));
                            ppmMarkerSegment.WriteByte((System.Byte)SupportClass.URShift(length, 8));
                            ppmMarkerSegment.WriteByte((System.Byte)length);
                            ppmLength += 4;

                            // Write packet headers
                            for (p = pStart; p < pStop; p++)
                            {
                                length = packetHeaders[t][p].Length;

                                // If next packet header value wont fit in
                                // current PPM marker segment write current PPM
                                // marker segment and start new
                                if (ppmLength + length > CSJ2K.j2k.codestream.Markers.MAX_LPPM)
                                {
                                    // Write current PPM marker
                                    temp    = ppmMarkerSegment.ToArray();
                                    length  = temp.Length - 2;
                                    temp[2] = (byte)(SupportClass.URShift(length, 8));
                                    temp[3] = (byte)length;
                                    fi.write(temp, 0, length + 2);

                                    // Start new PPM marker segment
                                    //UPGRADE_ISSUE: Method 'java.io.ByteArrayOutputStream.reset' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaioByteArrayOutputStreamreset'"
                                    //ppmMarkerSegment.reset();
                                    ppmMarkerSegment.SetLength(0);
                                    ppmMarkerSegment.WriteByte((System.Byte)SupportClass.URShift(CSJ2K.j2k.codestream.Markers.PPM, 8));
                                    ppmMarkerSegment.WriteByte((System.Byte)(CSJ2K.j2k.codestream.Markers.PPM & 0x00FF));
                                    ppmMarkerSegment.WriteByte((System.Byte) 0);                                     // Temp Lppm value
                                    ppmMarkerSegment.WriteByte((System.Byte) 0);                                     // Temp Lppm value
                                    ppmMarkerSegment.WriteByte((System.Byte)ppmIndex++);                             // zppm
                                    ppmLength = 3;
                                }

                                // write packet header
                                ppmMarkerSegment.Write(packetHeaders[t][p], 0, packetHeaders[t][p].Length);
                                ppmLength += packetHeaders[t][p].Length;
                            }
                            prem[t] -= numPackets;
                        }
                    }
                }
                // Write last PPM marker segment
                temp    = ppmMarkerSegment.ToArray();
                length  = temp.Length - 2;
                temp[2] = (byte)(SupportClass.URShift(length, 8));
                temp[3] = (byte)length;
                fi.write(temp, 0, length + 2);
            }

            // Write tile parts interleaved
            for (tp = 0; tp < maxtp; tp++)
            {
                for (t = 0; t < nt; t++)
                {
                    if (tileParts[t].Length > tp)
                    {
                        temp   = tileParts[t][tp];
                        length = temp.Length;
                        fi.write(temp, 0, length);
                    }
                }
            }
            fi.writeShort(CSJ2K.j2k.codestream.Markers.EOC);
        }
Ejemplo n.º 53
0
        /// <summary> This method creates the tileparts from the buffered tile headers,
        /// packet headers and packet data
        ///
        /// </summary>
        /// <exception cref="IOException">If an I/O error ocurred.
        ///
        /// </exception>
        private void  createTileParts()
        {
            int i, prem, t, length;
            int pIndex;             // phIndex removed
            int tppStart;
            int tilePart;
            int p, np, nomnp;
            int numTileParts;
            int numPackets;

            System.IO.MemoryStream temp = new System.IO.MemoryStream();
            byte[] tempByteArr;

            // Create tile parts
            tileParts = new byte[nt][][];
            maxtp     = 0;

            for (t = 0; t < nt; t++)
            {
                // Calculate number of tile parts. If tileparts are not used,
                // put all packets in the first tilepart
                if (pptp == 0)
                {
                    pptp = ppt[t];
                }
                prem = ppt[t];
                //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
                numTileParts = (int)System.Math.Ceiling(((double)prem) / pptp);
                numPackets   = packetHeaders[t].Length;
                maxtp        = (numTileParts > maxtp)?numTileParts:maxtp;
                tileParts[t] = new byte[numTileParts][];

                // Create all the tile parts for tile t
                tppStart = 0;
                pIndex   = 0;
                p        = 0;
                //phIndex = 0;

                for (tilePart = 0; tilePart < numTileParts; tilePart++)
                {
                    // Calculate number of packets in this tilepart
                    nomnp = (pptp > prem)?prem:pptp;
                    np    = nomnp;

                    // Write tile part header
                    if (tilePart == 0)
                    {
                        // Write original tile part header up to SOD marker
                        temp.Write(tileHeaders[t], 0, tileHeaders[t].Length - 2);
                    }
                    else
                    {
                        // Write empty header of length TP_HEAD_LEN-2
                        temp.Write(new byte[TP_HEAD_LEN - 2], 0, TP_HEAD_LEN - 2);
                    }

                    // Write PPT marker segments if PPT used
                    if (pptUsed)
                    {
                        int pptLength = 3;                         // Zppt and Lppt
                        int pptIndex  = 0;
                        int phLength;

                        p = pIndex;
                        while (np > 0)
                        {
                            phLength = packetHeaders[t][p].Length;

                            // If the total legth of the packet headers is greater
                            // than MAX_LPPT, several PPT markers are needed
                            if (pptLength + phLength > CSJ2K.j2k.codestream.Markers.MAX_LPPT)
                            {
                                temp.WriteByte((System.Byte)SupportClass.URShift(CSJ2K.j2k.codestream.Markers.PPT, 8));
                                temp.WriteByte((System.Byte)(CSJ2K.j2k.codestream.Markers.PPT & 0x00FF));
                                temp.WriteByte((System.Byte)SupportClass.URShift(pptLength, 8));
                                temp.WriteByte((System.Byte)pptLength);
                                temp.WriteByte((System.Byte)pptIndex++);
                                for (i = pIndex; i < p; i++)
                                {
                                    temp.Write(packetHeaders[t][i], 0, packetHeaders[t][i].Length);
                                }
                                pptLength = 3;                                 // Zppt and Lppt
                                pIndex    = p;
                            }
                            pptLength += phLength;
                            p++;
                            np--;
                        }
                        // Write last PPT marker
                        temp.WriteByte((System.Byte)SupportClass.URShift(CSJ2K.j2k.codestream.Markers.PPT, 8));
                        temp.WriteByte((System.Byte)(CSJ2K.j2k.codestream.Markers.PPT & 0x00FF));
                        temp.WriteByte((System.Byte)SupportClass.URShift(pptLength, 8));
                        temp.WriteByte((System.Byte)pptLength);
                        temp.WriteByte((System.Byte)pptIndex);
                        for (i = pIndex; i < p; i++)
                        {
                            temp.Write(packetHeaders[t][i], 0, packetHeaders[t][i].Length);
                        }
                    }
                    pIndex = p;
                    np     = nomnp;

                    // Write SOD marker
                    temp.WriteByte((System.Byte)SupportClass.URShift(CSJ2K.j2k.codestream.Markers.SOD, 8));
                    temp.WriteByte((System.Byte)(CSJ2K.j2k.codestream.Markers.SOD & 0x00FF));

                    // Write packet data and packet headers if PPT and PPM not used
                    for (p = tppStart; p < tppStart + np; p++)
                    {
                        if (!tempSop)
                        {
                            temp.Write(sopMarkSeg[t][p], 0, CSJ2K.j2k.codestream.Markers.SOP_LENGTH);
                        }

                        if (!(ppmUsed || pptUsed))
                        {
                            temp.Write(packetHeaders[t][p], 0, packetHeaders[t][p].Length);
                        }

                        temp.Write(packetData[t][p], 0, packetData[t][p].Length);
                    }
                    tppStart += np;

                    // Edit tile part header
                    tempByteArr            = temp.ToArray();
                    tileParts[t][tilePart] = tempByteArr;
                    length = (int)temp.Length;

                    if (tilePart == 0)
                    {
                        // Edit first tile part header
                        tempByteArr[6]  = (byte)(SupportClass.URShift(length, 24));                         // Psot
                        tempByteArr[7]  = (byte)(SupportClass.URShift(length, 16));
                        tempByteArr[8]  = (byte)(SupportClass.URShift(length, 8));
                        tempByteArr[9]  = (byte)(length);
                        tempByteArr[10] = (byte)SupportClass.Identity((0));              // TPsot
                        tempByteArr[11] = (byte)(numTileParts);                          // TNsot
                    }
                    else
                    {
                        // Edit tile part header
                        tempByteArr[0]  = (byte)(SupportClass.URShift(CSJ2K.j2k.codestream.Markers.SOT, 8)); // SOT
                        tempByteArr[1]  = (byte)(CSJ2K.j2k.codestream.Markers.SOT & 0x00FF);
                        tempByteArr[2]  = (byte)SupportClass.Identity((0));                                  // Lsot
                        tempByteArr[3]  = (byte)SupportClass.Identity((10));
                        tempByteArr[4]  = (byte)(SupportClass.URShift(t, 8));                                // Isot
                        tempByteArr[5]  = (byte)(t);                                                         //
                        tempByteArr[6]  = (byte)(SupportClass.URShift(length, 24));                          // Psot
                        tempByteArr[7]  = (byte)(SupportClass.URShift(length, 16));
                        tempByteArr[8]  = (byte)(SupportClass.URShift(length, 8));
                        tempByteArr[9]  = (byte)(length);
                        tempByteArr[10] = (byte)(tilePart);                          //TPsot
                        tempByteArr[11] = (byte)(numTileParts);                      // TNsot
                    }
                    //UPGRADE_ISSUE: Method 'java.io.ByteArrayOutputStream.reset' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaioByteArrayOutputStreamreset'"
                    //temp.reset();
                    temp.SetLength(0);
                    prem -= np;
                }
            }
            temp.Dispose();
        }
Ejemplo n.º 54
0
        /// <summary>
        /// This method just downloads the firmware file blocks to the device for a
        /// given range of blocks.  Use 1-based indexing for blocks.
        /// </summary>
        /// <param name="path">Complete path to the firmware file</param>
        /// <param name="usStartBlock">The first block to download.</param>
        /// <param name="usEndBlock">The last block to download.</param>
        /// <returns>FWDownloadResult</returns>
        // Revision History
        // MM/DD/YY who Version Issue# Description
        // -------- --- ------- ------ ---------------------------------------
        // 11/15/13 AF  3.50.03	       Class re-architecture - Cloned from CENTRON_AMI
        // 01/06/14 DLG 3.50.19        Class re-architecture - Moved from ICS_Gateway to
        //                             CommonFirmwareDownload.
        // 02/07/14 jrf 3.50.32 419257 Modified to use a dynamic FWDL block size based on the negotiated
        //                             PSEM packet size.
        //
        public FWDownloadResult DownloadFWBlocks(string path, ushort usStartBlock, ushort usEndBlock)
        {
            FWDownloadResult Result           = FWDownloadResult.SUCCESS;
            PSEMResponse     ProtocolResponse = PSEMResponse.Ok;
            byte             byEventNumber    = 0;
            ushort           idTable          = (ushort)CANSIDevice.FWDLTableIds.CommModuleFWTbl | CANSIDevice.PENDING_BIT;
            ushort           usNumberChunks   = 0;
            ushort           usIndex;

            System.IO.FileStream   streamFile;
            System.IO.MemoryStream streamHeader = new System.IO.MemoryStream();
            System.IO.MemoryStream streamPSEM   = new System.IO.MemoryStream();

            try
            {
                streamFile = new System.IO.FileStream(path, System.IO.FileMode.Open, FileAccess.Read);
                byte[] bybuffer = new byte[streamFile.Length];

                streamFile.Read(bybuffer, 0, (int)streamFile.Length);
                streamFile.Position = 0;

                switch (bybuffer[9])
                {
                case (byte)FirmwareType.ICSFW:
                {
                    byEventNumber = CANSIDevice.COMM_EVENT_NUMBER;
                    idTable       = (ushort)CANSIDevice.FWDLTableIds.CommModuleFWTbl | CANSIDevice.PENDING_BIT;
                    break;
                }

                default:
                {
                    throw new NotImplementedException("Table not yet supported");
                }
                }

                m_ANSIDevice.BuildPendingHeader(ref streamHeader, false, false,
                                                byEventNumber, PendingEventRecord.PendingEventCode.NonTimeTrigger);

                usNumberChunks = (ushort)(streamFile.Length / m_ANSIDevice.FWDLBlockSize);

                if (streamFile.Length != m_ANSIDevice.FWDLBlockSize * usNumberChunks)
                {
                    usNumberChunks++;
                }

                m_ANSIDevice.OnShowProgress(new ShowProgressEventArgs(1, usNumberChunks + 1,
                                                                      "Firmware Download",
                                                                      "Downloading..."));

                ushort usSendSize = m_ANSIDevice.FWDLBlockSize;

                //Make sure the start block is not less than 1
                if (usStartBlock < 1)
                {
                    usStartBlock = 1;
                }
                //Make sure the end block is not greater than the actual number of FW blocks.
                if (usEndBlock > usNumberChunks)
                {
                    usEndBlock = usNumberChunks;
                }

                for (usIndex = (ushort)(usStartBlock - 1);
                     (usIndex < usEndBlock) && (PSEMResponse.Ok == ProtocolResponse);
                     usIndex++)
                {
                    // The last chunk could be smaller
                    if (usNumberChunks - 1 == usIndex)
                    {
                        usSendSize = (ushort)(streamFile.Length % m_ANSIDevice.FWDLBlockSize);
                        // If no remainder then it is a full packet
                        if (0 == usSendSize)
                        {
                            usSendSize = m_ANSIDevice.FWDLBlockSize;
                        }
                    }

                    streamHeader.Position = 0;
                    streamPSEM.Position   = 0;
                    streamPSEM.SetLength(0);
                    streamHeader.WriteTo(streamPSEM);
                    streamPSEM.Write(bybuffer, usIndex * m_ANSIDevice.FWDLBlockSize, usSendSize);

                    ProtocolResponse = m_PSEM.OffsetWrite((ushort)idTable,
                                                          usIndex * m_ANSIDevice.FWDLBlockSize,
                                                          streamPSEM.ToArray());
                    m_ANSIDevice.OnStepProgress(new ProgressEventArgs());
                }

                // Translate Protocol result
                Result = TranslateProtocolResult(ProtocolResponse);

                streamFile.Close();

                m_ANSIDevice.OnHideProgress(new EventArgs());
            }

            catch (Exception e)
            {
                // Log it and pass it up
                m_ANSIDevice.OnHideProgress(new EventArgs());
                m_Logger.WriteException(this, e);
                throw e;
            }

            return(Result);
        }
Ejemplo n.º 55
0
        public FWDownloadResult DownloadFW(string path, ref ushort usBlockIndex, bool blnRetry = false, bool blnActivate = true)
        {
            FWDownloadResult     Result           = FWDownloadResult.UNKNOWN_DRIVER_ERROR;
            ProcedureResultCodes ProcResult       = ProcedureResultCodes.INVALID_PARAM;
            PSEMResponse         ProtocolResponse = PSEMResponse.Ok;
            byte   byEventNumber  = 0;
            ushort idTable        = (ushort)CANSIDevice.FWDLTableIds.CommModuleFWTbl | CANSIDevice.PENDING_BIT;
            ushort usNumberChunks = 0;
            //A non-zero starting block means we are need to pick up were we left off.
            bool blnResumeFWDL = (0 != usBlockIndex);

            System.IO.FileStream   streamFile;
            System.IO.MemoryStream streamHeader = new System.IO.MemoryStream();
            System.IO.MemoryStream streamPSEM   = new System.IO.MemoryStream();

            try
            {
                if (true == blnResumeFWDL)
                {
                    Result = FWDownloadResult.SUCCESS;

                    m_Logger.WriteLine(Logger.LoggingLevel.Functional,
                                       "Resuming Firmware Download @ Block " + usBlockIndex.ToString());
                }
                else
                {
                    // Tell the meter to enter firmware download mode
                    Result = EnterFirmwareDownloadMode(path);
                }

                if (FWDownloadResult.SUCCESS != Result)
                {
                    m_Logger.WriteLine(Logger.LoggingLevel.Detailed,
                                       "Initiate F/W Download procedure failed with result = "
                                       + Result);
                }
                else
                {
                    // Meter is ready to receive the firmware file
                    streamFile = new System.IO.FileStream(path, System.IO.FileMode.Open, FileAccess.Read);
                    byte[] bybuffer = new byte[streamFile.Length];

                    streamFile.Read(bybuffer, 0, (int)streamFile.Length);
                    streamFile.Position = 0;

                    switch (bybuffer[9])
                    {
                    case (byte)FirmwareType.ICSFW:
                    {
                        byEventNumber = CANSIDevice.COMM_EVENT_NUMBER;
                        idTable       = (ushort)CANSIDevice.FWDLTableIds.CommModuleFWTbl | CANSIDevice.PENDING_BIT;
                        break;
                    }

                    default:
                    {
                        throw new NotImplementedException("Table not supported");
                    }
                    }

                    m_ANSIDevice.BuildPendingHeader(ref streamHeader, false, false,
                                                    byEventNumber, PendingEventRecord.PendingEventCode.NonTimeTrigger);

                    usNumberChunks = (ushort)(streamFile.Length / m_ANSIDevice.FWDLBlockSize);

                    if (streamFile.Length != m_ANSIDevice.FWDLBlockSize * usNumberChunks)
                    {
                        usNumberChunks++;
                    }

                    m_ANSIDevice.OnShowProgress(new ShowProgressEventArgs(1, usNumberChunks + 1,
                                                                          "Firmware Download",
                                                                          "Downloading..."));

                    ushort usSendSize = m_ANSIDevice.FWDLBlockSize;

                    for (;
                         (usBlockIndex < usNumberChunks) && (PSEMResponse.Ok == ProtocolResponse);
                         usBlockIndex++)
                    {
                        // The last chunk could be smaller
                        if (usNumberChunks - 1 == usBlockIndex)
                        {
                            usSendSize = (ushort)(streamFile.Length % m_ANSIDevice.FWDLBlockSize);
                            // If no remainder then it is a full packet
                            if (0 == usSendSize)
                            {
                                usSendSize = m_ANSIDevice.FWDLBlockSize;
                            }
                        }

                        m_Logger.WriteLine(Logger.LoggingLevel.Functional,
                                           "Firmware Download - Sending Block " + usBlockIndex.ToString());

                        streamHeader.Position = 0;
                        streamPSEM.Position   = 0;
                        streamPSEM.SetLength(0);
                        streamHeader.WriteTo(streamPSEM);
                        streamPSEM.Write(bybuffer, usBlockIndex * m_ANSIDevice.FWDLBlockSize, usSendSize);

                        ProtocolResponse = m_PSEM.OffsetWrite((ushort)idTable,
                                                              usBlockIndex * m_ANSIDevice.FWDLBlockSize,
                                                              streamPSEM.ToArray());
                        m_ANSIDevice.OnStepProgress(new ProgressEventArgs());
                    }

                    // Translate Protocol result
                    Result = TranslateProtocolResult(ProtocolResponse);

                    streamFile.Close();

                    //Check on success and then activate the table
                    if (PSEMResponse.Ok == ProtocolResponse)
                    {
                        ProcResult = ProcedureResultCodes.COMPLETED;

                        if (ProcResult == ProcedureResultCodes.COMPLETED)
                        {
                            if (true == blnActivate)
                            {
                                m_Logger.WriteLine(Logger.LoggingLevel.Functional,
                                                   "Activating Firmware Download");

                                // Activate the pending table using mfg proc 69
                                ProcResult = m_ANSIDevice.ActivateFWDLTable(idTable, (byte)FirmwareType.ICSFW, bybuffer[5], bybuffer[6], bybuffer[7], bybuffer[8]);

                                Result = TranslateProcedureResult(ProcResult);
                            }
                        }
                        else
                        {
                            //TODO - not sure this is the correct error
                            Result = FWDownloadResult.SECURITY_ERROR;
                        }

                        m_ANSIDevice.OnStepProgress(new ProgressEventArgs());
                    }
                    else //PSEMResponse.Ok != ProtocolResponse
                    {
                        //Decrement the block index so we make sure we restart on the block that we failed on.
                        usBlockIndex--;

                        Result = FWDownloadResult.WRITE_ERROR;
                    }
                    m_ANSIDevice.OnHideProgress(new EventArgs());
                }
            }

            catch (Exception e)
            {
                m_Logger.WriteException(this, e);

                if (false == blnRetry)
                {
                    // Log it and pass it up
                    m_ANSIDevice.OnHideProgress(new EventArgs());

                    throw e;
                }
                else
                {
                    Result = FWDownloadResult.WRITE_ERROR;
                }
            }

            return(Result);
        }
Ejemplo n.º 56
0
        /// <summary>
        /// Downloads the firmware file to the device but does NOT
        /// activate.  On download failure, the pending table is cleared.
        /// </summary>
        /// <param name="path">Complete path to the firmware file</param>
        /// <param name="eventCode">event code activation method</param>
        /// <returns>FWDownloadResult</returns>
        // Revision History
        // MM/DD/YY who Version Issue# Description
        // -------- --- ------- ------ ---------------------------------------
        // 11/15/13 AF  3.50.03	       Class re-architecture - Cloned from CENTRON_AMI
        // 01/06/14 DLG 3.50.19        Class re-architecture - Moved from ICS_Gateway to
        //                             CommonFirmwareDownload.
        // 02/07/14 jrf 3.50.32 419257 Modified to use a dynamic FWDL block size based on the negotiated
        //                             PSEM packet size.
        //
        public FWDownloadResult DownloadFWNoActivate(string path, PendingEventRecord.PendingEventCode eventCode)
        {
            FWDownloadResult Result           = FWDownloadResult.UNKNOWN_DRIVER_ERROR;
            PSEMResponse     ProtocolResponse = PSEMResponse.Ok;
            byte             byEventNumber    = 0;
            ushort           idTable          = (ushort)CANSIDevice.FWDLTableIds.RegisterFWTbl | CANSIDevice.PENDING_BIT;
            ushort           usNumberChunks   = 0;
            ushort           intIndex;

            System.IO.FileStream   streamFile;
            System.IO.MemoryStream streamHeader = new System.IO.MemoryStream();
            System.IO.MemoryStream streamPSEM   = new System.IO.MemoryStream();

            try
            {
                Result = EnterFirmwareDownloadMode(path);

                if (FWDownloadResult.SUCCESS != Result)
                {
                    m_Logger.WriteLine(Logger.LoggingLevel.Detailed,
                                       "Initiate F/W Download procedure failed with result = "
                                       + Result);
                }
                else
                {
                    // Meter is ready to receive the firmware file
                    streamFile = new System.IO.FileStream(path, System.IO.FileMode.Open, FileAccess.Read);
                    byte[] bybuffer = new byte[streamFile.Length];

                    streamFile.Read(bybuffer, 0, (int)streamFile.Length);
                    streamFile.Position = 0;

                    switch (bybuffer[9])
                    {
                    case (byte)FirmwareType.ICSFW:
                    {
                        byEventNumber = CANSIDevice.COMM_EVENT_NUMBER;
                        idTable       = (ushort)CANSIDevice.FWDLTableIds.CommModuleFWTbl | CANSIDevice.PENDING_BIT;
                        break;
                    }

                    default:
                    {
                        throw new NotImplementedException("Table not yet supported");
                    }
                    }

                    m_ANSIDevice.BuildPendingHeader(ref streamHeader, false, false, byEventNumber, eventCode);

                    usNumberChunks = (ushort)(streamFile.Length / m_ANSIDevice.FWDLBlockSize);

                    if (streamFile.Length != m_ANSIDevice.FWDLBlockSize * usNumberChunks)
                    {
                        usNumberChunks++;
                    }

                    m_ANSIDevice.OnShowProgress(new ShowProgressEventArgs(1, usNumberChunks + 1,
                                                                          "Firmware Download",
                                                                          "Downloading..."));

                    ushort usSendSize = m_ANSIDevice.FWDLBlockSize;

                    for (intIndex = 0;
                         (intIndex < usNumberChunks) && (PSEMResponse.Ok == ProtocolResponse);
                         intIndex++)
                    {
                        // The last chunk could be smaller
                        if (usNumberChunks - 1 == intIndex)
                        {
                            usSendSize = (ushort)(streamFile.Length % m_ANSIDevice.FWDLBlockSize);
                            // If no remainder then it is a full packet
                            if (0 == usSendSize)
                            {
                                usSendSize = m_ANSIDevice.FWDLBlockSize;
                            }
                        }

                        streamHeader.Position = 0;
                        streamPSEM.Position   = 0;
                        streamPSEM.SetLength(0);
                        streamHeader.WriteTo(streamPSEM);
                        streamPSEM.Write(bybuffer, intIndex * m_ANSIDevice.FWDLBlockSize, usSendSize);

                        ProtocolResponse = m_PSEM.OffsetWrite((ushort)idTable,
                                                              intIndex * m_ANSIDevice.FWDLBlockSize,
                                                              streamPSEM.ToArray());
                        m_ANSIDevice.OnStepProgress(new ProgressEventArgs());
                    }

                    // Translate Protocol result
                    Result = TranslateProtocolResult(ProtocolResponse);

                    streamFile.Close();

                    // If any write failed, give up and clear the pending table
                    if (PSEMResponse.Ok != ProtocolResponse)
                    {
                        Result = FWDownloadResult.WRITE_ERROR;
                    }
                    m_ANSIDevice.OnHideProgress(new EventArgs());
                }
            }

            catch (Exception e)
            {
                // Log it and pass it up
                m_ANSIDevice.OnHideProgress(new EventArgs());
                m_Logger.WriteException(this, e);
                throw e;
            }

            return(Result);
        }
Ejemplo n.º 57
0
        /// <summary>
        /// Downloads the firmware file to the meter and activates it.
        /// On download failure, the pending table is cleared.  The activation
        /// will cause the meter to drop the psem task so meter log off must
        /// follow this function call
        /// </summary>
        /// <param name="path">Complete file path of the firmware file</param>
        /// <returns>Itron.Metering.Device.FWDownloadResult</returns>
        // Revision History
        // MM/DD/YY who Version Issue# Description
        // -------- --- ------- ------ ---------------------------------------
        // 08/28/06 AF  7.35.00  N/A   Created
        // 09/15/06 AF  7.35.00  N/A   Added Catch for TimeOutException
        // 10/18/06 AF  7.40.00  N/A   Removed wait within the main loop
        // 05/13/08 AF  1.50.24        Removed IFirmwareDownload from the method name
        // 04/19/10 AF  2.40.39        Added M2 Gateway support
        // 08/18/11 AF  2.52.05        Added support for authentication using a hash code
        // 08/26/11 AF  2.52.08        Added support for Cisco f/w
        // 09/22/11 AF  2.52.21  N/A   Added support for Cisco config file f/w d/l - TODO remove when no longer needed
        // 10/12/11 AF  2.53.00        Changed the Cisco Comm fw enum name
        // 03/22/12 JJJ 2.60.xx        Added support for ChoiceConnect FW
        // 05/10/12 JJJ 2.60.xx        Tweaked FW Type passed to AuthenticateFWDL if ChoiceConnect, make RFLAN
        //
        public FWDownloadResult DownloadFW(string path)
        {
            FWDownloadResult     Result           = FWDownloadResult.UNKNOWN_DRIVER_ERROR;
            ProcedureResultCodes ProcResult       = ProcedureResultCodes.INVALID_PARAM;
            PSEMResponse         ProtocolResponse = PSEMResponse.Ok;
            byte   byEventNumber  = 0;
            ushort idTable        = (ushort)PendingTableIds.RegisterFWTbl | PENDING_BIT;
            ushort usNumberChunks = 0;
            ushort intIndex;

            System.IO.FileStream   streamFile;
            System.IO.MemoryStream streamHeader = new System.IO.MemoryStream();
            System.IO.MemoryStream streamPSEM   = new System.IO.MemoryStream();

            try
            {
                // Tell the meter to enter firmware download mode
                Result = EnterFirmwareDownloadMode(path);

                if (FWDownloadResult.SUCCESS != Result)
                {
                    m_Logger.WriteLine(Logger.LoggingLevel.Detailed,
                                       "Initiate F/W Download procedure failed with result = "
                                       + Result);
                }
                else
                {
                    // Meter is ready to receive the firmware file
                    streamFile = new System.IO.FileStream(path, System.IO.FileMode.Open, FileAccess.Read);
                    byte[] bybuffer = new byte[streamFile.Length];

                    streamFile.Read(bybuffer, 0, (int)streamFile.Length);
                    streamFile.Position = 0;

                    switch (bybuffer[9])
                    {
                    case (byte)FirmwareType.RegisterFW:
                    case (byte)FirmwareType.M2GTWY:
                    case (byte)FirmwareType.DisplayFW:
                    {
                        byEventNumber = REGISTER_EVENT_NUMBER;
                        idTable       = (ushort)PendingTableIds.RegisterFWTbl | PENDING_BIT;
                        break;
                    }

                    case (byte)FirmwareType.ZigbeeFW:
                    {
                        byEventNumber = ZIGBEE_EVENT_NUMBER;
                        idTable       = (ushort)PendingTableIds.HANModuleFWTbl | PENDING_BIT;
                        break;
                    }

                    case (byte)FirmwareType.RFLANFW:
                    case (byte)FirmwareType.PLANFW:
                    case (byte)FirmwareType.CiscoCommFW:
                    case (byte)FirmwareType.CiscoCfgFW:
                    case (byte)FirmwareType.ChoiceConnectFW:
                    {
                        byEventNumber = COMM_EVENT_NUMBER;
                        idTable       = (ushort)PendingTableIds.CommModuleFWTbl | PENDING_BIT;
                        break;
                    }

                    case (byte)FirmwareType.HANDevFW:
                    {
                        byEventNumber = HAN_DEV_EVENT_NUMBER;
                        idTable       = (ushort)PendingTableIds.HANDeviceFWTbl | PENDING_BIT;
                        break;
                    }

                    default:
                    {
                        throw new NotImplementedException("Table not supported");
                    }
                    }

                    BuildPendingHeader(ref streamHeader, false, false,
                                       byEventNumber, PendingEventRecord.PendingEventCode.NonTimeTrigger);

                    usNumberChunks = (ushort)(streamFile.Length / BLOCK_SIZE);

                    if (streamFile.Length != BLOCK_SIZE * usNumberChunks)
                    {
                        usNumberChunks++;
                    }

                    OnShowProgress(new ShowProgressEventArgs(1, usNumberChunks + 1,
                                                             "Firmware Download",
                                                             "Downloading..."));

                    ushort usSendSize = BLOCK_SIZE;

                    for (intIndex = 0;
                         (intIndex < usNumberChunks) && (PSEMResponse.Ok == ProtocolResponse);
                         intIndex++)
                    {
                        // The last chunk could be smaller
                        if (usNumberChunks - 1 == intIndex)
                        {
                            usSendSize = (ushort)(streamFile.Length % BLOCK_SIZE);
                            // If no remainder then it is a full packet
                            if (0 == usSendSize)
                            {
                                usSendSize = BLOCK_SIZE;
                            }
                        }

                        streamHeader.Position = 0;
                        streamPSEM.Position   = 0;
                        streamPSEM.SetLength(0);
                        streamHeader.WriteTo(streamPSEM);
                        streamPSEM.Write(bybuffer, intIndex * BLOCK_SIZE, usSendSize);

                        ProtocolResponse = m_PSEM.OffsetWrite((ushort)idTable,
                                                              intIndex * BLOCK_SIZE,
                                                              streamPSEM.ToArray());
                        OnStepProgress(new ProgressEventArgs());
                    }

                    // Translate Protocol result
                    Result = TranslateProtocolResult(ProtocolResponse);

                    streamFile.Close();

                    //Check on success and then activate the table
                    if (PSEMResponse.Ok == ProtocolResponse)
                    {
                        if (FWDLLogSupported)
                        {
                            //Construct the hash code and call the procedure to authenticate
                            CENTRON_AMI_FW_File FWFile = new CENTRON_AMI_FW_File(path);
                            byte[] FWHashCode          = FWFile.HashCode;

                            // if MSM ChoiceConnect meter and ChoiceConnect FWDL request, spoof RFLAN FWDL
                            CENTRON_AMI AmiDevice = this as CENTRON_AMI;
                            if (AmiDevice != null &&
                                bybuffer[9] == (byte)FirmwareType.ChoiceConnectFW &&
                                AmiDevice.IsChoiceConnectMsmMeter)
                            {
                                bybuffer[9] = (byte)FirmwareType.RFLANFW;
                            }

                            ProcResult = AuthenticateFWDL(idTable, bybuffer[9], FWHashCode);
                        }
                        else
                        {
                            ProcResult = ProcedureResultCodes.COMPLETED;
                        }

                        if (ProcResult == ProcedureResultCodes.COMPLETED)
                        {
                            // Activate the pending table
                            ProcResult = ActivatePendingTable(false, false, byEventNumber,
                                                              PendingEventRecord.PendingEventCode.NonTimeTrigger);

                            Result = TranslateProcedureResult(ProcResult);
                        }
                        else
                        {
                            //We couldn't authenticate using the hash code so activation will fail
                            ProcResult = ClearPendingTable(false, false, byEventNumber,
                                                           PendingEventRecord.PendingEventCode.NonTimeTrigger);

                            //TODO - not sure this is the correct error
                            Result = FWDownloadResult.SECURITY_ERROR;
                        }

                        OnStepProgress(new ProgressEventArgs());
                    }
                    else
                    {
                        // Write failed, so clear the pending table
                        ProcResult = ClearPendingTable(false, false, byEventNumber,
                                                       PendingEventRecord.PendingEventCode.NonTimeTrigger);

                        Result = FWDownloadResult.WRITE_ERROR;
                    }
                    OnHideProgress(new EventArgs());
                }
            }

            catch (Exception e)
            {
                // Log it and pass it up
                OnHideProgress(new EventArgs());
                m_Logger.WriteException(this, e);
                throw e;
            }

            return(Result);
        }
Ejemplo n.º 58
0
        /// <summary>
        /// Downloads the firmware file to the device but does NOT
        /// activate.  On download failure, the pending table is cleared.
        /// </summary>
        /// <param name="path">Complete path to the firmware file</param>
        /// <param name="eventCode">event code activation method</param>
        /// <returns>FWDownloadResult</returns>
        // Revision History
        // MM/DD/YY who Version Issue# Description
        // -------- --- ------- ------ ---------------------------------------
        // 10/05/06 AF  7.35.00  N/A   Created
        // 10/18/06 AF  7.40.00  N/A   Removed wait within the main loop
        // 05/13/08 AF  1.50.24        Removed IFirmwareDownload from the method name
        // 04/19/10 AF  2.40.39        Added M2 Gateway support
        // 03/21/12 JJJ 2.60.xx        Added support for ChoiceConnect FW
        // 08/17/12 AF  2.60.55        Added support for RF Mesh FW and RF Mesh Config
        // 02/07/14 jrf 3.50.32 419257 Modified to use a dynamic FWDL block size based on the negotiated
        //                             PSEM packet size.
        // 06/15/15 mah 4.50.140 577669 Added a retry if a busy response was received
        // 08/24/16 PGH 4.70.15 701952     Added HAN OTA Firmware
        public FWDownloadResult DownloadFWNoActivate(string path, PendingEventRecord.PendingEventCode eventCode)
        {
            FWDownloadResult     Result           = FWDownloadResult.UNKNOWN_DRIVER_ERROR;
            ProcedureResultCodes ProcResult       = ProcedureResultCodes.INVALID_PARAM;
            PSEMResponse         ProtocolResponse = PSEMResponse.Ok;
            byte   byEventNumber  = 0;
            ushort idTable        = (ushort)PendingTableIds.RegisterFWTbl | PENDING_BIT;
            ushort usNumberChunks = 0;
            ushort intIndex;

            System.IO.FileStream   streamFile;
            System.IO.MemoryStream streamHeader = new System.IO.MemoryStream();
            System.IO.MemoryStream streamPSEM   = new System.IO.MemoryStream();

            try
            {
                Result = EnterFirmwareDownloadMode(path);

                if (FWDownloadResult.SUCCESS != Result)
                {
                    m_Logger.WriteLine(Logger.LoggingLevel.Detailed,
                                       "Initiate F/W Download procedure failed with result = "
                                       + Result);
                }
                else
                {
                    // Meter is ready to receive the firmware file
                    streamFile = new System.IO.FileStream(path, System.IO.FileMode.Open, FileAccess.Read);
                    byte[] bybuffer = new byte[streamFile.Length];

                    streamFile.Read(bybuffer, 0, (int)streamFile.Length);
                    streamFile.Position = 0;

                    switch (bybuffer[9])
                    {
                    case (byte)FirmwareType.RegisterFW:
                    case (byte)FirmwareType.M2GTWY:
                    case (byte)FirmwareType.DisplayFW:
                    {
                        byEventNumber = REGISTER_EVENT_NUMBER;
                        idTable       = (ushort)PendingTableIds.RegisterFWTbl | PENDING_BIT;
                        break;
                    }

                    case (byte)FirmwareType.ZigbeeFW:
                    {
                        byEventNumber = ZIGBEE_EVENT_NUMBER;
                        idTable       = (ushort)PendingTableIds.HANModuleFWTbl | PENDING_BIT;
                        break;
                    }

                    case (byte)FirmwareType.RFLANFW:
                    case (byte)FirmwareType.PLANFW:
                    case (byte)FirmwareType.CiscoCommFW:
                    case (byte)FirmwareType.CiscoCfgFW:
                    case (byte)FirmwareType.ChoiceConnectFW:
                    {
                        byEventNumber = COMM_EVENT_NUMBER;
                        idTable       = (ushort)PendingTableIds.CommModuleFWTbl | PENDING_BIT;
                        break;
                    }

                    case (byte)FirmwareType.HAN_OTA_FW:
                    case (byte)FirmwareType.HANDevFW:
                    {
                        byEventNumber = HAN_DEV_EVENT_NUMBER;
                        idTable       = (ushort)PendingTableIds.HANDeviceFWTbl | PENDING_BIT;
                        break;
                    }

                    default:
                    {
                        throw new NotImplementedException("Table not yet supported");
                    }
                    }

                    BuildPendingHeader(ref streamHeader, false, false, byEventNumber, eventCode);

                    usNumberChunks = (ushort)(streamFile.Length / FWDLBlockSize);

                    if (streamFile.Length != FWDLBlockSize * usNumberChunks)
                    {
                        usNumberChunks++;
                    }

                    OnShowProgress(new ShowProgressEventArgs(1, usNumberChunks + 1,
                                                             "Firmware Download",
                                                             "Downloading..."));

                    ushort usSendSize = FWDLBlockSize;

                    for (intIndex = 0;
                         (intIndex < usNumberChunks) && (PSEMResponse.Ok == ProtocolResponse);
                         intIndex++)
                    {
                        // The last chunk could be smaller
                        if (usNumberChunks - 1 == intIndex)
                        {
                            usSendSize = (ushort)(streamFile.Length % FWDLBlockSize);
                            // If no remainder then it is a full packet
                            if (0 == usSendSize)
                            {
                                usSendSize = FWDLBlockSize;
                            }
                        }

                        streamHeader.Position = 0;
                        streamPSEM.Position   = 0;
                        streamPSEM.SetLength(0);
                        streamHeader.WriteTo(streamPSEM);
                        streamPSEM.Write(bybuffer, intIndex * FWDLBlockSize, usSendSize);

                        ProtocolResponse = m_PSEM.OffsetWrite((ushort)idTable,
                                                              intIndex * FWDLBlockSize,
                                                              streamPSEM.ToArray());

                        // WR 577669 - The fwdl process is failing on ICS meters with a device busy status.  The intent of the next
                        // paragraph is to recognize that the meter may be off doing other operations when we first tried to download
                        // a block.

                        if (ProtocolResponse == PSEMResponse.Bsy)
                        {
                            // Wait for the device to complete it's current task, then retry to download the same block

                            Thread.Sleep(1500); // 1.5 seconds is an arbitary value - the intent is to give the meter enough time to
                                                // complete it's work

                            ProtocolResponse = m_PSEM.OffsetWrite((ushort)idTable,
                                                                  intIndex * FWDLBlockSize,
                                                                  streamPSEM.ToArray());
                        }
                        OnStepProgress(new ProgressEventArgs());
                    }

                    // Translate Protocol result
                    Result = TranslateProtocolResult(ProtocolResponse);

                    streamFile.Close();

                    // If any write failed, give up and clear the pending table
                    if (PSEMResponse.Ok != ProtocolResponse)
                    {
                        // Write failed, so clear the pending table
                        ProcResult = ClearPendingTable(false, false, byEventNumber,
                                                       PendingEventRecord.PendingEventCode.NonTimeTrigger);

                        Result = FWDownloadResult.WRITE_ERROR;
                    }
                    OnHideProgress(new EventArgs());
                }
            }

            catch (Exception e)
            {
                // Log it and pass it up
                OnHideProgress(new EventArgs());
                m_Logger.WriteException(this, e);
                throw e;
            }

            return(Result);
        }
Ejemplo n.º 59
0
        /// <summary>
        /// Downloads the firmware file to the meter and activates it.
        /// The activation will cause the meter to drop the psem task so meter log off must
        /// follow this function call on success.  This method supports resuming
        /// a previous failed FWDL.
        /// </summary>
        /// <param name="path">Complete file path of the firmware file</param>
        /// <param name="usBlockIndex">Dual purpose parameter. The passed in value indicates
        /// which block to begin downloading. The passed out parameter indicates which block to
        /// resume downloading in case there was a failure. This can then passed in again to
        /// restart the download at the point where it left off.</param>
        /// <param name="blnRetry">Whether or not to leave the FWDL in a state
        /// to permit subsequent retries at point of faliure. If false the pending table
        /// will be cleared on failure.</param>
        /// <param name="blnActivate">Whether or not to activate the firmware.</param>
        /// <returns>Itron.Metering.Device.FWDownloadResult</returns>
        // Revision History
        // MM/DD/YY who Version ID Number Description
        // -------- --- ------- -- ------ ---------------------------------------
        // 08/28/06 AF  7.35.00    N/A    Created
        // 09/15/06 AF  7.35.00    N/A    Added Catch for TimeOutException
        // 10/18/06 AF  7.40.00    N/A    Removed wait within the main loop
        // 05/13/08 AF  1.50.24           Removed IFirmwareDownload from the method name
        // 04/19/10 AF  2.40.39           Added M2 Gateway support
        // 08/18/11 AF  2.52.05           Added support for authentication using a hash code
        // 08/26/11 AF  2.52.08           Added support for Cisco f/w
        // 09/22/11 AF  2.52.21    N/A    Added support for Cisco config file f/w d/l - TODO remove when no longer needed
        // 10/12/11 AF  2.53.00           Changed the Cisco Comm fw enum name
        // 03/22/12 JJJ 2.60.xx           Added support for ChoiceConnect FW
        // 05/10/12 JJJ 2.60.xx           Tweaked FW Type passed to AuthenticateFWDL if ChoiceConnect, make RFLAN
        // 04/19/13 jrf 2.80.21 TQ 7639   Adding support for ICS comm module FWDL.
        // 07/08/13 jrf 2.80.51 TC 13201  Created to support retries of FWDL.
        // 07/15/13 jrf 2.80.?? TC 15062  Added parameter to control activation.
        // 08/22/13 jrf 2.85.26 WR 420902 Decrementing the block index on a failed block write, so
        //                                on a retry we will start back on the correct block.
        // 11/07/13 AF  3.50.02 TQ9508,9514 Have to activate the pending table using mfg proc 69 rather than std proc 13
        //                                  for I-210 and kV2c ICM firmware
        //  11/15/13 AF  3.50.03	    Class re-architecture - removed code specific to ICS_Gateway
        // 12/02/13 jrf 3.50.10            Refactored code used to modify the FWType byte to it's own method.
        // 02/07/14 jrf 3.50.32 WR 419257  Modified to use a dynamic FWDL block size based on the negotiated
        //                                 PSEM packet size.
        // 08/24/16 PGH 4.70.15 701952     Added HAN OTA Firmware
        // 02/06/17 AF  4.71.07 743128     Added supported for ICM modem firmware
        // 03/10/17 AF  4.71.09 749833     Renamed the firmware type because 37 is for Verizon LTE only
        // 12/05/17 AF  4.73.00 Task 469253 Added back the verizon modem fwdl
        // 12/06/17 AF  4.73.00 Task 469254 Added ATT/Rogers modem fwdl
        //
        public FWDownloadResult DownloadFW(string path, ref ushort usBlockIndex, bool blnRetry = false, bool blnActivate = true)
        {
            FWDownloadResult     Result           = FWDownloadResult.UNKNOWN_DRIVER_ERROR;
            ProcedureResultCodes ProcResult       = ProcedureResultCodes.INVALID_PARAM;
            PSEMResponse         ProtocolResponse = PSEMResponse.Ok;
            byte   byEventNumber  = 0;
            ushort idTable        = (ushort)PendingTableIds.RegisterFWTbl | PENDING_BIT;
            ushort usNumberChunks = 0;
            //A non-zero starting block means we are need to pick up were we left off.
            bool blnResumeFWDL = (0 != usBlockIndex);

            System.IO.FileStream   streamFile;
            System.IO.MemoryStream streamHeader = new System.IO.MemoryStream();
            System.IO.MemoryStream streamPSEM   = new System.IO.MemoryStream();

            try
            {
                if (true == blnResumeFWDL)
                {
                    Result = FWDownloadResult.SUCCESS;
                }
                else
                {
                    // Tell the meter to enter firmware download mode
                    Result = EnterFirmwareDownloadMode(path);
                }


                if (FWDownloadResult.SUCCESS != Result)
                {
                    m_Logger.WriteLine(Logger.LoggingLevel.Detailed,
                                       "Initiate F/W Download procedure failed with result = "
                                       + Result);
                }
                else
                {
                    // Meter is ready to receive the firmware file
                    streamFile = new System.IO.FileStream(path, System.IO.FileMode.Open, FileAccess.Read);
                    byte[] bybuffer = new byte[streamFile.Length];

                    streamFile.Read(bybuffer, 0, (int)streamFile.Length);
                    streamFile.Position = 0;

                    switch (bybuffer[9])
                    {
                    case (byte)FirmwareType.RegisterFW:
                    case (byte)FirmwareType.M2GTWY:
                    case (byte)FirmwareType.DisplayFW:
                    {
                        byEventNumber = REGISTER_EVENT_NUMBER;
                        idTable       = (ushort)PendingTableIds.RegisterFWTbl | PENDING_BIT;
                        break;
                    }

                    case (byte)FirmwareType.ZigbeeFW:
                    {
                        byEventNumber = ZIGBEE_EVENT_NUMBER;
                        idTable       = (ushort)PendingTableIds.HANModuleFWTbl | PENDING_BIT;
                        break;
                    }

                    case (byte)FirmwareType.RFLANFW:
                    case (byte)FirmwareType.PLANFW:
                    case (byte)FirmwareType.CiscoCommFW:
                    case (byte)FirmwareType.CiscoCfgFW:
                    case (byte)FirmwareType.ChoiceConnectFW:
                    case (byte)FirmwareType.ICSFW:
                    case (byte)FirmwareType.ICS_MODEM_FW_Sierra_Verizon_LTE:
                    case (byte)FirmwareType.ICS_MODEM_FW_Sierra_ATT_Rogers_Bell_LTE:
                    {
                        byEventNumber = COMM_EVENT_NUMBER;
                        idTable       = (ushort)PendingTableIds.CommModuleFWTbl | PENDING_BIT;
                        break;
                    }

                    case (byte)FirmwareType.HAN_OTA_FW:
                    case (byte)FirmwareType.HANDevFW:
                    {
                        byEventNumber = HAN_DEV_EVENT_NUMBER;
                        idTable       = (ushort)PendingTableIds.HANDeviceFWTbl | PENDING_BIT;
                        break;
                    }

                    default:
                    {
                        throw new NotImplementedException("Table not supported");
                    }
                    }

                    BuildPendingHeader(ref streamHeader, false, false,
                                       byEventNumber, PendingEventRecord.PendingEventCode.NonTimeTrigger);

                    usNumberChunks = (ushort)(streamFile.Length / FWDLBlockSize);

                    if (streamFile.Length != FWDLBlockSize * usNumberChunks)
                    {
                        usNumberChunks++;
                    }

                    OnShowProgress(new ShowProgressEventArgs(1, usNumberChunks + 1,
                                                             "Firmware Download",
                                                             "Downloading..."));

                    ushort usSendSize = FWDLBlockSize;

                    for (;
                         (usBlockIndex < usNumberChunks) && (PSEMResponse.Ok == ProtocolResponse);
                         usBlockIndex++)
                    {
                        // The last chunk could be smaller
                        if (usNumberChunks - 1 == usBlockIndex)
                        {
                            usSendSize = (ushort)(streamFile.Length % FWDLBlockSize);
                            // If no remainder then it is a full packet
                            if (0 == usSendSize)
                            {
                                usSendSize = FWDLBlockSize;
                            }
                        }

                        streamHeader.Position = 0;
                        streamPSEM.Position   = 0;
                        streamPSEM.SetLength(0);
                        streamHeader.WriteTo(streamPSEM);
                        streamPSEM.Write(bybuffer, usBlockIndex * FWDLBlockSize, usSendSize);

                        ProtocolResponse = m_PSEM.OffsetWrite((ushort)idTable,
                                                              usBlockIndex * FWDLBlockSize,
                                                              streamPSEM.ToArray());
                        OnStepProgress(new ProgressEventArgs());
                    }

                    // Translate Protocol result
                    Result = TranslateProtocolResult(ProtocolResponse);

                    streamFile.Close();

                    //Check on success and then activate the table
                    if (PSEMResponse.Ok == ProtocolResponse)
                    {
                        if (FWDLLogSupported)
                        {
                            //Construct the hash code and call the procedure to authenticate
                            CENTRON_AMI_FW_File FWFile = new CENTRON_AMI_FW_File(path);
                            byte[] FWHashCode          = FWFile.HashCode;

                            if ((bybuffer[9] != (byte)FirmwareType.ICSFW) && (bybuffer[9] != (byte)FirmwareType.ICS_MODEM_FW_Sierra_Verizon_LTE))
                            {
                                //Some devices may require this byte to be adjusted.
                                bybuffer[9] = SelectFWTypeByte(bybuffer[9]);

                                ProcResult = AuthenticateFWDL(idTable, bybuffer[9], FWHashCode);
                            }
                            else //Skip authenticate for ICS comm module and modem FWDL
                            {
                                ProcResult = ProcedureResultCodes.COMPLETED;
                            }
                        }
                        else
                        {
                            ProcResult = ProcedureResultCodes.COMPLETED;
                        }

                        if (ProcResult == ProcedureResultCodes.COMPLETED)
                        {
                            if (true == blnActivate)
                            {
                                // Activate the pending table using std proc 13
                                ProcResult = ActivatePendingTable(false, false, byEventNumber,
                                                                  PendingEventRecord.PendingEventCode.NonTimeTrigger);

                                Result = TranslateProcedureResult(ProcResult);
                            }
                        }
                        else
                        {
                            if (false == blnRetry)
                            {
                                //We couldn't authenticate using the hash code so activation will fail
                                ProcResult = ClearPendingTable(false, false, byEventNumber,
                                                               PendingEventRecord.PendingEventCode.NonTimeTrigger);
                            }

                            //TODO - not sure this is the correct error
                            Result = FWDownloadResult.SECURITY_ERROR;
                        }

                        OnStepProgress(new ProgressEventArgs());
                    }
                    else //PSEMResponse.Ok != ProtocolResponse
                    {
                        //Decrement the block index so we make sure we restart on the block that we failed on.
                        usBlockIndex--;

                        if (false == blnRetry)
                        {
                            // Write failed, so clear the pending table
                            ProcResult = ClearPendingTable(false, false, byEventNumber,
                                                           PendingEventRecord.PendingEventCode.NonTimeTrigger);
                        }

                        Result = FWDownloadResult.WRITE_ERROR;
                    }
                    OnHideProgress(new EventArgs());
                }
            }

            catch (Exception e)
            {
                if (false == blnRetry)
                {
                    // Log it and pass it up
                    OnHideProgress(new EventArgs());
                    m_Logger.WriteException(this, e);
                    throw e;
                }
                else
                {
                    Result = FWDownloadResult.WRITE_ERROR;
                }
            }

            return(Result);
        }
Ejemplo n.º 60
0
        /// <summary>
        /// Serializes objectToSerialize to a byte array using compression provided by compressor if T is an array of primitives.  Otherwise returns default value for T.  Override
        /// to serialize other types
        /// </summary>
        /// <param name="objectToSerialise">Object to serialize</param>
        /// <param name="dataProcessors">The compression provider to use</param>
        /// <param name="options">Options to be used during serialization and processing of data</param>
        /// <returns>The serialized and compressed bytes of objectToSerialize</returns>
        public static unsafe StreamSendWrapper SerialiseArrayObject(object objectToSerialise, List <DataProcessor> dataProcessors, Dictionary <string, string> options)
        {
            Type objType = objectToSerialise.GetType();

            if (objType.IsArray)
            {
                var elementType = objType.GetElementType();

                //No need to do anything for a byte array
                if (elementType == typeof(byte) && (dataProcessors == null || dataProcessors.Count == 0))
                {
                    byte[] bytesToSerialise = objectToSerialise as byte[];
                    //return objectToSerialise as byte[];
                    return(new StreamSendWrapper(new ThreadSafeStream(new MemoryStream(bytesToSerialise, 0, bytesToSerialise.Length, false, true), true)));
                }
                else if (elementType.IsPrimitive)
                {
                    var      asArray     = objectToSerialise as Array;
                    GCHandle arrayHandle = GCHandle.Alloc(asArray, GCHandleType.Pinned);

                    try
                    {
                        IntPtr safePtr      = Marshal.UnsafeAddrOfPinnedArrayElement(asArray, 0);
                        long   writtenBytes = 0;

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

                        using (UnmanagedMemoryStream inputDataStream = new System.IO.UnmanagedMemoryStream((byte *)safePtr, asArray.Length * Marshal.SizeOf(elementType)))
                        {
                            if (dataProcessors == null || dataProcessors.Count == 0)
                            {
                                AsyncStreamCopier.CopyStreamTo(inputDataStream, tempStream1);
                                //return tempStream1.ToArray();
                                return(new StreamSendWrapper(new ThreadSafeStream(tempStream1, true)));
                            }

                            dataProcessors[0].ForwardProcessDataStream(inputDataStream, tempStream1, options, out writtenBytes);
                        }

                        if (dataProcessors.Count > 1)
                        {
                            MemoryStream tempStream2 = new MemoryStream();

                            for (int i = 1; i < dataProcessors.Count; i += 2)
                            {
                                tempStream1.Seek(0, 0); tempStream1.SetLength(writtenBytes);
                                tempStream2.Seek(0, 0);
                                dataProcessors[i].ForwardProcessDataStream(tempStream1, tempStream2, options, out writtenBytes);

                                if (i + 1 < dataProcessors.Count)
                                {
                                    tempStream1.Seek(0, 0);
                                    tempStream2.Seek(0, 0); tempStream2.SetLength(writtenBytes);
                                    dataProcessors[i].ForwardProcessDataStream(tempStream2, tempStream1, options, out writtenBytes);
                                }
                            }

                            if (dataProcessors.Count % 2 == 0)
                            {
                                tempStream2.SetLength(writtenBytes + 4);
                                tempStream2.Seek(writtenBytes, 0);
                                tempStream2.Write(BitConverter.GetBytes(asArray.Length), 0, sizeof(int));
                                //return tempStream2.ToArray();
                                tempStream1.Dispose();
                                return(new StreamSendWrapper(new ThreadSafeStream(tempStream2, true)));
                            }
                            else
                            {
                                tempStream1.SetLength(writtenBytes + 4);
                                tempStream1.Seek(writtenBytes, 0);
                                tempStream1.Write(BitConverter.GetBytes(asArray.Length), 0, sizeof(int));
                                //return tempStream1.ToArray();
                                tempStream2.Dispose();
                                return(new StreamSendWrapper(new ThreadSafeStream(tempStream1, true)));
                            }
                        }
                        else
                        {
                            tempStream1.SetLength(writtenBytes + 4);
                            tempStream1.Seek(writtenBytes, 0);
                            tempStream1.Write(BitConverter.GetBytes(asArray.Length), 0, sizeof(int));
                            //return tempStream1.ToArray();
                            return(new StreamSendWrapper(new ThreadSafeStream(tempStream1, true)));
                        }
                    }
                    finally
                    {
                        arrayHandle.Free();
                    }
                }
            }

            return(null);
        }