public async Task <ActionResult> Edit(int?id)
        {
            if (id.HasValue)
            {
                try
                {
                    var userFound = _userRepo.Get(id.Value);
                    var rolesList = UserIdentityManager.GetRoles();

                    await Task.WhenAll(userFound, rolesList);

                    if (userFound.Result == null)
                    {
                        return(HttpNotFound());
                    }

                    if (rolesList.Result == null)
                    {
                        return(HttpNotFound());
                    }

                    model.InputModel = userFound.Result;
                    model.rolesList  = rolesList.Result;
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError
                        (string.Empty, ex.Message);
                }
                return(View(model));
            }

            return(HttpNotFound());
        }
Пример #2
0
        public virtual JsonResult GetUsersListNoSelf(string filter)
        {
            var userList = UserIdentityManager.SearchUsersByNameOrFullName(new GetUserByPCmailOrNameRequest {
                Search = filter
            });
            UsersByNameOrFullNameResponse response = new UsersByNameOrFullNameResponse();

            if (userList != null)
            {
                response = userList.Users.UserIdentityModelToResponse();

                if (response != null && response.ListResponse != null)
                {
                    var currentUser = response.ListResponse
                                      .SingleOrDefault(o => o.Value.ToUpper() == IDBContext.Current.UserName.ToUpper());
                    response.ListResponse.Remove(currentUser);
                }
            }

            return(new JsonResult
            {
                Data = response,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
        }
        public async Task <ActionResult> Create(Customer inputModel)
        {
            model.inputModel = inputModel;

            if (ModelState.IsValid)
            {
                try
                {
                    var currentLoggedUserId  = User.Identity.GetUserId();
                    var currentLoggedUserRes = await UserIdentityManager
                                               .GetUserById(currentLoggedUserId);

                    inputModel.UserCreatorId = currentLoggedUserRes.registeredUser.ID;
                    inputModel.UserUpdatorId = currentLoggedUserRes.registeredUser.ID;
                    inputModel.DateCreated   = DateTime.Now;
                    inputModel.DateUpdated   = DateTime.Now;
                    inputModel.IsActive      = true;

                    await _customerRepo.Create(inputModel);

                    return(RedirectToAction("Index"));
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError(string.Empty, ex.Message);
                    return(View("Create", model));
                }
            }
            return(View("Create", model));
        }
Пример #4
0
        public ActionResult LoginUser(string name, string password)
        {
            // TODO: DDoS vulnerability. Throttling needs to be added here.

            if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(password))
            {
                return(this.Json(new { result = "error", message = StringResource.login_ErrorUserCredentials }));
            }

            UserIdentityManager.ResetUser(this.Request, this.Response);

            var user = this.repository.Login(name, password);

            if (user == null)
            {
                return(this.Json(new { result = "error", message = StringResource.login_ErrorUserCredentials }));
            }

            if (!user.IsActivated)
            {
                return(this.Json(new { result = "error", message = StringResource.login_ErrorUserNotActivated }));
            }

            UserIdentityManager.AddUserSession(this.Response, user);

            return(this.Json(new { result = "success" }));
        }
        private VerDocumentRowViewModel GetDocumentData(
            int instanceId, string documentNumber, string documentName, string docWebUrl, string documentNameTemp)
        {
            var requestInstance = new VmrInstanceRequest
            {
                InstanceId = instanceId
            };
            var vmrInstance = _vmrGenericService.GetInstance(requestInstance).Instance;
            var model       = new VerDocumentRowViewModel
            {
                SLno           = 0,
                DocumentType   = 0,
                DocumentName   = documentName,
                PackageVersion = vmrInstance.VerInstance.Version.GetNameLanguage(Localization.CurrentLanguage),
                LastUpdate     = DateTime.Now,
                UserName       = UserIdentityManager
                                 .SearchFullNameByUserName(new GetUsersRequest {
                    UserName = IDBContext.Current.UserName
                })
                                 .FullName,
                IsPrimary        = false,
                IsRequired       = false,
                DocumentNumber   = documentNumber,
                ShpUrlDocument   = docWebUrl,
                IsVer            = false,
                LastUpdateFormat = string.Format("{0:dd MMM yyyy}", DateTime.Now),
                DocumentNameTemp = documentNameTemp
            };

            return(model);
        }
Пример #6
0
        public async Task <ActionResult> Create(ViewingViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    if (model.ListingId == 0)
                    {
                        model = await GetDefaultViewModelEntry();

                        model.PickedListingPostalCode = "No Listing is Picked";
                        ModelState.AddModelError(string.Empty, "Please pick a Listing");

                        return(View(model));
                    }

                    var modelState      = ModelState;
                    var viewingToCreate = new Viewing();
                    viewingToCreate = await _viewingService
                                      .GetViewingFromViewModel(model);

                    if (await _viewingService.IsViewingValid
                            (viewingToCreate, ModelState))
                    {
                        var currentLoggedUserId  = User.Identity.GetUserId();
                        var currentLoggedUserRes = await UserIdentityManager
                                                   .GetUserById(currentLoggedUserId);

                        viewingToCreate.CreatedDate = DateTime.Now;
                        viewingToCreate.UpdatedDate = DateTime.Now;

                        viewingToCreate.UserCreatorId =
                            currentLoggedUserRes.registeredUser.ID;

                        viewingToCreate.UserUpdatorId =
                            currentLoggedUserRes.registeredUser.ID;

                        viewingToCreate.IsActive = true;

                        var result = await _viewingRepo.Create
                                         (viewingToCreate);

                        return(RedirectToAction("Index"));
                    }
                    else
                    {
                        model = await GetDefaultViewModelEntry();

                        return(View(model));
                    }
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError(string.Empty, ex.Message);
                }
            }

            return(View(model));
        }
