ToString() публичный Метод

public ToString ( ) : string
Результат string
Пример #1
0
        static void Main(string[] args)
        {
            string data = "";
            byte[] sendBytes = new Byte[1024];
            byte[] rcvPacket = new Byte[1024];
            UdpClient client = new UdpClient();
            IPAddress address = IPAddress.Parse(IPAddress.Broadcast.ToString());
            client.Connect(address, 8008);
            IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);

            Console.WriteLine("Client is Started");
            Console.WriteLine("Type your message");

            while (data != "q")
            {
                data = Console.ReadLine();
                sendBytes = Encoding.ASCII.GetBytes(DateTime.Now.ToString() + " " + data);
                client.Send(sendBytes, sendBytes.GetLength(0));
                rcvPacket = client.Receive(ref remoteIPEndPoint);

                string rcvData = Encoding.ASCII.GetString(rcvPacket);
                Console.WriteLine("Handling client at " + remoteIPEndPoint + " - ");

                Console.WriteLine("Message Received: " + rcvPacket.ToString());
            }
            Console.WriteLine("Close Port Command Sent");  //user feedback
            Console.ReadLine();
            client.Close();  //close connection
        }
 /// <summary>
 /// Clears all historical control data (i.e. power on/off) associated with a numbered fan.
 /// </summary>
 /// <param name="fanNumber">Numbered fan to clear historical data from.</param>
 /// <returns>Asynchronous Processing Task.</returns>
 public async Task ClearFanCtrlData(Byte fanNumber)
 {
     //Call Worker.
     await RESTWorker("/MooseBox/API/v1.0/peripherals/fan/data/clear",
                      Method.DELETE,
                      restRequest => { restRequest.AddQueryParameter(ParamFanNumber, fanNumber.ToString()); });
 }
Пример #3
0
 public PacketHead(object head, Type type, int _progress = 0)
 {
     System.Byte Vaul = (System.Byte)Enum.Parse(type, head.ToString());
     Head     = byte.Parse(Vaul.ToString());
     Text     = head.ToString();
     Progress = _progress;
     Type     = type;
 }
 public void CheckByte(Byte value, string format)
 {
     var parsed = Format.Parse(format);
     var formatter = new StringFormatter(pool);
     formatter.Append(value, parsed);
     var result = formatter.ToString();
     var clrResult = value.ToString(format, CultureInfo.InvariantCulture);
     Assert.Equal(clrResult, result);
 }
        /// <summary>
        /// 文字列に変換する
        /// </summary>
        public override string ToString()
        {
            var text = new StringBuilder();

            text.AppendLine("{");
            text.AppendLine(nameof(SequenceNumber) + "=" + SequenceNumber.ToString());
            text.AppendLine(ToInnerString());
            text.AppendLine("}");
            return(text.ToString());
        }
Пример #6
0
        static void Main(string[] args)
        {
            if (args.Length > 1)
                throw new ArgumentException("Params : <[Port]>");
            int servPort = (args.Length == 1) ? Int32.Parse(args[0]) : 2500;
            TcpListener listner = null;

            try
            {
                listner = new TcpListener(IPAddress.Any, servPort);
                listner.Start();
                Console.WriteLine("Waiting for a connection ..... ");
            }
            catch (SocketException e)
            {
                Console.WriteLine(e.ErrorCode + ":" + e.Message);
                Environment.Exit(e.ErrorCode);
            }

            byte[] rcvBuffer = new Byte[BUFSIZE];

            int byteRcv;

            while (true)
            {
               Socket sock = null;

                try
                {
                    sock = listner.AcceptSocket();

                    Console.Write("Handling Client at " + sock.RemoteEndPoint + " : ");
                    int totalBytesEchoed = 0;

                  while ((byteRcv = sock.Receive(rcvBuffer, 0, rcvBuffer.Length, SocketFlags.None)) > 0)
                    {
                        string caps = Encoding.ASCII.GetString(rcvBuffer);
                        caps.ToUpper();
                        rcvBuffer = Encoding.ASCII.GetBytes(caps);
                        sock.Send(rcvBuffer, 0, byteRcv, SocketFlags.None);
                        totalBytesEchoed += byteRcv;
                    }
                    Console.WriteLine("Sent : " + rcvBuffer.ToString());
                    Console.WriteLine("Echoed {0} bytes.", totalBytesEchoed);

                    sock.Close();

                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    sock.Close();
                }
            }
        }
 /// <summary>
 /// Manually powers on/off a USB fan in the event it does not conflict with Fan Automation.
 /// </summary>
 /// <param name="fanNumber">Numbered fan to power on or off.</param>
 /// <param name="powerOn">true to power fan; false to unpower.</param>
 /// <returns>Asynchronous processing task.</returns>
 public async Task PowerFanCtrl(Byte fanNumber, bool powerOn)
 {
     //Call Worker.
     await RESTWorker("/MooseBox/API/v1.0/control/fan/power",
                      Method.PUT,
                      restRequest =>
                      {
                          restRequest.AddQueryParameter(ParamFanNumber, fanNumber.ToString());
                          restRequest.AddQueryParameter(ParamPowerOn, powerOn.ToString().ToLower());
                      });
 }
Пример #8
0
        public void delete(System.Byte key)
        {
            SqlCommand commDelete = new SqlCommand(" DELETE FROM parm_CSFPRoutes WHERE Id=" + key.ToString(), conn);

            command = new SqlCommand("SELECT * FROM parm_CSFPRoutes WHERE Id=" + key.ToString(), conn);
            dadAdpt = new SqlDataAdapter(command);
            dadAdpt.DeleteCommand = commDelete;
            dadAdpt.SelectCommand = command;
            dset.Clear();
            dadAdpt.Fill(dset, tbName);
            dset.Tables[tbName].Rows[0].Delete();
            dadAdpt.Update(dset, tbName);
        }
