Ejemplo n.º 1
0
        /// <summary>
        /// Creates the wrapper function that wraps a native function with our own defined or custom calling convention,
        /// into a regular CDECL function that is natively supported by the C# programming language.
        ///
        /// The return value is a pointer to a C# compatible CDECL fcuntion that calls our game function.
        ///
        /// This allows us to call non-standard "usercall" game functions, such as for example functions that take values
        /// in registers as parameters instead of using the stack, functions which take paremeters in a mixture of both stack
        /// and registers as well as functions which varying return parameters, either caller or callee cleaned up.
        /// </summary>
        /// <param name="functionAddress">The address of the function to create a wrapper for.</param>
        /// <param name="reloadedFunction">Structure containing the details of the actual function in question.</param>
        /// <returns>Pointer to the new CDECL function address to call from C# code to invoke our game function.</returns>
        private static IntPtr CreateWrapperFunctionInternal <TFunction>(IntPtr functionAddress, ReloadedFunctionAttribute reloadedFunction)
        {
            // Retrieve number of parameters.
            int numberOfParameters    = FunctionCommon.GetNumberofParameters(typeof(TFunction));
            int nonRegisterParameters = numberOfParameters - reloadedFunction.SourceRegisters.Length;

            // List of ASM Instructions to be Compiled
            List <string> assemblyCode = new List <string> {
                "use32"
            };

            // Backup Stack Frame
            assemblyCode.Add("push ebp");       // Backup old call frame
            assemblyCode.Add("mov ebp, esp");   // Setup new call frame

            // Reserve Extra Stack Space
            if (reloadedFunction.ReservedStackSpace > 0)
            {
                assemblyCode.Add($"sub esp, {reloadedFunction.ReservedStackSpace}");
            }

            // Setup Function Parameters
            if (numberOfParameters > 0)
            {
                assemblyCode.AddRange(AssembleFunctionParameters(numberOfParameters, reloadedFunction.SourceRegisters));
            }

            // Call Game Function Pointer (gameFunctionPointer is address at which our function address is written)
            IntPtr gameFunctionPointer = MemoryBufferManager.Add(functionAddress, IntPtr.Zero);

            assemblyCode.Add("call dword [0x" + gameFunctionPointer.ToString("X") + "]");

            // Stack cleanup if necessary
            // Move back the stack pointer to before our pushed parameters
            if (nonRegisterParameters > 0 && reloadedFunction.Cleanup == ReloadedFunctionAttribute.StackCleanup.Caller)
            {
                int stackCleanupBytes = 4 * nonRegisterParameters;
                assemblyCode.Add($"add esp, {stackCleanupBytes}");
            }

            if (reloadedFunction.ReturnRegister != ReloadedFunctionAttribute.Register.eax)
            {
                // MOV Game's custom calling convention return register into our return register, EAX.
                assemblyCode.Add("mov eax, " + reloadedFunction.ReturnRegister);
            }

            // Unreserve Extra Stack Space
            if (reloadedFunction.ReservedStackSpace > 0)
            {
                assemblyCode.Add($"add esp, {reloadedFunction.ReservedStackSpace}");
            }

            // Restore Stack Frame and Return
            assemblyCode.Add("pop ebp");
            assemblyCode.Add("ret");

            // Write function to buffer and return pointer.
            byte[] assembledMnemonics = Assembler.Assembler.Assemble(assemblyCode.ToArray());
            return(MemoryBufferManager.Add(assembledMnemonics));
        }
Ejemplo n.º 2
0
        public string GetLocalDiskAlignmentTest()
        {
            string result = FunctionCommon.GetLocalDiskAlignment();

            return(result);
            // TODO: 将断言添加到 方法 FunctionCommonTest.GetLocalDiskAlignmentTest()
        }
        public LoginResponseDto Login(LoginDto dto)
        {
            var result = new LoginResponseDto();

            dto.Password = FunctionCommon.GetMd5(FunctionCommon.GetSimpleMd5(dto.Password));

            var accountFromDb = db.Accounts.FirstOrDefault(x => x.UserName == dto.UserName && x.Password == dto.Password && !x.DelFlag);

            if (accountFromDb == null)
            {
                return null;
            }

            var isStudent = db.AccountGroups.FirstOrDefault(x => !x.DelFlag && x.Name.ToLower().Equals("Sinh viên")).Id == accountFromDb.AccountGroupId;

            var accessToken = JwtAuthenticationExtensions.CreateToken(accountFromDb, isStudent);

            result.AccessToken = accessToken;

            result.FirstName = accountFromDb.UserInfo.FirstName;

            result.LastName = accountFromDb.UserInfo.LastName;

            result.Avatar = accountFromDb.Avatar;

            result.UserName = accountFromDb.UserName;

            result.IsStudent = isStudent;

            return result;
        }
