示例#1
0
 public void ReadFromDatabase(DataRow row)
 {
     Male      = ReadMethods.EnumToBool(row["Male"].ToString());
     Hair      = byte.Parse(row["Hair"].ToString());
     HairColor = byte.Parse(row["HairColor"].ToString());
     Face      = byte.Parse(row["Face"].ToString());
 }
        /// <summary>
        /// Reads all fields with the specified binding of the object in alphabetical order using reflection.
        /// </summary>
        public static void ReadAllFields(
            this IBitBuffer buffer, object target, BindingFlags flags = DefaultBindingFlags)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            Type type = target.GetType();

            FieldInfo[] fields = type.GetFields(flags);
            SortMembers(fields);

            var readParams = new[] { buffer };

            foreach (FieldInfo fi in fields)
            {
                // find read method
                MethodInfo?readMethod;

                if (fi.FieldType.IsEnum)
                {
                    readMethod = EnumReadMethod;
                }
                else if (!ReadMethods.TryGetValue(fi.FieldType, out readMethod))
                {
                    throw new LidgrenException("Failed to find read method for type " + fi.FieldType);
                }

                // read and set value
                var value = readMethod.Invoke(null, readParams);
                fi.SetValue(target, value);
            }
        }
示例#3
0
        internal static ReadMethods GetReflectionBasedReadMethods(bool treatCollectionAsUserObject)
        {
            ReadMethods readMethods = new ReadMethods();

            readMethods.readMethodsProvider = new DynamicMethodProvider <ReadMethodDelegate>(t =>
            {
                return(ObjectReader.ReadObjectInnerUsingReflection);
            });

            readMethods.touchInlinedObjectMethodsProvider = new DynamicMethodProvider <TouchInlinedObjectMethodDelegate>(t =>
            {
                return((or, refId) => or.TryTouchInlinedObjectUsingReflection(t, refId));
            });

            readMethods.completeMethodsProvider = new DynamicMethodProvider <CompleteMethodDelegate>(t =>
            {
                return((or, refId) => or.CompletedInnerUsingReflection(refId));
            });

            readMethods.createObjectMethodsProvider = new DynamicMethodProvider <CreateObjectMethodDelegate>(t =>
            {
                return(() => ObjectReader.CreateObjectUsingReflection(t, treatCollectionAsUserObject));
            });
            return(readMethods);
        }
        private ObjectReader CreateReader(Stream stream)
        {
            ReadMethods readMethods = new ReadMethods();

            if (settings.DeserializationMethod == Method.Generated)
            {
                readMethods.readMethodsProvider = new DynamicMethodProvider <ReadMethodDelegate>(t =>
                {
                    var generator = new ReadMethodGenerator(t, settings.DisableTypeStamping, settings.TreatCollectionAsUserObject);
                    return(generator.Generate());
                });

                readMethods.touchInlinedObjectMethodsProvider = new DynamicMethodProvider <TouchInlinedObjectMethodDelegate>(t =>
                {
                    if (recipes.TryGetValue(t, out var recipe))
                    {
                        return((or, objectId) => or.ReadRecipe(objectId, recipe));
                    }

                    var generator = new TouchInlinedObjectGenerator(t, settings.DisableTypeStamping, settings.TreatCollectionAsUserObject);
                    return(generator.Generate());
                });

                readMethods.completeMethodsProvider = new DynamicMethodProvider <CompleteMethodDelegate>(t =>
                {
                    var generator = new CompletedGenerator(t, objectsForSurrogates, settings.DisableTypeStamping, settings.TreatCollectionAsUserObject, OnPostDeserialization != null);
                    return(generator.Generate());
                });

                readMethods.createObjectMethodsProvider = new DynamicMethodProvider <CreateObjectMethodDelegate>(t =>
                {
                    var generator = new CreateObjectGenerator(t, settings.DisableTypeStamping, settings.TreatCollectionAsUserObject);
                    return(generator.Generate());
                });

                readMethods.cloneContentMehtodsProvider = new DynamicMethodProvider <CloneMethodDelegate>(t =>
                {
                    if (t.IsValueType)
                    {
                        return(ObjectReader.CloneContentUsingReflection);
                    }
                    var generator = new CloneContentMethodGenerator(t);
                    return(generator.Generate());
                });

                readMethods.addHashCodeBasedDeferredElementProvider = new DynamicMethodProvider <AddDeferredHashCodeBasedElementDelegate>(t =>
                {
                    var generator = new AddDeferredElementToHashCodeBasedMethodGenerator(t);
                    return(generator.Generate());
                });
            }
            else
            {
                readMethods = GetReflectionBasedReadMethods(settings.TreatCollectionAsUserObject);
            }

            return(new ObjectReader(stream, readMethods, objectsForSurrogates, recipes, OnPostDeserialization,
                                    settings.TreatCollectionAsUserObject, settings.VersionTolerance, settings.UseBuffering,
                                    settings.DisableTypeStamping, settings.ReferencePreservation, settings.ForceStampVerification));
        }