Пример #7
0
        public virtual ActionResult GetParticipantsNewRow(
            string searchBy,
            int participantTypeId,
            int roleId,
            string userName,
            int organizationalUnitId,
            string email)
        {
            var modelParticipant = new VerParticipantRowViewModel();

            switch (searchBy)
            {
            case ModuleAccessLevelCode.ROLE:
                modelParticipant.ParticipantTypeId = participantTypeId;
                modelParticipant.Role     = roleId;
                modelParticipant.UserName = string.IsNullOrEmpty(userName)
                        ? _verPermissionsService
                                            .GetParticipantName(roleId, organizationalUnitId)
                                            .Participant.ParticipantsUserName
                        : userName;
                modelParticipant.FullName = string.IsNullOrEmpty(userName)
                        ? _verPermissionsService.GetParticipantName(roleId, organizationalUnitId)
                                            .Participant.ParticipantsFullName
                        : userName;
                modelParticipant.OrganizationalUnitId = organizationalUnitId == -1
                        ? (int?)null
                        : organizationalUnitId;
                modelParticipant.AccessLevelId = _catalogService
                                                 .GetConvergenceMasterDataIdByCode(
                    ModuleAccessLevelCode.ROLE, MasterType.MODULE_ACCESS_LEVEL).Id;
                modelParticipant.AccessLevelCode = searchBy;
                modelParticipant.Email           = string.IsNullOrEmpty(email) ? null : email;
                break;

            case ModuleAccessLevelCode.USER:
                modelParticipant.ParticipantTypeId = participantTypeId;
                modelParticipant.Role = roleId == -1 ? (int?)null : roleId;
                modelParticipant.OrganizationalUnitId = organizationalUnitId == -1
                        ? (int?)null
                        : organizationalUnitId;
                modelParticipant.UserName = userName;
                modelParticipant.FullName = UserIdentityManager
                                            .SearchFullNameByUserName(new GetUsersRequest {
                    UserName = userName
                })
                                            .FullName;
                modelParticipant.AccessLevelId = _catalogService
                                                 .GetConvergenceMasterDataIdByCode(
                    ModuleAccessLevelCode.USER, MasterType.MODULE_ACCESS_LEVEL).Id;
                modelParticipant.AccessLevelCode = searchBy;
                modelParticipant.Email           = string.IsNullOrEmpty(email) ? null : email;
                break;
            }

            _viewModelMapperHelper.GetParticipantList(true);
            return(PartialView("Partials/DataTables/TemplateRows/ParticipantsNewRow", modelParticipant));
        }