Ejemplo n.º 4
0
        private void UpdateSideCommandbar(Player player)
        {
            var sideCommandBar = _root.ScriptObject.GetMember("SideCommandBar").ToObject();

            if (player.SelectedUnits.Count > 0 && !_commandbarVisible)
            {
                var fadeIn = sideCommandBar.Item.ScriptObject.GetMember("FadeIn");

                if (fadeIn.Type != ValueType.Undefined)
                {
                    List <Value> emptyArgs = new List <Value>();
                    FunctionCommon.ExecuteFunction(fadeIn, emptyArgs.ToArray(), sideCommandBar.Item.ScriptObject, _window.Context.Avm);
                    _commandbarVisible = true;
                }

                UpdateCommandbuttons();
            }
            else if (player.SelectedUnits.Count == 0 && _commandbarVisible)
            {
                var fadeOut = sideCommandBar.Item.ScriptObject.GetMember("FadeOut");

                if (fadeOut.Type != ValueType.Undefined)
                {
                    List <Value> emptyArgs = new List <Value>();
                    FunctionCommon.ExecuteFunction(fadeOut, emptyArgs.ToArray(), sideCommandBar.Item.ScriptObject, _window.Context.Avm);
                    _commandbarVisible = true;
                }

                _commandbarVisible = false;
            }
        }
        public DocumentResponseDto UpdateFile(DocumentDto documentDto, string token, string host)
        {
            int    Id        = JwtAuthenticationExtensions.ExtractTokenInformation(token).UserId;
            int    idStudent = context.Students.FirstOrDefault(x => x.UserInfoId == Id && !x.DelFlag).Id;
            string url       = FunctionCommon.SaveFile(documentDto.File, documentDto.DocumentId, documentDto.FileName);
            string urlFile   = context.Documents.FirstOrDefault(x => x.Id == documentDto.DocumentId && x.StudentId == idStudent && !x.DelFlag).Url;
            string strUrl    = host + "/" + url;
            var    doc       = context.Documents.FirstOrDefault(x => !x.DelFlag && x.Id == documentDto.DocumentId);

            context.Documents.Where(x => x.Id == documentDto.DocumentId && x.StudentId == idStudent && !x.DelFlag).Update(x => new Database.Schema.Entity.Document
            {
                Url            = strUrl,
                FileName       = documentDto.FileName,
                StatusId       = 2,
                DocumentTypeId = doc.DocumentTypeId
            });
            context.SaveChanges();
            FunctionCommon.DeleteFile(urlFile.Substring(host.Length, urlFile.Length - host.Length));
            return(context.Documents.Where(x => x.Id == documentDto.DocumentId && !x.DelFlag).Select(x => new DocumentResponseDto
            {
                Id = x.Id,
                DocumentTypeId = x.DocumentTypeId,
                DocumentTypeName = x.DocumentType.Name,
                Url = x.Url,
                StatusId = x.StatusId,
                StatusName = x.Status.Name,
                IsRequired = x.DocumentType.IsRequired,
                ResponseMessage = x.ResponseMessage,
                Description = x.DocumentType.Description,
                FileName = x.FileName
            }).FirstOrDefault());
        }
        public IHttpActionResult ChangePassword(int id, [FromBody] PasswordDto password)
        {
            try
            {
                var token = Request.Headers.GetValues("Authorization").First();

                if (!FunctionCommon.ValidatePermission(token, id))
                {
                    return(ResponseMessage(new HttpResponseMessage(HttpStatusCode.Unauthorized)
                    {
                        Content = new StringContent("Not allowed.")
                    }));
                }
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                var i = _accountService.ChangePassword(password, id);
                if (i == -1)
                {
                    return(BadRequest("Cannot found this account"));
                }
                else if (i == 0)
                {
                    return(BadRequest("Old password isn't correct"));
                }
                return(Ok("Update password success"));
            }
            catch (Exception e)
            {
                return(InternalServerError(e));
            }
        }
        /// <summary>
        /// Creates the wrapper function that wraps a native function with our own defined or custom calling convention,
        /// into a regular X64 Microsoft Calling Convention function that is natively supported by the C# programming language.
        ///
        /// This allows us to call non-standard "usercall" game functions, such as for example functions that take values
        /// in registers as parameters instead of using the stack, functions which take paremeters in a mixture of both stack
        /// and registers as well as functions which varying return parameters, either caller or callee cleaned up.
        /// </summary>
        /// <param name="functionAddress">The address of the function to create a wrapper for.</param>
        /// <param name="reloadedFunction">Structure containing the details of the actual function in question.</param>
        /// <returns>Pointer to the new X64 Microsoft Calling Convention function address to call from C# code to invoke our game function.</returns>
        private static IntPtr CreateWrapperFunctionInternal <TFunction>(IntPtr functionAddress, X64ReloadedFunctionAttribute reloadedFunction)
        {
            // Retrieve number of parameters.
            int numberOfParameters    = FunctionCommon.GetNumberofParametersWithoutFloats(typeof(TFunction));
            int nonRegisterParameters = numberOfParameters - reloadedFunction.SourceRegisters.Length;

            // List of ASM Instructions to be Compiled
            List <string> assemblyCode = new List <string> {
                "use64"
            };

            // Backup Stack Frame
            assemblyCode.Add("push rbp");       // Backup old call frame
            assemblyCode.Add("mov rbp, rsp");   // Setup new call frame

            // Setup Function Parameters
            if (numberOfParameters > 0)
            {
                assemblyCode.AddRange(AssembleFunctionParameters(numberOfParameters, reloadedFunction.SourceRegisters));
            }

            // Make Shadow Space if necessary.
            if (reloadedFunction.ShadowSpace)
            {
                assemblyCode.Add("sub rsp, 32");   // Setup new call frame
            }
            // Assemble the call to the game function in question.
            assemblyCode.AddRange(HookCommon.X64AssembleAbsoluteCallMnemonics(functionAddress, reloadedFunction));

            // Move return register back if necessary.
            if (reloadedFunction.ReturnRegister != X64ReloadedFunctionAttribute.Register.rax)
            {
                assemblyCode.Add("mov rax, " + reloadedFunction.ReturnRegister);
            }

            // Restore the stack pointer from the Shadow Space
            // 8 = IntPtr.Size
            // 32 = Shadow Space
            if (reloadedFunction.ShadowSpace)
            {
                assemblyCode.Add("add rsp, " + ((nonRegisterParameters * 8) + 32));
            }
            else
            {
                assemblyCode.Add("add rsp, " + (nonRegisterParameters * 8));
            }

            // Restore Stack Frame and Return
            assemblyCode.Add("pop rbp");
            assemblyCode.Add("ret");

            // Write function to buffer and return pointer.
            byte[] assembledMnemonics = Assembler.Assembler.Assemble(assemblyCode.ToArray());
            return(MemoryBufferManager.Add(assembledMnemonics));
        }
        /// <summary>
        /// Creates a wrapper function that transforms our own C# function into an arbitrary calling convention; with pointer to transformed C# function.
        /// Basically, this creates a function pointer to a C# function.
        /// Note: You must keep an instance of this class as long as you're using the function pointer.
        /// </summary>
        /// <param name="function">The function to create a function pointer to.</param>
        public static X64ReverseFunctionWrapper <TFunction> CreateReverseWrapper(TFunction function)
        {
            // Set our C# function.
            var reverseFunctionWrapper = new X64ReverseFunctionWrapper <TFunction>();

            reverseFunctionWrapper.CSharpFunctionCopy = function;

            // Take fast path for CDECL, otherwise assemble wrapper.
            var reloadedFunctionAttribute = FunctionCommon.GetX64ReloadedFunctionAttribute <TFunction>();

            reverseFunctionWrapper.Pointer = CreateX64WrapperFunctionInternal <TFunction>(Marshal.GetFunctionPointerForDelegate(function), reloadedFunctionAttribute);

            return(reverseFunctionWrapper);
        }
        public bool UpdatePass(UpdatePassword updatePassword, string token)
        {
            int Id = JwtAuthenticationExtensions.ExtractTokenInformation(token).UserId;

            if (string.Compare(FunctionCommon.GetMd5(FunctionCommon.GetSimpleMd5(updatePassword.OldPassword)), context.Accounts.FirstOrDefault(x => x.UserInfoId == Id && !x.DelFlag).Password) != 0)
            {
                return(false);
            }
            else
            {
                var TaiKhoan = context.Accounts.FirstOrDefault(x => x.UserInfoId == Id && !x.DelFlag);
                TaiKhoan.Password = FunctionCommon.GetMd5(FunctionCommon.GetSimpleMd5(updatePassword.NewPassword));
                context.SaveChanges();
                return(true);
            }
        }
 public bool ForgetPass(ForgetPassword input)
 {
     var taikhoan = db.Accounts.FirstOrDefault(x => string.Compare(x.UserName, input.Username) == 0 && string.Compare(x.UserInfo.Email, input.Email) == 0 && !x.DelFlag);
     if (taikhoan == null)
     {
         return false;
     }
     else
     {
         string newPass = FunctionCommon.AutoPassword();
         SendMail.Send(taikhoan.UserInfo.Email, newPass, "[DUTAdmissionSystem] Forget Password");
         taikhoan.Password = FunctionCommon.GetMd5(FunctionCommon.GetSimpleMd5(newPass));
         db.SaveChanges();
         return true;
     }
 }
        /// <summary>
        /// Creates the wrapper function for redirecting program flow to our C# function.
        /// </summary>
        /// <param name="functionAddress">The address of the function to create a wrapper for.</param>
        /// <returns></returns>
        internal static IntPtr CreateReverseWrapperInternal <TFunction>(IntPtr functionAddress, ReloadedFunctionAttribute reloadedFunction)
        {
            // Retrieve number of parameters.
            int numberOfParameters    = FunctionCommon.GetNumberofParameters(typeof(TFunction));
            int nonRegisterParameters = numberOfParameters - reloadedFunction.SourceRegisters.Length;

            // List of ASM Instructions to be Compiled
            List <string> assemblyCode = new List <string> {
                "use32"
            };

            // Backup Stack Frame
            assemblyCode.Add("push ebp");       // Backup old call frame
            assemblyCode.Add("mov ebp, esp");   // Setup new call frame

            // Push registers for our C# method as necessary.
            assemblyCode.AddRange(AssembleFunctionParameters(numberOfParameters, reloadedFunction.SourceRegisters));

            // Call C# Function Pointer (cSharpFunctionPointer is address at which our C# function address is written)
            IntPtr cSharpFunctionPointer = MemoryBufferManager.Add(functionAddress, IntPtr.Zero);

            assemblyCode.Add("call dword [0x" + cSharpFunctionPointer.ToString("X") + "]");

            // Restore stack pointer + stack frame
            assemblyCode.Add($"add esp, {numberOfParameters * 4}");

            // MOV our own return register, EAX into the register expected by the calling convention
            assemblyCode.Add($"mov {reloadedFunction.ReturnRegister}, eax");

            // Restore Stack Frame and Return
            assemblyCode.Add("pop ebp");

            // Caller/Callee Cleanup
            if (reloadedFunction.Cleanup == ReloadedFunctionAttribute.StackCleanup.Callee)
            {
                assemblyCode.Add($"ret {nonRegisterParameters * 4}");
            }
            else
            {
                assemblyCode.Add("ret");
            }

            // Assemble and return pointer to code
            byte[] assembledMnemonics = Assembler.Assembler.Assemble(assemblyCode.ToArray());
            return(MemoryBufferManager.Add(assembledMnemonics));
        }
