public Post_When_Existing_Should()
            {
                dateTimeCreatorMock = new Mock <IDateTimeCreator>();
                expected            = new ActivationCodeToAdd
                {
                    PhoneNumber    = "07930123456",
                    ActivationCode = "BAC132"
                };
                var existing = new ActivationCode
                {
                    Id          = 101,
                    PhoneNumber = "07930123456",
                    Code        = "ABC0405"
                };
                var expectedDateTime = new DateTime(2001, 5, 4);

                dataStoreMock = new Mock <IDataStore>();
                dataStoreMock.Setup(x => x.GetActivationCode(expected.PhoneNumber))
                .Returns(existing);
                dataStoreMock.Setup(x => x.UpdateActivationCode(
                                        It.Is <ActivationCode>(y => y.Id == existing.Id &&
                                                               y.PhoneNumber == expected.PhoneNumber &&
                                                               y.Code == expected.ActivationCode &&
                                                               y.UpdatedAt == expectedDateTime)))
                .Returns(true);
                dateTimeCreatorMock.Setup(x => x.Create())
                .Returns(expectedDateTime);
                loggerMock = new Mock <ILogger <ActivationCodesController> >();

                sut = new ActivationCodesController(loggerMock.Object, dataStoreMock.Object, dateTimeCreatorMock.Object);
            }
Пример #2
0
        // Update the database on item sold on checkout
        public IActionResult Index()
        {
            string sessionId = HttpContext.Session.GetString("SessionId");

            //int orderid = Convert.ToInt32(str_orderid);

            if (sessionId == null)
            {
                // Use session storage here if not logged in //
                return(RedirectToAction("Index", "Login", new { FromCheckout = "true" }));
            }
            int userId = db.Sessions.FirstOrDefault(x => x.SessionId == sessionId).UserId;

            Session user = db.Sessions.FirstOrDefault(x => x.SessionId == sessionId);

            ViewData["User"] = user;

            // Stop the user from submitting an empty shopping cart
            Order exist = db.Orders.FirstOrDefault(x => x.UserId == userId && x.IsPaid == false);

            if (exist == null)
            {
                return(RedirectToAction("Index", "ShoppingCart"));
            }
            int int_orderid = exist.Id;

            Order order = db.Orders.FirstOrDefault(x => x.UserId == userId && x.Id == int_orderid && x.IsPaid == false);

            order.IsPaid       = true;
            order.CheckOutDate = DateTime.Now.ToString();
            db.SaveChanges();

            // Get the List Cart items of that orderId
            List <Cart> paidItems = db.Cart.Where(x => x.Order.Id == int_orderid).ToList();

            // Mark the activation code as sold and record it as sold to which orderId to display it for the customer later
            foreach (Cart item in paidItems)
            {
                for (int i = 0; i < item.Quantity; i++)
                {
                    ActivationCode activationCode =
                        db.ActivationCode.FirstOrDefault(x => x.ProductId == item.ProductId && x.IsSold == false);

                    // error is product is already sold

                    activationCode.IsSold  = true;
                    activationCode.OrderId = int_orderid;
                    db.SaveChanges();
                }
            }

            order = db.Orders.FirstOrDefault(x => x.UserId == userId);
            if (order.IsPaid)
            {
                Debug.WriteLine("paid");
            }
            ViewData["SessionId"] = sessionId;

            return(View());
        }
