public async Task <object> UpdateUser([FromBody] UpdateUserInfo updateUser,
                                              [FromQuery][Required] string oldUsername, [FromQuery][Required] string oldPassword)
        {
            try
            {
                string       token    = HttpContext.Request.Headers["token"];
                List <Claim> claims   = authService.GetTokenClaims(token).ToList();
                string       username = claims.Find(x => x.Type == ClaimTypes.Name).Value;
                string       password = claims.Find(x => x.Type == "Password").Value;
                if (oldUsername != username || oldPassword != password)
                {
                    return(StatusCode(401, Responder.Fail("wrong username or password")));
                }
                Result result = await userService.UpdateUserAsync(username, updateUser);

                if (result.status == 200)
                {
                    return(Ok(Responder.Success(result.data)));
                }
                else
                {
                    return(StatusCode(result.status, Responder.Fail(result.data)));
                }
            }
            catch (Exception error)
            {
                return(BadRequest(Responder.Fail(error.Message)));
            }
        }
示例#2
0
    //更新用户信息
    public void btnUserOK_Click(object sender, DirectEventArgs e)
    {
        //更新的当前站的数据库的USER表
        bool b = dal.FactoryDAL(PageHelper.ConnectionStrings, "FW_UserManager_SP", new List <IFields>()
        {
            dal.CreateIFields()
            .Append("username", FSecurityHelper.CurrentUserDataGET()[0].ToString())
            .Append("email", txtUserEmail.Text)
            .Append("option", "update")
            .Append("NameCHS", txtUserName.Text.ToUpper())
            .Append("NameENG", txtUserNameen.Text.ToUpper())
            .Append("tel", txtUserTel.Text.ToUpper())
            .Append("ext", txtUserExt.Text.ToUpper())
            .Append("fax", txtUserFax.Text.ToUpper())
        }).Update();

        if (b)
        {
            //用线程更新的香港数据库的USER表
            //  UpdateUserInfo.Start();
            UpdateUserInfo.CreateFile(txtUserEmail.Text, txtUserTel.Text.ToUpper(), txtUserFax.Text.ToUpper(), txtUserExt.Text.ToUpper(), txtUserName.Text.ToUpper(), txtUserNameen.Text.ToUpper());

            ReloadDate();
            X.AddScript("location.reload();");
        }
    }
示例#3
0
        /// <summary>
        /// method to update customer details to our database for future use
        /// </summary>
        /// <param name="custId"></param>
        /// <param name="cardId"></param>
        /// <param name="userid"></param>
        public static String UpdateStripeCardData(UpdateUserInfo obj)
        {
            String     msg = "";
            SqlCommand cmd = new SqlCommand();

            try
            {
                cmd.CommandText = "UPDATE MppUser SET PlanStatus=1, stp_custId = @cust_id, stp_cardId = @card_id WHERE MppUserID=@userid";
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@userid", SqlDbType.Int).Value  = obj.UserId;
                cmd.Parameters.Add("@cust_id", SqlDbType.VarChar, 500).Value = obj.CustId;
                cmd.Parameters.Add("@card_id", SqlDbType.VarChar, 500).Value = obj.CardId;
                DataAccess.ExecuteCommand(cmd);
            }
            catch (SqlException ex)
            {
                msg = ex.Message;
                LogFile.WriteLog("Update StripeCard Data : " + msg, SessionData.SellerName);
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                LogFile.WriteLog("Update StripeCard Data : " + msg, SessionData.SellerName);
            }
            finally
            {
                if (cmd != null)
                {
                    cmd.Dispose();
                }
            }
            return(msg);
        }
示例#4
0
        public void UpdateCurrentUser(UpdateUserContract data)
        {
            var user = m_authenticationManager.GetCurrentUser();

            if (user.ExternalId == null)
            {
                throw new MainServiceException(MainServiceErrorCode.UserHasMissingExternalId,
                                               $"User with ID {user.Id} has missing ExternalID",
                                               HttpStatusCode.BadRequest,
                                               new object[] { user.Id }
                                               );
            }

            var client = m_communicationProvider.GetAuthUserApiClient();

            var authUser = client.GetUserAsync(user.ExternalId.Value).GetAwaiter().GetResult();

            authUser.FirstName = data.FirstName;
            authUser.LastName  = data.LastName;

            client.EditSelfAsync(user.ExternalId.Value, authUser).GetAwaiter().GetResult();

            var updateUserInfo = new UpdateUserInfo(authUser.UserName, authUser.FirstName, authUser.LastName);

            new UpdateUserWork(m_userRepository, user.Id, updateUserInfo).Execute();
        }