Пример #8
0
 protected virtual void Initialize(Guid pageId, PageIdentity pageIdentity = PageIdentity.Unknown, bool promoteProducts = true)
 {
     this.currentUser = this.HttpContext.CurrentUser() ?? UserIdentityManager.GetActiveUser(this.Request, this.repository);
     this.ViewData["SettingsViewModel"] = this.settingsViewModel;
     this.ViewData["MainMenuViewModel"] = MenuViewModelFactory.CreateDefaultMenu(this.repository, pageId, currentUser, pageIdentity);
     this.ViewData["ShowLeftRailLogin"] = currentUser == null;
     //this.ViewData["MediaListViewModel"] = promoteProducts ? CategoryViewModelFactory.CreatePopularProducts(this.repository, null) : null;
     this.ViewData["HttpReferrer"] = this.Request.UrlReferrer != null?this.Request.UrlReferrer.ToString() : null;
 }
Пример #9
0
        // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
        public async Task ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});

            UserIdentityManager.CreateDefaultRoles();
            UserIdentityManager.CreateAssociatedListingEntries();
            await UserIdentityManager.CreateDefaultEntryIfNotExist();
        }
        public async Task <ActionResult> Register()
        {
            var model = new RegisterViewModel
            {
                rolesList       = await UserIdentityManager.GetRoles(),
                registeringUser = new OperatingUser()
            };

            return(View(model));
        }
        public async Task <ActionResult> DeleteConfirmed(int id)
        {
            try
            {
                var userToDelete = await _userRepo.Get(id);

                var identityUser = await UserIdentityManager.
                                   GetUserFromModelId(userToDelete.ID);

                if (identityUser != null &&
                    userToDelete != null)
                {
                    userToDelete.RoleID = RoleNames.ARCHIVED;

                    var result = await UserIdentityManager.Changerole
                                     (identityUser, userToDelete.RoleID);

                    userToDelete.IsActive = false;
                    var res = await _userRepo.Delete(userToDelete);

                    if (res == 0)
                    {
                        var user = await _userRepo.Get(id);

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

                        model.InputModel = user;

                        ModelState.AddModelError
                            (string.Empty, "Agent can't be deleted.");

                        return(View("Delete", model));
                    }
                }
                else
                {
                    return(HttpNotFound());
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError
                    (string.Empty, ex.Message);

                var user = await _userRepo.Get(id);

                model.InputModel = user;

                return(View("Delete", model));
            }
            return(RedirectToAction("Index"));
        }
Пример #12
0
        public ActionResult Offers(char t = 'a', int o = 0, int c = 50)
        {
            var user = UserIdentityManager.GetActiveUser(this.Request, repository);

            this.ViewData["MainMenuViewModel"] = MenuViewModelFactory.CreateAdminMenu(repository, ControlPanelPage.Offers);
            this.ViewData["SettingsViewModel"] = this.settingsViewModel;

            this.ViewData["OffersHeaderViewModel"] = new TabControlViewModel
            {
                Tabs = offerStatusMap.Select(key => CreateOfferStatusHeader(key, t)).ToList()
            };

            bool showActive;

            if (!offerStatusMap.TryGetValue(t, out showActive))
            {
                showActive = true;
            }

            using (var context = new InstantStoreDataContext())
            {
                Func <Offer, bool> selector = showActive
                    ? (Func <Offer, bool>)((Offer offer) => offer.IsActive)
                    : (Func <Offer, bool>)((Offer offer) => !offer.IsActive);

                this.ViewData["OffersTableViewModel"] = new TableViewModel
                {
                    Header = new List <TableCellViewModel>
                    {
                        new TableCellViewModel(StringResource.offerTableHeaderName),
                        new TableCellViewModel(StringResource.offerTableHeaderThreshold),
                        new TableCellViewModel(StringResource.offerTableHeaderDiscount),
                        new TableCellViewModel(string.Empty)
                    },
                    Rows = context.Offers
                           .Where(selector)
                           .OrderByDescending(offer => offer.Name)
                           .Skip(o)
                           .Take(c)
                           .Select(ConvertOfferToTableRow)
                           .ToList(),
                    RowClickAction = new NavigationLink("Offer"),
                    Pagination     = new PaginationViewModel(c, o, context.Offers.Count(selector))
                    {
                        Link = new NavigationLink("Offers", "Admin")
                        {
                            Parameters = new { t = t }
                        }
                    }
                };
            }

            return(this.View());
        }
Пример #13
0
        public ActionResult Order(OrderDetailsViewModel orderViewModel)
        {
            var user = UserIdentityManager.GetActiveUser(this.Request, repository);

            if (user == null || !user.IsAdmin || orderViewModel == null)
            {
                return(this.HttpNotFound());
            }

            this.ViewData["MainMenuViewModel"] = MenuViewModelFactory.CreateAdminMenu(repository, ControlPanelPage.Orders);
            this.ViewData["SettingsViewModel"] = this.settingsViewModel;

            using (var context = new InstantStoreDataContext())
            {
                var order = context.Orders.FirstOrDefault(x => x.Id == orderViewModel.Id);
                if (order == null)
                {
                    return(this.HttpNotFound());
                }

                if (order.Comment != orderViewModel.Description ||
                    order.Status != (int)orderViewModel.Status)
                {
                    order.Comment = orderViewModel.Description;
                    if (order.Status != (int)orderViewModel.Status)
                    {
                        order.Status = (int)orderViewModel.Status;
                        context.OrderUpdates.InsertOnSubmit(new OrderUpdate
                        {
                            Status   = (int)orderViewModel.Status,
                            DateTime = DateTime.Now,
                            Id       = Guid.NewGuid(),
                            OrderId  = order.Id
                        });
                    }

                    var orderSubmitDate = order.OrderUpdates.FirstOrDefault(x => x.Status == (int)OrderStatus.Placed);

                    context.SubmitChanges();

                    EmailManager.Send(
                        order.User,
                        this.repository,
                        EmailType.EmailOrderHasBeenUpdated,
                        new Dictionary <string, string> {
                        { "%order.id%", order.Id.ToString() },
                        { "%order.user%", order.User.Name },
                        { "%order.date%", orderSubmitDate != null ? orderSubmitDate.DateTime.ToString("F", russianCulture) : string.Empty }
                    });
                }
            }

            return(this.RedirectToAction("Orders"));
        }
Пример #14
0
        public virtual JsonResult GetUsersList(string filter)
        {
            var response = UserIdentityManager.SearchUsersByNameOrFullName(new GetUserByPCmailOrNameRequest {
                Search = filter
            });

            return(new JsonResult
            {
                Data = SearchUserByNameOrFullNameList(response),
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
        }
Пример #15
0
        private VerDocumentRowViewModel GetNewDocumentData(
            int instanceId, string documentNumber, string documentName, string docWebUrl, string docNameTemp, bool isGenerated)
        {
            var model           = new VerDocumentRowViewModel();
            var instanceRequest = new VerInstanceRequest
            {
                InstanceId = instanceId
            };

            var instanceResponse = _verGenericService.GetInstance(instanceRequest);

            if (instanceResponse.IsValid)
            {
                var loadSecurityRequest = new VerLoadSecurityRequest
                {
                    Instance = instanceResponse.Instance,
                    Pages    = VerSecurityValues.SECURITY_VER_DOCUMENT_PAGE
                };

                var security = _verGenericService.LoadSecurity(loadSecurityRequest);

                _viewModelMapperHelper.SecurityDocument(security.SecurityList.ToList());

                model = new VerDocumentRowViewModel
                {
                    SLno         = 0,
                    DocumentType = _catalogService.GetConvergenceMasterDataIdByCode(
                        VerDocumentTypeCode.OTHER, MasterType.VER_DOCUMENT_TYPE).Id,
                    DocumentName   = documentName,
                    PackageVersion = instanceResponse.Instance.Version.GetNameLanguage(Localization.CurrentLanguage),
                    LastUpdate     = DateTime.Now,
                    UserName       = UserIdentityManager
                                     .SearchFullNameByUserName(new GetUsersRequest {
                        UserName = IDBContext.Current.UserName
                    })
                                     .FullName,
                    IsPrimary           = false,
                    IsRequired          = false,
                    DocumentNumber      = documentNumber,
                    ShpUrlDocument      = docWebUrl,
                    IsVer               = true,
                    IncInPublish        = false,
                    IsVisibleChkPublish = false,
                    IsVersionHistory    = false,
                    IsGenerated         = isGenerated,
                    IsNewDocument       = true,
                    DocumentNameTemp    = docNameTemp
                };
            }

            return(model);
        }
Пример #16
0
        public ActionResult CopyOrder(Guid id)
        {
            var user = UserIdentityManager.GetActiveUser(this.Request, this.repository);

            if (user == null)
            {
                return(this.HttpNotFound());
            }

            this.repository.AddProductsFromOrder(id, user);

            return(this.RedirectToAction("Orders"));
        }
        public VerDocumentRowViewModel GetDataNewDocument(
            int instanceId,
            string documentNumber,
            string documentName,
            string docWebUrl,
            string documentNameTemp)
        {
            var requestInstance = new VmrInstanceRequest
            {
                InstanceId = instanceId
            };
            var vmrInstance         = _vmrGenericService.GetInstance(requestInstance).Instance;
            var loadSecurityRequest = new VmrLoadSecurityRequest
            {
                Instance = vmrInstance,
                Pages    = VmrSecurityValues.SECURITY_VMR_DOCUMENT_PAGE
            };

            var documentSecurity = _vmrGenericService.LoadSecurity(loadSecurityRequest).SecurityList;

            SecurityDocument(documentSecurity.ToList());

            var document = new VerDocumentRowViewModel
            {
                SLno         = 0,
                DocumentType = _catalogService.GetConvergenceMasterDataIdByCode(
                    VerDocumentTypeCode.OTHER, MasterType.VER_DOCUMENT_TYPE).Id,
                DocumentName   = documentName,
                PackageVersion = vmrInstance.VerInstance.Version.GetNameLanguage(
                    Localization.CurrentLanguage),
                LastUpdate = DateTime.Now,
                UserName   = UserIdentityManager
                             .SearchFullNameByUserName(
                    new GetUsersRequest {
                    UserName = IDBContext.Current.UserName
                })
                             .FullName,
                IsPrimary        = false,
                IsRequired       = false,
                DocumentNumber   = documentNumber,
                ShpUrlDocument   = docWebUrl,
                IsVer            = false,
                LastUpdateFormat = string.Format("{0:dd MMM yyyy}", DateTime.Now),
                IsVersionHistory = false,
                DocumentNameTemp = documentNameTemp,
                IsNewDocument    = true
            };

            return(document);
        }
Пример #18
0
        protected void Application_Error(object sender, EventArgs e)
        {
            var httpContext = (sender as MvcApplication).Context;
            var httpRequest = httpContext != null ? httpContext.Request : null;
            var exception   = this.Server.GetLastError();

            var requestUrl   = httpRequest != null ? httpRequest.RawUrl : null;
            var clientIp     = httpRequest != null ? httpRequest.ServerVariables["REMOTE_ADDR"] : null;
            var rawUserAgent = httpRequest != null ? httpRequest.ServerVariables["HTTP_USER_AGENT"] : null;
            var rawHeaders   = httpRequest != null ? httpRequest.ServerVariables["ALL_RAW"] : null;
            var userId       = UserIdentityManager.GetActiveUserId(httpRequest.Cookies);

            new LinqRepository().LogError(exception, DateTime.Now, requestUrl, clientIp, rawUserAgent, rawHeaders, userId);
        }
Пример #19
0
        public async Task <ActionResult> Edit(ViewingViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var modelState = ModelState;

                    var viewingToModify = await _viewingService
                                          .GetViewingFromViewModel(model);

                    viewingToModify.ID            = model.ReadonlyViewingModel.ID;
                    viewingToModify.UserCreatorId = model.ReadonlyViewingModel.UserCreatorId;


                    if (await _viewingService.IsViewingValid
                            (viewingToModify, ModelState))
                    {
                        var currentLoggedUserId = User.Identity.GetUserId();

                        var currentLoggedUserRes = await UserIdentityManager
                                                   .GetUserById(currentLoggedUserId);

                        viewingToModify.UpdatedDate = DateTime.Now;

                        viewingToModify.UserUpdatorId =
                            currentLoggedUserRes.registeredUser.ID;

                        await _viewingRepo.Update(viewingToModify);

                        return(RedirectToAction("Details", new { id = viewingToModify.ID }));
                    }
                    else
                    {
                        var viewingModel = model.ReadonlyViewingModel;
                        model = await GetDefaultViewModelEntry();

                        model.ReadonlyViewingModel = viewingModel;

                        return(View(model));
                    }
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError(string.Empty, ex.Message);
                }
            }

            return(View(model));
        }
Пример #20
0
        public async Task <ActionResult> Edit(int?listingId, int?id)
        {
            try
            {
                var currentLoggedUserId = User.Identity.GetUserId();

                var currentLoggedUserRes = await UserIdentityManager.GetUserById
                                               (currentLoggedUserId);

                if (!currentLoggedUserRes.registeredUser.IsVerified &&
                    currentLoggedUserRes.registeredUser.RoleID == RoleNames.AGENT)
                {
                    errorModel.ErrorMessage =
                        "Agent cannot access viewing resource.\n Agent is not verified";

                    return(View(NOT_AUTHORIZED_PATH, errorModel));
                }


                var viewingModel = await _viewingRepo.Get(id.Value);

                if (viewingModel == null)
                {
                    return(HttpNotFound());
                }

                //If user Picked a different Listing on Edit
                if (listingId.HasValue)
                {
                    viewingModel.Listing = await _viewingRepo.GetListingById(listingId.Value);
                }

                model = _viewingService.GetViewingViewModelFromModel(viewingModel);

                var tmpModel = await GetDefaultViewModelEntry();

                model.Listings                = tmpModel.Listings;
                model.Customers               = tmpModel.Customers;
                model.Agents                  = tmpModel.Agents;
                model.DurationList            = tmpModel.DurationList;
                model.PickedListingPostalCode =
                    $@"{ viewingModel.Listing.ListingAddress.PostalCode} { viewingModel.Listing.ListingAddress.StreetAddress} { viewingModel.Listing.ListingAddress.Municipality}";
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, ex.Message);
            }
            return(View(model));
        }