Пример #3
0
        public async Task ActivateCodeAsync(string code)
        {
            try
            {
                FilterBase codeFilter = new EqualityFilter <string>(typeof(ActivationCode)
                                                                    .GetBsonPropertyName("Code"), code);
                FilterBase usedFilter = new EqualityFilter <bool>(typeof(ActivationCode)
                                                                  .GetBsonPropertyName("Used"), false);

                await database.Connect().ConfigureAwait(false);

                ActivationCode activationCode = (await database.Get(codeFilter & usedFilter)
                                                 .ConfigureAwait(false)).FirstOrDefault();

                if (activationCode == null)
                {
                    throw new DatabaseException("Such a code does not exist");
                }

                activationCode.Used      = true;
                activationCode.UsageDate = DateTime.UtcNow;

                await database.Update(activationCode, new[] { "Used", "UsageDate" }).ConfigureAwait(false);
            }
            catch (Exception ex) when(ex.GetType() != typeof(DatabaseException))
            {
                exceptionLogger.Log(new ApplicationError(ex), LogLevel.Error, logConfiguration);
                throw new DatabaseException("THe error happened while activating the code");
            }
        }
        public async Task <OperationResult <string> > Handle(UserActivationcCodeRequestCommand request, CancellationToken cancellationToken)
        {
            var result = await unitOfWork.UsersRepository.GetUserByPhoneNumberAsync(request.PhoneNumber, cancellationToken);

            if (result.Result != null)
            {
                ActivationCode acCode = new ActivationCode(result.Result.Id, CodeTypes.PhoneConfirmed, Utility.Hash(result.Result.Username));
                var            gerateActivationCode = await unitOfWork.UsersRepository.ActivationCodeRepository.AddAsync(acCode, cancellationToken);

                if (gerateActivationCode.Success)
                {
                    var registerSetting = await unitOfWork.SettingRepository.Get <RegisterUserSetting>(SettingEnum.RegisterUserSetting.EnumToString(), cancellationToken);

                    if (registerSetting.Success)
                    {
                        SendNotif sendNotif = sendNotifs.Where(x => x.SendCodeType == registerSetting.Result.SendCodeVerifications)
                                              .FirstOrDefault();
                        var sendCode = await sendNotif.SendCodeAsync(gerateActivationCode.Result.Item2.ToString(), request.PhoneNumber, cancellationToken);

                        if (sendCode.Success)
                        {
                            /// Save to Database
                            await unitOfWork.CommitSaveChangeAsync();

                            return(OperationResult <string> .BuildSuccessResult(gerateActivationCode.Result.Item1));
                        }
                        return(OperationResult <string> .BuildFailure(sendCode.ErrorMessage));
                    }
                    return(OperationResult <string> .BuildFailure(registerSetting.ErrorMessage));
                }
                return(OperationResult <string> .BuildFailure(gerateActivationCode.ErrorMessage));
            }
            return(OperationResult <string> .BuildFailure("User Not found"));
        }
        public HttpResponseMessage AddUserToGroupByCode(string code, string userId)
        {
            ActivationCode codeInfo = codeRepository.GetGroupByCode(code);

            if (codeInfo == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Koden hittades inte. Försök igen."));
            }

            int group = codeInfo.GroupId;

            if (codeInfo.Activated == true)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Kod: " + code + " är redan aktiverad."));
            }

            else
            {
                Group           groupID = groupRepository.GetById(group);
                ApplicationUser user    = userRepository.GetByIdUser(userId);

                user.Group.Add(groupID);
                groupID.Users.Add(user);
                codeInfo.Activated = true;
                dataContext.SaveChanges();

                return(Request.CreateResponse(HttpStatusCode.OK, "Du är nu inlagd i din introduktionsgrupp."));
            }
        }
        public ActivationCodeModel GenerateCode(int userId, string reason)
        {
            _unitOfWork.ActivationCodeRepository.Delete(x => x.UserId == userId && x.Reason == reason);
            _unitOfWork.Save();
            string   code     = RandomString(6);
            DateTime issuedOn = BusinessSettings.ServerNow;

            DateTime expiredOn      = BusinessSettings.ServerNow.AddDays(1);
            var      activationCode = new ActivationCode
            {
                UserId    = userId,
                Code      = code,
                IssuedOn  = issuedOn,
                ExpiresOn = expiredOn,
                Reason    = reason
            };

            Mapper.CreateMap <User, UserModel>();
            var userModel = Mapper.Map <User, UserModel>(_unitOfWork.UserRepository.FindSingleBy(u => u.Id == userId));

            _unitOfWork.ActivationCodeRepository.Add(activationCode);
            _unitOfWork.Save();
            var activatopnCodeModel = new ActivationCodeModel()
            {
                UserId    = userId,
                IssuedOn  = issuedOn,
                Code      = code,
                ExpiresOn = expiredOn,
                Reason    = reason,
                User      = userModel
            };

            return(activatopnCodeModel);
        }