示例#5
0
        public void Update(UpdateUserInfo userInfo)
        {
            if (userInfo.FirstName.IsNotNullOrWhiteSpace())
            {
                FirstName = userInfo.FirstName;
            }

            if (userInfo.MiddleName.IsNotNullOrWhiteSpace())
            {
                MiddleName = userInfo.MiddleName;
            }

            if (userInfo.LastName.IsNotNullOrWhiteSpace())
            {
                LastName = userInfo.LastName;
            }

            if (userInfo.Email.IsNotNullOrWhiteSpace())
            {
                Email = userInfo.Email;
            }

            if (userInfo.MobileNumber.IsNotNullOrWhiteSpace())
            {
                MobileNumber = userInfo.MobileNumber;
            }

            BloodGroup  = userInfo.BloodGroup;
            DateOfBirth = userInfo.DateOfBirth;
        }
示例#6
0
 public IActionResult EditUserStatus(UpdateUserInfo check, int userId)
 {
     if (checkLogStatus() == false)
     {
         return(RedirectToAction("LoginPage", "User"));
     }
     else
     {
         int? id       = HttpContext.Session.GetInt32("userId");
         User thisUser = _context.Users.Where(u => u.UserId == userId).Include(p => p.products).SingleOrDefault();
         if (thisUser.UserId != 1)
         {
             if (ModelState.IsValid)
             {
                 thisUser.Status     = check.Status;
                 thisUser.ReviewedId = check.ReviewedId;
                 _context.SaveChanges();
                 TempData["error"] = "User Status Changed successfully!";
                 return(RedirectToAction("EditUserPage"));
             }
             else
             {
                 TempData["error"] = "Inputs invalid!";
                 return(RedirectToAction("EditUserPage"));
             }
         }
         else
         {
             TempData["error"] = "You cannot change status of this user!";
             return(RedirectToAction("EditUserPage"));
         }
     }
 }
        public bool UpdateUser(FilterDefinition <BsonDocument> filter, UpdateUserInfo updateUser)
        {
            try
            {
                UpdateDefinition <BsonDocument> update = Builders <BsonDocument> .Update.Set("updateAt", BsonDateTime.Create(DateTime.Now));

                if (updateUser.username != null)
                {
                    FilterDefinition <BsonDocument> nameFilter = Builders <BsonDocument> .Filter.Eq("username", updateUser.username);

                    BsonDocument checkUser = mCollection.Find(nameFilter).First();
                    if (checkUser != null)
                    {
                        return(false);
                    }
                    update = update.Set("username", updateUser.username);
                }
                if (updateUser.password != null)
                {
                    string newPassword = Utilities.CalcuteSHA256Hash(updateUser.password);
                    update = update.Set("password", newPassword);
                }
                if (updateUser.email != null)
                {
                    update = update.Set("email", updateUser.email);
                }
                UpdateResult result = mCollection.UpdateOne(filter, update);
                return(result.ModifiedCount > 0);
            }
            catch
            {
                return(false);
            }
        }
示例#8
0
 public void AddIdForExternalUsers(List <UserContract> userDetailContracts)
 {
     foreach (var userDetailContract in userDetailContracts)
     {
         var userInfo = new UpdateUserInfo(userDetailContract.UserName, userDetailContract.FirstName, userDetailContract.LastName);
         var userId   = new CreateOrUpdateUserIfNotExistWork(m_userRepository, userDetailContract.ExternalId, null, userInfo, m_codeGenerator).Execute();
         userDetailContract.Id = userId;
     }
 }
示例#9
0
        public int CreateUserIfNotExist(CreateUserIfNotExistContract data)
        {
            var userExternalId = data.ExternalId;
            var userInfo       = new UpdateUserInfo(data.Username, data.FirstName, data.LastName);

            var authUserApiClient = m_communicationProvider.GetAuthUserApiClient();
            var userRoles         = authUserApiClient.GetRolesByUserAsync(userExternalId).GetAwaiter().GetResult();
            var userId            = new CreateOrUpdateUserIfNotExistWork(m_userRepository, userExternalId, userRoles, userInfo, m_codeGenerator).Execute();

            return(userId);
        }