示例#5
0
        /// <inheritdoc />
        public T Read <T>()
        {
            if (this.State != PacketStateType.Read)
            {
                throw new InvalidOperationException("Packet is in write-only mode.");
            }

            return(ReadMethods.TryGetValue(typeof(T), out Func <BinaryReader, object> method)
                ? (T)method.Invoke(this.reader)
                : default);
示例#6
0
        /// <devdoc>
        ///     <para>
        ///         Moves to the element that contains the current attribute node.
        ///     </para>
        /// </devdoc>
        public override bool MoveToElement()
        {
            ReadMethod = ReadMethods.MoveToElement;
            var result = BaseReader.MoveToElement();

            if (result)
            {
                _XPathCollection.Advance(this);
            }
            return(result);
        }
示例#7
0
        /// <devdoc>
        ///     <para>
        ///         Reads the next
        ///         node from the stream.
        ///     </para>
        /// </devdoc>
        public override bool Read()
        {
            ReadMethod = ReadMethods.Read;

            var ret = BaseReader.Read();

            if (ret)
            {
                _XPathCollection.Advance(this);
            }
            return(ret);
        }
示例#8
0
        /// <devdoc>
        ///     <para>Moves to the attribute with the specified <see cref='XPathReader.Name' /> .</para>
        /// </devdoc>
        public override bool MoveToAttribute(string AttributeName)
        {
            ReadMethod = ReadMethods.MoveToAttribute;

            var ret = BaseReader.MoveToAttribute(AttributeName);

            if (ret)
            {
                _XPathCollection.Advance(this);
            }
            return(ret);
        }
示例#9
0
        /// <include file='doc\XPathReader.uex' path='docs/doc[@for="XPathReader.MoveToAttribute"]/*' />
        /// <devdoc>
        /// <para>Moves to the attribute with the specified <see cref='System.Xml.XPathReader.Name'/> .</para>
        /// </devdoc>
        public override bool MoveToAttribute(string name)
        {
            this.readMethod = ReadMethods.MoveToAttribute;

            bool ret = false;

            ret = this.reader.MoveToAttribute(name);

            if (ret)
            {
                xpathCollection.Advance(this);
            }
            return(ret);
        }
示例#10
0
        /// <include file='doc\XPathReader.uex' path='docs/doc[@for="XPathReader.Read"]/*' />
        /// <devdoc>
        ///    <para>
        ///       Reads the next
        ///       node from the stream.
        ///    </para>
        /// </devdoc>
        public override bool Read()
        {
            this.readMethod = ReadMethods.Read;

            bool ret = true;

            ret = this.reader.Read();

            if (ret)
            {
                xpathCollection.Advance(this);
            }
            return(ret);
        }
示例#11
0
        /// <include file='doc\XPathReader.uex' path='docs/doc[@for="XPathReader.MoveToElement"]/*' />
        /// <devdoc>
        ///    <para>
        ///       Moves to the element that contains the current attribute node.
        ///    </para>
        /// </devdoc>
        public override bool MoveToElement()
        {
            bool ret = false;

            readMethod = ReadMethods.MoveToElement;

            ret = this.reader.MoveToElement();

            if (ret)
            {
                xpathCollection.Advance(this);
            }

            return(ret);
        }
示例#12
0
        internal ReadMethods GetReflectionBasedReadMethods(bool treatCollectionAsUserObject)
        {
            ReadMethods readMethods = new ReadMethods();

            readMethods.readMethodsProvider = new DynamicMethodProvider <ReadMethodDelegate>(t =>
            {
                return(ObjectReader.ReadObjectInnerUsingReflection);
            });

            readMethods.touchInlinedObjectMethodsProvider = new DynamicMethodProvider <TouchInlinedObjectMethodDelegate>(t =>
            {
                if (recipes.TryGetValue(t, out var recipe))
                {
                    return((or, refId) => or.ReadRecipe(refId, recipe));
                }
                return((or, refId) => or.TryTouchInlinedObjectUsingReflection(t, refId));
            });

            readMethods.completeMethodsProvider = new DynamicMethodProvider <CompleteMethodDelegate>(t =>
            {
                return((or, refId) => or.CompletedInnerUsingReflection(refId));
            });

            readMethods.createObjectMethodsProvider = new DynamicMethodProvider <CreateObjectMethodDelegate>(t =>
            {
                return(() => ObjectReader.CreateObjectUsingReflection(t, treatCollectionAsUserObject));
            });

            readMethods.addHashCodeBasedDeferredElementProvider = new DynamicMethodProvider <AddDeferredHashCodeBasedElementDelegate>(t =>
            {
                return((hashCodeBased, key, value) =>
                {
                    var hashCodeBasedType = hashCodeBased.GetType();
                    var addMethod = hashCodeBasedType.GetMethod("Add");
                    if (addMethod.GetParameters().Length == 2)
                    {
                        addMethod.Invoke(hashCodeBased, new[] { key, value });
                    }
                    else
                    {
                        addMethod.Invoke(hashCodeBased, new[] { key });
                    }
                });
            });
            return(readMethods);
        }
示例#13
0
 public bool GetCharacterByID(int ID, out WorldCharacter pChar)
 {
     World.Networking.WorldClient pclient = ClientManager.Instance.GetClientByCharID(ID);
     if (pclient != null)
     {
         pChar = pclient.Character;
         return(true);
     }
     else
     {
         pChar = null;
         Character      DBpChar    = ReadMethods.ReadCharObjectByIDFromDatabase(ID, Program.DatabaseManager);
         WorldCharacter ReaderChar = new WorldCharacter(DBpChar, null);
         pChar = ReaderChar;
         if (DBpChar == null)
         {
             return(false);
         }
         return(true);
     }
 }
示例#14
0
        /// <summary>
        /// Constructor for the Application object.
        /// </summary>
        public App()
        {
            // Global handler for uncaught exceptions.
            UnhandledException += Application_UnhandledException;

            // Standard Silverlight initialization
            InitializeComponent();

            // Phone-specific initialization
            InitializePhoneApplication();

            //Create viewmodels
            _connManager = new ConnectionManagers();
            _readMethods = new ReadMethods();


            // Show graphics profiling information while debugging.
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // Display the current frame rate counters.
                Application.Current.Host.Settings.EnableFrameRateCounter = true;

                // Show the areas of the app that are being redrawn in each frame.
                //Application.Current.Host.Settings.EnableRedrawRegions = true;

                // Enable non-production analysis visualization mode,
                // which shows areas of a page that are handed off to GPU with a colored overlay.
                //Application.Current.Host.Settings.EnableCacheVisualization = true;

                // Disable the application idle detection by setting the UserIdleDetectionMode property of the
                // application's PhoneApplicationService object to Disabled.
                // Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
                // and consume battery power when the user is not using the phone.
                PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
            }
        }