Ejemplo n.º 12
0
        private void InitializePalantir(Player player)
        {
            if (!_palantirInitialized)
            {
                logger.Info("Initialize Palantir!");

                var showCommandInterface = _root.ScriptObject.GetMember("SetPalantirFrameState");
                if (showCommandInterface.Type != ValueType.Undefined)
                {
                    bool         good      = Array.Exists(player.Template.IntrinsicSciences, s => s == "SCIENCE_GOOD");
                    List <Value> emptyArgs = new List <Value>();
                    emptyArgs.Add(Value.FromString(good ? "_good" : "_evil"));
                    FunctionCommon.ExecuteFunction(showCommandInterface, emptyArgs.ToArray(), _root.ScriptObject, _window.Context.Avm);
                    _palantirInitialized = true;
                }
            }
        }
Ejemplo n.º 13
0
        public int ChangePassword(PasswordDto password, int id)
        {
            var account = db.Accounts.FirstOrDefault(x => !x.DelFlag && x.UserId == id);

            if (account == null)
            {
                return(-1);                 // cannot found this account
            }
            if (!account.Password.Equals(FunctionCommon.GetMd5(FunctionCommon.GetSimpleMd5(password.OldPassword))))
            {
                return(0);
            }

            account.Password = FunctionCommon.GetMd5(FunctionCommon.GetSimpleMd5(password.NewPassword));

            db.SaveChanges();
            return(1);
        }
