public void send(Byte[] bytes)
 {
     lock (UdpAdapter._udpc)
     {
         Byte[] b = new Byte[bytes.Count() + 8];
         Buffer.BlockCopy(bytes, 0, b, 0, bytes.Count());
         Buffer.BlockCopy(BitConverter.GetBytes(UdpAdapter.count++), 0, b, bytes.Count(), 8);
         UdpAdapter._udpc.Send(b, b.Count(),
             new IPEndPoint(this._ipep.Address, this._ipep.Port));
     }
 }
Esempio n. 2
0
        private void ProcessMessage(Byte[] receiveBytes)
        {
            if (receiveBytes.Count() < MessageHeaderLength)
            {
                return;
            }

            long timeStamp = BitConverter.ToInt64(receiveBytes, 0);

            if (timeStamp <= lastTimeStamp)
            {
                Debug.WriteLine("UDP packet out of order");
                return;
            }

            lastTimeStamp = timeStamp;

            byte messageType = receiveBytes[8];

            switch (messageType)
            {
                // Cursor position
                case 0:

                    // Check length
                    if (receiveBytes.Count() != MessageHeaderLength + 8 * 4)
                    {
                        return;
                    }

                    int[] values = new int[8];
                    for (int i = 0; i < values.Length; i++)
                    {
                        values[i] = BitConverter.ToInt32(receiveBytes, MessageHeaderLength + i * 4);
                    }

                    InputEventArgs eventArgs = new InputEventArgs();
                    eventArgs.cursorPosition = new Point(values[0], values[1]);
                    eventArgs.caretPosition = new Rectangle(values[2], values[3], values[4], values[5]);
                    eventArgs.screenSize = new Point(values[6], values[7]);
                    if (OnInputPositionReceived != null)
                        OnInputPositionReceived(this, eventArgs);

                    break;
                default:
                    break;
            }
        }
Esempio n. 3
0
 public static List<Packet> DecodeBytes(Byte[] bytes)
 {
     List<Packet> packets = new List<Packet>();
     Byte marker;
     Int32 offset = 0;
     Single lastTime = 0;
     UInt32 contentLength = 0;
     Byte packetHeader = 0;
     UInt32 blockParam = 0;
     while (offset < bytes.Count() - 5)
     {
         marker = bytes[offset++];
         if (((marker >> 7) & 1) == 1)
             lastTime += bytes[offset++] / 1000.0f;
         else
             lastTime = BitConverter.ToSingle(new Byte[4] { bytes[offset++], bytes[offset++], bytes[offset++], bytes[offset++] }, 0);
         if (((marker >> 4) & 1) == 1)
             contentLength = bytes[offset++];
         else
             contentLength = BitConverter.ToUInt32(new Byte[4] { bytes[offset++], bytes[offset++], bytes[offset++], bytes[offset++] }, 0);
         if (((marker >> 6) & 1) == 0)
             packetHeader = bytes[offset++];
         if (((marker >> 5) & 1) == 1)
         {
             Byte b = bytes[offset++];
             if (b >> 7 == 1)
             {
                 b = (byte)(0xff - b);
                 blockParam -= b;
             }
             else
                 blockParam += b;
         }
         else
             blockParam = BitConverter.ToUInt32(new Byte[4] { bytes[offset++], bytes[offset++], bytes[offset++], bytes[offset++] }, 0);
         List<Byte> content = new List<Byte>();
         for (UInt32 j = 0; j < contentLength; j++)
         {
             content.Add(bytes[offset++]);
         }
         packets.Add(new Packet(blockParam, packetHeader, lastTime, content.ToArray()));
     }
     return packets;
 }