Пример #21
0
        public virtual JsonResult GetUsersList(string filter)
        {
            UsersByNameOrFullNameResponse resp = new UsersByNameOrFullNameResponse();
            var response = UserIdentityManager.SearchUsersByFullNameOrName(new GetUsersRequest {
                FullName = filter
            });

            if (response != null && response.Users != null)
            {
                resp = response.Users.UserIdentityModelToResponse();
            }

            return(new JsonResult {
                Data = resp, JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
        }
Пример #22
0
        public ActionResult Orders(Guid?id, string a)
        {
            this.Initialize(Guid.Empty, PageIdentity.Cart);
            var user = UserIdentityManager.GetActiveUser(this.Request, this.repository);

            if (user == null)
            {
                return(this.HttpNotFound());
            }

            if (a == "delete" && id != null)
            {
                repository.DeleteOrderProduct(id.Value);
            }

            return(this.View("Orders", new OrderDetailsViewModel(this.repository, user)));
        }
Пример #23
0
        public ActionResult PlaceOrder(OrderDetailsViewModel viewModel)
        {
            var user = UserIdentityManager.GetActiveUser(this.Request, this.repository);

            if (user == null)
            {
                return(this.HttpNotFound());
            }

            var order = this.repository.GetOrderById(viewModel.Id);

            if (order == null || order.Status != (int)OrderStatus.Active)
            {
                return(this.HttpNotFound());
            }

            var orderProducts = this.repository.GetProductsForOrder(order.Id);

            if (orderProducts.Count != viewModel.Products.Count || !orderProducts.All(x => viewModel.Products.Any(y => y.Id == x.Key.Id)))
            {
                throw new ApplicationException("Cart contents is inconsistent.");
            }

            var orderProductsToRemove = new List <Guid>();

            foreach (var orderProduct in orderProducts.Where(x => !viewModel.Products.Any(y => y.Id == x.Key.Id)))
            {
                this.repository.RemoveOrderProduct(orderProduct.Key.Id);
            }

            this.repository.SubmitOrder(order.Id);

            var orderSubmitDate = this.repository.GetStatusesForOrder(order.Id).FirstOrDefault(x => x.Status == (int)OrderStatus.Placed);

            EmailManager.Send(
                user,
                this.repository,
                EmailType.EmailOrderHasBeenPlaced,
                new Dictionary <string, string> {
                { "%order.id%", order.Id.ToString() },
                { "%order.user%", user.Name },
                { "%order.date%", orderSubmitDate != null ? orderSubmitDate.DateTime.ToString("F", new CultureInfo("ru-RU")) : string.Empty }
            });

            return(this.RedirectToAction("Index", "Main"));
        }
        public async Task <ActionResult> UserProfile()
        {
            try
            {
                var currentLoggedUserId = User.Identity.GetUserId();

                var currentLoggedUserRes = await UserIdentityManager.GetUserById
                                               (currentLoggedUserId);


                if (currentLoggedUserRes == null)
                {
                    return(HttpNotFound());
                }


                var user = await _userRepo.Get
                               (currentLoggedUserRes.registeredUser.ID);

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

                var model = GetDefaultProfileViewModel(user);


                if (user.RoleID == RoleNames.AGENT)
                {
                    model.IsTypeAgent = true;
                }
                else
                {
                    model.IsTypeAgent = false;
                }


                return(View(model));
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, ex.Message);
                return(View(new UserProfileViewModel()));
            }
        }
Пример #25
0
        public ActionResult Recalculate(OrderDetailsViewModel viewModel)
        {
            var user = UserIdentityManager.GetActiveUser(this.Request, this.repository);

            if (user == null)
            {
                repository.LogError(new ApplicationException("Current user is null."), DateTime.Now, "[Code] Recalculate", null, null, null, null);
                return(this.HttpNotFound());
            }

            var order = this.repository.GetOrderById(viewModel.Id);

            if (order == null || order.Status != (int)OrderStatus.Active)
            {
                repository.LogError(new ApplicationException("There are no order associated. Order id: " + viewModel.Id.ToString()), DateTime.Now, "[Code] Recalculate", null, null, null, null);
                return(this.HttpNotFound());
            }

            var orderProducts = this.repository.GetProductsForOrder(order.Id);

            if (orderProducts.Count != viewModel.Products.Count || !orderProducts.All(x => viewModel.Products.Any(y => y.Id == x.Key.Id)))
            {
                throw new ApplicationException("Cart contents is inconsistent.");
            }

            // update the cart items count.
            foreach (var orderProduct in viewModel.Products)
            {
                var orderProductPair = orderProducts.Where(x => x.Key.Id == orderProduct.Id).First();
                var product          = orderProductPair.Value;
                var orderItem        = orderProductPair.Key;

                if (!product.IsAvailable)
                {
                    continue;
                }

                orderItem.Count           = orderProduct.Count;
                orderItem.Price           = product.GetPriceForUser(user, this.repository.GetExchangeRates());
                orderItem.PriceCurrencyId = user.DefaultCurrencyId.Value;
                this.repository.UpdateOrderProduct(orderItem);
            }

            return(this.Orders(null, null));
        }
Пример #26
0
        public ActionResult AddToCart(Guid id, int count = 1)
        {
            if (id == Guid.Empty)
            {
                return(this.HttpNotFound());
            }

            var user = UserIdentityManager.GetActiveUser(this.Request, this.repository);

            if (user == null || !user.IsActivated)
            {
                return(this.HttpNotFound());
            }

            this.repository.AddItemToCurrentOrder(user, id, count);

            return(this.Json(new { result = "success" }));
        }
        public async Task <ActionResult> Edit(CustomerViewModel returnModel)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var currentLoggedUserId = User.Identity.GetUserId();

                    var currentLoggedUserRes = await UserIdentityManager
                                               .GetUserById(currentLoggedUserId);

                    if (currentLoggedUserRes != null)
                    {
                        returnModel.inputModel.UserUpdatorId =
                            currentLoggedUserRes.registeredUser.ID;

                        returnModel.inputModel.DateUpdated = DateTime.Now;

                        await _customerRepo.Update(returnModel.inputModel);

                        model.inputModel = returnModel.inputModel;


                        return(View("Details", model));
                    }
                    else
                    {
                        return(HttpNotFound());
                    }
                }
                catch (Exception ex)
                {
                    model.inputModel = returnModel.inputModel;

                    ModelState.AddModelError(string.Empty, ex.Message);
                    return(View("Edit", model));
                }
            }
            model.inputModel = returnModel.inputModel;

            return(View("Edit", model));
        }