示例#10
0
        public async Task UpdateUserInfo(string userId, UpdateUserInfo viewModel)
        {
            var user = await Get(userId);

            var mapped = _mapper.Map(viewModel, user);
            var result = await _userManager.UpdateAsync(_mapper.Map <User>(mapped));

            if (!result.Succeeded)
            {
                throw new ApplicationException($"Cannot update user info with id '{userId}'");
            }
        }
        public async Task <Result <UserDto> > Handle(UpdateUserInfo request, CancellationToken cancellationToken)
        {
            var currentUser = await _currentUser.GetOpenIdUser();

            if (currentUser.IsFailed)
            {
                return(Result <UserDto> .Error(currentUser.Errors.FirstOrDefault()));
            }

            var user = await _userRepository.UpdateAsync(currentUser.Value.Id, request);

            return(Result <UserDto> .Success(_mapper.Map <UserDto>(user)));
        }
示例#12
0
 public void Undo_업데이트제거과정시에_업데이트_전의_데이터가_없는_경우()
 {
     //Arrange
     MockRepository mocks = new MockRepository();
     UserInfo stubData = mocks.Stub<UserInfo>();
     UserInfo stubPreData = null;
     stubData.id = "id";
     stubData.password = "******";
     ICommandListener mockListener = mocks.DynamicMock<UserAuthController>();
     UpdateUserInfo uui = new UpdateUserInfo(stubData, mockListener);
     uui.preUserInfo = stubPreData;
     //Act
     uui.Undo();
 }
        public ActionResult UserActivation(String ActivationCode)
        {
            string result   = "";
            var    userInfo = new UpdateUserInfo();

            if (!String.IsNullOrEmpty(ActivationCode))
            {
                var dr = userregistrationData.AccountConfirmation(ActivationCode);
                if (dr != null)
                {
                    result = "true";
                    String StripeCustmId   = Convert.ToString(dr["stp_custId"]);
                    var    customerOptions = new StripeCustomerCreateOptions
                    {
                        Email       = Convert.ToString(dr["Email"]),
                        Description = Convert.ToString(dr["name"]),
                    };
                    var customerDetails = StripeHelper.AddCustomer(customerOptions, StripeCustmId);
                    if (customerDetails != null)
                    {
                        var planId       = (int)Statics.StripePlans.Trial;
                        var subscription = StripeHelper.Subscription(customerDetails.Id, new StripeSubscriptionCreateOptions {
                            PlanId = planId.ToString()
                        }, out result);
                        if (String.IsNullOrEmpty(result))
                        {
                            userInfo.CustId        = customerDetails.Id;
                            userInfo.UserId        = Convert.ToInt32(dr["id"]);
                            userInfo.PlanId        = planId;
                            userInfo.PlanStartDate = Convert.ToDateTime(subscription.CurrentPeriodStart).ToString();
                            userInfo.TrialEndDate  = subscription.TrialEnd.ToString();
                            userInfo.Amount        = subscription.StripePlan.Amount.ToString();
                            userInfo.PlanEndDate   = Convert.ToDateTime(subscription.CurrentPeriodEnd).ToString();
                            AccountData.UpdateStripeData(userInfo);
                        }
                        else
                        {
                            result = "Subscription error, please contact Administrator";
                        }
                    }
                }
                else
                {
                    result = "false";
                }
            }

            ViewBag.Confirmation = result;
            return(View("Login"));
        }
        public async Task <User> UpdateAsync(OpenIdKey openIdKey, UpdateUserInfo userInfo)
        {
            var db   = _connectionMultiplexer.GetDatabase();
            var user = await db.JsonGetAsync <User>(openIdKey.GetPersistenceKey());

            user.Update(userInfo);

            var json = JsonSerializer.Serialize(user, _jsonSerializerOptions);
            var persistenceResult = await db.JsonSetAsync(user.GetPersistenceKey(), json);

            _logger.LogDebug("[User] [UPDATE] {json} [{result}]", json, persistenceResult.IsSuccess);

            return(user);
        }