Esempio n. 4
0
        public Byte[] Encrypt(Byte[] data)
        {
            Byte[] ret = new Byte[1024];
            int mLoopItr = 0;
            int loop3 = 0;
            byte var_f, var_e, var_d, var_c = 0, var_b = 0;

            mLoopItr = data.Count() / 3;
            if (data.Count() % 3 != 0)
                mLoopItr++;

            for (int x = 0; x < mLoopItr; x++)
            {
                var_d = data[loop3];
                if (loop3 + 1 < data.Count())
                    try { var_c = data[loop3 + 1]; }
                    catch { var_c = 0; }
                if (loop3 + 2 < data.Count())
                    try { var_b = data[loop3 + 2]; }
                    catch { var_b = 0; }

                ret[x * 4] = Convert.ToByte(var_d >> 2);
                var_e = Convert.ToByte((var_d & 3) << 4);
                var_f = Convert.ToByte(var_c >> 4);
                ret[x * 4 + 1] = Convert.ToByte(var_e | var_f);
                var_e = Convert.ToByte((var_c & 0x0F) << 2);
                var_f = Convert.ToByte(var_b >> 6);
                ret[x * 4 + 2] = Convert.ToByte(var_e | var_f);
                ret[x * 4 + 3] = Convert.ToByte(var_b & 0x3F);

                ret[x * 4] += 0x3B;
                ret[x * 4 + 1] += 0x3B;
                ret[x * 4 + 2] += 0x3B;
                ret[x * 4 + 3] += 0x3B;
                loop3 += 3;
            }
            int size = Array.IndexOf<Byte>(ret, 0);
            ret[size] = 0x2E;
            ret[size + 1] = 0x0A;
            //    ret[size + 2] = 0x00;

            Array.Resize(ref ret, size + 2);
            return ret;
        }
 public void send(Byte[] bytes)
 {
     this._udpc.Send(bytes, bytes.Count(), ConnectionInfo.Host, ConnectionInfo.Port);
 }
Esempio n. 6
0
        public static Byte[] Decrypt(Byte[] data)
        {
            Byte[] ret = new Byte[512];
            List<Byte> temp = new List<Byte>();
            //   int TrimIndex = Array.IndexOf<Byte>(data, 0x2E);

            //     if (TrimIndex + 2 < data.Count())
            //          throw new Exception("Found 0x2E byte not at end of packet");

            //       data = data.Take(TrimIndex+1).ToArray();

            int mLoopItr = 0;
            int loop3 = 0;
            byte var_f, var_e, var_d, var_c, var_b, var_a;

            mLoopItr = (data.Count() - 1) >> 2;
            for (int x = 0; x < (data.Count() - 1); x++)
            {
                if (data[x] == 0x2E)
                    break;
                data[x] -= 0x3B;
            }

            for (int x = 0; x < mLoopItr; x++)
            {
                var_d = data[loop3];
                try { var_c = data[loop3 + 1]; }
                catch { var_c = 0; }
                try { var_b = data[loop3 + 2]; }
                catch { var_b = 0; }
                try { var_a = data[loop3 + 3]; }
                catch { var_a = 0; }

                var_e = Convert.ToByte((var_d << 2) & 0xFF);
                var_f = Convert.ToByte(var_c >> 4);
                // ret[x * 3] = Convert.ToByte(var_e | var_f);
                temp.Add(Convert.ToByte(var_e | var_f));
                var_e = Convert.ToByte((var_c << 4) & 0xFF);
                var_f = Convert.ToByte(var_b >> 2);
                //    ret[x * 3 + 1] = Convert.ToByte(var_e | var_f);
                temp.Add(Convert.ToByte(var_e | var_f));
                var_e = Convert.ToByte((var_b << 6) & 0xFF);
                var_f = var_a;
                //  ret[x * 3 + 2] = Convert.ToByte(var_e | var_f);
                temp.Add(Convert.ToByte(var_e | var_f));

                loop3 += 4;
            }
            //     int size = Array.IndexOf<Byte>(ret, 0);
            //   ret[size] = 0x00;
            //    Array.Resize(ref ret, size); //Last DWORD byte

            var i = temp.Count - 1;
            while (temp[i] == 0)
            {
                if (temp[0] == 0 && temp[1] == 0)
                {
                    i = 1; break;
                }
                i--;
            }
            temp = temp.Take(i + 2).ToList<Byte>();

            return temp.ToArray<Byte>();
        }