Пример #7
0
        public async Task <OperationResult <string> > Handle(CreateUserCommand request, CancellationToken cancellationToken)
        {
            string fileName = null;

            if (request.Photo != null)
            {
                var uploadFile = await UploadUtiltie.UploadInCustomePath(request.Photo, ".png", request.Username, UploadFolderPath.PathUserUploadFolder(), UploadFolderPath.PathAvatarUserUploadFolder());

                fileName = uploadFile.Result;
            }
            /// Register User
            var user    = new User(request.Username, request.Password, request.Name, request.Family, request.PhoneNumber, request.Email, fileName);
            var addUser = await unitOfWork.UsersRepository.AddAsync(user, cancellationToken);

            if (addUser.Success)
            {
                try
                {
                    var registerSetting = await unitOfWork.SettingRepository.Get <RegisterUserSetting>(SettingEnum.RegisterUserSetting.EnumToString(), cancellationToken);

                    if (registerSetting.Result != null)
                    {
                        /// Add User  Role
                        var addUserRole = await mediator.Send(new CreateUserRoleCommand(registerSetting.Result.RegisterRoleByAdmin, user.Id));

                        if (addUserRole.Success)
                        {
                            /// Add User Generation Code
                            ActivationCode acCode = new ActivationCode(user.Id, CodeTypes.PhoneConfirmed, Utility.Hash(user.Username));
                            var            gerateActivationCode = await unitOfWork.UsersRepository.ActivationCodeRepository.AddAsync(acCode, cancellationToken);

                            if (gerateActivationCode.Success)
                            {
                                /// Send Registration Code
                                SendNotif sendNotif = sendNotifs.Where(x => x.SendCodeType == registerSetting.Result.SendCodeVerifications)
                                                      .FirstOrDefault();
                                var sendCode = await sendNotif.SendCodeAsync(gerateActivationCode.Result.Item2.ToString(), user.PhoneNumber, cancellationToken);

                                if (sendCode.Success)
                                {
                                    /// Save to Database
                                    await unitOfWork.CommitSaveChangeAsync();

                                    return(OperationResult <string> .BuildSuccessResult(gerateActivationCode.Result.Item1));
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    return(OperationResult <string> .BuildFailure(ex.Message));
                }
            }
            return(OperationResult <string> .BuildFailure(addUser.ErrorMessage));
        }
Пример #8
0
        public ActivateViewModel PostActivate(ActivateInputViewModel input)
        {
            try
            {
                string tokenId        = input.TokenId;
                string activationCode = input.ActivationCode;
                string deviceId       = input.DeviceId;
                string deviceModel    = input.DeviceModel;
                string osType         = input.OsType;
                string osVersion      = input.OsVersion;


                ActivateViewModel activate = new ActivateViewModel();
                Status            status   = new Status();
                ActivateResult    result   = new ActivateResult();

                ActivationCode activation = IsValidActivationCode(tokenId, activationCode);
                if (activation != null)
                {
                    User user = ActivateUser(tokenId, activationCode);
                    UpdateActivationCode(activation, deviceId, deviceModel, osType, osVersion);
                    UnitOfWork.Save();

                    status.IsSuccess  = true;
                    status.Message    = Resources.Messages.Register_SuccessActivate;
                    status.StatusCode = 0;

                    LoginResultViewModel login = Login(user.CellNum, user.Password);
                    if (login.IsSuccess)
                    {
                        UpdateUserWithToken(user, login.Token);
                        result.TokenId = login.Token;
                        UnitOfWork.Save();
                    }
                }
                else
                {
                    status.IsSuccess  = false;
                    status.Message    = Resources.Messages.Registe_WrongActivationCode;
                    status.StatusCode = 2;
                }

                activate.Result = result;
                activate.Status = status;
                return(activate);
            }
            catch (Exception e)
            {
                return(new ActivateViewModel()
                {
                    Result = null,
                    Status = status.ReturnStatus(100, "خطا در بازیابی اطلاعات", false)
                });
            }
        }
Пример #9
0
        public void ApproveUser(ATAEntities context, string userName, MemberRoles newMemberRole)
        {
            Member         memberToBeApproved = context.Members.Where(x => x.UserName.Equals(userName)).FirstOrDefault();
            ActivationCode ac = GenerateNewActivationCode();

            memberToBeApproved.ActivationCodes.Add(ac);
            memberToBeApproved.UserMemberRole = newMemberRole;
            memberToBeApproved.StatusId       = (int)Statuses.PendingActivation;
            SendActivationEmail(memberToBeApproved);
            context.SaveChanges();
        }
Пример #10
0
 public OperationResult <int> Remove(ActivationCode activation)
 {
     try
     {
         ActivationCodes.Remove(activation);
         return(OperationResult <int> .BuildSuccessResult(1));
     }
     catch (Exception ex)
     {
         return(OperationResult <int> .BuildFailure(ex.Message));
     }
 }
        public void addPurchaseDataToDb(List <ProductDetails> proList, string username, string gameusername)
        {
            User user = new User();

            user = findUserIdbyUserName(username);



            //add transactin data to transaction db
            Transaction transaction = new Transaction()
            {
                Id                = Guid.NewGuid().ToString(),
                UserId            = user.OldId,
                UtcTimestamp      = DateTime.UtcNow,
                TransactionDetail = new List <TransactionDetail>()
            };

            //add transactiondetail data to db
            foreach (ProductDetails pd in proList)
            {
                TransactionDetail transactionDetail = new TransactionDetail()
                {
                    Id            = Guid.NewGuid().ToString(),
                    TransactionId = transaction.Id,
                    ProductId     = pd.product.Id,
                    Quantity      = pd.Quantity,
                    Value         = pd.product.Value * pd.Quantity,
                    Amount        = pd.product.Price * pd.Quantity
                };

                if (transactionDetail.Value > 0)
                {
                    transactionDetail.GameUsername = gameusername;
                }

                //add activation code data to db
                for (int j = 0; j < transactionDetail.Quantity; j++)
                {
                    ActivationCode activationCode = new ActivationCode()
                    {
                        Id = Guid.NewGuid().ToString(),
                        TransactionDetailId = transactionDetail.Id
                    };
                    _dbContext.ActivationCodes.Add(activationCode);
                }
                _dbContext.TransactionDetails.Add(transactionDetail);

                transaction.TransactionDetail.Add(transactionDetail);
            }

            _dbContext.Transactions.Add(transaction);
            _dbContext.SaveChanges();
        }
 public async Task <bool> CanRegister(string ActivactionCode)
 {
     return(await Task.Run(() =>
     {
         ActivationCode act = _ctx.ActivationCodes.FirstOrDefault(e => (e.ActivactionCode == ActivactionCode));
         if (act == null || act.ExpiredDate < DateTime.Now)
         {
             return false;
         }
         return true;
     }));
 }
 public async Task <ActivationCode> TryRegisterAsync(ActivationCode act)
 {
     return(await Task.Run(() =>
     {
         ActivationCode rec = _ctx.ActivationCodes.FirstOrDefault(e => (e.Mobile == act.Mobile) || (e.MedicoCode == act.MedicoCode));
         if (rec == null)
         {
             _ctx.ActivationCodes.Add(act);
             _ctx.SaveChanges();
         }
         return rec;
     }));
 }
Пример #14
0
        public async Task Handle()
        {
            await userFriendsService.CreateUserFriendsRecord(user.ID).ConfigureAwait(false);

            ActivationCode activationCode = codesService.CreateActivationCode(user.ID);
            await codesService.InsertCodeInDatabaseAsync(activationCode).ConfigureAwait(false);

            await userMainFoldersService.CreateNewUserMainFolders(user.ID).ConfigureAwait(false);

            await documentDeskStateService.CreateDeskStateAsync(user.ID).ConfigureAwait(false);

            //await emailService.SendConfirmationEmailAsync(activationCode.Code, user.Email).ConfigureAwait(false);
        }
Пример #15
0
        public void SendActivationCode(User user)
        {
            //Generate activation code and send it to user
            string         activationCode = GenerateActivationCode();
            ActivationCode ac             = new ActivationCode();

            ac.activationCode = activationCode;
            ac.user_id        = user.Id;
            ac.createdDate    = DateTime.Now;

            _context.Entry(ac).State = EntityState.Added;
            _context.SaveChanges();
        }
Пример #16
0
        public async Task <OperationResult <Tuple <string, int> > > AddAsync(ActivationCode activation, CancellationToken cancellation)
        {
            try
            {
                var add = await ActivationCodes.AddAsync(activation, cancellation);

                return(OperationResult <Tuple <string, int> > .BuildSuccessResult(new Tuple <string, int>(activation.HashCode, activation.ActivateCode.Code)));
            }
            catch (Exception ex)
            {
                return(OperationResult <Tuple <string, int> > .BuildFailure(ex.Message));
            }
        }
Пример #17
0
        public ActionResult DoRegister(FATUser user, string valCode)
        {
            JsonResult result = new JsonResult();

            using (FATContainer dbContainer = new FATContainer())
            {
                valCode = valCode.Trim();
                ActivationCode existedCode = dbContainer.ActivationCode.FirstOrDefault(n => n.ActivateCode == valCode && n.CurrStatus == ConstDefine.ActivationCode_Status_Unused);
                if (existedCode == null)
                {
                    result.Data = "激活码不存在或者已被使用";
                    return(result);
                }
                existedCode.CurrStatus = ConstDefine.ActivationCode_Status_Used;

                FATUser existedUser = dbContainer.FATUser.FirstOrDefault(n => n.UserCode == user.UserCode && n.School == user.School);
                if (existedUser != null)
                {
                    result.Data = "用户登录名已存在";
                    return(result);
                }
                if ((user.Password.Length < 6) || (user.Password.Length > 15))
                {
                    result.Data = "密码必须在6-15位之间";
                    return(result);
                }
                user.UserCode = user.UserCode.Trim();
                if (string.IsNullOrEmpty(user.UserCode))
                {
                    result.Data = "登录名不能为空";
                    return(result);
                }
                FATUser newUser = dbContainer.FATUser.Create();
                newUser.UserCode    = user.UserCode;
                newUser.School      = user.School;
                newUser.UserName    = user.UserName;
                newUser.IsStudent   = 1;
                newUser.IsAdmin     = 0;
                newUser.IsTeacher   = 0;
                newUser.Password    = user.Password;
                newUser.CurrStatus  = ConstDefine.UserStatus_Valid;
                newUser.CreatedDate = DateTime.Now;
                dbContainer.FATUser.Add(newUser);

                dbContainer.SaveChanges();

                CurrentUser.UserLogin(newUser);
                result.Data = string.Empty;
                return(result);
            }
        }
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "v1/CreateActivationCodes")] HttpRequest req,
            ILogger log)
        {
            try{
                var conn       = System.Environment.GetEnvironmentVariable("MongoDBConnectionString");
                var client     = new MongoClient(conn);
                var dbName     = System.Environment.GetEnvironmentVariable("license_management_db");
                var database   = client.GetDatabase(dbName);
                var collection = database.GetCollection <ActivationCode>(
                    System.Environment.GetEnvironmentVariable("activation_codes_col")
                    );

                string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                dynamic data        = JsonConvert.DeserializeObject(requestBody);

                var product_code = ((string)data?.productcode).Trim();
                var product_name = ((string)data?.productname).Trim();
                var license_type = ((string)data?.licensetype).Trim();
                var quantity     = (int)data?.quantity;
                var lifetime     = (int)data?.lifetime;

                //Simple validation
                if (product_code == "" || product_name == "" || license_type == "" || quantity < 1 || lifetime < 0)
                {
                    throw new Exception("Parameters are not valid for operation.");
                }

                for (int i = 0; i < quantity; i++)
                {
                    var activationCode = new ActivationCode();
                    activationCode.GuidCode    = Guid.NewGuid().ToString();
                    activationCode.ProductCode = product_code;
                    activationCode.ProductName = product_name;
                    activationCode.LicenseType = license_type;
                    activationCode.LifeTime    = lifetime;

                    await collection.InsertOneAsync(activationCode);
                }

                BasicResponse response = new BasicResponse();
                response.Status  = "OK";
                response.Code    = "Success";
                response.Message = "Activation codes created succefully.";

                return(new OkObjectResult(response));
            }catch (Exception e)
            {
                return(new OkObjectResult(e.Message));
            }
        }
Пример #19
0
        public IActionResult Checkout()
        {
            //Get Cart
            string UserId = HttpContext.Session.GetString("UserId");
            var    user   = dbcontext.User.Find(UserId);

            if (user == null || UserId == "Anonymous")
            {
                TempData["Error"] = "Please Log In Before checking out";
                return(RedirectToAction("Login", "Home"));
            }
            else
            {
                Order myorder = new Order
                {
                    Id     = Guid.NewGuid().ToString(),
                    UserId = user.Id,
                    Time   = DateTime.Now
                };
                dbcontext.Add(myorder);
                var Cart = dbcontext.Cart.Where(x => x.UserId == UserId).FirstOrDefault();
                List <CartDetails> CartDetails = dbcontext.CartDetails.Where(x => x.CartId == Cart.Id).ToList();
                foreach (CartDetails detail in CartDetails)
                {
                    List <ActivationCode> codes    = detail.Product.ActivationCodes.ToList();
                    OrderDetails          newOrder = new OrderDetails
                    {
                        Id        = Guid.NewGuid().ToString(),
                        ProductId = detail.Product.Id,
                        OrderId   = myorder.Id,
                        Qty       = detail.Qty
                    };
                    dbcontext.Add(newOrder);
                    System.Diagnostics.Debug.WriteLine(detail.Qty.ToString());
                    for (var i = 0; i < detail.Qty; i++)
                    {
                        ActivationCode codeToUse = codes[i];
                        System.Diagnostics.Debug.WriteLine(codeToUse.Id);
                        codeToUse.OrderDetails   = newOrder;
                        codeToUse.OrderDetailsId = newOrder.Id;
                        codeToUse.ProductId      = null;
                        dbcontext.Update(codeToUse);
                    }
                    dbcontext.Remove(detail);
                    HttpContext.Session.SetString("cartItems", "0");
                }
                dbcontext.SaveChanges();
                return(RedirectToAction("Index", "OrderHistory"));
            }
        }
Пример #20
0
        public void UpdateActivationCode(ActivationCode activationCode, string deviceId, string deviceModel,
                                         string OsType, string OsVersion)
        {
            activationCode.IsUsed           = true;
            activationCode.UsingDate        = DateTime.Now;
            activationCode.IsActive         = false;
            activationCode.LastModifiedDate = DateTime.Now;
            activationCode.DeviceId         = deviceId;
            activationCode.DeviceModel      = deviceModel;
            activationCode.OsType           = OsType;
            activationCode.OsVersion        = OsVersion;

            UnitOfWork.ActivationCodeRepository.Update(activationCode);
        }
Пример #21
0
        //public List<Cart_Model> CartItems()
        //{
        //    List<Cart_Model> listofCartItems = (from c in db.Carts
        //                                        join prod in db.Products
        //                                        on c.ProductId equals prod.ProductId
        //                                        join prodtype in db.ProductTypes
        //                                        on prod.ProductTypeId equals prodtype.ProductTypeId
        //                                        where c.UserId == "U01"
        //                                        select new Cart_Model()
        //                                        {
        //                                            CartId = c.CartId,
        //                                            ProductId = c.ProductId,
        //                                            ProductQuantity = c.ProductQuantity,
        //                                            ProductName = prod.ProductName,
        //                                            ProductDescription = prod.ProductDescription,
        //                                            ProductPrice = prod.ProductPrice,
        //                                            ImageURL = prod.ImageURL,
        //                                            ProductTypeName = prodtype.ProductTypeName,
        //                                            subTotal = prod.ProductPrice * c.ProductQuantity
        //                                        }).ToList();
        //    return listofCartItems;
        //}
        //public string DeleteItems(string productId)
        //{
        //    Cart cart = db.Carts
        //                .Where(x => x.ProductId == productId
        //                )
        //                .FirstOrDefault();

        //    if (cart == null)
        //    { return "fail"; }

        //    db.Carts.Remove(cart);
        //    db.SaveChanges();

        //    return "success";
        //}

        public string AddtoOrder(string TotalAmt, string userId, List <UserCart> selectedproducts)
        {
            //need to get logged in userid
            // var userId = "U02";
            //List<Cart> cart = db.Carts.Where(x => x.UserId == ).ToList();

            //add to order from cart
            Order order = new Order()
            {
                OrderId    = Guid.NewGuid().ToString(),
                UserId     = userId,
                OrderDate  = DateTime.UtcNow,
                TotalPrice = Double.Parse(TotalAmt)
            };

            db.Orders.Add(order);
            db.SaveChanges();
            foreach (var item in selectedproducts)
            {
                //add to order details from cart
                OrderDetail orderDetail = new OrderDetail()
                {
                    OrderId   = order.OrderId,
                    ProductId = item.ProductId,
                    Quantity  = item.ProductQuantity
                };
                db.OrderDetails.Add(orderDetail);
                db.SaveChanges();

                //Create activation code
                for (int i = 0; i < item.ProductQuantity; i++)
                {
                    ActivationCode activationCode = new ActivationCode()
                    {
                        OrderId          = order.OrderId,
                        ProductId        = item.ProductId,
                        ActivationCodeId = Guid.NewGuid().ToString()
                    };
                    db.ActivationCodes.Add(activationCode);
                    db.SaveChanges();
                }
                //Remove from cart
                //db.Remove(item);
                //db.SaveChanges();
            }

            //db.Remove(cart);
            //db.SaveChanges();
            return("success");
        }
            public void AddActivationCode()
            {
                expectedActivationCode = new ActivationCode
                {
                    Code        = "ABC123",
                    PhoneNumber = "0123456789"
                };

                using (sut.BeginTransaction())
                    sut.InsertActivationCode(expectedActivationCode);

                var actual = sut.GetActivationCode(expectedActivationCode.PhoneNumber);

                actual.Should().BeEquivalentTo(expectedActivationCode, o => o.Excluding(x => x.CreatedAt));
            }
Пример #23
0
        /// <summary>
        /// Creates an activation code and sends this code to the user on the given email.
        /// </summary>
        /// <exception cref="DatabaseException">
        /// Throws this exception if the error occurs while working with the database service.
        /// This exception provides the meaningful description for the error, so this message
        /// can be returned to the user.
        /// </exception>
        public async Task Handle()
        {
            try
            {
                ActivationCode activationCode = codesService.CreateActivationCode(userID);
                //await codesService.InsertCodeInDatabaseAsync(activationCode).ConfigureAwait(false);

                //await emailService.SendConfirmationEmailAsync(activationCode.Code, email).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                exceptionLogger.Log(new ApplicationError(ex), LogLevel.Error, logConfiguration);
                throw new DatabaseException("The error occured while sending confirmation email");
            }
        }
Пример #24
0
        public void InsertActivationCode(ActivationCode activationCode)
        {
            var options = Options.Create(new Config
            {
                ConnectionString = connectionString
            });

            dataStore = new DataStore(options);

            output.WriteLine($"Inserting ActivationCode for PhoneNumber={activationCode.PhoneNumber}");

            using var tx = dataStore.BeginTransaction();
            dataStore.InsertActivationCode(activationCode);

            activationCodes.Add(activationCode);
        }
Пример #25
0
        /// <summary>Run the command</summary>
        public override int Run()
        {
            // If a file is given, load the data from it
            if (m_filepath.HasValue())
            {
                if (!Path_.FileExists(m_filepath))
                {
                    throw new Exception($"File '{m_filepath}' doesn't exist");
                }

                m_data = File.ReadAllText(m_filepath);
            }

            // If no data is available, error
            if (!m_data.HasValue())
            {
                throw new Exception("No data to generate key from");
            }

            // No private key?
            if (!m_pk.HasValue() || !Path_.FileExists(m_pk))
            {
                throw new Exception($"Private key '{m_pk}' doesn't exist");
            }

            var priv = File.ReadAllText(m_pk);
            var code = ActivationCode.Generate(m_data, priv);
            var key  = Convert.ToBase64String(code);

            // Save to the system clipboard
            if (m_outclip)
            {
                Clipboard.SetText(key);
            }

            // Save to a file
            if (m_outfile.HasValue())
            {
                key.ToFile(m_outfile);
            }

            // Write to StdOut
            Console.WriteLine(key);
            return(0);
        }
Пример #26
0
        public int CreateActivationCode(Guid userId)
        {
            DeactiveOtherActivationCode(userId);

            int            code           = RandomCode();
            ActivationCode activationCode = new ActivationCode();

            activationCode.UserId       = userId;
            activationCode.Code         = code;
            activationCode.ExpireDate   = DateTime.Now.AddDays(2);
            activationCode.IsUsed       = false;
            activationCode.IsActive     = true;
            activationCode.CreationDate = DateTime.Now;
            activationCode.IsDeleted    = false;

            UnitOfWork.ActivationCodeRepository.Insert(activationCode);
            return(code);
        }
Пример #27
0
        public ActivationCode IsValidActivationCode(string tokenId, string activationCode)
        {
            Guid userId = new Guid(tokenId);
            int  code   = Convert.ToInt32(activationCode);

            ActivationCode oActivationCode = UnitOfWork.ActivationCodeRepository
                                             .Get(current => current.UserId == userId && current.Code == code && current.IsUsed == false &&
                                                  current.IsActive == true && current.ExpireDate > DateTime.Now).FirstOrDefault();

            if (oActivationCode != null)
            {
                return(oActivationCode);
            }
            else
            {
                return(null);
            }
        }
Пример #28
0
        public void DeleteActivationCode(ActivationCode activationCode)
        {
            if (activationCode == null)
            {
                return;
            }

            var sql = "delete from ExternalMobileTelecomsNetwork.ActivationCodes where PhoneNumber=@PhoneNumber";

            var connection         = new SqlConnection(connectionString);
            var currentTransaction = new Transaction(connection);

            output.WriteLine(
                $"Deleting ExternalMobileTelecomsNetwork.ActivationCode with PhoneNumber={activationCode.PhoneNumber}");
            connection.Execute(sql, new { activationCode.PhoneNumber }, currentTransaction.Get());

            currentTransaction.Get().Commit();
        }
Пример #29
0
        [Test] public void ActivationCodeGen1()
        {
                        #if false // Todo: update for .Net standard 2.0
            // Generate a public and private key.
            // Save the public key in the app (in a resource file)
            // Save the private key somewhere safe, you need that to generate more code numbers for the app
            string pub, priv;
            Crypt.GenerateRSAKeyPair(out pub, out priv, 384);
            Assert.NotEqual(pub, priv);

            // This is the licence issuer
            var user_data = "Pauls Test Data";
            var key       = ActivationCode.Generate(user_data, priv);

            // This is the app, checking the licence
            var valid = ActivationCode.Validate(user_data, key, pub);
            Assert.True(valid);
                        #endif
        }
Пример #30
0
        /// <summary>
        /// Inserts the given activation code in the database.
        /// </summary
        /// <exception cref="DatabaseException">
        /// Fires when error happens while working with the database.
        /// </exception>
        public async Task InsertCodeInDatabaseAsync(ActivationCode activationCode)
        {
            try
            {
                await database.Connect().ConfigureAwait(false);

                IFilter filter = new EqualityFilter <ObjectId>(typeof(ActivationCode).GetBsonPropertyName("UserID"),
                                                               activationCode.ID);

                await database.Delete(filter).ConfigureAwait(false);

                await database.Insert(activationCode).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                exceptionLogger.Log(new ApplicationError(ex), LogLevel.Error, logConfiguration);
                throw new DatabaseException("The error happened inserting the activation code");
            }
        }