public void CopiesResult()
        {
            // Note that a preable is not expected on the generated stream.
            string text = "Hello world";
            Byte[] textInBytes = Encoding.UTF8.GetBytes(text);
            string outputText;

            Byte[] buffer = new Byte[1024];

            using (MemoryStream stream = new MemoryStream(buffer))
            using (StringWriter writer = new StringWriter())
            using (StreamWriter outputWriter = new StreamWriter(stream))
            {
                writer.Write(text);
                writer.CopyTo(outputWriter);

                outputText = writer.ToString();
            }

            Assert.Equal(text, outputText, StringComparer.Ordinal);

            for (int i = 0; i < textInBytes.Length; i++)
            {
                Assert.Equal(textInBytes[i], buffer[i]);
            }
        }
 public void Decrement()
 {
     // Reduce the size of the byte by 1 (note that this does not check for overflows!)
     Byte b = new Byte(1);
     b.TwosComplement();
     RippleAdd(b);
 }
示例#3
0
 public static string DecompressString(Byte[] value)
 {
     if (value.Length > 0)
         return Encoding.UTF8.GetString(CLZF.Decompress(value));
     else
         return "";
 }
        public void OnlyUsesBufferUpToSize(int count)
        {
            string text = new string('a', count);
            Byte[] textInBytes = Encoding.UTF8.GetBytes(text);

            Mock<StreamWriter> mock;

            Byte[] buffer = new Byte[textInBytes.Length + 100];

            using (MemoryStream stream = new MemoryStream(buffer))
            {
                StringWriter writer = new StringWriter();

                mock = new Mock<StreamWriter>(MockBehavior.Strict, stream) { CallBase = true };
                mock.Setup(sw => sw.Write(It.IsAny<char[]>(),
                                          It.IsAny<int>(),
                                          It.Is<int>(c => c == StringWriterExtensions.BufferSize ||
                                                          c == textInBytes.Length % StringWriterExtensions.BufferSize)))
                    .Verifiable();

                StreamWriter outputWriter = mock.Object;
                writer.Write(text);
                writer.CopyTo(outputWriter);

                mock.Verify();
            }
        }
 public void PosTest2()
 {
     Byte[] bytes = new Byte[] { };
     UTF7Encoding UTF7 = new UTF7Encoding();
     int charCount = UTF7.GetCharCount(bytes, 0, 0);
     Assert.Equal(0, charCount);
 }
            public void CanCompareToBoxedRawBytes()
            {
                var lhs = new Binary(new Byte[] { 1, 2, 3 });
                var rhs = new Byte[] { 1, 2, 3 };

                Assert.Equal(0, lhs.CompareTo((Object)rhs));
            }
            public void WrapUnderlyingBytes()
            {
                var rawBytes = new Byte[0];
                var bytes = new Binary(rawBytes);

                Assert.Same(rawBytes, (Byte[])bytes);
            }
 public ReadWriteAsyncParams(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
 {
     this.Buffer = buffer;
     this.Offset = offset;
     this.Count = count;
     this.CancellationHelper = cancellationToken.CanBeCanceled ? new IOCancellationHelper(cancellationToken) : null;
 }
示例#9
0
            public static Byte[] DecompressArray(Byte[] inBuf)
            {
                Logger.Enter();
                MemoryStream memory = new MemoryStream();

                try
                {
                    using (GZipStream stream = new GZipStream(new MemoryStream(inBuf), CompressionMode.Decompress))
                    {
                        const int size = 4096;
                        byte[] buffer = new byte[size];

                        int count = 0;
                        do
                        {
                            count = stream.Read(buffer, 0, size);
                            if (count > 0)
                            {
                                memory.Write(buffer, 0, count);
                            }
                        }
                        while (count > 0);
                    }
                }
                catch(Exception ex)
                {
                    Logger.Error(String.Format("Decompress error.Internal msg: {0}", ex.Message));
                }

                Logger.Leave();
                return memory.ToArray();
            }
示例#10
0
        public void ToggleBit(byte register, int bit_position)
        {
            Byte b = new Byte(Read(register));     // Read control register
            b.ToggleBit(bit_position);                // Modify oscillator bit

            // Write new byte value
            Write(register, b.ToByte());
        }
 public void PosTest3()
 {
     Char[] chars = GetCharArray(10);
     Byte[] bytes = new Byte[20];
     UnicodeEncoding uEncoding = new UnicodeEncoding();
     int actualValue;
     actualValue = uEncoding.GetBytes(chars, 0, 0, bytes, 20);
     Assert.Equal(0, actualValue);
 }
示例#12
0
文件: BGLib.cs 项目: shariat/bglib
 public GAPScanResponseEventArgs(Byte rssi, Byte packet_type, Byte[] bd_addr, Byte address_type, Byte bond, Byte[] data)
 {
     this.rssi = rssi;
     this.packet_type = packet_type;
     this.bd_addr = bd_addr;
     this.address_type = address_type;
     this.bond = bond;
     this.data = data;
 }
示例#13
0
 public void PosTest1()
 {
     Byte[] bytes;
     String chars = "UTF7 Encoding Example";
     UTF7Encoding UTF7 = new UTF7Encoding();
     int byteCount = chars.Length;
     bytes = new Byte[byteCount];
     int bytesEncodedCount = UTF7.GetBytes(chars, 1, 2, bytes, 0);
 }
示例#14
0
        public async Task ModifyBaseStream()
        {
            var ms = await LocalMemoryStream.readAppFileAsync(gzTestFile("GZTestDocument.txt.gz"));

            var zip = new GZipStream(ms, CompressionMode.Decompress);
            int size = 1024;
            Byte[] bytes = new Byte[size];
            zip.BaseStream.Read(bytes, 0, size); // This will throw if the underlying stream is not writeable as expected
        }
示例#15
0
 public void PosTest1()
 {
     Byte[] bytes = new Byte[] {
                      85,  84,  70,  56,  32,  69, 110,
                      99, 111, 100, 105, 110, 103,  32,
                      69, 120,  97, 109, 112, 108, 101};
     UTF7Encoding utf7 = new UTF7Encoding();
     string str = utf7.GetString(bytes, 0, bytes.Length);
 }
        public void PosTest3()
        {
            UnicodeEncoding uE = new UnicodeEncoding(false, true);
            Byte[] expectedValue = new Byte[] { 0xff, 0xfe };
            Byte[] actualValue;

            actualValue = uE.GetPreamble();
            Assert.Equal(expectedValue, actualValue);
        }
示例#17
0
 public void PosTest2()
 {
     Char[] chars;
     Byte[] bytes = new Byte[] { };
     UTF7Encoding UTF7 = new UTF7Encoding();
     int charCount = UTF7.GetCharCount(bytes, 0, 0);
     chars = new Char[] { };
     int charsDecodedCount = UTF7.GetChars(bytes, 0, 0, chars, 0);
     Assert.Equal(0, charsDecodedCount);
 }
示例#18
0
 public void PosTest1()
 {
     Byte[] bytes = new Byte[] {
                                  85,  84,  70,  56,  32,  69, 110,
                                  99, 111, 100, 105, 110, 103,  32,
                                  69, 120,  97, 109, 112, 108, 101};
     UTF7Encoding UTF7 = new UTF7Encoding();
     int charCount = UTF7.GetCharCount(bytes, 2, 8);
     Assert.Equal(8, charCount);
 }
        public void PosTest3()
        {
            String chars = GetString(10);
            Byte[] bytes = new Byte[30];
            UnicodeEncoding uEncoding = new UnicodeEncoding();
            int actualValue;

            actualValue = uEncoding.GetBytes(chars, 0, 0, bytes, 30);
            Assert.Equal(0, actualValue);
        }
示例#20
0
 public void PosTest2()
 {
     Byte[] bytes;
     Char[] chars = new Char[] { };
     UTF7Encoding UTF7 = new UTF7Encoding();
     int byteCount = UTF7.GetByteCount(chars, 0, 0);
     bytes = new Byte[byteCount];
     int bytesEncodedCount = UTF7.GetBytes(chars, 0, 0, bytes, 0);
     Assert.Equal(0, bytesEncodedCount);
 }
示例#21
0
 public void PosTest2()
 {
     Byte[] bytes;
     String chars = "";
     UTF7Encoding UTF7 = new UTF7Encoding();
     int byteCount = chars.Length;
     bytes = new Byte[byteCount];
     int bytesEncodedCount = UTF7.GetBytes(chars, 0, byteCount, bytes, 0);
     Assert.Equal(0, bytesEncodedCount);
 }
示例#22
0
文件: BGLib.cs 项目: shariat/bglib
 public SystemBootEventArgs(UInt16 major, UInt16 minor, UInt16 patch, UInt16 build, UInt16 ll_version, Byte protocol_version, Byte hw)
 {
     this.major = major;
     this.minor = minor;
     this.patch = patch;
     this.build = build;
     this.ll_version = ll_version;
     this.protocol_version = protocol_version;
     this.hw = hw;
 }
示例#23
0
        public static UInt32 GetUInt32(this Byte[] buffer, Int32 pos)
        {
            Byte[] copybuffer;

            copybuffer = new Byte[4];
            Array.Copy(buffer, pos, copybuffer, 0, 4);
            Array.Reverse(copybuffer);

            return BitConverter.ToUInt32(copybuffer, 0);
        }
 public void NegTest1()
 {
     Char[] chars = null;
     Byte[] bytes = new Byte[30];
     UnicodeEncoding uEncoding = new UnicodeEncoding();
     int actualValue;
     Assert.Throws<ArgumentNullException>(() =>
     {
         actualValue = uEncoding.GetBytes(chars, 0, 0, bytes, 0);
     });
 }
示例#25
0
 public void PosTest3()
 {
     Char[] srcChars = GetCharArray(10);
     Char[] desChars = new Char[10];
     Byte[] bytes = new Byte[20];
     UnicodeEncoding uEncoding = new UnicodeEncoding();
     int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0);
     int actualValue;
     actualValue = uEncoding.GetChars(bytes, 0, 0, desChars, 10);
     Assert.Equal(0, actualValue);
 }