Пример #28
0
        public async Task <ActionResult> Create(int?listingId)
        {
            try
            {
                var currentLoggedUserId = User.Identity.GetUserId();

                var currentLoggedUserRes = await UserIdentityManager.GetUserById
                                               (currentLoggedUserId);

                if (!currentLoggedUserRes.registeredUser.IsVerified &&
                    currentLoggedUserRes.registeredUser.RoleID == RoleNames.AGENT)
                {
                    errorModel.ErrorMessage =
                        "Agent cannot access viewing resource.\n Agent is not verified";

                    return(View(NOT_AUTHORIZED_PATH, errorModel));
                }


                model = await GetDefaultViewModelEntry();

                if (listingId.HasValue)
                {
                    model.ListingId = listingId.Value;

                    var listingInDb = await _viewingRepo.GetListingById(model.ListingId);

                    model.PickedListingPostalCode =
                        $@"{listingInDb.ListingAddress.PostalCode} { listingInDb.ListingAddress.StreetAddress} {listingInDb.ListingAddress.Municipality}";
                }
                else
                {
                    model.PickedListingPostalCode = "No Listing is Picked";
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, ex.Message);
            }
            return(View(model));
        }
Пример #29
0
        private void SetFullname()
        {
            string fulllName        = string.Empty;
            var    listUserIdentity = UserIdentityManager
                                      .SearchUsersByNameOrFullName(new GetUserByPCmailOrNameRequest {
                Search = IDBContext.Current.UserName
            });

            if (listUserIdentity != null)
            {
                var response = listUserIdentity.Users.UserIdentityModelToResponse();
                if (response != null && response.ListResponse != null)
                {
                    var listItemViewModel = response.ListResponse.FirstOrDefault();
                    fulllName = listItemViewModel.Text;
                }
            }

            ViewBag.FullName = fulllName;
            ViewBag.UserName = IDBContext.Current.UserName;
        }