Пример #9
0
        static StackObject *ToString_0(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 1);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Byte instance_of_this_method = GetInstance(__domain, ptr_of_this_method, __mStack);

            var result_of_this_method = instance_of_this_method.ToString();

            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
Пример #10
0
    static int ToString(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 1 && TypeChecker.CheckTypes(L, 1, typeof(byte)))
            {
                System.Byte obj = (System.Byte)ToLua.ToObject(L, 1);
                string      o   = obj.ToString();
                LuaDLL.lua_pushstring(L, o);
                return(1);
            }
            else if (count == 2 && TypeChecker.CheckTypes(L, 1, typeof(byte), typeof(System.IFormatProvider)))
            {
                System.Byte            obj  = (System.Byte)ToLua.ToObject(L, 1);
                System.IFormatProvider arg0 = (System.IFormatProvider)ToLua.ToObject(L, 2);
                string o = obj.ToString(arg0);
                LuaDLL.lua_pushstring(L, o);
                return(1);
            }
            else if (count == 2 && TypeChecker.CheckTypes(L, 1, typeof(byte), typeof(string)))
            {
                System.Byte obj  = (System.Byte)ToLua.ToObject(L, 1);
                string      arg0 = ToLua.ToString(L, 2);
                string      o    = obj.ToString(arg0);
                LuaDLL.lua_pushstring(L, o);
                return(1);
            }
            else if (count == 3 && TypeChecker.CheckTypes(L, 1, typeof(byte), typeof(string), typeof(System.IFormatProvider)))
            {
                System.Byte            obj  = (System.Byte)ToLua.ToObject(L, 1);
                string                 arg0 = ToLua.ToString(L, 2);
                System.IFormatProvider arg1 = (System.IFormatProvider)ToLua.ToObject(L, 3);
                string                 o    = obj.ToString(arg0, arg1);
                LuaDLL.lua_pushstring(L, o);
                return(1);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: System.Byte.ToString"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
Пример #11
0
        static StackObject *ToString_13(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 2);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.IFormatProvider provider = (System.IFormatProvider) typeof(System.IFormatProvider).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);
            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.Byte instance_of_this_method = GetInstance(__domain, ptr_of_this_method, __mStack);

            var result_of_this_method = instance_of_this_method.ToString(provider);

            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
Пример #12
0
		///<summary>The only valid input is a value between 0 and 15.  Text returned will be 1-9 or a-f.</summary>
		private static string ByteToStr(Byte byteVal) {
			//No need to check RemotingRole; no call to db.
			switch(byteVal) {
				case 10:
					return "a";
				case 11:
					return "b";
				case 12:
					return "c";
				case 13:
					return "d";
				case 14:
					return "e";
				case 15:
					return "f";
				default:
					return byteVal.ToString();
			}
		}
Пример #13
0
 public void open(System.Byte key)
 {
     try
     {
         if (conn.State == ConnectionState.Closed)
         {
             conn.Open();
         }
         command = new SqlCommand("SELECT * FROM " + tbName + " WHERE Id=" + key.ToString(), conn);
         dadAdpt = new SqlDataAdapter(command);
         dadAdpt.SelectCommand = command;
         dset.Clear();
         dadAdpt.Fill(dset, tbName);
         if (conn.State == ConnectionState.Open)
         {
             conn.Close();
         }
     }
     catch (SqlException ex) { }
 }