示例#15
0
 protected override void Page_Load(object sender, EventArgs e)
 {
     UpdateUserInfo.Start();
     UserName    = FSecurityHelper.CurrentUserDataGET()[2];
     webTitle    = FSecurityHelper.CurrentUserDataGET()[32] == "" ? "" : FSecurityHelper.CurrentUserDataGET()[32] + "-";
     this.dview  = this.GetMenu().Tables[0].DefaultView;
     this.dview1 = this.GetMenu().Tables[1].DefaultView;
     if (!IsPostBack)
     {
         BinderStat();
         cmbStat.Text = FSecurityHelper.CurrentUserDataGET()[12];
         selectUserInfo();
     }
 }
示例#16
0
        public async Task Authenticate_WithValidUser_ReturnsOk()
        {
            // Arrange
            CreateUser user = new CreateUser()
            {
                FirstName = "Test",
                LastName  = "User",
                Email     = "*****@*****.**",
                Password  = "******"
            };
            UpdateUserInfo updateUserInfo = new UpdateUserInfo();

            var requestContent = new StringContent(
                JsonConvert.SerializeObject(user),
                Encoding.UTF8, "application/json");

            // Act
            HttpResponseMessage createUserResponse = await _client.PutAsync("api/user", requestContent);

            string createdUserSerialized = await createUserResponse.Content.ReadAsStringAsync();

            User createdUser = JsonConvert.DeserializeObject <User>(createdUserSerialized);

            createUserResponse.StatusCode.Should().Be(HttpStatusCode.OK);
            createdUser.Id.Should().NotBe(Guid.Empty);


            AuthenticateUser authenticateUser = new AuthenticateUser
            {
                Email    = "*****@*****.**",
                Password = "******"
            };

            var authRequestContent = new StringContent(
                JsonConvert.SerializeObject(authenticateUser),
                Encoding.UTF8, "application/json");
            HttpResponseMessage authenticateResponse = await _client.PostAsync("api/user/authenticate", authRequestContent);

            authenticateResponse.StatusCode.Should().Be(HttpStatusCode.OK);

            string authenticatedUserSerialized = await authenticateResponse.Content.ReadAsStringAsync();

            AuthenticatedUserDto authenticatedUserDto = JsonConvert.DeserializeObject <AuthenticatedUserDto>(authenticatedUserSerialized);

            authenticatedUserDto.User.Should().NotBe(null);
            authenticatedUserDto.User.Id.Should().NotBe(Guid.Empty);
            authenticatedUserDto.WebToken.Token.Should().NotBe(string.Empty);
            authenticatedUserDto.WebToken.Token.Should().NotBe(null);
        }
示例#17
0
        public void UpdateUser(int userId, UpdateUserContract data)
        {
            var userExternalId = GetUserExternalId(userId);
            var client         = m_communicationProvider.GetAuthUserApiClient();
            var authUser       = client.GetUserAsync(userExternalId).GetAwaiter().GetResult();

            authUser.FirstName = data.FirstName;
            authUser.LastName  = data.LastName;

            client.EditUserAsync(userExternalId, authUser).GetAwaiter().GetResult();

            var updateUserInfo = new UpdateUserInfo(authUser.UserName, authUser.FirstName, authUser.LastName);

            new UpdateUserWork(m_userRepository, userId, updateUserInfo).Execute();
        }
示例#18
0
        public void Undo_업데이트제거과정시에_업데이트_전의_데이터가_없는_경우()
        {
            //Arrange
            MockRepository mocks       = new MockRepository();
            UserInfo       stubData    = mocks.Stub <UserInfo>();
            UserInfo       stubPreData = null;

            stubData.id       = "id";
            stubData.password = "******";
            ICommandListener mockListener = mocks.DynamicMock <UserAuthController>();
            UpdateUserInfo   uui          = new UpdateUserInfo(stubData, mockListener);

            uui.preUserInfo = stubPreData;
            //Act
            uui.Undo();
        }
示例#19
0
        public object MstUserUpdateUserInfo(UpdateUserInfo updateUserInfo)
        {
            string token = Request.Headers.Authorization.ToString();
            int    valid = new ExceptionHandler().TokenCheck(token);

            if (valid == 0)
            {
                return("Token has expired");
            }
            if (valid == -1)
            {
                return("Token has invalid signature");
            }
            int ret = repository.MstUserUpdateUserInfo(pclsCache, updateUserInfo.UserId, updateUserInfo.Identify, updateUserInfo.PhoneNo, updateUserInfo.UserName, updateUserInfo.Role, updateUserInfo.TerminalIP, updateUserInfo.TerminalName, updateUserInfo.revUserId);

            return(new ExceptionHandler().SetData(Request, ret));
        }