示例#15
0
        /// <include file='doc\XPathReader.uex' path='docs/doc[@for="XPathReader.Read"]/*' />
        /// <devdoc>
        ///    <para>
        ///       Reads the next
        ///       node from the stream.
        ///    </para>
        /// </devdoc>
        public override bool Read() {

            this.readMethod = ReadMethods.Read;

            bool ret = true;
            ret = this.reader.Read();

            if(ret) {
                xpathCollection.Advance(this);
            }
            return ret;
        }
示例#16
0
 /// <devdoc>
 ///     <para>Moves to the attribute with the specified index.</para>
 /// </devdoc>
 public override void MoveToAttribute(int i)
 {
     ReadMethod = ReadMethods.MoveToAttribute;
     BaseReader.MoveToAttribute(i);
     _XPathCollection.Advance(this);
 }
示例#17
0
        /// <include file='doc\XPathReader.uex' path='docs/doc[@for="XPathReader.MoveToAttribute2"]/*' />
        /// <devdoc>
        ///    <para>Moves to the attribute with the specified index.</para>
        /// </devdoc>
        public override void MoveToAttribute(int i) {
            this.readMethod = ReadMethods.MoveToAttribute;
            this.reader.MoveToAttribute(i);
            xpathCollection.Advance(this);

        }