Esempio n. 7
0
        public void HandleIncoming(Byte[] data)
        {
            if (nsa != null)
            {
                nsa.AppendPacketIn(data);
            }
            PacketReader p = null;
            switch (data[0])
            {
                case 0x34: // Keep Alive
                    keepalive = Server.tickcount.ElapsedMilliseconds;
                    break;
                //Identifiy
                /*     case 0x37:
                         //     for (int x = 0; x < 40; x++)
                         //     {
                         //        SendPacket(new CreateSlotMagic(new MagicSpell((byte)(x+81), "Hii", 1, 1, (byte)x, library.MagicType.Casted)).Compile());
                         //    }
                         int y = 14;
                         byte sprite = 0;
                         for (int x = 0; x < 255; x++)
                         {
                             Thread.Sleep(100);
                             if (x != 0 && x % 19 == 0)
                             {
                                 y += 3;
                                 x -= 19;
                             }
                             //    SendPacket(new CreateMonster(new Monster(3, (short)(x+23),(short)y,"village.map", sprite.ToString(), sprite, 0), Serial.NewMobile).Compile());
                             sprite++;
                         }
                         break;*/
                case 0x3A: //find 물건 찾기.
                    if (player.Map == "Loen")
                    {
                        var slot = data[1] + 40 + (12 * player.BankTab);
                        var itemtofind = World.NewItems.Where(xe => xe.Value.ParSer == player.Serial && xe.Value.InvSlot == slot).FirstOrDefault();
                        if (itemtofind.Value != null)
                        {
                            if (player.GetFreeSlot() != -1)
                            {
                                SendPacket(new DeleteEntrustSlot((byte)data[1]).Compile());

                                itemtofind.Value.InvSlot = player.GetFreeSlot();
                                SendPacket(new AddItemToInventory2(itemtofind.Value).Compile());
                            }
                        }
                    }
                    break;
                case 0x36: //Entrust 보관하기.
                    if (player.Map == "Loen")
                    {
                        var itemtoentrust = World.NewItems.Where(xe => xe.Value.ParSer == player.Serial && xe.Value.InvSlot == data[1]).FirstOrDefault();
                        if (itemtoentrust.Value != null)
                        {
                            SendPacket(new DeleteItemSlot((byte)itemtoentrust.Value.InvSlot).Compile());
                            itemtoentrust.Value.InvSlot = player.FreeBankSlot; // 선택한 인벤을 빈칸으로 만듬.
                            SendPacket(new AddItemToEntrust(itemtoentrust.Value).Compile());
                        }
                    }
                    break;

                case 0x35: //sell
                    if (player.Map == "Loen")
                    {
                        var itemtosell = World.NewItems.Where(xe => xe.Value.ParSer == player.Serial && xe.Value.InvSlot == data[1]).FirstOrDefault();
                        if (itemtosell.Value != null && itemtosell.Value.SellPrice > 0)
                        {
                            player.Gold += (uint)itemtosell.Value.SellPrice;
                            itemtosell.Value.Delete(player);
                        }
                    }
                    break;

                //Cast
                //  3D-00-00-01-00-00-00-0A-00-09-00
                case 0x3D:
                case 0x19:
                case 0x18: // 마법 캐스트 관련.
                    if (LKCamelot.Server.tickcount.ElapsedMilliseconds - player.CastSpeed > LastCast)
                    {
                        LastCast = LKCamelot.Server.tickcount.ElapsedMilliseconds;
                        p = new PacketReader(data, data.Count(), true);
                        int spellslot = p.ReadInt16();
												//if (player.MagicLearned.Count() < spellslot)
												//		return;
                        int castonid = p.ReadInt32();
                        short castx = p.ReadInt16();
                        short casty = p.ReadInt16();

                        script.spells.Spell castspell = player.MagicLearned.Where(xe => xe.Slot == spellslot).FirstOrDefault();
                        if (castspell == null) return;

                        castHandler.HandleCast(data[0], castspell, player, castonid, castx, casty);
                    }
                    break;
                //Attack
                case 0x17: // 공격하는 쪽.
                    if (LKCamelot.Server.tickcount.ElapsedMilliseconds - player.AttackSpeed > LastAttack)
                    {
                        LastAttack = LKCamelot.Server.tickcount.ElapsedMilliseconds;

                        World.SendToAll(new QueDele(player.Serial, player.Map, new SwingAnimationChar(player.Serial, player.Face).Compile()));
                        combatHandler.HandleMelee(player, data[1]);
                    }
                    break;

                //NPC Shop
                case 0x45:
                    var npclook = World.NewNpcs.Where(xe => xe.Key == data[1]).FirstOrDefault();
                    if (npclook.Value != null)
                    {
                        if (npclook.Value.Name == "Loen")
                        {
                            SendPacket(new SpawnShopGump2(npclook.Value.Gump).Compile());
                        }
                        if (npclook.Value.Name == "Arnold")
                        {
                            SendPacket(new SpawnShopGump2(npclook.Value.Gump).Compile());
                        }
                        if (npclook.Value.Name == "Employee")
                        {
                            SendPacket(new SpawnShopGump2(npclook.Value.Gump).Compile());
                        }
                        if (npclook.Value.Name == "Boy")
                        {
                            SendPacket(new SpawnShopGump2(npclook.Value.Gump).Compile());
                        }
                    }
                    break;

                case 0x2B: //2B-03-00-00-00-01-00-04-00-4D-65-6E-75-00
                    p = new PacketReader(data, data.Count(), true);
                    var npcid = p.ReadInt32();
                    var buyslot = p.ReadByte();

                    var npcitself = World.NewNpcs.Where(xe => xe.Key == npcid).FirstOrDefault();
                    if (npcitself.Value != null)
                        npcitself.Value.Buy(player, buyslot);

                    break;

                //Inventory
                case 0x00: //use
                    if (data[1] == 0)
                        return;
                    var itemu = World.NewItems.Where(xe => xe.Value.m_Parent == player
                      && xe.Value.InvSlot == data[1]).FirstOrDefault();

                    if (itemu.Value != null)
                        itemu.Value.Use(player);

                    break;

                case 0x20: //drop
                    var item = World.NewItems.Where(xe => xe.Value.m_Parent == player
                        && xe.Value.InvSlot == data[1]).FirstOrDefault();

                    if (item.Value != null)
                        item.Value.Drop(player);
                    break;

                case 0x1F: //pickup
                    var item1 = World.NewItems.Where(xe => xe.Value.m_Map != null
                        && xe.Value.m_Map == player.Map
                        && xe.Value.Loc.X == player.X && xe.Value.Loc.Y == player.Y)
                       .FirstOrDefault();

                    if (item1.Value != null)
                        item1.Value.PickUp(player);

                    break;
                case 0x1E: //equip Use
                    // case 0x36:
                    var eitem = World.NewItems.Where(xe => xe.Value.m_Parent == player
                        && xe.Value.InvSlot == data[1]).FirstOrDefault();

                    if (eitem.Value != null)
                    {
                        if (eitem.Value is script.item.BaseArmor || eitem.Value is script.item.BaseWeapon)
                            eitem.Value.Equip(player);
                        if (eitem.Value is script.item.BaseSpellbook)
                            eitem.Value.Use(player);
                        if (eitem.Value is script.item.BasePotion)
                            eitem.Value.Use(player);
                    }

                    break;
                case 0x23://unequip
                    var uitem = World.NewItems.Where(xe => xe.Value.m_Parent == player
                        && xe.Value.InvSlot == (data[1] + 25)).FirstOrDefault();

                    if (uitem.Value != null)
                        uitem.Value.Unequip(player, data[1] + 25);
                    break;

                case 0x25: //swap items
                    var item11 = World.NewItems.Where(xe => xe.Value.ParSer == player.Serial && xe.Value.InvSlot == data[1]).FirstOrDefault().Value;
                    int sss = 0;
                    if (data.Count() > 3)
                        sss = data[3];

                    var target1 = World.NewItems.Where(xe => xe.Value.ParSer == player.Serial && xe.Value.InvSlot == sss).FirstOrDefault().Value;

                    player.SwapItems(item11, target1, sss);

                    break;

                case 0x24: //drag,drop
                    var itemdragdrop = World.NewItems.Where(xe => xe.Value.ParSer == player.Serial && xe.Value.InvSlot == data[1]).FirstOrDefault().Value;
                    if (itemdragdrop != null)
                    {
                        p = new PacketReader(data, data.Count(), false);
                        var targetid = p.ReadInt32();

                        script.item.Item targeti = null;
                        World.NewItems.TryGetValue(targetid, out targeti);
                        if (targeti != null)
                        {
                            string fail = "Refining failed.";
                            string succ = "Refining success.";
                            if ((itemdragdrop is script.item.Zel && targeti is script.item.BaseArmor)
                                || (itemdragdrop is script.item.Dai && targeti is script.item.BaseWeapon))
                            {
                                if (targeti.TryUpgrade())
                                {
                                    castHandler.CreateMagicEffect(targeti.Loc, targeti.m_Map, 42);
                                    SendPacket(new UpdateChatBox(0xff, 0xff, 1, (short)succ.Count(), succ).Compile());
                                    SendPacket(new DeleteObject(targeti.m_Serial).Compile());
                                    SendPacket(new CreateItemGround2(targeti, targeti.m_Serial).Compile());
                                }
                                else
                                {
                                    castHandler.CreateMagicEffect(targeti.Loc, targeti.m_Map, 56);
                                    SendPacket(new UpdateChatBox(0xff, 0xff, 1, (short)fail.Count(), fail).Compile());
                                }
                                itemdragdrop.Delete(player);
                            }
                        }

                        if (targetid == 4)
                        {
                            if (itemdragdrop.Name == "Promote Life Drug" && AronStage == 4)
                            {
                                AronStage = 1;
                                itemdragdrop.Delete(player);
                                string achat = "[Aron]: Are you ready for the promotion?";
                                SendPacket(new UpdateChatBox(0xff, 0xff, 1, (short)achat.Count(), achat).Compile());
                            }
                            if (itemdragdrop.Name == "Promote Magic Drug" && AronStage == 4)
                            {
                                AronStage = 2;
                                itemdragdrop.Delete(player);
                                string achat = "[Aron]: Are you ready for the promotion?";
                                SendPacket(new UpdateChatBox(0xff, 0xff, 1, (short)achat.Count(), achat).Compile());
                            }
                        }
                    }
                    break;

                //Chat message
                case 0x16:
                    p = new PacketReader(data, data.Count(), false);
                    var str = p.ReadString();
                    var str2 = str.Split(' ');

                    if (Util.ContainsUnicodeCharacter(str))
                    {
                        var x = 1;
                    }

                    HandleChat(str2, str);

                    break;

                //Movement
                case 0x14:
                    player.Face = data[1];
                    World.SendToAll(new QueDele(player.Serial, player.Map, new ChangeFace(player.Serial, player.Face).Compile()));
                    break;
                case 0x15:

                    if (Server.tickcount.ElapsedMilliseconds - player.lastmove < 150)
                    {
                        return;
                    }

                    long totalwalk = 0;
                    foreach (var loc in walktrace)
                    {
                        totalwalk += loc;
                    }

                  //  if(player.Name == "SIR")
                  //  Console.WriteLine(string.Format("{0},{1}   {2}", px, py, Server.tickcount.ElapsedMilliseconds));           
                    if (Server.tickcount.ElapsedMilliseconds - player.lastmove > player.m_MoveSpeed)
                    {
                        p = new PacketReader(data, data.Count(), true);
                        player.Face = p.ReadInt16();
                        var px = p.ReadInt16();
                        var py = p.ReadInt16();

                        walktrace.Add(Server.tickcount.ElapsedMilliseconds - player.lastmove);
                        player.lastmove = Server.tickcount.ElapsedMilliseconds;
                        /*
                        if (walktrace.Count > 3 && totalwalk < 1600)
                        {
                            SendPacket(new MoveSpriteWalkChar(player.Serial, player.Face, player.X, player.Y).Compile());
                            return;
                        }

                        while (walktrace.Count > 4)
                            walktrace.Remove(walktrace.ElementAt(0)); 
                               */
                        if (World.Dist2d(new Point2D(px, py), player.m_Loc) > 3)
                        {
                            SendPacket(new MoveSpriteWalkChar(player.Serial, player.Face, player.X, player.Y).Compile());
                            return;
                        }
                        player.X = px;
                        player.Y = py;

                        World.SendToAll(new QueDele(player.Serial, player.Map, new MoveSpriteWalkChar(player.Serial, player.Face,
                        player.X, player.Y).Compile()));
                        parseFace();
                    }
                    else
                    {
                        SendPacket(new MoveSpriteWalkChar(player.Serial, player.Face, player.X, player.Y).Compile());
                    }
                    break;

                //Stats
                case 0x2C:
                    player.AddStat(ref player.m_Str);
                    SendPacket(new UpdateCharStats(player).Compile());
                    break;
                case 0x2D:
                    player.AddStat(ref player.m_Men);
                    SendPacket(new UpdateCharStats(player).Compile());
                    break;
                case 0x2E:
                    player.AddStat(ref player.m_Dex);
                    SendPacket(new UpdateCharStats(player).Compile());
                    break;
                case 0x2F:
                    player.AddStat(ref player.m_Vit);
                    SendPacket(new UpdateCharStats(player).Compile());
                    break;


                case 0x03: //Login
                    var result = TryLogin(data);
                    switch (result[0])
                    {
                        case '1':
                            var puser2 = result.Remove(0, 1).Split(',');
                            player = handler.add.Where(xe => xe.Value.Name == puser2[0]).FirstOrDefault().Value;
                            player.client = this;
                            player.loggedIn = true;
                            LoadPlayer();
                            SendPacket(new CloseLogin().Compile());
                            break;
                        case '2':
                            SendPacket(new WrongPass().Compile());
                            break;
                        case '3':
                            SendPacket(new WrongID().Compile());
                            break;
                        case '4': //invalid chars
                            SendPacket(new WrongID().Compile());
                            break;
                        case '5':
                            SendPacket(new AlreadyOnline().Compile());
                            break;
                        case '6':
                            player = new Player(this);
                            player.CreateBeginner(result.Remove(0, 1));
                            firstlogin = true;
                            LoadPlayer();
                            player.Pass = Cryption.CreateSaltedSHA256(player.Pass, player.Name);
                            try
                            {
                                handler.add.TryAdd(player.Name, player);
                                var touch = handler.add.Where(xe => xe.Key == player.Name).FirstOrDefault();
                                touch.Value.client = this;
                                touch.Value.loggedIn = true;
                                //   BinaryIO.SavePlayer(player);
                                // World.DBConnect.InsertPlayer(player);
                            }
                            catch
                            {
                                Console.WriteLine("failed to insert new player");
                            }
                            SendPacket(new CloseLogin().Compile());
                            break;
                    }
                    break;

                case 0x49: //delete magic
                    var magdelslot = data[1];
                    player.DeleteMagic(magdelslot);
                    break;

                case 0x26: //swap magic
                    if (data.Count() < 4)
                        player.SwapMagic(data[1], 0);
                    else
                        player.SwapMagic(data[1], data[3]);
                    break;

                case 0xff:
                    SendPacket(new PlayMusic(1000).Compile());
                    if (true) //Login
                    {
                        //         SendPacket(new CloseLogin().Compile());

                        //           SendPacket(new LoadWorld(1, 0x12, 0x12, new byte[] { 00, 04, 00, 00, 00, 00, 00, 00, 00, 03 },
                        //               01, 01, 00, 03, 04, 00, 00,
                        //               new byte[] { 0x69, 0x70, 0x69, 0x67, 0x6d, 0x79, 0x31, 0x2e, 0x6d, 0x61, 0x70, 00 }).Format());
                        break;
                    }
            }
        }
        /// <summary>
        /// Deserializes passed binary data.
        /// </summary>
        /// <param name="lInputData"><see cref="Byte[]"/> of data you want to serialize.</param>
        /// <param name="InitalOffset">Offset where you want to start serialization as <see cref="int"/></param>
        /// <param name="NewOffset"Offset where serialization ended as <see cref="int"/></param>
        /// <returns>Serialized objects as <see cref="object[]"/></returns>
        public virtual object[] DeserializeData(Byte[] lInputData, int InitalOffset, ref int NewOffset, int startType = 0, int endType = 0)
        {
            int offset = InitalOffset;
            List<object> OutputStructures = new List<object>();
            int loffset = 0;
            uint ManyParse = 0;
            bool ManyParseCondition = false;

            if (endType == 0)
                endType = cSerializableTypes.Count();

            //Check the bounds of start and end.
            if (startType > cSerializableTypes.Count() - 1 || endType > cSerializableTypes.Count())
                return null;

            for (int x = startType; x < endType; )
            {
                Type CurrentType = cSerializableTypes[x];
                if (offset >= lInputData.Count())
                {
                    log.Error("Offset is bigger than data count");
                    return null;
                }

                switch (CurrentType.Name)
                {
                    case "VarByte":
                        ManyParseCondition = true;
                        CurrentType = typeof(Byte);
                        break;//Go to next export round
                    case "VarUInt16":
                        ManyParseCondition = true;
                        CurrentType = typeof(UInt16);
                        break;//Go to next export round
                    case "VarUInt32":
                        ManyParseCondition = true;
                        CurrentType = typeof(UInt32);
                        break;//Go to next export round
                }
                switch (CurrentType.Name)
                {
                    case "String":
                        string strdata = ByteArrayToString(lInputData.Skip(offset).ToArray());
                        if (strdata == null)
                        {
                            log.Error("Problems while deserializing to String");
                            return null;
                        }
                        OutputStructures.Add(strdata);
                        loffset = strdata.Length + 1;
                        break;
                    case "Byte[]":
                        Byte[] bytedata = lInputData.Skip(offset).ToArray();
                        OutputStructures.Add(bytedata);
                        loffset = bytedata.Length;
                        break;
                    default:
                        //We must get size or we get error.
                        object result = ByteArrayToStructure(lInputData.Skip(offset).ToArray(), CurrentType, ref loffset);
                        if (result == null)
                        {
                            List<Type> t= new List<Type>();
                            foreach (System.Reflection.FieldInfo prop in CurrentType.GetFields())
                                t.Add(prop.FieldType);

                            object[] allData= (new BinarySerializer(t.ToArray())).DeserializeData(lInputData.Skip(offset).ToArray(), loffset, ref loffset);
                            int m=0;
                            object o = Activator.CreateInstance(CurrentType);
                            foreach (System.Reflection.FieldInfo prop in CurrentType.GetFields())
                            {
                                prop.SetValue(o, allData[m]);
                                m++;
                            }
                            log.Error("Problems while deserializing to unkown type");
                            return null;
                        }
                        OutputStructures.Add(result);
                        break;
                }

                offset += loffset;
                loffset = 0;

                if (ManyParseCondition)
                {
                    ManyParse = (uint)Convert.ChangeType(OutputStructures.Last(), typeof(uint));
                    ManyParseCondition = false;
                    x++;
                }
                else
                {
                    if (ManyParse > 1)
                        ManyParse--;
                    else
                        x++;
                }
            }

            NewOffset = offset;
            log.Debug("Deserialized "+ OutputStructures.Count+ " elements with types; "+ GetStringTypes(OutputStructures.ToArray()));
            return OutputStructures.ToArray();
        }
