Ejemplo n.º 1
0
        private void LoadComboBox_Status()
        {
            var d = new Decode();
            SqlConnection cn = new SqlConnection(d.ConnectionString);
            SqlCommand cmd = new SqlCommand("DTUSER.SoldStatusComboBox");
            SqlDataReader dr;
            try
            {
                cn.Open();
                cmd.Connection = cn;
                dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    cboSoldStatus.Items.Add(dr.GetValue(0).ToString());
                }

            }
            catch (SqlException sx)
            {
                MessageBox.Show(sx.Message.ToString(), "SQL Data Error", MessageBoxButtons.OK);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "C# Error", MessageBoxButtons.OK);
            }
            finally
            {
                if (cn.State != ConnectionState.Closed)
                {
                    cn.Close();
                }
            }
        }
Ejemplo n.º 2
0
 private int GetMaxInventoryID()
 {
     int maxid = 0;
     string cmdText = "SELECT MAX(ITEMNUMBER) FROM DTUSER.NEWINVENTORY";
     var d = new Decode();
     SqlConnection cn = new SqlConnection(d.ConnectionString);
     SqlCommand cmd = new SqlCommand(cmdText, cn);
     cn.Open();
     SqlDataReader dr = cmd.ExecuteReader();
     while (dr.Read())
     {
         maxid = dr.GetSqlInt32(0).Value;
     }
     cn.Close();
     return maxid + 1;
 }
Ejemplo n.º 3
0
        public static void oPCode(Decode decode)
        {
            try
            {
                Systems sys = (Systems)decode.Packet;
                sys.PacketInformation = decode;
                PacketReader Reader = new PacketReader(sys.PacketInformation.buffer);

                //Console.WriteLine("Opcode: {0}",decode.opcode);

                switch (decode.opcode)
                {
                    case CLIENT.CLIENT_HANDSHAKE:
                        break;
                    case CLIENT.CLIENT_PING_CHECK:
                        //To be checked
                        break;
                    case CLIENT.CLIENT_INFO:
                        //if (Reader.Text() == "SR_Client")
                        sys.client.Send(GateWayPacket());
                        break;
                    case CLIENT.CLIENT_UPDATE:
                        sys.Patch();
                        break;
                    case CLIENT.CLIENT_SERVERLIST:
                        sys.client.Send(ServerListPacket(sys.client.Version));
                        break;
                    case CLIENT.CLIENT_AUTH:
                        sys.Connect();
                        break;
                    case CLIENT.CLIENT_OPEN:
                        sys.client.Send(LoadGame_6());
                        sys.client.Send(News());
                        break;
                    case 1905:
                        byte[] buffer = decode.buffer;
                        User_Current = BitConverter.ToInt16(buffer, 0);
                        break;
                    default:
                        Console.WriteLine("Default Opcode: {0}", decode.opcode);
                        break;
                }
            }
            catch (Exception)
            {
            }
        }
Ejemplo n.º 4
0
 public static void oPCode(Decode decode)
 {
     try
     {
         Systems sys = (Systems)decode.Packet;
         sys.PacketInformation = decode;
         PacketReader Reader = new PacketReader(sys.PacketInformation.buffer);
         LogDebug.Show("Opcode: {0}", decode.opcode);
         Opcode opc = (Opcode)decode.opcode;
         switch (opc)
         {
             case Opcode._MSG_LOGIN:
                 {
                     string username_shift = Reader.String(32);
                     string password_md5 = Reader.String(32);
                     Reader.Skip(4);
                     string client_mac = Reader.String(32);
                     Reader.Skip(32);
                     uint unk3 = Reader.UInt32();
                     StringShift shift = new StringShift();
                     string username = shift.Parser(username_shift);
                     LogDebug.Show("username: {0}", username);
                     LogDebug.Show("password_md5: {0}", password_md5);
                     //LogDebug.Show("Mac: {0}", client_mac);
                     //LogDebug.Show("unk3: {0}", unk3);
                     int res = UserLogin(username, password_md5, client_mac);
                     if (res == 1)
                     {
                         sys.client.SendC(ServerListPacket(1));
                     }
                     else
                     {
                         sys.client.SendC(UserFail(0xF0));
                     }
                 }
                 break;
             default:
                 LogConsole.Show("Default Opcode: {0:X} - {1}", decode.opcode, opc);
                 //LogDebug.HexDump(sys.PacketInformation.buffer, 16, true);
                 break;
         }
     }
     catch (Exception)
     {
     }
 }
 public AmqpPrimitiveType(Type type, Encode encoder, Decode decoder)
     : base(null, type)
 {
     this.encoder = encoder;
     this.decoder = decoder;
 }
Ejemplo n.º 6
0
    static public void Work()
    {
        F_stall = D_stall = E_stall = false;
        //        F_bubble = D_bubble = E_bubble = false;
        W_bubble = M_bubble; M_bubble = E_bubble;
        E_bubble = D_bubble; D_bubble = F_bubble;
        F_bubble = false;

        bool ld = false, rt = false, wj = false;

        if ((Excute.Show_E_icode() == Codes.IMRMOVQ || Excute.Show_E_icode() == Codes.IPOPQ) && (Excute.Show_E_dstM() == Decode.Show_d_srcA() || Excute.Show_E_dstM() == Decode.Show_d_srcB()))
        {
            ld = true;
        }
        if ((Excute.Show_E_icode() == Codes.IRET) || (Memory.Show_M_icode() == Codes.IRET) || (Decode.Show_D_icode() == Codes.IRET))
        {
            rt = true;
        }
        if (!Excute.Show_e_Cnd() && Excute.Show_e_icode() == Codes.IJXX)
        {
            wj = true;
        }

        if (ld && !rt)
        {
            F_stall = D_stall = E_bubble = true;           //LOAD_USE
        }
        if (rt && !ld)
        {
            F_stall = D_bubble = true;           //RET
        }
        if (wj)
        {
            E_bubble = D_bubble = true;    //WRONG_JXX
        }
        if (ld && rt)
        {
            E_bubble = D_stall = F_stall = true;          //LOAD_USE && RET
        }
    }