示例#20
0
 public void execute_업데이트과정_정상적으로_거치는지_검증()
 {
     MockRepository mocks = new MockRepository();
     UserInfo stubData = mocks.Stub<UserInfo>();
     stubData.id = "id";
     stubData.password = "******";
     ICommandListener mockListener = mocks.DynamicMock<UserAuthController>();
     UpdateUserInfo uui = new UpdateUserInfo(stubData, mockListener);
     using (mocks.Record())
     {
         mockListener.Select(stubData);
         mockListener.Update(stubData,stubData);
         LastCall.Return(true);
     }
     uui.execute();
     mocks.Verify(mockListener);
 }
示例#21
0
        public IHttpActionResult UpdateProfile([FromBody] UpdateUserInfo model)
        {
            var user = DB.Users.Find(UserId);

            if (user == null)
            {
                return(NotFound());
            }

            ObjectMapper.CopyPropertiesTo(model, user, ObjectMapper.UpdateFlag.DeferUpdateOnNull, new string[] {
                nameof(user.Username),
                nameof(user.FullName)
            });

            DB.SaveChanges();
            return(Empty());
        }
示例#22
0
        // GET: /Manage/ChangeUserName
        public ActionResult ChangeUserInfo()
        {
            var model = new UpdateUserInfo();
            //var userId = User.Identity.GetUserId();
            //var currentUserId = User.Identity.GetUserId();
            var user = UserManager.FindById(User.Identity.GetUserId());

            if (user != null)
            {
                //var manager = new UserManager<MyUser>(new UserStore<MyUser>(new MyDbContext()));
                model.FirstName = user.FirstName;
                model.LastName  = user.LastName;
                model.Email     = user.Email;
            }
            ;
            return(View(model));
        }
示例#23
0
        public ActionResult ChangeUserInfo(UpdateUserInfo model)
        {
            var user = UserManager.FindById(User.Identity.GetUserId());

            if (!ModelState.IsValid)
            {
                return(View());
            }
            user.FirstName   = model.FirstName;
            user.LastName    = model.LastName;
            user.DisplayName = model.FirstName + " " + model.LastName;
            user.Email       = model.Email;

            //apply the chnages if any to the db
            UserManager.Update(user);

            return(RedirectToAction("Index", new { message = ManageMessageId.ChangeInfoSuccess }));
        }
示例#24
0
        public async Task <IActionResult> UpdateUserInfo(
            [FromRoute] string userId,
            [FromBody] UpdateUserInfo viewModel)
        {
            try
            {
                await _userUseCases.UpdateUserInfo(userId, viewModel);

                return(Ok());
            }
            catch (ApplicationException e)
            {
                return(BadRequest(e.Message));
            }
            catch (NotFoundException e)
            {
                return(NotFound(e.Message));
            }
        }
示例#25
0
        public void execute_업데이트과정_정상적으로_거치는지_검증()
        {
            MockRepository mocks    = new MockRepository();
            UserInfo       stubData = mocks.Stub <UserInfo>();

            stubData.id       = "id";
            stubData.password = "******";
            ICommandListener mockListener = mocks.DynamicMock <UserAuthController>();
            UpdateUserInfo   uui          = new UpdateUserInfo(stubData, mockListener);

            using (mocks.Record())
            {
                mockListener.Select(stubData);
                mockListener.Update(stubData, stubData);
                LastCall.Return(true);
            }
            uui.execute();
            mocks.Verify(mockListener);
        }