示例#18
0
        /// <include file='doc\XPathReader.uex' path='docs/doc[@for="XPathReader.MoveToElement"]/*' />
        /// <devdoc>
        ///    <para>
        ///       Moves to the element that contains the current attribute node.
        ///    </para>
        /// </devdoc>
        public override bool MoveToElement() {
            bool ret = false;

            readMethod = ReadMethods.MoveToElement;

            ret = this.reader.MoveToElement();

            if (ret) {
                xpathCollection.Advance(this);
            }

            return ret;
        }
示例#19
0
        public static void Login(LoginClient pClient, Packet pPacket)
        {
            // Initialize DB
            var dbClient = Program.DatabaseManager.GetClient();

            // XX XX XX XX XX XX XX XX XX XX XX - login length
            // 00 00 00 00 00 00 00 - space
            // XX XX XX XX XX XX XX - password
            // 00 00 00 00 00 00 00 00 00 4F 72 69 67 69 6E 61 6C 00 00 00 00 00 00 00 00 00 00 00

            // Define packet lengths, as these may change with client updates
            const int packetLength  = 54,
                      loginBlock    = 11,
                      spaceLength   = 7,
                      passwordBlock = 7;

            var md5            = pPacket.ReadStringForLogin(packetLength);
            var md5Char        = md5.ToCharArray();
            var clientUsername = "";
            var clientPassword = "";

            // TODO - Escape these before query processing

            // Read from 0 --> 11
            for (var i = 0; i <= loginBlock; i++)
            {
                clientUsername += md5Char[i].ToString().Replace("\0", "");
            }

            Log.WriteLine(LogLevel.Debug, "{0} tries to login.", clientUsername);

            // Read from 18 --> onwards
            for (var i = loginBlock + spaceLength; i <= loginBlock + spaceLength + passwordBlock; i++)
            {
                clientPassword += md5Char[i].ToString().Replace("\0", "");
            }

            Log.WriteLine(LogLevel.Debug, "{0} tries to login.", clientPassword);

            DataTable loginData;

            using (dbClient)
                loginData = dbClient.ReadDataTable("SELECT * FROM accounts WHERE Username= '******'");

            // Auto account creation if no username found
            if (loginData.Rows.Count == 0)
            {
                dbClient.ExecuteQuery("INSERT INTO accounts (username, password) VALUES ('" + clientUsername + "','" +
                                      clientPassword + "')");

                using (dbClient)
                    loginData = dbClient.ReadDataTable("SELECT * FROM accounts WHERE Username= '******'");
            }

            if (loginData == null)
            {
                return;
            }
            if (loginData.Rows.Count <= 0)
            {
                return;
            }

            foreach (DataRow row in loginData.Rows)
            {
                var username = (string)row["username"];
                var password = (string)row["password"];
                var banned   = ReadMethods.EnumToBool(row["banned"].ToString());

                if (clientPassword == password)
                {
                    if (banned)
                    {
                        SendFailedLogin(pClient, ServerError.Blocked);
                        Log.WriteLine(LogLevel.Debug, "Banned user - {0} tries to login.", clientUsername);
                    }

                    else if (ClientManager.Instance.IsLoggedIn(username))
                    {
                        Log.WriteLine(LogLevel.Warn, "{0} is trying dual login. Disconnecting.", username);
                        pClient.Disconnect();

                        break;
                    }
                    else
                    {
                        pClient.Username        = username;
                        pClient.IsAuthenticated = true;
                        pClient.Admin           = 0; /*(byte)row["Admin"];*/
                        pClient.AccountID       = int.Parse(row["id"].ToString());
                        WorldList(pClient, false);
                    }
                }
                else
                {
                    SendFailedLogin(pClient, ServerError.InvalidCredentials);
                }
            }
        }