示例#26
0
 public void NegTest4()
 {
     Byte[] bytes = new Byte[] {
                                  85,  84,  70,  56,  32,  69, 110,
                                  99, 111, 100, 105, 110, 103,  32,
                                  69, 120,  97, 109, 112, 108, 101};
     UTF7Encoding UTF7 = new UTF7Encoding();
     Assert.Throws<ArgumentOutOfRangeException>(() =>
     {
         int charCount = UTF7.GetCharCount(bytes, bytes.Length, 6);
     });
 }
 public void NegTest1()
 {
     Char[] chars = GetCharArray(10);
     Byte[] bytes = new Byte[20];
     UnicodeEncoding uEncoding = new UnicodeEncoding();
     int byteCount = uEncoding.GetBytes(chars, 0, 10, bytes, 0);
     int actualValue;
     Assert.Throws<ArgumentNullException>(() =>
     {
         actualValue = uEncoding.GetCharCount(null, 0, 0);
     });
 }
示例#28
0
        public void PosTest2()
        {
            Byte[] bytes;
            Char[] chars = new Char[] { };

            UTF8Encoding utf8 = new UTF8Encoding();

            int byteCount = utf8.GetByteCount(chars, 0, 0);
            bytes = new Byte[byteCount];
            int charsEncodedCount = utf8.GetChars(bytes, 0, 0, chars, 0);
            Assert.Equal(0, charsEncodedCount);
        }
示例#29
0
 public void NegTest3()
 {
     Byte[] bytes;
     String chars = "UTF7 Encoding Example";
     UTF7Encoding UTF7 = new UTF7Encoding();
     int byteCount = chars.Length;
     bytes = new Byte[byteCount];
     Assert.Throws<ArgumentOutOfRangeException>(() =>
     {
         int bytesEncodedCount = UTF7.GetBytes(chars, -1, 2, bytes, 0);
     });
 }
示例#30
0
 public void NegTest1()
 {
     Byte[] bytes;
     String chars = null;
     UTF7Encoding UTF7 = new UTF7Encoding();
     int byteCount = 10;
     bytes = new Byte[byteCount];
     Assert.Throws<ArgumentNullException>(() =>
     {
         int bytesEncodedCount = UTF7.GetBytes(chars, 1, 2, bytes, 0);
     });
 }
示例#31
0
        private int QQwry()
        {
            string pattern = @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$";
            Regex  objRe   = new Regex(pattern);
            Match  objMa   = objRe.Match(ip);

            if (!objMa.Success)
            {
                this.errMsg = "IP格式错误";
                return(4);
            }

            long ip_Int = this.IpToInt(ip);
            int  nRet   = 0;

            if (ip_Int >= IpToInt("127.0.0.0") && ip_Int <= IpToInt("127.255.255.255"))
            {
                this.country = "本机内部环回地址";
                this.local   = "";
                nRet         = 1;
            }
            else if ((ip_Int >= IpToInt("0.0.0.0") && ip_Int <= IpToInt("2.255.255.255")) || (ip_Int >= IpToInt("64.0.0.0") && ip_Int <= IpToInt("126.255.255.255")) || (ip_Int >= IpToInt("58.0.0.0") && ip_Int <= IpToInt("60.255.255.255")))
            {
                this.country = "网络保留地址";
                this.local   = "";
                nRet         = 1;
            }
            objfs = new FileStream(this.dataPath, FileMode.Open, FileAccess.Read);
            try
            {
                //objfs.Seek(0,SeekOrigin.Begin);
                objfs.Position = 0;
                byte[] buff = new Byte[8];
                objfs.Read(buff, 0, 8);
                firstStartIp = buff[0] + buff[1] * 256 + buff[2] * 256 * 256 + buff[3] * 256 * 256 * 256;
                lastStartIp  = buff[4] * 1 + buff[5] * 256 + buff[6] * 256 * 256 + buff[7] * 256 * 256 * 256;
                long recordCount = Convert.ToInt64((lastStartIp - firstStartIp) / 7.0);
                if (recordCount <= 1)
                {
                    country = "FileDataError";
                    objfs.Close();
                    return(2);
                }
                long rangE = recordCount;
                long rangB = 0;
                long recNO = 0;
                while (rangB < rangE - 1)
                {
                    recNO = (rangE + rangB) / 2;
                    this.GetStartIp(recNO);
                    if (ip_Int == this.startIp)
                    {
                        rangB = recNO;
                        break;
                    }
                    if (ip_Int > this.startIp)
                    {
                        rangB = recNO;
                    }
                    else
                    {
                        rangE = recNO;
                    }
                }
                this.GetStartIp(rangB);
                this.GetEndIp();
                if (this.startIp <= ip_Int && this.endIp >= ip_Int)
                {
                    this.GetCountry();
                    this.local = this.local.Replace("(我们一定要解放台湾!!!)", "");
                }
                else
                {
                    nRet         = 3;
                    this.country = "未知";
                    this.local   = "";
                }
                objfs.Close();
                return(nRet);
            }
            catch (Exception ex)
            {
                return(1);
            }
        }