Пример #14
0
        private void ReadWriteReg()
        {
            WDC_REG reg      = m_regs[0];
            DWORD   dwStatus = (DWORD)wdc_err.WD_STATUS_SUCCESS;
            BOOL    bIsRead  = (m_direction == RW.READ);

            if (!IsLegalDirection(0))
            {
                txtData.Text += "you have chosen to " + (bIsRead?
                                                         "read from" : "write to") + " a register which is " +
                                (bIsRead? "write-only" : "read-only") + Environment.NewLine;
                return;
            }

            switch (reg.dwSize)
            {
            case wdc_lib_consts.WDC_SIZE_8:
            {
                if (RW.READ == m_direction)
                {
                    dwStatus = (m_regType == ACTION_TYPE.CFG) ?
                               wdc_lib_decl.WDC_PciReadCfg8(m_device.Handle,
                                                            reg.dwOffset, ref m_bData) :
                               wdc_lib_decl.WDC_ReadAddr8(m_device.Handle,
                                                          reg.dwAddrSpace, reg.dwOffset, ref m_bData);
                }
                else
                {
                    dwStatus = (m_regType == ACTION_TYPE.CFG) ?
                               wdc_lib_decl.WDC_PciWriteCfg8(m_device.Handle,
                                                             reg.dwOffset, m_bData) :
                               wdc_lib_decl.WDC_WriteAddr8(m_device.Handle,
                                                           reg.dwAddrSpace, reg.dwOffset, m_bData);
                }
                break;
            }

            case wdc_lib_consts.WDC_SIZE_16:
            {
                if (RW.READ == m_direction)
                {
                    dwStatus = (m_regType == ACTION_TYPE.CFG) ?
                               wdc_lib_decl.WDC_PciReadCfg16(m_device.Handle,
                                                             reg.dwOffset, ref m_wData) :
                               wdc_lib_decl.WDC_ReadAddr16(m_device.Handle,
                                                           reg.dwAddrSpace, reg.dwOffset, ref m_wData);
                }
                else
                {
                    dwStatus = (m_regType == ACTION_TYPE.CFG) ?
                               wdc_lib_decl.WDC_PciWriteCfg16(m_device.Handle,
                                                              reg.dwOffset, m_wData) :
                               wdc_lib_decl.WDC_WriteAddr16(m_device.Handle,
                                                            reg.dwAddrSpace, reg.dwOffset, m_wData);
                }
                break;
            }

            case wdc_lib_consts.WDC_SIZE_32:
            {
                if (RW.READ == m_direction)
                {
                    dwStatus = (m_regType == ACTION_TYPE.CFG) ?
                               wdc_lib_decl.WDC_PciReadCfg32(m_device.Handle,
                                                             reg.dwOffset, ref m_u32Data) :
                               wdc_lib_decl.WDC_ReadAddr32(m_device.Handle,
                                                           reg.dwAddrSpace, reg.dwOffset, ref m_u32Data);
                }
                else
                {
                    dwStatus = (m_regType == ACTION_TYPE.CFG) ?
                               wdc_lib_decl.WDC_PciWriteCfg32(m_device.Handle,
                                                              reg.dwOffset, m_u32Data) :
                               wdc_lib_decl.WDC_WriteAddr32(m_device.Handle,
                                                            reg.dwAddrSpace, reg.dwOffset, m_u32Data);
                }
                break;
            }

            case wdc_lib_consts.WDC_SIZE_64:
            {
                if (RW.READ == m_direction)
                {
                    dwStatus = (m_regType == ACTION_TYPE.CFG) ?
                               wdc_lib_decl.WDC_PciReadCfg64(m_device.Handle,
                                                             reg.dwOffset, ref m_u64Data) :
                               wdc_lib_decl.WDC_ReadAddr64(m_device.Handle,
                                                           reg.dwAddrSpace, reg.dwOffset, ref m_u64Data);
                }
                else
                {
                    dwStatus = (m_regType == ACTION_TYPE.CFG) ?
                               wdc_lib_decl.WDC_PciWriteCfg64(m_device.Handle,
                                                              reg.dwOffset, m_u64Data) :
                               wdc_lib_decl.WDC_WriteAddr64(m_device.Handle,
                                                            reg.dwAddrSpace, reg.dwOffset, m_u64Data);
                }
                break;
            }
            }
            TraceLog((((DWORD)wdc_err.WD_STATUS_SUCCESS == dwStatus)?
                      (bIsRead? "read " : "wrote ") + "0x" +
                      ((reg.dwSize == wdc_lib_consts.WDC_SIZE_8)?
                       m_bData.ToString("X2"):
                       ((reg.dwSize == wdc_lib_consts.WDC_SIZE_16)?
                        m_wData.ToString("X4") :
                        ((reg.dwSize == wdc_lib_consts.WDC_SIZE_32)?
                         m_u32Data.ToString("X8") : m_u64Data.ToString("X16")))) +
                      (bIsRead? " from " : " to ") + "register " + reg.sName :
                      "failed to complete the transaction on register" + reg.sName),
                     (wdc_err)dwStatus);
        }
Пример #15
0
        public TakenParams[] GetTakenParamByMetersGUIDandParamsType(Guid guid_meters, Byte types_params)
        {
            string query = "SELECT id, guid, guid_params, guid_meters FROM taken_params " +
                            "WHERE guid_meters = '" + guid_meters.ToString() + "' AND guid_params IN (SELECT guid FROM params WHERE guid_types_params IN (SELECT guid FROM types_params WHERE type = " + types_params.ToString() + "))";

            List<Object> list = GetRecordsFromReader(query, RetrieveTakenParams);

            TakenParams[] result = new TakenParams[list.Count];

            for (int i = 0; i < list.Count; i++)
            {
                result[i] = (TakenParams)list[i];
            }

            list.Clear();

            return result;
        }
Пример #16
0
        public Param[] GetParamByTakenParam(Guid guid_meters, Byte types_params)
        {
            string query = "SELECT params.guid, params.param_address, params.channel, params.guid_types_meters, names_params.name, types_params.period, types_params.type FROM params " +
                            "JOIN names_params ON names_params.guid = params.guid_names_params " +
                            "JOIN types_params ON types_params.guid = params.guid_types_params " +
                            "JOIN taken_params ON taken_params.guid_meters = '" + guid_meters.ToString() + "' " +
                            "WHERE params.guid = taken_params.guid_params AND types_params.type = " + types_params.ToString();

            List<Object> list = GetRecordsFromReader(query, RetrieveParam);

            Param[] result = new Param[list.Count];

            for (int i = 0; i < list.Count; i++)
            {
                result[i] = (Param)list[i];
            }

            list.Clear();

            return result;
        }
Пример #17
0
		/// <summary>
		/// Initializes a new instance of the <see cref="TimesInstruction"/> class.
		/// </summary>
		/// <param name="length">The length.</param>
		/// <param name="value">The value.</param>
		public TimesInstruction (UInt32 length, Byte value)
			: base (true, string.Empty, string.Empty, "TIMES", length.ToString () + " DB " + value.ToString (), null, null, null, value, null)
		{
			this.length = length;
		}
Пример #18
0
 private Byte[] GetAsHex(Byte value)
 {
     return encoding.GetBytes(value.ToString("X2", CultureInfo.InvariantCulture));
 }