示例#20
0
 /// <include file='doc\XPathReader.uex' path='docs/doc[@for="XPathReader.MoveToAttribute2"]/*' />
 /// <devdoc>
 ///    <para>Moves to the attribute with the specified index.</para>
 /// </devdoc>
 public override void MoveToAttribute(int i)
 {
     this.readMethod = ReadMethods.MoveToAttribute;
     this.reader.MoveToAttribute(i);
     xpathCollection.Advance(this);
 }
示例#21
0
        public bool LoadCharacters()
        {
            if (!Authenticated)
            {
                return(false);
            }
            Characters = new Dictionary <byte, WorldCharacter>();
            try
            {
                DataTable charData = null;
                using (DatabaseClient dbClient = Program.DatabaseManager.GetClient())
                {
                    charData = dbClient.ReadDataTable("SELECT * FROM Characters WHERE AccountID='" + this.AccountID + "'");
                }

                if (charData != null)
                {
                    foreach (DataRow row in charData.Rows)
                    {
                        Database.Storage.Character ch = new Database.Storage.Character();
                        ch.PositionInfo.ReadFromDatabase(row);
                        ch.LookInfo.ReadFromDatabase(row);
                        ch.CharacterStats.ReadFromDatabase(row);
                        ch.Slot           = (byte)row["Slot"];
                        ch.CharLevel      = (byte)row["Level"];
                        ch.AccountID      = this.AccountID;
                        ch.Name           = (string)row["Name"];
                        ch.ID             = GetDataTypes.GetInt(row["CharID"]);
                        ch.Job            = (byte)row["Job"];
                        ch.Money          = GetDataTypes.GetLong(row["Money"].ToString());
                        ch.Exp            = long.Parse(row["Exp"].ToString());
                        ch.HP             = int.Parse(row["CurHP"].ToString());
                        ch.HPStones       = 10;
                        ch.MasterJoin     = DateTime.Parse(row["MasterJoin"].ToString());
                        ch.SP             = int.Parse(row["CurSP"].ToString());
                        ch.SPStones       = 10;
                        ch.StatPoints     = (byte)row["StatPoints"];
                        ch.UsablePoints   = (byte)row["UsablePoints"];
                        ch.Fame           = 0; // TODO
                        ch.GameSettings   = Database.DataStore.ReadMethods.GetGameSettings(ch.ID, Program.DatabaseManager);
                        ch.ClientSettings = Database.DataStore.ReadMethods.GetClientSettings(ch.ID, Program.DatabaseManager);
                        ch.Shortcuts      = Database.DataStore.ReadMethods.GetShortcuts(ch.ID, Program.DatabaseManager);
                        ch.QuickBar       = Database.DataStore.ReadMethods.GetQuickBar(ch.ID, Program.DatabaseManager);
                        ch.QuickBarState  = Database.DataStore.ReadMethods.GetQuickBarState(ch.ID, Program.DatabaseManager);
                        ch.ReviveCoper    = GetDataTypes.GetLong(row["MasterReciveMoney"]);
                        if (row.IsNull("GroupID"))
                        {
                            ch.GroupId = -1;
                        }
                        else
                        {
                            ch.GroupId = long.Parse(row["GroupID"].ToString());
                        }

                        if (ch.GroupId == -1 || row.IsNull("IsGroupMaster"))
                        {
                            ch.IsGroupMaster = false;
                        }
                        else
                        {
                            ch.IsGroupMaster = ReadMethods.EnumToBool(row["IsGroupMaster"].ToString());
                        }

                        Characters.Add(ch.Slot, new WorldCharacter(ch, this));
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteLine(LogLevel.Exception, "Error loading characters from {0}: {1}", Username, ex.InnerException.ToString());
                return(false);
            }
            return(true);
        }
示例#22
0
        /// <include file='doc\XPathReader.uex' path='docs/doc[@for="XPathReader.MoveToAttribute"]/*' />
        /// <devdoc>
        /// <para>Moves to the attribute with the specified <see cref='System.Xml.XPathReader.Name'/> .</para>
        /// </devdoc>
        public override bool MoveToAttribute(string name) {
            this.readMethod = ReadMethods.MoveToAttribute;

            bool ret = false;

            ret = this.reader.MoveToAttribute(name);

            if (ret) {
                xpathCollection.Advance(this);
            }
            return ret;
        }