示例#32
0
文件: Form1.cs 项目: HoangTa-SHC/ble
        private void btnStart_Click(object sender, EventArgs e)
        {
            btnStart.Enabled = false;

            if (serial_number.max > 0)
            {
                // Do work
                string jlink_script  = File.ReadAllText(JLINK_TEMPLATE_FILE);
                string serial_string = serial_number.start.ToString("D" + serial_number.length);
                byte[] serial_hex    = Encoding.Default.GetBytes(serial_string);
                File.WriteAllText(JLINK_SCRIPT_FILE, jlink_script);
                for (Byte i = 0; i < serial_number.length; i++)
                {
                    File.AppendAllText(JLINK_SCRIPT_FILE, "\r\nw1 0x" + (serial_number.address + i).ToString("X") + ", 0x" + serial_hex[i].ToString("X2"));
                }
                if (force)
                {
                    File.AppendAllText(JLINK_SCRIPT_FILE, "\r\nr\r\n");
                }
                File.AppendAllText(JLINK_SCRIPT_FILE, "\r\nexit\r\n");


                // Execute the command synchronously.
                ExecuteCommand exe    = new ExecuteCommand();
                string         result = exe.ExecuteCommandSync(jlink + " -ExitOnError -CommanderScript " + JLINK_SCRIPT_FILE);
                File.AppendAllText(LOG_FILE, result);
                File.Delete(JLINK_SCRIPT_FILE);

                if (result.Contains("Connecting to J-Link via USB...FAILED: Cannot connect to J-Link via USB."))
                {
                    MessageBox.Show("Cannot connect to J-Link via USB!");
                    btnStart.Enabled = true;
                    return;
                }

                if (result.Contains("Cannot connect to target."))
                {
                    MessageBox.Show("Cannot connect to target!");
                    btnStart.Enabled = true;
                    return;
                }

                // Update ini file
                serial_number.start++;
                serial_number.max--;
                config["SerialNo"]["Start"] = serial_number.start.ToString();
                config["SerialNo"]["Max"]   = serial_number.max.ToString();
                var parser = new FileIniDataParser();
                parser.WriteFile(CONFIGURATION_FILE, config);

                lbSerialNo.Text = serial_number.start.ToString("D" + serial_number.length);

                if (serial_number.max <= 0)
                {
                    MessageBox.Show("Maximum count reached!");
                    btnStart.Enabled = false;
                }
                else if (lbSerialNo.Text.Length > serial_number.length)
                {
                    MessageBox.Show("Out of range!");
                    btnStart.Enabled = false;
                }
                else
                {
                    btnStart.Enabled = true;
                }
            }
            else
            {
                // Should never reach here
                MessageBox.Show("Maximum count reached!");
            }
        }
示例#33
0
        private void getData()
        {
            TcpListener server = null;

            try
            {
                // 設置 TcpListener port 13000.
                Int32     port2     = 7777;//5678
                IPAddress localAddr = IPAddress.Parse("127.0.0.2");
                server = new TcpListener(localAddr, port2);
                //建立新的TcpListener
                server.Start();               //開始監聽client的請求
                Byte[] bytes = new Byte[256]; //建立buffer來讀取資料
                String data  = "";
                // 進入監聽迴圈
                while (true)
                {
                    //傳入一個變數訊息給ReportProgress借以改變UI
                    //,直接在執行緒修改UI是不被允許
                    TcpClient client = server.AcceptTcpClient();
                    //接收client端的請求
                    UI_stas = Convert.ToInt32(E.strat);
                    backgroundWorker1.ReportProgress(UI_stas);

                    data = null;

                    NetworkStream stream = client.GetStream();
                    //取得client傳過來的資料
                    int i;
                    // 開始接收 client 的資料
                    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        data = System.Text.Encoding.Unicode.GetString(bytes, 0, i);
                        if (init == true)
                        {
                            UI_stas = Convert.ToInt32(E.display);
                            if (data != "disconnect")
                            {
                                _Ls.Add(data);//接收到的資存入List
                            }
                            backgroundWorker1.ReportProgress(UI_stas, data);
                            init = false;
                        }
                        else
                        {
                            _Ls.Clear();
                            UI_stas = Convert.ToInt32(E.recived);
                            if (data == "check")//1062981
                            {
                                check = 1;
                            }
                            else
                            {
                                _Ls.Add(data);
                            }
                            backgroundWorker1.ReportProgress(UI_stas, data);
                        }
                    }

                    UI_stas = Convert.ToInt32(E.disconnected);
                    backgroundWorker1.ReportProgress(UI_stas);
                    client.Close();
                }
            }
            catch (SocketException e)
            {
                MessageBox.Show("SocketException:{0}" + e);
            }
            finally            //釋放區塊
            {
                server.Stop(); //停止監聽clients
            }
        }
 void TestShlRegisterRegisterInstruction(byte[] byteCode, Byte regNum0, Byte regNum1) => TestParseInstruction(byteCode, new BinaryRegisterOperationStub(ParsedInstructionCode.ShlReg, regNum0, regNum1));
 void TestDrawSpriteInstruction(byte[] byteCode, Byte regNum0, Byte regNum1) => TestParseInstruction(byteCode, new BinaryRegisterOperationStub(ParsedInstructionCode.DrawSprite, regNum0, regNum1));