Пример #19
0
        /// <summary>
        /// Updates the memory indicator describing percentage of memory used.
        /// </summary>
        /// <param name="percentUsed">Percentage of memory used, 0 <= X <= 100.</param>
        private void UpdateMemoryIndicator(Byte percentUsed)
        {
            Debug.Assert(percentUsed <= 100);

            textBoxPercentUsed.Text = percentUsed.ToString();
        }
        public ClientManager(Player player)
        {
            this.playah = player;

            this.ConnectionSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            Byte[] message = new Byte[1024];
            this.Server = new IPEndPoint(IPAddress.Parse("25.9.152.191"), 904);
            this.SReceiver = new IPEndPoint(IPAddress.Parse("255.0.0.0"), 905);
            this.ConnectionSocket.Bind(SReceiver);

            this.ConnectMe = new Thread(() => {

                lock (MessageLock)
                {
                    message = Encoding.ASCII.GetBytes("Client Connected...");
                }

                Socket clientSocketSend = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                while (true)
                {
                    clientSocketSend.SendTo(message, Server);
                    Console.WriteLine("Tried...");
                    Thread.Sleep(100);
                }
            });

            this.ListenServer = new Thread(() =>
            {

                EndPoint Doubleorigin;
                Doubleorigin = (EndPoint)this.SReceiver;
                ConnectionSocket.Bind(Doubleorigin);

                while (true)
                {
                    int size = this.ConnectionSocket.ReceiveFrom(message, ref Doubleorigin);
                    string answer = "";

                    if (message.ToString() != "")
                    {
                        if (message[0] == 'P' && !Registred)
                        {
                            for (int i = 1; i < size; i++)
                            {
                                answer += message[i].ToString();
                            }
                            lock (this.ClientLock)
                            {
                                this.Server = new IPEndPoint(Server.Address, int.Parse(answer));
                                this.Registred = true;
                            }

                            this.ConnectMe.Abort();
                        }
                        else
                        {
                            Boolean newClient = true;
                            for (int i = 2; i < size; i++)
                            {
                                answer += message[i].ToString();
                            }

                            int IP = int.Parse(answer);

                            foreach(IPEndPoint Adress in enemies.Keys )
                            {
                                if (int.Parse(Adress.Address.ToString()) == IP)
                                    newClient = false;
                            }

                            if (newClient)
                            {
                                AddEnemy(IP.ToString());
                            }
                        }
                        Console.WriteLine("Received: " + message.ToString() + "\nFrom " + this.SReceiver.Address.ToString());
                        this.ConnectionSocket.SendTo(Encoding.ASCII.GetBytes("00"), this.Server);
                    }
                }
            });

            this.ConnectMe.Start();
            this.ListenServer.Start();
        }
 public void SCsendLEDarray(Byte[] ledStripArray)
 {
     if (this.comPortOpen)
     {
         arduinoBoard.WriteLine("99");
         arduinoBoard.WriteLine(ledStripArray.ToString());
     }
 }
Пример #22
0
        /// <summary>
        /// Calculates the value this animation believes should be the current value for the property.
        /// </summary>
        /// <param name="defaultOriginValue">
        /// This value is the suggested origin value provided to the animation
        /// to be used if the animation does not have its own concept of a
        /// start value. If this animation is the first in a composition chain
        /// this value will be the snapshot value if one is available or the
        /// base property value if it is not; otherise this value will be the 
        /// value returned by the previous animation in the chain with an 
        /// animationClock that is not Stopped.
        /// </param>
        /// <param name="defaultDestinationValue">
        /// This value is the suggested destination value provided to the animation
        /// to be used if the animation does not have its own concept of an
        /// end value. This value will be the base value if the animation is
        /// in the first composition layer of animations on a property; 
        /// otherwise this value will be the output value from the previous 
        /// composition layer of animations for the property.
        /// </param>
        /// <param name="animationClock">
        /// This is the animationClock which can generate the CurrentTime or
        /// CurrentProgress value to be used by the animation to generate its
        /// output value.
        /// </param>
        /// <returns>
        /// The value this animation believes should be the current value for the property.
        /// </returns>
        protected override Byte GetCurrentValueCore(Byte defaultOriginValue, Byte defaultDestinationValue, AnimationClock animationClock)
        {
            Debug.Assert(animationClock.CurrentState != ClockState.Stopped);

            if (!_isAnimationFunctionValid)
            {
                ValidateAnimationFunction();
            }

            double progress = animationClock.CurrentProgress.Value;

            IEasingFunction easingFunction = EasingFunction;
            if (easingFunction != null)
            {
                progress = easingFunction.Ease(progress);
            }

            Byte   from        = new Byte();
            Byte   to          = new Byte();
            Byte   accumulated = new Byte();
            Byte   foundation  = new Byte();

            // need to validate the default origin and destination values if 
            // the animation uses them as the from, to, or foundation values
            bool validateOrigin = false;
            bool validateDestination = false;

            switch(_animationType)
            {
                case AnimationType.Automatic:

                    from    = defaultOriginValue;
                    to      = defaultDestinationValue;

                    validateOrigin = true;
                    validateDestination = true;

                    break;

                case AnimationType.From:

                    from    = _keyValues[0];
                    to      = defaultDestinationValue;

                    validateDestination = true;

                    break;

                case AnimationType.To:

                    from = defaultOriginValue;
                    to = _keyValues[0];

                    validateOrigin = true;

                    break;

                case AnimationType.By:

                    // According to the SMIL specification, a By animation is
                    // always additive.  But we don't force this so that a
                    // user can re-use a By animation and have it replace the
                    // animations that precede it in the list without having
                    // to manually set the From value to the base value.

                    to          = _keyValues[0];
                    foundation  = defaultOriginValue;

                    validateOrigin = true;

                    break;

                case AnimationType.FromTo:

                    from    = _keyValues[0];
                    to      = _keyValues[1];

                    if (IsAdditive)
                    {
                        foundation = defaultOriginValue;
                        validateOrigin = true;
                    }

                    break;

                case AnimationType.FromBy:

                    from    = _keyValues[0];
                    to      = AnimatedTypeHelpers.AddByte(_keyValues[0], _keyValues[1]);

                    if (IsAdditive)
                    {
                        foundation = defaultOriginValue;
                        validateOrigin = true;
                    }

                    break;

                default:

                    Debug.Fail("Unknown animation type.");

                    break;
            }

            if (validateOrigin 
                && !AnimatedTypeHelpers.IsValidAnimationValueByte(defaultOriginValue))
            {
                throw new InvalidOperationException(
                    SR.Get(
                        SRID.Animation_Invalid_DefaultValue,
                        this.GetType(),
                        "origin",
                        defaultOriginValue.ToString(CultureInfo.InvariantCulture)));
            }

            if (validateDestination 
                && !AnimatedTypeHelpers.IsValidAnimationValueByte(defaultDestinationValue))
            {
                throw new InvalidOperationException(
                    SR.Get(
                        SRID.Animation_Invalid_DefaultValue,
                        this.GetType(),
                        "destination",
                        defaultDestinationValue.ToString(CultureInfo.InvariantCulture)));
            }


            if (IsCumulative)
            {
                double currentRepeat = (double)(animationClock.CurrentIteration - 1);

                if (currentRepeat > 0.0)
                {
                    Byte accumulator = AnimatedTypeHelpers.SubtractByte(to, from);

                    accumulated = AnimatedTypeHelpers.ScaleByte(accumulator, currentRepeat);
                }
            }

            // return foundation + accumulated + from + ((to - from) * progress)

            return AnimatedTypeHelpers.AddByte(
                foundation, 
                AnimatedTypeHelpers.AddByte(
                    accumulated,
                    AnimatedTypeHelpers.InterpolateByte(from, to, progress)));
        }