Ejemplo n.º 7
0
        public void DataReceived(object sender, AGIInterface.CustomDataEvtArg e)
        {
            if (CSAMForm.InvokeRequired)
            {
                try
                {
                    if (CSAMForm != null)
                    {
                        //proTracDisplay.Invoke(new Class1.DeviceSendDataToProTrackHandler(DataReceived), sender, e);
                        CSAMForm.BeginInvoke(new Class1.DeviceSendDataToProTrackHandler(DataReceived), sender, e);
                    }
                    else
                    {
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(">>>Message= " + ex.Message + "\r\n StrackTrace: " + ex.StackTrace);
                }
            }
            else
            {
                if (Global.CurrentSender == CSAMForm.Name && e.deivceName == Global.GCurrentDevice)
                {
                    try
                    {
                        UInt16 messageType = 0;
                        messageType = BitConverter.ToUInt16(e.data, 6);
                        UInt16 messageLength = 0;
                        messageLength = BitConverter.ToUInt16(e.data, 10);
                        //判断消息长度
                        if (messageLength * 4 != e.data.Length - 12)
                        {
                            return;
                        }

                        switch (messageType)
                        {
                        case COM.ZCTT.AGI.Common.AGIMsgDefine.L2P_AG_CELL_CAPTURE_IND_MSG_TYPE:
                        {
                            Dictionary <string, string> result = Decode.dataBackControl_SendMIBToDisplayEvent(e);
                            //string tai = (BitConverter.ToUInt16(e.data, 26)).ToString();
                            //string ecgi = (BitConverter.ToUInt32(e.data, 28)).ToString();
                            //string rsrp = (BitConverter.ToUInt16(e.data, 32) * 0.125).ToString("f2") + "dBm";
                            short MinRSRQ = -15;
                            if ((result["RSRQ"] == "NULL" || Convert.ToInt16(result["RSRQ"]) < MinRSRQ) && isSecond == false)
                            {
                                CellSearchItemIndex--;
                                isSecond = true;
                            }
                            else
                            {
                                System.Diagnostics.Debug.WriteLine(">>>>>>>>>>>>>>>>CellSearchItemIndex: " + CellSearchItemIndex);
                                if (result["RSRP"] != "NULL")
                                {
                                    CSAMForm.CellSearchListView.Items[CellSearchItemIndex].SubItems[4].Text = result["RSRP"] + "dBm";
                                }
                                else
                                {
                                    CSAMForm.CellSearchListView.Items[CellSearchItemIndex].SubItems[4].Text = "N/A";
                                }
                                if (result["RSRP"] != "NULL")
                                {
                                    CSAMForm.CellSearchListView.Items[CellSearchItemIndex].SubItems[5].Text = result["RSRQ"] + "dB";
                                }
                                else
                                {
                                    CSAMForm.CellSearchListView.Items[CellSearchItemIndex].SubItems[5].Text = "N/A";
                                }
                                switch (result["DLBand"])
                                {
                                case "NULL": CSAMForm.CellSearchListView.Items[CellSearchItemIndex].SubItems[6].Text = "N/A"; break;

                                case "0": CSAMForm.CellSearchListView.Items[CellSearchItemIndex].SubItems[6].Text = "1.4M"; break;

                                case "1": CSAMForm.CellSearchListView.Items[CellSearchItemIndex].SubItems[6].Text = "3M"; break;

                                case "2": CSAMForm.CellSearchListView.Items[CellSearchItemIndex].SubItems[6].Text = "5M"; break;

                                case "3": CSAMForm.CellSearchListView.Items[CellSearchItemIndex].SubItems[6].Text = "10M"; break;

                                case "4": CSAMForm.CellSearchListView.Items[CellSearchItemIndex].SubItems[6].Text = "15M"; break;

                                case "5": CSAMForm.CellSearchListView.Items[CellSearchItemIndex].SubItems[6].Text = "20M"; break;
                                }
                                CSAMForm.CellSearchListView.Items[CellSearchItemIndex].SubItems[7].Text = result["TAC"];
                                CSAMForm.CellSearchListView.Items[CellSearchItemIndex].SubItems[8].Text = result["CellID"];
                                isSecond = false;
                            }
                            Thread.Sleep(2000);
                            mutexRelease = 1;
                            ReleaseProtocolTracing();
                            break;
                        }

                        case COM.ZCTT.AGI.Common.AGIMsgDefine.L1_AG_PROTOCOL_TRACE_REL_ACK_MSG_TYPE:
                        case COM.ZCTT.AGI.Common.AGIMsgDefine.AG_PC_PROTOCOL_TRACE_REL_ACK_MSG_TYPE:
                        {
                            CellSearchItemIndex++;
                            if (CellSearchItemIndex == CSAMForm.CellSearchListView.Items.Count)
                            {
                                CellSearchItemIndex = 0;
                            }
                            CSAMForm.CellSearchStart();
                            break;
                        }

                        default:
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(">>>Message= " + ex.Message + "\r\n StrackTrace: " + ex.StackTrace);
                        return;
                    }
                }
            }
        }
Ejemplo n.º 8
0
        public void Decode(string fileName)
        {
            try
            {
                // Attempt to open .FIT file
                _fitSource = new FileStream(fileName, FileMode.Open);

                Decode          decodeDemo      = new Decode();
                MesgBroadcaster mesgBroadcaster = new MesgBroadcaster();

                // Connect the Broadcaster to our event (message) source (in this case the Decoder)
                decodeDemo.MesgEvent += mesgBroadcaster.OnMesg;
                // Subscribe to message events of interest by connecting to the Broadcaster
                mesgBroadcaster.MesgEvent += OnMesg;

                mesgBroadcaster.ActivityMesgEvent         += ActivityValues.OnActivityMesg;
                mesgBroadcaster.DeveloperDataIdMesgEvent  += DeveloperDataIdValues.OnDeveloperDataIdMesg;
                mesgBroadcaster.DeviceInfoMesgEvent       += DeviceInfoValues.OnDeviceInfoMesg;
                mesgBroadcaster.FieldDescriptionMesgEvent += FieldDescriptionValues.OnFieldDescriptionMesg;
                mesgBroadcaster.FileIdMesgEvent           += FileIdValues.OnFileIDMesg;
                mesgBroadcaster.EventMesgEvent            += EventValues.OnEventMesg;
                mesgBroadcaster.SportMesgEvent            += SportValues.OnSportMesg;
                mesgBroadcaster.WorkoutMesgEvent          += WorkoutValues.OnWorkoutMesg;
                //mesgBroadcaster.HrZoneMesgEvent += HRZonesManager.OnMesg;

                bool status = decodeDemo.IsFIT(_fitSource);
                status &= decodeDemo.CheckIntegrity(_fitSource);

                // Process the file
                if (status)
                {
                    //Console.WriteLine("Decoding...");
                    decodeDemo.Read(_fitSource);
                    //Console.WriteLine("Decoded FIT file {0}", args[0]);
                }
                else
                {
                    try
                    {
                        //Console.WriteLine("Integrity Check Failed {0}", args[0]);
                        if (decodeDemo.InvalidDataSize)
                        {
                            //Console.WriteLine("Invalid Size Detected, Attempting to decode...");
                            decodeDemo.Read(_fitSource);
                        }
                        else
                        {
                            //Console.WriteLine("Attempting to decode by skipping the header...");
                            decodeDemo.Read(_fitSource, DecodeMode.InvalidHeader);
                        }
                    }
                    catch (FitException ex)
                    {
                        MessageBox.Show("Decode caught FitException: " + ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        //Console.WriteLine("DecodeDemo caught FitException: " + ex.Message);
                    }
                }
                _fitSource.Close();
            }
            catch (FitException ex)
            {
                MessageBox.Show("A FitException occurred when trying to decode the FIT file. Message: " + ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //Console.WriteLine("A FitException occurred when trying to decode the FIT file. Message: " + ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception occurred when trying to decode the FIT file. Message: " + ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //Console.WriteLine("Exception occurred when trying to decode the FIT file. Message: " + ex.Message);
            }
            finally
            {
            }
        }
Ejemplo n.º 9
0
 public static SerializableType CreatePrimitiveType(Type type, Encode encoder, Decode decoder)
 {
     return new AmqpPrimitiveType(type, encoder, decoder);
 }
Ejemplo n.º 10
0
        internal static bool TryGetCodec(Type type, out Encode encoder, out Decode decoder)
        {
            Serializer codec = (Serializer)codecByType[type];
            if (codec == null && type.IsArray)
            {
                codec = serializers[20];
            }

            if (codec != null)
            {
                encoder = codec.Encoder;
                decoder = codec.Decoder;
                return true;
            }
            else
            {
                encoder = null;
                decoder = null;
                return false;
            }
        }
Ejemplo n.º 11
0
        /**
         * Read informations of a rpm file out of an input stream.
         *
         * @param rpmInputStream The input stream representing the rpm file
         * @throws IOException if an error occurs during read of the rpm file
         */
        private void readFromStream(java.io.InputStream rpmInputStream)
        {//throws IOException {
            ByteCountInputStream allCountInputStream = new ByteCountInputStream(
                rpmInputStream);

            java.io.InputStream inputStream = new java.io.DataInputStream(allCountInputStream);

            lead      = new RPMLead((java.io.DataInputStream)inputStream);
            signature = new RPMSignature((java.io.DataInputStream)inputStream, store);

            if (logger.isLoggable(java.util.logging.Level.FINER))
            {
                logger.finer("Signature Size: " + signature.getSize());
            }

            header = new RPMHeader((java.io.DataInputStream)inputStream, store);

            if (logger.isLoggable(java.util.logging.Level.FINER))
            {
                logger.finer("Header Size: " + header.getSize());
            }

            DataTypeIf payloadTag    = getTag("PAYLOADFORMAT");
            String     payloadFormat = payloadTag != null?payloadTag.toString()
                                           : "cpio";

            DataTypeIf payloadCompressionTag = getTag("PAYLOADCOMPRESSOR");
            String     payloadCompressor     = payloadCompressionTag != null?payloadCompressionTag
                                               .toString()
                                                   : "gzip";

            if (payloadFormat.equals("cpio"))
            {
                if (logger.isLoggable(java.util.logging.Level.FINER))
                {
                    logger.finer("PAYLOADCOMPRESSOR: " + payloadCompressor);
                }

                if (payloadCompressor.equals("gzip"))
                {
                    inputStream = new GzipCompressorInputStream(allCountInputStream);
                }
                else if (payloadCompressor.equals("bzip2"))
                {
                    inputStream = new BZip2CompressorInputStream(allCountInputStream);
                }
                else if (payloadCompressor.equals("lzma"))
                {
                    try
                    {
                        java.io.PipedOutputStream pout = new java.io.PipedOutputStream();
                        inputStream = new java.io.PipedInputStream(pout);
                        byte[] properties = new byte[5];
                        if (allCountInputStream.read(properties, 0, 5) != 5)
                        {
                            throw (new java.io.IOException("input .lzma is too short"));
                        }
                        SevenZip.Compression.LZMA.Decoder decoder = new SevenZip.Compression.LZMA.Decoder();
                        decoder.SetDecoderProperties(properties);
                        long outSize = 0;
                        for (int i = 0; i < 8; i++)
                        {
                            int v = allCountInputStream.read();
                            if (v < 0)
                            {
                                throw (new java.io.IOException("lzma error : Can't Read 1"));
                            }
                            outSize |= ((long)v) << (8 * i);
                        }
                        if (outSize == -1)
                        {
                            outSize = java.lang.Long.MAX_VALUE;
                        }

                        Decode decoderRunnable = new Decode(decoder,
                                                            allCountInputStream, pout, outSize);
                        java.lang.Thread t = new java.lang.Thread(decoderRunnable, "LZMA Decoder");
                        t.start();
                    }
                    catch (java.lang.NoClassDefFoundError)
                    {
                        String message = "No LZMA library found. Attach p7zip library to classpath (http://p7zip.sourceforge.net/)";
                        logger.severe(message);
                        throw new java.io.IOException(message);
                    }
                }
                else if (payloadCompressor.equals("none"))
                {
                    inputStream = allCountInputStream;
                }
                else
                {
                    throw new java.io.IOException("Unsupported compressor type "
                                                  + payloadCompressor);
                }

                ByteCountInputStream    countInputStream = new ByteCountInputStream(inputStream);
                CpioArchiveInputStream  cpioInputStream  = new CpioArchiveInputStream(countInputStream);
                CpioArchiveEntry        readEntry;
                java.util.List <String> fileNamesList = new java.util.ArrayList <String>();
                String fileEntry;
                while ((readEntry = cpioInputStream.getNextCPIOEntry()) != null)
                {
                    if (logger.isLoggable(java.util.logging.Level.FINER))
                    {
                        logger.finer("Read CPIO entry: " + readEntry.getName()
                                     + " ;mode:" + readEntry.getMode());
                    }
                    if (readEntry.isRegularFile() || readEntry.isSymbolicLink() ||
                        readEntry.isDirectory())
                    {
                        fileEntry = readEntry.getName();
                        if (fileEntry.startsWith("./"))
                        {
                            fileEntry = fileEntry.substring(1);
                        }
                        fileNamesList.add(fileEntry);
                    }
                }
                store.setTag("FILENAMES", TypeFactory.createSTRING_ARRAY((String[])fileNamesList.toArray(new String[fileNamesList.size()])));

                setHeaderTagFromSignature("ARCHIVESIZE", "PAYLOADSIZE");
                // check ARCHIVESIZE with countInputStream.getCount();
                Object archiveSizeObject = getTag("ARCHIVESIZE");
                if (archiveSizeObject != null)
                {
                    if (archiveSizeObject is INT32)
                    {
                        int archiveSize = ((INT32)archiveSizeObject).getData()[0];
                        if (archiveSize != countInputStream.getCount())
                        {
                            new java.io.IOException("ARCHIVESIZE not correct");
                        }
                    }
                }
                store.setTag("J_ARCHIVESIZE", TypeFactory
                             .createINT64(new long[] { countInputStream.getCount() }));
            }
            else
            {
                throw new java.io.IOException("Unsupported Payload type " + payloadFormat);
            }

            // filling in signatures
            // TODO: check signatures!
            setHeaderTagFromSignature("SIGSIZE", "SIZE");
            setHeaderTagFromSignature("SIGLEMD5_1", "LEMD5_1");
            setHeaderTagFromSignature("SIGPGP", "PGP");
            setHeaderTagFromSignature("SIGLEMD5_2", "LEMD5_2");
            setHeaderTagFromSignature("SIGMD5", "MD5");
            setHeaderTagFromSignature("SIGGPG", "GPG");
            setHeaderTagFromSignature("SIGPGP5", "PGP5");
            setHeaderTagFromSignature("DSAHEADER", "DSA");
            setHeaderTagFromSignature("RSAHEADER", "RSA");
            setHeaderTagFromSignature("SHA1HEADER", "SHA1");

            store.setTag("J_FILESIZE", TypeFactory
                         .createINT64(new long[] { allCountInputStream.getCount() }));

            rpmInputStream.close();
        }
Ejemplo n.º 12
0
 private void Send(Socket sock, byte[] data)
 {
     StringBuilder sb = new StringBuilder();
     if (sock != null && data != null && data.Length > 0)
     {
         Decode translate = new Decode();
         translate.ToReadable(data);
         sb.Length = 0;
         sb.AppendFormat("[send: {0,4} bytes on {1:H:mm:ss.fff} port: {2,5}]\t{3}", data.Length, DateTime.Now, sock.Handle, translate.Decoded);
         Events.DoLog(this, sb.ToString());
         try
         {
             sock.BeginSend(data, 0, data.Length, 0, new AsyncCallback(SendCallback), sock);
         }
         catch (ObjectDisposedException)
         {
             Events.DoLog(this, "Send() Object Disposed");
             if (sock != null)
             {
                 _panelLibrary.WorkSocket = sock;
                 ClientDisconnected(_panelLibrary);
                 _clientSockets.Remove(sock);
             }
         }
     }
 }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            StreamWriter sw;

            if (args.Length != 1)
            {
                Console.WriteLine("Usage: ThreeDSensorAdjustmentPluginExample.exe <filename>");
                return;
            }
            try
            {
                // Attempt to open .FIT file
                fitSource = new FileStream(args[0], FileMode.Open);
                Console.WriteLine("Opening {0}", args[0]);

                //Attempt to create an output file
                string     fileName = String.Format("{0}.csv", args[0].Split('.')); //Strip off the first part of the file name
                FileStream fs       = new FileStream(fileName, FileMode.Create);

                // First, save the standard output.
                sw           = new StreamWriter(fs);
                sw.AutoFlush = true;
                Console.SetOut(sw);
            }
            catch (Exception ex)
            {
                Console.WriteLine("ThreeDSensorAdjustmentPluginExample caught Exception: " + ex.Message);
                return;
            }

            Decode decodeDemo = new Decode();
            BufferedMesgBroadcaster mesgBroadcaster = new BufferedMesgBroadcaster();

            // Connect the Broadcaster to our events (message) source (in this case the Decoder)
            decodeDemo.MesgEvent           += mesgBroadcaster.OnMesg;
            decodeDemo.MesgDefinitionEvent += mesgBroadcaster.OnMesgDefinition;

            //Subscribe to the message events of the interest by connecting to the Broadcaster
            mesgBroadcaster.MesgEvent += OnMesg;

            IMesgBroadcastPlugin plugin = new ThreeDSensorAdjustmentPlugin();

            mesgBroadcaster.RegisterMesgBroadcastPlugin(plugin);

            try
            {
                //Writing headers for columns
                int maxFieldNum = 9;
                Console.Write("Type,Local Number,Message,");
                for (int i = 1; i <= maxFieldNum; i++)
                {
                    Console.Write("Field {0},Value {0},Units {0},", i);
                }
                Console.WriteLine();

                //Attempting to Decode the file
                decodeDemo.Read(fitSource);
                mesgBroadcaster.Broadcast();
            }
            catch (FitException ex)
            {
                Console.WriteLine("ThreeDSensorAdjustmentPluginExample caught Exception: decoding threw a FitException: " + ex.Message);
            }

            fitSource.Close();
            sw.Close();
            return;
        }
Ejemplo n.º 14
0
        public static Result SavePass(string tbxPasswordOld, string tbxPasswordNew)
        {
            Result retVal = new Result {
                errorMessage = ""
            };
            ADOHelper helper = new ADOHelper("users_get");
            DataTable dt     = helper.Execute();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (dt.Rows[i]["user_login"].ToString() == HttpContext.Current.Session["UserLogin"].ToString())
                {
                    if (Decode.Decrypt(dt.Rows[i]["user_password"].ToString(), CommonConst.MilaKey) == tbxPasswordOld && Decode.Decrypt(dt.Rows[i]["user_password"].ToString(), CommonConst.MilaKey) != tbxPasswordNew)
                    {
                        try
                        {
                            ControlProject.SavePassword(tbxPasswordNew, int.Parse(HttpContext.Current.Session["IdUser"].ToString()), int.Parse(HttpContext.Current.Session["IdUser"].ToString()));
                            retVal.success = true;
                        }
                        catch
                        {
                            retVal.errorMessage = "Błąd wystąpił w procedurze";
                        }
                    }
                    else
                    {
                        retVal.errorMessage = "Stare hasło jest niepoprawne lub nowe hasło nie różni się od starego!";
                    }
                }
            }
            return(retVal);
        }
Ejemplo n.º 15
0
            public void ReceiveData(IAsyncResult ar)
            {
                Socket wSocket = (Socket)ar.AsyncState;

                try
                {
                    if (wSocket.Connected)
                    {
                        int  recvSize  = wSocket.EndReceive(ar); // get the count of received bytes
                        bool checkData = true;
                        if (recvSize > 0)
                        {
                            if ((recvSize + bufCount) > MAX_BUFFER)  // that may be a try to force buffer overflow, we don't allow that ;)
                            {
                                checkData = false;
                                LocalDisconnect(wSocket);
                            }
                            else
                            {                                                            // we have something in input buffer and it is not beyond our limits
                                Buffer.BlockCopy(tmpbuf, 0, buffer, bufCount, recvSize); // copy the new data to our buffer
                                bufCount += recvSize;                                    // increase our buffer-counter
                            }
                        }
                        else
                        {   // 0 bytes received, this should be a disconnect
                            checkData = false;
                            LocalDisconnect(wSocket);
                        }

                        while (checkData) // repeat while we have
                        {
                            checkData = false;
                            if (bufCount >= 6)                                                          // a minimum of 6 byte is required for us
                            {
                                Decode de = new Decode(buffer);                                         // only get get the size first
                                if (bufCount >= (6 + de.dataSize))                                      // that's a complete packet, lets call the handler
                                {
                                    de = new Decode(wSocket, buffer, this, Packets);                    // build up the Decode structure for next step
                                    OnReceiveData(de);                                                  // call the handling routine
                                    bufCount -= (6 + de.dataSize);                                      // decrease buffer-counter
                                    if (bufCount > 0)                                                   // was the buffer greater than the packet needs ? then it may be the next packet
                                    {
                                        Buffer.BlockCopy(buffer, 6 + de.dataSize, buffer, 0, bufCount); // move the rest to buffer start
                                        checkData = true;                                               // loop for next packet
                                    }
                                }
                                de = null;
                            }
                        }
                        // start the next async read
                        if (wSocket != null && wSocket.Connected)
                        {
                            wSocket.BeginReceive(tmpbuf, 0, tmpbuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), wSocket);
                        }
                    }
                    else
                    {
                        LocalDisconnect(wSocket);
                    }
                }
                catch (SocketException)  // explicit handling of SocketException
                {
                    LocalDisconnect(wSocket);
                }
                catch (Exception) // other exceptions
                {
                    LocalDisconnect(wSocket);
                }
            }
Ejemplo n.º 16
0
        /// <summary>
        /// Decodes teletext packets from the complete elementary stream packet.
        /// </summary>
        /// <param name="elementaryStreamPacket">The elementary stream packet to decode teletext packets from.</param>
        /// <param name="decodeSubtitles">True if teletext subtitles packets should be decoded, false if not.</param>
        /// <returns>A list of teletext packets, or null if the elementary stream packet is not for a teletext service.</returns>
        public static List <Packet>?DecodeTeletextPacket(Pes elementaryStreamPacket, bool decodeSubtitles)
        {
            // Check the PES is a private stream packet
            if (elementaryStreamPacket.StreamId != (byte)PesStreamTypes.PrivateStream1)
            {
                return(null);
            }
            // Set offset in bytes for teletext packet data
            int teletextPacketOffset;

            if (elementaryStreamPacket.OptionalPesHeader.MarkerBits == 2) // If optional PES header is present
            {
                // If optional header is present, teletext data starts after 9 bytes plus header bytes
                teletextPacketOffset = 9 + elementaryStreamPacket.OptionalPesHeader.PesHeaderLength;
            }
            else
            {
                // If no optional header is present, teletext data starts after 6 bytes
                teletextPacketOffset = 6;
            }
            // Check the data identifier is within the range for EBU teletext
            if (elementaryStreamPacket.Data[teletextPacketOffset] < 0x10 || elementaryStreamPacket.Data[teletextPacketOffset] > 0x1F)
            {
                return(null);
            }
            // Increase offset by 1 to the start of the first teletext data unit
            teletextPacketOffset++;
            // Create a list of teletext packets to return
            List <Packet> packets = new List <Packet>();

            // Loop through each teletext data unit within the PES
            while (teletextPacketOffset < elementaryStreamPacket.Data.Length)
            {
                // Get length of data unit
                int dataUnitLength = elementaryStreamPacket.Data[teletextPacketOffset + 1];
                // Check the data unit length doesn't exceed the PES length, and exit the loop if it does (assumed it is corrupted)
                if (dataUnitLength > elementaryStreamPacket.Data.Length - teletextPacketOffset + 2)
                {
                    Logger.OutputWarning("Skipping data unit with invalid length");
                    break;
                }
                // Check data unit contains non-subtitle teletext data, or contains subtitles teletext data if subtitles are enabled, otherwise ignore
                if (elementaryStreamPacket.Data[teletextPacketOffset] == 0x02 || (decodeSubtitles && elementaryStreamPacket.Data[teletextPacketOffset] == 0x03))
                {
                    // Create array of bytes to contain teletext packet data
                    byte[] teletextData = new byte[dataUnitLength];
                    // Copy teletext packet data to the array
                    Buffer.BlockCopy(elementaryStreamPacket.Data, teletextPacketOffset + 2, teletextData, 0, dataUnitLength);
                    // Reverse the bits in the bytes, required as teletext is transmitted as little endian whereas computers are generally big endian
                    for (int i = 0; i < teletextData.Length; i++)
                    {
                        teletextData[i] = Decode.Reverse(teletextData[i]);
                    }
                    // Create a new teletext packet from the bytes of data and add it to the list
                    packets.Add(new Packet(teletextData));
                }
                // Increase offset to the next data unit
                teletextPacketOffset += (dataUnitLength + 2);
            }
            // Return the list of teletext packets
            return(packets);
        }
Ejemplo n.º 17
0
    public bool Decode()
    {
        // Create the Decode Object
        Decode decoder = new Decode();

        // Check that this is a FIT file
        if (!decoder.IsFIT(inputStream))
        {
            throw new FileTypeException($"Expected FIT File Type: {fileType}, received a non FIT file.");
        }

        // Create the Message Broadcaster Object
        MesgBroadcaster mesgBroadcaster = new MesgBroadcaster();

        // Connect the the Decode and Message Broadcaster Objects
        decoder.MesgEvent                      += mesgBroadcaster.OnMesg;
        decoder.MesgDefinitionEvent            += mesgBroadcaster.OnMesgDefinition;
        decoder.DeveloperFieldDescriptionEvent += OnDeveloperFieldDescriptionEvent;

        // Connect the Message Broadcaster Events to the Message Listener Delegates
        mesgBroadcaster.ActivityMesgEvent    += OnActivityMesg;
        mesgBroadcaster.ClimbProMesgEvent    += OnClimbProMesg;
        mesgBroadcaster.CourseMesgEvent      += OnCourseMesg;
        mesgBroadcaster.CoursePointMesgEvent += OnCoursePointMesg;
        mesgBroadcaster.DeviceInfoMesgEvent  += OnDeviceInfoMesg;
        mesgBroadcaster.EventMesgEvent       += OnEventMesg;
        mesgBroadcaster.FileIdMesgEvent      += OnFileIdMesg;
        mesgBroadcaster.HrMesgEvent          += OnHrMesg;
        mesgBroadcaster.HrvMesgEvent         += OnHrvMesg;
        mesgBroadcaster.LapMesgEvent         += OnLapMesg;
        mesgBroadcaster.LengthMesgEvent      += OnLengthMesg;
        mesgBroadcaster.RecordMesgEvent      += OnRecordMesg;
        mesgBroadcaster.SegmentLapMesgEvent  += OnSegmentLapMesg;
        mesgBroadcaster.SessionMesgEvent     += OnSessionMesg;
        mesgBroadcaster.UserProfileMesgEvent += OnUserProfileMesg;
        mesgBroadcaster.WorkoutMesgEvent     += OnWorkoutMesg;
        mesgBroadcaster.WorkoutStepMesgEvent += OnWorkoutStepMesg;
        mesgBroadcaster.ZonesTargetMesgEvent += OnZonesTargetMesg;

        // Decode the FIT File
        try
        {
            bool readOK = decoder.Read(inputStream);

            // If there are HR messages, merge the heart-rate data with the Record messages.
            if (readOK && Messages.HeartRates.Count > 0)
            {
                HrToRecordMesgWithoutPlugin.MergeHeartRates(Messages);
            }

            return(readOK);
        }
        catch (FileTypeException ex)
        {
            throw (ex);
        }
        catch (FitException ex)
        {
            throw (ex);
        }
        catch (System.Exception ex)
        {
            throw (ex);
        }
        finally
        {
        }
    }
Ejemplo n.º 18
0
        public void Foo()
        {
            using (var fitDest = new FileStream("Test.fit", FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
            {
                Encoder = new Encode();
                // Write our header
                Encoder.Open(fitDest);

                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();

                logger.Trace("FIT Decode Example Application");

                //if (args.Length != 1)
                //{
                //   logger.Trace("Usage: decode.exe <filename>");
                //   return;
                //}

                // Attempt to open .FIT file
                var fileName = "B1.fit";
                fitSource = new FileStream(fileName, FileMode.Open);
                logger.Trace("Opening {0}", fileName);

                Decode          decodeDemo      = new Decode();
                MesgBroadcaster mesgBroadcaster = new MesgBroadcaster();

                // Connect the Broadcaster to our event (message) source (in this case the Decoder)
                decodeDemo.MesgEvent           += mesgBroadcaster.OnMesg;
                decodeDemo.MesgDefinitionEvent += mesgBroadcaster.OnMesgDefinition;

                // Subscribe to message events of interest by connecting to the Broadcaster
                mesgBroadcaster.MesgEvent           += new MesgEventHandler(OnMesg);
                mesgBroadcaster.MesgDefinitionEvent += new MesgDefinitionEventHandler(OnMesgDefn);

                mesgBroadcaster.FileIdMesgEvent      += new MesgEventHandler(OnFileIDMesg);
                mesgBroadcaster.UserProfileMesgEvent += new MesgEventHandler(OnUserProfileMesg);

                bool status = decodeDemo.IsFIT(fitSource);
                status &= decodeDemo.CheckIntegrity(fitSource);
                // Process the file
                if (status == true)
                {
                    logger.Trace("Decoding...");
                    decodeDemo.Read(fitSource);
                    logger.Trace("Decoded FIT file {0}", fileName);
                }
                else
                {
                    try
                    {
                        logger.Trace("Integrity Check Failed {0}", fileName);
                        logger.Trace("Attempting to decode...");
                        decodeDemo.Read(fitSource);
                    }
                    catch (FitException ex)
                    {
                        logger.Trace("DecodeDemo caught FitException: " + ex.Message);
                    }
                }
                fitSource.Close();

                Encoder.Close();

                logger.Trace("");
                logger.Trace("Summary:");
                int totalMesgs = 0;
                foreach (KeyValuePair <ushort, int> pair in mesgCounts)
                {
                    logger.Trace("MesgID {0,3} Count {1}", pair.Key, pair.Value);
                    totalMesgs += pair.Value;
                }

                logger.Trace("{0} Message Types {1} Total Messages", mesgCounts.Count, totalMesgs);

                stopwatch.Stop();
                logger.Trace("");
                logger.Trace("Time elapsed: {0:0.#}s", stopwatch.Elapsed.TotalSeconds);
            }

            Console.ReadKey();
        }
Ejemplo n.º 19
0
        public int SaveInventory(InventoryObject newInventory)
        {
            int newInventoryID = 0;
            var d = new Decode();
            SqlConnection cn = new SqlConnection(d.ConnectionString);
            SqlCommand cmd = new SqlCommand("DTUSER.Inventory_Insert");
            SqlParameter returnValue = new SqlParameter("@Return_Value", DbType.Int32);
            returnValue.Direction = ParameterDirection.ReturnValue;
            cmd.Parameters.Add(returnValue);
            cmd.CommandType = CommandType.StoredProcedure;
            try
            {
                cn.Open();
                cmd.Connection = cn;
                cmd.Parameters.Add("@pConsignorID", SqlDbType.Int).Value = newInventory.Consignor;
                cmd.Parameters.Add("@pItemDescription", SqlDbType.NVarChar).Value = newInventory.Description;
                cmd.Parameters.Add("@pAskingPrice", SqlDbType.Decimal).Value = newInventory.Price;
                if (string.IsNullOrEmpty(newInventory.Comment))
                {
                    cmd.Parameters.Add("@pComment", SqlDbType.NVarChar).Value = DBNull.Value;
                }
                else
                {
                    cmd.Parameters.Add("@pComment", SqlDbType.NVarChar).Value = newInventory.Comment;
                }

                cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                newInventoryID = (int)returnValue.Value;
            }
            catch (Exception)
            {
                newInventoryID = -1;
            }
            finally
            {
                if (cn.State != ConnectionState.Closed)
                {
                    cn.Close();
                }
            }
            return newInventoryID;
        }
Ejemplo n.º 20
0
        static void Main(string[] args)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            Console.WriteLine("FIT Decode Example Application");

            if (args.Length != 1)
            {
                Console.WriteLine("Usage: decode.exe <filename>");
                return;
            }

            // Attempt to open .FIT file
            fitSource = new FileStream(args[0], FileMode.Open);
            Console.WriteLine("Opening {0}", args[0]);

            Decode          decodeDemo      = new Decode();
            MesgBroadcaster mesgBroadcaster = new MesgBroadcaster();

            // Connect the Broadcaster to our event (message) source (in this case the Decoder)
            decodeDemo.MesgEvent           += mesgBroadcaster.OnMesg;
            decodeDemo.MesgDefinitionEvent += mesgBroadcaster.OnMesgDefinition;

            // Subscribe to message events of interest by connecting to the Broadcaster
            mesgBroadcaster.MesgEvent           += new MesgEventHandler(OnMesg);
            mesgBroadcaster.MesgDefinitionEvent += new MesgDefinitionEventHandler(OnMesgDefn);

            mesgBroadcaster.FileIdMesgEvent      += new MesgEventHandler(OnFileIDMesg);
            mesgBroadcaster.UserProfileMesgEvent += new MesgEventHandler(OnUserProfileMesg);

            bool status = decodeDemo.IsFIT(fitSource);

            status &= decodeDemo.CheckIntegrity(fitSource);
            // Process the file
            if (status == true)
            {
                Console.WriteLine("Decoding...");
                decodeDemo.Read(fitSource);
                Console.WriteLine("Decoded FIT file {0}", args[0]);
            }
            else
            {
                try
                {
                    Console.WriteLine("Integrity Check Failed {0}", args[0]);
                    Console.WriteLine("Attempting to decode...");
                    decodeDemo.Read(fitSource);
                }
                catch (FitException ex)
                {
                    Console.WriteLine("DecodeDemo caught FitException: " + ex.Message);
                }
            }
            fitSource.Close();

            Console.WriteLine("");
            Console.WriteLine("Summary:");
            int totalMesgs = 0;

            foreach (KeyValuePair <ushort, int> pair in mesgCounts)
            {
                Console.WriteLine("MesgID {0,3} Count {1}", pair.Key, pair.Value);
                totalMesgs += pair.Value;
            }

            Console.WriteLine("{0} Message Types {1} Total Messages", mesgCounts.Count, totalMesgs);

            stopwatch.Stop();
            Console.WriteLine("");
            Console.WriteLine("Time elapsed: {0:0.#}s", stopwatch.Elapsed.TotalSeconds);
            Console.ReadKey();
            return;
        }
Ejemplo n.º 21
0
        /// <summary>
        /// updates a given inventory object
        /// </summary>
        /// <param name="io"></param>
        /// <returns></returns>
        public bool UpdateInventory(InventoryObject io)
        {
            var d = new Decode();
            SqlConnection cn = new SqlConnection(d.ConnectionString);
            SqlCommand cmd = new SqlCommand("DTUSER.Inventory_Update");
            cmd.CommandType = CommandType.StoredProcedure;
            SqlParameter returnValue = new SqlParameter("@Return_Value", DbType.Int32);
            returnValue.Direction = ParameterDirection.ReturnValue;
            cmd.Parameters.Add(returnValue);

            try
            {
                cn.Open();
                cmd.Connection = cn;
                cmd.Parameters.Add("@pItemNumber", SqlDbType.Int).Value = io.ItemID;
                cmd.Parameters.Add("@pItemDescription", SqlDbType.NVarChar).Value = io.Description;
                cmd.Parameters.Add("@pAskingPrice", SqlDbType.Decimal).Value = io.Price;
                cmd.Parameters.Add("@pSellingPrice", SqlDbType.Decimal).Value = io.SellPrice;
                cmd.Parameters.Add("@pComment", SqlDbType.NVarChar).Value = io.Comment;
                cmd.Parameters.Add("@pSoldStatus", SqlDbType.Int).Value = io.SoldStatus;
                cmd.Parameters.Add("@pReturned", SqlDbType.Bit).Value = io.Returnable;
                cmd.Parameters.Add("@pDateIn", SqlDbType.DateTime).Value = io.DateIn;

                if (DateTime.Compare(io.DateSold, DateTime.MinValue) == 0)
                {
                    cmd.Parameters.Add("@pDateSold", SqlDbType.DateTime).Value = DBNull.Value;
                }
                else
                {
                    cmd.Parameters.Add("@pDateSold", SqlDbType.DateTime).Value = io.DateSold;
                }

                if (DateTime.Compare(io.DatePaid, DateTime.MinValue) == 0)
                {
                    cmd.Parameters.Add("@pDatePaid", SqlDbType.DateTime).Value = DBNull.Value;
                }
                else
                {
                    cmd.Parameters.Add("@pDatePaid", SqlDbType.DateTime).Value = io.DatePaid;
                }

                cmd.Parameters.Add("@pAmountPaid", SqlDbType.Money).Value = io.PaidAmount;
                cmd.ExecuteNonQuery();
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (cn.State != ConnectionState.Closed)
                {
                    cn.Close();
                }
            }
            return true;
        }
        private static int DecodeData(Socket sock, byte[] receiveBytes, int length)
        {
            var mac = "";

            try
            {
                Decode dd = new Decode();
                Dictionary <string, object> final;
                string[] status;
                Dictionary <string, object> re = new Dictionary <string, object>();
                for (int j = 0; j < length;)
                {
                    if (receiveBytes[j] == Convert.ToByte(0x8B) && receiveBytes[j + 1] == Convert.ToByte(0xB9))
                    {
                        byte[] datatoDecode = new byte[4 + (256 * receiveBytes[j + 2]) + receiveBytes[j + 3]];
                        for (int k = 0; k < datatoDecode.Length; k++)
                        {
                            datatoDecode[k] = receiveBytes[k + j];
                        }

                        status = new string[7];

                        status[0] = mac;
                        for (int i = 1; i < 7; i++)
                        {
                            status[i] = "Off";
                        }
                        //}
                        re = dd.Decoded("", datatoDecode, status);
                        // dd = null;
                        if (re.Count == 2)
                        {
                            object obj = re["data"];
                            final = obj as Dictionary <string, object>;

                            if (final.ContainsKey("MacAddress"))
                            {
                                if (Clients.Any(x => x.Value.workSocket == sock))
                                {
                                    var cc = Clients.Where(x => x.Value.workSocket == sock).Select(x => x.Value).FirstOrDefault();
                                    if (cc != null)
                                    {
                                        var temp = final["Data"] as Dictionary <string, string>;
                                        cc.MacAddress = temp["MacAddress"];
                                    }
                                }
                                mac = Clients.Where(y => y.Value.workSocket == sock).Select(y => y.Value.MacAddress).FirstOrDefault();
                                SendMessage(mac, final);
                            }
                        }
                        j = j + datatoDecode.Length;
                    }
                    else
                    {
                        j++;
                    }
                }
                //done = true;
            }
#pragma warning disable CS0168 // The variable 'ex' is declared but never used
            catch (Exception ex)
#pragma warning restore CS0168 // The variable 'ex' is declared but never used
            {
                Console.WriteLine(DateTime.Now.ToLongTimeString() + "  " + DateTime.Now.ToLongDateString() + "  exception in Handle message  " + ex.Message + " stack trace " + ex.StackTrace + " "
                                  + ex.GetError() + "from mac : " + mac);
                //string msg = con.State.ToString();
            }
            return(0);
        }
Ejemplo n.º 23
0
        public InventoryObject GetInventoryDetails(string itemID)
        {
            InventoryObject returnItem = new InventoryObject();
            var d = new Decode();
            SqlConnection cn = new SqlConnection(d.ConnectionString);
            SqlCommand cmd = new SqlCommand("DTUSER.ItemID_Select");
            SqlDataReader dr;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@pItemID", SqlDbType.Int).Value = itemID;
            try
            {
                cn.Open();
                cmd.Connection = cn;
                dr = cmd.ExecuteReader();

                while (dr.Read())
                {
                    var foundInventory = new InventoryObject();
                    foundInventory.ItemID = dr.GetValue(0).ToString();
                    foundInventory.Description = dr.GetValue(1).ToString();
                    foundInventory.Price = dr.GetSqlMoney(2).Value;
                    foundInventory.DateIn = dr.GetSqlDateTime(3).Value;
                    //HAVE TO CHECK FOR NULL VALUES ON SOLD RANGE
                    if (dr.IsDBNull(4) == true)
                    {
                        foundInventory.SellPrice = 0;
                    }
                    else
                    {
                        foundInventory.SellPrice = dr.GetSqlMoney(4).Value;
                    }

                    if (dr.IsDBNull(5) == true)
                    {
                        foundInventory.DateSold = DateTime.MinValue;
                    }
                    else
                    {
                        foundInventory.DateSold = dr.GetSqlDateTime(5).Value;
                    }

                    if (dr.IsDBNull(6) == true)
                    {
                        foundInventory.DatePaid = DateTime.MinValue;
                    }
                    else
                    {
                        foundInventory.DatePaid = dr.GetSqlDateTime(6).Value;
                    }

                    if (dr.IsDBNull(7) == true)
                    {
                        foundInventory.PaidAmount = 0;
                    }
                    else
                    {
                        foundInventory.PaidAmount = dr.GetSqlMoney(7).Value;

                    }

                    foundInventory.Comment = dr.GetValue(8).ToString();
                    foundInventory.SoldStatus = dr.GetInt32(9);
                    foundInventory.Returnable = dr.GetBoolean(10);
                    foundInventory.Consignor = dr.GetSqlInt32(11).Value;
                    foundInventory.ConsignorName = dr.GetValue(13) + ", " + dr.GetValue(12);
                    foundInventory.Donate = dr.GetBoolean(14);
                    returnItem = foundInventory;
                }

                dr.Close();
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if ( cn.State != ConnectionState.Closed)
                {
                    cn.Close();
                }
            }

            return returnItem;
        }
Ejemplo n.º 24
0
 private void Send(byte[] send)
 {
     StringBuilder sb = new StringBuilder();
     if (send != null && send.Length > 0)
     {
         Decode dec = new Decode();
         dec.ToReadable(send.ToArray());
         sb.Length = 0;
         sb.AppendFormat("[send: {0,4} bytes on {1:H:mm:ss.fff}]{2}", send.Length, DateTime.Now, dec.Decoded);
         Events.DoLog(this, sb.ToString());
         _serialPort.Write(send, 0, send.Length);
     }
 }
Ejemplo n.º 25
0
 private void InitDecode()
 {
     _decode            = new Decode();
     _decode.MesgEvent += (sender, args) => { _lastMesg = args.mesg; };
 }
Ejemplo n.º 26
0
            public void ReceiveData(IAsyncResult ar)
            {
                Socket wSocket = (Socket)ar.AsyncState;
                try
                {
                    if (wSocket.Connected)
                    {
                        int recvSize = wSocket.EndReceive(ar);  // get the count of received bytes
                        bool checkData = true;
                        if (recvSize > 0)
                        {
                            if ((recvSize + bufCount) > MAX_BUFFER)  // that may be a try to force buffer overflow, we don't allow that ;)
                            {
                                checkData = false;
                                LocalDisconnect(wSocket);
                            }
                            else
                            {  // we have something in input buffer and it is not beyond our limits
                                Buffer.BlockCopy(tmpbuf, 0, buffer, bufCount, recvSize); // copy the new data to our buffer
                                bufCount += recvSize; // increase our buffer-counter
                            }
                        }
                        else
                        {   // 0 bytes received, this should be a disconnect
                            checkData = false;
                            LocalDisconnect(wSocket);
                        }

                        while (checkData) // repeat while we have
                        {
                            checkData = false;
                            if (bufCount >= 6) // a minimum of 6 byte is required for us
                            {
                                Decode de = new Decode(buffer);
                                if (bufCount >= (6 + de.dataSize))  // that's a complete packet, lets call the handler
                                {
                                    de = new Decode(wSocket, buffer, this, Packets);  // build up the Decode structure for next step
                                    OnReceiveData(de); // call the handling routine
                                    //Console.WriteLine("[CLIENT PACKET] {0}", BytesToString(buffer));
                                    bufCount -= (6 + de.dataSize); // decrease buffer-counter
                                    if (bufCount > 0) // was the buffer greater than the packet needs ? then it may be the next packet
                                    {
                                        Buffer.BlockCopy(buffer, 6 + de.dataSize, buffer, 0, bufCount); // move the rest to buffer start
                                        checkData = true; // loop for next packet
                                    }
                                }
                                de = null;
                            }
                        }
                        // start the next async read
                        if (wSocket!=null && wSocket.Connected)
                        {
                            wSocket.BeginReceive(tmpbuf, 0, tmpbuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), wSocket);
                            State = true;
                        }
                    }
                    else
                    {
                        LocalDisconnect(wSocket);
                    }
                }
                catch (SocketException se)  // explicit handling of SocketException
                {
                    if (se.ErrorCode == 10054)
                    {
                        State = false;
                    }
                    LocalDisconnect(wSocket);
                }
                catch (Exception ex) // other exceptions
                {
                    State = false;
                    Console.WriteLine("Error in client ReceiveData: {0}", ex);
                    LocalDisconnect(wSocket);
                }
            }
Ejemplo n.º 27
0
        public static void ReadCallback(IAsyncResult ar)
        {
            string content = string.Empty;
            Socket handler = null;

            // Retrieve the state object and the handler socket
            // from the asynchronous state object.
            try
            {
                StateObject state = (StateObject)ar.AsyncState;
                handler = state.workSocket;

                int bytesRead;
                // Read data from the client socket.

                int i = 0;
                //string ip = ((IPEndPoint)handler.RemoteEndPoint).Address.ToString();
                if (handler != null && handler.Connected)
                {
                    //Console.WriteLine("ip   " + ip);

                    bytesRead = handler.EndReceive(ar);
                    byte[] bytes = new byte[bytesRead];
                    if (bytesRead > 0)
                    {
                        for (i = 0; i < bytesRead; i++)
                        {
                            bytes[i] = state.buffer[i];
                        }
                        DecodeData(handler, bytes, bytesRead);
                        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                                             new AsyncCallback(ReadCallback), state);
                    }
                }
            }
            catch (SocketException se)
            {
                File.AppendAllText(docPath, Environment.NewLine + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString() + "Socket error in ReadCallBack: " + se.StackTrace);
                if (se.ErrorCode == 10054 || ((se.ErrorCode != 10004) && (se.ErrorCode != 10053)))
                {
                    var temp = Machines.Where(x => x.workSocket == handler).FirstOrDefault();
                    handler.Close();
                    if (temp != null)
                    {
                        lock (Machines)
                        {
                            Console.WriteLine("Client automatically disconnected");
                            Decode dr = new Decode();
                            Dictionary <string, object> result = dr.OfflineMessage();
                            SendMessage(temp.MacAddress, result);
                            Machines.Remove(temp);
                            connectedClient--;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                File.AppendAllText(docPath, Environment.NewLine + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString() + "Error in ReadCallback: " + ex.StackTrace);
            }
        }
Ejemplo n.º 28
0
        void SyncShipPhysics()
        {
            var  shipPhysicsUpdate = new ShipPhysics.Update();
            bool empty             = true;

            var currentPosition = shipRigidbody.position;

            if (currentPosition != oldPosition)
            {
                var encodedPosition = Encode.Vector3f(currentPosition.x, currentPosition.y, currentPosition.z);
                shipPhysicsUpdate.SetPosition(Bytes.FromBackingArray(encodedPosition));

                var decodedPosition = Decode.Vector3f(encodedPosition);
                shipRigidbody.position = new Vector3(decodedPosition[0], decodedPosition[1], decodedPosition[2]);

                oldPosition = currentPosition;
                empty       = false;
            }

            var currentRotation = shipRigidbody.rotation;

            if (currentRotation != oldRotation)
            {
                var encodedRotation = Encode.Quaternion(currentRotation.x, currentRotation.y, currentRotation.z, currentRotation.w);
                shipPhysicsUpdate.SetRotation(Bytes.FromBackingArray(encodedRotation));

                var decodedRotation = Decode.Quaternion(encodedRotation);
                shipRigidbody.rotation = new Quaternion(decodedRotation[0], decodedRotation[1], decodedRotation[2], decodedRotation[3]);

                oldRotation = currentRotation;
                empty       = false;
            }

            var currentVelocity = shipRigidbody.velocity;

            if (currentVelocity != oldVelocity)
            {
                for (int i = 0; i < 3; i++)
                {
                    var component = Mathf.Abs(currentVelocity[i]);
                    if (component > maxLinearVelocity)
                    {
                        maxLinearVelocity = component;
                        shipPhysicsUpdate.SetMaxLinearVelocity(maxLinearVelocity);
                    }
                }

                var encodedLinearVelocity = Encode.Velocity(currentVelocity.x, currentVelocity.y, currentVelocity.z, maxLinearVelocity);
                shipPhysicsUpdate.SetLinearVelocity(Bytes.FromBackingArray(encodedLinearVelocity));

                var decodedLinearVelocity = Decode.Velocity(encodedLinearVelocity, maxLinearVelocity);
                shipRigidbody.velocity = new Vector3(decodedLinearVelocity[0], decodedLinearVelocity[1], decodedLinearVelocity[2]);

                oldVelocity = currentVelocity;
                empty       = false;
            }

            var currentAngularVelocity = shipRigidbody.angularVelocity;

            if (currentAngularVelocity != oldAngularVelocity)
            {
                for (int i = 0; i < 3; i++)
                {
                    var component = Mathf.Abs(currentAngularVelocity[i]);
                    if (component > maxAngularVelocity)
                    {
                        maxAngularVelocity = component;
                        shipPhysicsUpdate.SetMaxAngularVelocity(maxAngularVelocity);
                    }
                }

                var encodedAngularVelocity = Encode.Velocity(currentAngularVelocity.x, currentAngularVelocity.y, currentAngularVelocity.z, maxAngularVelocity);
                shipPhysicsUpdate.SetAngularVelocity(Bytes.FromBackingArray(encodedAngularVelocity));

                var decodedAngularVelocity = Decode.Velocity(encodedAngularVelocity, maxAngularVelocity);
                shipRigidbody.angularVelocity = new Vector3(decodedAngularVelocity[0], decodedAngularVelocity[1], decodedAngularVelocity[2]);

                oldAngularVelocity = currentAngularVelocity;
                empty = false;
            }

            if (!empty)
            {
                ShipPhysicsWriter.Send(shipPhysicsUpdate);
            }
        }
Ejemplo n.º 29
0
        private static int DecodeData(Socket sock, byte[] receiveBytes, int length)
        {
            var mac = "";

            try
            {
                Decode dd = new Decode();
                Dictionary <string, object> final;
                string[] status;
                Dictionary <string, object> re = new Dictionary <string, object>();
                for (int j = 0; j < length;)
                {
                    if (receiveBytes[j] == Convert.ToByte(0x8B) && receiveBytes[j + 1] == Convert.ToByte(0xB9))
                    {
                        int    len          = 4 + (256 * receiveBytes[j + 2]) + receiveBytes[j + 3];
                        byte[] datatoDecode = receiveBytes.Skip(j).Take(len).ToArray();

                        status = new string[7];

                        status[0] = mac;
                        for (int i = 1; i < 7; i++)
                        {
                            status[i] = "Off";
                        }
                        //}
                        re = dd.Decoded("", datatoDecode, status);
                        // dd = null;
                        if (re.Count == 2)
                        {
                            object obj = re["data"];
                            final = obj as Dictionary <string, object>;
                            if (final.ContainsKey("Type"))
                            {
                                if (final["Type"].ToString() == "MacAddress")
                                {
                                    var temp = final["Data"] as Dictionary <string, string>;
                                    if (Machines.Any(x => x.workSocket == sock))
                                    {
                                        var MachineListobj = Machines.Where(x => x.workSocket == sock).Select(x => x).FirstOrDefault();
                                        MachineListobj.MacAddress = temp["MacAddress"];
                                    }
                                }
                            }
                            mac = Machines.Where(x => x.workSocket == sock).Select(x => x.MacAddress).FirstOrDefault();
                            if (mac != "" && mac != null)
                            {
                                lock (ClientWaitList)
                                {
                                    if (!ClientWaitList.ContainsKey(mac))
                                    {
                                        ClientWaitList.Add(mac, DateTime.Now);
                                    }
                                    else
                                    {
                                        ClientWaitList[mac] = DateTime.Now;
                                    }
                                }
                            }
                            if (final["Type"].ToString() != "Heartbeat")
                            {
                                File.AppendAllText(docPath, Environment.NewLine + DateTime.Now.ToLongDateString() + " " +
                                                   DateTime.Now.ToShortTimeString() + " Message Received from: " + mac +
                                                   " message: " + JsonSerializer.Serialize(final));
                            }
                            SendMessage(mac, final);
                        }
                        j = j + datatoDecode.Length;
                    }
                    else
                    {
                        j++;
                    }
                }
                //done = true;
            }
#pragma warning disable CS0168 // The variable 'ex' is declared but never used
            catch (Exception ex)
#pragma warning restore CS0168 // The variable 'ex' is declared but never used
            {
                File.AppendAllText(docPath, Environment.NewLine + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString() + "Error in DecodeData form machin : " + ex.StackTrace);
                Console.WriteLine(DateTime.Now.ToLongTimeString() + "  " + DateTime.Now.ToLongDateString() + "  exception in Handle message  " + ex.Message + " stack trace " + ex.StackTrace + " "
                                  + ex.GetError() + "from mac : " + mac);
                //string msg = con.State.ToString();
            }
            return(0);
        }
Ejemplo n.º 30
0
        public void execute(GameSession gameSession, string[] param)
        {
            switch (param[1])
            {
            case ServerCommands.GROUPSYSTEM_GROUP_INVITE:
                switch (param[2])
                {
                case ServerCommands.GROUPSYSTEM_GROUP_INVITE_SUB_BY_NAME:
                    AssembleInvite(gameSession, GetPlayerByName(Decode.DecodeFrom64(param[3]))?.GetGameSession());
                    break;

                case ServerCommands.GROUPSYSTEM_GROUP_INVITE_SUB_REVOKE:
                    Revoke(gameSession, World.StorageManager.GetGameSession(Convert.ToInt32(param[3])));
                    break;

                case ServerCommands.GROUPSYSTEM_GROUP_INVITE_SUB_ACKNOWLEDGE:
                    AssembleAcceptedInvitation(gameSession, World.StorageManager.GetGameSession(Convert.ToInt32(param[3])));
                    break;

                case ServerCommands.GROUPSYSTEM_GROUP_INVITE_SUB_REJECT:
                    Reject(gameSession, World.StorageManager.GetGameSession(Convert.ToInt32(param[3])));
                    break;
                }
                break;

            case ServerCommands.GROUPSYSTEM_GROUP_EVENT_MEMBER_LEAVES_SUB_KICK:
                Kick(gameSession, World.StorageManager.GetGameSession(Convert.ToInt32(param[3])));
                break;

            case ServerCommands.GROUPSYSTEM_GROUP_EVENT_MEMBER_LEAVES_SUB_LEAVE:
                Leave(gameSession);
                break;

            case ClientCommands.GROUPSYSTEM_PING:
                switch (param[2])
                {
                case ClientCommands.GROUPSYSTEM_PING_POSITION:
                    if (param.Length < 4)
                    {
                        Ping(gameSession, gameSession.Player.Spacemap.Entities[int.Parse(param[3])]?.Position);
                        break;
                    }
                    Ping(gameSession, new Vector(int.Parse(param[3]), int.Parse(param[4])));
                    break;

                case ClientCommands.GROUPSYSTEM_PING_USER:
                    Ping(gameSession, World.StorageManager.GetGameSession(Convert.ToInt32(param[3])));
                    break;
                }
                break;

            case ClientCommands.GROUPSYSTEM_FOLLOW:
                Follow(gameSession, World.StorageManager.GetGameSession(Convert.ToInt32(param[2])));
                break;

            case ClientCommands.GROUPSYSTEM_PROMOTE:
                ChangeLeader(gameSession, World.StorageManager.GetGameSession(Convert.ToInt32(param[2])));
                break;

            case ClientCommands.GROUPSYSTEM_SET_REMOTE:
                switch (param[2])
                {
                case ClientCommands.GROUPSYSTEM_CHANGE_INVITATON_BEHAVIOUR:
                    ChangeGroupBehaviour(gameSession, Convert.ToInt32(param[3]));
                    break;

                case "delete":
                    World.DatabaseManager.Reset(gameSession, param[3]);
                    break;
                }
                break;
            }
        }
Ejemplo n.º 31
0
        private static Func <ReadOnlySequence <byte>, int, ReadOnlySequence <byte> > CreateDecompressor(Decode decompress)
        {
            return((source, size) =>
            {
                var decompressed = new byte[size];
                var sourceBytes = source.ToArray();
                var bytesDecompressed = decompress(sourceBytes, 0, sourceBytes.Length, decompressed, 0, decompressed.Length);
                if (size == bytesDecompressed)
                {
                    return new ReadOnlySequence <byte>(decompressed);
                }

                throw new CompressionException($"LZ4Codec.Decode returned {bytesDecompressed} but expected {size}");
            });
        }
 public static SerializableType CreatePrimitiveType(Type type, Encode encoder, Decode decoder)
 {
     return(new AmqpPrimitiveType(type, encoder, decoder));
 }
Ejemplo n.º 33
0
        /// <summary>
        /// Loads an image from webp into a byte array in RGBA format.
        /// </summary>
        /// <returns>The RGBA from web p.</returns>
        /// <param name="lData">L data.</param>
        /// <param name="lWidth">L width.</param>
        /// <param name="lHeight">L height.</param>
        /// <param name="lMipmaps">If set to <c>true</c> l mipmaps.</param>
        /// <param name="lError">L error.</param>
        /// <param name="scalingFunction">Scaling function.</param>
        public static unsafe byte[] LoadRGBAFromWebP(byte[] lData, ref int lWidth, ref int lHeight, bool lMipmaps, out Error lError, ScalingFunction scalingFunction = null)
        {
            lError = 0;
            byte[] lRawData = null;
            int    lLength  = lData.Length;

            fixed(byte *lDataPtr = lData)
            {
                // If we've been supplied a function to alter the width and height, use that now.
                scalingFunction?.Invoke(ref lWidth, ref lHeight);

                // If mipmaps are requested we need to create 1/3 more memory for the mipmaps to be generated in.
                int numBytesRequired = lWidth * lHeight * 4;

                if (lMipmaps)
                {
                    numBytesRequired = Mathf.CeilToInt((numBytesRequired * 4.0f) / 3.0f);
                }

                lRawData = new byte[numBytesRequired];
                fixed(byte *lRawDataPtr = lRawData)
                {
                    int lStride = 4 * lWidth;

                    // As we have to reverse the y order of the data, we pass through a negative stride and
                    // pass through a pointer to the last line of the data.
                    byte *lTmpDataPtr = lRawDataPtr + (lHeight - 1) * lStride;

                    WebPDecoderConfig config = new WebPDecoderConfig();

                    if (Decode.WebPInitDecoderConfig(ref config) == 0)
                    {
                        throw new Exception("WebPInitDecoderConfig failed. Wrong version?");
                    }

                    // Set up decode options
                    config.options.use_threads = 1;
                    if (scalingFunction != null)
                    {
                        config.options.use_scaling = 1;
                    }
                    config.options.scaled_width  = lWidth;
                    config.options.scaled_height = lHeight;

                    // read the .webp input file information
                    VP8StatusCode result = Decode.WebPGetFeatures((IntPtr)lDataPtr, (UIntPtr)lLength, ref config.input);

                    if (result != VP8StatusCode.VP8_STATUS_OK)
                    {
                        throw new Exception(string.Format("Failed WebPGetFeatures with error {0}.", result.ToString()));
                    }

                    // specify the output format
                    config.output.colorspace         = WEBP_CSP_MODE.MODE_RGBA;
                    config.output.u.RGBA.rgba        = (IntPtr)lTmpDataPtr;
                    config.output.u.RGBA.stride      = -lStride;
                    config.output.u.RGBA.size        = (UIntPtr)(lHeight * lStride);
                    config.output.height             = lHeight;
                    config.output.width              = lWidth;
                    config.output.is_external_memory = 1;

                    // Decode
                    result = Decode.WebPDecode((IntPtr)lDataPtr, (UIntPtr)lLength, ref config);
                    if (result != VP8StatusCode.VP8_STATUS_OK)
                    {
                        throw new Exception(string.Format("Failed WebPDecode with error {0}.", result.ToString()));
                    }
                }

                lError = Error.Success;
            }

            return(lRawData);
        }
Ejemplo n.º 34
0
        private void TestActivityFitFile(string filename, int expectedTotalMessages, int expectedTotalDefinitions)
        {
            // Read the answer CSV file
            var file = FitParserHelpers.ReadFitCsvFile(TESTDATA_PATH + filename + ".csv");

            // Decode a Fit file
            var fileStream = System.IO.File.OpenRead(TESTDATA_PATH + filename + ".fit");

            Assert.IsNotNull(fileStream);

            var decode = new Decode();

            Assert.IsNotNull(decode);

            var mesgBroadcaster = new MesgBroadcaster();

            Assert.IsNotNull(mesgBroadcaster);

            Assert.IsTrue(decode.IsFIT(fileStream));

            // Note that it is possible to have something that fails an integrity check, but we can still attempt to parse it
            Assert.IsTrue(decode.CheckIntegrity(fileStream));

            // Connect the Broadcaster to our event (message) source (in this case the Decoder)
            decode.MesgEvent           += mesgBroadcaster.OnMesg;
            decode.MesgDefinitionEvent += mesgBroadcaster.OnMesgDefinition;

            int totalMessages = 0, totalDefinitions = 0;
            int currentRecord = 0;

            mesgBroadcaster.MesgEvent += (sender, args) =>
            {
                foreach (var field in args.mesg.fields)
                {
                    string fieldName             = FitParserHelpers.ConvertPascalCaseToRubyCase(field.Name);
                    var    record                = file.Records[currentRecord];
                    string fieldValue            = ConvertField(field.GetValue()).ToString();
                    var    csvField              = record.GetField(fieldName);
                    string diagnosticFieldString = FormatFieldString(currentRecord, record, args.mesg.fields);
                    Assert.IsNotNull(csvField, diagnosticFieldString);
                    Assert.AreEqual(csvField.Value.ToString(), fieldValue, diagnosticFieldString);
                }
                totalMessages++;
                currentRecord++;
            };

            mesgBroadcaster.MesgDefinitionEvent += (sender, args) =>
            {
                foreach (var field in args.mesgDef.GetFields())
                {
                    var record = file.Records[currentRecord];
                }
                totalDefinitions++;
                currentRecord++;
            };

            Assert.IsTrue(decode.Read(fileStream));
            Assert.AreEqual(expectedTotalMessages, totalMessages);
            Assert.AreEqual(expectedTotalDefinitions, totalDefinitions);

            fileStream.Close();
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Update an existing consignor based on consignor ID
        /// </summary>
        /// <param name="c"></param>
        /// <returns>Success or Failure</returns>
        public virtual bool Consignor_Update(Consignor c)
        {
            bool returnValue = false;
            var d = new Decode();
            SqlConnection cn = new SqlConnection(d.ConnectionString);
            SqlCommand cmd = new SqlCommand("DTUSER.Consignor_Update");
            cmd.CommandType = CommandType.StoredProcedure;

            try
            {
                cn.Open();
                cmd.Connection = cn;
                cmd.Parameters.Add("@pConsignorID", SqlDbType.Int).Value = c.ConsignorID;
                cmd.Parameters.Add("@pLastName", SqlDbType.NVarChar).Value = c.LastName;
                cmd.Parameters.Add("@pFirstName", SqlDbType.NVarChar).Value = c.FirstName;
                cmd.Parameters.Add("@pAddress1Street", SqlDbType.NVarChar).Value = c.Address1Street;
                cmd.Parameters.Add("@pAddress1City", SqlDbType.NVarChar).Value = c.Address1City;
                cmd.Parameters.Add("@pAddress1State", SqlDbType.NVarChar).Value = c.Address1State;
                cmd.Parameters.Add("@pAddress1Zip", SqlDbType.NVarChar).Value = c.Address1Zip;
                cmd.Parameters.Add("@pHomePhone", SqlDbType.NVarChar).Value = c.HomePhone;
                cmd.Parameters.Add("@pWorkPhone", SqlDbType.NVarChar).Value = c.WorkPhone;
                cmd.Parameters.Add("@pCellPhone", SqlDbType.NVarChar).Value = c.CellPhone;
                cmd.Parameters.Add("@pEmailAddress", SqlDbType.NVarChar).Value = c.EmailAddress;
                cmd.Parameters.Add("@pComments", SqlDbType.NVarChar).Value = c.Comments;
                cmd.Parameters.Add("@pDonate", SqlDbType.Bit).Value = c.Donate;
                cmd.ExecuteNonQuery();
                returnValue = true;
            }
            catch (SqlException sx)
            {
                Console.WriteLine(sx);
                returnValue = false;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                returnValue = false;
            }
            finally
            {
                if (cn.State != ConnectionState.Closed)
                {
                    cn.Close();
                }
            }
            return returnValue;
        }
Ejemplo n.º 36
0
        public static void Main(string[] args)
        {
            DicConsole.WriteLineEvent      += System.Console.WriteLine;
            DicConsole.WriteEvent          += System.Console.Write;
            DicConsole.ErrorWriteLineEvent += System.Console.Error.WriteLine;

            Settings.Settings.LoadSettings();
            Statistics.LoadStats();
            if (Settings.Settings.Current.Stats != null && Settings.Settings.Current.Stats.ShareStats)
            {
                Statistics.SubmitStats();
            }

            Parser.Default.ParseArguments(args, typeof(AnalyzeOptions), typeof(BenchmarkOptions),
                                          typeof(ChecksumOptions), typeof(CompareOptions), typeof(ConfigureOptions),
                                          typeof(ConvertImageOptions), typeof(CreateSidecarOptions),
                                          typeof(DecodeOptions), typeof(DeviceInfoOptions), typeof(DeviceReportOptions),
                                          typeof(DumpMediaOptions), typeof(EntropyOptions), typeof(ExtractFilesOptions),
                                          typeof(FormatsOptions), typeof(ImageInfoOptions), typeof(ListDevicesOptions),
                                          typeof(ListEncodingsOptions), typeof(ListOptionsOptions), typeof(LsOptions),
                                          typeof(MediaInfoOptions), typeof(MediaScanOptions), typeof(PrintHexOptions),
                                          typeof(StatsOptions), typeof(VerifyOptions))
            .WithParsed <AnalyzeOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                Analyze.DoAnalyze(opts);
            }).WithParsed <CompareOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                Compare.DoCompare(opts);
            }).WithParsed <ChecksumOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                Checksum.DoChecksum(opts);
            }).WithParsed <EntropyOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                Entropy.DoEntropy(opts);
            }).WithParsed <VerifyOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                Verify.DoVerify(opts);
            }).WithParsed <PrintHexOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                Commands.PrintHex.DoPrintHex(opts);
            }).WithParsed <DecodeOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                Decode.DoDecode(opts);
            }).WithParsed <DeviceInfoOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                DeviceInfo.DoDeviceInfo(opts);
            }).WithParsed <MediaInfoOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                MediaInfo.DoMediaInfo(opts);
            }).WithParsed <MediaScanOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                MediaScan.DoMediaScan(opts);
            }).WithParsed <FormatsOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                Formats.ListFormats(opts);
            }).WithParsed <BenchmarkOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                Benchmark.DoBenchmark(opts);
            }).WithParsed <CreateSidecarOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                CreateSidecar.DoSidecar(opts);
            }).WithParsed <DumpMediaOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                DumpMedia.DoDumpMedia(opts);
            }).WithParsed <DeviceReportOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                DeviceReport.DoDeviceReport(opts);
            }).WithParsed <LsOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                Ls.DoLs(opts);
            }).WithParsed <ExtractFilesOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                ExtractFiles.DoExtractFiles(opts);
            }).WithParsed <ListDevicesOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                ListDevices.DoListDevices(opts);
            }).WithParsed <ListEncodingsOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                ListEncodings.DoList();
            }).WithParsed <ListOptionsOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                ListOptions.DoList();
            }).WithParsed <ConvertImageOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                ConvertImage.DoConvert(opts);
            }).WithParsed <ImageInfoOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                ImageInfo.GetImageInfo(opts);
            }).WithParsed <ConfigureOptions>(opts =>
            {
                PrintCopyright();
                Configure.DoConfigure();
            }).WithParsed <StatsOptions>(opts =>
            {
                PrintCopyright();
                Commands.Statistics.ShowStats();
            }).WithNotParsed(errs => Environment.Exit(1));

            Statistics.SaveStats();
        }