示例#36
0
    public static void Main(string[] args)
    {
        if (args.Length == 1)
        {
            TcpListener server = null;
            try
            {
                // Set the TcpListener on port args[0].
                Int32 port = Int32.Parse(args[0]);
                //IPAddress localAddr = IPAddress.Parse("127.0.0.1");
                IPAddress localAddr = IPAddress.Parse("0.0.0.0");

                // TcpListener server = new TcpListener(port);
                Console.Write("Server: Create TcpListener...\n");
                server = new TcpListener(localAddr, port);
                //server = new TcpListener(IPAddress.Any, port);

                // Start listening for client requests.
                Console.Write("Server: Start listening for client requests... \n");
                server.Start();

                // Buffer for reading data
                Byte[] bytes = new Byte[1024];
                String data  = null;

                // Enter the listening loop.
                while (true)
                {
                    Console.Write("Server: Waiting for a connection from clients or press ctrl+c to exit...\n");

                    // Perform a blocking call to accept requests.
                    // You could also user server.AcceptSocket() here.

                    TcpClient  client           = server.AcceptTcpClient();
                    IPEndPoint remoteIpEndPoint = client.Client.RemoteEndPoint as IPEndPoint;
                    IPEndPoint localIpEndPoint  = client.Client.LocalEndPoint as IPEndPoint;

                    Console.Write("Server: accepted client from {0}. \n", remoteIpEndPoint.Address);
                    Console.WriteLine("Server: Connected to client {0}!", remoteIpEndPoint.Address);

                    data = null;

                    // Get a stream object for reading and writing
                    NetworkStream stream = client.GetStream();

                    int i;

                    // Loop to receive all the data sent by the client.
                    Console.Write("Server: keep reading data from client {0}. \n", remoteIpEndPoint.Address);
                    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        // Translate data bytes to a ASCII string.
                        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                        Console.WriteLine("Server: Received message '{0}' from client {1} ", data, remoteIpEndPoint.Address);

                        // Process the data sent by the client.
                        data = data.ToUpper();
                        Console.WriteLine("Server: Convert client message to upcase");

                        byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

                        // Send back a response.
                        stream.Write(msg, 0, msg.Length);
                        Console.WriteLine("Server: Sent '{0}' back to client {1}", data, remoteIpEndPoint.Address);
                    }

                    // Shutdown and end connection
                    Console.WriteLine("Disconnect from client {0}", remoteIpEndPoint.Address);
                    client.Close();
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine("Server: SocketException: {0}", e);
            }
            finally
            {
                // Stop listening for new clients.
                server.Stop();
            }

            Console.WriteLine("\nServer: Hit enter to continue...");
            Console.Read();
        }
        else
        {
            Console.WriteLine("Usage: csServer <port number> \n");
        }
    }
            internal static object ConvertParameterStringToObject(Type desiredType, string parameters, object defaultObject)
            {
                try
                {
                    //DO NOT ADD CUSTOM CLASSES TO CONVERT TYPE! USE A DATABASE PRIMARY KEY INSTEAD!

                    //System Objects

                    #region Boolean

                    if (desiredType == typeof(Boolean))
                    {
                        Boolean output;
                        return(Boolean.TryParse(parameters, out output) ? output : defaultObject);
                    }

                    #endregion

                    #region Byte

                    if (desiredType == typeof(Byte))
                    {
                        Byte output;
                        return(Byte.TryParse(parameters, out output) ? output : defaultObject);
                    }

                    #endregion
                    #region SByte

                    if (desiredType == typeof(SByte))
                    {
                        SByte output;
                        return(SByte.TryParse(parameters, out output) ? output : defaultObject);
                    }

                    #endregion

                    #region Int16

                    if (desiredType == typeof(Int16))
                    {
                        Int16 output;
                        return(Int16.TryParse(parameters, out output) ? output : defaultObject);
                    }

                    #endregion
                    #region UInt16

                    if (desiredType == typeof(UInt16))
                    {
                        UInt16 output;
                        return(UInt16.TryParse(parameters, out output) ? output : defaultObject);
                    }

                    #endregion

                    #region Int32

                    if (desiredType == typeof(Int32))
                    {
                        Int32 output;
                        return(Int32.TryParse(parameters, out output) ? output : defaultObject);
                    }

                    #endregion
                    #region UInt32

                    if (desiredType == typeof(UInt32))
                    {
                        UInt32 output;
                        return(UInt32.TryParse(parameters, out output) ? output : defaultObject);
                    }

                    #endregion

                    #region Int64

                    if (desiredType == typeof(Int64))
                    {
                        Int64 output;
                        return(Int64.TryParse(parameters, out output) ? output : defaultObject);
                    }

                    #endregion
                    #region UInt64

                    if (desiredType == typeof(UInt64))
                    {
                        UInt64 output;
                        return(UInt64.TryParse(parameters, out output) ? output : defaultObject);
                    }

                    #endregion

                    #region Single

                    if (desiredType == typeof(Single))
                    {
                        Single output;
                        return(Single.TryParse(parameters, out output) ? output : defaultObject);
                    }

                    #endregion
                    #region Double

                    if (desiredType == typeof(Double))
                    {
                        Double output;
                        return(Double.TryParse(parameters, out output) ? output : defaultObject);
                    }

                    #endregion

                    #region IPAddress

                    if (desiredType == typeof(IHostAddress))
                    {
                        IHostAddress Default = defaultObject as IHostAddress;
                        try
                        {
                            IHostAddress HostAddress = ObjectFactory.CreateHostAddress(parameters);
                            return((Default.IpAddress.ToString() == HostAddress.IpAddress.ToString()) ? Default : HostAddress);
                        }
                        catch
                        {
                        }
                        return(defaultObject);
                    }

                    #endregion

                    #region String

                    if (desiredType == typeof(String))
                    {
                        return(parameters);
                    }

                    #endregion

                    //Units Of Measurement

                    #region Angle

                    if (desiredType == typeof(IAngle))
                    {
                        IAngle nullConversion; ObjectFactory.TryParse("0DEGREES", out nullConversion);
                        IAngle converted; ObjectFactory.TryParse(parameters, out converted);
                        return((converted.ToString() == nullConversion.ToString()) ? defaultObject : converted);
                    }

                    #endregion
                    #region Area

                    if (desiredType == typeof(IArea))
                    {
                        IArea nullConversion; ObjectFactory.TryParse("0SQUAREMETERS", out nullConversion);
                        IArea converted; ObjectFactory.TryParse(parameters, out converted);
                        return((converted.ToString() == nullConversion.ToString()) ? defaultObject : converted);
                    }

                    #endregion
                    #region Distance

                    if (desiredType == typeof(IDistance))
                    {
                        IDistance nullConversion; ObjectFactory.TryParse("0METERS", out nullConversion);
                        IDistance converted; ObjectFactory.TryParse(parameters, out converted);
                        return((converted.ToString() == nullConversion.ToString()) ? defaultObject : converted);
                    }

                    #endregion
                    #region Durations

                    if (desiredType == typeof(IDate))
                    {
                        IDate nullConversion = ObjectFactory.CreateDate("");
                        IDate converted      = ObjectFactory.CreateDate(parameters);
                        return((converted.ToString() == nullConversion.ToString()) ? defaultObject : converted);
                    }
                    if (desiredType == typeof(IDateTime))
                    {
                        IDateTime nullConversion = ObjectFactory.CreateDateTime("");
                        IDateTime converted      = ObjectFactory.CreateDateTime(parameters);
                        return((converted.ToString() == nullConversion.ToSystemString()) ? defaultObject : converted);
                    }
                    if (desiredType == typeof(ITime))
                    {
                        ITime nullConversion = ObjectFactory.CreateTime("");
                        ITime converted      = ObjectFactory.CreateTime(parameters);
                        return((converted.ToString() == nullConversion.ToString()) ? defaultObject : converted);
                    }
                    if (desiredType == typeof(ITimeSpan))
                    {
                        ITimeSpan nullConversion = ObjectFactory.CreateTimeSpan("");
                        ITimeSpan converted      = ObjectFactory.CreateTimeSpan(parameters);
                        return((converted.ToString() == nullConversion.ToString()) ? defaultObject : converted);
                    }

                    #endregion
                    #region Energy

                    if (desiredType == typeof(IEnergy))
                    {
                        IEnergy nullConversion; ObjectFactory.TryParse("0KILOJOULES", out nullConversion);
                        IEnergy converted; ObjectFactory.TryParse(parameters, out converted);
                        return((converted.ToString() == nullConversion.ToString()) ? defaultObject : converted);
                    }

                    #endregion
                    #region Mass

                    if (desiredType == typeof(IMass))
                    {
                        IMass nullConversion; ObjectFactory.TryParse("0KILOGRAMS", out nullConversion);
                        IMass converted; ObjectFactory.TryParse(parameters, out converted);
                        return((converted.ToString() == nullConversion.ToString()) ? defaultObject : converted);
                    }

                    #endregion
                    #region Power

                    if (desiredType == typeof(IPower))
                    {
                        IPower nullConversion; ObjectFactory.TryParse("0KILOWATTS", out nullConversion);
                        IPower converted; ObjectFactory.TryParse(parameters, out converted);
                        return((converted.ToString() == nullConversion.ToString()) ? defaultObject : converted);
                    }

                    #endregion
                    #region Pressure

                    if (desiredType == typeof(IPressure))
                    {
                        IPressure nullConversion; ObjectFactory.TryParse("0PASCALS", out nullConversion);
                        IPressure converted; ObjectFactory.TryParse(parameters, out converted);
                        return((converted.ToString() == nullConversion.ToString()) ? defaultObject : converted);
                    }

                    #endregion
                    #region Speed

                    if (desiredType == typeof(ISpeed))
                    {
                        ISpeed nullConversion; ObjectFactory.TryParse("0M/SEC", out nullConversion);
                        ISpeed converted; ObjectFactory.TryParse(parameters, out converted);
                        return((converted.ToString() == nullConversion.ToString()) ? defaultObject : converted);
                    }

                    #endregion
                    #region Temperature

                    if (desiredType == typeof(ITemperature))
                    {
                        ITemperature nullConversion; ObjectFactory.TryParse("0CELCIUS", out nullConversion);
                        ITemperature converted; ObjectFactory.TryParse(parameters, out converted);
                        return((converted.ToString() == nullConversion.ToString()) ? defaultObject : converted);
                    }

                    #endregion
                    #region Volume

                    if (desiredType == typeof(IVolume))
                    {
                        IVolume nullConversion; ObjectFactory.TryParse("0LITRES", out nullConversion);
                        IVolume converted; ObjectFactory.TryParse(parameters, out converted);
                        return((converted.ToString() == nullConversion.ToString()) ? defaultObject : converted);
                    }

                    #endregion

                    //Colors

                    #region XRGBColor

                    if (desiredType == typeof(I24BitColor))
                    {
                        string[] split = parameters.Split(' ');

                        byte red   = 255;
                        byte green = 255;
                        byte blue  = 255;

                        I24BitColor Default = defaultObject as I24BitColor;

                        if (split.Length < 3)
                        {
                            return(Default);
                        }

                        try
                        {
                            red   = Convert.ToByte(split[0]);
                            green = Convert.ToByte(split[1]);
                            blue  = Convert.ToByte(split[2]);
                        }
                        catch (OverflowException)
                        {
                            //Debug
                            return(Default);
                        }
                        catch (FormatException)
                        {
                            //Debug
                            return(Default);
                        }
                        I24BitColor output = ObjectFactory.CreateColor(red, green, blue).Get24BitColor();
                        return(output);
                    }

                    #endregion
                }
                catch (Exception e)
                {
                    Debug.AddErrorMessage(e, "Error converting setting from string.");
                }
                return(defaultObject);
            }