Пример #23
0
 static public String Rend(Byte d)
 {
     return d.ToString();
 }
        /// <summary>
        /// Uses a feature report to set the blink pattern on the SuperMutt's LED. 
        /// 
        /// Please note that when we create a FeatureReport, all data is nulled out in the report. Since we will only be modifying 
        /// data we care about, the other bits that we don't care about, will be zeroed out. Controls will effectively do the same thing (
        /// all bits are zeroed out except for the bits we care about).
        /// 
        /// Any errors in async function will be passed down the task chain and will not be caught here because errors should be handled 
        /// at the end of the task chain.
        ///
        /// The SuperMutt has the following patterns:
        /// 0 - LED always on
        /// 1 - LED flash 2 seconds on, 2 off, repeat
        /// 2 - LED flash 2 seconds on, 1 off, 2 on, 4 off, repeat
        /// ...
        /// 7 - 7 iterations of 2 on, 1 off, followed by 4 off, repeat
        /// </summary>
        /// <param name="pattern">A number from 0-7. Each number represents a different blinking pattern</param>
        /// <returns>A task that can be used to chain more methods after completing the scenario</returns>
        async Task SetLedBlinkPatternAsync(Byte pattern)
        {
            var featureReport = EventHandlerForDevice.Current.Device.CreateFeatureReport(SuperMutt.LedPattern.ReportId);

            var dataWriter = new DataWriter();

            // First byte is always the report id
            dataWriter.WriteByte((Byte) featureReport.Id);
            dataWriter.WriteByte(pattern);

            featureReport.Data = dataWriter.DetachBuffer();

            await EventHandlerForDevice.Current.Device.SendFeatureReportAsync(featureReport);

            rootPage.NotifyUser("The Led blink pattern is set to " + pattern.ToString(), NotifyType.StatusMessage);
        }
Пример #25
0
        private Boolean IsLandingSquareEmpty(Byte startSquare, MoveDirection jumpDirection)
        {
            Boolean answer = false;
            String start = startSquare.ToString() + jumpDirection.ToString().ToLower();
            Byte landingSquare = JumpLandingSquareLookup[start];
            UInt64 landingBitBoard = squareTable[landingSquare];

            if ((emptySquares & landingBitBoard) != 0UL)
                answer = true;

            return answer;
        }
Пример #26
0
        private Move CreateMoveFromJump(Byte index, MoveDirection direction)
        {
            String key = index.ToString() + direction.ToString().ToLower();
            Byte landingSquare = JumpLandingSquareLookup[key];
            Move move = new Move(index, landingSquare, true);

            return move;
        }
Пример #27
0
        private static String InternalFormattedHexString(Object value)
        {
            TypeCode typeCode = Convert.GetTypeCode(value);

            switch (typeCode)
            {
            case TypeCode.SByte:
            {
                Byte result = (byte)(sbyte)value;

                return(result.ToString("X2", null));
            }

            case TypeCode.Byte:
            {
                Byte result = (byte)value;

                return(result.ToString("X2", null));
            }

            case TypeCode.Int16:
            {
                UInt16 result = (UInt16)(Int16)value;

                return(result.ToString("X4", null));
            }

            case TypeCode.UInt16:
            {
                UInt16 result = (UInt16)value;

                return(result.ToString("X4", null));
            }

            case TypeCode.UInt32:
            {
                UInt32 result = (UInt32)value;

                return(result.ToString("X8", null));
            }

            case TypeCode.Int32:
            {
                UInt32 result = (UInt32)(int)value;

                return(result.ToString("X8", null));
            }

            case TypeCode.UInt64:
            {
                UInt64 result = (UInt64)value;

                return(result.ToString("X16", null));
            }

            case TypeCode.Int64:
            {
                UInt64 result = (UInt64)(Int64)value;

                return(result.ToString("X16", null));
            }

            // All unsigned types will be directly cast
            default:
                BCLDebug.Assert(false, "Invalid Object type in Format");
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
            }
        }
Пример #28
0
 /// <summary>
 /// Converts the value of the specified nullable 8-bit unsigned integer  to its equivalent String representation.
 /// </summary>
 /// <param name="value">A nullable 8-bit unsigned integer.</param>
 /// <returns>The String equivalent of the nullable 8-bit unsigned integer value.</returns>
 public static String ToString(Byte? value) { return value.ToString(); }