Esempio n. 9
0
 public static bool sendReport(UdpClient client, IPEndPoint to, Byte[] msg, int timeOut, int retries, LogFile log)
 {
     Byte[] received = new Byte[msg.Count()];
       int loop = 0;
       int nBytesSent;
       String dataReceived;
       string strRecv;
       bool response = false;
       do
       {
     try
     {
       nBytesSent = client.Send(msg, msg.Length);
       log.writeToLogFile(string.Format("message sent: {0}", System.Text.ASCIIEncoding.ASCII.GetString(msg)));
     }
     catch (Exception ex)
     {
       log.writeToLogFile("Excepcion al enviar udp : {0}", ex.Message);
     }
     Thread.Sleep(250);
     client.Client.ReceiveTimeout = timeOut * 2;
     for (int i = 0; i < 5; i++)
     {
       if (client.Available > 0)
       {
     try
     {
       received = client.Receive(ref to);
       dataReceived = System.Text.Encoding.ASCII.GetString(received);
       strRecv = System.Text.Encoding.ASCII.GetString(received).Trim('\0');
       log.writeToLogFile(string.Format("message response: {0}", strRecv));
       response = true;
       break;
     }
     catch (Exception ex)
     {
       log.writeToLogFile("Excepcion al recibir udp : {0}", ex.Message);
     }
       }
       else
       {
     //si ya lo envió, dale mas tiempo al server
     log.writeToLogFile("Extra time para recibir udp : {0}", timeOut * (loop + 1));
     Thread.Sleep(timeOut * (loop + 1));
       }
     }
     loop++;
       } while (!response && loop < retries);
       return response;
 }