Ejemplo n.º 37
0
        /// <summary>
        /// check for valid consignor identification
        /// </summary>
        /// <param name="consignorID"></param>
        /// <returns></returns>
        public virtual bool ValidConsignor(string consignorID)
        {
            bool returnValue = false;
            var d = new Decode();
            SqlConnection cn = new SqlConnection(d.ConnectionString);
            SqlCommand cmd = new SqlCommand("DTUSER.ConsignorTest");
            cmd.CommandType = CommandType.StoredProcedure;
            SqlParameter returnParam = new SqlParameter("@Return_Value", DbType.Int32);
            returnParam.Direction = ParameterDirection.ReturnValue;
            cmd.Parameters.Add(returnParam);

            try
            {
                cn.Open();
                cmd.Connection = cn;
                cmd.Parameters.Add("@pConsignorID", SqlDbType.Int).Value = int.Parse(consignorID);
                cmd.ExecuteNonQuery();

                int iReturn = Int32.Parse(cmd.Parameters["@Return_Value"].Value.ToString());
                if (iReturn != 0)
                {
                    returnValue = true;
                }
            }
            catch (SqlException sx)
            {
                Console.WriteLine(sx);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                if (cn.State != ConnectionState.Closed)
                {
                    cn.Close();
                }
            }
            return returnValue;
        }