Пример #30
0
        private VerDocumentRowViewModel GetDocumentData(
            int instanceId, string documentNumber, string documentName, string docWebUrl, string documentNameTemp)
        {
            var model = new VerDocumentRowViewModel();

            var instanceRequest = new VerInstanceRequest
            {
                InstanceId = instanceId
            };

            var instanceResponse = _verGenericService.GetInstance(instanceRequest);

            if (instanceResponse.IsValid)
            {
                model = new VerDocumentRowViewModel
                {
                    SLno         = 0,
                    DocumentType = _catalogService.GetConvergenceMasterDataIdByCode(
                        VerDocumentTypeCode.OTHER, MasterType.VER_DOCUMENT_TYPE).Id,
                    DocumentName   = SanitizeFileName(documentName),
                    PackageVersion = instanceResponse.Instance.Version.GetNameLanguage(Localization.CurrentLanguage),
                    LastUpdate     = DateTime.Now,
                    UserName       = UserIdentityManager
                                     .SearchFullNameByUserName(new GetUsersRequest {
                        UserName = IDBContext.Current.UserName
                    })
                                     .FullName,
                    IsPrimary           = false,
                    IsRequired          = false,
                    DocumentNumber      = documentNumber,
                    ShpUrlDocument      = docWebUrl,
                    IsVer               = true,
                    IsVisibleChkPublish = false,
                    IsNewDocument       = true,
                    DocumentNameTemp    = documentNameTemp
                };
            }

            return(model);
        }
Пример #31
0
 public ModelFactory(HttpRequestMessage request, UserIdentityManager appUserManager)
 {
     urlHelper = new UrlHelper(request);
     this.appUserManager = appUserManager;
 }
Пример #32
0
 public AuthRepository()
 {
     dbContext = new UserIdentityDbContext();
     userManager = new UserIdentityManager(new UserStore<UserIdentity>(dbContext));
 }