Пример #29
0
        private bool Func_Modbus_Recv_Handle()
        {
            bool res = true;

            modbus_handling = true;
            String SerialIn = "";

            for (int i = 0; i < modbus_recv_cnt; i++)
            {
                //SerialIn += modbus_recv_data[i].ToString();
                if (modbus_recv_data[i] < 0x0f)
                {
                    SerialIn += "0x0";
                    SerialIn += Convert.ToString(modbus_recv_data[i], 16);
                }
                else
                {
                    SerialIn += "0x";
                    SerialIn += Convert.ToString(modbus_recv_data[i], 16);
                }

                SerialIn += " ";
            }

            if (checkBox_ShowTxt.Checked == true)
            {
                this.Invoke((EventHandler)(delegate
                {
                    this.textBox_ComRec.AppendText("Recv: ");
                    this.textBox_ComRec.AppendText(SerialIn);                           //在接收文本中添加串口接收数据
                    this.textBox_ComRec.AppendText("\r\n");

                    if (textBox_ComRec.TextLength > 32768)
                    {
                        textBox_ComRec.Text = "";
                    }
                }));
            }

            /*
             *      Send:
             *      [0]		   0x01: SubAddress
             *      [1]		   0x03: Read(WORD)
             *      [2]		   0x01: Register
             *      [3]		   0x01: Num(要读的WORD数)
             *      [4-7]0x00000001: Val(传递的参数)
             *      [8]		   0x**: CRCH
             *      [9]		   0x**: CRCL
             *
             *      Rec:
             *      [0]		   0x01: SubAddress
             *      [1]		   0x03: Read(WORD)
             *      [2]		   0x01: Register
             *      [3]		   0x01: Num
             *      [4]		   0x00: ValH[0]
             *      [5]		   0x01: ValL[0]
             *      [6]		   0x**: CRCH
             *      [7]		   0x**: CRCL
             */

            //send:01 03 01 01 00 00 00 01 4F 16->received:01 03 01 01 55 AA AA D9//读故障报警状态

            u16 CRC_Result_Cal   = 0;
            u16 CRC_Result_Trans = 0;
            u8  Register_Address = 0;

            modbus_is_busy = false;
            switch (modbus_recv_data[1])                                                                //功能码
            {
            case 0x03:                                                                                  //读寄存器的值(WORD)
            {
                CRC_Result_Cal   = Func_Get_CRC(modbus_recv_data, 6);                                   //CRC校验正确则发送数据给主站,否则等待主站再次发送数据
                CRC_Result_Trans = (u16)((((u16)modbus_recv_data[6]) << 8) | ((u16)modbus_recv_data[7]));
                if (CRC_Result_Cal == CRC_Result_Trans)
                {
                    u8  Need_Read_WORD_Num;
                    u32 Func_Val = 0;

                    Register_Address   = modbus_recv_data[2];                                                   //寄存器值
                    Need_Read_WORD_Num = modbus_recv_data[3];                                                   //要读的WORD数
                    Func_Val           = ((((u32)modbus_recv_data[4]) << 8) |
                                          (((u32)modbus_recv_data[5]) << 0));

                    Console.WriteLine("MBI Reg:{0} Num:{1} Val:{2}", Register_Address, Need_Read_WORD_Num, Func_Val);

                    switch (Register_Address)
                    {
                    case REG_IDENTIFY:                                                                                                  //测试modbus通信是否正常
                    {
                        Console.WriteLine("REG_IDENTIFY:{0:X}", Func_Val);
                        this.Invoke((EventHandler)(delegate
                                {
                                    label_Status.Text = Func_Val.ToString();
                                }));

                        break;
                    }

                    case REG_MOUSE_PRESS:
                    {
                        Console.WriteLine("REG_MOUSE:{0:X}", Func_Val);
                        break;
                    }

                    case REG_MOUSE_CLICK:
                    {
                        this.Invoke((EventHandler)(delegate
                                {
                                    if (button_ClickLeft.Enabled == false)
                                    {
                                        button_ClickLeft.Enabled = true;
                                    }
                                    if (button_ClickRight.Enabled == false)
                                    {
                                        button_ClickRight.Enabled = true;
                                    }
                                }));

                        break;
                    }

                    case REG_MOUSE_SPEED:
                    {
                        this.Invoke((EventHandler)(delegate
                                {
                                    if (button_SpeedUp.Enabled == false)
                                    {
                                        button_SpeedUp.Enabled = true;
                                    }
                                    if (button_SpeedDown.Enabled == false)
                                    {
                                        button_SpeedDown.Enabled = true;
                                    }
                                    if (mouse_speed_chk == false)
                                    {
                                        mouse_speed_chk = true;
                                    }
                                    label_MouseSpeed.Text = Func_Val.ToString();
                                }));

                        break;
                    }

                    case REG_KEYBOARD:
                    case REG_SYSTEM_REBOOT:
                    case REG_USB_RECONNECT:
                    {
                        break;
                    }

                    default:
                    {
                        MessageBox.Show("error reg!!!: " + Register_Address.ToString(), "提示");
                        res = false;
                        break;
                    }
                    }
                    modbus_send_cmd_is_busy = false;

                    if (Func_KB_FIFO_HasData() == true)
                    {
                        modbus_send_cmd_is_busy = true;
                        Func_Modbus_Send_03(REG_KEYBOARD, 1, Func_KB_FIFO_Output());
                    }
                }
                else
                {
                    MessageBox.Show("error crc!!!: " + CRC_Result_Cal.ToString(), "提示");
                    res = false;
                }
                break;
            }

            case 0x06:
            {
                break;
            }

            default:
            {
                MessageBox.Show("error func!!!: " + modbus_recv_data[1].ToString(), "提示");
                res = false;
                break;
            }
            }
            modbus_recv_data[1] = 0xFF;                                     //取完后立马清掉,表示已经用过了

            modbus_recv_cnt = 0;
            modbus_handling = false;

            if (res == true)
            {
                modbus_success_cnt++;
            }
            else
            {
                modbus_fail_cnt++;
                modbus_send_cmd_is_busy = false;
            }
            this.Invoke((EventHandler)(delegate
            {
                label_CmdSuccessCnt.Text = "CmdCnt: ";
                label_CmdSuccessCnt.Text += modbus_success_cnt.ToString();
                label_CmdSuccessCnt.Text += " | ";
                label_CmdSuccessCnt.Text += modbus_fail_cnt.ToString();
            }));

            return(res);
        }