示例#38
0
        private void GetHistory(OleDocument doc)
        {
            using (Stream WordDocument = doc.OpenStream("WordDocument"))
            {
                if (WordDocument == null)
                {
                    return;
                }
                BinaryReader br = new BinaryReader(WordDocument);
                WordDocument.Seek(0xB, SeekOrigin.Begin);
                Byte tipo = br.ReadByte();

                WordDocument.Seek(0x2D2, SeekOrigin.Begin);
                UInt32 dir = br.ReadUInt32();
                UInt32 tam = br.ReadUInt32();
                if (tam > 0)
                {
                    using (var table = doc.OpenStream((tipo & 2) == 2 ? "1Table" : "0Table"))
                    {
                        table.Seek(dir, SeekOrigin.Begin);
                        br = new BinaryReader(table);
                        Boolean unicode        = br.ReadUInt16() == 0xFFFF;
                        UInt32  nroCadenas     = br.ReadUInt16();
                        UInt32  extraDataTable = br.ReadUInt16();
                        for (int i = 0; i < nroCadenas; i += 2)
                        {
                            UInt16 strSize = br.ReadUInt16();
                            string author;
                            if (unicode)
                            {
                                Byte[] cadena = br.ReadBytes(strSize * 2);
                                author = Encoding.Unicode.GetString(cadena).Replace('\0', ' ');
                            }
                            else
                            {
                                Byte[] cadena = br.ReadBytes(strSize);
                                author = Encoding.Default.GetString(cadena).Replace('\0', ' ');
                            }
                            History hi = new History(author);

                            this.foundMetadata.Add(new User(author, false, "History"));

                            strSize = br.ReadUInt16();
                            if (unicode)
                            {
                                Byte[] cadena = br.ReadBytes(strSize * 2);
                                hi.Path = Encoding.Unicode.GetString(cadena).Replace('\0', ' ');
                            }
                            else
                            {
                                Byte[] cadena = br.ReadBytes(strSize);
                                hi.Path = Encoding.Default.GetString(cadena).Replace('\0', ' ');
                            }
                            this.foundMetadata.Add(hi);
                            bool isComputerPath = false;

                            foreach (User ui in this.foundMetadata.Users)
                            {
                                if (hi.Value.Trim() == ui.Value.Trim())
                                {
                                    isComputerPath = ui.IsComputerUser;
                                }
                            }
                            this.foundMetadata.Add(new Diagrams.Path(PathAnalysis.CleanPath(hi.Path), isComputerPath));
                        }
                    }
                }
            }
        }