示例#26
0
        public async Task UpdateUser_WithValidPassword_ReturnsOK()
        {
            using (var client = _factory.CreateClient())
            {
                // Arrange
                CreateUser user = new CreateUser()
                {
                    FirstName = "Test",
                    LastName  = "User",
                    Email     = "*****@*****.**",
                    Password  = "******"
                };
                UpdateUserInfo updateUserInfo = new UpdateUserInfo();

                var requestContent = new StringContent(
                    JsonConvert.SerializeObject(user),
                    Encoding.UTF8, "application/json");

                // Act
                HttpResponseMessage createUserResponse = await client.PutAsync("api/user", requestContent);

                string createdUserSerialized = await createUserResponse.Content.ReadAsStringAsync();

                User createdUser = JsonConvert.DeserializeObject <User>(createdUserSerialized);

                updateUserInfo.FirstName       = "New User Name";
                updateUserInfo.LastName        = "New User Last Name";
                updateUserInfo.CurrentPassword = "******";
                updateUserInfo.NewPassword     = "******";
                updateUserInfo.UserId          = createdUser.Id;


                var updateUserContent = new StringContent(
                    JsonConvert.SerializeObject(updateUserInfo),
                    Encoding.UTF8, "application/json");

                HttpResponseMessage updateUserResponse = await client.PostAsync("api/user", updateUserContent);

                // Assert
                updateUserResponse.StatusCode.Should().Be(HttpStatusCode.OK);
            }
        }
示例#27
0
        private void btnSaveInfo_Click(object sender, RoutedEventArgs e)
        {
            if (this.txtUserLastName.Text.Length > 0 &&
                this.txtUserEmail.Text.Length > 0 &&
                this.txtUserName.Text.Length > 0 &&
                this.txtUserPhone.Text.Length > 0)
            {
                var uui = new UpdateUserInfo(new DbOperations());

                this._user.Info.Name        = this.txtUserName.Text;
                this._user.Info.LastName    = this.txtUserLastName.Text;
                this._user.Info.EMail       = this.txtUserEmail.Text;
                this._user.Info.PhoneNumber = this.txtUserPhone.Text;

                var result = uui.UpdateUser(this._user);
                MessageBox("SAVE USER INFO", result ? "SUCCESS" : "COULD NOT SAVED");
            }
            else
            {
                MessageBox("SAVE USER INFO", "FILL EMPTY BLOCKS");
            }
        }
示例#28
0
        //public String UpdateActivationEmailAlert(Int32 id)
        //{
        //    String msg = "";
        //    SqlCommand cmd = new SqlCommand();
        //    try
        //    {
        //        cmd.CommandText = "DECLARE @activation int=0;SELECT @activation=ISNULL(ActivationEmailAlert,0) FROM MppUser where MppUserID=@id;Update MppUser set ActivationEmailAlert=@activation+1,ModifiedOn=GETDATE() where MppUserID=@id;";
        //        cmd.CommandType = CommandType.Text;
        //        cmd.Parameters.Add("@id", SqlDbType.VarChar).Value = id; ;
        //        DataAccess.ExecuteCommand(cmd);
        //    }
        //    catch (SqlException ex)
        //    {
        //        msg = ex.Message;
        //    }
        //    catch (Exception ex)
        //    {
        //        msg = ex.Message;
        //    }
        //    finally
        //    {
        //        if (cmd != null)
        //        {
        //            cmd.Dispose();
        //        }
        //    }
        //    return msg;
        //}

        /// <summary>
        /// method to update customer details to our database for future use
        /// </summary>
        /// <param name="custId"></param>
        /// <param name="cardId"></param>
        /// <param name="userid"></param>
        public static String UpdateStripeData(UpdateUserInfo obj)
        {
            String     msg = "";
            SqlCommand cmd = new SqlCommand();

            try
            {
                var timeZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
                cmd.CommandText = "Sbsp_AddUserStripeIds";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@userid", SqlDbType.Int).Value        = obj.UserId;
                cmd.Parameters.Add("@cust_id", SqlDbType.VarChar, 500).Value       = obj.CustId;
                cmd.Parameters.Add("@card_id", SqlDbType.VarChar, 500).Value       = obj.CardId;
                cmd.Parameters.Add("@planId", SqlDbType.Int).Value                 = obj.PlanId;
                cmd.Parameters.AddWithValue("@amount", SqlDbType.Decimal).Value    = Convert.ToDecimal(obj.Amount);
                cmd.Parameters.Add("@StartDate", SqlDbType.SmallDateTime).Value    = TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(obj.PlanStartDate), timeZone);
                cmd.Parameters.Add("@EndDate", SqlDbType.SmallDateTime).Value      = TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(obj.PlanEndDate).AddDays(-1), timeZone);
                cmd.Parameters.Add("@TrialEndDate", SqlDbType.SmallDateTime).Value = obj.TrialEndDate == "" ? Convert.ToDateTime("1970-01-01 00:00:00") : TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(obj.TrialEndDate).AddDays(-1), timeZone);
                DataAccess.ExecuteCommand(cmd);
            }
            catch (SqlException ex)
            {
                msg = ex.Message;
                LogFile.WriteLog("Update StripeData : " + msg, SessionData.SellerName);
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                LogFile.WriteLog("Update StripeData : " + msg, SessionData.SellerName);
            }
            finally
            {
                if (cmd != null)
                {
                    cmd.Dispose();
                }
            }
            return(msg);
        }