Ejemplo n.º 14
0
        public bool AddParent(ParentDto parent)
        {
            try
            {
                var user = new EM.Database.Schema.User
                {
                    FirstName            = parent.FirstName,
                    LastName             = parent.LastName,
                    Gender               = parent.Gender,
                    Birthday             = parent.Birthday,
                    Address              = parent.Address,
                    PhoneNumber          = parent.PhoneNumber,
                    IdentificationNumber = parent.IdentificationNumber,
                    Avatar               = parent.Avatar
                };

                db.Users.Add(user);
                db.SaveChanges();
                var account = new EM.Database.Schema.Account
                {
                    UserName = parent.Username,
                    Password = FunctionCommon.GetMd5(FunctionCommon.GetSimpleMd5(parent.Password)),
                    UserId   = user.Id,
                    GroupId  = db.Groups.FirstOrDefault(x => !x.DelFlag && x.Name.Equals("Parent")).Id
                };

                db.Accounts.Add(account);
                db.SaveChanges();

                var parentFromDb = new EM.Database.Schema.Parent
                {
                    UserId = user.Id
                };
                db.Parents.Add(parentFromDb);
                db.SaveChanges();

                return(true);
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// Creates a wrapper function that transforms our own C# function into an arbitrary calling convention; with pointer to transformed C# function.
        /// Basically, this creates a function pointer to a C# function.
        /// Note: You must keep an instance of this class as long as you're using the function pointer.
        /// </summary>
        /// <param name="function">The function to create a function pointer to.</param>
        public static ReverseFunctionWrapper <TFunction> CreateReverseWrapper(TFunction function)
        {
            // Set our C# function.
            var reverseFunctionWrapper = new ReverseFunctionWrapper <TFunction>();

            reverseFunctionWrapper.CSharpFunctionCopy = function;

            // Take fast path for CDECL, otherwise assemble wrapper.
            var reloadedFunctionAttribute = FunctionCommon.GetReloadedFunctionAttribute <TFunction>();

            if (reloadedFunctionAttribute.Equals(new ReloadedFunctionAttribute(CallingConventions.Cdecl)))
            {
                reverseFunctionWrapper.Pointer = (IntPtr)Marshal.GetFunctionPointerForDelegate(function);
            }
            else
            {
                reverseFunctionWrapper.Pointer = CreateReverseWrapperInternal <TFunction>(Marshal.GetFunctionPointerForDelegate(function), reloadedFunctionAttribute);
            }

            return(reverseFunctionWrapper);
        }
        public bool AddUser(UserInfoDto userInfo)
        {
            try
            {
                var user = new EM.Database.Schema.User
                {
                    FirstName            = userInfo.FirstName,
                    LastName             = userInfo.LastName,
                    Gender               = userInfo.Gender,
                    Birthday             = userInfo.Birthday,
                    Address              = userInfo.Address,
                    PhoneNumber          = userInfo.PhoneNumber,
                    IdentificationNumber = userInfo.IdentificationNumber,
                    Avatar               = userInfo.Avatar
                };

                db.Users.Add(user);
                db.SaveChanges();
                var account = new EM.Database.Schema.Account
                {
                    UserName = userInfo.Username,
                    Password = FunctionCommon.GetMd5(FunctionCommon.GetSimpleMd5(userInfo.Password)),
                    UserId   = user.Id,
                    GroupId  = userInfo.IsAdmin ? db.Groups.FirstOrDefault(x => !x.DelFlag && x.Name.Equals("Admin")).Id :
                               db.Groups.FirstOrDefault(x => !x.DelFlag && x.Name.Equals("Mod")).Id
                };

                db.Accounts.Add(account);
                db.SaveChanges();
                return(true);
            }
            catch (Exception e)
            {
                return(false);
            }
        }
Ejemplo n.º 17
0
        private void UpdateCommandbuttons()
        {
            if (_game.Scene3D.LocalPlayer.SelectedUnits.Count == 0)
            {
                return;
            }

            var selectedUnit = _game.Scene3D.LocalPlayer.SelectedUnits.First();

            if (selectedUnit == null)
            {
                return;
            }
            if (selectedUnit.Definition.CommandSet == null || selectedUnit.Definition.CommandSet.Value == null)
            {
                return;
            }

            var isProducing = selectedUnit.ProductionUpdate?.IsProducing ?? false;
            var commandSet  = selectedUnit.Definition.CommandSet.Value;

            var aptCommandButtons = _root.ScriptObject.GetMember("CommandButtons").ToObject();

            for (var i = 1; i <= 6; i++)
            {
                var commandButton = aptCommandButtons.GetMember((i - 1).ToString()).ToObject();
                var placeHolder   = commandButton.GetMember("placeholder").ToObject();
                placeHolder.Item.Visible = false;

                if (!commandSet.Buttons.ContainsKey(i))
                {
                    continue;
                }
                var button = commandSet.Buttons[i].Value;
                if (!button.InPalantir || button.Command == CommandType.Revive)
                {
                    continue;
                }

                var createContent = commandButton.GetMember("CreateContent");
                var args          = new List <Value>();
                args.Add(Value.FromString("bttn"));
                args.Add(Value.FromString("CommandButton"));

                //TODO: fix so this works
                FunctionCommon.ExecuteFunction(createContent, args.ToArray(), commandButton.Item.ScriptObject, _window.Context.Avm);

                placeHolder.Item.Visible = true;
                var shape = (placeHolder.Item as SpriteItem).Content.Items[1] as RenderItem;

                var(count, progress) = isProducing ? selectedUnit.ProductionUpdate.GetCountAndProgress(button) : (0, 0.0f);

                var texture = button.ButtonImage.Value;
                shape.RenderCallback = (AptRenderingContext renderContext, Geometry geom, Texture orig) =>
                {
                    var enabled = selectedUnit.CanPurchase(button);
                    var rect    = new Rectangle(renderContext.GetBoundingBox(geom)).ToRectangleF();
                    renderContext.GetActiveDrawingContext().DrawMappedImage(texture, rect, grayscaled: !enabled);

                    if (count > 0)
                    {
                        renderContext.GetActiveDrawingContext().FillRectangleRadial360(
                            new Rectangle(rect),
                            new ColorRgbaF(1.0f, 1.0f, 1.0f, 0.6f),
                            progress);

                        if (count > 1)
                        {
                            var textRect = new Rectangle(RectangleF.Transform(rect, Matrix3x2.CreateTranslation(new Vector2(0, rect.Width / 4))));
                            renderContext.GetActiveDrawingContext().DrawText(count.ToString(), _font, TextAlignment.Center, _fontColor, textRect);
                        }
                    }
                };
            }
        }
        /// <summary>
        /// Creates the wrapper function for redirecting program flow to our C# function.
        /// </summary>
        /// <param name="reloadedFunction">Structure containing the details of the actual function in question.</param>
        /// <param name="functionAddress">The address of the function to create a wrapper for.</param>
        /// <returns></returns>
        internal static IntPtr CreateX64WrapperFunctionInternal <TFunction>(IntPtr functionAddress, X64ReloadedFunctionAttribute reloadedFunction)
        {
            // Retrieve number of parameters.
            int numberOfParameters    = FunctionCommon.GetNumberofParametersWithoutFloats(typeof(TFunction));
            int nonRegisterParameters = numberOfParameters - reloadedFunction.SourceRegisters.Length;

            // List of ASM Instructions to be Compiled
            List <string> assemblyCode = new List <string> {
                "use64"
            };

            // If the attribute is Microsoft Call Convention, take fast path!
            if (reloadedFunction.Equals(new X64ReloadedFunctionAttribute(X64CallingConventions.Microsoft)))
            {
                // Backup old call frame
                assemblyCode.AddRange(HookCommon.X64AssembleAbsoluteJumpMnemonics(functionAddress, reloadedFunction));
            }
            else
            {
                // Backup Stack Frame
                assemblyCode.Add("push rbp");       // Backup old call frame
                assemblyCode.Add("mov rbp, rsp");   // Setup new call frame

                // We assume that we are stack aligned in usercall/custom calling conventions, if we are not, game over for now.
                // Our stack frame alignment is off by 8 here, we must also consider non-register parameters.
                // Note to self: In the case you forget, dummy. Your stack needs to be 16 byte aligned.

                // Calculate the bytes our wrapper parameters take on the stack in total.
                // The stack frame backup, push rbp and CALL negate themselves so it's down to this.
                // Then our misalignment to the stack.
                int stackBytesTotal   = (nonRegisterParameters * 8);
                int stackMisalignment = (stackBytesTotal % 16);

                // Prealign stack
                assemblyCode.Add($"sub rbp, {stackMisalignment}");   // Setup new call frame

                // Setup the registers for our C# method.
                assemblyCode.AddRange(AssembleFunctionParameters(numberOfParameters, reloadedFunction, stackMisalignment));

                // And now we add the shadow space for C# method's Microsoft Call Convention.
                assemblyCode.Add("sub rsp, 32");   // Setup new call frame

                // Assemble the Call to C# Function Pointer.
                assemblyCode.AddRange(HookCommon.X64AssembleAbsoluteCallMnemonics(functionAddress, reloadedFunction));

                // MOV our own return register, EAX into the register expected by the calling convention
                assemblyCode.Add($"mov {reloadedFunction.ReturnRegister}, rax");

                // Restore stack pointer (this is always the same, our function is Microsoft Call Convention Compliant)
                assemblyCode.Add("add rsp, " + ((nonRegisterParameters * 8) + 32));

                // Restore stack alignment
                assemblyCode.Add($"add rbp, {stackMisalignment}");

                // Restore Stack Frame and Return
                assemblyCode.Add("pop rbp");
                assemblyCode.Add("ret");
            }

            // Assemble and return pointer to code
            byte[] assembledMnemonics = Assembler.Assembler.Assemble(assemblyCode.ToArray());
            return(MemoryBufferManager.Add(assembledMnemonics));
        }
        public StudentDto UpdateStudent(StudentDto studentInput)
        {
            if (studentInput.Id == 0)
            {
                var user = new UserInfo()
                {
                    FirstName = studentInput.FirstName,
                    LastName  = studentInput.LastName,
                    Avatar    = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT_S9DUg_S9CHf-DxgcNbxYzZmibzud95wxTQslnreREOxA1ch1",
                    BirthInfo = new BirthInfo()
                    {
                        Sex          = true,
                        DateOfBirth  = studentInput.DateOfBirth,
                        PlaceOfBirth = "Việt Nam"
                    },
                    ContactInfo = new ContactInfo()
                    {
                        Address     = studentInput.Address,
                        Email       = studentInput.Email,
                        PhoneNumber = studentInput.PhoneNumber
                    },
                    IdentityInfo = new IdentityInfo()
                    {
                        IdentityNumber = studentInput.IdentityNumber,
                        DateOfIssue    = DateTime.Now,
                        PlaceOfIssue   = "Việt Nam"
                    }
                };

                var student = new Student()
                {
                    UserInfo             = user,
                    IdentificationNumber = studentInput.IdentificationNumber,
                    HightSchoolName      = "THPT",
                    ElectionTypeId       = 1,
                    YouthGroupInfo       = null,
                    CircumstanceTypeId   = 1,
                    EnrollmentAreaId     = 1,
                    ClassId      = studentInput.ClassId,
                    PersonalInfo = new PersonalInfo()
                    {
                        EthnicId           = 1,
                        NationalityId      = 1,
                        ReligionId         = 1,
                        PermanentResidence = "Việt Nam"
                    },
                };

                var account = new Account()
                {
                    UserInfo       = user,
                    AccountGroupId = 2,
                    Token          = "",
                    UserName       = studentInput.IdentificationNumber,
                    Password       = FunctionCommon.GetMd5(FunctionCommon.GetSimpleMd5(studentInput.IdentificationNumber))
                };

                db.Accounts.Add(account);
                db.Students.Add(student);
            }
            else
            {
                var student = db.Students.FirstOrDefault(x => x.Id == studentInput.Id && !x.DelFlag);
                if (student != null)
                {
                    student.UserInfo.FirstName                   = studentInput.FirstName;
                    student.UserInfo.LastName                    = studentInput.LastName;
                    student.UserInfo.BirthInfo.DateOfBirth       = studentInput.DateOfBirth;
                    student.UserInfo.IdentityInfo.IdentityNumber = studentInput.IdentityNumber;
                    student.UserInfo.ContactInfo.PhoneNumber     = studentInput.PhoneNumber;
                    student.UserInfo.ContactInfo.Email           = studentInput.Email;
                    student.UserInfo.ContactInfo.Address         = studentInput.Address;
                    student.ClassId = studentInput.ClassId;
                }
            }
            db.SaveChanges();
            studentInput.ClassName = db.Classes.FirstOrDefault(x => x.Id == studentInput.ClassId && !x.DelFlag).Name;
            return(studentInput);
        }
        public void getExcelFile()
        {
            DataContext context = new DataContext();

            //Create COM Objects. Create a COM object for everything that is referenced
            Excel.Application xlApp       = new Excel.Application();
            Excel.Workbook    xlWorkbook  = xlApp.Workbooks.Open(@"C:\Users\Aiden\Desktop\data.xlsx");
            Excel._Worksheet  xlWorksheet = xlWorkbook.Sheets[1];
            Excel.Range       xlRange     = xlWorksheet.UsedRange;

            int rowCount = xlRange.Rows.Count;
            int colCount = xlRange.Columns.Count;

            //iterate over the rows and columns and print to the console as it appears in the file
            //excel is not zero based!!
            for (int i = 1; i <= 50; i++)
            {
                var user = new UserInfo()
                {
                    FirstName = xlRange.Cells[i, 4].Value2.ToString(),
                    LastName  = xlRange.Cells[i, 3].Value2.ToString(),
                    Avatar    = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT_S9DUg_S9CHf-DxgcNbxYzZmibzud95wxTQslnreREOxA1ch1",
                    BirthInfo = new BirthInfo()
                    {
                        Sex          = true,
                        DateOfBirth  = DateTime.ParseExact(xlRange.Cells[i, 5].Value2.ToString(), "dd/MM/yyyy", null),
                        PlaceOfBirth = xlRange.Cells[i, 10].Value2.ToString()
                    },
                    ContactInfo = new ContactInfo()
                    {
                        Address     = xlRange.Cells[i, 10].Value2.ToString(),
                        Email       = xlRange.Cells[i, 8].Value2.ToString(),
                        PhoneNumber = xlRange.Cells[i, 7].Value2.ToString()
                    },
                    IdentityInfo = new IdentityInfo()
                    {
                        IdentityNumber = xlRange.Cells[i, 11].Value2.ToString(),
                        DateOfIssue    = DateTime.Now,
                        PlaceOfIssue   = "Việt Nam"
                    }
                };

                var student = new Student()
                {
                    UserInfo             = user,
                    IdentificationNumber = xlRange.Cells[i, 2].Value2.ToString(),
                    HightSchoolName      = "THPT",
                    ElectionTypeId       = 1,
                    YouthGroupInfo       = null,
                    CircumstanceTypeId   = 1,
                    EnrollmentAreaId     = Convert.ToInt32(xlRange.Cells[i, 9].Value2.ToString()),
                    ClassId      = Convert.ToInt32(xlRange.Cells[i, 1].Value2.ToString()),
                    PersonalInfo = new PersonalInfo()
                    {
                        EthnicId           = 1,
                        NationalityId      = 1,
                        ReligionId         = 1,
                        PermanentResidence = xlRange.Cells[i, 10].Value2.ToString()
                    },
                };

                var account = new Account()
                {
                    UserInfo       = user,
                    AccountGroupId = 2,
                    Token          = "",
                    UserName       = xlRange.Cells[i, 2].Value2.ToString(),
                    Password       = FunctionCommon.GetMd5(FunctionCommon.GetSimpleMd5(xlRange.Cells[i, 2].Value2.ToString()))
                };

                context.Accounts.Add(account);
                context.Students.Add(student);
            }

            context.SaveChanges();
            //cleanup
            GC.Collect();
            GC.WaitForPendingFinalizers();

            //rule of thumb for releasing com objects:
            //  never use two dots, all COM objects must be referenced and released individually
            //  ex: [somthing].[something].[something] is bad

            //release com objects to fully kill excel process from running in the background
            Marshal.ReleaseComObject(xlRange);
            Marshal.ReleaseComObject(xlWorksheet);

            //close and release
            xlWorkbook.Close();
            Marshal.ReleaseComObject(xlWorkbook);

            //quit and release
            xlApp.Quit();
            Marshal.ReleaseComObject(xlApp);
        }