Пример #30
0
 /// <summary>
 /// Converts the value of the specified nullable 8-bit unsigned integer  to its equivalent SqlString representation.
 /// </summary>
 /// <param name="value">A nullable 8-bit unsigned integer.</param>
 /// <returns>The SqlString equivalent of the nullable 8-bit unsigned integer value.</returns>
 public static SqlString ToSqlString(Byte? value) { return value.HasValue ? value.ToString() : SqlString.Null; }
Пример #31
0
		/// <summary>Converts the value from <c>Byte?</c> to an equivalent <c>SqlChars</c> value.</summary>
		public static SqlChars ToSqlChars(Byte? p)           { return p.HasValue? new SqlChars(p.ToString().ToCharArray()): SqlChars.Null; }
Пример #32
0
 private bool VerifyToString(String id, Byte myByte, String format, String expected)
 {
     try
     {
         String actual = myByte.ToString(format);
         if (actual != expected)
         {
             TestLibrary.TestFramework.LogError(id + "_001", "Expected: " + expected + " Actual: " + actual);
             return false;
         }
     }
     catch (Exception e)
     {
         TestLibrary.TestFramework.LogError(id + "_002", "Unexpected exception occurs: " + e);
         return false;
     }
     return true;
 }
Пример #33
0
		/// <summary>Converts the value from <c>Byte</c> to an equivalent <c>SqlString</c> value.</summary>
		public static SqlString ToSqlString(Byte            p) { return p.ToString();                                                                     }
Пример #34
0
        private void ProcessDeviceType(string OperationName, BPProtocolHeader lProtocolHeader, Byte lLinkId, object[] DeserializedData)
        {
            log.Info("Processing device type of peer "+ lLinkId);
            log.Info("Device type is " + ((byte)DeserializedData[0]).ToString());
            cForm1.Invoke((MethodInvoker)delegate
            {
                //EnumerableRowCollection<Devices.DeviceRow> rows = (from n in cDevices.Device where n.DeviceAddress == lProtocolHeader.cLinkId select n);
                DataRow[] rows = cDevices.Device.Select("LinkId=" + lLinkId.ToString());
                if (rows.Count() == 0)
                    return;
                Devices.DeviceRow Row = (Devices.DeviceRow)rows[0];
                if (Row == null)
                    return;

                Row.DeviceType = (byte)DeserializedData[0];
                Row.AcceptChanges();
            });
        }
Пример #35
0
 /// <summary>
 /// Converts the value of the specified nullable 8-bit unsigned integer to its equivalent SqlChars representation.
 /// </summary>
 /// <param name="value">A nullable 8-bit unsigned integer.</param>
 /// <returns>The equivalent SqlChars.</returns>
 public static SqlChars ToSqlChars(Byte? value) { return value.HasValue ? new SqlChars(value.ToString().ToCharArray()) : SqlChars.Null; }
Пример #36
0
 private void ProcessNewPeer(string OperationName, BPProtocolHeader lProtocolHeader, Byte lLinkId, object[] DeserializedData)
 {
     log.Info("Processing new peer with LinkId "+ lLinkId);
     cForm1.Invoke((MethodInvoker)delegate
     {
         DataRow[] rows = cDevices.Device.Select("LinkId=" + lLinkId.ToString());
         if(rows.Count()>0)
             return;
         cDevices.Device.AddDeviceRow(lLinkId, (Byte)DeviceType.Unknown);
     });
 }
Пример #37
0
 /// <summary>
 /// Converts the value of the specified 8-bit unsigned integer to its equivalent SqlString representation.
 /// </summary>
 /// <param name="value">A 8-bit unsigned integer.</param>
 /// <returns>The SqlString equivalent of the 8-bit unsigned integer value.</returns>
 public static SqlString ToSqlString(Byte value) { return value.ToString(); }
Пример #38
0
        /***	void ListenForResponse(Object obj)
         *
         *	Parameters:
         *          obj - a "this" pointer to the instantiated of the form
         *              
         *	Return Values:
         *          None
         *
         *	Description: 
         *	
         *      This gets invoked to listen for any incoming data on the connection
         *      And safely prints it to the log. If the connection is lost, the thread closes
         *      as well as closes the stream and connection.
         * ------------------------------------------------------------ */
        private void ListenForResponse(Object obj)
        {
            TCPEchoClient me = (TCPEchoClient)obj;
            Byte[] rgbIn = new Byte[1024];
            int cbRead = 0;

            PrintTextSafe("Starting to listen", Color.Black);

            try
            {
                while ((cbRead = me.nwStream.Read(rgbIn, 0, rgbIn.Length)) > 0)
                {
                    try
                    {
                        Encoding ascii = Encoding.ASCII;
                        string sz = ascii.GetString(rgbIn, 0, cbRead);
                        PrintTextSafe(sz, Color.Blue);
                    }
                    catch
                    {
                        PrintTextSafe("Unrecognized string: " + rgbIn.ToString(), Color.Red);
                    }
                }
            }
            catch
            {
            }
            finally
            {
                // kill our stream and connection
                if (me.nwStream != null)
                {
                    me.nwStream.Close();
                }

                if (me.tcpClient != null)
                {
                    me.tcpClient.Close();
                }
            }

            PrintTextSafe("Ending listening", Color.Black);
        }