示例#29
0
        public async Task <Result> UpdateUserAsync(string userId, UpdateUserInfo updateUser)
        {
            FilterDefinitionBuilder <BsonDocument> builder = Builders <BsonDocument> .Filter;
            FilterDefinition <BsonDocument>        filter  = builder.Eq("_id", userId);
            bool result = await service.UpdateUserAsync(filter, updateUser);

            if (result)
            {
                return new Result
                       {
                           status = Status.OK,
                           data   = result
                       }
            }
            ;
            else
            {
                return new Result
                       {
                           status = Status.BadRequest,
                           data   = Messages.BadRequest
                       }
            };
        }
示例#30
0
        //Billing
        public ActionResult CreateStripeCustomer(string token)
        {
            var          email           = Session["Email"].ToString();
            var          subscription    = new StripeSubscription();
            var          customerDetails = new StripeCustomer();
            var          userInfo        = new UpdateUserInfo();
            string       msg             = "";
            var          cardStatus      = 0;
            DataTable    userData;
            StripeCharge charge = null;

            try
            {
                if (token != null)
                {
                    var ds = new AccountData().ValidateEmailAndGetUserinfo(email);
                    userData = ds.Tables[0];
                    var custID = Convert.ToString(userData.Rows[0]["stp_custId"]);
                    if (userData.Rows.Count > 0 && !string.IsNullOrWhiteSpace(custID))                                 //update
                    {
                        var customerUpdateOptions = new StripeCustomerUpdateOptions
                        {
                            Email       = email,
                            Description = Session["FirstName"] + " " + Session["LastName"],
                            SourceToken = token
                        };

                        //updated customer
                        customerDetails = StripeHelper.UpdateCustomer(custID, customerUpdateOptions);

                        //add a test charge for $1
                        var makeTestCharge = new StripeChargeCreateOptions
                        {
                            CustomerId  = customerDetails.Id,
                            Amount      = 100,
                            Currency    = "usd",
                            Description = "Card verification charge",
                            SourceTokenOrExistingSourceId = customerDetails.DefaultSourceId
                        };
                        charge = StripeHelper.MakePayment(makeTestCharge);
                        if (charge != null)
                        {
                            var refund = StripeHelper.RefundCharge(charge.Id);
                            cardStatus      = 1;
                            userInfo.CustId = customerDetails.Id;
                            userInfo.CardId = customerDetails.DefaultSourceId;
                            userInfo.UserId = Convert.ToInt32(Session["UserID"]);
                            AccountData.UpdateStripeCardData(userInfo);
                            if ((SessionData.PlanID == 1 && SessionData.TrialEndOn < DateTime.Now) || SessionData.PlanStatus == 0) //When trail was expired || Unsubscribed and adding a card since payments are not succesfull
                            {
                                msg = StripeServices.SubscribePlan(SessionData.StripeCustId, userInfo.CardId);
                            }
                            if (String.IsNullOrWhiteSpace(msg))
                            {
                                SessionData.PlanStatus   = 1; //Default subscription
                                SessionData.StripeCustId = customerDetails.Id;
                                SessionData.StripeCardId = customerDetails.DefaultSourceId;
                            }
                        }
                        else
                        {
                            StripeHelper.DeleteCard(customerDetails.DefaultSourceId, custID);
                            cardStatus = 0;
                        }
                    }
                    customerDetails = StripeHelper.GetStripeCustomer(customerDetails.Id);
                }

                var respo = new { Status = cardStatus, Message = msg, CustomerDetails = customerDetails };
                return(Json(respo, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                LogFile.WriteLog("CreateCustomer - " + ex.Message.ToString());
                return(Json(null, JsonRequestBehavior.AllowGet));
            }
        }
示例#31
0
        /// <summary>
        /// 更新使用者資料
        /// </summary>
        /// <param name="data"> 封包資料 </param>
        /// <returns> 結果 </returns>
        public string OnUpdateUserInfo(string data)
        {
            string ret = "";

            UpdateUserInfo packet = JsonConvert.DeserializeObject <UpdateUserInfo>(data);

            UpdateUserInfoResult rData = new UpdateUserInfoResult();

            UserInfo userInfo = null;

            try
            {
                userInfo = GetSql().Queryable <UserInfo>().With(SqlSugar.SqlWith.RowLock).Where(it => it.MemberID == packet.MemberID).Single();

                // 有找到資料
                if (userInfo != null)
                {
                    userInfo.NickName           = packet.UpdateData.NickName == null ? userInfo.NickName : packet.UpdateData.NickName;
                    userInfo.Birthday           = packet.UpdateData.Birthday == null ? userInfo.Birthday : packet.UpdateData.Birthday;
                    userInfo.BodyHeight         = packet.UpdateData.BodyHeight == 0 ? userInfo.BodyHeight : packet.UpdateData.BodyHeight;
                    userInfo.BodyWeight         = packet.UpdateData.BodyWeight == 0 ? userInfo.BodyWeight : packet.UpdateData.BodyWeight;
                    userInfo.FrontCover         = packet.UpdateData.FrontCover == null ? userInfo.FrontCover : packet.UpdateData.FrontCover;
                    userInfo.Avatar             = packet.UpdateData.Avatar == null ? userInfo.Avatar : packet.UpdateData.Avatar;
                    userInfo.Photo              = packet.UpdateData.Photo == null ? userInfo.Photo : packet.UpdateData.Photo;
                    userInfo.Mobile             = packet.UpdateData.Mobile == null ? userInfo.Mobile : packet.UpdateData.Mobile;
                    userInfo.Gender             = packet.UpdateData.Gender == 0 ? userInfo.Gender : packet.UpdateData.Gender;
                    userInfo.County             = packet.UpdateData.Country == 0 ? userInfo.County : packet.UpdateData.Country;
                    userInfo.SpecificationModel = packet.UpdateData.SpecificationModel == null ? userInfo.SpecificationModel : packet.UpdateData.SpecificationModel;

                    // 設定DB 交易的起始點
                    GetSql().BeginTran();

                    if (GetSql().Updateable <UserInfo>(userInfo).With(SqlSugar.SqlWith.RowLock).Where(it => it.MemberID == packet.MemberID).ExecuteCommand() > 0)
                    {
                        rData.Result = (int)UpdateUserInfoResult.ResultDefine.emResult_Success;

                        SaveLog($"[Info] MessageFcunction::OnUpdateUserInfo Update User: {packet.MemberID} Info Success");
                    }
                    else
                    {
                        rData.Result = (int)UpdateUserInfoResult.ResultDefine.emResult_Fail;

                        SaveLog($"[Info] MessageFcunction::OnUpdateUserInfo Update User: {packet.MemberID} Info Fail");
                    }
                }
                else
                {
                    rData.Result = (int)UpdateUserInfoResult.ResultDefine.emResult_Fail;

                    SaveLog($"[Info] MessageFcunction::OnUpdateUserInfo Can Not Find User: {packet.MemberID}");
                }
            }
            catch (Exception ex)
            {
                SaveLog($"[Error] MessageFcunction::OnUpdateUserInfo Catch Error, Msg: {ex.Message}");

                rData.Result = (int)UpdateUserInfoResult.ResultDefine.emResult_Fail;
            }

            if (rData.Result == (int)UpdateUserInfoResult.ResultDefine.emResult_Success)
            {
                GetRedis((int)Connect.RedisDB.emRedisDB_User).HashSet($"UserInfo_" + userInfo.MemberID, hashTransfer.TransToHashEntryArray(userInfo));

                // DB 交易提交
                GetSql().CommitTran();
            }
            else
            {
                // DB 交易失敗, 啟動Rollback
                GetSql().RollbackTran();
            }

            JObject jsMain = new JObject();

            jsMain.Add("CmdID", (int)S2C_CmdID.emUpdateUserInfoResult);
            jsMain.Add("Data", JsonConvert.DeserializeObject <JObject>(JsonConvert.SerializeObject(rData)));

            ret = jsMain.ToString();

            return(ret);
        }
示例#32
0
 public static IEndpoint Update(UpdateUserInfo userInfo) => new ApiEndpoint(BaseUri, HttpMethod.Put, userInfo);