Esempio n. 10
0
        public void CallOperation(int LinkId, string OperationName, object[] data=null)
        {
            MemoryStream StreamToWrite= new MemoryStream();
            BPOperation lOperation;
            try
            {
                lOperation = (from o in cOperations where o.cOperationName == OperationName select o).First();
            }
            catch { return; }

            if (lOperation.cSendCode == -1)
                return;

            //Serializes header data.
            BPProtocolHeader lBPProtocolHeader= new BPProtocolHeader((byte)lOperation.cSendCode);
            base.SerializeData(ref StreamToWrite, new object[] {lBPProtocolHeader});

            int ExpectedLength= lOperation.cDownlinkSerializer.GetSerializedDataLength();

            //It allows us to send only a command if data is not set.
            Byte[] SerializedData = new Byte[0];
            if (data != null && lOperation.cUplinkSerializer!=null)
            {
                SerializedData = lOperation.cUplinkSerializer.SerializeData(data);
                StreamToWrite.Write(SerializedData, 0, SerializedData.Count());
            }

            cLinkLayer.Write(new BPPacket( LinkId, lBPProtocolHeader, StreamToWrite.ToArray(), SerializedData, ExpectedLength);
        }
Esempio n. 11
0
		public List<Tuple<int, int>> Find(Byte[] input) => Find(input, 0, input.Count());
Esempio n. 12
0
 virtual public bool WriteBytes( string fileName, Byte[] bytes )
 {
     try
     {
         using ( IsolatedStorageFileStream isfs = new IsolatedStorageFileStream( fileName, FileMode.Create, UserStorage ) )
         {
             isfs.Write( bytes, 0, bytes.Count() );
         }
     }
     catch ( IsolatedStorageException ex )
     {
         Logger.Log(
             ID
             , string.Format( "WriteByte@{0}: {1}", fileName, ex.Message )
             , LogType.ERROR
         );
         return false;
     }
     return true;
 }