Пример #39
0
 //#define ROM_IGNORE(length)                          { nullptr,  nullptr,                 0,        (length), ROMENTRYTYPE_IGNORE | ROM_INHERITFLAGS },
 public static tiny_rom_entry ROM_FILL(u32 offset, u32 length, u8 value)
 {
     return(new tiny_rom_entry(null, value.ToString(), offset, length, ROMENTRYTYPE_FILL));
 }
Пример #40
0
 public static String BinToHex(Byte value)
 {
     StringBuilder sb = new StringBuilder("");
     sb.Append(value.ToString("X2"));  //the 2 means 2 digits
     return sb.ToString();
 }
Пример #41
0
        private void Form1_Load(object sender, EventArgs e)
        {
            s32 i;

            this.Text = "KMouse Git" + _VersionGit.ToString();

            textBox_eKey.Enabled = false;

            /*********************初始化鼠标按键 start**********************/
            for (i = 0; i < KEY_MousePress_ALL; i++)
            {
                mouse_press_en[i]      = false;
                mouse_press_en_last[i] = false;
            }
            /*********************初始化鼠标按键 end************************/


            /********************更新串口下来列表的选项-start******************/
            string[] strArr    = Func_GetHarewareInfo(HardwareEnum.Win32_PnPEntity, "Name");
            int      SerialNum = 0;

            foreach (string vPortName in SerialPort.GetPortNames())
            {
                String SerialIn = "";
                SerialIn += vPortName;
                SerialIn += ':';
                foreach (string s in strArr)
                {
                    if (s.Contains(vPortName))
                    {
                        SerialIn += s;
                    }
                }
                Console.WriteLine(SerialIn);
                comboBox_COMNumber.Items.Add(SerialIn);
                SerialNum++;
            }
            /********************更新串口下来列表的选项-end********************/

            //波特率
            for (i = 0; i < badurate_array.Length; i++)
            {
                comboBox_COMBaudrate.Items.Add(badurate_array[i].ToString());
            }

            //校验位
            comboBox_COMCheckBit.Items.Add("None");
            comboBox_COMCheckBit.Items.Add("Odd");
            comboBox_COMCheckBit.Items.Add("Even");

            //数据位
            comboBox_COMDataBit.Items.Add("8");
            comboBox_COMStopBit.Items.Add("0");

            //停止位
            comboBox_COMStopBit.Items.Add("1");
            comboBox_COMStopBit.Items.Add("2");
            comboBox_COMStopBit.Items.Add("1.5");

            if ((SerialNum > 0) && (Properties.Settings.Default._com_num_select_index < SerialNum))    //串口列表选用号
            {
                comboBox_COMNumber.SelectedIndex = Properties.Settings.Default._com_num_select_index;
            }
            else
            {
                comboBox_COMNumber.SelectedIndex = -1;
            }

            comboBox_COMBaudrate.SelectedIndex = Properties.Settings.Default._baudrate_select_index;
            comboBox_COMCheckBit.SelectedIndex = 0;
            comboBox_COMDataBit.SelectedIndex  = 0;
            comboBox_COMStopBit.SelectedIndex  = 1;
            com.DataReceived += Func_COM_DataRec;            //指定串口接收函数

            textBox_eKey.Text = Properties.Settings.Default.eKey_string;

            Func_COM_Open();
        }
        public bool test4()
        {
            // Test 4 - 100 packets write, single packet read
            Debug.WriteLine("Reference Application -> Starting Test 4");

            // Declare our output buffer
            Byte[] outputBuffer = new Byte[65];

            // Declare our input buffer
            Byte[] inputBuffer = new Byte[15];

            // Before performing a bulk send to the device we have to send a command
            // packet to let the device know what's about to happen...

            // Byte 0 must be set to 0
            outputBuffer[0] = 0;

            // Byte 1 must be set to our command
            outputBuffer[1] = 0x83;

            // Fill the rest of the buffer with known data
            int bufferPointer;
            Byte data = 0;
            for (bufferPointer = 2; bufferPointer < 65; bufferPointer++)
                {
                // We send the numbers 0 to 63 to the device
                outputBuffer[bufferPointer] = data;
                data++;
                }

            // Perform the write command
            bool success;
            success = writeRawReportToDevice(outputBuffer);

            // If the write was successful we begin the bulk send
            if (success)
                {
                // Now we send 128 packets to the device
                for (int packetCounter = 0; packetCounter < 128; packetCounter++)
                    {
                    // Fill the buffer with meaningful data
                    outputBuffer[0] = 0;
                    for (bufferPointer = 1; bufferPointer < 65; bufferPointer++) outputBuffer[bufferPointer] = (Byte)packetCounter;

                    // Send the packet to the device
                    success = writeRawReportToDevice(outputBuffer);

                    if (!success)
                        {
                        Debug.WriteLine("Reference Application -> TEST4: Bulk send to device failed!");
                        return false;
                        }
                    }
                }
            else Debug.WriteLine("Reference Application -> TEST4: Write report to device failed!");
            readSingleReportFromDevice(ref inputBuffer);
            Debug.Print(inputBuffer.ToString());
            // We can't tell from here if the device received the data ok, you have to check the device status LEDs
            return true;
        }