Ejemplo n.º 38
0
 private void ReadCallback(IAsyncResult ar)
 {
     string content = string.Empty;
     StringBuilder rb = new StringBuilder();
     PanelLibrary state = (PanelLibrary)ar.AsyncState;
     if (state.WorkSocket != null && state.WorkSocket.Connected)
     {
         try
         {
             Socket handler = state.WorkSocket;
             int bytesRead = handler.EndReceive(ar);
             if (bytesRead > 0)
             {
                 List<byte> raw = new List<byte>();
                 for (int loop = 0; loop < bytesRead; loop++)
                 {
                     raw.Add(state.Buffer[loop]);
                 }
                 Decode translate = new Decode();
                 translate.ToReadable(state.Buffer, 0, bytesRead);
                 rb.Length = 0;
                 rb.AppendFormat("[recv: {0,4} bytes on {1:H:mm:ss.fff} port: {2,5}]\t{3}", bytesRead, DateTime.Now, state.WorkSocket.Handle, translate.Decoded);
                 ReceivedEventArgs de = new ReceivedEventArgs();
                 de.Message = rb.ToString();
                 de.ClientSocket = state.WorkSocket;
                 de.Raw = raw;
                 Events.DoReceived(this, de);
                 Array.Clear(state.Buffer, 0, bytesRead);
                 handler.BeginReceive(state.Buffer, 0, state.BufferSize, 0, new AsyncCallback(ReadCallback), state);
             }
         }
         catch (ObjectDisposedException)
         {
             ClientDisconnected(state);
             _clientSockets.Remove(state.WorkSocket);
         }
         catch (SocketException se)
         {
             if (se.SocketErrorCode == SocketError.WouldBlock ||
                       se.SocketErrorCode == SocketError.IOPending ||
                       se.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
             {
                 return;
             }
             else
             {
                 StringBuilder sb = new StringBuilder();
                 sb.AppendFormat("ReadCallback({0}) Socket Exception - {1}", se.SocketErrorCode, se.Message);
                 Events.DoLog(this, sb.ToString());
                 ClientDisconnected(state);
                 _clientSockets.Remove(state.WorkSocket);
             }
         }
     }
 }
Ejemplo n.º 39
0
        public static void OpCode(Decode state, Client ed)
        {
            try
            {
                LogConsole.Show(LogType.DEBUG, "OpCode()");
                Systems sys = (Systems)state.Packet;
                sys.PacketInformation = state;

                ByteQueue queue = ed.queue;

                int length = queue.Length;
                LogConsole.Show(LogType.DEBUG, "OpCode() {0}", length);
                while ((length > 0))
                {
                    byte[] buffer;
                    int packetID = queue.GetPacketID();
                    int packetLength = queue.GetPacketLength();
                    int packetControlCode = queue.GetPacketControlCode();

                    LogConsole.Show(LogType.DEBUG, "PacketControl: {0} PacketID: 0x{1:X2} Length: {2}", packetControlCode, packetID, packetLength );
                    LogConsole.HexDump(state.buffer, "", 16);

                    PacketHandler handler = PacketHandlers.GetHandler(packetID);
                    if (handler == null)
                    {
                        byte[] buffer2 = new byte[length];
                        length = queue.Dequeue(buffer2, 0, length);
                        LogConsole.Show(LogType.DEBUG, "Client: {0}: Unhandled packet 0x{1:X2}", new object[] { state, packetID });
                        break;
                    }

                    int size = handler.Length;
                    if (length >= 4)
                    {
                        size = packetLength;
                        if (packetLength >= 4)
                        {
                            if (length < size)
                            {
                                break;
                            }

                            if (0x400 >= size)
                            {
                                buffer = m_Buffers.AquireBuffer();
                            }
                            else
                            {
                                buffer = new byte[size];
                            }

                            size = queue.Dequeue(buffer, 0, size);

                            ushort packetid = ByteQueue.GetPacketID(buffer);

                            bool flag = IsCrypted(packetid);
                            if (flag)
                            {
                                LogConsole.Show(LogType.DEBUG, "Crypted Packet 0x{0:X4}", new object[] { packetid });
                            }

                            try
                            {
                                PacketReader2 pr = new PacketReader2(buffer, size);
                                handler.OnReceive(ed, pr);
                            }
                            catch { break; }

                            length = queue.Length;
                            if ((0x400 >= size) && !flag)
                            {
                                m_Buffers.ReleaseBuffer(buffer);
                                break;
                            }
                        }
                    }

                    length = 0;
                }
            }
            catch (Exception)
            {
            }
        }
Ejemplo n.º 40
0
        static void RunOptionsAndReturnExitCode(Options opts)
        {
            options = opts;

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            Console.WriteLine("FIT Decode Example Application");

            try
            {
                fitDest = new FileStream(options.OutFile, FileMode.Create, FileAccess.ReadWrite, FileShare.Read);
                Console.WriteLine("Opening Destintion {0}", options.OutFile);
                // Write our header
                encodeDemo.Open(fitDest);

                // Attempt to open .FIT file
                fitSource = new FileStream(options.InFile, FileMode.Open);
                Console.WriteLine("Opening Source {0}", options.InFile);

                Decode          decodeDemo      = new Decode();
                MesgBroadcaster mesgBroadcaster = new MesgBroadcaster();

                // Connect the Broadcaster to our event (message) source (in this case the Decoder)
                decodeDemo.MesgEvent           += mesgBroadcaster.OnMesg;
                decodeDemo.MesgDefinitionEvent += mesgBroadcaster.OnMesgDefinition;
                //decodeDemo.DeveloperFieldDescriptionEvent += OnDeveloperFieldDescriptionEvent;

                // Subscribe to message events of interest by connecting to the Broadcaster
                mesgBroadcaster.MesgEvent           += OnMesg;
                mesgBroadcaster.MesgDefinitionEvent += OnMesgDefn;

                mesgBroadcaster.FileIdMesgEvent      += OnFileIDMesg;
                mesgBroadcaster.UserProfileMesgEvent += OnUserProfileMesg;
                mesgBroadcaster.MonitoringMesgEvent  += OnMonitoringMessage;
                mesgBroadcaster.DeviceInfoMesgEvent  += OnDeviceInfoMessage;
                mesgBroadcaster.RecordMesgEvent      += OnRecordMessage;

                bool status = decodeDemo.IsFIT(fitSource);
                status &= decodeDemo.CheckIntegrity(fitSource);

                // Process the file
                if (status)
                {
                    Console.WriteLine("Translating...");
                    decodeDemo.Read(fitSource);
                    Console.WriteLine("Translated FIT file {0}", options.InFile);
                }
                else
                {
                    try
                    {
                        Console.WriteLine("Integrity Check Failed {0}", options.InFile);
                        if (decodeDemo.InvalidDataSize)
                        {
                            Console.WriteLine("Invalid Size Detected, Attempting to decode...");
                            decodeDemo.Read(fitSource);
                        }
                        else
                        {
                            Console.WriteLine("Attempting to decode by skipping the header...");
                            decodeDemo.Read(fitSource, DecodeMode.InvalidHeader);
                        }
                    }
                    catch (FitException ex)
                    {
                        Console.WriteLine("Translate caught FitException: " + ex.Message);
                    }
                }
                fitSource.Close();

                // Update header datasize and file CRC
                encodeDemo.Close();
                fitDest.Close();

                Console.WriteLine("");
                Console.WriteLine("Summary:");
                int totalMesgs = 0;
                foreach (KeyValuePair <ushort, int> pair in mesgCounts)
                {
                    Console.WriteLine("MesgID {0,3} Count {1}", pair.Key, pair.Value);
                    totalMesgs += pair.Value;
                }

                Console.WriteLine("{0} Message Types {1} Total Messages", mesgCounts.Count, totalMesgs);

                stopwatch.Stop();
                Console.WriteLine("");
                Console.WriteLine("Time elapsed: {0:0.#}s", stopwatch.Elapsed.TotalSeconds);
                Console.ReadKey();
            }
            catch (FitException ex)
            {
                Console.WriteLine("A FitException occurred when trying to decode the FIT file. Message: " + ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception occurred when trying to decode the FIT file. Message: " + ex.Message);
            }
        }
        public static void ReadCallback(IAsyncResult ar)
        {
            string content = string.Empty;

            // Retrieve the state object and the handler socket
            // from the asynchronous state object.
            StateObject state   = (StateObject)ar.AsyncState;
            Socket      handler = state.workSocket;

            int bytesRead;
            // Read data from the client socket.

            int    i  = 0;
            string ip = ((IPEndPoint)handler.RemoteEndPoint).Address.ToString();

            if (handler.Connected)
            {
                //Console.WriteLine("ip   " + ip);
                try
                {
                    bytesRead = handler.EndReceive(ar);
                    byte[] bytes = new byte[bytesRead];
                    if (bytesRead > 0)
                    {
                        for (i = 0; i < bytesRead; i++)
                        {
                            bytes[i] = state.buffer[i];
                        }


                        DecodeData(handler, bytes, bytesRead);
                        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                                             new AsyncCallback(ReadCallback), state);
                    }
                }
                catch (SocketException se)
                {
                    if (se.ErrorCode == 10054 || ((se.ErrorCode != 10004) && (se.ErrorCode != 10053)))
                    {
                        handler.Close();
                        lock (Clients)
                        {
                            if (Clients.Count > 0)
                            {
                                foreach (KeyValuePair <string, StateObject> c in Clients)
                                {
                                    if (c.Value.workSocket == handler)
                                    {
                                        Clients.Remove(c.Key);
                                        Console.WriteLine("Client automatically disconnected");
                                        Decode dr = new Decode();
                                        string m  = dr.offlineMessage();
                                        //SendMessage(ip, m);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
Ejemplo n.º 42
0
 public Consignor GetExistingConsignor(int ConsignorID)
 {
     var returnConsignor = new Consignor();
     var d = new Decode();
     SqlConnection cn = new SqlConnection(d.ConnectionString);
     SqlCommand cmd = new SqlCommand("DTUSER.GetConsignor_Select");
     SqlDataReader dr;
     cmd.CommandType = CommandType.StoredProcedure;
     try
     {
         cn.Open();
         cmd.Connection = cn;
         cmd.Parameters.Add("@pConsignorID", SqlDbType.VarChar).Value = ConsignorID;
         dr = cmd.ExecuteReader();
         while (dr.Read())
         {
             returnConsignor.ConsignorID = ConsignorID;
             returnConsignor.LastName = dr.GetValue(0).ToString();
             returnConsignor.FirstName = dr.GetValue(1).ToString();
             returnConsignor.Address1Street = dr.GetValue(2).ToString();
             returnConsignor.Address1City = dr.GetValue(3).ToString();
             returnConsignor.Address1State = dr.GetValue(4).ToString();
             returnConsignor.Address1Zip = dr.GetValue(5).ToString();
             returnConsignor.HomePhone = dr.GetValue(6).ToString();
             returnConsignor.WorkPhone = dr.GetValue(7).ToString();
             returnConsignor.CellPhone = dr.GetValue(8).ToString();
             returnConsignor.EmailAddress = dr.GetValue(9).ToString();
             returnConsignor.Comments = dr.GetValue(10).ToString();
             returnConsignor.Donate = dr.GetBoolean(11);
         }
     }
     catch (SqlException sx)
     {
         // return an empty consingor
         var falseConsignor = new Consignor();
         returnConsignor.LastName = "SQL Exception";
         returnConsignor.Comments = sx.Message;
     }
     catch (Exception ex)
     {
         // return an empty consingor
         var falseConsignor = new Consignor();
         returnConsignor.LastName = "C# Exception";
         returnConsignor.Comments = ex.Message;
     }
     finally
     {
         if (cn.State != ConnectionState.Closed)
         {
             cn.Close();
         }
     }
     return returnConsignor;
 }
Ejemplo n.º 43
0
    public override void DoCommand()
    {
        int command = BitConverter.ToInt32(bytes, 8);

        switch (command)
        {
        case 1:                                                                                                //处理将闲置房间列发反馈给客户端
            rooms = DataDo.Json2Object <Dictionary <string, RoomInfo> >(Decode.DecodSecondContendBtye(bytes)); //查找数据报错,解析成对象时
            if (RoomsHallPanel.Get())
            {
                RoomsHallPanel.Get().OperateRoom();
            }
            Debug.Log("查找成功, 房间数:" + rooms.Count);
            break;

        case 2:
            Debug.Log("开房成功");

            break;

        case 3:
            //返回房间界面
            RoomInfo room = DataDo.Json2Object <RoomInfo>(Decode.DecodSecondContendBtye(bytes));
            RoomPanel.room = room;
            SceneManager.LoadScene("Scenes/MainScence");
            UnityAction <Scene, LoadSceneMode> onLoaded = null;
            onLoaded = (Scene scene, LoadSceneMode mode) =>
            {
                RoomPanel.Open().ForeachPlayerList(room);
                RoomPanel.Get().inPutField.text = room.roomName;
                SceneManager.sceneLoaded -= onLoaded;
            };
            SceneManager.sceneLoaded += onLoaded;


            break;

        case 4:
            Debug.Log("加入房间:");
            RoomsHallPanel.Close();
            RoomInfo roomInfos = DataDo.Json2Object <RoomInfo>(Decode.DecodSecondContendBtye(bytes));
            RoomPanel.room = roomInfos;

            //判断是否是在房间界面
            if (SceneManager.GetActiveScene().name == "MainScence")
            {
                RoomPanel.Open().ForeachPlayerList(roomInfos);
                RoomPanel.Get().inPutField.text = roomInfos.roomName;
                NetStart.myInfo.roomNum = roomInfos.roomID;
            }
            break;

        case 5:
            RoomInfo roomInfo5 = DataDo.Json2Object <RoomInfo>(Decode.DecodSecondContendBtye(bytes));
            RoomPanel.room = roomInfo5;
            RoomPanel roomPanel = RoomPanel.Get();
            if (roomPanel)
            {
                roomPanel.inPutField.text = roomInfo5.roomName;
                roomPanel.ForeachPlayerList(roomInfo5);
            }
            Debug.Log("已退出房间" + roomInfo5.member.Count);
            break;

        case 6:
            Debug.Log("房主转让");
            //被动接受
            break;

        case 8:
            Debug.Log("邀请加入");

            break;

        case 9:
            Debug.Log("踢出房间");

            break;

        case 10:
            Debug.Log("添加好友");

            break;

        case 11:
            Debug.Log("获取可以邀请好友列表");

            break;

        case 12:
            Debug.Log("修改房间名");

            break;
        }
    }
Ejemplo n.º 44
0
        /// <summary>
        /// Add a consignor to the database
        /// </summary>
        /// <param name="newconsignor"></param>
        /// <returns>New Consignor ID</returns>
        public virtual int AddNewConsignor(Consignor newconsignor)
        {
            int count;
            var d = new Decode();
            SqlConnection cn = new SqlConnection(d.ConnectionString);
            SqlCommand cmd = new SqlCommand("DTUSER.NewConsignor_Insert");
            cmd.CommandType = CommandType.StoredProcedure;
            SqlParameter returnValue = new SqlParameter("@Return_Value", DbType.Int32);
            returnValue.Direction = ParameterDirection.ReturnValue;
            cmd.Parameters.Add(returnValue);

            try
            {
                cn.Open();
                cmd.Connection = cn;
                cmd.Parameters.Add("@pLastName", SqlDbType.NVarChar).Value = newconsignor.LastName;
                cmd.Parameters.Add("@pFirstName", SqlDbType.NVarChar).Value = newconsignor.FirstName;
                cmd.Parameters.Add("@pAddress1Street", SqlDbType.NVarChar).Value = newconsignor.Address1Street;
                cmd.Parameters.Add("@pAddress1City", SqlDbType.NVarChar).Value = newconsignor.Address1City;
                cmd.Parameters.Add("@pAddress1State", SqlDbType.NVarChar).Value = newconsignor.Address1State;
                cmd.Parameters.Add("@pAddress1Zip", SqlDbType.NVarChar).Value = newconsignor.Address1Zip;
                cmd.Parameters.Add("@pHomePhone", SqlDbType.NVarChar).Value = newconsignor.HomePhone;
                cmd.Parameters.Add("@pWorkPhone", SqlDbType.NVarChar).Value = newconsignor.WorkPhone;
                cmd.Parameters.Add("@pCellPhone", SqlDbType.NVarChar).Value = newconsignor.CellPhone;
                cmd.Parameters.Add("@pEmailAddress", SqlDbType.NVarChar).Value = newconsignor.EmailAddress;
                cmd.Parameters.Add("@pComments", SqlDbType.NVarChar).Value = newconsignor.Comments;
                cmd.Parameters.Add("@pDonate", SqlDbType.Bit).Value = newconsignor.Donate;
                cmd.Parameters.Add("@pCreateBy", SqlDbType.NVarChar).Value = "NewConsignor";

                cmd.ExecuteNonQuery();
                count = Int32.Parse(cmd.Parameters["@Return_Value"].Value.ToString());
            }
            catch (SqlException sx)
            {
                Console.WriteLine(sx);
                count = -1;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                count = -2;
            }
            finally
            {
                if (cn.State != ConnectionState.Closed)
                {
                    cn.Close();
                }
            }
            return count;
        }
Ejemplo n.º 45
0
 static void Updata_Excute()
 {
     if (!Control.Show_E_bubble() && !Control.Show_E_stall())
     {
         Excute.Updata(Decode.Show_d_state(), Decode.Show_d_icode(), Decode.Show_d_ifun(), Decode.Show_d_valC(), Decode.Show_d_valA(), Decode.Show_d_valB(), Decode.Show_d_dstE(), Decode.Show_d_dstM(), Decode.Show_d_srcA(), Decode.Show_d_srcB());
     }
     if (Control.Show_E_bubble())
     {
         Excute.Updata(Control.States.SAOK, Control.Codes.INOP, 0, 0, 0, 0, Control.Registers.RNONE, Control.Registers.RNONE, Control.Registers.RNONE, Control.Registers.RNONE);
     }
 }
Ejemplo n.º 46
0
 private int GetMaxConsignorID()
 {
     int maxid = 0;
     string cmdText = "SELECT MAX(CONSIGNORID) FROM DTUSER.NEWCONSIGNOR";
     var d = new Decode();
     SqlConnection cn = new SqlConnection(d.ConnectionString);
     SqlCommand cmd = new SqlCommand(cmdText, cn);
     cn.Open();
     SqlDataReader dr = cmd.ExecuteReader();
     while (dr.Read())
     {
         maxid = dr.GetSqlInt32(0).Value;
     }
     cn.Close();
     return maxid;
 }
Ejemplo n.º 47
0
 private void button1_Click(object sender, EventArgs e)
 {
     txtDecode.Text = Decode.EncodeCode(txtOriginal.Text);
 }
Ejemplo n.º 48
0
 public AmqpPrimitiveType(Type type, Encode encoder, Decode decoder)
     : base(null, type)
 {
     this.encoder = encoder;
     this.decoder = decoder;
 }
Ejemplo n.º 49
0
 private void btnDecode_Click(object sender, EventArgs e)
 {
     textBox1.Text = Decode.DecodeCode(textBox2.Text);
 }
Ejemplo n.º 50
0
 void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
 {
     StringBuilder sb = new StringBuilder();
     if (_serialPort != null)
     {
         int numBytes = _serialPort.BytesToRead;
         List<byte> newReceived = new List<byte>();
         for (int count = 0; count < numBytes; count++)
         {
             newReceived.Add((byte)_serialPort.ReadByte());
         }
         Decode dec = new Decode();
         dec.ToReadable(newReceived.ToArray());
         sb.Length = 0;
         sb.AppendFormat("[recv: {0,4} bytes on {1:H:mm:ss.fff}]{2}", newReceived.Count, DateTime.Now, dec.Decoded);
         ReceivedEventArgs de = new ReceivedEventArgs();
         de.Message = sb.ToString();
         de.Port = _serialPort.PortName;
         de.Raw = newReceived;
         Events.DoReceived(this, de);
     }
 }
Ejemplo n.º 51
0
        public static void Decode(string filePath)
        {
            using var tracing = Tracing.Trace($"{nameof(FitConverter)}.{nameof(Decode)}")
                                .WithTag(TagKey.Format, FileFormat.Fit.ToString());

            Decode          decoder         = new Decode();
            MesgBroadcaster mesgBroadcaster = new MesgBroadcaster();

            decoder.MesgEvent                      += mesgBroadcaster.OnMesg;
            decoder.MesgDefinitionEvent            += mesgBroadcaster.OnMesgDefinition;
            decoder.DeveloperFieldDescriptionEvent += Write;

            mesgBroadcaster.AccelerometerDataMesgEvent           += Write;
            mesgBroadcaster.ActivityMesgEvent                    += Write;
            mesgBroadcaster.AntChannelIdMesgEvent                += Write;
            mesgBroadcaster.AntRxMesgEvent                       += Write;
            mesgBroadcaster.AntTxMesgEvent                       += Write;
            mesgBroadcaster.AviationAttitudeMesgEvent            += Write;
            mesgBroadcaster.BarometerDataMesgEvent               += Write;
            mesgBroadcaster.BikeProfileMesgEvent                 += Write;
            mesgBroadcaster.BloodPressureMesgEvent               += Write;
            mesgBroadcaster.CadenceZoneMesgEvent                 += Write;
            mesgBroadcaster.CameraEventMesgEvent                 += Write;
            mesgBroadcaster.CapabilitiesMesgEvent                += Write;
            mesgBroadcaster.ClimbProMesgEvent                    += Write;
            mesgBroadcaster.ConnectivityMesgEvent                += Write;
            mesgBroadcaster.CourseMesgEvent                      += Write;
            mesgBroadcaster.CoursePointMesgEvent                 += Write;
            mesgBroadcaster.DeveloperDataIdMesgEvent             += Write;
            mesgBroadcaster.DeviceInfoMesgEvent                  += Write;
            mesgBroadcaster.DeviceSettingsMesgEvent              += Write;
            mesgBroadcaster.DiveAlarmMesgEvent                   += Write;
            mesgBroadcaster.DiveGasMesgEvent                     += Write;
            mesgBroadcaster.DiveSettingsMesgEvent                += Write;
            mesgBroadcaster.DiveSummaryMesgEvent                 += Write;
            mesgBroadcaster.EventMesgEvent                       += Write;
            mesgBroadcaster.ExdDataConceptConfigurationMesgEvent += Write;
            mesgBroadcaster.ExdDataFieldConfigurationMesgEvent   += Write;
            mesgBroadcaster.ExdScreenConfigurationMesgEvent      += Write;
            mesgBroadcaster.ExerciseTitleMesgEvent               += Write;
            mesgBroadcaster.FieldCapabilitiesMesgEvent           += Write;
            mesgBroadcaster.FieldDescriptionMesgEvent            += Write;
            mesgBroadcaster.FileCapabilitiesMesgEvent            += Write;
            mesgBroadcaster.FileCreatorMesgEvent                 += Write;
            mesgBroadcaster.FileIdMesgEvent                      += Write;
            mesgBroadcaster.GoalMesgEvent             += Write;
            mesgBroadcaster.GpsMetadataMesgEvent      += Write;
            mesgBroadcaster.GyroscopeDataMesgEvent    += Write;
            mesgBroadcaster.HrMesgEvent               += Write;
            mesgBroadcaster.HrmProfileMesgEvent       += Write;
            mesgBroadcaster.HrvMesgEvent              += Write;
            mesgBroadcaster.HrZoneMesgEvent           += Write;
            mesgBroadcaster.JumpMesgEvent             += Write;
            mesgBroadcaster.LapMesgEvent              += Write;
            mesgBroadcaster.LengthMesgEvent           += Write;
            mesgBroadcaster.MagnetometerDataMesgEvent += Write;
            mesgBroadcaster.MemoGlobMesgEvent         += Write;
            mesgBroadcaster.MesgCapabilitiesMesgEvent += Write;
            mesgBroadcaster.MesgEvent                        += Write;
            mesgBroadcaster.MetZoneMesgEvent                 += Write;
            mesgBroadcaster.MonitoringInfoMesgEvent          += Write;
            mesgBroadcaster.MonitoringMesgEvent              += Write;
            mesgBroadcaster.NmeaSentenceMesgEvent            += Write;
            mesgBroadcaster.ObdiiDataMesgEvent               += Write;
            mesgBroadcaster.OhrSettingsMesgEvent             += Write;
            mesgBroadcaster.OneDSensorCalibrationMesgEvent   += Write;
            mesgBroadcaster.PadMesgEvent                     += Write;
            mesgBroadcaster.PowerZoneMesgEvent               += Write;
            mesgBroadcaster.RecordMesgEvent                  += Write;
            mesgBroadcaster.ScheduleMesgEvent                += Write;
            mesgBroadcaster.SdmProfileMesgEvent              += Write;
            mesgBroadcaster.SegmentFileMesgEvent             += Write;
            mesgBroadcaster.SegmentIdMesgEvent               += Write;
            mesgBroadcaster.SegmentLapMesgEvent              += Write;
            mesgBroadcaster.SegmentLeaderboardEntryMesgEvent += Write;
            mesgBroadcaster.SegmentPointMesgEvent            += Write;
            mesgBroadcaster.SessionMesgEvent                 += Write;
            mesgBroadcaster.SlaveDeviceMesgEvent             += Write;
            mesgBroadcaster.SoftwareMesgEvent                += Write;
            mesgBroadcaster.SpeedZoneMesgEvent               += Write;
            mesgBroadcaster.SportMesgEvent                   += Write;
            mesgBroadcaster.StressLevelMesgEvent             += Write;
            mesgBroadcaster.ThreeDSensorCalibrationMesgEvent += Write;
            mesgBroadcaster.TimestampCorrelationMesgEvent    += Write;
            mesgBroadcaster.TotalsMesgEvent                  += Write;
            mesgBroadcaster.TrainingFileMesgEvent            += Write;
            mesgBroadcaster.UserProfileMesgEvent             += Write;
            mesgBroadcaster.VideoClipMesgEvent               += Write;
            mesgBroadcaster.VideoDescriptionMesgEvent        += Write;
            mesgBroadcaster.VideoFrameMesgEvent              += Write;
            mesgBroadcaster.VideoMesgEvent                   += Write;
            mesgBroadcaster.VideoTitleMesgEvent              += Write;
            mesgBroadcaster.WatchfaceSettingsMesgEvent       += Write;
            mesgBroadcaster.WeatherAlertMesgEvent            += Write;
            mesgBroadcaster.WeatherConditionsMesgEvent       += Write;
            mesgBroadcaster.WeightScaleMesgEvent             += Write;
            mesgBroadcaster.WorkoutMesgEvent                 += Write;
            mesgBroadcaster.WorkoutSessionMesgEvent          += Write;
            mesgBroadcaster.WorkoutStepMesgEvent             += Write;
            mesgBroadcaster.ZonesTargetMesgEvent             += Write;

            FileStream fitDest = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read);

            decoder.Read(fitDest);
        }
Ejemplo n.º 52
0
            public void ReceiveData(IAsyncResult ar)
            {
                Socket wSocket = (Socket)ar.AsyncState;
                try
                {
                    if (wSocket.Connected)
                    {
                        int recvSize = wSocket.EndReceive(ar);  // get the count of received bytes
                        bool checkData = true;
                        if (recvSize > 0)
                        {
                            if ((recvSize + bufCount) > MAX_BUFFER)  // that may be a try to force buffer overflow, we don't allow that ;)
                            {
                                checkData = false;
                                LocalDisconnect(wSocket);
                            }
                            else
                            {  // we have something in input buffer and it is not beyond our limits
                                Buffer.BlockCopy(tmpbuf, 0, buffer, bufCount, recvSize); // copy the new data to our buffer
                                bufCount += recvSize; // increase our buffer-counter
                            }
                        }
                        else
                        {   // 0 bytes received, this should be a disconnect
                            checkData = false;
                            LocalDisconnect(wSocket);
                        }

                        while (checkData) // repeat while we have
                        {
                            checkData = false;
                            if (bufCount >= 4) // a minimum of 4 byte is required for us
                            {
                                Decode de = new Decode(buffer); // only get get the size first
                                LogConsole.Show(LogType.DEBUG, "Decode()");
                                if (bufCount >= (de.dataSize-2))  // that's a complete packet, lets call the handler
                                {
                                    de = new Decode(wSocket, buffer, this, Packets);  // build up the Decode structure for next step
                                    LogConsole.Show(LogType.DEBUG, "Decode()->dataSize");
                                    queue.Enqueue(buffer, 0, bufCount);
                                    OnReceiveData(de, this); // call the handling routine
                                    bufCount -= (de.dataSize); // decrease buffer-counter
                                    if (bufCount > 0) // was the buffer greater than the packet needs ? then it may be the next packet
                                    {
                                        Buffer.BlockCopy(buffer, 2 + de.dataSize, buffer, 0, bufCount); // move the rest to buffer start
                                        checkData = true; // loop for next packet
                                    }
                                }
                                de = null;
                            }
                        }
                        // start the next async read
                        if (wSocket != null && wSocket.Connected)
                        {
                            wSocket.BeginReceive(tmpbuf, 0, tmpbuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), wSocket);
                        }
                    }
                    else
                    {
                        LocalDisconnect(wSocket);
                    }
                }
                catch (SocketException)  // explicit handling of SocketException
                {
                    LocalDisconnect(wSocket);
                }
                catch (Exception) // other exceptions
                {
                    LocalDisconnect(wSocket);
                }
            }
Ejemplo n.º 53
0
 public static void oPCode(Decode de)
 {
     try
     {
         Systems sys = (Systems)de.Packet;
         sys.PacketInformation = de;
         //Console.WriteLine("Recv: (0x{0})", de.opcode.ToString("X4"));
         switch (de.opcode)
         {
             case 0x7481:
                 break;
             case CLIENT_PING:
             case CLIENT_PING2:
                 break;
             case CLIENT_PATCH:
                 sys.Patch();
                 break;
             case CLIENT_CONNECTION:
                 sys.Connect();
                 break;
             case CLIENT_CHARACTERSCREEN:
                 sys.CharacterScreen();
                 sys.Ping();
                 break;
             case CLIENT_INGAME_REQUEST:
                 sys.IngameLogin();
                 break;
             case CLIENT_INGAME_SUCCESS:
                 sys.InGameSuccess();
                 break;
             case CLIENT_REQUEST_WEATHER:
                 sys.LoadWeather();
                 break;
             case CLIENT_SIT:
                 sys.Doaction();
                 break;
             case CLIENT_QUESTMARK:
                 sys.QuestionMark();
                 break;
             case CLIENT_MOVEMENT:
                 sys.Movement();
                 break;
             case CLIENT_ANGLE_MOVE:
                 sys.Angle();
                 break;
             case CLIENT_SAVE_BAR:
                 sys.Save();
                 break;
             case CLIENT_LEAVE_REQUEST:
                 sys.LeaveGame();
                 break;
             case CLIENT_LEAVE_CANCEL:
                 sys.CancelLeaveGame();
                 break;
             case CLIENT_ITEM_MOVE:
                 sys.ItemMain();
                 break;
             case CLIENT_SELECT_OBJECT:
                 sys.SelectObject();
                 break;
             case CLIENT_GM:
                 sys.GM();
                 break;
             case CLIENT_EMOTE:
                 sys.Emote();
                 break;
             case CLIENT_TELEPORTSTART:
                 sys.Teleport_Start();
                 break;
             case CLIENT_TELEPORTDATA:
                 sys.Teleport_Data();
                 break;
             case CLIENT_CHAT:
                 sys.Chat();
                 break;
             case CLIENT_MAINACTION:
                 sys.ActionMain();
                 break;
             case CLIENT_MASTERY_UP:
                 sys.Mastery_Up();
                 break;
             case CLIENT_SKILL_UP:
                 sys.Mastery_Skill_Up();
                 break;
             case CLIENT_GETUP:
                 sys.Player_Up();
                 break;
             case CLIENT_REQUEST_PARTY:
                 sys.NormalRequest();
                 break;
             case CLIENT_PARTY_REQUEST:
                 sys.CharacterRequest();
                 break;
             case CLIENT_EXCHANGE_REQUEST:
                 sys.Exchange_Request();
                 break;
             case CLIENT_EXCHANGE_WINDOWS_CLOSE:
                 sys.Exchange_Close();
                 break;
             case CLIENT_EXCHANGE_ACCEPT:
                 sys.Exchange_Accept();
                 break;
             case CLIENT_EXCHANGE_APPROVE:
                 sys.Exchange_Approve();
                 break;
             case CLIENT_PARTY_ADDMEMBERS:
                 sys.PartyAddmembers();
                 break;
             case CLIENT_PARTY_LEAVE:
                 sys.LeaveParty();
                 break;
             case CLIENT_PARTY_BANPLAYER:
                 sys.PartyBan();
                 break;
             case CLIENT_GUIDE:
                 sys.Gameguide();
                 break;
             case CLIENT_PLAYER_UPDATE_INT:
                 sys.InsertInt();
                 break;
             case CLIENT_PLAYER_UPDATE_STR:
                 sys.InsertStr();
                 break;
             case CLIENT_PLAYER_HANDLE:
                 sys.Handle();
                 break;
             case CLIENT_PLAYER_BERSERK:
                 sys.Player_Berserk_Up();
                 break;
             case CLIENT_CLOSE_NPC:
                 sys.Close_NPC();
                 break;
             case CLIENT_OPEN_NPC:
                 sys.Open_NPC();
                 break;
             case CLIENT_NPC_BUYPACK:
                 sys.Player_BuyPack();
                 break;
             case CLIENT_OPEN_WAREHOUSE:
                 sys.Open_Warehouse();
                 break;
             case CLIENT_CLOSE_SCROLL:
                 sys.StopScrollTimer();
                 break;
             case CLIENT_SAVE_PLACE:
                 sys.SavePlace();
                 break;
             case CLIENT_ALCHEMY:
                 sys.AlchemyElixirMain();
                 break;
             case CLIENT_ALCHEMY_CREATE_STONE:
                 sys.AlchemyCreateStone();
                 break;
             case CLIENT_PET_MOVEMENT:
                 sys.MovementPet();
                 break;
             case CLIENT_PET_TERMINATE:
                 sys.HandleClosePet();
                 break;
             case CLIENT_PARTYMATCHING_LIST_REQUEST:
                 sys.ListPartyMatching(Party);
                 break;
             case CLIENT_CREATE_FORMED_PARTY:
                 sys.CreateFormedParty();
                 break;
             case CLIENT_FORMED_PARTY_DELETE:
                 sys.DeleteFormedParty(0);
                 break;
             case CLIENT_JOIN_FORMED_RESPONSE:
                 sys.FormedResponse();
                 break;
             case CLIENT_CHANGE_PARTY_NAME:
                 sys.RenameParty();
                 break;
             case CLIENT_JOIN_FORMED_PARTY:
                 sys.JoinFormedParty();
                 break;
             case CLIENT_START_PK:
                 sys.PkPlayer();
                 break;
             case CLIENT_GUILD:
                 sys.GuildCreate();
                 break;
             case CLIENT_GUILD_TRANSFER:
                 sys.GuildTransferLeaderShip();
                 break;
             case CLIENT_GUILD_PERMISSIONS:
                 sys.GuildPermissions();
                 break;
             case CLIENT_GUILD_PROMOTE:
                 sys.GuildPromote();
                 break;
             case CLIENT_GUILD_DISBAND:
                 sys.GuildDisband();
                 break;
             case CLIENT_GUILD_MESSAGE:
                 sys.GuildMessage();
                 break;
             case CLIENT_OPEN_GUILD_STORAGE:
                 sys.GuildStorage();
                 break;
             case CLIENT_CLOSE_GUILD_STORAGE:
                 sys.GuildStorageClose();
                 break;
             case CLIENT_GUILD_WAR_GOLD:
                 sys.GuildWarGold();
                 break;
             case CLIENT_OPEN_GUILD_STORAGE2:
                 sys.GuildStorage2();
                 break;
             case CLIENT_GUILD_KICK:
                 sys.KickFromGuild();
                 break;
             case CLIENT_GUILD_LEAVE:
                 sys.GuildLeave();
                 break;
             case CLIENT_GUILD_TITLE_SET:
                 sys.GuildTitle();
                 break;
             case CLIENT_GUILD_INVITE:
                 sys.GuildInvite();
                 break;
             case CLIENT_GUILD_DONATE_GP:
                 sys.DonateGP();
                 break;
             case CLIENT_GACHA_PLAY:
                 //Add function
                 break;
             case CLIENT_JOIN_MERC:
                 sys.JoinMerc();
                 break;
             case CLIENT_RANKING_LISTS:
                 sys.RankList();
                 break;
             case CLIENT_PREV_JOB:
                 sys.PrevJob();
                 break;
             case CLIENT_HONOR_RANK:
                 sys.HonorRank();
                 break;
             case CLIENT_PM_MESSAGE:
                 sys.PrivateMessage();
                 break;
             case CLIENT_PM_SEND:
                 sys.PrivateMessageSend();
                 break;
             case CLIENT_PM_OPEN:
                 sys.PrivateMessageOpen();
                 break;
             case CLIENT_PM_DELETE:
                 sys.PrivateMessageDelete();
                 break;
             case CLIENT_PET_UNSUMMON:
                 sys.UnSummonPet();
                 break;
             case CLIENT_PET_RENAME:
                 sys.RenamePet();
                 break;
             case CLIENT_GPET_SETTINGS:
                 sys.GrabPetSettings();
                 break;
             case CLIENT_MAKE_ALIAS:
                 sys.MakeAlias();
                 break;
             case CLIENT_LEAVE_JOB:
                 sys.LeaveJob();
                 break;
             case CLIENT_DISSEMBLE_ITEM:
                 sys.BreakItem();
                 break;
             case CLIENT_STALL_OPEN:
                 sys.StallOpen();
                 break;
             case CLIENT_STALL_CLOSE:
                 sys.StallClose();
                 break;
             case CLIENT_STALL_BUY:
                 sys.StallBuy();
                 break;
             case CLIENT_STALL_ACTION:
                 sys.StallMain();
                 break;
             case CLIENT_STALL_OTHER_OPEN:
                 sys.EnterStall();
                 break;
             case CLIENT_STALL_OTHER_CLOSE:
                 sys.LeaveStall();
                 break;
             case CLIENT_PVP:
                 sys.StartPvpTimer(10000);
                 break;
             case CLIENT_ALCHEMY_STONE:
                 sys.AlchemyStoneMain();
                 break;
             case CLIENT_ITEM_MALL_WEB:
                 sys.ItemMallWeb();
                 break;
             case CLIENT_ITEM_STORAGE_BOX:
                 sys.ItemStorageBox();
                 break;
             case CLIENT_ITEM_BOX_LOG:
                 sys.ItemStorageBoxLog();
                 break;
             case CLIENT_FRIEND_REMOVAL:
                 sys.FriendRemoval();
                 break;
             case CLIENT_FRIEND_INVITE:
                 sys.FriendAdd();
                 break;
             case CLIENT_FRIEND_GROUP:
                 sys.FriendGroup("ADD");
                 break;
             case CLIENT_FRIEND_GROUP_REMOVE:
                 sys.FriendGroup("REMOVE");
                 break;
             case CLIENT_FRIEND_GROUP_MANAGE_FRIEND:
                 sys.FriendGroup("MOVE");
                 break;
             case CLIENT_FRIEND_INVITE_RESPONSE:
                 sys.FriendAddResponse();
                 break;
             case CLIENT_UNION_APPLY:
                 sys.unionapply();
                 break;
             case CLIENT_ICON_REQUEST:
                 sys.RequestIcons();
                 break;
             default:
                 Print.Format("(0x{0}) {1}", de.opcode.ToString("X4"), Decode.StringToPack(sys.PacketInformation.buffer));
                 break;
         }
     }
     catch (Exception ex)
     {
         Systems.Debugger.Write(ex);
     }
 }