示例#39
0
        internal static bool BuildHFS0(string inDir, string outFile, SHA256 sha)
        {
            Console.WriteLine("Building {0} from folder {1}...", outFile, inDir);


            hfs0_header header = new hfs0_header();

            header.Magic = 0x30534648; // HFS0

            List <hfs0_file_entry> fileEntries = new List <hfs0_file_entry>();
            List <string>          stringTable = new List <string>();

            char[]       objPath = new char[256];
            FileStream   fs;
            BinaryWriter bw;

            // Opening output file
            try
            {
                fs = new FileStream(outFile, FileMode.Create, FileAccess.Write);
                bw = new BinaryWriter(fs);
            }
            catch (Exception ex)
            {
                Console.WriteLine("[ERR] Cannot create {0}.\n{1}", outFile, ex.Message);
                return(false);
            }

            // Opening input directory
            if (!Directory.Exists(inDir))
            {
                Console.WriteLine("[ERR] Input folder {0} does not exist.", inDir);
                return(false);
            }

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

            foreach (string file in Directory.GetFiles(inDir))
            {
                inputFiles.Add(Path.GetFileName(file));
            }


            // Handling root partitions for correct partition order
            if (inputFiles.Count >= 3 && inputFiles.Count <= 4 && inputFiles.Contains("secure") && inputFiles.Contains("normal") && inputFiles.Contains("update"))
            {
                if (inputFiles.Contains("logo"))
                {
                    Console.WriteLine("Treating {0} as CARD2 root hfs0", outFile);
                    inputFiles = new List <string>();
                    inputFiles.Add("update");
                    inputFiles.Add("normal");
                    inputFiles.Add("secure");
                    inputFiles.Add("logo");
                }
                else if (inputFiles.Count == 3)
                {
                    Console.WriteLine("Treating {0} as CARD1 root hfs0", outFile);
                    inputFiles = new List <string>();
                    inputFiles.Add("update");
                    inputFiles.Add("normal");
                    inputFiles.Add("secure");
                }
            }

            // Number of files in HFS0 archive
            header.NumberOfFiles = Convert.ToUInt32(inputFiles.Count);

            header.StringTableSize = 0;

            UInt64 fileEntry_relativeOffset = 0;

            // Building stringtable



            foreach (string file in inputFiles)
            {
                var absPath = Path.Combine(inDir, file);
                stringTable.Add(file);

                FileStream      inputFS       = new FileStream(absPath, FileMode.Open, FileAccess.Read);
                BinaryReader    inputFSReader = new BinaryReader(inputFS);
                hfs0_file_entry fileEntry     = new hfs0_file_entry();

                fileEntry.Offset = Convert.ToUInt64(fileEntry_relativeOffset);
                fileEntry.Size   = Convert.ToUInt64(inputFS.Length);

                UInt64 paddedSize = Convert.ToUInt64(Math.Ceiling((double)fileEntry.Size / (double)0x200) * 0x200);
                fileEntry_relativeOffset += paddedSize;



                if (fileEntry.Size > 0x200)
                {
                    fileEntry.HashedSize = 0x200;
                }
                else
                {
                    fileEntry.HashedSize = Convert.ToUInt32(fileEntry.Size);
                }

                byte[] dataToHash = new byte[fileEntry.HashedSize];
                inputFSReader.Read(dataToHash, 0, dataToHash.Length);

                inputFSReader.Close();
                inputFS.Close();

                fileEntry.StringTableOffset = header.StringTableSize;
                fileEntry.FileHash          = sha.ComputeHash(dataToHash);


                header.StringTableSize += Convert.ToUInt32(file.Length + 1);

                fileEntries.Add(fileEntry);
            }

            // Calculate padding fo alignment
            ulong bytesWrittenUntilNow       = HFS0_HEADER_LENGTH + (HFS0_ENTRY_LENGTH * header.NumberOfFiles) + header.StringTableSize;
            ulong bytesWrittenUntilNowPadded = Convert.ToUInt64(Math.Ceiling((double)bytesWrittenUntilNow / (double)0x200) * 0x200);
            ulong bytesWrittenUntilNowDif    = bytesWrittenUntilNowPadded - bytesWrittenUntilNow;

            header.StringTableSize += Convert.ToUInt32(bytesWrittenUntilNowDif);

            bw.Write(Utils.StructureToByteArray(header));
            foreach (hfs0_file_entry fileEntry in fileEntries)
            {
                bw.Write(Utils.StructureToByteArray(fileEntry));
            }
            foreach (string str in stringTable)
            {
                bw.Write(str.ToCharArray());
                bw.Write((byte)0x00);
            }
            // Fill padding
            for (ulong i = 0; i < bytesWrittenUntilNowDif; i++)
            {
                bw.Write((byte)0x0);
            }
            foreach (string file in inputFiles)
            {
                var        absPath = Path.Combine(inDir, file);
                FileStream stream  = new FileStream(absPath, FileMode.Open, FileAccess.Read);
                byte[]     buffer  = new Byte[1024 * 5];
                int        count   = 0;
                while ((count = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    bw.Write(buffer, 0, count);
                }

                ulong paddedLength = Convert.ToUInt64(Math.Ceiling((double)stream.Length / (double)0x200) * 0x200);

                ulong difference = paddedLength - Convert.ToUInt64(stream.Length);

                for (ulong i = 0; i < difference; i++)
                {
                    bw.Write((byte)0x0);
                }
                stream.Close();
            }
            bw.Close();
            fs.Close();



            Console.WriteLine("Operation successful");
            return(true);
        }
示例#40
0
        /// <summary>
        /// method to send the data to notify engine using TDC/IP
        /// </summary>
        /// <param name="data"></param>
        static void Send(string data)
        {
            if (_server == string.Empty || _port == 0)
            {
                WriteLine("\nWARNING! You must specify the server and port to connect and execute notification component. \n");
                DisplayHelp("connect");
                return;
            }

            WriteLine("\nExecuting (Remotehost - " + _server + ":" + _port + ")....\n");


            Console.ForegroundColor = ConsoleColor.White;

            TcpClient     client = null;
            NetworkStream stream = null;

            try
            {
                client = new TcpClient(_server, _port);

                // Translate the passed message into ASCII and store it as a Byte array.
                Byte[] buffer = System.Text.Encoding.ASCII.GetBytes(data);

                // Get a client stream for reading and writing.
                //  Stream stream = client.GetStream();

                stream = client.GetStream();

                // Send the message to the connected TcpServer.
                stream.Write(buffer, 0, buffer.Length);

                // Receive the TcpServer.response.
                // Buffer to store the response bytes.
                buffer = new Byte[1024];

                // String to store the response ASCII representation.
                String responseData = String.Empty;

                // Read the first batch of the TcpServer response bytes.
                Int32 bytes = stream.Read(buffer, 0, buffer.Length);
                responseData = System.Text.Encoding.ASCII.GetString(buffer, 0, bytes);



                WriteLine("\n-------------------------------------\n");
                WriteLine("Result:");
                WriteLine("\n-------------------------------------\n");
                DisplayOutput(responseData);
                WriteLine("\n-------------------------------------\n");
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                WriteLine("\n");
                WriteLine("\nERROR : " + ex.Message);
                WriteLine("\n\n");
            }

            finally
            {
                Console.ForegroundColor = ConsoleColor.Gray;
                // Close everything.
                if (stream != null)
                {
                    stream.Close();
                }
                if (client != null)
                {
                    client.Close();
                }
            }
        }
示例#41
0
        private void convertToArray(Bitmap bitmap)
        {
            int         width     = bitmap.Width;
            int         high      = bitmap.Height;
            string      newString = "";
            int         pixel     = 0;
            Byte        ch        = 0;
            List <Byte> byteList  = new List <byte>();

            if (cb_text.Checked)
            {
                newString += "unsigned char yize_image[1024]={\r\n";
            }
            for (int page = 0; page < 8; page++)
            {
                for (int i = 0; i < 128; i++)
                {
                    for (int j = page * 8; j < page * 8 + 8; j++)
                    {
                        Color color = bitmap.GetPixel(i, j);
                        if ((color.R + color.G + color.B) < Convert.ToInt32(nud_yuzhi.Value))
                        {
                            pixel = 0;
                        }
                        else
                        {
                            pixel = 1;
                        }
                        if (j % 8 == 0)
                        {
                            //byteList.Add(ch);

                            if (cb_ascii.Checked)
                            {
                                newString += ch.ToString("X2") + " ";
                            }
                            else if (cb_text.Checked)
                            {
                                newString += ch + ",";
                            }

                            ch = 0;
                        }
                        if (pixel == 1)
                        {
                            ch |= (Byte)(1 << (j % 8));
                        }
                    }
                }
                if (cb_text.Checked)
                {
                    newString += "\r\n";
                }
            }
            //byteList.ToString();
            if (cb_text.Checked)
            {
                newString += "};";
            }
            tb_data.Text = newString;
        }
示例#42
0
 public LogicElementHeaderZLIB(Int32 compressionFlag, Int32 compressedDataLength, Byte compressionAlgorithm)
 {
     CompressionFlag      = compressionFlag;
     CompressedDataLength = compressedDataLength;
     CompressionAlgorithm = compressionAlgorithm;
 }
 void TestSkipIfKeyNotPressedInstruction(byte[] byteCode, Byte keyNum) => TestParseInstruction(byteCode, new BinaryRegisterOperationStub(ParsedInstructionCode.SkipIfKeyNot, keyNum));
示例#44
0
 /// <summary>
 /// 将一个 1位CHAR转换成1位的BYTE[]
 /// </summary>
 /// <param name="data"></param>
 /// <returns></returns>
 public static Byte[] GetSocketBytes(Char data)
 {
     Byte[] bytes = new Byte[] { (Byte)data };
     return(bytes);
 }
 void TestGenerateRandomInstruction(byte[] byteCode, Byte regNum0, Byte regNum1) => TestParseInstruction(byteCode, new BinaryRegisterOperationStub(ParsedInstructionCode.GenRandom, regNum0, regNum1));
示例#46
0
 public void SetAge(Byte Age)
 {
     this.Age = Age;
 }
示例#47
0
 public static DHCPv6PacketIdentityAssociationPrefixDelegationOption AsSuccess(UInt32 id, TimeSpan T1, TimeSpan T2, Byte prefixLength, IPv6Address prefixAddress, TimeSpan preferredLifetime, TimeSpan validLifetime) =>
 new DHCPv6PacketIdentityAssociationPrefixDelegationOption(id, T1, T2, new List <DHCPv6PacketSuboption>
 {
     new DHCPv6PacketIdentityAssociationPrefixDelegationSuboption(preferredLifetime, validLifetime, prefixLength, prefixAddress, new List <DHCPv6PacketSuboption>
     {
         new DHCPv6PacketStatusCodeSuboption(DHCPv6StatusCodes.Success, "have a good lease"),
     })
 });
 public OneByteDecoder()
 {
     data = 0x00;
 }
 public void Decode(ref Byte[] bytes, ref int index)
 {
     data = bytes[index];
     ++index;
 }
示例#50
0
        private static void generateCube3FromBFBFile(String FileName, String cube3FileName)
        {
            Encoding encoding = Encoding.ASCII;

            PaddedBufferedBlockCipher cipher;

            if (FileName != null || FileName.Length > 0)
            {
                try
                {
                    using (var inFile = File.OpenRead(FileName))
                        using (var streamReader = new StreamReader(inFile))
                        {
                            var inputBFBFile = streamReader.ReadToEnd();

                            try
                            {
                                ZeroBytePadding padding = new ZeroBytePadding();
                                cipher = new PaddedBufferedBlockCipher(engine, padding);

                                // create the key parameter
                                Byte[]       keyBytes = encoding.GetBytes(key);
                                KeyParameter param    = new KeyParameter(encoding.GetBytes(key));

                                // initalize the cipher
                                cipher.Init(true, new KeyParameter(keyBytes));

                                Byte[] newDataModel = encoding.GetBytes(inputBFBFile);

                                Byte[] encodedBytes = new Byte[cipher.GetOutputSize(newDataModel.Length)];

                                int encodedLength = cipher.ProcessBytes(newDataModel, 0, newDataModel.Length, encodedBytes, 0);
                                cipher.DoFinal(encodedBytes, encodedLength);

                                FileBackup.MakeBackup(cube3FileName, 5);

                                using (var outFile = File.OpenWrite(cube3FileName))
                                    using (var binaryWriter = new BinaryWriter(outFile))
                                    {
                                        binaryWriter.Write(encodedBytes);
                                        outFile.Close();
                                    }
                            }
                            catch (IOException)
                            {
                                Console.WriteLine($"Unable to process BFB File [{FileName}] or unable to open output file [{cube3FileName}]");
                                Environment.Exit(-1);
                            }
                        }
                }
                catch (SecurityException ex)
                {
                    Console.WriteLine($"Security error\n\nError message: {ex.Message}\n\n" +
                                      $"Details:\n\n{ex.StackTrace}");
                    Environment.Exit(ex.HResult);
                }
            }
            else
            {
                throw new SecurityException("No File specified!");
            }
        }
示例#51
0
 /// <summary>
 /// Write a byte
 /// </summary>
 /// <param name="value">Value</param>
 public void WriteByte(Byte value)
 {
     buffer.Add(value);
     Position++;
 }
 void TestAddRegisterValueInstruction(byte[] byteCode, Byte regNum0, Byte value) => TestParseInstruction(byteCode, new BinaryRegisterOperationStub(ParsedInstructionCode.AddRegValue, regNum0, value));
示例#53
0
文件: Size.cs 项目: zyjia/dbatools
 /// <inheritdoc cref="IComparable{Size}.CompareTo"/>
 /// <remarks>For sorting</remarks>
 public int CompareTo(Size obj)
 {
     return(Byte.CompareTo(obj.Byte));
 }
 void TestSkifIfRegistersEqualInstruction(byte[] byteCode, Byte regNum0, Byte regNum1) => TestParseInstruction(byteCode, new BinaryRegisterOperationStub(ParsedInstructionCode.SkipIfRegReg, regNum0, regNum1));
示例#55
0
文件: Size.cs 项目: zyjia/dbatools
 /// <inheritdoc cref="Int64.GetHashCode"/>
 /// <remarks>The hashcode of the underlying size</remarks>
 public override int GetHashCode()
 {
     // ReSharper disable once NonReadonlyMemberInGetHashCode
     return(Byte.GetHashCode());
 }
 void TestSkifIfRegisterNotEqualInstruction(byte[] byteCode, Byte regNum, Byte value) => TestParseInstruction(byteCode, new BinaryRegisterOperationStub(ParsedInstructionCode.SkipIfNotRegValue, regNum, value));
        protected object ParseValue(object value, Type typeToConvert)
        {
            if (typeToConvert == typeof(String))
            {
                return(value.ToString());
            }

            if (typeToConvert == typeof(Char))
            {
                return(Char.Parse(value.ToString()));
            }

            if (typeToConvert == typeof(Boolean))
            {
                var valueType = value.GetType();

                if (valueType == typeof(Int16) ||
                    valueType == typeof(Int32) ||
                    valueType == typeof(Int64) ||
                    valueType == typeof(UInt16) ||
                    valueType == typeof(UInt32) ||
                    valueType == typeof(UInt64))
                {
                    return(value.ToString().Equals("1"));
                }

                if (TRUE_STRING.Contains(value.ToString()))
                {
                    return(true);
                }

                if (value.GetType() == typeof(Boolean))
                {
                    return(value);
                }

                return(false);
            }

            if (typeToConvert == typeof(Byte))
            {
                return(Byte.Parse(value.ToString()));
            }

            if (typeToConvert == typeof(SByte))
            {
                return(SByte.Parse(value.ToString()));
            }

            if (typeToConvert == typeof(Int16))
            {
                return(Int16.Parse(value.ToString()));
            }

            if (typeToConvert == typeof(Int32))
            {
                return(Int32.Parse(value.ToString()));
            }

            if (typeToConvert == typeof(Int64))
            {
                return(Int64.Parse(value.ToString()));
            }

            if (typeToConvert == typeof(UInt16))
            {
                return(UInt16.Parse(value.ToString()));
            }

            if (typeToConvert == typeof(UInt32))
            {
                return(UInt32.Parse(value.ToString()));
            }

            if (typeToConvert == typeof(UInt64))
            {
                return(UInt64.Parse(value.ToString()));
            }

            if (typeToConvert == typeof(Double))
            {
                return(Double.Parse(value.ToString()));
            }

            if (typeToConvert == typeof(Decimal))
            {
                return(Decimal.Parse(value.ToString()));
            }

            if (typeToConvert == typeof(DateTime))
            {
                return(DateTime.Parse(value.ToString()));
            }

            return(null);
        }
示例#58
0
        public static void StartListening(string host, int port)
        {
            // Data buffer for incoming data.
            byte[] bytes = new Byte[1024];

            // Establish the local endpoint for the socket.
            // Dns.GetHostName returns the name of the
            // host running the application.
            IPHostEntry ipHostInfo = Dns.GetHostEntry(host);
            IPAddress   ipAddress  = ipHostInfo.AddressList[1];

            Console.WriteLine($"Server IP:{ipAddress}");

            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);

            // Create a TCP/IP socket.
            Socket listener = new Socket(ipAddress.AddressFamily,
                                         SocketType.Stream, ProtocolType.Tcp);

            // Bind the socket to the local endpoint and
            // listen for incoming connections.
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(10);

                // Start listening for connections.
                while (true)
                {
                    Console.WriteLine("Waiting for a connection...");
                    // Program is suspended while waiting for an incoming connection.
                    Socket handler = listener.Accept();
                    data = null;

                    // An incoming connection needs to be processed.
                    while (true)
                    {
                        int bytesRec = handler.Receive(bytes);
                        data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                        // Show the data on the console.
                        Console.WriteLine("Text received : {0}", data);

                        // Echo the data back to the client.
                        byte[] replay = Encoding.ASCII.GetBytes(data);

                        handler.Send(replay);
                        if (data.IndexOf("<EOF>") > -1)
                        {
                            break;
                        }
                    }

                    // Show the data on the console.
                    Console.WriteLine("Text received : {0}", data);

                    // Echo the data back to the client.
                    byte[] msg = Encoding.ASCII.GetBytes(data);

                    handler.Send(msg);
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            Console.WriteLine("\nPress ENTER to continue...");
            Console.Read();
        }
示例#59
0
        private void beginRead(TcpClient akTcpClient)
        {
            if (!disposed && akTcpClient.Connected == false)
            {
                if (ConnectionClosed != null && this.State == Status.CONNECTED)
                {
                    if (context == null)
                    {
                        ConnectionClosed(tcpClient);
                    }
                    else
                    {
                        context.Post(delegate { ConnectionClosed(tcpClient); }, null);
                    }
                }

                //if (this.State != Status.CONNECTING)
                StopInternal();

                if (!AllowMultipleClients || connection_active)
                {
                    if (AutoReConnect && this.State != Status.CONNECTING)
                    {
                        Start();
                    }
                }
                return;
            }

            if (!disposed)
            {
                try
                {
                    if (readBytesPerCennection.ContainsKey(akTcpClient))
                    {
                        readBytesPerCennection.Remove(akTcpClient);
                        readBytesCountPerCennection.Remove(akTcpClient);
                    }
                    byte[] readBytes;

                    if (fixedLength <= 0)
                    {
                        readBytes = new Byte[65536];
                    }
                    else
                    {
                        readBytes = new Byte[fixedLength];
                    }

                    readBytesPerCennection.Add(akTcpClient, readBytes);
                    readBytesCountPerCennection.Add(akTcpClient, 0);

                    akTcpClient.Client.BeginReceive(readBytes, 0, readBytes.Length, SocketFlags.None, new AsyncCallback(DoReadCallback), akTcpClient);
                }
                catch (Exception ex)
                {
                    string sMsg = DateTime.Now.ToString() + " - " + "TCPSocketClientAndServer.beginRead(TcpClient) - error: " + ex.Message;
                    this.LastErrorMessage = sMsg;

                    if (ex is SocketException) // && ((SocketException)ex).ErrorCode == 10060)
                    {
                        if (ConnectionClosed != null && this.State == Status.CONNECTED)
                        {
                            if (context == null)
                            {
                                ConnectionClosed(tcpClient);
                            }
                            else
                            {
                                context.Post(delegate { ConnectionClosed(tcpClient); }, null);
                            }
                        }

                        //if (this.State != Status.CONNECTING)
                        StopInternal();

                        if (!AllowMultipleClients || connection_active)
                        {
                            if (AutoReConnect && this.State != Status.CONNECTING)
                            {
                                Start();
                            }
                        }
                    }
                    else
                    {
                        if (AsynchronousExceptionOccured != null)
                        {
                            AsynchronousExceptionOccured(this, new ThreadExceptionEventArgs(ex));
                        }
                    }
                }
            }
        }
示例#60
0
        static void Main(string[] args)
        {
            try
            {
                // Create a TcpClient.
                // Note, for this client to work you need to have a TcpServer
                // connected to the same address as specified by the server, port
                // combination.
                TcpClient client = new TcpClient("127.0.0.1", 5678);


                /*********************************************/
                /*********************************************/
                // Write - Send message to the TcpServer
                /*********************************************/
                /*********************************************/
                string message = "HI from client";

                // Translate the passed message into ASCII and store it as a Byte array.
                Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);

                // Get a client stream for reading and writing.
                //  Stream stream = client.GetStream();

                NetworkStream stream = client.GetStream();

                // Send the message to the connected TcpServer.
                stream.Write(data, 0, data.Length);

                Console.WriteLine("Sent: {0}", message);

                /*********************************************/
                /*********************************************/
                // READ - Receive the TcpServer.response.
                /*********************************************/
                /*********************************************/

                // Buffer to store the response bytes.
                data = new Byte[256];

                // String to store the response ASCII representation.
                String responseData = String.Empty;

                // Read the first batch of the TcpServer response bytes.
                Int32 bytes = stream.Read(data, 0, data.Length);
                responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                Console.WriteLine("Received: {0}", responseData);

                // Close everything.
                // stream.Close();
                // client.Close();
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("ArgumentNullException: {0}", e);
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }

            Console.WriteLine("\n Press Enter to continue...");
            Console.Read();
        }